# Authentication Source: https://docs.paycrest.io/api-reference/authentication Send your **API Key** in the `API-Key` header on every request. Keep your **API Secret** on your server to verify webhook signatures. It is never sent with a request. ## API-Key Header Include your **API Key** in the `API-Key` header for every API request: ```http theme={null} API-Key: YOUR_API_KEY ``` * You can find your API Key in your dashboard. * Requests with a missing, invalid or revoked API-Key return **401 Unauthorized**. A valid key used on a route its account type can't access (for example, a sender key on a provider route) returns **403 Forbidden**. > [!WARNING] > > Do not commit your API keys to git, or use them in client-side code. Never share your API Secret. If you believe it has been compromised, rotate it immediately in your dashboard. ## API Secret Your **API Secret** is used for sensitive operations such as verifying webhook signatures and should **never** be shared or exposed in client-side code. > [!WARNING] > > Keep your API Secret safe. The API Secret is for server-side use only (e.g., webhook signature verification). Never expose it in frontend code, public repositories, or logs. ## Webhook Signature Verification When receiving webhooks, use your API Secret to verify the authenticity of the payload. Refer to the webhook documentation for implementation details. > [!WARNING] > > Always ensure your server verifies the SSL connection to Paycrest. Do not set SSL verification (e.g., `VERIFY_PEER`) to `FALSE` in your HTTP client. # Errors Source: https://docs.paycrest.io/api-reference/errors The Paycrest API uses standard HTTP status codes and provides detailed error information to help you troubleshoot issues quickly. ## HTTP Status Codes | Code | Status | Description | | - | - | - | | `200` | OK | Request successful | | `201` | Created | Resource created successfully | | `400` | Bad Request | Invalid parameters or request format | | `401` | Unauthorized | Missing, invalid or revoked credentials (API key, signature or token) | | `403` | Forbidden | Authenticated, but the account type or API key scope isn't allowed on this route. The response has `data.field: "role"` | | `404` | Not Found | Resource not found | | `409` | Conflict | Resource conflict (e.g., duplicate order) | | `422` | Unprocessable Entity | Validation failed | | `429` | Too Many Requests | Rate limit exceeded | | `500` | Internal Server Error | Server error | | `503` | Service Unavailable | No providers available to handle the request | ## Error Response Format All error responses follow a consistent format: ```json theme={null} { "status": "error", "message": "Human-readable error description", "data": [ { "field": "field_name", "message": "Specific validation error" } ] } ``` ## Common Error Scenarios ### 400 Bad Request * **Invalid parameters**: Missing required fields, invalid formats * **Unsupported combinations**: Token/currency pairs not supported * **Amount validation**: Amounts outside provider limits * **Provider issues**: Provider not found or misconfigured * **Provider queue**: `providerId` and `providerIds` sent together, more than 3 entries, duplicates, or an entry that can't serve the corridor — see [Pin a provider queue](/implementation-guides/sender-api-integration#pin-a-provider-queue) ### 503 Service Unavailable * **No provider available**: When no providers can handle the specific request * **Service temporarily unavailable**: During maintenance or high load * **Geographic restrictions**: Service not available in your region A 503 means no provider could be found **at create time**. Once an order is created it is never 503'd: routing walks the order's provider queue, and Paycrest may still route the order elsewhere before refunding it. ## Handling Service Unavailability When you receive a 503 error: 1. **Check request parameters**: Verify token, amount, and currency combinations 2. **Try different amounts**: Some providers have minimum/maximum limits 3. **Retry later**: Provider availability may change over time 4. **Contact support**: If the issue persists, reach out to our team ## Getting Help If you're experiencing persistent errors: 1. **Check the error response** for specific details 2. **Review our documentation** for endpoint requirements 3. **Join our developer community** on [Telegram](https://t.me/+Stx-wLOdj49iNDM0) 4. **Contact support** at [support@paycrest.io](mailto:support@paycrest.io) 5. **Report issues** on [GitHub](https://github.com/paycrest) > [!NOTE] > > When reporting errors, please include the complete error response, request details, and your API key (with sensitive parts redacted). # Get Aggregator Public Key Source: https://docs.paycrest.io/api-reference/general/get-aggregator-public-key openapi-v2.yaml GET /pubkey Retrieve the aggregator's public key. # Get Markets Source: https://docs.paycrest.io/api-reference/general/get-markets openapi-v2.yaml GET /markets Returns the live protocol orderbook (all funded, available provider quotes across corridors × tokens × networks) plus network-wide aggregate statistics. **Public endpoint** — no authentication required, CORS open. Responses are cached for ~10 s. Requests are per-IP rate limited. Optional query filters (`side`, `fiat`, `token`, `network`) apply only to `data.book`. `data.aggregates` always remain network-wide (unfiltered). Provider balances and success rates are intentionally public to support integrator tooling and the Paycrest Markets dashboard. Returns the live protocol **orderbook** (every funded, available provider quote across corridors × tokens × networks) plus **network-wide aggregate statistics**. Use this endpoint to display live liquidity, rates, and protocol health without requiring authentication. > [!NOTE] > > **Public endpoint** — no API key or HMAC signature required. CORS is open. Responses are cached for \~10 s and are per-IP rate limited. ## Query parameters Optional filters narrow `data.book` only. **`data.aggregates` always remain network-wide** (same values whether or not you filter the book). | Param | Form | Description | | - | - | - | | `side` | single | `buy` or `sell`; omit for both. Invalid values return **400** | | `fiat` | comma-separated | e.g. `NGN,KES` (case-sensitive codes as stored) | | `token` | comma-separated | e.g. `USDC,USDT` | | `network` | comma-separated | e.g. `base,polygon` | Empty or omitted params apply no filter on that dimension. ## Response shape (`data`) | Field | Type | Description | | - | - | - | | `asOf` | string (ISO 8601) | Timestamp when the response was generated | | `aggregates` | object | Network-wide aggregate statistics (see below) — not affected by query filters | | `book` | array | Provider quote rows forming the live orderbook (optionally filtered) | ## Book row fields Each element of `book` is a single provider quote for one `side` on one `network`: | Field | Type | Description | | - | - | - | | `providerId` | string | Provider identifier | | `side` | string | `sell` = off-ramp (crypto → fiat); `buy` = on-ramp (fiat → crypto) | | `token` | string | Token symbol, e.g. `USDT`, `USDC` | | `fiat` | string | Fiat currency code, e.g. `NGN`, `KES` | | `network` | string | Network identifier, e.g. `base`, `ethereum` | | `rate` | string | Provider's effective rate (fiat per crypto for sell; crypto per fiat for buy) | | `rateType` | string | `fixed` or `floating` | | `min` | string | Minimum order amount for this corridor | | `max` | string | Maximum order amount for this corridor | | `balance` | string | Available liquidity: fiat amount for sell rows, token amount for buy rows | | `balanceCurrency` | string | Currency of `balance` — fiat code for sell, token symbol for buy | | `balanceUsd` | string | Balance normalised to USD | | `settled` | integer | Total settled orders for this provider in this corridor | | `successPercent` | string \| null | Success rate as a percentage string (`null` when no settled or refunded history) | > [!NOTE] > > `balance` is a **shared pool** repeated across a provider's networks for the same fiat (sell) or token (buy). De-duplicate by `providerId + fiat` (sell) or `providerId + token` (buy) when summing total depth to avoid double-counting. **Qualifying offer filters:** `is_available = true`, funded (positive balance), enabled fiat/token, non-testnet network. All book rows are public regardless of a provider's visibility setting—visibility only affects the narrower position benchmark pool on the [Get Market Rate](/api-reference/provider/get-market-rate) endpoint. ## Aggregates fields | Field | Type | Description | | - | - | - | | `settledVolumeUsd` | windowed | USD volume of settled orders — `24h`, `7d`, `30d`, `all` (strings) | | `settledTxns` | windowed | Count of settled transactions — `24h`, `7d`, `30d`, `all` (integers) | | `networkSuccessPercent` | windowed | Network success rate (settled / (settled + refunded)) — `24h`, `7d`, `30d` (strings or null) | | `medianDeliverySecs` | windowed | Median order delivery time in seconds — `24h`, `7d`, `30d` (integers or null) | | `activeProviders` | windowed | Distinct providers with ≥1 settled order — `24h`, `7d`, `30d`, `all` (integers) | | `activeSenders` | windowed | Distinct senders with ≥1 settled order — `24h`, `7d`, `30d`, `all` (integers) | | `liveLiquidityUsd` | string | Total available USD-denominated liquidity across all book rows | | `corridors` | integer | Distinct token/fiat pairs in the current book | | `tokens` | integer | Distinct tokens in the current book | | `networks` | integer | Distinct networks in the current book | Windowed success and median fields are `null` for a window when no terminal orders exist in that period. ## Example ```bash theme={null} GET https://api.paycrest.io/v2/markets ``` All values in this example are illustrative placeholders, not live network figures. ```json theme={null} { "status": "success", "message": "OK", "data": { "asOf": "2026-06-08T14:30:00Z", "aggregates": { "settledVolumeUsd": { "24h": "1000.00", "7d": "7000.00", "30d": "30000.00", "all": "100000.00" }, "settledTxns": { "24h": 10, "7d": 70, "30d": 300, "all": 1000 }, "networkSuccessPercent": { "24h": "99.00", "7d": "99.00", "30d": "99.00" }, "medianDeliverySecs": { "24h": 20, "7d": 20, "30d": 20 }, "activeProviders": { "24h": 5, "7d": 5, "30d": 5, "all": 10 }, "activeSenders": { "24h": 10, "7d": 50, "30d": 100, "all": 500 }, "liveLiquidityUsd": "50000.00", "corridors": 2, "tokens": 2, "networks": 2 }, "book": [ { "providerId": "AbCdEfGh", "side": "sell", "token": "USDT", "fiat": "NGN", "network": "base", "rate": "1605.50", "rateType": "floating", "min": "500.00", "max": "500000.00", "balance": "12000000.00", "balanceCurrency": "NGN", "balanceUsd": "7462.69", "settled": 3200, "successPercent": "98.90" }, { "providerId": "IjKlMnOp", "side": "buy", "token": "USDC", "fiat": "KES", "network": "ethereum", "rate": "130.25", "rateType": "fixed", "min": "100.00", "max": "100000.00", "balance": "9500.00", "balanceCurrency": "USDC", "balanceUsd": "9500.00", "settled": 850, "successPercent": "97.20" } ] } } ``` ### Filtered example Sell-side USDC offers on Base for NGN or KES. Aggregates in the response are still the full network-wide KPIs. ```bash theme={null} GET https://api.paycrest.io/v2/markets?side=sell&fiat=NGN,KES&token=USDC&network=base ``` ## Errors | HTTP | Cause | | - | - | | **400** | Invalid `side` (expected `buy` or `sell`) | | **429** | Per-IP rate limit exceeded | | **500** | Internal error | # Get Token Rate Source: https://docs.paycrest.io/api-reference/general/get-token-rate openapi-v2.yaml GET /rates/{network}/{from}/{amount}/{to} Public quote on a specific network. Returns **buy** and/or **sell** quotes, order type, and refund timeout. **Token + fiat:** each of **`from`** / **`to`** is either an enabled **fiat currency code** or an enabled **crypto (token) symbol** on **`network`**. Exactly one must be fiat and one crypto (`.../USDT/100/NGN` and `.../NGN/100/USDT` are equivalent). **`amount`** is the **crypto notional**. Rates are **fiat per 1 token** for each side. **`from` and `to` cannot both be crypto.** **Ambiguous segment:** if a path value matches **both** an enabled fiat code **and** an enabled crypto symbol on that network (e.g. same string), the request returns **400** unless **`from_source`** and/or **`to_source`** is set to **`fiat`** or **`crypto`** to pick the leg. **Fiat + fiat:** both segments are fiat codes. The quote **bridges through USDC** on the same **`network`**. **`amount`** is denominated in **`from`** fiat. **`sell`** is **destination fiat per 1 unit of `from` fiat** (buy USDC with `from`, sell USDC for `to`). **`buy`** is **`from` fiat per 1 unit of `to` fiat** (inverse corridor; buy USDC with `to`, sell USDC for `from`)—asymmetric from **`sell`**, not a simple reciprocal. Path order does **not** imply trade direction for token/fiat pairs; omitting **`side`** returns **both** sides when available. **Provider queue:** each side carries **`providerIds`** — up to 3 provider ids ranked best first, in the order assignment would try them. Pass them to **`destination.providerIds`** on `POST /sender/orders` to lock routing to the providers you quoted. Use **`limit`** to request fewer. For the legacy single-number response, use **`GET /v1/rates/{token}/{amount}/{fiat}`** with optional `network` query. Get buy and/or sell quotes on a **specific network**—either a **token + fiat** pair or a **fiat + fiat** corridor (via USDC). This is the recommended public rates URL for v2 integrations. > [!NOTE] > > The legacy endpoint **`GET /v1/rates/{token}/{amount}/{fiat}`** (optional `network` query) returns a **single numeric** `data` field. The v2 path below returns a structured **`buy` / `sell`** payload. ## Path parameters | Parameter | Description | | - | - | | `network` | Network id: `ethereum`, `base`, `bnb-smart-chain`, `celo`, `arbitrum-one`, `polygon`, `starknet`, `tron`, `solana` | | `from` | Fiat currency code **or** token symbol on `network` (paired with `to`) | | `amount` | For **token + fiat**: crypto (token) notional. For **fiat + fiat**: amount in **`from`** fiat. | | `to` | Fiat currency code **or** token symbol on `network` (paired with `from`) | **Token + fiat:** exactly **one** fiat and **one** token (`.../USDT/100/NGN` ≡ `.../NGN/100/USDT`). **`from`/`to` cannot both be tokens.** **Path order does not imply trade direction**—use `side` or read **`data.buy`** / **`data.sell`** for on-ramp vs off-ramp display. **Fiat + fiat:** both are fiat codes; the server quotes through **USDC** on the same network. **`sell.rate`** = **`to` per 1 `from`**. **`buy.rate`** = **`from` per 1 `to`** (inverse corridor, **not** the reciprocal of `sell`—each side uses the appropriate leg bid/ask). ## Query parameters | Parameter | Required | Description | | - | - | - | | `side` | No | `buy` or `sell` to return **only** that side. Omit to receive **both** when available. | | `from_source` | No | If `from` matches **both** a fiat currency and a crypto asset on the network, set to **`fiat`** or **`crypto`**. Omit when unambiguous. | | `to_source` | No | If `to` matches **both** a fiat currency and a crypto asset on the network, set to **`fiat`** or **`crypto`**. Omit when unambiguous. | | `provider_id` | No | Exactly **8 alphabetic** characters (`A–Z`, `a–z`) to pin the quote to one provider. Returns a **single** entry in `providerIds`. | | `limit` | No | Max ranked provider ids per side in `providerIds`. Integer **1–3**, default **3**. Anything else returns **400**. | ## Example ```bash theme={null} # Both buy and sell quotes on Base (token then fiat) GET https://api.paycrest.io/v2/rates/base/USDT/100/NGN # Same pair with fiat then token GET https://api.paycrest.io/v2/rates/base/NGN/100/USDT # Sell side only (typical for offramp display) GET https://api.paycrest.io/v2/rates/base/USDT/100/NGN?side=sell # Specific provider GET https://api.paycrest.io/v2/rates/base/USDT/100/NGN?provider_id=AbCdEfGh # Best provider only (single id in providerIds) GET https://api.paycrest.io/v2/rates/base/USDT/100/NGN?limit=1 ``` ## Success response (`data`) Each populated side includes: | Field | Type | Description | | - | - | - | | `rate` | string | For token+fiat: fiat per crypto. For fiat+fiat: see path rules above (`sell` = `to` per `from`, `buy` = `from` per `to`). This is the rate of **`providerIds[0]`**. | | `providerIds` | string\[] | **Ranked provider queue**, best first—up to **3** ids, in the order assignment would try them. See [Rate resolution](#rate-resolution). | | `orderType` | string | e.g. `regular` | | `refundTimeoutMinutes` | integer | Minutes until automatic refund for that flow | ```json theme={null} { "status": "success", "message": "Rate fetched successfully", "data": { "buy": { "rate": "1498.25", "providerIds": ["AbCdEfGh"], "orderType": "regular", "refundTimeoutMinutes": 60 }, "sell": { "rate": "1500.50", "providerIds": ["AbCdEfGh", "IjKlMnOp", "QrStUvWx"], "orderType": "regular", "refundTimeoutMinutes": 60 } } } ``` When `side=buy` or `side=sell`, only that key is present under `data`. **`providerIds` is always an array**: `[]` when no provider is available, never `null`. It carries **exactly one** id when you pass `?provider_id=` or `?limit=1`. Fewer than 3 ids means fewer eligible providers for that corridor and notional. ## Errors | HTTP | Typical cause | | - | - | | **400** | Invalid `amount`, invalid `side`, invalid `from_source`/`to_source` (must be `fiat` or `crypto`), ambiguous segment without disambiguation, invalid `provider_id`, `limit` outside **1–3**, unsupported asset on network, or conversion rules (e.g. stable only to its base fiat) | | **404** | No provider available for the amount/currency/network | | **503** | Banking/mobile network issues affecting providers for the currency | | **500** | Internal error while resolving the rate | ## Rate resolution Behavior matches the priority-queue–based resolution used when creating orders: the quote reflects provider selection and validation for the requested **side** (`buy` vs `sell`). **Path segment order (`from` / `to`) does not select direction**—use `?side=`, or read **`data.sell`** for **off-ramp** (crypto → fiat) display and **`data.buy`** for **on-ramp** (fiat → crypto) before `POST /v2/sender/orders`. ### The provider queue **`providerIds` is ranked, best first**, and is the same queue an order created from this quote will walk. **`providerIds[0]`** is the provider whose rate is quoted in **`rate`**; the remaining ids are the ones assignment falls through to if the head declines, expires, or exhausts its retries. The queue is resolved **once, at order creation**, and the order carries it for its whole life. Two ways to use that: **1. Let the API resolve it** Omit **`destination.providerId`** and **`destination.providerIds`** on create. The API resolves a fresh queue at creation time. Nothing to do—this is the default. **2. Pass the queue you quoted** Send **`data.sell.providerIds`** straight through as **`destination.providerIds`** on `POST /v2/sender/orders`. Routing is then pinned to the providers your user actually saw a rate from. See [Pin a provider queue](/implementation-guides/sender-api-integration#pin-a-provider-queue). > [!NOTE] > > **Exhausting the queue is not an immediate refund.** After the last entry, Paycrest may still route the order elsewhere before refunding it. Don't model this as "3 tries then refund". Quotes rank the **public** book, so `providerIds` lists only providers open to every sender. If you route to a provider dedicated to you, name it directly in **`destination.providerIds`** on create—it will not appear in a public quote. See also [Get Token Rate (v1)](/api-reference/general/get-token-rate-v1) for the legacy scalar response. # List Supported Currencies Source: https://docs.paycrest.io/api-reference/general/list-supported-currencies openapi-v2.yaml GET /currencies Retrieve a list of supported fiat currencies. # List Supported Institutions Source: https://docs.paycrest.io/api-reference/general/list-supported-institutions openapi-v2.yaml GET /institutions/{currency_code} Retrieve a list of supported institutions for a given currency. # List Supported Tokens Source: https://docs.paycrest.io/api-reference/general/list-supported-tokens openapi-v2.yaml GET /tokens Retrieve a list of supported tokens. # Reindex Transaction Source: https://docs.paycrest.io/api-reference/general/reindex-transaction openapi-v2.yaml GET /reindex/{network}/{tx_hash_or_address} Reindex a transaction by network and transaction hash. # Verify Account Source: https://docs.paycrest.io/api-reference/general/verify-account openapi-v2.yaml POST /verify-account Resolves the account holder name when available. For some fiat corridors (e.g. KES M-Pesa), `data` may be `"OK"` when the account is valid but no display name is returned — supply your own `accountName` on the order in that case. Verify a bank or mobile money account before creating an order. Currency is determined by the **institution** code (no separate `currency` field on this endpoint). ## Mobile money identifiers For institutions with type **mobile\_money**, the API **normalizes** `accountIdentifier` before calling providers: * Strips `+` and non-digit characters * Removes a leading domestic `0` and adds the country dial code when missing | Fiat | Dial code | | - | - | | KES | 254 | | UGX | 256 | | TZS | 255 | | GHS | 233 | **KES M-Pesa example:** `0712345678`, `+254712345678`, and `254712345678` all normalize to `254712345678`. You can send local or international MSISDN format; normalization also runs on order create for the same institution types. ## KES Till and Paybill Phone normalization is **not** applied when: * **`metadata`** indicates Till or Paybill (same shape as [recipient metadata](/implementation-guides/sender-api-integration) on order create), or * The identifier looks like Paybill (`businessNumber|reference`) or Till (fewer than 9 digits) Pass optional **`metadata`** on the verify request for Till/Paybill validation. ## Response `data` * A **real name** (e.g. `"JOHN DOE"`) — use that exact string as `accountName` on the order. * **`"OK"`** — account treated as valid but name lookup is unavailable for that corridor (common for some KES/GHS/UGX mobile flows). Provide your own `accountName` on the order. The same checks run again when you create an order; calling verify first improves checkout UX. ## Status codes | Status | Meaning | What to do | | - | - | - | | **200** | Account verified. `data` is the account name or `"OK"`. | Continue to order creation. | | **400** | Not verified: the institution is unsupported or unknown, or every eligible provider rejected the account. A malformed request body also returns 400, with field errors in `data`. | Treat as final. Ask the user to check the institution and account number. Do not retry unchanged. | | **503** | Verification could not complete: providers were unavailable, timed out, returned an error or a malformed response, or gave mixed results. For NGN, also returned when no provider returns a real account name. | Retry with backoff. | Branch on the HTTP status, not on the `message` text. If you already treat any non-200 response as "not verified", no change is needed. # Introduction Source: https://docs.paycrest.io/api-reference/introduction API Reference for Paycrest. Explore endpoints, request/response formats, and integration details. Welcome to the Paycrest API Reference. Here you'll find detailed documentation for all available endpoints, including request/response formats, authentication, and integration tips. * For a quick start, see the [Quickstart](/quickstart) guide. * For the interactive API explorer, use the individual endpoint pages in the sidebar. The Paycrest Aggregator API provides a comprehensive interface for interacting with the Paycrest protocol. This API enables senders to create payment orders, providers to fulfill orders, and general access to protocol information. ## Base URL ```bash theme={null} # Production (use this base for all new integrations) https://api.paycrest.io/v2 ``` > [!NOTE] > > Existing **v1** integrations use the same path names with base URL `https://api.paycrest.io/v1`. See the **Legacy (v1)** tab in the API Reference. ## Authentication All API requests require authentication using an API key. Include your API key in the request header: ```bash theme={null} API-Key: YOUR_API_KEY ``` ### Getting Your API Key 1. **Register** at [app.paycrest.io](https://app.paycrest.io) 2. **Complete KYB verification** (required for compliance) 3. **Access your API key** in your dashboard > [!NOTE] > > Your API key should be kept secure and never shared publicly. It's used to authenticate all API requests and identify your account. ## API Endpoints The Paycrest API is organized into three main categories: ### Sender Endpoints For entities that create payment orders: * **`POST /sender/orders`** - Create a new payment order (off-ramp or on-ramp) * **`GET /sender/orders`** - List payment orders with filtering * **`GET /sender/orders/{id}`** - Get a specific payment order * **`GET /sender/stats`** - Get sender statistics ### Provider Endpoints For liquidity providers that fulfill orders: * **`GET /provider/orders`** - List orders available for fulfillment * **`GET /provider/orders/{id}`** - Get a specific order * **`GET /provider/rates/{token}/{fiat}`** - Get market rate bands (`buy` / `sell` sides) * **`GET /provider/stats`** - Get provider statistics * **`GET /provider/node-info`** - Get provision node information ### General Endpoints For protocol information and utilities: * **`GET /currencies`** - List supported fiat currencies * **`GET /institutions/{currency_code}`** - List supported institutions * **`GET /tokens`** - List supported tokens and contract addresses * **`GET /rates/{network}/{from}/{amount}/{to}`** - Get public buy/sell rate quotes (token+fiat or fiat+fiat via USDC on a network; no API key) * **`GET /pubkey`** - Get aggregator public key * **`POST /verify-account`** - Verify bank or mobile money account details before creating an order (mobile MSISDN normalized server-side; see [Verify Account](/api-reference/general/verify-account)) * **`GET /orders/{chain_id}/{id}`** - Get order status by on-chain Gateway ID * **`GET /reindex/{network}/{tx_hash_or_address}`** - Reindex a transaction or address ## Request Format All requests should include the following headers: ```bash theme={null} Content-Type: application/json API-Key: YOUR_API_KEY ``` ### Example Request > [tab] cURL > > ```bash theme={null} > curl -X POST "https://api.paycrest.io/v2/sender/orders" \ > -H "Content-Type: application/json" \ > -H "API-Key: YOUR_API_KEY" \ > -d '{ > "amount": "100", > "source": { > "type": "crypto", > "currency": "USDT", > "network": "base", > "refundAddress": "0xYourWalletAddress" > }, > "destination": { > "type": "fiat", > "currency": "NGN", > "recipient": { > "institution": "GTBINGLA", > "accountIdentifier": "1234567890", > "accountName": "John Doe", > "memo": "Salary payment" > } > }, > "reference": "payment-123" > }' > ``` > [tab] JavaScript > > ```javascript theme={null} > const axios = require('axios'); > > const API_KEY = 'YOUR_API_KEY'; > const BASE_URL = 'https://api.paycrest.io/v2'; > > const orderData = { > amount: '100', > source: { > type: 'crypto', > currency: 'USDT', > network: 'base', > refundAddress: '0xYourWalletAddress' > }, > destination: { > type: 'fiat', > currency: 'NGN', > recipient: { > institution: 'GTBINGLA', > accountIdentifier: '1234567890', > accountName: 'John Doe', > memo: 'Salary payment' > } > }, > reference: 'payment-123' > }; > > const response = await axios.post(`${BASE_URL}/sender/orders`, orderData, { > headers: { > 'API-Key': API_KEY, > 'Content-Type': 'application/json' > } > }); > > console.log(response.data); > ``` > [tab] Python > > ```python theme={null} > import requests > > API_KEY = 'YOUR_API_KEY' > BASE_URL = 'https://api.paycrest.io/v2' > > order_data = { > "amount": "100", > "source": { > "type": "crypto", > "currency": "USDT", > "network": "base", > "refundAddress": "0xYourWalletAddress" > }, > "destination": { > "type": "fiat", > "currency": "NGN", > "recipient": { > "institution": "GTBINGLA", > "accountIdentifier": "1234567890", > "accountName": "John Doe", > "memo": "Salary payment" > } > }, > "reference": "payment-123" > } > > response = requests.post( > f'{BASE_URL}/sender/orders', > headers={ > 'API-Key': API_KEY, > 'Content-Type': 'application/json' > }, > json=order_data > ) > > print(response.json()) > ``` > [tab] Go > > ```go theme={null} > package main > > import ( > "bytes" > "encoding/json" > "fmt" > "io" > "net/http" > ) > > func main() { > orderData := map[string]interface{}{ > "amount": "100", > "source": map[string]interface{}{ > "type": "crypto", > "currency": "USDT", > "network": "base", > "refundAddress": "0xYourWalletAddress", > }, > "destination": map[string]interface{}{ > "type": "fiat", > "currency": "NGN", > "recipient": map[string]interface{}{ > "institution": "GTBINGLA", > "accountIdentifier": "1234567890", > "accountName": "John Doe", > "memo": "Salary payment", > }, > }, > "reference": "payment-123", > } > > jsonData, _ := json.Marshal(orderData) > req, _ := http.NewRequest("POST", "https://api.paycrest.io/v2/sender/orders", bytes.NewBuffer(jsonData)) > req.Header.Set("API-Key", "YOUR_API_KEY") > req.Header.Set("Content-Type", "application/json") > > client := &http.Client{} > resp, _ := client.Do(req) > defer resp.Body.Close() > > body, _ := io.ReadAll(resp.Body) > fmt.Println(string(body)) > } > ``` ## Response Format All API responses follow a consistent format: ```json theme={null} { "status": "success", "message": "Operation completed successfully", "data": { // Response data here } } ``` ### Error Responses Error responses include detailed information: ```json theme={null} { "status": "error", "message": "Validation failed", "data": [ { "field": "amount", "message": "Amount must be greater than 0" } ] } ``` ## Rate Limiting API requests are rate-limited to ensure fair usage. Authenticated requests have a significantly higher limit than unauthenticated ones. If you hit the limit, the API returns `429 Too Many Requests` — back off and retry after a short delay. ## Pagination List endpoints support pagination with the following parameters: * **`page`** - Page number (default: 1) * **`pageSize`** - Items per page (default: 20, max: 100) ### Example > [tab] cURL > > ```bash theme={null} > curl -X GET "https://api.paycrest.io/v2/sender/orders?page=2&pageSize=10" \ > -H "API-Key: YOUR_API_KEY" > ``` > [tab] JavaScript > > ```javascript theme={null} > const axios = require('axios'); > > const API_KEY = 'YOUR_API_KEY'; > const BASE_URL = 'https://api.paycrest.io/v2'; > > async function getOrders(page = 2, pageSize = 10) { > const response = await axios.get(`${BASE_URL}/sender/orders`, { > headers: { 'API-Key': API_KEY }, > params: { page, pageSize } > }); > console.log(response.data); > } > getOrders(); > ``` > [tab] Python > > ```python theme={null} > import requests > > API_KEY = 'YOUR_API_KEY' > BASE_URL = 'https://api.paycrest.io/v2' > > response = requests.get( > f'{BASE_URL}/sender/orders', > headers={'API-Key': API_KEY}, > params={'page': 2, 'pageSize': 10} > ) > print(response.json()) > ``` > [tab] Go > > ```go theme={null} > package main > > import ( > "fmt" > "io" > "net/http" > "net/url" > ) > > func main() { > baseURL := "https://api.paycrest.io/v2/sender/orders" > params := url.Values{} > params.Add("page", "2") > params.Add("pageSize", "10") > > req, _ := http.NewRequest("GET", baseURL+"?"+params.Encode(), nil) > req.Header.Set("API-Key", "YOUR_API_KEY") > > client := &http.Client{} > resp, _ := client.Do(req) > defer resp.Body.Close() > > body, _ := io.ReadAll(resp.Body) > fmt.Println(string(body)) > } > ``` Response includes pagination metadata: ```json theme={null} { "status": "success", "message": "Orders retrieved successfully", "data": { "total": 150, "page": 2, "pageSize": 10, "orders": [...] } } ``` ## Webhooks Set up webhooks to receive real-time updates: ### Webhook Events * **`payment_order.deposited`** - Deposit detected on the receive address * **`payment_order.pending`** - Order matched and awaiting provider fulfillment * **`payment_order.validated`** - Provider confirmed fiat delivery * **`payment_order.settling`** - Settlement transaction broadcast on-chain * **`payment_order.settled`** - Settlement confirmed on-chain; the recipient has the funds * **`payment_order.refunding`** - Refund transaction initiated * **`payment_order.refunded`** - Deposit refunded to sender (fulfillment failed); the refund has landed at the refund address * **`payment_order.expired`** - Order expired with no deposit received * **`payment_order.compliance_hold`** - On-ramp fiat received, but settlement is held pending compliance review. Unlike the events above, this one is not named after a status: the order stays `pending`, so `data.status` reports `pending` ### Webhook Payload Webhook signatures use HMAC-SHA256 over the **exact raw request body**. Do not re-serialize parsed JSON (key ordering differs). The `X-Paycrest-Signature` header is a **hex string** — compare using timing-safe equality on the **UTF-8 bytes of the hex strings** (see the [Sender API integration guide](/implementation-guides/sender-api-integration#verify-webhook-signatures)). ```json theme={null} { "event": "payment_order.settled", "webhookVersion": "2", "data": { "id": "550e8400-e29b-41d4-a716-446655440000", "direction": "offramp", "status": "settled", "amount": "100", "amountInUsd": "100", "amountPaid": "100", "amountReturned": "0", "percentSettled": "100", "senderFee": "1", "transactionFee": "0.01", "rate": "1580.5", "gatewayId": "0xabc...", "senderId": "f47ac10b-58cc-4372-a567-0e02b2c3d479", "source": { "type": "crypto", "currency": "USDT", "network": "base", "refundAddress": "0xSenderWallet..." }, "destination": { "type": "fiat", "currency": "NGN", "recipient": { "institution": "ACCESS", "accountIdentifier": "0123456789", "accountName": "Jane Doe", "memo": "" } }, "fromAddress": "0xReceiverAddress...", "reference": "ref-001", "txHash": "0x1234567890abcdef...", "timestamp": "2024-01-15T10:30:00Z", "paymentReference": "100004261019223045000123456789" } } ``` ### Delivery logs & retry Every webhook send is recorded as a **delivery**. Failed deliveries — transport errors **and** non-2xx responses — are retried automatically with exponential backoff for a 24-hour window, then marked `expired`. You can audit and replay deliveries yourself: * [List Webhook Deliveries](/api-reference/sender/list-webhook-deliveries) — newest first, filter by `status`, `event`, `event_id`, `order_id`, or date range. * [Get Webhook Delivery](/api-reference/sender/get-webhook-delivery-by-id) — full record including request payload and response body. * [Retry Webhook Delivery](/api-reference/sender/retry-webhook-delivery) — replay a delivery (`?sync=true` for an inline result, otherwise queued). > [!NOTE] > > For detailed webhook implementation guide including signature verification, retry logic, and best practices, see the [Sender API Integration Guide](/implementation-guides/sender-api-integration#webhooks). ## Testing Paycrest supports very low minimum orders (as little as \$0.50) and uses cost-effective EVM L2s, making it perfect for testing with real transactions. Start small and scale up as you gain confidence. > [!NOTE] > > There is no sandbox environment at the moment. All testing should be done on production using small amounts. ## Support Need help with the API? * **Documentation**: Browse our comprehensive guides * **Telegram**: Join our developer community at [t.me/+Stx-wLOdj49iNDM0](https://t.me/+Stx-wLOdj49iNDM0) * **GitHub**: Report issues at [github.com/paycrest](https://github.com/paycrest) * **Email**: Contact support at [support@paycrest.io](mailto:support@paycrest.io) ## Fee Model Senders pay the quoted rate, plus a `transactionFee` for the order's gas (by default it comes out of the sender fee) and any optional sender fee they set. See [Who pays the transaction fee](/implementation-guides/sender-api-integration#who-pays-the-transaction-fee). # Get Market Rate Source: https://docs.paycrest.io/api-reference/provider/get-market-rate openapi-v2.yaml GET /provider/rates/{token}/{fiat} Returns **buy** and **sell** market rate **bands** (reference rate plus min/max tolerance) for a token/fiat pair. Use this to validate whether a sender-provided `rate` on order creation is within allowed bounds. ## Response shape (`data`) | Field | Type | Description | | - | - | - | | `buy` | object (optional) | Buy-side band — see fields below | | `sell` | object (optional) | Sell-side band — see fields below | Each side object: | Field | Type | Description | | - | - | - | | `marketRate` | string | Reference market rate for this side (fiat per crypto) | | `minimumRate` | string | Minimum allowed rate for this side | | `maximumRate` | string | Maximum allowed rate for this side | | `position` | object (optional) | Rate benchmark vs. best public peer — see below | Numeric values are returned as **strings** (decimal). Either side may be omitted depending on corridor configuration. ## `position` object When qualifying public offers exist for this corridor, each side includes a `position` object so you can see how your effective rate compares to the best public peer: | Field | Type | Description | | - | - | - | | `bestPublicRate` | string | Best rate among enabled non-testnet public peers (highest for sell; lowest for buy) | | `yourEffectiveRate` | string | Your own effective rate for this corridor and side | | `deltaVsBest` | string | `yourEffectiveRate − bestPublicRate` | **Interpreting `deltaVsBest`:** * **Sell** (off-ramp): a **positive** delta means your rate is higher than the best peer — you are more competitive. * **Buy** (on-ramp): a **negative** delta means your rate is lower than the best peer — you are more competitive. `position` is **omitted** when: * No qualifying public offers exist for the corridor, or * You have no effective rate configured for this corridor. The reference fields `marketRate`, `minimumRate`, and `maximumRate` are **unchanged** — `position` is purely additive (backward compatible). The benchmark pool uses all enabled, non-testnet networks; it is not filtered by the `{token}/{fiat}` path parameters' network. ## Example ```json theme={null} { "status": "success", "message": "Rate fetched successfully", "data": { "sell": { "marketRate": "1605.00", "minimumRate": "1580.00", "maximumRate": "1630.00", "position": { "bestPublicRate": "1608.00", "yourEffectiveRate": "1605.00", "deltaVsBest": "-3.00" } }, "buy": { "marketRate": "1598.00", "minimumRate": "1575.00", "maximumRate": "1620.00", "position": { "bestPublicRate": "1595.00", "yourEffectiveRate": "1598.00", "deltaVsBest": "3.00" } } } } ``` Example when `position` is omitted (no public benchmark available): ```json theme={null} { "status": "success", "message": "Rate fetched successfully", "data": { "sell": { "marketRate": "1605.00", "minimumRate": "1580.00", "maximumRate": "1630.00" } } } ``` > [!NOTE] > > **`GET /v1/provider/rates/{token}/{fiat}`** uses the same response shape as this v2 route, including the `position` field. See [Get Market Rate (v1)](/api-reference/provider/get-market-rate-v1). # Get Node Info Source: https://docs.paycrest.io/api-reference/provider/get-node-info openapi-v2.yaml GET /provider/node-info Retrieve node information for the provider. # Get Order by ID Source: https://docs.paycrest.io/api-reference/provider/get-order-by-id-v2 openapi-v2.yaml GET /provider/orders/{id} Returns a single payment order assigned to the authenticated provider, including polymorphic source/destination, providerAccount, and transaction logs. > [!NOTE] > > On provider order endpoints, `transactionFee` is the protocol fee deducted from that order, net of any rebate once the order is settled. Before settlement it reflects the gross fee. # Get Provider Stats Source: https://docs.paycrest.io/api-reference/provider/get-provider-stats openapi-v2.yaml GET /provider/stats Retrieve statistics for the provider. # List Orders Source: https://docs.paycrest.io/api-reference/provider/list-orders-v2 openapi-v2.yaml GET /provider/orders Returns a paginated list of payment orders assigned to the authenticated provider, in the v2 response schema. Requires a `currency` query parameter. Supports optional `direction` (`onramp` / `offramp`), `search`, `export=csv`, `from`/`to` date filters, and `ordering` (asc/desc). > [!NOTE] > > On provider order endpoints, `transactionFee` is the protocol fee deducted from that order, net of any rebate once the order is settled. Before settlement it reflects the gross fee. # Get Order Status by Gateway ID Source: https://docs.paycrest.io/api-reference/sender/get-order-by-gateway-id openapi-v2.yaml GET /orders/{chain_id}/{id} Retrieve the status of an order by its on-chain Gateway ID and chain ID. Use this for smart contract integrations. Retrieve the status of an order by its on-chain Gateway ID and chain ID. Use this for smart contract integrations where you have the Gateway order ID from the blockchain rather than the API order UUID. # Get Order by ID Source: https://docs.paycrest.io/api-reference/sender/get-payment-order-by-id-v2 openapi-v2.yaml GET /sender/orders/{id} # Get Sender Stats Source: https://docs.paycrest.io/api-reference/sender/get-sender-stats openapi-v2.yaml GET /sender/stats Retrieve statistics for the sender. # Get Webhook Delivery Source: https://docs.paycrest.io/api-reference/sender/get-webhook-delivery-by-id openapi-v2.yaml GET /sender/webhooks/{id} Returns a single webhook delivery, including the frozen `payload` and the captured `responseBody`. Returns `404` if the delivery belongs to another sender. # Initiate Order Source: https://docs.paycrest.io/api-reference/sender/initiate-payment-order-v2 openapi-v2.yaml POST /sender/orders Creates a new payment order. - **Off-ramp** (stablecoin → fiat): set `source.type = "crypto"` and `destination.type = "fiat"`. The response `providerAccount` contains a `receiveAddress` to send tokens to. - **On-ramp** (fiat → stablecoin): set `source.type = "fiat"` and `destination.type = "crypto"`. The response `providerAccount` contains a virtual bank account for the user to deposit fiat into. **Off-ramp deposit.** Send exactly `providerAccount.amountToTransfer` of `providerAccount.currency`: that is `amount + senderFee + transactionFee`. When `providerAccount.memo` is present, include it with the deposit or the deposit cannot be credited. **Transaction fee.** By default the sender pays the transaction fee out of their sender fee, so the returned `senderFee` is what the sender earns and the customer only tops up a shortfall. Set `transactionFeePayer: "customer"` (or change the token's setting in the dashboard) to add the transaction fee on top of the full sender fee instead. **Solana** (`solana`) is available through this endpoint only; v1 order endpoints reject it. For on-ramp to Solana, the recipient wallet must already have a token account for the stablecoin's mint. **Provider routing.** On **off-ramp**, leave `destination.providerIds` unset and the API resolves a ranked queue of up to 3 providers at creation; assignment walks it in order. Set `destination.providerIds` to supply your own queue — typically the ids from a [rate quote](/api-reference/general/get-token-rate) — or a one-entry queue to route to a single provider. Queue exhaustion is not an immediate refund: Paycrest may still route the order elsewhere before refunding it. On **on-ramp**, the provider is selected when the order is created, so `destination.providerIds` accepts at most one entry and acts as a pin. The singular `destination.providerId` is retained for backward compatibility on both flows and is mutually exclusive with `providerIds`. Routing validation failures return **400** with `data` as a single `{ field, message }` object rather than an array. # List Orders Source: https://docs.paycrest.io/api-reference/sender/list-payment-orders-v2 openapi-v2.yaml GET /sender/orders # List Webhook Deliveries Source: https://docs.paycrest.io/api-reference/sender/list-webhook-deliveries openapi-v2.yaml GET /sender/webhooks Returns the authenticated sender's webhook delivery log, newest first. Use this to audit which events were delivered and to find failed or expired deliveries to replay. List items omit the large `payload` and `responseBody` fields; fetch a single delivery to see them. # Retry Webhook Delivery Source: https://docs.paycrest.io/api-reference/sender/retry-webhook-delivery openapi-v2.yaml POST /sender/webhooks/{id}/retry Replays a webhook delivery using its original frozen payload. - **Synchronous** (`?sync=true`): the payload is re-sent immediately and the HTTP result is returned inline (`200`). - **Asynchronous** (default): a new `pending` delivery is queued for the retry worker and the new delivery ID is returned (`202`). Returns `404` if the delivery belongs to another sender. # Protocol Architecture Source: https://docs.paycrest.io/concepts/architecture The technical components behind Paycrest's payment routing: Gateway contract, aggregator and provision nodes Paycrest is a payment routing protocol built on three cooperating layers: a Gateway smart contract for on-chain escrow, an aggregator for order routing and coordination, and provision nodes for fiat execution. This page explains how those components interact. ```mermaid theme={null} flowchart TD APP["Sender App"] subgraph PROTO["Paycrest Protocol"] AGG["Aggregator Node"] GW["Gateway Contract\nonchain escrow"] end subgraph PROV["Provider"] NODE["Provision Node"] PSP["PSP"] end RECIP(["Recipient"]) APP -->|"initiate order"| AGG APP <-->|"stablecoin lock / release"| GW GW -.->|"order events"| AGG AGG -->|"route order"| NODE NODE <-->|"fiat execution"| PSP PSP <-->|"fiat / stablecoins"| RECIP NODE -.->|"fulfillment confirmed"| AGG AGG -.->|"webhook"| APP ``` ## Core Components ### Gateway Contract The **Gateway contract** is the on-chain entry point for all payment orders. It holds stablecoins in escrow during the settlement process. Neither Paycrest nor any provider ever custodies the funds directly. #### Key Functions * **Order Creation**: Accepts payment orders from senders; locks stablecoins in escrow (off-ramp) or coordinates stablecoin release to recipients (on-ramp) * **Event Emission**: Emits events that the aggregator monitors to begin routing * **Escrow Settlement**: Releases escrowed funds to providers after fulfillment is verified, or returns them to senders if the order can't be completed #### Payment Flow **1. Order Creation** Sender creates an order via the Sender API or direct contract interaction. For off-ramp, stablecoins are locked in escrow. For on-ramp, the contract coordinates stablecoin release once fiat receipt is confirmed. **2. Routing** Aggregator picks up the on-chain event and routes the order to the most suitable liquidity provider based on rate, availability, and corridor. **3. Fulfillment** For off-ramp, the provider disburses fiat to the recipient via a local PSP. For on-ramp, the provider receives the user's fiat deposit and reports confirmation. **4. Completion** After fulfillment is verified, the contract settles atomically: escrowed stablecoins are released to the provider (off-ramp), or stablecoins are transferred to the recipient's wallet (on-ramp). If fulfillment fails, funds are automatically returned. ### Aggregator Node The **aggregator node** is the coordination layer: it monitors on-chain events, manages provider routing, and oversees the settlement pipeline. #### Core Functions * **Order Monitoring**: Watches the Gateway contract for new orders * **Provider Matching**: Routes orders to the optimal provider based on rate and availability * **Settlement Coordination**: Manages the fulfillment → validation → settlement flow * **Webhook Delivery**: Notifies senders of order status changes > [!NOTE] > > Paycrest operates the **Paycrest Aggregator** today. The protocol is designed to support multiple independent aggregators in the future. See the [Decentralization Path](/introduction#decentralization-path). #### API Layer * REST API (v1 and v2 sender/provider endpoints) * Webhook delivery to senders * Rate limiting and authentication ### Provision Nodes **Provision nodes** handle fiat execution: disbursing fiat to recipients for off-ramp orders, or receiving and confirming fiat deposits for on-ramp orders. They are run by independent liquidity providers who connect their own PSP integrations. #### Components * **PSP Integration**: Connects to local payment service providers (banks, mobile wallets) * **Rate Management**: Sets and updates competitive rates per corridor * **Order Processing**: Executes assigned payment orders * **Settlement Reporting**: Reports fulfillment status back to the aggregator #### Integration Types > [card] Bank APIs > > * Direct bank integrations > * Real-time payment rails > * Batch processing > [card] Mobile Money > > * M-Pesa, Airtel Money, MTN Mobile Money > * Other mobile wallets #### Deployment Options **Self-Hosted Deployment** * Complete control over infrastructure and PSP connections * Requires technical expertise for setup and maintenance * Recommended for providers with existing PSP relationships **Managed Deployment via Blockops** * One-click deployment through [Blockops](https://blockops.network/) * Automated scaling and monitoring * Recommended for providers new to infrastructure management ### Sender API & Webhooks The interface businesses and apps use to: * **Create payment orders** in either direction, on-ramp or off-ramp * **Configure** refund addresses, fee addresses and fee percentages * **Manage API keys** and authentication * **Receive webhooks** for every order status change ## Multi-Chain Support The protocol is live on 6 EVM-compatible networks, where senders can use the Sender API or call the Gateway contract directly: | Network | Chain ID | Primary Use | | - | - | - | | Ethereum | 1 | USDT, USDC, cNGN | | Base | 8453 | USDT, USDC, cNGN | | Arbitrum One | 42161 | USDT, USDC | | Polygon | 137 | USDT, USDC, cNGN | | BNB Smart Chain | 56 | USDT, USDC, cNGN | | Celo | 42220 | USDT, USDC, cNGN | **Starknet** (`starknet`), **Tron** (`tron`) and **Solana** (`solana`) are supported through the Sender API only; Tron and Solana orders use the v2 API. See [Supported Stablecoins](/resources/supported-stablecoins) for tokens and address formats. See [Gateway Contract Addresses](/resources/gateway-contract-addresses) for the EVM deployment table, and [Supported Stablecoins](/resources/supported-stablecoins) for per-network token details. ## Security Architecture ### Smart Contract Security The Gateway contract implements multiple security measures: * **Non-custodial escrow**: Funds are locked on-chain, not held by Paycrest or providers * **Automatic refunds**: Unfulfilled orders are refunded automatically * **Access control**: Role-based permissions and multi-signature governance for protocol changes * **Open-source contracts**: see the [contracts repository](https://github.com/paycrest/contracts) ### Data Protection * **Encrypted recipient data**: Recipient bank details are encrypted in transit and at rest * **API key authentication**: All API requests authenticated via API Key + API Secret * **Webhook signature verification**: HMAC-SHA256 signatures on all webhook payloads ## Integration Paths Senders have two integration options: > [card] [Sender API](/implementation-guides/sender-api-integration) > > REST API integration and the fastest way to go live. Paycrest handles the on-chain interaction for you. > [card] [Smart Contract](/implementation-guides/smart-contract-interaction) > > Direct Gateway contract integration with full on-chain composability. Automated flows like yield-to-fiat and liquidation-to-bank work natively. # Compliance & Security Source: https://docs.paycrest.io/concepts/compliance-security How compliance works in the Paycrest protocol, and what security guarantees the protocol provides. Paycrest is a payment routing and settlement protocol, not a financial institution. It never takes custody of funds: during an order they sit in the Gateway contract, which can only release them to the assigned provider or refund them to the sender. Most compliance responsibility sits with the participants. ## Compliance Model: Compliance at the Edges Paycrest verifies who takes part, and each participant owns the compliance closest to them: > [card] Providers own local compliance > > Each liquidity provider is responsible for complying with the rules that apply to them locally: AML/CFT requirements and any reporting obligations in their jurisdiction. > [card] Senders own their compliance > > Senders (apps integrating Paycrest) are responsible for their own user KYC/KYB, sanctions screening, and applicable regulations in the markets they serve. > [card] Screening and review > > Paycrest screens orders for sanctions risk and can hold an order for review. Treat `status` as the source of truth. > [card] KYB-gated participation > > Every sender and provider business is verified before going live. ## KYB Requirements ### For Senders Senders are companies or developers who integrate Paycrest to provide on- or off-ramp services to their users: * Business verification (KYB) required before going live * Register at [app.paycrest.io](https://app.paycrest.io) and complete the KYB process ### For Providers Providers are businesses that supply fiat and stablecoin liquidity in both directions: * Business verification (KYB) required before going live * Live fiat rails in each corridor they serve, for paying out and receiving funds * Ongoing compliance monitoring as a condition of continued participation ## Security ### Smart Contract Security The Gateway contract is the only place funds are held, and only temporarily, in escrow: * **Open-source contracts**: The Gateway contracts are public at [github.com/paycrest/contracts](https://github.com/paycrest/contracts). * **Non-custodial escrow**: Funds are locked on-chain until either (a) payout is verified and stablecoins are released to the provider, or (b) the order cannot be fulfilled and is refunded to the sender automatically. * **Multi-signature governance**: Protocol parameter changes require multi-signature approval * **Emergency pause**: The Gateway contract can be paused in a security incident ### API Security * **API Key authentication**: Every API request requires a valid `API-Key` header * **API Secret**: Used for webhook signature verification. Never expose it in client-side code * **Webhook HMAC verification**: All webhooks include an `X-Paycrest-Signature` header using HMAC-SHA256, allowing receivers to verify payload authenticity * **TLS required**: All API communication over HTTPS; never disable SSL verification in your HTTP client ### Data Protection * **Encrypted recipient data**: Bank account and mobile wallet details are encrypted in transit and at rest * **Minimal data retention**: The protocol stores only what is needed for routing, settlement and compliance ## Governance Protocol changes are ratified by the Paycrest Core Multisig. As the protocol matures, governance is intended to move toward broader, community-led decision-making. See the [Decentralization Path](/introduction#decentralization-path). ## Pricing & Sender Fees What a sender pays on each order: * **Rate**: Quoted live by the Paycrest Sender API before the order is created. * **Transaction fee**: Covers the gas the aggregator pays to create and settle the order. By default it comes out of the sender fee; the integrating app can pass it to its customers instead. * **Sender fee (optional)**: Set by the integrating app and settled on-chain in the same transaction as the order. Apart from the transaction fee and any sender fee, nothing is added to the quoted rate, and there is nothing to invoice or reconcile off-chain. Planning high volumes? Talk to us at [support@paycrest.io](mailto:support@paycrest.io). > [!NOTE] > > Paycrest is not a licensed financial institution. This documentation does not constitute legal or regulatory advice. Participants are responsible for their own compliance obligations in their respective jurisdictions. # Protocol Participants Source: https://docs.paycrest.io/concepts/participants Understanding the key participants in the Paycrest protocol ecosystem The Paycrest protocol ecosystem consists of four main participant types, each with specific roles and responsibilities. Understanding these participants is crucial for building on the protocol. ## Sender A **KYB-verified entity** that initiates either a fiat-to-stablecoin or stablecoin-to-fiat transaction. ### Characteristics * **KYB Required**: Must complete business verification * **API Access**: Uses the Sender API to create orders or can interact directly with the Gateway contract * **Fee Structure**: The quoted rate, plus a transaction fee that covers the order's gas. Senders can add their own optional fee * **Flexibility**: Can be smart contracts, dApps, smart accounts (e.g. EIP-7702), or traditional applications ### Responsibilities * **Order Creation**: Specify amount, token, recipient, and rate * **Recipient Information**: Provide accurate bank account or wallet details * **Compliance**: Maintain KYC status and regulatory compliance * **Monitoring**: Track order status and handle webhooks * **Fee Management**: Optionally set sender fees to monetize their service ### Use Cases * **Remittance Services**: Send money to family abroad * **Business Payments**: Pay suppliers in different currencies * **DeFi Applications**: Bridge between crypto and traditional finance * **E-commerce**: Accept crypto payments and settle in fiat * **Wallets and apps**: Let users buy stablecoins with local currency (on-ramp) > [!NOTE] > > **Sender Fee Model:** Sender businesses can optionally charge fees to their users. Configure a default fee via the dashboard, or pass `senderFee` / `senderFeePercent` on each V2 order request. When the effective fee is greater than zero, a fee recipient is required: either configured on the profile or passed as `senderFeeAddress` on the request. The fee is settled atomically on-chain upon successful order settlement, with no off-chain billing required. ## Recipient The **beneficiary** of the transaction who receives funds without interacting with the protocol directly. ### Characteristics * **Passive Role**: No direct protocol interaction required * **Multiple Options**: Can receive fiat or stablecoins * **Flexible Delivery**: Bank accounts, mobile wallets, or crypto wallets * **Zero Complexity**: Doesn't need to understand blockchain technology ### Delivery Methods * **Bank Transfer**: Direct deposit to local bank account * **Mobile**: Transfer to mobile wallet (M-Pesa, etc.) or other mobile payment systems * **Crypto Wallet**: Receive stablecoins in specified wallet > **Note:** Cash pickup is not supported. All off-ramps are to fiat accounts or wallets. ### Example Scenarios * **Family Remittance**: Receive USD in local bank account * **Freelancer Payment**: Get paid in local currency for crypto work * **Business Settlement**: Receive supplier payments in preferred currency * **Investment Returns**: Convert crypto gains to fiat * **Stablecoin Purchase**: Pay in local currency and receive stablecoins in a wallet ## Provider A **KYB-verified participant** that supplies fiat liquidity in exchange for stablecoins or provides stablecoins in exchange for fiat. ### Characteristics * **Liquidity Supply**: Provides fiat or crypto liquidity * **KYB Required**: Business verification for compliance * **PSP Integration**: Connects to Payment Service Providers * **Competitive Rates**: Sets rates based on market conditions ### Responsibilities * **Order Fulfillment**: Pay out fiat on off-ramp orders and collect fiat on on-ramp orders * **Rate Management**: Set competitive rates for currency pairs * **Compliance**: Maintain regulatory compliance and reporting * **Infrastructure**: Operate reliable payment infrastructure ### Revenue Model * **Rate spread**: Earn the spread between your quoted rate and your cost of liquidity * **Order flow**: Access order flow from senders integrated with Paycrest ### Provider Types > [card] Traditional PSPs > > * Banks and financial institutions > * Money transfer operators > * Payment processors > * Mobile payment providers > [card] Crypto-Native Providers > > * Crypto exchanges > * DeFi protocols > * Crypto payment processors ## Aggregator The **Paycrest Aggregator** is the neutral middle between senders and independent verified providers. It coordinates every order from creation to settlement and never holds funds. ### Characteristics * **Order Matching**: Matches orders with suitable providers * **Quality Assurance**: Ensures reliable order fulfillment * **Compliance Oversight**: Verifies sender and provider businesses (KYB) and screens orders for sanctions risk * **Infrastructure**: Operates high-availability nodes ### Responsibilities * **Order Indexing**: Monitor blockchain for new orders * **Provider Management**: Maintain the provider registry * **Order Assignment**: Match orders with optimal providers * **Settlement Coordination**: Coordinate settlement with the assigned provider * **Compliance Verification**: Verify businesses before they go live and hold flagged orders for review * **Refunds**: Unfulfilled orders are refunded automatically, so there is no manual dispute process ### Aggregator Functions **1. Order Detection** Monitor Gateway contract for new payment orders **2. Provider Matching** Find suitable providers based on rates, limits, and availability **3. Order Assignment** Assign orders to providers with optimal conditions **4. Fulfillment Monitoring** Track order fulfillment and validate completion **5. Settlement Coordination** Coordinate on-chain settlement ### Who runs the aggregator Today the **Paycrest Aggregator**, operated by Paycrest, is the only aggregator. The protocol is designed to support independent aggregators in the future. ## Participant Relationships ### Sender → Aggregator * **Order Submission**: Senders submit orders through API * **Status Updates**: Receive real-time order status updates * **Webhook Notifications**: Get notified of order lifecycle events ### Aggregator → Provider * **Order Assignment**: Aggregators assign orders to providers * **Rate Management**: Providers set competitive rates * **Fulfillment Coordination**: Coordinate payment execution ### Provider → Recipient * **Payment Execution**: Providers execute payments to recipients * **Settlement Confirmation**: Confirm successful payment delivery * **Compliance Reporting**: Report transactions for regulatory compliance ### Key Benefits > [card] For Senders > > * One quoted rate per order > * Global reach with local delivery > * Real-time status tracking > * Verified counterparties > [card] For Recipients > > * No technical knowledge required > * Multiple delivery options > * Fast settlement times > * Competitive exchange rates > [card] For Providers > > * Access to global demand > * Automated order matching > * Escrow-backed settlement > * Order flow from integrated senders # Transaction Lifecycle Source: https://docs.paycrest.io/concepts/transaction-lifecycle Understanding how payment messages flow through the Paycrest protocol from order creation to settlement Paycrest supports two payment directions: **off-ramp** (stablecoin → fiat) and **on-ramp** (fiat → stablecoin). Both flows follow a similar lifecycle through the protocol. ## Off-ramp Lifecycle (Stablecoin → Fiat) ```mermaid theme={null} stateDiagram-v2 [*] --> initiated initiated --> deposited: deposit received initiated --> expired: no deposit before validUntil deposited --> pending: provider matched pending --> fulfilling: fiat payout started fulfilling --> validated: payout confirmed validated --> settling: settlement tx broadcast settling --> settled: onchain confirmed deposited --> refunding: fulfillment failed pending --> refunding: fulfillment failed fulfilling --> refunding: fulfillment failed refunding --> refunded: funds returned to sender expired --> [*] settled --> [*] refunded --> [*] ``` **1. initiated** Sender creates a payment order via the API or Gateway contract. The order is recorded and a receive address (deposit address) is returned. Funds have not yet arrived. **2. deposited** Stablecoins are detected at the receive address. The protocol confirms the deposit and begins matching. **3. pending** The aggregator has assigned the order to a suitable liquidity provider. The provider's provision node is processing the fiat payout. **4. fulfilling** The provision node is actively disbursing fiat to the recipient's bank account or mobile wallet via a local PSP. **5. validated** The provider has confirmed successful fiat delivery. The order is waiting for on-chain settlement. **6. settling** On-chain settlement is in progress: the escrowed stablecoins are being released to the provider. **7. settled** The order is fully closed. Stablecoins have been released to the provider; fiat has been delivered to the recipient. > [!NOTE] > > **Performance**: The median NGN order completes in under 30 seconds from deposit. If fulfillment fails after a deposit is received, the sender is refunded automatically. > [!WARNING] > > **expired vs refunded**: These are two distinct failure modes. `expired` means the receive address (off-ramp) or virtual account (on-ramp) was never funded — no deposit was received. `refunded` means a deposit was received but the order could not be fulfilled (e.g. no available provider, PSP unavailability, rate constraints) — and the deposited funds have been returned to the sender. ## On-ramp Lifecycle (Fiat → Stablecoin) ```mermaid theme={null} stateDiagram-v2 [*] --> initiated initiated --> pending: provider matched initiated --> expired: no fiat deposit (timeout) pending --> fulfilling: fiat deposit confirmed fulfilling --> validated: stablecoin release authorized validated --> settling: onchain transfer started settling --> settled: stablecoins delivered pending --> refunding: fulfillment failed fulfilling --> refunding: fulfillment failed refunding --> refunded: fiat returned expired --> [*] settled --> [*] refunded --> [*] ``` **1. initiated** Sender creates an on-ramp order via the API. The protocol returns provider account details (virtual bank account or mobile wallet) for the user to deposit fiat into. **2. pending** The aggregator has matched the order to a provider. Waiting for the user's fiat deposit to be confirmed by the provider. **3. fulfilling** Provider has confirmed fiat receipt. The protocol is preparing to release stablecoins to the recipient's wallet address. **4. validated** Fiat receipt confirmed and stablecoin release authorized. **5. settling** On-chain transfer of stablecoins to the recipient's wallet is in progress. **6. settled** Stablecoins have been delivered to the recipient's wallet. The order is fully closed. > [!NOTE] > > `expired` means the virtual account was never funded — no fiat deposit was received. `refunded` means fiat was received but the order could not be completed, and the deposited funds have been returned. ## Order Statuses The complete set of order status values: | Status | Description | | - | - | | `initiated` | Order created, awaiting deposit | | `deposited` | Deposit confirmed (off-ramp only) | | `pending` | Assigned to provider, awaiting fulfillment | | `fulfilling` | Provider is disbursing fiat or stablecoins | | `fulfilled` | Fulfillment completed by provider (internal) | | `validated` | Payout confirmed | | `settling` | On-chain settlement in progress | | `settled` | Fully complete | | `cancelled` | Order cancelled | | `refunding` | Refund in progress (deposit received, fulfillment failed) | | `refunded` | Funds returned to sender | | `expired` | Receive address or virtual account expired without receiving a deposit | ## Webhook Events Paycrest sends webhooks to your configured endpoint as an order progresses. Most events are named after the status the order just entered (`payment_order.`); a small number report an event that is not a status change, and are marked below. Failed deliveries are retried automatically with exponential backoff, and every delivery is queryable and replayable via the [sender webhook endpoints](/implementation-guides/sender-api-integration#webhook-delivery-logs--retry). | Event | Triggered When | | - | - | | `payment_order.deposited` | Deposit confirmed on the receive address | | `payment_order.pending` | Order assigned to a provider | | `payment_order.validated` | Payout confirmed by provider | | `payment_order.settling` | On-chain settlement started | | `payment_order.settled` | Settlement complete — the recipient has the funds | | `payment_order.refunding` | Refund initiated | | `payment_order.refunded` | Refund complete — the funds have landed at the refund address | | `payment_order.expired` | Order expired without a deposit (after `validUntil`) | | `payment_order.compliance_hold` | On-ramp fiat received, settlement held pending compliance review (**not a status change** — see below) | > [!NOTE] > > Not all statuses emit webhooks. Intermediate states like `initiated`, `fulfilling`, and `cancelled` do not trigger webhook events. ### Compliance holds You may receive `payment_order.compliance_hold` when an on-ramp order's fiat has been received and the order is held for a compliance review. It is sent at most once per order. Always treat `payment_order.settled` or `payment_order.refunded` as the order's final outcome. A deposit from an account that is not the customer's own (the payer must match the customer in `source.kyc`) is usually not reviewed: Paycrest returns it in full to the account it came from, and you receive `payment_order.refunded` without a `payment_order.compliance_hold`. Paycrest may hold a deposit for review instead. Two things make this event different from the rest: * **It is not a status change.** The order deliberately remains `pending`, so `data.status` reads `pending`, not `compliance_hold`. If you route webhooks by `data.status`, this event will look like a duplicate `pending`, so branch on `event` instead. * **It is not final.** A held order does not expire. When the review ends, the order either settles (`payment_order.settled`) or the deposit is returned to the account it came from (`payment_order.refunded`). A review can take several days. **Polling instead of webhooks?** A held order reads `"status": "pending"` and may carry `"statusDetail": "under_review"`. Treat `status` as the source of truth; `statusDetail` is informational and may be absent. A deposit returned to the account it came from ends `refunded` with a `refundReason`: `payer_mismatch` when it came from an account not in the customer's name, or `payer_unverified` when the payer could not be confirmed. Both fields are on the v2 order and in v2 webhooks. Do not prompt the customer to pay again: a second deposit into the same virtual account will be held as well. What you tell your own customer is your decision; contact Paycrest support if you need to know where a review stands. ### Webhook Payload (v1) ```json theme={null} { "event": "payment_order.settled", "webhookVersion": "1", "data": { "id": "550e8400-e29b-41d4-a716-446655440000", "amount": "100", "amountInUsd": "100.00", "amountPaid": "100", "amountReturned": "0", "percentSettled": "100", "senderFee": "0.5", "networkFee": "0.01", "rate": "1500.50", "network": "base", "gatewayId": "0xabc123...", "senderId": "sender-uuid", "recipient": { "institution": "GTBINGLA", "accountIdentifier": "1234567890", "accountName": "John Doe", "currency": "NGN", "memo": "Payment" }, "fromAddress": "0xsender...", "returnAddress": "0xrefund...", "reference": "payment-123", "txHash": "0xtxhash...", "status": "settled", "updatedAt": "2026-03-01T10:30:00Z", "createdAt": "2026-03-01T10:29:35Z" } } ``` ### Webhook Payload (v2) The v2 payload adds a `direction` field and uses polymorphic `source`/`destination` objects that vary based on whether the order is an off-ramp or on-ramp: ```json theme={null} { "event": "payment_order.settled", "webhookVersion": "2", "data": { "id": "550e8400-e29b-41d4-a716-446655440000", "direction": "offramp", "amount": "100", "amountInUsd": "100.00", "amountPaid": "100", "amountReturned": "0", "percentSettled": "100", "senderFee": "0.5", "transactionFee": "0.01", "rate": "1500.50", "gatewayId": "0xabc123...", "senderId": "sender-uuid", "source": { "type": "crypto", "currency": "USDT", "network": "base" }, "destination": { "type": "fiat", "currency": "NGN", "recipient": { "institution": "GTBINGLA", "accountIdentifier": "1234567890", "accountName": "John Doe", "memo": "Payment" } }, "fromAddress": "0xsender...", "reference": "payment-123", "txHash": "0xtxhash...", "status": "settled", "timestamp": "2026-03-01T10:30:00Z", "paymentReference": "100004261019223045000123456789" } } ``` ## Webhook Verification Verify the authenticity of webhook payloads using your API Secret to compute an HMAC-SHA256 signature and compare it against the `X-Paycrest-Signature` header. Always verify against the **raw request body bytes** — do not parse and re-serialize the JSON, as key ordering may differ. The `X-Paycrest-Signature` value is a **hex string**. Use **timing-safe** comparison on the **UTF-8 bytes** of the hex strings (`Buffer.from(hex, 'utf8')`), not `Buffer.from(hex, 'hex')`. Trim and lowercase the header first. > [tab] JavaScript > > ```javascript theme={null} > const crypto = require('crypto'); > > function verifyWebhook(rawBody, signature, secret) { > const sig = (signature && String(signature).trim().toLowerCase()) || ''; > const key = String(secret || '').trim(); > if (!sig || !key) return false; > > const bodyBuf = Buffer.isBuffer(rawBody) ? rawBody : Buffer.from(rawBody, 'utf8'); > const computed = crypto.createHmac('sha256', key).update(bodyBuf).digest('hex').toLowerCase(); > if (computed.length !== sig.length) return false; > try { > return crypto.timingSafeEqual(Buffer.from(computed, 'utf8'), Buffer.from(sig, 'utf8')); > } catch { > return false; > } > } > ``` > [tab] Python > > ```python theme={null} > import hmac > import hashlib > > def verify_webhook(raw_body, signature, secret): > # raw_body is request.data (raw bytes) > sig = (signature or "").strip().lower() > body = raw_body if isinstance(raw_body, bytes) else raw_body.encode() > computed = hmac.new( > secret.strip().encode("utf-8"), > body, > hashlib.sha256, > ).hexdigest().lower() > return hmac.compare_digest(computed, sig) > ``` > [tab] Go > > ```go theme={null} > import ( > "crypto/hmac" > "crypto/sha256" > "encoding/hex" > "strings" > ) > > func verifyWebhook(payload []byte, signature, secret string) bool { > mac := hmac.New(sha256.New, []byte(strings.TrimSpace(secret))) > mac.Write(payload) > computed := hex.EncodeToString(mac.Sum(nil)) > sig := strings.ToLower(strings.TrimSpace(signature)) > return hmac.Equal([]byte(computed), []byte(sig)) > } > ``` ## Timeframes The median NGN order completes in under 30 seconds. Completion times vary by corridor, provider and payment rail. ## Error Handling There are two distinct failure paths: **`expired`** — No deposit was ever received. The receive address (off-ramp) or virtual account (on-ramp) expired without being funded. The order closes with no funds moved. Common causes: * User abandoned the payment flow * Deposit was sent to the wrong address or after the address expired **`refunded`**: A deposit was received but fulfillment failed. The deposited funds are automatically returned to the sender. For an off-ramp order already created on-chain, the refund is `amount + senderFee`: the transaction fee has already paid for the network. Common causes: * No provider available at the requested rate * PSP unavailability in the corridor * Deposited amount doesn't match the quoted rate within tolerance Monitor `payment_order.refunded` and `payment_order.expired` webhook events and implement retry logic in your integration. You can also poll [GET /v2/sender/orders/:id](/api-reference/sender/get-payment-order-by-id-v2) directly. # Use Cases Source: https://docs.paycrest.io/concepts/use-cases How businesses and developers use Paycrest for on-ramp and off-ramp payments Paycrest works in both directions: off-ramp (stablecoins to local currency) and on-ramp (local currency to stablecoins). The scenarios below show common ways businesses use it. For code, see the [Sender API Integration](/implementation-guides/sender-api-integration) guide. ## Crypto Businesses ### DeFi Payouts **Overview:** Enable DeFi protocols to pay out yields and rewards directly to users' bank accounts. **How it works:** * DeFi protocols integrate directly with Paycrest Gateway contract * Users receive stablecoin rewards from yield farming, staking, or trading * Protocol automatically converts rewards to fiat and sends to user's bank account * No manual withdrawal process required **Benefits:** * Automated payout system reduces operational overhead * Users receive funds in their preferred local currency * Eliminates need for users to manage crypto-to-fiat conversion * Improves user experience and retention * Direct smart contract integration for better composability **Example Implementation:** ```javascript theme={null} // DeFi protocol payout using Gateway contract const gateway = new Contract(gatewayAddress, gatewayAbi, signer); const payoutOrder = await gateway.createOrder( usdtAddress, parseUnits('150.00', 6), rate, ZeroAddress, 0, refundAddress, messageHash ); ``` ### Wallet and App On-ramp **Overview:** Let users buy stablecoins with local currency from inside a wallet or app. **How it works:** * The app creates an on-ramp order through the Sender API from its backend * The user pays the exact amount shown into the provider's local account * Once the provider confirms the payment, stablecoins are delivered to the user's wallet on-chain * If the payment can't be completed, it is refunded to the user's account **Benefits:** * Users fund their wallets without leaving the app * The rate is quoted before the user pays * The same integration also handles off-ramp ### NFT Marketplace Payouts **Overview:** Enable NFT marketplaces to pay out sales proceeds to creators and sellers. **How it works:** * NFT marketplace integrates Paycrest for automatic payouts * When NFT sells, proceeds are converted to fiat * Funds are sent directly to creator's bank account * Supports multiple currencies and regions **Benefits:** * Creators receive payments in their local currency * Reduces payment processing fees * Faster settlement compared to traditional payment methods * Global reach for international creators ### Crypto Exchange Off-ramp **Overview:** Provide users with seamless off-ramp capabilities directly from crypto exchanges. **How it works:** * Exchange integrates Paycrest Sender API * Users can sell crypto and receive fiat directly * Supports multiple cryptocurrencies and fiat currencies * Real-time exchange rates and instant settlement **Benefits:** * One-click crypto-to-fiat conversion * Competitive exchange rates * Fast settlement times * Global currency support ## Traditional Businesses ### Cross-Border Payroll **Overview:** Enable companies to pay international employees and contractors using stablecoins. **How it works:** * Company holds stablecoins for payroll * Integrates Paycrest to convert to local currencies * Employees receive payments in their preferred currency * Automated payroll processing with real-time rates **Benefits:** * Reduced international transfer fees * Faster payment processing * Transparent exchange rates * Simplified compliance and reporting ### E-commerce Payment Processing **Overview:** Enable e-commerce platforms to accept crypto payments and settle in fiat. **How it works:** * Customers pay with crypto at checkout * Platform converts to fiat using Paycrest * Merchants receive payments in their local currency * Real-time conversion with competitive rates **Benefits:** * Access to crypto-paying customers * Reduced payment processing fees * Global market expansion * Automated settlement process ### Freelancer and Gig Economy Payments **Overview:** Streamline payments for freelancers and gig economy workers globally. **How it works:** * Platforms integrate Paycrest for contractor payments * Workers receive payments in their local currency * Automated payment processing * Support for multiple payment methods **Benefits:** * Faster payment processing * Reduced international transfer fees * Improved worker satisfaction * Simplified platform operations ## Financial Services ### Remittance Services **Overview:** Enable remittance companies to offer faster, cheaper international transfers. **How it works:** * Remittance company uses stablecoins for transfers * Paycrest converts to local currencies * Recipients receive funds in their bank account * Real-time settlement and competitive rates **Benefits:** * Lower transfer fees compared to traditional methods * Faster settlement times * Transparent exchange rates * Global reach with local compliance ### Microfinance and Lending **Overview:** Enable microfinance institutions to disburse loans and collect repayments efficiently. **How it works:** * Lenders use stablecoins for loan disbursement * Paycrest converts to local currencies for borrowers * Repayments can be collected in local currency and converted to stablecoins (on-ramp) * Automated payment processing **Benefits:** * Reduced operational costs * Faster loan disbursement * Improved repayment tracking * Access to unbanked populations ## Gaming and Entertainment ### Gaming Platform Payouts **Overview:** Enable gaming platforms to pay out winnings and rewards to players globally. **How it works:** * Gaming platform integrates Paycrest for payouts * Players receive winnings in their local currency * Supports multiple payment methods * Real-time conversion and settlement **Benefits:** * Global player base support * Faster payout processing * Reduced payment fees * Improved player experience ### Content Creator Payments **Overview:** Enable platforms to pay content creators and influencers globally. **How it works:** * Platform uses Paycrest for creator payments * Creators receive payments in their local currency * Automated payment processing * Support for multiple currencies **Benefits:** * Global creator network * Faster payment processing * Reduced international fees * Simplified platform operations ## Enterprise Solutions ### B2B Payment Processing **Overview:** Enable businesses to make international payments to suppliers and partners. **How it works:** * Company holds stablecoins for international payments * Paycrest converts to supplier's local currency * Real-time settlement with competitive rates * Automated payment processing **Benefits:** * Reduced international transfer costs * Faster payment processing * Transparent exchange rates * Simplified treasury management ### Treasury Management **Overview:** Enable companies to manage international cash flows using stablecoins and Paycrest. **How it works:** * Company holds stablecoins for international operations * Paycrest provides conversion to local currencies * Automated payment processing * Real-time rate management **Benefits:** * Reduced currency risk * Lower transaction costs * Faster international payments * Simplified cash management ## Getting Started To implement any of these use cases: 1. **Sign up** as a sender at [app.paycrest.io](https://app.paycrest.io) 2. **Complete KYB** for your business 3. **Get API credentials** from your dashboard 4. **Integrate the Sender API**: start with the [Quickstart](/quickstart), then the [Sender API Integration](/implementation-guides/sender-api-integration) guide 5. **Test** with small amounts (\$0.50 minimum on most networks) 6. **Go live** > [!WARNING] > > Call the Sender API from your backend. Never put your API key or secret in a browser or mobile app. # Provider Setup Guide Source: https://docs.paycrest.io/implementation-guides/provider-setup-guide Complete step-by-step guide to become a Paycrest provider and run a provision node This guide walks you through the complete process of becoming a Paycrest provider, from initial signup to running a production provision node. Follow these steps to start earning from on-ramp and off-ramp orders. ### Step 1: Signup as a Provider 1. Visit [https://app.paycrest.io](https://app.paycrest.io) 2. Sign up as a **Provider** 3. Complete the registration process ### Step 2: Initiate KYB Process * Complete the basic in-app Know-Your-Business (KYB) process * This process can run concurrently with PSP account setup * KYB approval is required for production access ### Step 3: Register with Payment Service Providers (PSPs) Your provision node can support multiple payment service providers to ensure reliable transaction processing. The specific PSPs available to you will be shown in your provider dashboard so you can begin PSP account setup in parallel with your KYB process. #### Obtain Required Credentials You need two credential groups: 1. **Paycrest Aggregator Credentials** (from your Paycrest dashboard) * Go to **Provider Dashboard → Settings → Payout tab → API Keys** * Copy: * **API Key** -> set as `AGGREGATOR_CLIENT_ID` * **API Secret** -> set as `AGGREGATOR_SECRET_KEY` 2. **PSP Credentials** (from each PSP portal) * For each PSP you enable, collect the required fields (for example: API key, client secret, client assertion, account ID, base URL, callback URL, webhook secret) * Use the dashboard PSP setup page to see the exact environment variable keys to populate * Add these values to your node `.env` ### Step 4: Provision Node Setup Choose your provision node hosting method: #### Option A: Blockops (Managed hosting) * Managed hosting with guided setup * Video setup guide available * Start here: [https://blockops.network](https://blockops.network) * After setup, obtain the Host Identifier URL from Blockops * In the app: **Settings → Payout tab → Configure Provision Node → Host identifier** — paste the URL and click **Update** Choose this option if you want faster setup with minimal infrastructure management. #### Option B: Self-Hosted Deployment (Recommended for Developers) A Paycrest provision node is a backend service hosted on Docker Hub. The deployment process involves pulling the Docker image, configuring environment variables, and starting the server. **Requirements:** * Docker installed on your server * Access to Docker Hub * Server with internet connectivity * Minimum 512MB RAM, 1 vCPU (tested on DigitalOcean \$5 droplet) **Deployment Steps:** 1. **Pull the Docker Image** ```bash theme={null} docker pull safaria/riverpod:latest ``` 2. **Create Environment Configuration** Create a `.env` file with your configuration: ```bash theme={null} # Server Config DEBUG=False ALLOWED_HOSTS=* # optional; used for trusted proxy configuration SERVER_HOST=0.0.0.0 # optional (default: 0.0.0.0) SERVER_PORT=8000 # optional (default: 8000) CURRENCIES=KES # single currency # CURRENCIES=NGN,KES,UGX # multiple currencies must be comma-separated ENVIRONMENT=production # local, staging, production SERVER_URL=https://your-server-domain-or-ip EVM_PRIVATE_KEY= # required for EVM onramp settlements STARKNET_SNIP9_USER_ADDRESS= # required for Starknet onramp (payin) STARKNET_SNIP9_PRIVATE_KEY= # required for Starknet onramp (payin) # Aggregator Config AGGREGATOR_CLIENT_ID=your_paycrest_api_key # Provider Dashboard → Settings → Payout → API Keys AGGREGATOR_SECRET_KEY=your_paycrest_api_secret # Provider Dashboard → Settings → Payout → API Keys AGGREGATOR_BASE_URL=https://api.paycrest.io/v2/provider # PSP Config - Only configure for PSPs you are using # Use the exact variable names shown for each PSP on the dashboard PSP setup page # (availability varies by corridor and currency) _API_KEY= _SECRET_KEY= ``` > **Credential Mapping** > > * `AGGREGATOR_CLIENT_ID` must be your Paycrest **API Key** (Settings → **Payout** → **API Keys**) > * `AGGREGATOR_SECRET_KEY` must be your Paycrest **API Secret** (Settings → **Payout** → **API Keys**) > * PSP variables (`_*`) use values issued by each PSP. Prefixes match PSPs listed in the dashboard; availability depends on your corridor and currency. #### `EVM_PRIVATE_KEY` explained * **What it is**: The private key for a dedicated EVM wallet (EOA) used by your provision node. * **When you need it**: Required for EVM on-ramp-related wallet/authorization flows. If you're running off-ramp-only operations, you can leave it unset. * **How to generate it**: Create a new dedicated EVM wallet (do not reuse a personal wallet) and use that wallet's private key. * **Security**: Treat this as a production secret. Never commit it to git, store it in a secure secret manager or protected `.env`, and rotate it immediately if exposed. #### Starknet on-ramp envs explained * **What they are**: * `STARKNET_SNIP9_USER_ADDRESS` — Starknet account address used to sign SNIP-9 OutsideExecution payin messages * `STARKNET_SNIP9_PRIVATE_KEY` — private key for that Starknet account * **When you need them**: Required when fulfilling **Starknet on-ramp (payin)** orders. If you only handle EVM or off-ramp-only flows, you can leave them unset. * **Address format**: Use a Starknet felt hex address (`0x` + 63–64 hex characters), not an EVM checksum address. * **Security**: Treat both as production secrets. Never commit them to git, store them in a secure secret manager or protected `.env`, and rotate them immediately if exposed. > **Important Notes:** > > * One node works for multiple currencies and can support multiple PSPs (for the same currency) > * Only configure the variables for the PSPs you are using > * If there is no comment on a credential key that has a value, DO NOT change that value > * DO NOT change the value of `AGGREGATOR_BASE_URL` > * The dashboard PSP setup page shows the exact environment variable keys per PSP > * Retrieve the credential values from each PSP and place them in your `.env` 3. **Start the Service** ```bash theme={null} docker run -d -p 8000:8000 --env-file .env safaria/riverpod:latest ``` 4. **Verify Deployment** Check the info endpoint to confirm your node is running and reporting provider metadata: ```bash theme={null} curl http://your-server-ip:8000/info ``` Expected response: ```json theme={null} { "status": "success", "message": "Provider information", "data": { "serviceInfo": { "currencies": ["KES"], "totalPSPs": 1, "version": "..." } } } ``` 5. **Configure Host Identifier** * Take the base URL of your server (e.g., `http://your-server-ip:8000`) * In the app: **Settings → Payout tab → Configure Provision Node → Host identifier** — paste the URL and save * Go live on your dashboard **Benefits:** * Complete control over infrastructure * Custom security configurations * No dependency on third-party services * Potential cost savings at scale ### Step 5: Configure Trade Settings #### Set Rates & Limits **Rates: Choose between:** * **Floating Rate (Recommended)**: Allows dynamic pricing with a margin * **Fixed Rate**: Static pricing, less flexible **Slippage**: It's advised to enable slippage to handle volatility **Order Limits:** * Set your minimum limit: Set the minimum amount (in USD) you can fulfill * Set your maximum limit: Set an amount (in USD) based on the available fiat balance in your PSP account **Protocol fee:** A protocol fee, a percentage of each order, is deducted at settlement. It appears as `transactionFee` on provider orders in the API and as **Protocol Fee** on order details in the dashboard. #### Set Settlement Addresses **Configure Networks** * Add settlement addresses for all supported networks and tokens * You can add a settlement address on multiple networks for flexibility * For **Starknet**, use a Starknet wallet address (`0x` + 63–64 hex characters), not an EVM address — network identifier is `starknet` ### Step 6: Node Testing & Launch #### Testing in Private Mode * After setting your settlement address(es), test your node in Private mode before going public * With private mode, you can route a transaction to your node using Noblocks * To go "LIVE" in Private Mode, switch your node to "Private Mode" on your dashboard **Test with Noblocks:** Use the Noblocks testing tool to verify your node in private mode: `https://noblocks.xyz?provider=YOUR_PROVIDER_ID` (Replace `YOUR_PROVIDER_ID` with your actual provider ID) #### Go Live on Public Mode * Once testing is successful, switch to Public Mode * Ensure your PSP account is funded and active for transaction fulfillment ## Onboarding Checklist Use this checklist to track your progress: | Task | Status | | - | - | | Provider Account Created | ⬜ | | KYB Submitted | ⬜ | | PSP Accounts Created | ⬜ | | Paycrest API Key + API Secret copied (for `AGGREGATOR_CLIENT_ID` / `AGGREGATOR_SECRET_KEY`) | ⬜ | | PSP credentials obtained and added to `.env` | ⬜ | | Node Deployed (Preferably Blockops) | ⬜ | | Trade Settings Configured | ⬜ | | Settlement Addresses Added | ⬜ | | Node Tested in Private Mode | ⬜ | | Switched to Public Mode | ⬜ | ## Technical Requirements ### Infrastructure Requirements **Minimum Requirements:** * **512MB RAM, 1 vCPU** (tested on DigitalOcean \$5 droplet) * 50GB+ storage * Stable internet connection * Docker installed (for self-hosted deployment) > **Note:** The minimum requirements are based on real-world testing. A DigitalOcean \$5 droplet (512MB RAM, 1 vCPU, 50GB bandwidth) is sufficient for running a Provision Node in production. ### Docker Installation (For Self-Hosted) If you choose self-hosted deployment, install Docker on your server: ```bash theme={null} # Update system packages sudo apt update && sudo apt upgrade -y # Install Docker curl -fsSL https://get.docker.com -o get-docker.sh sudo sh get-docker.sh # Add user to docker group sudo usermod -aG docker $USER # Logout and login again for docker group changes to take effect # Or run: newgrp docker ``` ## Security Best Practices ### Network Security * Use firewalls to restrict access * Implement rate limiting * Enable DDoS protection * Use VPN for secure access ### Key Management * Store API keys securely * Rotate keys regularly * Use environment variables * Implement key encryption ### Monitoring and Alerting * Set up log aggregation * Configure performance alerts * Monitor transaction volumes * Track error rates ## Troubleshooting ### Common Issues **Node Not Starting** ```bash theme={null} # Check logs docker logs # Verify environment variables docker run --rm --env-file .env safaria/riverpod:latest echo "Environment loaded" # Restart container docker restart ``` **API Connection Issues** ```bash theme={null} # Test API connectivity curl -X GET https://api.paycrest.io/v2/currencies ``` **Database Connection Errors** ```bash theme={null} # Check container status docker ps # Verify environment variables docker exec env | grep DATABASE ``` ### Getting Help * **Documentation**: [docs.paycrest.io](https://docs.paycrest.io) * **Community**: [Telegram](https://t.me/+Stx-wLOdj49iNDM0) * **Support**: [support@paycrest.io](mailto:support@paycrest.io) * **Blockops Support**: Available through Blockops platform ### When to Contact Support Most providers can complete setup without support. Contact support only if: * KYB remains pending beyond expected review time * A required PSP is unavailable for your corridor * Node status remains offline after valid `hostIdentifier` and `.env` setup * API keys under **Settings → Payout → API Keys** are missing or cannot be copied/rotated ## Next Steps After successfully deploying your Provision Node: 1. **Test Transactions**: Process test transactions to verify functionality 2. **Monitor Performance**: Track your node's performance and earnings 3. **Scale Up**: Consider deploying additional nodes for increased capacity 4. **Optimize**: Fine-tune pricing and configuration based on market conditions For detailed API documentation and advanced configuration options, see the [API Reference](/api-reference/introduction). # Sender API Integration Source: https://docs.paycrest.io/implementation-guides/sender-api-integration Ship off-ramp and on-ramp with one create call; add verify-account and public rates when you want a richer checkout UX. The Sender API lets your app create payment orders in two directions: * **Off-ramp** — user sends stablecoins, recipient receives local fiat (bank or mobile wallet) * **On-ramp** — user deposits fiat into a virtual account, recipient receives stablecoins Both flows use the same endpoint: **`POST /v2/sender/orders`**. Direction comes from the `source` and `destination` types you pass. **Fastest path to production:** one authenticated create call. The API **validates** bank or mobile account details and **resolves** an acceptable rate inside that request—you are **not** required to call verify-account or the public rates URL first. The sections after [Create a payment order](#create-a-payment-order) cover what happens next (response shape, webhooks). [Optional: prefetch quotes and account names](#optional-prefetch-quotes-and-account-names) explains how to polish checkout when you want prefetching—not because it is required. > [!NOTE] > > Prefer natural language? Create and track orders from **Claude Code**, **Cursor**, or **VS Code** with the [Sender Agent Guide](/implementation-guides/sender-mcp) (MCP). ## Flow Overview > [tab] Off-ramp (Stablecoin → Fiat) > > ```mermaid theme={null} > sequenceDiagram > participant App as Sender App > participant API as Sender API > participant GW as Gateway Contract > participant PRV as Provider Node > participant PSP as Local PSP > participant RCP as Recipient > > App->>API: POST /v2/sender/orders
(source: crypto, destination: fiat) > API-->>App: receiveAddress + order ID > App->>GW: Transfer stablecoins to receiveAddress > GW-->>API: OrderCreated event > API->>PRV: Assign order > PRV->>PSP: Initiate fiat transfer > PSP->>RCP: Deliver fiat to bank / wallet > PRV-->>API: Payout confirmed > API->>GW: Release escrow > GW->>PRV: Transfer stablecoins > API-->>App: Webhook: payment_order.settled > ``` > [tab] On-ramp (Fiat → Stablecoin) > > ```mermaid theme={null} > sequenceDiagram > participant App as Sender App > participant API as Sender API > participant PRV as Provider Node > participant USR as User > participant GW as Gateway Contract > participant WLT as Recipient Wallet > > App->>API: POST /v2/sender/orders
(source: fiat, destination: crypto) > API-->>App: providerAccount (virtual bank account) > App-->>USR: Show fiat deposit instructions > USR->>PRV: Deposit fiat to virtual account > PRV-->>API: Fiat deposit confirmed > API->>GW: Release stablecoins to recipient > GW->>WLT: Transfer stablecoins > API-->>App: Webhook: payment_order.settled > ``` ## Getting Started ### 1. Obtain API Credentials Sign up as a **Sender** at [app.paycrest.io](https://app.paycrest.io) and complete the KYB process. Once verified, you'll have: * **API Key** — included in every request as the `API-Key` header * **API Secret** — used to verify webhook signatures; keep this secret ```javascript theme={null} const headers = { "API-Key": "YOUR_API_KEY", "Content-Type": "application/json" }; ``` ### 2. Configure Tokens (Optional) In the dashboard settings, you can set defaults per token/network: fee percent, max fee cap, [who pays the transaction fee](#who-pays-the-transaction-fee), and addresses. **Off-ramp:** default `refundAddress` (crypto) and `feeAddress`; you can also pass `source.refundAddress` on the request. **On-ramp:** you supply **`source.refundAccount`** (fiat bank or mobile details for refunds) in the order payload—configure related defaults in the dashboard where available. *** ## Create a payment order **`POST /v2/sender/orders`** Pass a `source` and a `destination` object. The `type` field on each determines the direction. **Off-ramp** and **on-ramp** use the same endpoint; examples below include **`curl`** for both directions. The extra **JavaScript** and **Python** snippets are **off-ramp**-shaped—mirror the **on-ramp** `curl` payload (`source.type: "fiat"`, `destination.type: "crypto"`, `refundAccount`, etc.) in your language. > [!NOTE] > > **Starknet / Tron / Solana:** set `network` to **`starknet`**, **`tron`** or **`solana`**. Crypto addresses (`source.refundAddress` on off-ramp, `destination.recipient.address` on on-ramp) must match the network: Starknet felt hex (`0x` + 63–64 hex digits), Tron Base58 (`T…`) or a Solana Base58 public key (32–44 characters). Do not pass EVM checksum addresses on these networks. Tron and Solana are available through the v2 API only; `senderFeeAddress` on a Tron or Solana order is an address on that network too. See [Supported Stablecoins](/resources/supported-stablecoins). > [tab] Off-ramp (stablecoin → fiat) > > User sends stablecoins; recipient receives fiat. Set `source.type = "crypto"` and `destination.type = "fiat"`. > > ```bash theme={null} > curl -X POST "https://api.paycrest.io/v2/sender/orders" \ > -H "API-Key: YOUR_API_KEY" \ > -H "Content-Type: application/json" \ > -d '{ > "amount": "100", > "source": { > "type": "crypto", > "currency": "USDT", > "network": "base", > "refundAddress": "0xYourWalletAddress" > }, > "destination": { > "type": "fiat", > "currency": "NGN", > "recipient": { > "institution": "GTBINGLA", > "accountIdentifier": "1234567890", > "accountName": "John Doe", > "memo": "Salary payment" > } > }, > "reference": "order-001" > }' > ``` > [tab] Off-ramp (Starknet) > > Same shape as EVM off-ramp; use `network: "starknet"` and a Starknet refund address. > > ```bash theme={null} > curl -X POST "https://api.paycrest.io/v2/sender/orders" \ > -H "API-Key: YOUR_API_KEY" \ > -H "Content-Type: application/json" \ > -d '{ > "amount": "100", > "source": { > "type": "crypto", > "currency": "USDT", > "network": "starknet", > "refundAddress": "0x046a056257607e1126a73b789bc6b56216e260261d4b54dd0809df46638bcbad" > }, > "destination": { > "type": "fiat", > "currency": "NGN", > "recipient": { > "institution": "GTBINGLA", > "accountIdentifier": "1234567890", > "accountName": "John Doe", > "memo": "Salary payment" > } > }, > "reference": "order-starknet-001" > }' > ``` > > After create, transfer Starknet USDT/USDC to `providerAccount.receiveAddress` (also a Starknet address) before `validUntil`. Confirm settlement via webhooks or [GET order by ID](/api-reference/sender/get-payment-order-by-id-v2). > [tab] Off-ramp (Tron) > > Same shape as EVM off-ramp; use `network: "tron"` and a Tron Base58 refund address (starts with `T`). Tron supports USDT, through the v2 API only. > > ```bash theme={null} > curl -X POST "https://api.paycrest.io/v2/sender/orders" \ > -H "API-Key: YOUR_API_KEY" \ > -H "Content-Type: application/json" \ > -d '{ > "amount": "100", > "source": { > "type": "crypto", > "currency": "USDT", > "network": "tron", > "refundAddress": "TYourTronWalletAddress............." > }, > "destination": { > "type": "fiat", > "currency": "NGN", > "recipient": { > "institution": "GTBINGLA", > "accountIdentifier": "1234567890", > "accountName": "John Doe", > "memo": "Salary payment" > } > }, > "reference": "order-tron-001" > }' > ``` > > After create, transfer **exactly** `providerAccount.amountToTransfer` of Tron USDT to `providerAccount.receiveAddress` (also a Tron address) before `validUntil`. A smaller deposit is not credited: it is returned to your `refundAddress`, less the Tron network's transfer cost. Confirm settlement via webhooks or [GET order by ID](/api-reference/sender/get-payment-order-by-id-v2). > [tab] On-ramp (fiat → stablecoin) > > User deposits fiat; recipient receives stablecoins. Set `source.type = "fiat"` and `destination.type = "crypto"`. > > ```bash theme={null} > curl -X POST "https://api.paycrest.io/v2/sender/orders" \ > -H "API-Key: YOUR_API_KEY" \ > -H "Content-Type: application/json" \ > -d '{ > "amount": "50000", > "amountIn": "fiat", > "source": { > "type": "fiat", > "currency": "NGN", > "refundAccount": { > "institution": "GTBINGLA", > "accountIdentifier": "1234567890", > "accountName": "John Doe" > }, > "kyc": { > "entityType": "person", > "personDetails": { > "fullName": "John Doe", > "birthDate": "1990-04-12", > "idDocument": { "type": "BVN", "number": "22212345678", "issuerCountry": "NG" } > } > } > }, > "destination": { > "type": "crypto", > "currency": "USDT", > "recipient": { > "address": "0xRecipientWalletAddress", > "network": "base" > } > }, > "reference": "order-002" > }' > ``` > [tab] JavaScript (off-ramp) > > ```javascript theme={null} > const res = await fetch("https://api.paycrest.io/v2/sender/orders", { > method: "POST", > headers: { "API-Key": "YOUR_API_KEY", "Content-Type": "application/json" }, > body: JSON.stringify({ > amount: "100", > source: { > type: "crypto", > currency: "USDT", > network: "base", > refundAddress: "0xYourWalletAddress" > }, > destination: { > type: "fiat", > currency: "NGN", > recipient: { > institution: "GTBINGLA", > accountIdentifier: "1234567890", > accountName: "John Doe", > memo: "Salary payment" > } > }, > reference: "order-001" > }) > }); > const order = await res.json(); > ``` > [tab] Python (off-ramp) > > ```python theme={null} > import requests > > order = requests.post( > "https://api.paycrest.io/v2/sender/orders", > headers={"API-Key": "YOUR_API_KEY", "Content-Type": "application/json"}, > json={ > "amount": "100", > "source": { > "type": "crypto", > "currency": "USDT", > "network": "base", > "refundAddress": "0xYourWalletAddress" > }, > "destination": { > "type": "fiat", > "currency": "NGN", > "recipient": { > "institution": "GTBINGLA", > "accountIdentifier": "1234567890", > "accountName": "John Doe", > "memo": "Salary payment" > } > }, > "reference": "order-001" > } > ).json() > ``` > [tab] JavaScript (on-ramp) > > ```javascript theme={null} > const res = await fetch("https://api.paycrest.io/v2/sender/orders", { > method: "POST", > headers: { "API-Key": "YOUR_API_KEY", "Content-Type": "application/json" }, > body: JSON.stringify({ > amount: "50000", > amountIn: "fiat", > source: { > type: "fiat", > currency: "NGN", > refundAccount: { > institution: "GTBINGLA", > accountIdentifier: "1234567890", > accountName: "John Doe", > }, > kyc: { > entityType: "person", > personDetails: { > fullName: "John Doe", > birthDate: "1990-04-12", > idDocument: { type: "BVN", number: "22212345678", issuerCountry: "NG" }, > }, > }, > }, > destination: { > type: "crypto", > currency: "USDT", > recipient: { > address: "0xRecipientWalletAddress", > network: "base", > }, > }, > reference: "order-002", > }), > }); > const order = await res.json(); > ``` > [tab] Python (on-ramp) > > ```python theme={null} > import requests > > order = requests.post( > "https://api.paycrest.io/v2/sender/orders", > headers={"API-Key": "YOUR_API_KEY", "Content-Type": "application/json"}, > json={ > "amount": "50000", > "amountIn": "fiat", > "source": { > "type": "fiat", > "currency": "NGN", > "refundAccount": { > "institution": "GTBINGLA", > "accountIdentifier": "1234567890", > "accountName": "John Doe", > }, > "kyc": { > "entityType": "person", > "personDetails": { > "fullName": "John Doe", > "birthDate": "1990-04-12", > "idDocument": { "type": "BVN", "number": "22212345678", "issuerCountry": "NG" }, > }, > }, > }, > "destination": { > "type": "crypto", > "currency": "USDT", > "recipient": { > "address": "0xRecipientWalletAddress", > "network": "base", > }, > }, > "reference": "order-002", > }, > ).json() > ``` ### Request Fields | Field | Type | Required | Description | | - | - | - | - | | `amount` | string | ✅ | Payment amount. Denomination set by `amountIn` (defaults to crypto units). | | `amountIn` | string | — | `"crypto"` (default) or `"fiat"`. Set to `"fiat"` when `amount` is in the fiat currency. | | `rate` | string | — | Exchange rate (fiat per crypto). **Omit** to let the API choose a valid rate. Pass **`rate`** only when you lock a quote from the user; it must stay within market tolerance. See [Prefetch a quote for the UI](#prefetch-a-quote-for-the-ui) if you display rates before create. | | `senderFee` | string | — | Optional fixed fee in crypto units. Mutually exclusive with `senderFeePercent`. | | `senderFeePercent` | string | — | Optional fee percentage you collect, settled atomically on-chain. Mutually exclusive with `senderFee`. | | `senderFeeAddress` | string | Conditionally | Fee recipient address. **Required when the effective sender fee is greater than zero** and no fee address is configured on the sender profile. Not required when fee is zero. | | `transactionFeePayer` | string | — | `"sender"` or `"customer"`: who pays the transaction fee on this order. Overrides the token's dashboard setting (default `"sender"`). See [Who pays the transaction fee](#who-pays-the-transaction-fee). | | `reference` | string | — | Your internal order ID. | | `source` | object | ✅ | `{ type: "crypto", ... }` for off-ramp; `{ type: "fiat", ... }` for on-ramp. | | `destination` | object | ✅ | `{ type: "fiat", ... }` for off-ramp; `{ type: "crypto", ... }` for on-ramp. | ### On-ramp customer KYC Every on-ramp order must identify the customer paying in, in **`source.kyc`**. An order without it, or with a field missing or malformed, returns **400** with `"field": "Source"` and a message listing **every** problem by path, so you can fix the payload in one round trip. **Person** (`"entityType": "person"`): | Field | Required | Rule | | - | - | - | | `personDetails.fullName` | ✅ | Customer's full name | | `personDetails.birthDate` | ✅ | `YYYY-MM-DD`; the customer must be 18 or over | | `personDetails.idDocument` | ✅ | `type` (`passport`, `nationalID` or `driverLicense`; for NGN also `BVN`), `number`, `issuerCountry` (ISO 3166-1 alpha-2) | | BVN or NIN | NGN only | The `idDocument` must be one of them: the BVN — `{"type": "BVN", "number": "<11 digits>", "issuerCountry": "NG"}` — or the NIN — `{"type": "nationalID", "number": "<11 digits>", "issuerCountry": "NG"}`. A BVN needs no other document | | `personDetails.contact.phoneE164` | KES only | The customer's Kenyan mobile number (`+2547…` or `+2541…`); the payment prompt is pushed here | **Organization** (`"entityType": "organization"`): | Field | Required | Rule | | - | - | - | | `organizationDetails.legalName` | ✅ | Registered name. `tradingName` is optional | | `organizationDetails.registrationNumber` | ✅ | | | `organizationDetails.registrationCountry` | ✅ | ISO 3166-1 alpha-2 | | `organizationDetails.directors` | ✅ | At least one director whose `personDetails` meets the person rules above (the KES phone is not needed for directors) | | `organizationDetails.contact.phoneE164` | KES only | The organization's Kenyan mobile number | **The customer must pay from their own account.** The provider reports who each deposit came from, and Paycrest checks it against `source.kyc`. An organization pays from an account in its `legalName` or `tradingName`, or from the personal account of a director whose national identifier you sent: the BVN or NIN for NGN, or the director's national ID (`personDetails.idDocument` with `"type": "nationalID"`) for other currencies. A deposit from anyone else is returned in full to the account it came from, and you receive `payment_order.refunded`; when it cannot be returned automatically, it is held for compliance review and you receive [`payment_order.compliance_hold`](/concepts/transaction-lifecycle#compliance-holds). **The refund account must belong to the customer.** Where the bank resolves the `source.refundAccount` holder's name (NGN), it must match `personDetails.fullName` or, for an organization, `legalName` or `tradingName`. A mismatch returns **400** `Refund account name does not match the customer in source.kyc`. **KYC on the other sides of an order** uses the same shape and is optional: * **Off-ramp `source.kyc`** — the customer sending the stablecoin. * **Off-ramp `destination.kyc`** — the recipient of the fiat payout. * **On-ramp `destination.kyc`** — the recipient of the stablecoin. ### Pin a provider queue By default the API resolves a **ranked queue of up to 3 providers** at order creation and assignment walks it in order—if the first declines, expires, or exhausts its retries, the order moves to the next. You don't have to do anything to get this. Set **`destination.providerIds`** when you want routing pinned to providers you already quoted. Typically you pass through the ids from [`GET /v2/rates`](/api-reference/general/get-token-rate) so the user is routed to the provider whose rate they saw: ```json theme={null} "destination": { "type": "fiat", "currency": "NGN", "providerIds": ["AbCdEfGh", "IjKlMnOp", "QrStUvWx"], "recipient": { "institution": "GTBINGLA", "accountIdentifier": "1234567890", "accountName": "John Doe", "memo": "Payment" } } ``` | Rule | Detail | | - | - | | Order matters | Entries are tried first to last. `providerIds[0]` should be the provider whose rate you locked in `rate`. | | Max **3** | More than 3 entries returns **400**. | | Format | Each id is exactly **8 alphabetic** characters (`A–Z`, `a–z`). | | Mutually exclusive with `providerId` | Sending **both** returns **400**. To route to a single provider, send a one-entry `providerIds`—the singular `providerId` is retained for backward compatibility. | | No duplicates, no empty strings | Both return **400**. | | Providers you can route to | Multi-entry queues must name **active** providers with a **live standard offer** for this corridor. A provider restricted to specific senders is allowed when **you are on its list**. | **A one-entry queue is a pin.** `providerIds: ["AbCdEfGh"]` routes exactly like `providerId: "AbCdEfGh"`, for every provider you're able to pin—the corridor checks above apply only to queues of two or more. That equivalence is what lets you use `providerIds` everywhere and never reach for the singular field. Validation failures return **400** with `message: "Failed to validate payload"` and `data` as a single object—`{ "field": "Destination", "message": "..." }`—not an array: | `data.message` | Cause | | - | - | | `providerId and providerIds are mutually exclusive; provide only one` | Both fields sent | | `providerIds accepts at most 3 providers` | More than 3 entries | | `Invalid provider ID "xyz". Expected 8 alphabetic characters` | Malformed entry | | `providerIds contains an empty provider ID` | Empty-string entry | | `providerIds contains duplicate provider ID: AbCdEfGh` | Repeated entry | | `provider AbCdEfGh cannot serve this order` | Entry is inactive, has no live offer for this corridor, or is restricted to senders that don't include you | > [!NOTE] > > **Exhausting the queue does not refund immediately.** After the last entry, Paycrest may still route the order elsewhere before refunding it. `providerIds` is accepted on create but **not echoed back**: order responses and webhooks return the singular assigned **`providerId`**. ### Pinning on on-ramp On-ramp picks its provider while the order is being created rather than walking a queue, so **`destination.providerIds` accepts at most one entry**—it is a pin in queue form, there so you never need the singular field: ```json theme={null} "destination": { "type": "crypto", "currency": "USDT", "providerIds": ["AbCdEfGh"], "recipient": { "address": "0xRecipientWalletAddress", "network": "base" } } ``` | `data.message` | Cause | | - | - | | `providerIds accepts a single entry on onramp orders` | Two or more entries | | `providerId and providerIds are mutually exclusive; provide only one` | Both fields sent | | `provider AbCdEfGh cannot serve this order` | The provider is restricted to senders that don't include you | > [!WARNING] > > Pinning an on-ramp order to a provider restricted to other senders returns **400**. Off-ramp has always behaved this way; on-ramp now matches, and it applies to **`providerId`** as well as `providerIds`. If you pin providers on on-ramp, confirm you're authorized for them. On the **v1** API the off-ramp field lives at **`recipient.providerIds`** with identical rules; its errors use `"field": "Recipient"`. *** ## KES mobile money (M-Pesa, Till, Paybill) Kenya off-ramp to mobile rails uses institution **`SAFAKEPC`** (Safaricom M-Pesa) or another KES **mobile\_money** code from **[GET /institutions/KES](/api-reference/general/list-supported-institutions)**. **Till** and **Paybill** are not separate institution codes—you pass them in **`destination.recipient.metadata`**. | Channel | `metadata.channel` | `accountIdentifier` | Notes | | - | - | - | - | | Phone M-Pesa | `Mobile` or omit | Mobile number (e.g. `254712345678`) | Default when channel is omitted and the identifier looks like a phone number. Use **`Mobile`** in new integrations (not `MoMo`, which is provider-internal). | | Till (buy goods) | `Till` | Till / buy-goods number | Do not rely on phone normalization; till numbers are not E.164 phones. | | Paybill | `Paybill` | Paybill account or reference | Set **`metadata.businessNumber`** to the paybill business number when required. | **Example — Till** ```json theme={null} "destination": { "type": "fiat", "currency": "KES", "recipient": { "institution": "SAFAKEPC", "accountIdentifier": "123456", "accountName": "Merchant Name", "memo": "Order 42", "metadata": { "channel": "Till" } } } ``` **Example — Paybill** ```json theme={null} "destination": { "type": "fiat", "currency": "KES", "recipient": { "institution": "SAFAKEPC", "accountIdentifier": "INV-001", "accountName": "Customer Name", "memo": "Invoice", "metadata": { "channel": "Paybill", "businessNumber": "400200" } } } ``` **KYC on off-ramp:** optional **`destination.kyc`** applies to the **recipient** only. Do not send sender or provider KYB on off-ramp create. **GET / webhooks (v2):** for off-ramp orders, **`destination.recipient.metadata`** returns the metadata you supplied on create (same shape as above). **`destination.kyc`** returns destination KYC when stored. There is no v1-style flat metadata fallback on v2 GET. **Verify-account:** Till and Paybill identifiers are not normalized as mobile phone numbers. Use the exact till or paybill values you will send on the order. *** ## Handle the create response The create response includes a `providerAccount` whose shape depends on direction: **off-ramp** gives a **crypto receive address**; **on-ramp** gives **virtual account / fiat transfer** instructions. ### Off-ramp — send tokens to `receiveAddress` ```json theme={null} { "id": "550e8400-...", "status": "initiated", "providerAccount": { "network": "base", "receiveAddress": "0xProviderReceiveAddress", "validUntil": "2026-03-01T10:05:00Z", "amountToTransfer": "100.6", "currency": "USDT" }, "source": { "type": "crypto", "currency": "USDT", "network": "base" }, "destination": { "type": "fiat", "currency": "NGN", "recipient": { ... } } } ``` Send **exactly** `providerAccount.amountToTransfer` of `providerAccount.currency` to `providerAccount.receiveAddress` on `providerAccount.network` before `validUntil`. It equals `amount + senderFee + transactionFee` (all returned in the response); `transactionFee` covers all network costs. When `providerAccount.memo` is present, include it with the deposit — without it the deposit cannot be credited. It is omitted when the deposit does not need one. ### On-ramp — present virtual account to user ```json theme={null} { "id": "550e8400-...", "status": "initiated", "providerAccount": { "institution": "Guaranty Trust Bank", "accountIdentifier": "0123456789", "accountName": "Provider A / John Doe", "amountToTransfer": "50000", "currency": "NGN", "validUntil": "2026-03-01T10:05:00Z" }, "source": { "type": "fiat", "currency": "NGN" }, "destination": { "type": "crypto", "currency": "USDT", "recipient": { ... } } } ``` Display the `providerAccount` details to your user. They must transfer exactly `amountToTransfer` in `currency` to `accountIdentifier` before `validUntil`. (There is no on-chain token `transfer` from your app for this path: the user moves **fiat** through their bank or mobile wallet.) The order's `amount` is what the recipient receives in stablecoins. When `destination.recipient.network` is `solana`, the recipient wallet must already have a token account for the stablecoin's mint. *** ## Monitor completion Listen for webhooks or poll `GET /v2/sender/orders/:id`. ### Webhook Events Configure your webhook URL in the [Sender Dashboard](https://app.paycrest.io). Most webhooks are named for the status the order entered (`payment_order.`) and all include a `direction` field (`"offramp"` or `"onramp"`). Branch on `event` rather than `data.status` — a few events, noted below, are not status changes: ```json theme={null} { "event": "payment_order.settled", "webhookVersion": "2", "data": { "id": "550e8400-...", "direction": "offramp", "status": "settled", "amount": "100", "txHash": "0x...", "paymentReference": "TIMCW5AK69", ... } } ``` | Event | When it fires | | - | - | | `payment_order.deposited` | Stablecoin deposit detected (off-ramp) | | `payment_order.pending` | Assigned to provider / fiat deposit confirmed (on-ramp) | | `payment_order.validated` | Fiat payout confirmed by provider | | `payment_order.settling` | On-chain release in progress | | `payment_order.settled` | Order complete — the recipient has the funds | | `payment_order.refunding` | Refund in progress | | `payment_order.refunded` | Funds returned — the refund has landed at the refund address | | `payment_order.expired` | No deposit received before `validUntil` | | `payment_order.compliance_hold` | On-ramp fiat received, settlement held pending compliance review. **Not a status change** — `data.status` stays `pending` | > [!NOTE] > > You can notify the user of a successful off-ramp at `payment_order.validated`: that's when the provider has confirmed fiat delivery. For on-ramp, use `payment_order.settled`: that's when stablecoins are confirmed on-chain at the recipient's address. **Payment reference.** On an off-ramp, the v2 order and v2 webhooks carry `paymentReference`: the receipt from the bank or mobile-money network that paid the recipient, such as an M-Pesa receipt code or a bank transfer session ID. Your customer can use it to trace the payout with their bank or mobile-money network. It is not your `reference`, the ID you set when creating the order. It is `null` until the payout is confirmed, and stays `null` on on-ramp orders, on orders paid before the field was added, and when the provider did not report one. Coverage depends on the provider, so treat `null` as normal. Once set, it does not change. > [!WARNING] > > **Do not prompt a retry on `payment_order.compliance_hold`.** The order stays `pending` while it is reviewed, and does not expire. It ends in `payment_order.settled`, or in `payment_order.refunded` with the deposit returned to the account it came from. A second deposit into the same virtual account will be held too. See [Compliance holds](/concepts/transaction-lifecycle#compliance-holds). ### Verify Webhook Signatures Verify the `X-Paycrest-Signature` header using HMAC-SHA256 with your API Secret: The header value is a **hex string** (64 characters for SHA-256). Compare it to your computed hex using **timing-safe equality on the UTF-8 bytes of those strings** (do not `Buffer.from(hex, 'hex')` for the header — that compares raw digest bytes and does not match how the aggregator compares signatures). Normalize the header with **trim** and **lowercase** before comparing. > [tab] JavaScript > > ```javascript theme={null} > const crypto = require('crypto'); > > function verifyWebhook(rawBody, signature, secret) { > const sig = (signature && String(signature).trim().toLowerCase()) || ''; > const key = String(secret || '').trim(); > if (!sig || !key) return false; > > const bodyBuf = Buffer.isBuffer(rawBody) ? rawBody : Buffer.from(rawBody, 'utf8'); > const computed = crypto.createHmac('sha256', key).update(bodyBuf).digest('hex').toLowerCase(); > if (computed.length !== sig.length) return false; > try { > return crypto.timingSafeEqual(Buffer.from(computed, 'utf8'), Buffer.from(sig, 'utf8')); > } catch { > return false; > } > } > > app.post('/webhook', express.raw({ type: 'application/json' }), (req, res) => { > const sig = req.headers['x-paycrest-signature']; > if (!verifyWebhook(req.body, sig, process.env.API_SECRET)) { > return res.status(401).send('Invalid signature'); > } > const { event, data } = JSON.parse(req.body); > // handle event... > res.sendStatus(200); > }); > ``` > [tab] Python > > ```python theme={null} > import hmac, hashlib > > def verify_webhook(raw_body: bytes, signature: str, secret: str) -> bool: > sig = (signature or "").strip().lower() > computed = hmac.new(secret.strip().encode("utf-8"), raw_body, hashlib.sha256).hexdigest().lower() > return hmac.compare_digest(computed, sig) > > @app.route('/webhook', methods=['POST']) > def webhook(): > sig = request.headers.get('X-Paycrest-Signature') > if not verify_webhook(request.data, sig, os.getenv('API_SECRET')): > return 'Invalid signature', 401 > payload = request.json > # handle payload['event'] ... > return '', 200 > ``` > [tab] Go > > ```go theme={null} > import ( > "crypto/hmac" > "crypto/sha256" > "encoding/hex" > "io" > "net/http" > "strings" > ) > > func verifyWebhook(body []byte, signature, secret string) bool { > mac := hmac.New(sha256.New, []byte(strings.TrimSpace(secret))) > mac.Write(body) > computed := hex.EncodeToString(mac.Sum(nil)) > sig := strings.ToLower(strings.TrimSpace(signature)) > return hmac.Equal([]byte(computed), []byte(sig)) > } > > func webhookHandler(w http.ResponseWriter, r *http.Request) { > body, _ := io.ReadAll(r.Body) > sig := r.Header.Get("X-Paycrest-Signature") > if !verifyWebhook(body, sig, os.Getenv("API_SECRET")) { > http.Error(w, "Invalid signature", http.StatusUnauthorized) > return > } > // handle body... > } > ``` ### Webhook delivery logs & retry Every webhook we send is recorded as a **delivery** you can inspect and replay — so a briefly-down endpoint no longer means a lost event. **Automatic retries.** A delivery that fails — either a transport error **or a non-2xx response** — is retried automatically with exponential backoff. Retries continue for a cumulative **24-hour window**, after which the delivery is marked `expired` and we email your sender account once. Return a `2xx` status as soon as you've accepted the event to stop retries. Each delivery has a `status`: | Status | Meaning | | - | - | | `pending` | Queued or awaiting its next retry | | `success` | Your endpoint returned a 2xx | | `failed` | Transport error or non-2xx; scheduled for retry | | `expired` | Gave up after the 24h retry window | The `trigger` field records what produced an attempt: `automatic` (first send), `cron_retry` (automatic backoff retry), or `manual_sync` / `manual_async` (a retry you initiated). **Inspect deliveries.** List your deliveries (newest first), filtered by `status`, `event`, `event_id`, `order_id`, or a `from`/`to` date range: ```bash theme={null} curl "https://api.paycrest.io/v2/sender/webhooks?status=failed" \ -H "API-Key: YOUR_API_KEY" ``` Fetch a single delivery to see the frozen request payload and the captured response body (truncated to 4KB): ```bash theme={null} curl "https://api.paycrest.io/v2/sender/webhooks/DELIVERY_ID" \ -H "API-Key: YOUR_API_KEY" ``` **Replay a delivery.** Retry replays the original frozen payload. Use `?sync=true` to replay immediately and get the HTTP result inline: ```bash theme={null} curl -X POST "https://api.paycrest.io/v2/sender/webhooks/DELIVERY_ID/retry?sync=true" \ -H "API-Key: YOUR_API_KEY" ``` Omit `sync` to queue a new delivery for the retry worker instead — the response is `202` with the new delivery's `id`: ```bash theme={null} curl -X POST "https://api.paycrest.io/v2/sender/webhooks/DELIVERY_ID/retry" \ -H "API-Key: YOUR_API_KEY" ``` All three endpoints are scoped to the authenticated sender; another sender's delivery returns `404`. See [List Webhook Deliveries](/api-reference/sender/list-webhook-deliveries), [Get Webhook Delivery](/api-reference/sender/get-webhook-delivery-by-id), and [Retry Webhook Delivery](/api-reference/sender/retry-webhook-delivery). ### Polling ```javascript theme={null} async function getOrderStatus(orderId) { const { data } = await fetch(`https://api.paycrest.io/v2/sender/orders/${orderId}`, { headers: { "API-Key": "YOUR_API_KEY" } }).then(r => r.json()); switch (data.status) { case 'validated': // offramp: fiat delivered — safe to notify user case 'settled': // onramp: stablecoins delivered — or offramp fully onchain case 'refunded': // funds returned case 'expired': // no deposit received } return data; } ``` *** ## Optional: Prefetch quotes and account names Use this when you want **clearer UX** before the user confirms—not because the API requires extra calls. ### Resolve the account display name early **`POST /v2/verify-account`** runs the **same checks** again on create, but calling it first cuts down “invalid account” surprises and returns a canonical **`accountName`** for your form. * **Off-ramp** — verify the **fiat recipient** you will send in `destination.recipient` (same `institution` and `accountIdentifier` as the order). * **On-ramp** — verify **`source.refundAccount`** (where fiat refunds go), not the crypto wallet in `destination.recipient`. For **KES Till or Paybill**, pass the same **`accountIdentifier`** and **`metadata.channel`** you will use on create. Phone-style normalization does not apply to till or paybill numbers. **NGN bank:** ```bash theme={null} curl -X POST "https://api.paycrest.io/v2/verify-account" \ -H "API-Key: YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "institution": "GTBINGLA", "accountIdentifier": "0123456789" }' ``` **KES M-Pesa** — you may send local (`07…`) or international (`254…`) MSISDN; the API normalizes to dial code `254` before verification: ```bash theme={null} curl -X POST "https://api.paycrest.io/v2/verify-account" \ -H "API-Key: YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "institution": "SAFAKEPC", "accountIdentifier": "0712345678" }' ``` For **KES Till/Paybill**, pass **`metadata`** (e.g. `"channel": "Till"`) so phone normalization is skipped — see [Verify Account](/api-reference/general/verify-account). A `200 OK` response returns the resolved name in `data`. If `data` is a real name (e.g. `"JOHN DOE"`), use that exact string as `accountName` on the order. If `data` is `"OK"`, name lookup is not available for that corridor—supply your own `accountName`. ### Prefetch a quote for the UI **`GET /v2/rates/{network}/{from}/{amount}/{to}`** is **public** (no API key). **`from` and `to`** are the fiat code and token symbol in either order. Use it when you want to **show** a rate before submit, or when you will pass **`rate`** on create (it must stay within market tolerance). If you omit **`rate`** on create, the API still picks an acceptable rate. > [!NOTE] > > The JSON `data` object includes **`buy`** and **`sell`** (unless you pass `?side=buy` or `?side=sell`). Use **`data.sell.rate`** for **off-ramp** and **`data.buy.rate`** for **on-ramp** when displaying a quote. **`provider_id`** is optional and must be exactly **8 letters** (`A–Z` or `a–z`) if you pin a provider. > > Each side also carries **`providerIds`**—up to **3** ranked provider ids, best first. Pass them to **`destination.providerIds`** on create to route the order to the providers you quoted (see [Pin a provider queue](#pin-a-provider-queue)). Add **`?limit=1|2|3`** to request fewer. > [tab] cURL > > ```bash theme={null} > curl "https://api.paycrest.io/v2/rates/base/USDT/100/NGN" > ``` > [tab] JavaScript > > ```javascript theme={null} > const res = await fetch("https://api.paycrest.io/v2/rates/base/USDT/100/NGN").then((r) => r.json()); > const sellRate = res.data?.sell?.rate; // offramp display > const buyRate = res.data?.buy?.rate; // onramp display > > // Ranked provider queue — pass straight through on create as destination.providerIds > const providerIds = res.data?.sell?.providerIds ?? []; > ``` > [tab] Python > > ```python theme={null} > import requests > res = requests.get("https://api.paycrest.io/v2/rates/base/USDT/100/NGN") > data = res.json()["data"] > sell_rate = (data.get("sell") or {}).get("rate") > buy_rate = (data.get("buy") or {}).get("rate") > > # Ranked provider queue — pass straight through on create as destination.providerIds > provider_ids = (data.get("sell") or {}).get("providerIds") or [] > ``` *** ## Sender Fees You can optionally charge your users a fee on each order. It's settled atomically on-chain: no off-chain billing required. You can configure a default fee in [Sender Dashboard](https://app.paycrest.io) settings, or pass a per-request fee via `senderFee` (fixed amount) or `senderFeePercent`. Do not send both `senderFee` and `senderFeePercent` on the same request. **Fee address rule:** when the effective sender fee is greater than zero (from the request or a profile-configured fee), a fee recipient address is **required** — either configured on the sender profile for that token, or passed as `senderFeeAddress` on the create payload. When the effective fee is zero, `senderFeeAddress` is not required. **Example — with sender fee (fee address required):** ```json theme={null} { "amount": "100", "amountIn": "fiat", "senderFeePercent": "1", "senderFeeAddress": "0xYourFeeRecipientAddress", "reference": "order-ref-001", "source": { "type": "fiat", "currency": "NGN", "refundAccount": { "institution": "MOMONGPC", "accountIdentifier": "1234567890", "accountName": "John Doe" }, "kyc": { "entityType": "person", "personDetails": { "fullName": "John Doe", "birthDate": "1990-04-12", "idDocument": { "type": "BVN", "number": "22212345678", "issuerCountry": "NG" } } } }, "destination": { "type": "crypto", "currency": "USDC", "recipient": { "address": "0xRecipientWalletAddress", "network": "base" } } } ``` Fixed fee alternative: ```json theme={null} { "amount": "100", "senderFee": "0.5", "senderFeeAddress": "0xYourFeeRecipientAddress", ... } ``` **Example — no sender fee (fee address not required):** ```json theme={null} { "amount": "100", "amountIn": "fiat", "reference": "order-ref-002", "source": { "type": "fiat", "currency": "NGN", "refundAccount": { "institution": "MOMONGPC", "accountIdentifier": "1234567890", "accountName": "John Doe" }, "kyc": { "entityType": "person", "personDetails": { "fullName": "John Doe", "birthDate": "1990-04-12", "idDocument": { "type": "BVN", "number": "22212345678", "issuerCountry": "NG" } } } }, "destination": { "type": "crypto", "currency": "USDC", "recipient": { "address": "0xRecipientWalletAddress", "network": "base" } } } ``` **Off-ramp:** the total stablecoin amount the user sends to `providerAccount.receiveAddress` is `providerAccount.amountToTransfer` — `amount + senderFee + transactionFee`, all returned in the create response; `transactionFee` covers all network costs. **On-ramp:** the user pays **fiat** using `providerAccount.amountToTransfer` (and currency); fee line items in the response still describe what applies on settlement—follow the fields returned for your order. ### Who pays the transaction fee Every order carries a **transaction fee** (`transactionFee`) that covers its network costs. You choose who pays it, per token in the dashboard (**Settings › Trading › Transaction fee paid by**) or per order with `transactionFeePayer`: | `transactionFeePayer` | You earn (`senderFee`) | Your customer sends (`amountToTransfer`) | | - | - | - | | `sender` (default) | `max(0, fee − transactionFee)` | `amount + max(fee, transactionFee)` | | `customer` | `fee` | `amount + fee + transactionFee` | Here `fee` is the sender fee you configured or passed (`senderFee` / `senderFeePercent`, capped by your max fee cap). The response's `senderFee` is always what you earn, so `amountToTransfer = amount + senderFee + transactionFee` in both modes. For example, with a 100 USDC order, a 1% fee and a 0.1 USDC transaction fee: * `sender`: you earn 0.9 and your customer sends 101. * `customer`: you earn 1 and your customer sends 101.1. * `sender` with a 0.05 fee: you earn 0 and your customer sends 100.1. The fee is used up by the transaction fee and your customer pays the remaining 0.05. With no sender fee, both modes are the same. On-ramp works the same way: the fiat your customer pays covers `amount + senderFee + transactionFee` at the order's rate. *** ## On-chain attribution On EVM networks, the aggregator tags the transactions it submits for your orders (creation, settlement, and refunds) with an [ERC-8021](https://eip.tools/eip/8021) data suffix carrying the **trading name** from your KYB profile. It makes your orders publicly attributable to your business on-chain. * **Automatic.** There is nothing to configure or send. Senders with no trading name on file simply get no suffix. * **EVM only.** Starknet and Tron transactions carry no suffix. * **Display only.** The suffix does not affect order processing, sender resolution, or webhooks, and it is not read back by the aggregator. It costs roughly 16 gas per non-zero byte. If you call the Gateway contract directly instead of using this API, see [On-chain Attribution (ERC-8021)](/implementation-guides/smart-contract-interaction#on-chain-attribution-erc-8021) for appending your own suffix. *** ## Testing Paycrest runs on mainnet only. Test with the minimum order size: **\$0.50 on any supported chain**. Use small amounts until you've verified your integration end-to-end. **Smoke test:** credentials + **`POST /v2/sender/orders`** + handle **`providerAccount`** + one webhook or poll. Add **`verify-account`** and **`GET /v2/rates`** when you are polishing the checkout experience—they are not required to go live. *** ## v1 Legacy API The v1 API is fully supported for existing integrations. It supports **off-ramp only** and uses a flat request schema. > [accordion] v1 Off-ramp — Create Order > > `POST /v1/sender/orders` > > ```json theme={null} > { > "amount": 100, > "token": "USDT", > "network": "base", > "rate": "1500.50", > "recipient": { > "institution": "GTBINGLA", > "accountIdentifier": "1234567890", > "accountName": "John Doe", > "currency": "NGN", > "memo": "Payment" > }, > "reference": "order-001", > "returnAddress": "0xYourWalletAddress" > } > ``` > > The response includes `receiveAddress` (string) and `validUntil`. Send tokens to `receiveAddress`. > [accordion] v1 vs v2 Differences > > | Feature | v1 | v2 | > | - | - | - | > | Off-ramp | ✅ | ✅ | > | On-ramp | ❌ | ✅ | > | Schema | Flat: `token`, `network`, `recipient` | Polymorphic: `source`, `destination` with `type` | > | `refundAddress` | `returnAddress` (top-level) | `source.refundAddress` (off-ramp); on-ramp uses `source.refundAccount` | > | Amount direction | Always crypto | `amountIn: "fiat"` or `"crypto"` | > | Sender fee | Fixed via dashboard (fee + refund addresses required on profile) | Optional; `senderFee` / `senderFeePercent` on request. If fee > 0, `senderFeeAddress` (or profile fee address) is required | > | Numeric types | Number | String | > | Webhook version | `"1"` | `"2"` | *** ## Related * [Transaction Lifecycle](/concepts/transaction-lifecycle) — order statuses, webhook events, expired vs refunded * [Supported Stablecoins](/resources/supported-stablecoins) — tokens, networks, contract addresses * [Supported Currencies](/resources/supported-currencies) — active fiat corridors * [API Reference — Sender](/api-reference/sender/initiate-payment-order-v2) — full endpoint spec * [Sender Agent Guide](/implementation-guides/sender-mcp) — run Paycrest from Claude Code, Cursor, or VS Code via MCP # Sender Agent Guide Source: https://docs.paycrest.io/implementation-guides/sender-mcp Install the Paycrest sender agent (MCP) and connect it to Claude Code, Cursor, or VS Code to create and track payment orders with natural language. Use **Paycrest** from **Claude Code**, **Cursor**, or **VS Code** through the [Model Context Protocol (MCP)](https://modelcontextprotocol.io/). A small app runs on your machine, talks to the Paycrest Sender API, and lets your AI agent create and track payment orders in plain language. You do **not** need Go or a local clone for normal use: only an MCP-capable client and a sender API key. For HTTP API integration (apps and backends), see [Sender API Integration](/implementation-guides/sender-api-integration). ## Prerequisites 1. An **MCP client** — one of: * **[Claude Code](https://claude.com/claude-code)** * **[Cursor](https://cursor.com/)** * **[VS Code](https://code.visualstudio.com/)** with GitHub Copilot Chat (**Agent** mode) 2. A **sender API key** from the [Paycrest dashboard](https://paycrest.io) (Settings → API keys) 3. On Windows, **Windows PowerShell** — not Git Bash — for the install one-liner ## Install the agent The installer downloads the latest release binary to a **fixed path**. It configures Cursor automatically; Claude Code and VS Code are one manual step each, below. | OS | Binary path | | - | - | | Windows | `%USERPROFILE%\.paycrest\paycrest-mcp.exe` | | macOS / Linux | `~/.paycrest/paycrest-mcp` | ### Windows (PowerShell — not Git Bash) Open **Windows PowerShell** (or Terminal → PowerShell). Do **not** use Git Bash for this one-liner. ```powershell theme={null} irm https://raw.githubusercontent.com/paycrest/sender-mcp/main/scripts/install.ps1 | iex ``` ### macOS / Linux ```bash theme={null} curl -fsSL https://raw.githubusercontent.com/paycrest/sender-mcp/main/scripts/install.sh | bash ``` ### What the script does 1. Downloads the matching binary from [Releases](https://github.com/paycrest/sender-mcp/releases) 2. Saves it under `~/.paycrest/` with a fixed name (no manual rename) 3. Merges a `paycrest` entry into **Cursor’s** `~/.cursor/mcp.json` (unless you skip that step) > [!NOTE] > > The script does **not** configure Claude Code or VS Code — see [Connect Claude Code](#connect-claude-code) and [Connect VS Code](#connect-vs-code). > > Ignore the **Source code (zip/tar.gz)** links on the Releases page — those are source archives, not the MCP binary. ### Where the config lives All three clients run the **same binary** from the path above. Only the config file and its top-level key differ. | Client | Config | Top-level key | | - | - | - | | Claude Code | `~/.claude.json` (local / user scope), or `.mcp.json` in the repo root (project scope) — managed by `claude mcp` | `mcpServers` | | Cursor | `~/.cursor/mcp.json` | `mcpServers` | | VS Code | Command Palette → **MCP: Open User Configuration** | `servers` (plus `"type": "stdio"`) | You only ever need one environment variable: **`PAYCREST_API_KEY`**. ## Connect Claude Code The installer does not touch Claude Code. Add the server with one command: ```powershell Windows theme={null} claude mcp add --env PAYCREST_API_KEY=your-sender-api-key --transport stdio --scope user paycrest -- C:/Users/YOU/.paycrest/paycrest-mcp.exe ``` ```bash macOS / Linux theme={null} claude mcp add --env PAYCREST_API_KEY=your-sender-api-key --transport stdio --scope user paycrest -- ~/.paycrest/paycrest-mcp ``` > [!WARNING] > > Two flag-order rules, both easy to trip over: > > * **`--` must come before the binary path.** It separates Claude Code’s own options from the command that runs the server. > * **Don’t put the server name straight after `--env`.** `--env` accepts multiple `KEY=value` pairs, so `paycrest` would be read as another pair and rejected. Keep at least one other option (`--transport`, `--scope`) between them, as above. > > Write out the full Windows path — `%USERPROFILE%` is not expanded here. ### Choose a scope | Scope | Loads in | Stored in | | - | - | - | | `local` (default) | Current project only | `~/.claude.json` | | `project` | Current project, shared with your team | `.mcp.json` in the repo root | | `user` | All your projects | `~/.claude.json` | Use **`--scope user`** for Paycrest — a payments agent isn’t tied to one repo. ### Verify ```bash theme={null} claude mcp list ``` `paycrest` should show **`✔ Connected`**. Inside a Claude Code session, `/mcp` shows the same status and lets you inspect the server’s tools. To start over, run `claude mcp remove paycrest` and add it again. ### Project config (`.mcp.json`) If you’d rather commit the server for your whole team, add it at project scope and Claude Code writes `.mcp.json` in the repo root: ```json Windows theme={null} { "mcpServers": { "paycrest": { "command": "C:/Users/YOU/.paycrest/paycrest-mcp.exe", "env": { "PAYCREST_API_KEY": "your-sender-api-key" } } } } ``` ```json macOS / Linux theme={null} { "mcpServers": { "paycrest": { "command": "/Users/YOU/.paycrest/paycrest-mcp", "env": { "PAYCREST_API_KEY": "your-sender-api-key" } } } } ``` > [!WARNING] > > `.mcp.json` is meant to be committed. Don’t put a real sender API key in it — keep the key at user scope, or have each teammate set `PAYCREST_API_KEY` in their own environment. ## Connect Cursor The installer may already have done this — open `~/.cursor/mcp.json` and check for a `paycrest` entry before editing. Typical config after install (path may match your username): ```json Windows theme={null} { "mcpServers": { "paycrest": { "command": "C:/Users/YOU/.paycrest/paycrest-mcp.exe", "env": { "PAYCREST_API_KEY": "your-sender-api-key" } } } } ``` ```json macOS / Linux theme={null} { "mcpServers": { "paycrest": { "command": "/Users/YOU/.paycrest/paycrest-mcp", "env": { "PAYCREST_API_KEY": "your-sender-api-key" } } } } ``` ### Set your API key in Cursor Open the MCP settings (**Cursor Settings → Tools & MCP**) and edit the `paycrest` server’s JSON to replace `your-sender-api-key` with your key. > [tab] Windows > > 1. **Hover** over the **paycrest** MCP server. > 2. Click the **edit** (pencil) icon. > 3. Update `PAYCREST_API_KEY` in the JSON with your key. > [tab] macOS > > 1. Click the **three dots** on the right of the **paycrest** MCP server. > 2. Click **Configure**. > 3. Choose **User**. > 4. Update `PAYCREST_API_KEY` in the JSON with your key. ### Reload MCP After install or editing `mcp.json`: 1. Open **Cursor Settings → Tools & MCP**, or 2. Restart Cursor Confirm **paycrest** shows as connected / no error on the server. ## Connect VS Code The installer does not touch VS Code either, and its MCP config shape differs from Cursor’s. > [!NOTE] > > VS Code uses `"servers"` at the top level and requires `"type": "stdio"`. Cursor and Claude Code use `"mcpServers"`. Open **Command Palette → MCP: Open User Configuration** (or **MCP: Add Server** for a guided flow), then add: ```json Windows theme={null} { "servers": { "paycrest": { "type": "stdio", "command": "C:/Users/YOU/.paycrest/paycrest-mcp.exe", "env": { "PAYCREST_API_KEY": "your-sender-api-key" } } } } ``` ```json macOS / Linux theme={null} { "servers": { "paycrest": { "type": "stdio", "command": "/Users/YOU/.paycrest/paycrest-mcp", "env": { "PAYCREST_API_KEY": "your-sender-api-key" } } } } ``` ### Keep the key out of the file VS Code can prompt for the key instead of storing it in plain text. Use an `inputs` entry and reference it from `env`: ```json theme={null} { "inputs": [ { "id": "paycrest-api-key", "type": "promptString", "description": "Paycrest sender API key", "password": true } ], "servers": { "paycrest": { "type": "stdio", "command": "/Users/YOU/.paycrest/paycrest-mcp", "env": { "PAYCREST_API_KEY": "${input:paycrest-api-key}" } } } } ``` ### Start the server 1. Open **GitHub Copilot Chat**. 2. Switch chat mode to **Agent**. 3. Start or enable the `paycrest` MCP server when VS Code prompts (or run **MCP: List Servers**). 4. Try the smoke tests below. ## Smoke tests In Claude Code, Cursor Agent, or VS Code Copilot Chat (**Agent** mode), try: * “List Paycrest currencies” * “What’s the rate for 100 USDC on base to NGN?” If those succeed, the MCP server and API key are working. ## Order flow (create → pay → watch) Typical flow the agent should follow: **1. Create** Create an order (on-ramp or off-ramp) via natural language. **2. Pay-in details** The agent shows pay-in details (bank / wallet / account info) and the order id. **3. Send funds** You send the funds (fiat or crypto, as instructed). **4. Confirm payment** Reply **`paid`** (or “I have paid” / “transfer confirmed”). **5. Watch until terminal** The agent runs **one continuous watch** until the order is **settled**, **cancelled**, **refunded**, or **expired**. You can also use the MCP prompt **“After payment — watch order”** and paste the order id if the chat lost context. ### Example prompts **Off-ramp** (crypto → fiat): ```text theme={null} offramp 0.5 USDC Base, refund 0xYourRefundAddress, NGN OPay 0987654321, John Doe. ``` **On-ramp** (fiat → crypto): ```text theme={null} onramp 1000 NGN to USDC on Base at 0xYourWalletAddress, refund OPay 0987654321, name John Doe. ``` After you’ve paid: ```text theme={null} paid ``` ## Upgrade 1. **Quit every client running the server** — exit your Claude Code sessions, quit Cursor, quit VS Code. The running MCP process holds a lock on the `.exe` / binary. 2. Re-run the same install one-liner. 3. Reconnect: * **Claude Code** — start a new session, then `claude mcp list` * **Cursor** — **Cursor Settings → Tools & MCP** * **VS Code** — restart the `paycrest` server from **MCP: List Servers** If a client is still running, Windows often fails with “file in use” / access denied. > [!NOTE] > > Re-running the installer replaces the **binary** only. Your client config and API key are untouched. ## Troubleshooting | Problem | What to do | | - | - | | `irm` / curl returns **404** | Repo or raw script URL not reachable. Use a [Release](https://github.com/paycrest/sender-mcp/releases) download, or clone and run `.\scripts\install.ps1` / `./scripts/install.sh` with `gh auth login`. | | **File in use** / cannot overwrite binary | Quit **every** MCP client running the server — Claude Code sessions, Cursor, VS Code — then re-run install. | | Install fails in **Git Bash** | Use **PowerShell** on Windows for `irm … \| iex`. | | Auth / **401** / sender tools fail | Check `PAYCREST_API_KEY` in your client’s config (see [Where the config lives](#where-the-config-lives)) — wrong, expired, or missing key. In Claude Code, `claude mcp remove paycrest` then re-run the add command. Reload MCP after fixing. | | Downloaded something that isn’t an app | Ignore **Source code (zip/tar.gz)** on Releases. Use the platform asset (e.g. `…_windows_amd64.exe`, `…_darwin_arm64`). | | MCP server red / not listed / failed to connect | Confirm the `command` path exists (`ls ~/.paycrest`), then reload: `claude mcp list` (Claude Code), **Cursor Settings → Tools & MCP**, or **MCP: List Servers** (VS Code). | | `claude mcp add` rejected the name, or the server never starts | Flag order. `--env` must not sit immediately before the server name, and `--` must come before the binary path. Run `claude mcp remove paycrest`, then re-run the exact command above. | ## Links * [GitHub Releases (binaries)](https://github.com/paycrest/sender-mcp/releases) * [sender-mcp repository](https://github.com/paycrest/sender-mcp) * [Sender API Integration](/implementation-guides/sender-api-integration) # Smart Contract Interaction Source: https://docs.paycrest.io/implementation-guides/smart-contract-interaction Integrate with Paycrest using the Gateway smart contract for on-chain order management. Interact directly with the Paycrest Gateway smart contract for on-chain **stablecoin-to-fiat (off-ramp)** order creation, settlement, and refunds. This approach gives you full control over the blockchain transactions and is ideal for dapps, wallets, or any EVM-compatible application. > [!NOTE] > > This guide uses **Viem** for smart contract interactions, which is the recommended Ethereum library for modern applications. Viem provides better TypeScript support, improved performance, and a more intuitive API compared to ethers.js. > [!NOTE] > > **Starknet, Tron and Solana:** this page documents **EVM** contract calls only. For those networks, use the [Sender API Integration](/implementation-guides/sender-api-integration) with `network: "starknet"`, `"tron"` or `"solana"`. Tron and Solana orders are created through the v2 Sender API only. Token contracts for these networks are listed under [Supported Stablecoins](/resources/supported-stablecoins). ## Overview The Gateway contract is a multi-chain EVM-based smart contract that facilitates the on-chain lifecycle of payment orders. It empowers users to create off-ramp orders while enabling liquidity providers to facilitate those orders at competitive exchange rates. ## Prerequisites * **Paycrest Sender Account**: Register at [app.paycrest.io](https://app.paycrest.io) and complete KYB verification. You'll need your **API Key** to embed in every order's encrypted metadata: this links the on-chain order to your sender profile and enables webhooks. * **Ethereum Provider**: MetaMask, WalletConnect, or any Web3 provider * **Viem**: For smart contract interactions * **USDT/USDC Balance**: Sufficient token balance for orders * **Gas Fees**: ETH for transaction fees ## Connect Wallet > [tab] JavaScript > > ```javascript theme={null} > import { createPublicClient, createWalletClient, http, getAddress } from "viem"; > import { base } from "viem/chains"; > > // Connect to user's wallet > const publicClient = createPublicClient({ > chain: base, > transport: http() > }); > > const walletClient = await createWalletClient({ > chain: base, > transport: window.ethereum > }); > > const [userAddress] = await walletClient.getAddresses(); > ``` > [tab] Python > > ```python theme={null} > from web3 import Web3 > from eth_account import Account > > # Connect to Base network > w3 = Web3(Web3.HTTPProvider('https://mainnet.base.org')) > > # For browser integration, you'd typically use a wallet like MetaMask > # This example shows how to connect with a private key > account = Account.from_key('YOUR_PRIVATE_KEY') > user_address = account.address > ``` > [tab] Go > > ```go theme={null} > package main > > import ( > "fmt" > "log" > > "github.com/ethereum/go-ethereum/crypto" > "github.com/ethereum/go-ethereum/ethclient" > ) > > func connectWallet() { > // Connect to Base network > client, err := ethclient.Dial("https://mainnet.base.org") > if err != nil { > log.Fatal(err) > } > > // Load private key > privateKey, err := crypto.HexToECDSA("YOUR_PRIVATE_KEY") > if err != nil { > log.Fatal(err) > } > > // Get account address > publicKey := privateKey.Public() > publicKeyECDSA, ok := publicKey.(*crypto.PublicKey) > if !ok { > log.Fatal("error casting public key to ECDSA") > } > > userAddress := crypto.PubkeyToAddress(*publicKeyECDSA) > fmt.Printf("Connected wallet: %s\n", userAddress.Hex()) > } > ``` > [tab] cURL > > ```bash theme={null} > # Wallet connection is typically done in your application code > # rather than with cURL. Use one of the programming language examples above. > ``` ## Initialize Contracts > [tab] JavaScript > > ```javascript theme={null} > import { getContract } from "viem"; > > // Gateway contract configuration > const GATEWAY_ADDRESS = "0x30F6A8457F8E42371E204a9c103f2Bd42341dD0F"; // Base > const USDT_ADDRESS = "0xfde4C96c8593536E31F229EA8f37b2ADa2699bb2"; // USDT on Base > > // Contract instances > const gateway = getContract({ > address: GATEWAY_ADDRESS, > abi: GATEWAY_ABI, > publicClient, > walletClient > }); > > const usdt = getContract({ > address: USDT_ADDRESS, > abi: USDT_ABI, > publicClient, > walletClient > }); > ``` > [tab] Python > > ```python theme={null} > from web3 import Web3 > > # Gateway contract configuration > GATEWAY_ADDRESS = "0x30F6A8457F8E42371E204a9c103f2Bd42341dD0F" # Base > USDT_ADDRESS = "0xfde4C96c8593536E31F229EA8f37b2ADa2699bb2" # USDT on Base > > # Contract instances > gateway = w3.eth.contract(address=GATEWAY_ADDRESS, abi=GATEWAY_ABI) > usdt = w3.eth.contract(address=USDT_ADDRESS, abi=USDT_ABI) > ``` > [tab] Go > > ```go theme={null} > package main > > import ( > "github.com/ethereum/go-ethereum/common" > "github.com/ethereum/go-ethereum/ethclient" > ) > > // Gateway contract configuration > const GATEWAY_ADDRESS = "0x30F6A8457F8E42371E204a9c103f2Bd42341dD0F" // Base > const USDT_ADDRESS = "0xfde4C96c8593536E31F229EA8f37b2ADa2699bb2" // USDT on Base > > func initializeContracts(client *ethclient.Client) { > gatewayAddress := common.HexToAddress(GATEWAY_ADDRESS) > usdtAddress := common.HexToAddress(USDT_ADDRESS) > > // Contract instances would be created with ABI bindings > // This is a simplified example > fmt.Printf("Gateway contract: %s\n", gatewayAddress.Hex()) > fmt.Printf("USDT contract: %s\n", usdtAddress.Hex()) > } > ``` > [tab] cURL > > ```bash theme={null} > # Contract initialization is typically done in your application code > # rather than with cURL. Use one of the programming language examples above. > ``` ## Create an Order > [tab] JavaScript > > ```javascript theme={null} > async function createOffRampOrder(amount, recipient, refundAddress) { > try { > const rate = await getExchangeRate(); > const accountName = await verifyAccount(recipient); > const messageHash = await encryptRecipientData({ > ...recipient, > accountName, > metadata: { apiKey: process.env.PAYCREST_API_KEY } > }); > await approveUSDT(amount); > const { request } = await gateway.simulate.createOrder({ > args: [ > USDT_ADDRESS, > parseUnits(amount, 6), > rate, > zeroAddress, > 0n, > refundAddress, > messageHash > ] > }); > > const hash = await walletClient.writeContract(request); > const receipt = await publicClient.waitForTransactionReceipt({ hash }); > const orderId = extractOrderId(receipt); > return { orderId, transactionHash: receipt.hash }; > } catch (error) { > console.error("Error creating order:", error); > throw error; > } > } > ``` > [tab] Python > > ```python theme={null} > async def create_off_ramp_order(amount, recipient, refund_address): > try: > rate = await get_exchange_rate() > account_name = await verify_account(recipient) > message_hash = await encrypt_recipient_data({ > **recipient, > 'accountName': account_name, > 'metadata': {'apiKey': os.environ['PAYCREST_API_KEY']} > }) > await approve_usdt(amount) > > # Build transaction > tx = gateway.functions.createOrder( > USDT_ADDRESS, > w3.to_wei(amount, 'ether'), > rate, > '0x0000000000000000000000000000000000000000', > 0, > refund_address, > message_hash > ).build_transaction({ > 'from': user_address, > 'gas': 200000, > 'gasPrice': w3.eth.gas_price, > 'nonce': w3.eth.get_transaction_count(user_address) > }) > > # Sign and send transaction > signed_tx = w3.eth.account.sign_transaction(tx, private_key) > tx_hash = w3.eth.send_raw_transaction(signed_tx.rawTransaction) > receipt = w3.eth.wait_for_transaction_receipt(tx_hash) > > order_id = extract_order_id(receipt) > return {'orderId': order_id, 'transactionHash': receipt['transactionHash'].hex()} > except Exception as error: > print(f"Error creating order: {error}") > raise error > ``` > [tab] Go > > ```go theme={null} > func createOffRampOrder(amount string, recipient map[string]interface{}, refundAddress string) error { > rate, err := getExchangeRate() > if err != nil { > return err > } > > accountName, err := verifyAccount(recipient) > if err != nil { > return err > } > > recipient["accountName"] = accountName > recipient["metadata"] = map[string]interface{}{ > "apiKey": os.Getenv("PAYCREST_API_KEY"), > } > > messageHash, err := encryptRecipientData(recipient) > if err != nil { > return err > } > > err = approveUSDT(amount) > if err != nil { > return err > } > > // Build transaction data > data := buildCreateOrderData(amount, rate, refundAddress, messageHash) > > // Create transaction > tx := &types.Transaction{ > To: &gatewayAddress, > Value: big.NewInt(0), > Gas: 200000, > GasPrice: big.NewInt(20000000000), // 20 gwei > Data: data, > } > > // Sign and send transaction > signedTx, err := types.SignTx(tx, types.NewEIP155Signer(big.NewInt(8453)), privateKey) > if err != nil { > return err > } > > err = client.SendTransaction(context.Background(), signedTx) > if err != nil { > return err > } > > fmt.Printf("Order created with hash: %s\n", signedTx.Hash().Hex()) > return nil > } > ``` > [tab] cURL > > ```bash theme={null} > # Smart contract interactions are typically done in your application code > # rather than with cURL. Use one of the programming language examples above. > ``` ## Exchange Rate and Account Verification > [!NOTE] > > For **mobile money** recipients, you may pass local MSISDN (e.g. KES `07…`); **`POST /v2/verify-account`** normalizes dial codes server-side. Optional **`metadata`** on verify applies for KES Till/Paybill. See [Verify Account](/api-reference/general/verify-account). The same rates response also returns **`data.sell.providerIds`**—the ranked provider queue for the corridor. Read it alongside `rate` if you want to carry that queue into the encrypted recipient as `providerIds` (see [Routing fields](#routing-fields)). > [tab] JavaScript > > ```javascript theme={null} > async function getExchangeRate() { > const response = await fetch("https://api.paycrest.io/v2/rates/base/usdt/1/ngn"); > const body = await response.json(); > const rateStr = body.data?.sell?.rate ?? body.data?.buy?.rate; > return rateStr != null ? Number(rateStr) : NaN; > } > > async function verifyAccount(recipient) { > const response = await fetch("https://api.paycrest.io/v2/verify-account", { > method: "POST", > headers: { "Content-Type": "application/json" }, > body: JSON.stringify({ > institution: recipient.institution, > accountIdentifier: recipient.accountIdentifier > }) > }); > const data = await response.json(); > return data.data; > } > ``` > [tab] Python > > ```python theme={null} > import requests > > async def get_exchange_rate(): > response = requests.get("https://api.paycrest.io/v2/rates/base/usdt/1/ngn") > data = response.json() > d = data.get("data") or {} > side = d.get("sell") or d.get("buy") or {} > rate = side.get("rate") > return float(rate) if rate is not None else float("nan") > > async def verify_account(recipient): > response = requests.post( > "https://api.paycrest.io/v2/verify-account", > headers={"Content-Type": "application/json"}, > json={ > "institution": recipient["institution"], > "accountIdentifier": recipient["accountIdentifier"] > } > ) > data = response.json() > return data['data'] > ``` > [tab] Go > > ```go theme={null} > import ( > "bytes" > "encoding/json" > "fmt" > "io" > "net/http" > "strconv" > ) > > func getExchangeRate() (float64, error) { > resp, err := http.Get("https://api.paycrest.io/v2/rates/base/usdt/1/ngn") > if err != nil { > return 0, err > } > defer resp.Body.Close() > > body, err := io.ReadAll(resp.Body) > if err != nil { > return 0, err > } > > var result struct { > Data struct { > Sell *struct { > Rate string `json:"rate"` > } `json:"sell"` > Buy *struct { > Rate string `json:"rate"` > } `json:"buy"` > } `json:"data"` > } > if err := json.Unmarshal(body, &result); err != nil { > return 0, err > } > var rateStr string > if result.Data.Sell != nil { > rateStr = result.Data.Sell.Rate > } else if result.Data.Buy != nil { > rateStr = result.Data.Buy.Rate > } > if rateStr == "" { > return 0, fmt.Errorf("no rate in response") > } > return strconv.ParseFloat(rateStr, 64) > } > > func verifyAccount(recipient map[string]interface{}) (string, error) { > jsonData, _ := json.Marshal(map[string]interface{}{ > "institution": recipient["institution"], > "accountIdentifier": recipient["accountIdentifier"], > }) > > resp, err := http.Post( > "https://api.paycrest.io/v2/verify-account", > "application/json", > bytes.NewBuffer(jsonData), > ) > if err != nil { > return "", err > } > defer resp.Body.Close() > > body, err := io.ReadAll(resp.Body) > if err != nil { > return "", err > } > > var result map[string]interface{} > json.Unmarshal(body, &result) > > return result["data"].(string), nil > } > ``` > [tab] cURL > > ```bash theme={null} > # Get exchange rate (see data.sell.rate / data.buy.rate in JSON) > curl -X GET "https://api.paycrest.io/v2/rates/base/usdt/1/ngn" > > # Verify account > curl -X POST "https://api.paycrest.io/v2/verify-account" \ > -H "Content-Type: application/json" \ > -d '{ > "institution": "GTB", > "accountIdentifier": "1234567890" > }' > ``` ## Data Encryption The recipient object is encrypted with the aggregator's public key to produce the `messageHash` passed to the contract. **Always include your API Key in the `metadata.apiKey` field**: this is the same key used as the `API-Key` header in REST requests, and it links the on-chain order to your sender profile, enabling webhooks and order attribution. > [!NOTE] > > Your API Key is available in the dashboard at [app.paycrest.io](https://app.paycrest.io). > [!NOTE] > > On EVM networks you can additionally (or instead) attribute orders with an on-chain ERC-8021 data suffix. See [On-chain Attribution (ERC-8021)](#on-chain-attribution-erc-8021). ### Routing fields The recipient object may carry routing hints: this is the only channel for them on-chain, since `createOrder` has no provider argument: | Field | Description | | - | - | | `providerIds` | Ordered **provider queue** (max 3). Assignment tries entries in order. Typically the ids from [`GET /v2/rates`](/api-reference/general/get-token-rate). A one-entry queue routes to a single provider. | | `providerId` | Single provider, 8 alphabetic characters. Retained for backward compatibility—prefer `providerIds`. | The two are **mutually exclusive**. A hash carrying both is not rejected: the queue wins and `providerId` is ignored. A queue whose entries can't serve the corridor is **dropped silently** and the order routes as unpinned; there is no on-chain rejection and no error webhook, so validate ids against a rate quote before encrypting. Omit both and the aggregator resolves a queue itself at order creation. Entries in a multi-entry queue must name providers that can serve the corridor: active, with a live standard offer, and, for a provider restricted to specific senders, one whose list includes the sender resolved from `metadata.apiKey`. A one-entry queue is simply a pin. > [!WARNING] > > **Budget \~450 bytes for recipient data.** `MESSAGE_HASH_MAX_SIZE` caps the recipient JSON at **500 bytes**, measured **before** encryption. The size check reserves room for a full 3-provider queue on **every** order—including orders that send no `providerIds`—because the aggregator may resolve one onto the order, and it rides in the message hash at gateway submit. > > That reservation costs about **49 bytes** (**\~41** if you pin a `providerId`), leaving roughly **450 bytes** for `accountIdentifier` + `accountName` + `memo` + `metadata` combined. Exceeding it returns **400** with `"Recipient data too large for encryption"`. Trim `memo` and `metadata` first—see [Troubleshooting](/resources/troubleshooting). > [!NOTE] > > **Reading a hash the aggregator produced:** queued orders publish `"ProviderID": ""` plus a `ProviderIDs` array. Anything downstream that parses `ProviderID` must fall back to `ProviderIDs[0]`. Keys decode case-insensitively, so `providerIds` and `ProviderIDs` are equivalent on the way in. > [tab] JavaScript > > ```javascript theme={null} > async function encryptRecipientData(recipient) { > const response = await fetch("https://api.paycrest.io/v2/pubkey"); > const { data: publicKey } = await response.json(); > const encrypt = new JSEncrypt(); > encrypt.setPublicKey(publicKey); > const encrypted = encrypt.encrypt(JSON.stringify(recipient)); > if (!encrypted) { > throw new Error("Failed to encrypt recipient data"); > } > return encrypted; > } > ``` > [tab] Python > > ```python theme={null} > import requests > from Crypto.PublicKey import RSA > from Crypto.Cipher import PKCS1_OAEP > import json > import base64 > > async def encrypt_recipient_data(recipient): > response = requests.get("https://api.paycrest.io/v2/pubkey") > public_key = response.json()['data'] > > # Import public key > key = RSA.import_key(public_key) > cipher = PKCS1_OAEP.new(key) > > # Encrypt recipient data > recipient_json = json.dumps(recipient) > encrypted = cipher.encrypt(recipient_json.encode('utf-8')) > encrypted_b64 = base64.b64encode(encrypted).decode('utf-8') > > return encrypted_b64 > ``` > [tab] Go > > ```go theme={null} > import ( > "crypto/rand" > "crypto/rsa" > "crypto/x509" > "encoding/base64" > "encoding/json" > "encoding/pem" > "fmt" > "io" > "net/http" > ) > > func encryptRecipientData(recipient map[string]interface{}) (string, error) { > // Get public key > resp, err := http.Get("https://api.paycrest.io/v2/pubkey") > if err != nil { > return "", err > } > defer resp.Body.Close() > > body, err := io.ReadAll(resp.Body) > if err != nil { > return "", err > } > > var result map[string]interface{} > json.Unmarshal(body, &result) > publicKeyPEM := result["data"].(string) > > // Parse public key > block, _ := pem.Decode([]byte(publicKeyPEM)) > if block == nil { > return "", fmt.Errorf("failed to parse public key") > } > > pubKey, err := x509.ParsePKIXPublicKey(block.Bytes) > if err != nil { > return "", err > } > > rsaPubKey, ok := pubKey.(*rsa.PublicKey) > if !ok { > return "", fmt.Errorf("not an RSA public key") > } > > // Encrypt recipient data > recipientJSON, _ := json.Marshal(recipient) > encrypted, err := rsa.EncryptPKCS1v15(rand.Reader, rsaPubKey, recipientJSON) > if err != nil { > return "", err > } > > return base64.StdEncoding.EncodeToString(encrypted), nil > } > ``` > [tab] cURL > > ```bash theme={null} > # Get public key for encryption > curl -X GET "https://api.paycrest.io/v2/pubkey" > > # Note: Encryption is typically done in your application code > # rather than with cURL. Use one of the programming language examples above. > ``` ## On-chain Attribution (ERC-8021) Paycrest tags EVM transactions with an [ERC-8021](https://eip.tools/eip/8021) schema-0 data suffix that carries a sender's **trading name** as a public, human-readable attribution tag. The suffix is execution-inert: the Gateway contract ignores trailing bytes beyond its expected ABI arguments, so it passes through without affecting execution. Cost is roughly 16 gas per non-zero byte. > [!NOTE] > > **The suffix is public attribution only.** It is not read for sender identification. Sender resolution, webhook delivery, and order lookup use `metadata.apiKey` inside the encrypted `messageHash`, which remains the authoritative and only mechanism. ### Who appends the suffix | Path | Who appends it | Code used | | - | - | - | | **Sender API** (aggregator-relayed orders) | The aggregator, automatically | The sender's KYB trading name | | **Direct Gateway integration** (this guide) | You, on your own `createOrder` calldata | Whatever you choose to publish | On the Sender API path the aggregator appends the suffix to the transactions it submits for an order: creation, settlement, and refunds. Senders with no trading name on their KYB profile get no suffix. There is nothing to configure. If you call the Gateway contract directly, nothing is appended for you. The rest of this section covers appending your own. ### Your sender code Pick a printable-ASCII code that identifies you publicly. Paycrest uses the **trading name** from the KYB profile for its own attribution, so matching that keeps your direct transactions consistent with your Sender API ones. ```javascript theme={null} // Your trading name from your KYB profile at app.paycrest.io const senderCode = "AcmeCorp"; ``` Whatever you put in the suffix is **permanently public on-chain**. Use a business identifier you are happy to publish. Never place an API secret, key ID, or any credential in the suffix: your API secret stays for webhooks and REST authentication only. ### Suffix layout Schema 0, parsed **backwards from the end** of the calldata: | Field | Size | Value | | - | - | - | | `codes` | variable | Comma-joined ASCII codes | | `length` | 1 byte | Byte length of `codes` | | `schemaId` | 1 byte | `0x00` | | `marker` | 16 bytes | `0x8021` repeated 8 times | Constraints: `codes` must be non-empty printable ASCII (`0x20` to `0x7e`), individual codes must not contain a comma (the delimiter), and the joined string must be at most **255 bytes**. Violating any of these makes the suffix unparseable by ERC-8021 readers. It has no effect on your order, which is processed from `metadata.apiKey` either way. **Worked example** for trading name `AcmeCorp`: ```text theme={null} 41636d65436f7270 08 00 80218021802180218021802180218021 └── "AcmeCorp" ──┘ len schema marker 0x08 0x00 ``` ### Encoding the suffix > [tab] JavaScript > > ```javascript theme={null} > import { concatHex, stringToHex, toHex } from "viem"; > > const ERC8021_MARKER = `0x${"8021".repeat(8)}`; > > function encodeAttributionSuffix(codes) { > for (const code of codes) { > if (!code || code.includes(",")) { > throw new Error("ERC-8021 codes must be non-empty and comma-free"); > } > } > const joined = codes.join(","); > if (!joined || joined.length > 255) { > throw new Error("ERC-8021 codes must be 1-255 bytes once joined"); > } > for (let i = 0; i < joined.length; i++) { > const c = joined.charCodeAt(i); > if (c < 0x20 || c > 0x7e) { > throw new Error("ERC-8021 codes must be printable ASCII"); > } > } > return concatHex([ > stringToHex(joined), > toHex(joined.length, { size: 1 }), > "0x00", > ERC8021_MARKER, > ]); > } > ``` > [tab] Python > > ```python theme={null} > ERC8021_MARKER = bytes.fromhex("8021" * 8) > > def encode_attribution_suffix(codes): > for code in codes: > if not code or "," in code: > raise ValueError("ERC-8021 codes must be non-empty and comma-free") > joined = ",".join(codes) > if not joined or len(joined) > 255: > raise ValueError("ERC-8021 codes must be 1-255 bytes once joined") > encoded = joined.encode("ascii") > if any(b < 0x20 or b > 0x7e for b in encoded): > raise ValueError("ERC-8021 codes must be printable ASCII") > return encoded + bytes([len(encoded), 0x00]) + ERC8021_MARKER > ``` > [tab] Go > > ```go theme={null} > import ( > "fmt" > "strings" > > "github.com/ethereum/go-ethereum/common" > ) > > var erc8021Marker = common.Hex2Bytes("80218021802180218021802180218021") > > func encodeAttributionSuffix(codes []string) ([]byte, error) { > for _, code := range codes { > if code == "" || strings.Contains(code, ",") { > return nil, fmt.Errorf("ERC-8021 codes must be non-empty and comma-free") > } > } > joined := strings.Join(codes, ",") > if joined == "" || len(joined) > 255 { > return nil, fmt.Errorf("ERC-8021 codes must be 1-255 bytes once joined") > } > for i := 0; i < len(joined); i++ { > if joined[i] < 0x20 || joined[i] > 0x7e { > return nil, fmt.Errorf("ERC-8021 codes must be printable ASCII") > } > } > out := make([]byte, 0, len(joined)+2+len(erc8021Marker)) > out = append(out, joined...) > out = append(out, byte(len(joined)), 0x00) > out = append(out, erc8021Marker...) > return out, nil > } > ``` > [tab] cURL > > ```bash theme={null} > # Suffix encoding is a calldata construction step and has no cURL equivalent. > # Use one of the programming language examples above. > ``` ### Appending to createOrder The suffix must be appended to the calldata **before signing and gas estimation** so it is covered by the signature and paid for in the gas limit. Keep sending `metadata.apiKey`: the suffix is additive, not a replacement. Viem's `writeContract` and `simulate` helpers build calldata internally and give you no place to append raw bytes. To attach a suffix, encode the call yourself with `encodeFunctionData` and send it with `sendTransaction`. > [tab] JavaScript > > ```javascript theme={null} > import { concatHex, encodeFunctionData, parseUnits, zeroAddress } from "viem"; > > async function createOffRampOrderAttributed(amount, recipient, refundAddress) { > const rate = await getExchangeRate(); > const accountName = await verifyAccount(recipient); > const messageHash = await encryptRecipientData({ > ...recipient, > accountName, > // Required: this is how the aggregator identifies you. The suffix does not replace it. > metadata: { apiKey: process.env.PAYCREST_API_KEY }, > }); > await approveUSDT(amount); > > const callData = encodeFunctionData({ > abi: GATEWAY_ABI, > functionName: "createOrder", > args: [ > USDT_ADDRESS, > parseUnits(amount, 6), > rate, > zeroAddress, > 0n, > refundAddress, > messageHash, > ], > }); > > const senderCode = "AcmeCorp"; // Your public attribution code > const data = concatHex([callData, encodeAttributionSuffix([senderCode])]); > > const hash = await walletClient.sendTransaction({ > to: GATEWAY_ADDRESS, > data, > }); > const receipt = await publicClient.waitForTransactionReceipt({ hash }); > return { orderId: extractOrderId(receipt), transactionHash: receipt.transactionHash }; > } > ``` > [tab] Python > > ```python theme={null} > tx = gateway.functions.createOrder( > USDT_ADDRESS, > w3.to_wei(amount, 'ether'), > rate, > '0x0000000000000000000000000000000000000000', > 0, > refund_address, > message_hash > ).build_transaction({ > 'from': user_address, > 'nonce': w3.eth.get_transaction_count(user_address), > }) > > sender_code = "AcmeCorp" # Your public attribution code > tx['data'] = tx['data'] + encode_attribution_suffix([sender_code]).hex() > > # Estimate gas AFTER appending so the suffix is covered. > tx['gas'] = w3.eth.estimate_gas(tx) > tx['gasPrice'] = w3.eth.gas_price > > signed_tx = w3.eth.account.sign_transaction(tx, private_key) > tx_hash = w3.eth.send_raw_transaction(signed_tx.rawTransaction) > ``` > [tab] Go > > ```go theme={null} > callData, err := gatewayABI.Pack( > "createOrder", > tokenAddress, amount, rate, senderFeeRecipient, senderFee, refundAddress, messageHash, > ) > if err != nil { > return err > } > > senderCode := "AcmeCorp" // Your public attribution code > suffix, err := encodeAttributionSuffix([]string{senderCode}) > if err != nil { > return err > } > data := append(callData, suffix...) > > // Estimate gas against the suffixed calldata. > gasLimit, err := client.EstimateGas(ctx, ethereum.CallMsg{ > From: fromAddress, > To: &gatewayAddress, > Data: data, > }) > ``` > [tab] cURL > > ```bash theme={null} > # Smart contract interactions are typically done in your application code > # rather than with cURL. Use one of the programming language examples above. > ``` ### Where the suffix must live ERC-8021 readers parse the **outer transaction calldata** backwards from its final byte, so the suffix has to be the last thing in the top-level input. * **EOA senders**: append to `tx.data`. * **Account abstraction / smart accounts**: append to the **outer** `userOp.callData`, the top-level input that lands on-chain. * **Do not** bury the suffix inside a nested or inner call. A suffix on an inner call is invisible to the parser, because ABI encoding pads inner `bytes` fields and the outer calldata will not end with the marker. Anything that appends bytes after your suffix breaks parsing too, since only the trailing suffix is read. ### Codes and the Base Builder Code The `codes` field is a list, so a transaction can carry more than one code, comma-joined. For direct integrators the default is **your own code alone**, on every EVM network including Base. Use only your own code. Do not copy another app's Base Builder Code into your transactions. ### Relationship to `metadata.apiKey` `metadata.apiKey` is unchanged, **not deprecated**, and remains the single mechanism by which the aggregator identifies the sender behind an order. Keep sending it exactly as before. | Present | Sender resolution | | - | - | | `metadata.apiKey` only | `metadata.apiKey` | | On-chain suffix only | **Order is not attributed to a sender.** The suffix is not read for identification | | Both | `metadata.apiKey` | | Suffix malformed or absent | No effect: resolution uses `metadata.apiKey` | Appending a suffix does **not** replace `metadata.apiKey`. An order created with a suffix but without `metadata.apiKey` will not be linked to your sender profile, and you will not receive webhooks for it. Adding a suffix can never break order indexing. A malformed suffix, an unrecognized code, or no suffix at all leaves order processing untouched. ### Network support On-chain attribution applies to **EVM networks only**. On **Starknet** no suffix is appended or read, and attribution works from `metadata.apiKey` exclusively. **References:** [ERC-8021 specification](https://eip.tools/eip/8021) ## Token Approval > [tab] JavaScript > > ```javascript theme={null} > async function approveUSDT(amount) { > const usdtAmount = parseUnits(amount, 6); > const allowance = await usdt.read.allowance([userAddress, GATEWAY_ADDRESS]); > if (allowance < usdtAmount) { > const { request } = await usdt.simulate.approve({ > args: [GATEWAY_ADDRESS, usdtAmount] > }); > const hash = await walletClient.writeContract(request); > await publicClient.waitForTransactionReceipt({ hash }); > } > } > ``` > [tab] Python > > ```python theme={null} > async def approve_usdt(amount): > usdt_amount = w3.to_wei(amount, 'ether') > allowance = usdt.functions.allowance(user_address, GATEWAY_ADDRESS).call() > > if allowance < usdt_amount: > tx = usdt.functions.approve( > GATEWAY_ADDRESS, > usdt_amount > ).build_transaction({ > 'from': user_address, > 'gas': 100000, > 'gasPrice': w3.eth.gas_price, > 'nonce': w3.eth.get_transaction_count(user_address) > }) > > signed_tx = w3.eth.account.sign_transaction(tx, private_key) > tx_hash = w3.eth.send_raw_transaction(signed_tx.rawTransaction) > w3.eth.wait_for_transaction_receipt(tx_hash) > ``` > [tab] Go > > ```go theme={null} > func approveUSDT(amount string) error { > usdtAmount := new(big.Int) > usdtAmount.SetString(amount, 10) > usdtAmount.Mul(usdtAmount, new(big.Int).Exp(big.NewInt(10), big.NewInt(6), nil)) // USDT has 6 decimals > > // Check current allowance > allowance, err := usdtContract.Allowance(nil, userAddress, gatewayAddress) > if err != nil { > return err > } > > if allowance.Cmp(usdtAmount) < 0 { > // Build approve transaction > data := buildApproveData(gatewayAddress, usdtAmount) > > tx := &types.Transaction{ > To: &usdtAddress, > Value: big.NewInt(0), > Gas: 100000, > GasPrice: big.NewInt(20000000000), // 20 gwei > Data: data, > } > > // Sign and send transaction > signedTx, err := types.SignTx(tx, types.NewEIP155Signer(big.NewInt(8453)), privateKey) > if err != nil { > return err > } > > err = client.SendTransaction(context.Background(), signedTx) > if err != nil { > return err > } > > fmt.Printf("USDT approved with hash: %s\n", signedTx.Hash().Hex()) > } > > return nil > } > ``` > [tab] cURL > > ```bash theme={null} > # Token approval is typically done in your application code > # rather than with cURL. Use one of the programming language examples above. > ``` ## Get Order Information > [tab] JavaScript > > ```javascript theme={null} > async function getOrderInfo(orderId) { > const orderInfo = await gateway.read.getOrderInfo([orderId]); > return { > sender: orderInfo.sender, > token: orderInfo.token, > amount: formatUnits(orderInfo.amount, 6), > isFulfilled: orderInfo.isFulfilled, > isRefunded: orderInfo.isRefunded, > refundAddress: orderInfo.refundAddress > }; > } > ``` > [tab] Python > > ```python theme={null} > def get_order_info(order_id): > order_info = gateway.functions.getOrderInfo(order_id).call() > return { > 'sender': order_info[0], > 'token': order_info[1], > 'amount': w3.from_wei(order_info[2], 'ether'), > 'isFulfilled': order_info[3], > 'isRefunded': order_info[4], > 'refundAddress': order_info[5] > } > ``` > [tab] Go > > ```go theme={null} > func getOrderInfo(orderID string) (map[string]interface{}, error) { > orderInfo, err := gatewayContract.GetOrderInfo(nil, orderID) > if err != nil { > return nil, err > } > > amount := new(big.Float).Quo( > new(big.Float).SetInt(orderInfo.Amount), > new(big.Float).SetInt(new(big.Int).Exp(big.NewInt(10), big.NewInt(6), nil)), > ) > > return map[string]interface{}{ > "sender": orderInfo.Sender.Hex(), > "token": orderInfo.Token.Hex(), > "amount": amount.Text('f', 6), > "isFulfilled": orderInfo.IsFulfilled, > "isRefunded": orderInfo.IsRefunded, > "refundAddress": orderInfo.RefundAddress.Hex(), > }, nil > } > ``` > [tab] cURL > > ```bash theme={null} > # Get order information from blockchain > # This requires a Web3 provider and contract interaction > # Use one of the programming language examples above. > ``` ## Event Listening > [tab] JavaScript > > ```javascript theme={null} > // Listen for events using viem's watchContractEvent > const unwatchOrderCreated = publicClient.watchContractEvent({ > address: GATEWAY_ADDRESS, > abi: GATEWAY_ABI, > eventName: 'OrderCreated', > onLogs: (logs) => { > logs.forEach((log) => { > console.log("Order Created:", { > sender: log.args.sender, > token: log.args.token, > amount: formatUnits(log.args.amount, 6), > orderId: log.args.orderId, > rate: log.args.rate > }); > }); > } > }); > > const unwatchSettleOut = publicClient.watchContractEvent({ > address: GATEWAY_ADDRESS, > abi: GATEWAY_ABI, > eventName: 'SettleOut', > onLogs: (logs) => { > logs.forEach((log) => { > console.log("Order Settled (SettleOut):", { > orderId: log.args.orderId, > liquidityProvider: log.args.liquidityProvider, > settlePercent: log.args.settlePercent > }); > }); > } > }); > > const unwatchOrderRefunded = publicClient.watchContractEvent({ > address: GATEWAY_ADDRESS, > abi: GATEWAY_ABI, > eventName: 'OrderRefunded', > onLogs: (logs) => { > logs.forEach((log) => { > console.log("Order Refunded:", { > fee: formatUnits(log.args.fee, 6), > orderId: log.args.orderId > }); > }); > } > }); > ``` > [tab] Python > > ```python theme={null} > from web3.middleware import geth_poa_middleware > import asyncio > > # Add middleware for Base network > w3.middleware_onion.inject(geth_poa_middleware, layer=0) > > def handle_order_created(event): > print("Order Created:", { > 'sender': event['args']['sender'], > 'token': event['args']['token'], > 'amount': w3.from_wei(event['args']['amount'], 'ether'), > 'orderId': event['args']['orderId'], > 'rate': event['args']['rate'] > }) > > def handle_settle_out(event): > print("Order Settled (SettleOut):", { > 'orderId': event['args']['orderId'], > 'liquidityProvider': event['args']['liquidityProvider'], > 'settlePercent': event['args']['settlePercent'] > }) > > def handle_order_refunded(event): > print("Order Refunded:", { > 'fee': w3.from_wei(event['args']['fee'], 'ether'), > 'orderId': event['args']['orderId'] > }) > > # Create event filters > order_created_filter = gateway.events.OrderCreated.create_filter(fromBlock='latest') > settle_out_filter = gateway.events.SettleOut.create_filter(fromBlock='latest') > order_refunded_filter = gateway.events.OrderRefunded.create_filter(fromBlock='latest') > > # Poll for events > async def poll_events(): > while True: > for event in order_created_filter.get_new_entries(): > handle_order_created(event) > for event in settle_out_filter.get_new_entries(): > handle_settle_out(event) > for event in order_refunded_filter.get_new_entries(): > handle_order_refunded(event) > await asyncio.sleep(1) > ``` > [tab] Go > > ```go theme={null} > import ( > "context" > "fmt" > "log" > "time" > > "github.com/ethereum/go-ethereum" > "github.com/ethereum/go-ethereum/common" > "github.com/ethereum/go-ethereum/core/types" > ) > > func watchEvents(client *ethclient.Client) { > // Create event filters > orderCreatedSig := []byte("OrderCreated(address,address,uint256,bytes32,uint256)") > settleOutSig := []byte("SettleOut(bytes32,bytes32,address,uint64,uint64)") > orderRefundedSig := []byte("OrderRefunded(uint256,bytes32)") > > orderCreatedSigHash := crypto.Keccak256(orderCreatedSig) > settleOutSigHash := crypto.Keccak256(settleOutSig) > orderRefundedSigHash := crypto.Keccak256(orderRefundedSig) > > query := ethereum.FilterQuery{ > Addresses: []common.Address{gatewayAddress}, > Topics: [][]common.Hash{ > {common.BytesToHash(orderCreatedSigHash), common.BytesToHash(settleOutSigHash), common.BytesToHash(orderRefundedSigHash)}, > }, > } > > logs := make(chan types.Log) > sub, err := client.SubscribeFilterLogs(context.Background(), query, logs) > if err != nil { > log.Fatal(err) > } > > for { > select { > case err := <-sub.Err(): > log.Fatal(err) > case vLog := <-logs: > if vLog.Topics[0] == common.BytesToHash(orderCreatedSigHash) { > handleOrderCreated(vLog) > } else if vLog.Topics[0] == common.BytesToHash(settleOutSigHash) { > handleSettleOut(vLog) > } else if vLog.Topics[0] == common.BytesToHash(orderRefundedSigHash) { > handleOrderRefunded(vLog) > } > } > } > } > > func handleOrderCreated(log types.Log) { > fmt.Printf("Order Created: %+v\n", log) > } > > func handleSettleOut(log types.Log) { > fmt.Printf("Order Settled (SettleOut): %+v\n", log) > } > > func handleOrderRefunded(log types.Log) { > fmt.Printf("Order Refunded: %+v\n", log) > } > ``` > [tab] cURL > > ```bash theme={null} > # Event listening is typically done in your application code > # rather than with cURL. Use one of the programming language examples above. > ``` ## Error Handling > [tab] JavaScript > > ```javascript theme={null} > function handleContractError(error) { > if (error.code === 4001) { > throw new Error("User rejected transaction"); > } else if (error.message.includes("insufficient funds")) { > throw new Error("Insufficient USDT balance or ETH for gas"); > } else if (error.message.includes("execution reverted")) { > throw new Error("Transaction reverted - check parameters"); > } else { > throw new Error(`Contract error: ${error.message}`); > } > } > > async function retryTransaction(txFunction, maxRetries = 3) { > for (let attempt = 1; attempt <= maxRetries; attempt++) { > try { > return await txFunction(); > } catch (error) { > if (attempt === maxRetries) throw error; > await new Promise(resolve => setTimeout(resolve, 1000 * attempt)); > } > } > } > ``` > [tab] Python > > ```python theme={null} > def handle_contract_error(error): > if "user rejected" in str(error).lower(): > raise Exception("User rejected transaction") > elif "insufficient funds" in str(error).lower(): > raise Exception("Insufficient USDT balance or ETH for gas") > elif "execution reverted" in str(error).lower(): > raise Exception("Transaction reverted - check parameters") > else: > raise Exception(f"Contract error: {str(error)}") > > async def retry_transaction(tx_function, max_retries=3): > for attempt in range(1, max_retries + 1): > try: > return await tx_function() > except Exception as error: > if attempt == max_retries: > raise error > await asyncio.sleep(1000 * attempt) > ``` > [tab] Go > > ```go theme={null} > import ( > "fmt" > "strings" > "time" > ) > > func handleContractError(err error) error { > errStr := strings.ToLower(err.Error()) > if strings.Contains(errStr, "user rejected") { > return fmt.Errorf("user rejected transaction") > } else if strings.Contains(errStr, "insufficient funds") { > return fmt.Errorf("insufficient USDT balance or ETH for gas") > } else if strings.Contains(errStr, "execution reverted") { > return fmt.Errorf("transaction reverted - check parameters") > } else { > return fmt.Errorf("contract error: %v", err) > } > } > > func retryTransaction(txFunction func() error, maxRetries int) error { > for attempt := 1; attempt <= maxRetries; attempt++ { > err := txFunction() > if err == nil { > return nil > } > > if attempt == maxRetries { > return err > } > > time.Sleep(time.Duration(1000*attempt) * time.Millisecond) > } > return fmt.Errorf("max retries exceeded") > } > ``` > [tab] cURL > > ```bash theme={null} > # Error handling is typically done in your application code > # rather than with cURL. Use one of the programming language examples above. > ``` ## Complete Example > [tab] JavaScript > > ```javascript theme={null} > import { parseUnits, formatUnits, zeroAddress } from "viem"; > > class PaycrestGateway { > constructor(publicClient, walletClient, gatewayAddress, usdtAddress) { > this.provider = publicClient; > this.walletClient = walletClient; > this.gatewayAddress = gatewayAddress; > this.usdtAddress = usdtAddress; > this.gateway = null; > this.usdt = null; > } > > async initialize() { > this.gateway = getContract({ > address: this.gatewayAddress, > abi: GATEWAY_ABI, > publicClient: this.provider, > walletClient: this.walletClient > }); > this.usdt = getContract({ > address: this.usdtAddress, > abi: USDT_ABI, > publicClient: this.provider, > walletClient: this.walletClient > }); > this.setupEventListeners(); > } > > setupEventListeners() { > this.provider.watchContractEvent({ > address: this.gatewayAddress, > abi: GATEWAY_ABI, > eventName: 'OrderCreated', > onLogs: this.handleOrderCreated.bind(this) > }); > this.provider.watchContractEvent({ > address: this.gatewayAddress, > abi: GATEWAY_ABI, > eventName: 'SettleOut', > onLogs: this.handleSettleOut.bind(this) > }); > this.provider.watchContractEvent({ > address: this.gatewayAddress, > abi: GATEWAY_ABI, > eventName: 'OrderRefunded', > onLogs: this.handleOrderRefunded.bind(this) > }); > } > > async createOrder(amount, recipient, refundAddress) { > try { > const rate = await this.getExchangeRate(); > const accountName = await this.verifyAccount(recipient); > const messageHash = await this.encryptRecipientData({ ...recipient, accountName }); > await this.approveUSDT(amount); > const { request } = await this.gateway.simulate.createOrder({ > args: [ > this.usdtAddress, > parseUnits(amount, 6), > rate, > zeroAddress, > 0n, > refundAddress, > messageHash > ] > }); > const hash = await this.walletClient.writeContract(request); > const receipt = await this.provider.waitForTransactionReceipt({ hash }); > return { orderId: this.extractOrderId(receipt), hash: receipt.hash }; > } catch (error) { > handleContractError(error); > } > } > // ... other methods (getExchangeRate, verifyAccount, etc.) > } > > // Usage > const paycrest = new PaycrestGateway( > publicClient, > walletClient, > "0xE8bc3B607CfE68F47000E3d200310D49041148Fc", > "0xdac17f958d2ee523a2206206994597c13d831ec7" > ); > > await paycrest.initialize(); > > const order = await paycrest.createOrder( > "100", // USDT amount > { > institution: "GTBINGLA", > accountIdentifier: "123456789" > }, > "0x123..." // Refund address > ); > ``` > [tab] Python > > ```python theme={null} > from web3 import Web3 > from eth_account import Account > import asyncio > > class PaycrestGateway: > def __init__(self, w3, gateway_address, usdt_address): > self.w3 = w3 > self.gateway_address = gateway_address > self.usdt_address = usdt_address > self.gateway = None > self.usdt = None > > async def initialize(self): > self.gateway = self.w3.eth.contract( > address=self.gateway_address, > abi=GATEWAY_ABI > ) > self.usdt = self.w3.eth.contract( > address=self.usdt_address, > abi=USDT_ABI > ) > self.setup_event_listeners() > > def setup_event_listeners(self): > # Event listeners would be set up here > pass > > async def create_order(self, amount, recipient, refund_address): > try: > rate = await self.get_exchange_rate() > account_name = await self.verify_account(recipient) > message_hash = await self.encrypt_recipient_data({**recipient, 'accountName': account_name}) > await self.approve_usdt(amount) > > tx = self.gateway.functions.createOrder( > self.usdt_address, > self.w3.to_wei(amount, 'ether'), > rate, > '0x0000000000000000000000000000000000000000', > 0, > refund_address, > message_hash > ).build_transaction({ > 'from': user_address, > 'gas': 200000, > 'gasPrice': self.w3.eth.gas_price, > 'nonce': self.w3.eth.get_transaction_count(user_address) > }) > > signed_tx = self.w3.eth.account.sign_transaction(tx, private_key) > tx_hash = self.w3.eth.send_raw_transaction(signed_tx.rawTransaction) > receipt = self.w3.eth.wait_for_transaction_receipt(tx_hash) > > return {'orderId': self.extract_order_id(receipt), 'hash': receipt['transactionHash'].hex()} > except Exception as error: > handle_contract_error(error) > > # ... other methods (get_exchange_rate, verify_account, etc.) > > # Usage > w3 = Web3(Web3.HTTPProvider('https://mainnet.base.org')) > paycrest = PaycrestGateway( > w3, > "0xE8bc3B607CfE68F47000E3d200310D49041148Fc", > "0xdac17f958d2ee523a2206206994597c13d831ec7" > ) > > await paycrest.initialize() > > order = await paycrest.create_order( > "100", # USDT amount > { > "institution": "GTBINGLA", > "accountIdentifier": "123456789" > }, > "0x123..." # Refund address > ) > ``` > [tab] Go > > ```go theme={null} > package main > > import ( > "context" > "fmt" > "log" > "math/big" > > "github.com/ethereum/go-ethereum/common" > "github.com/ethereum/go-ethereum/ethclient" > ) > > type PaycrestGateway struct { > client *ethclient.Client > gatewayAddress common.Address > usdtAddress common.Address > gateway *GatewayContract > usdt *USDTContract > } > > func NewPaycrestGateway(client *ethclient.Client, gatewayAddr, usdtAddr string) *PaycrestGateway { > return &PaycrestGateway{ > client: client, > gatewayAddress: common.HexToAddress(gatewayAddr), > usdtAddress: common.HexToAddress(usdtAddr), > } > } > > func (pg *PaycrestGateway) Initialize() error { > // Initialize contracts with ABI bindings > gateway, err := NewGatewayContract(pg.gatewayAddress, pg.client) > if err != nil { > return err > } > pg.gateway = gateway > > usdt, err := NewUSDTContract(pg.usdtAddress, pg.client) > if err != nil { > return err > } > pg.usdt = usdt > > pg.setupEventListeners() > return nil > } > > func (pg *PaycrestGateway) setupEventListeners() { > // Event listeners would be set up here > } > > func (pg *PaycrestGateway) CreateOrder(amount string, recipient map[string]interface{}, refundAddress string) error { > rate, err := pg.getExchangeRate() > if err != nil { > return err > } > > accountName, err := pg.verifyAccount(recipient) > if err != nil { > return err > } > > messageHash, err := pg.encryptRecipientData(recipient, accountName) > if err != nil { > return err > } > > err = pg.approveUSDT(amount) > if err != nil { > return err > } > > // Build transaction data > data := pg.buildCreateOrderData(amount, rate, refundAddress, messageHash) > > // Create transaction > tx := &types.Transaction{ > To: &pg.gatewayAddress, > Value: big.NewInt(0), > Gas: 200000, > GasPrice: big.NewInt(20000000000), // 20 gwei > Data: data, > } > > // Sign and send transaction > signedTx, err := types.SignTx(tx, types.NewEIP155Signer(big.NewInt(8453)), privateKey) > if err != nil { > return err > } > > err = pg.client.SendTransaction(context.Background(), signedTx) > if err != nil { > return err > } > > fmt.Printf("Order created with hash: %s\n", signedTx.Hash().Hex()) > return nil > } > > // Usage > func main() { > client, err := ethclient.Dial("https://mainnet.base.org") > if err != nil { > log.Fatal(err) > } > > paycrest := NewPaycrestGateway( > client, > "0xE8bc3B607CfE68F47000E3d200310D49041148Fc", > "0xdac17f958d2ee523a2206206994597c13d831ec7", > ) > > err = paycrest.Initialize() > if err != nil { > log.Fatal(err) > } > > recipient := map[string]interface{}{ > "institution": "GTBINGLA", > "accountIdentifier": "123456789", > } > > err = paycrest.CreateOrder("100", recipient, "0x123...") > if err != nil { > log.Fatal(err) > } > } > ``` > [tab] cURL > > ```bash theme={null} > # Smart contract interactions are typically done in your application code > # rather than with cURL. Use one of the programming language examples above. > ``` ## Supported Networks * **Ethereum**: USDT, USDC, cNGN * **Base**: USDT, USDC, cNGN (primary recommended network) * **Arbitrum One**: USDT, USDC * **Polygon**: USDT, USDC, cNGN * **BNB Smart Chain**: USDT, USDC, cNGN * **Celo**: USDT, USDC, cNGN Starknet, Tron and Solana are supported through the [Sender API](/implementation-guides/sender-api-integration) only, not through direct contract calls. Tron and Solana orders use the v2 API. See [Gateway Contract Addresses](/resources/gateway-contract-addresses) for deployment addresses per network. > [!NOTE] > > Paycrest supports very low minimum orders (\$0.50) and uses cost-effective EVM L2s. Start with small amounts to test your integration before scaling up. Failed transactions still consume gas. Validate all parameters before submitting transactions. Choose this method for full on-chain control and direct smart contract interaction. # Introduction Source: https://docs.paycrest.io/introduction Decentralized payment routing infrastructure for stablecoin-fiat conversion, connecting apps and users to a global network of fiat liquidity providers. # Welcome to Paycrest Paycrest is a **decentralized payment routing protocol** for stablecoin-fiat payments in emerging markets. It routes bidirectional conversion orders between stablecoins and local currencies through a distributed network of liquidity providers, with on-chain escrow that settles orders automatically without Paycrest ever holding user funds. Paycrest is built for **wallets, fintechs, exchanges, DeFi protocols, and platforms** that need to move stablecoins into and out of local fiat accounts in high-friction markets. If you're building a product that touches cross-border payments, remittances, payroll, or stablecoin on-ramps and off-ramps, Paycrest is the routing layer. ## The Problem Cross-border payments, especially in Africa and other emerging markets, remain globally expensive, slow, and fragmented. Sending $200 to Sub-Saharan Africa costs an average of 7.9% in fees, according to the World Bank's [Migration and Development Brief 40](https://www.worldbank.org/en/news/press-release/2024/06/26/remittances-slowed-in-2023-expected-to-grow-faster-in-2024). For the $54 billion in remittances that flowed into the region in 2023, a large share of that value is lost to intermediaries. Stablecoins have emerged as the most viable alternative: they move in minutes, cost fractions of a cent on modern L2 chains, and are already seeing massive organic adoption. But there is a critical gap: the **last mile**. Converting between stablecoins and local currency remains fragmented and increasingly contested by platform-specific networks tied to individual stablecoin issuers, each building a walled garden around their own token. **There is no neutral, open, protocol-level routing layer for stablecoin-fiat conversion. Paycrest is building that layer: issuer-agnostic by design, with no preference for one stablecoin or issuer over another.** ## How It Works **1. Create Order** A sender (or an app on their behalf) initiates a payment order through the Gateway Smart Contract, which locks stablecoins in escrow. No funds are held by Paycrest. **2. Route** The aggregator indexes the order and routes it to the most suitable liquidity provider based on rate, availability, and corridor. **3. Fulfill** The provider's automated provision node disburses fiat to the recipient's bank account or mobile wallet via a local PSP. **4. Complete** Once payout is verified, the escrowed stablecoins are released to the provider on-chain. If the order can't be fulfilled, the sender is automatically refunded. > [!NOTE] > > The on-ramp flow runs the other way: a user deposits fiat with a provider, and the protocol delivers stablecoins to their wallet. ## What is Paycrest? Paycrest is not a payment app. It is infrastructure: an open payment routing protocol that any application can integrate to offer stablecoin on-ramps and off-ramps to its users. It is also not a P2P consumer product, not a card-issuing solution, and not suitable for anonymous flows. All senders and providers are KYB-verified. The protocol handles the full stack: * **Order routing**: matching senders with the right provider for each corridor and rate * **Encrypted message passing**: recipient bank/wallet details transmitted securely * **On-chain escrow**: neither party needs to trust the other; the contract enforces completion * **Compliance coordination**: providers own local regulatory obligations, senders own theirs The key properties: > [card] Non-Custodial > > Paycrest never holds user funds. Escrow is on-chain; provider fiat is provider-controlled. > [card] Open & Composable > > Any smart contract can trigger settlement. Any app can integrate the Sender API. > [card] Provider-Sovereign > > Liquidity providers run their own provision nodes, set their own rates, and connect their own PSPs. > [card] Simple Pricing > > Senders pay the rate quoted live by the Paycrest Sender API, plus the transaction fee and any sender fee they set. ## Key Participants > [card] Sender > > KYB-verified businesses (wallets, fintechs, DeFi protocols) that initiate payment orders via the Sender API or Gateway contract. > [card] Recipient > > The beneficiary who receives local fiat or stablecoins without interacting with the protocol directly. > [card] Provider > > KYB-verified participants that supply fiat and stablecoin liquidity in both directions, running automated provision nodes. > [card] Aggregator > > The Paycrest Aggregator matches orders with suitable providers, coordinates fulfillment and manages settlement. ## Get Started > [card] [For Senders](/quickstart) > > Learn how to create payment orders with the Paycrest Sender API. The Sender API v2 supports both off-ramp (stablecoin → fiat) and on-ramp (fiat → stablecoin). > [card] [Become a provider](/implementation-guides/provider-setup-guide) > > Complete KYB, set up a provision node and serve on-ramp and off-ramp order flow from integrated senders. ## Supported Corridors Paycrest is live across 4 active corridors with real provider liquidity. New corridors launch only when committed providers are onboarded and tested. > [card] African Markets > >
    >
  • NGN 🇳🇬: Nigerian Naira
  • >
  • KES 🇰🇪: Kenyan Shilling
  • >
  • UGX 🇺🇬: Ugandan Shilling
  • >
  • TZS 🇹🇿: Tanzanian Shilling
  • >
## Supported Stablecoins > [card] Stablecoins > >
    >
  • **USDT**: Tether USDt (multi-chain)
  • >
  • **USDC**: USD Coin (multi-chain)
  • >
  • **cNGN**: Compliant Naira (multi-chain)
  • >
> [card] Networks > >
    >
  • Ethereum, Base, Arbitrum One
  • >
  • Polygon, BNB Smart Chain
  • >
  • Celo, Starknet, Tron, Solana
  • >
> [!NOTE] > > For the complete token list with contract addresses, see **[Supported Stablecoins](/resources/supported-stablecoins)** or use the **[GET /tokens](/api-reference/general/list-supported-tokens)** endpoint. ## Security & Compliance > [card] KYB-gated participation > > Every sender and provider business is verified before going live. > [card] Smart Contract Security > > Non-custodial on-chain escrow. Funds are never held by Paycrest. > [card] Compliance at the Edges > > Providers own their local regulatory obligations; senders own theirs, including customer KYC. Paycrest verifies every business before it goes live and screens orders for sanctions risk. > [card] Built-in Sender Monetization > > Senders can add their own fee on top of the quoted rate, settled on-chain in the same transaction as the order. *** ## Where We're Headed Paycrest is focused on one thing: making stablecoin-fiat routing in emerging markets reliable enough to be trusted infrastructure. We want Paycrest to become the default routing path for stablecoin-fiat payments because it is the most reliable, not because anyone is locked in. Every new provider makes the corridors it serves more robust. *** ## Decentralization Path Today the **Paycrest Aggregator**, operated by Paycrest, is the neutral middle between senders and independent verified providers. It is non-custodial and works in both directions, on-ramp and off-ramp. The protocol is designed so that multiple independent aggregators can run on it in the future. Starting with one is deliberate: the network proves itself in production before control is distributed. The protocol is designed to evolve in three phases. > [accordion] Phase 1: Federated Foundation (Current) > > **How it works today**: The Paycrest Aggregator routes each order to a provider, confirms the payout and coordinates settlement. Every sender and provider is KYB-verified before going live. > > **What this means for you**: You integrate once and work with one accountable team. Funds sit in on-chain escrow, never with Paycrest. > [accordion] Phase 2: Attested Settlement (Future) > > **What changes**: Independent parties confirm each payout, so verification no longer rests with a single aggregator. > > **What this means for you**: Stronger guarantees for senders, because no single party decides whether a payout happened. > [accordion] Phase 3: Permissionless Protocol (Future) > > **What changes**: Multiple independent aggregators run on the protocol, and any provider that meets the compliance requirements can join without approval from Paycrest. > > **What this means for you**: The routing layer stays neutral. It has no stake in which stablecoin you use, which provider fills your order, or who runs the aggregator. > > **What stays the same in every phase**: non-custodial on-chain escrow, the Gateway contract's guarantees, the Paycrest Sender API contract, and KYB verification at the compliance layer. ## Talk to us Integrating as a sender, or want to supply liquidity as a provider? Email [support@paycrest.io](mailto:support@paycrest.io). # Quickstart Source: https://docs.paycrest.io/quickstart Create your first Paycrest payment order in minutes. This guide walks through creating a payment order using the Sender API, the recommended path for all new integrations. You'll have a working off-ramp in under 10 minutes. You do **not** need to call the public rates API first—`POST /v2/sender/orders` resolves an acceptable rate unless you pass a locked **`rate`** on create (see the [Sender API integration guide](/implementation-guides/sender-api-integration)). ## Prerequisites * A **Paycrest Sender account** (sign up at [app.paycrest.io](https://app.paycrest.io)) * **KYB verification** completed (typically 1–3 business days) * Your **API Key** from the dashboard *** ## Optional: Prefetch a quote for the UI If you want to **show** an exchange rate in checkout before create, call the public **`GET /v2/rates/{network}/{from}/{amount}/{to}`** endpoint (no API key). For when to pass **`rate`** on create and full examples, see [Optional: prefetch quotes and account names](/implementation-guides/sender-api-integration#optional-prefetch-quotes-and-account-names). Endpoint reference: [Get Token Rate (v2)](/api-reference/general/get-token-rate). *** ## Step 1: Create a Payment Order Use `POST /v2/sender/orders`. Set `source.type` and `destination.type` to choose the direction. > [tab] Off-ramp — stablecoin → fiat > > ```bash theme={null} > curl -X POST "https://api.paycrest.io/v2/sender/orders" \ > -H "API-Key: YOUR_API_KEY" \ > -H "Content-Type: application/json" \ > -d '{ > "amount": "100", > "source": { > "type": "crypto", > "currency": "USDT", > "network": "base", > "refundAddress": "0xYourWalletAddress" > }, > "destination": { > "type": "fiat", > "currency": "NGN", > "recipient": { > "institution": "GTBINGLA", > "accountIdentifier": "1234567890", > "accountName": "John Doe", > "memo": "Payment" > } > }, > "reference": "my-order-001" > }' > ``` > [tab] On-ramp — fiat → stablecoin > > ```bash theme={null} > curl -X POST "https://api.paycrest.io/v2/sender/orders" \ > -H "API-Key: YOUR_API_KEY" \ > -H "Content-Type: application/json" \ > -d '{ > "amount": "50000", > "amountIn": "fiat", > "source": { > "type": "fiat", > "currency": "NGN", > "refundAccount": { > "institution": "GTBINGLA", > "accountIdentifier": "1234567890", > "accountName": "John Doe" > }, > "kyc": { > "entityType": "person", > "personDetails": { > "fullName": "John Doe", > "birthDate": "1990-04-12", > "idDocument": { "type": "nationalID", "number": "12345678901", "issuerCountry": "NG" }, > "taxId": { "type": "BVN", "value": "22212345678" } > } > } > }, > "destination": { > "type": "crypto", > "currency": "USDT", > "recipient": { > "address": "0xRecipientWalletAddress", > "network": "base" > } > }, > "reference": "my-order-002" > }' > ``` > [tab] JavaScript > > ```javascript theme={null} > const res = await fetch("https://api.paycrest.io/v2/sender/orders", { > method: "POST", > headers: { > "API-Key": "YOUR_API_KEY", > "Content-Type": "application/json" > }, > body: JSON.stringify({ > amount: "100", > source: { > type: "crypto", > currency: "USDT", > network: "base", > refundAddress: "0xYourWalletAddress" > }, > destination: { > type: "fiat", > currency: "NGN", > recipient: { > institution: "GTBINGLA", > accountIdentifier: "1234567890", > accountName: "John Doe", > memo: "Payment" > } > }, > reference: "my-order-001" > }) > }); > const { data: order } = await res.json(); > console.log(order.id, order.providerAccount); > ``` > [tab] Python > > ```python theme={null} > import requests > > res = requests.post( > "https://api.paycrest.io/v2/sender/orders", > headers={"API-Key": "YOUR_API_KEY", "Content-Type": "application/json"}, > json={ > "amount": "100", > "source": { > "type": "crypto", > "currency": "USDT", > "network": "base", > "refundAddress": "0xYourWalletAddress" > }, > "destination": { > "type": "fiat", > "currency": "NGN", > "recipient": { > "institution": "GTBINGLA", > "accountIdentifier": "1234567890", > "accountName": "John Doe", > "memo": "Payment" > } > }, > "reference": "my-order-001" > } > ) > order = res.json()["data"] > print(order["id"], order["providerAccount"]) > ``` > [tab] Go > > ```go theme={null} > package main > > import ( > "bytes" > "encoding/json" > "fmt" > "io" > "net/http" > ) > > func main() { > payload := map[string]interface{}{ > "amount": "100", > "source": map[string]interface{}{ > "type": "crypto", > "currency": "USDT", > "network": "base", > "refundAddress": "0xYourWalletAddress", > }, > "destination": map[string]interface{}{ > "type": "fiat", > "currency": "NGN", > "recipient": map[string]interface{}{ > "institution": "GTBINGLA", > "accountIdentifier": "1234567890", > "accountName": "John Doe", > "memo": "Payment", > }, > }, > "reference": "my-order-001", > } > body, _ := json.Marshal(payload) > req, _ := http.NewRequest("POST", "https://api.paycrest.io/v2/sender/orders", bytes.NewBuffer(body)) > req.Header.Set("API-Key", "YOUR_API_KEY") > req.Header.Set("Content-Type", "application/json") > resp, _ := http.DefaultClient.Do(req) > defer resp.Body.Close() > out, _ := io.ReadAll(resp.Body) > fmt.Println(string(out)) > } > ``` *** ## Step 2: Complete the Payment The response includes a `providerAccount` that tells you (or your user) where to send funds. > [card] Off-ramp > > Send tokens to `providerAccount.receiveAddress` before `validUntil`. > The total to send is `amount + senderFee + transactionFee` (all returned in the response). > [card] On-ramp > > Show `providerAccount` details to the user. > They transfer exactly `amountToTransfer` in `currency` to `accountIdentifier` before `validUntil`. *** ## Step 3: Track Order Status Poll `GET /v2/sender/orders/:id` or listen for webhooks configured in your dashboard. > [tab] cURL > > ```bash theme={null} > curl "https://api.paycrest.io/v2/sender/orders/ORDER_ID" \ > -H "API-Key: YOUR_API_KEY" > ``` > [tab] JavaScript > > ```javascript theme={null} > const { data: order } = await fetch( > `https://api.paycrest.io/v2/sender/orders/${orderId}`, > { headers: { "API-Key": "YOUR_API_KEY" } } > ).then(r => r.json()); > > console.log(order.status); // e.g. "settled" > ``` > [tab] Python > > ```python theme={null} > res = requests.get( > f"https://api.paycrest.io/v2/sender/orders/{order_id}", > headers={"API-Key": "YOUR_API_KEY"} > ) > print(res.json()["data"]["status"]) > ``` > [tab] Go > > ```go theme={null} > req, _ := http.NewRequest("GET", "https://api.paycrest.io/v2/sender/orders/"+orderID, nil) > req.Header.Set("API-Key", "YOUR_API_KEY") > resp, _ := http.DefaultClient.Do(req) > defer resp.Body.Close() > body, _ := io.ReadAll(resp.Body) > fmt.Println(string(body)) > ``` > [card] Order Statuses > >
    >
  • **initiated** — order created, awaiting deposit
  • >
  • **deposited** — deposit confirmed (off-ramp)
  • >
  • **pending** — assigned to provider
  • >
  • **fulfilling** — fiat/crypto disbursement in progress
  • >
  • **validated** — payout confirmed by provider
  • >
  • **settling**: on-chain release in progress
  • >
  • **settled** — order complete
  • >
  • **expired** — no deposit received before deadline
  • >
  • **refunding** — refund in progress
  • >
  • **refunded** — deposit returned to sender
  • >
> [card] Timing > >
    >
  • **Median completion (NGN)**: under 30 seconds
  • >
  • **expired**: receive address or virtual account never funded
  • >
  • **refunded**: deposit received but order couldn't complete
  • >
  • **Minimum order**: \$0.50 on most chains; on-ramps to Tron have a higher minimum, stated in the error if an order is below it
  • >
*** ## Next Steps > [card] [Full Integration Guide](/implementation-guides/sender-api-integration) > > Webhooks, signature verification, token transfers, v1 legacy API, and more > [card] [API Reference](/api-reference/sender/initiate-payment-order-v2) > > Interactive endpoint docs with full request/response schemas > [card] [Supported Stablecoins](/resources/supported-stablecoins) > > Tokens, networks, contract addresses, and decimals > [card] [Supported Currencies](/resources/supported-currencies) > > Active fiat corridors and delivery channels # Changelog Source: https://docs.paycrest.io/resources/changelog A record of notable API, protocol, and documentation changes. This page tracks significant changes to the Paycrest API and protocol. For full commit history, see the [aggregator repository](https://github.com/paycrest/aggregator). *** ## Q4 2026 ### Webhook delivery reference corrected (October 2026) **Docs fix:** the [webhook delivery endpoints](/api-reference/sender/list-webhook-deliveries) now document the field names the API has always returned. The API itself has not changed. * Delivery records: `webhookUrl` (was documented as `destinationUrl`), `statusCode` (was `httpStatusCode`) and `payload` (was `requestPayload`). `signature` was never returned and has been removed. * Retry results: `statusCode` (was `httpStatusCode`), plus `attemptNumber` and `message`. `errorMessage` was never returned and has been removed. A queued retry (`202`) returns the same shape with `status: "pending"`. ### Verify-account status codes: 400 vs 503 (October 2026) **Updated:** [`POST /v2/verify-account`](/api-reference/general/verify-account) and [`POST /v1/verify-account`](/api-reference/general/verify-account-v1) now separate a definitive "not verified" from a temporary failure. Previously every verification failure returned **503**. Successful responses are unchanged. See [Status codes](/api-reference/general/verify-account#status-codes). * **Behavior change:** an unsupported or unknown institution, or an account every eligible provider rejects, returns **400**. Treat it as final and ask the user to check the institution and account number. * **Behavior change:** provider outages, timeouts and inconclusive results return **503** "Failed to verify account". Retry with backoff. For NGN, a response with no real account name also returns 503. * Branch on the status code, not the message text. If you already treat any non-200 as "not verified", no change is needed. ### Duplicate reasons on provider decline and cancel (October 2026) **New:** `POST /provider/orders/{id}/decline` accepts an optional JSON body with `timestamp` and `reason`. Without `reason`, a decline still reassigns the order to another provider. * **New:** on decline and on `POST /provider/orders/{id}/cancel`, the reason `duplicate_gateway_order:` or `duplicate_reference:` tells the aggregator the provider will not pay out because another order already holds it. The order is cancelled and not reassigned. * This applies only when the aggregator can confirm the claim: the holding order shares this order's on-chain order and token, or the on-chain order is already fulfilled or refunded. Otherwise the request is handled as an ordinary decline or cancel. * Providers running the Paycrest provider node get this automatically. ### Payment reference on v2 off-ramp orders (October 2026) **New:** v2 orders ([`GET /v2/sender/orders/:id`](/api-reference/sender/get-payment-order-by-id-v2) and [`GET /v2/sender/orders`](/api-reference/sender/list-payment-orders-v2)) and v2 webhooks carry `paymentReference`, the receipt from the bank or mobile-money network that paid the recipient (for example an M-Pesa receipt code). See [Monitor completion](/implementation-guides/sender-api-integration#monitor-completion). * Off-ramp only. It is `null` until the payout is confirmed, and on orders paid before this change. Coverage depends on the provider, so treat `null` as normal. * Not on v1 orders or v1 webhooks. ### Lisk support removed (October 2026) **Updated:** Lisk is no longer supported as of October 20, 2026, ahead of the Lisk Chain shutdown on October 31, 2026. Lisk has been removed from supported networks, stablecoins and gateway contract addresses. * **Behavior change:** orders on `lisk` are no longer accepted. Use another supported network, such as Base or Celo. ### Third-party on-ramp deposits are returned automatically (October 2026) **Updated:** an on-ramp deposit from an account that is not the customer's own is now usually returned in full to the account it came from, instead of waiting for a compliance review. You receive `payment_order.refunded`, with no `payment_order.compliance_hold`. Paycrest may hold a deposit for review instead. See [Compliance holds](/concepts/transaction-lifecycle#compliance-holds). * **New:** v2 orders and v2 webhooks can carry `statusDetail: "under_review"` while a deposit is held, and `refundReason` (`payer_mismatch` or `payer_unverified`) when it was returned to the account it came from. ### On-ramp deposits must come from the customer (October 2026) **Updated:** an on-ramp deposit must be paid from the customer's own account. Paycrest checks the payer the provider reports against `source.kyc`; see [On-ramp customer KYC](/implementation-guides/sender-api-integration#on-ramp-customer-kyc). * **Behavior change:** a deposit from anyone else is held for compliance review, and you receive `payment_order.compliance_hold`. * **Behavior change:** a held order no longer expires. It ends in `payment_order.settled`, or in `payment_order.refunded` with the deposit returned to the account it came from. See [Compliance holds](/concepts/transaction-lifecycle#compliance-holds). ### Customer KYC required on on-ramp orders (October 2026) **Updated:** every on-ramp order created with [`POST /v2/sender/orders`](/api-reference/sender/initiate-payment-order-v2) must now identify the customer paying in, in `source.kyc`. See [On-ramp customer KYC](/implementation-guides/sender-api-integration#on-ramp-customer-kyc) for the full field list. * **Behavior change:** an on-ramp order without `source.kyc`, or with a required field missing or malformed, returns **400** with `"field": "Source"` and a message listing every problem. * A person needs `fullName`, `birthDate` (18 or over) and `idDocument`. For NGN, also the BVN in `taxId` or the NIN as the `idDocument`. For KES, `contact.phoneE164` must be a Kenyan mobile number. * An organization needs `legalName`, `registrationNumber`, `registrationCountry` and at least one director meeting the person rules. * Where the bank resolves the refund account holder's name (NGN), it must match the customer in `source.kyc`. ### Tron orders through the v2 API only (October 2026) **Updated:** Tron (USDT) orders are now created through [`POST /v2/sender/orders`](/api-reference/sender/initiate-payment-order-v2) only, the same as Solana. Off-ramp and on-ramp both work as before on v2. * **Behavior change:** v1 order creation on `tron` returns **400** "This network is available only via POST /v2/sender/orders". The v1 error for Solana now reads the same. * Off-ramp: send **exactly** `providerAccount.amountToTransfer`. A smaller deposit is not credited; it is returned to your `refundAddress`, less the Tron network's transfer cost. * On-ramp to Tron has a higher minimum order than other networks because of Tron's transfer cost. An order below it is refused, and the error states the minimum. * Tron rates are unchanged: [`GET /v2/rates`](/api-reference/general/get-token-rate) and v1 rates with `network=tron`. *** ## Q3 2026 ### Sender fees on Solana (September 2026) **Updated:** Solana orders now pay sender fees to a Solana address, configured like any other network. Set a fee address, fee percent and max fee cap on your **Solana** token in the dashboard (**Settings › Trading**), or pass a Solana `senderFeeAddress` on [`POST /v2/sender/orders`](/api-reference/sender/initiate-payment-order-v2). * Fees from Solana orders are paid out to your Solana fee address in batches, once they add up to at least 1 USDC or USDT. The payout's network cost comes out of the batch. * **Behavior change:** if you had set an EVM `senderFeeAddress` for Solana orders, replace it with a Solana address. * Your Solana fee address needs a token account for the stablecoin (it has one once it has ever held the token). *** ### Transaction fee payer (September 2026) **New:** Senders choose who pays each order's transaction fee (`transactionFee`, the order's network cost). Set it per token in the dashboard under **Settings › Trading › Transaction fee paid by**, or per order with the new `transactionFeePayer` field on [`POST /v2/sender/orders`](/api-reference/sender/initiate-payment-order-v2): * `sender` (default): the transaction fee comes out of your sender fee first. You earn `max(0, fee − transactionFee)` and your customer sends `amount + max(fee, transactionFee)`. With a fee smaller than the transaction fee, your customer tops up only the difference. * `customer`: your customer pays the transaction fee on top of your full sender fee, as before. **Behavior change:** existing tokens default to `sender`. If you charge a sender fee, it now covers the transaction fee unless you choose `customer`. With no sender fee, nothing changes. **API:** * `senderFee` in responses and webhooks is the fee you earn on the order. `amountToTransfer = amount + senderFee + transactionFee` still holds. * `PATCH /settings/sender` accepts `tokens[].transactionFeePayer`, and `GET /settings/sender` returns it. * The transaction fee now reimburses the gas the aggregator spends creating and settling the order. A refund after an order is created on-chain returns `amount + senderFee`. See [Who pays the transaction fee](/implementation-guides/sender-api-integration#who-pays-the-transaction-fee). *** ### Solana now supported (September 2026) **Solana** is supported for off-ramp and on-ramp through the v2 Sender API. * Network identifier: `solana` * Tokens: USDT (6 decimals; mint `Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB`) and USDC (6 decimals; mint `EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v`) * Addresses: Base58 public keys (32–44 characters) * Orders: create with [`POST /v2/sender/orders`](/api-reference/sender/initiate-payment-order-v2) — `source.network: "solana"` for off-ramp, `destination.recipient.network: "solana"` for on-ramp. v1 endpoints return **400** "Solana is available only via POST /v2/sender/orders" * Off-ramp: send exactly `providerAccount.amountToTransfer` of `providerAccount.currency` to `providerAccount.receiveAddress`, and include `providerAccount.memo` when it is present * On-ramp: the recipient wallet must already have a token account for the stablecoin's mint * For Solana orders, provide an EVM address for `senderFeeAddress` (no longer the case: see "Sender fees on Solana" above) **API:** `providerAccount.amountToTransfer` (`amount + senderFee + transactionFee`) and `providerAccount.currency` are now returned on every off-ramp order, on every network; `providerAccount.memo` is returned only when the deposit must include it. **503** "Network temporarily unavailable" means the network or a quote for the amount is briefly unavailable — nothing was created; retry shortly. See [Supported Stablecoins](/resources/supported-stablecoins) and [Troubleshooting](/resources/troubleshooting). *** ### On-chain sender attribution via ERC-8021 (August 2026) **New:** The aggregator now stamps the EVM transactions it submits with an [ERC-8021](https://eip.tools/eip/8021) schema-0 data suffix carrying the sender's **trading name** from their KYB profile. It is applied to the transactions the aggregator submits for an order: creation, settlement, and refunds. Orders placed through the Sender API carry public on-chain attribution with no integration work. * **Sender code**: the sender's KYB trading name (for example, `AcmeCorp`). Senders with no trading name on file get no suffix. * **Suffix layout** (parsed backwards from the end of calldata): comma-joined ASCII `codes` · 1-byte length · 1-byte schema `0x00` · 16-byte marker `0x8021...8021`. * **EVM only**: Starknet and Tron transactions carry no suffix. **Important:** the suffix is a public, human-readable attribution tag. It is **not** used for sender identification. Sender resolution, webhook delivery, and order lookup continue to use `metadata.apiKey` inside the encrypted `messageHash`, which is unchanged and not deprecated. Direct Gateway integrators can append their own suffix to `createOrder` calldata for public attribution. See [On-chain Attribution (ERC-8021)](/implementation-guides/smart-contract-interaction#on-chain-attribution-erc-8021). *** ### Ranked provider queues (August 2026) Each order now carries a ranked queue of up to **3 providers**, resolved once at order creation and tried in order. **Updated:** `GET /v2/rates/{network}/{from}/{amount}/{to}` — each side's **`providerIds`** now carries up to **3 provider ids ranked best first**, in the order assignment would try them. Previously always 0 or 1 entry. `providerIds[0]` is still the provider whose rate is in `rate`, so clients reading `[0]` are unaffected. | Param | Form | Behavior | | - | - | - | | `limit` | single | Max ranked ids per side. Integer **1–3**, default **3**. Anything else returns **400** | Pinned (`?provider_id=`) quotes still return exactly one id. **New:** order creation accepts an explicit **`providerIds`** queue: `destination.providerIds` on `POST /v2/sender/orders`, `recipient.providerIds` on `POST /v1/sender/orders`, and `providerIds` inside the encrypted recipient for on-chain orders. Pass the ids from a rate quote to route the order to the providers your user was quoted. | Rule | Behavior | | - | - | | Mutually exclusive with `providerId` | Sending both returns **400** | | Size | Off-ramp up to **3** entries; on-ramp **1** (it selects its provider at creation rather than walking a queue) | | No duplicates, no empty strings | **400** | | Format | Exactly 8 alphabetic characters per id | | Eligibility | Multi-entry queues must name active providers with a live standard offer for the corridor; a provider restricted to specific senders is allowed when you are on its list. | | One-entry queues | Exactly a pin — `providerIds: [X]` routes like `providerId: X` for every provider you can pin | | Response | Accepted on create, never echoed back. Orders and webhooks return the singular assigned `providerId` | The singular **`providerId`** is retained for backward compatibility on both flows; `providerIds` covers every case it does, so new integrations need only the array form. **Behavior change:** the recipient encryption size check now budgets for a **full 3-provider queue on every order** — including orders that send no `providerIds` — because a queue may be resolved onto the order and rides in the message hash at gateway submit. The effective budget for `accountIdentifier` + `accountName` + `memo` + `metadata` is **\~49 bytes smaller** within the 500-byte cap (**\~41** when pinning a `providerId`). Requests that previously passed can now return **400** `"Recipient data too large for encryption"`. Trim `memo` and `metadata` if you were near the limit. **Behavior change:** pinning an **on-ramp** order to a provider restricted to other senders now returns **400** `provider X cannot serve this order`. Off-ramp has always enforced this; on-ramp previously accepted such a pin and routed the order. It applies to **`providerId`** as well as `providerIds`, so on-ramp integrations that pin providers should confirm they are authorized for them. **Exhausting a queue is not an immediate refund.** After the last entry, Paycrest may still route the order elsewhere before refunding it. See [Get Token Rate](/api-reference/general/get-token-rate), [Pin a provider queue](/implementation-guides/sender-api-integration#pin-a-provider-queue), and [Smart Contract Interaction](/implementation-guides/smart-contract-interaction#routing-fields). *** ### Optional `senderFeeAddress` on V2 create order (July 2026) **Updated:** `POST /v2/sender/orders` accepts an optional top-level **`senderFeeAddress`**. | Effective sender fee | `senderFeeAddress` | | - | - | | Greater than zero (from `senderFee`, `senderFeePercent`, or a profile-configured fee) | **Required** — pass it on the request, or configure a fee address on the sender profile for that token | | Zero | **Not required** | `senderFee` and `senderFeePercent` remain mutually exclusive. Applies to both off-ramp and on-ramp. V1 create order is unchanged (still requires fee and refund addresses on the sender profile). See [Sender API Integration — Sender Fees](/implementation-guides/sender-api-integration#sender-fees) and [Initiate Order](/api-reference/sender/initiate-payment-order-v2). *** ### Markets orderbook query filters (July 2026) **Updated:** `GET /v2/markets` accepts optional query filters to narrow the returned orderbook: | Param | Form | Behavior | | - | - | - | | `side` | single | `buy` or `sell`; omit for both. Invalid values return **400** | | `fiat` | comma-separated | e.g. `NGN,KES` | | `token` | comma-separated | e.g. `USDC,USDT` | | `network` | comma-separated | e.g. `base,polygon` | Filters apply only to **`data.book`**. **`data.aggregates` remain network-wide** (unfiltered), matching dashboard behavior (global KPIs, filtered table). See [Get Markets](/api-reference/general/get-markets). *** ## Q2 2026 ### Starknet and Tron network support (July 2026) **Starknet** (chain ID `23448594291968334`) and **Tron** (chain ID `728126428`) are fully supported by the aggregator. **Starknet** * Network identifier: `starknet` * Tokens: USDT and USDC (6 decimals) * Addresses: felt hex (`0x` + 63–64 hex characters) **Tron** * Network identifier: `tron` * Tokens: USDT (6 decimals; contract `TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t`) * Addresses: Base58Check starting with `T` **Docs cleanup:** Asset Chain is no longer listed as a supported network. Prefer the [Sender API](/implementation-guides/sender-api-integration) for Starknet and Tron orders; see [Gateway Contract Addresses](/resources/gateway-contract-addresses) and [Supported Stablecoins](/resources/supported-stablecoins). *** ### Public markets orderbook & provider rate position (June 2026) **New:** `GET /v2/markets` — unauthenticated public endpoint returning the live protocol orderbook and network-wide aggregate statistics. No API key required; CORS open; \~10 s cache; per-IP rate limited. * **`data.book`** — array of provider quote rows (one per provider × side × token × fiat × network), including `rate`, `rateType`, `min`, `max`, `balance`, `balanceUsd`, `settled`, and `successPercent`. * **`data.aggregates`** — network-wide stats: settled volume/txns (24h/7d/30d/all-time), success rate, median delivery seconds, active providers/senders, live liquidity USD, and corridor/token/network counts. **Updated:** `GET /v1/provider/rates/{token}/{fiat}` and `GET /v2/provider/rates/{token}/{fiat}` — each side (`buy`, `sell`) now carries an optional **`position`** object so providers can benchmark their effective rate against the best public peer in the same corridor: | Field | Description | | - | - | | `bestPublicRate` | Best rate among enabled non-testnet public peers (highest for sell; lowest for buy) | | `yourEffectiveRate` | Your effective rate for this corridor | | `deltaVsBest` | `yourEffectiveRate − bestPublicRate` — positive means higher; for sell positive is more competitive, for buy negative is more competitive | `position` is omitted when no qualifying public offers exist or you have no effective rate configured (backward compatible). See [Get Markets](/api-reference/general/get-markets) and [Get Market Rate](/api-reference/provider/get-market-rate). *** ### Webhook delivery logs & retry API (June 2026) Senders can now audit and replay webhook deliveries instead of re-triggering the order flow when an endpoint is briefly down. **New endpoints:** * `GET /v2/sender/webhooks` — list deliveries (newest first); filters: `status`, `event`, `event_id`, `order_id`, `from`, `to`. * `GET /v2/sender/webhooks/:id` — full delivery record including request payload and response body. * `POST /v2/sender/webhooks/:id/retry` — replay a delivery. `?sync=true` replays immediately and returns the HTTP result inline; otherwise a new delivery is queued and the API returns `202` with its ID. **Behavior change:** non-2xx responses now count as failed deliveries and are retried (previously only transport errors were). Retries use exponential backoff and expire after a cumulative 24-hour window, after which the sender is emailed once. See [Webhook delivery logs & retry](/implementation-guides/sender-api-integration#webhook-delivery-logs--retry) and [List Webhook Deliveries](/api-reference/sender/list-webhook-deliveries). *** ### Verify-account mobile money normalization (June 2026) **`POST /v1/verify-account`** and **`POST /v2/verify-account`** now normalize **mobile\_money** `accountIdentifier` values before provider verification (country dial code, strip `+` and leading `0`). Supported fiat dial codes: KES `254`, UGX `256`, TZS `255`, GHS `233`. * Optional request field **`metadata`** (KES Till/Paybill) skips normalization when appropriate. * Response **`data`** may still be `"OK"` when the account is valid but no display name is returned (e.g. some M-Pesa corridors). See [Verify Account](/api-reference/general/verify-account). *** ### KES Till and Paybill off-ramp (May 2026) **Off-ramp** to Kenya mobile rails now supports **Till** (buy goods) and **Paybill** in addition to phone M-Pesa. * On create, set **`destination.recipient.metadata.channel`** to **`Mobile`**, **`Till`**, or **`Paybill`** (use **`Mobile`** for phone M-Pesa; omit channel only when the identifier is a standard mobile number). * **Paybill** may require **`metadata.businessNumber`**. * Optional **`destination.kyc`** on off-ramp is **recipient-only** (no sender/provider KYB on create). * **v2 GET / webhooks:** **`destination.recipient.metadata`** echoes create-time recipient metadata; **`destination.kyc`** when stored. * Till/Paybill identifiers are not normalized as phone numbers on create or verify-account. See **[Sender API Integration — KES mobile money](/implementation-guides/sender-api-integration#kes-mobile-money-m-pesa-till-paybill)** and **[Supported Currencies](/resources/supported-currencies)**. *** ### Optional `direction` on v2 order lists and stats (April 2026) **`GET /v2/sender/orders`** and **`GET /v2/provider/orders`** accept an optional query parameter **`direction`**, either **`onramp`** or **`offramp`**, to return only orders for that flow. Omit it to list both directions (default). On list endpoints, values other than `onramp` or `offramp` are ignored (no direction filter is applied). **`GET /v2/sender/stats`** and **`GET /v2/provider/stats`** accept the same optional **`direction`** parameter; omitted means totals and aggregates include both directions. Invalid **`direction`** values return **400 Bad Request**. **HMAC (ApiKeyAuth) on GET:** request signatures are built from all query parameters—include **`direction`** in the signed payload when you send it (e.g. alongside `timestamp` and `currency` on provider stats). *** ## Q1 2026 ### Public v2 rates path and buy/sell quotes (April 2026) **`GET /v2/rates/{network}/{from}/{amount}/{to}`** is the supported public rates URL. The network is a **path** segment (not the `network` query used on v1). **`from` and `to`** may be a **token + fiat** pair (either order; **not** two tokens) or **two fiat codes**. Fiat–fiat quotes **bridge through USDC** on the same network; **`amount`** is in **`from`** fiat; **`sell`** / **`buy`** use asymmetric inverse-corridor semantics (not simple reciprocals). Path order does **not** imply trade direction for token/fiat—omit **`side`** to get **both** sides when available. Responses use structured **`buy`** and **`sell`** objects (`rate`, `providerIds`, `orderType`, `refundTimeoutMinutes`) instead of a single scalar `data` value. Optional query parameters: * **`side`**: `buy` or `sell` to return only one side. * **`provider_id`**: exactly **8 alphabetic** characters to pin the quote to one provider. **Legacy:** **`GET /v1/rates/{token}/{amount}/{fiat}`** with optional `network` query is unchanged and still returns a single rate in `data`. **Provider market rate:** **`GET /v1/provider/rates/{token}/{fiat}`** and **`GET /v2/provider/rates/{token}/{fiat}`** now return **`buy`** and **`sell`** objects, each with `marketRate`, `minimumRate`, and `maximumRate` (replacing the previous flat `marketBuyRate` / `marketSellRate` fields). See [Get Token Rate](/api-reference/general/get-token-rate) and [Get Market Rate](/api-reference/provider/get-market-rate). *** ### FX on-ramp settlement amounts (April 2026) No REST schema changes. FX on-ramp recipients now receive at least the quoted net stablecoin amount. On-chain principal amounts may differ slightly from orders created before this change. *** ## Q1 2026 ### v2 API — On-ramp & Off-ramp (March 2026) The v2 API introduces a unified endpoint for both off-ramp and on-ramp flows, replacing the v1 off-ramp-only schema. **New endpoints:** * `POST /v2/sender/orders` — create off-ramp or on-ramp orders * `GET /v2/sender/orders/:id` — get a single v2 order * `GET /v2/sender/orders` — list v2 orders * `GET /v2/provider/orders` — provider view of v2 orders * `GET /v2/provider/orders/:id` — provider view of a single v2 order **What changed:** | Feature | v1 | v2 | | - | - | - | | Direction support | Off-ramp only | Off-ramp + on-ramp | | Request schema | Flat: `token`, `network`, `recipient` | Polymorphic: `source`, `destination` with `type` discriminator | | Amount direction | Always crypto | `amountIn: "fiat"` or `"crypto"` | | Sender fee | Fixed amount via dashboard | Optional; `senderFee` / `senderFeePercent` on request. If fee > 0, `senderFeeAddress` (or profile fee address) is required | | Numeric field types | `decimal.Decimal` | `string` | | Webhook version | `webhookVersion: "1"` | `webhookVersion: "2"` | The v1 API remains fully supported. No breaking changes to existing v1 integrations. **Migration notes:** If you're building a new integration, use v2. Key differences to be aware of: 1. The `source` and `destination` objects use a `type` discriminator (`"crypto"` or `"fiat"`) to distinguish off-ramp from on-ramp. 2. For off-ramp, the `source.refundAddress` field replaces the v1 `returnAddress` field. 3. All numeric values (amount, rate, fees) are returned as `string` in v2 — parse them as needed. 4. The `providerAccount` in the create response is a virtual account (`V2FiatProviderAccount`) for on-ramp orders, replacing the `receiveAddress` string from v1. See the [Sender API Integration Guide](/implementation-guides/sender-api-integration) for full v2 off-ramp and on-ramp documentation. *** ### On-ramp in production (March 2026) Fiat-to-stablecoin on-ramp is live across active corridors. Available via the v2 API. *** ## 2025 ### cNGN support added cNGN (Compliant Naira) is now supported as a stablecoin across Ethereum, Base, Polygon, and BNB Smart Chain. This is the first local-currency stablecoin supported by the protocol. ### Protocol launch (February 2025) Initial mainnet deployment across Base, Polygon, BNB Smart Chain, and Arbitrum One. NGN corridor live with bank transfer and mobile delivery. *** ## API Versioning Policy The Paycrest API uses URL-based versioning (`/v1/`, `/v2/`). Within a major version: * Additive changes (new optional fields, new endpoints) are non-breaking and may be introduced at any time * Breaking changes (removed fields, changed field types, changed semantics) require a new major version v1 will continue to be supported until an explicit deprecation notice is issued with at least 90 days' advance notice. # Code Standards Source: https://docs.paycrest.io/resources/code-standards Understanding Paycrest's currency and institution code formats Paycrest follows international standards for currency and institution codes to ensure consistency and compatibility across different systems and regions. ## Currency Codes Paycrest uses **ISO 4217** standard currency codes, which are the internationally recognized three-letter codes for currencies. ### Examples: * **NGN** - Nigerian Naira * **KES** - Kenyan Shilling * **UGX** - Ugandan Shilling * **TZS** - Tanzanian Shilling > [!NOTE] > > All currency codes used in Paycrest API calls must follow the ISO 4217 standard. These codes are case-sensitive and should be provided in uppercase. ## Institution Codes Paycrest uses a hybrid approach for institution codes to accommodate both international banks and local financial institutions. ### SWIFT Codes (Banks) For a bank that has a SWIFT/BIC, the Paycrest code **is** the bank's 8-character SWIFT/BIC code. #### Examples: * **GTBINGLA** - Guaranty Trust Bank (Nigeria) * **FBNINGLA** - First Bank of Nigeria * **CITINGLA** - Citibank Nigeria * **SCBLNGLA** - Standard Chartered Bank Nigeria * **KCBLKENX** - Kenya Commercial Bank * **EQBLKENA** - Equity Bank Kenya Some codes reflect a bank's **former name** but are still its real BIC — e.g. `ZEIBNGLA` (Zenith, from "Zenith International Bank"), `NAMENGLA` (Sterling, from the former NAL Bank), and `KDHLNGLA` (FBNQuest, from Kakawa Discount House). A few historical codes differ from the bank's current SWIFT — use the Paycrest code, not the SWIFT you may find elsewhere: * **`SBICNGLA`** — Stanbic IBTC Bank (SWIFT `SBICNGLX`) * **`PROVNGLA`** — Providus Bank (SWIFT `UMPLNGLA`) ### Custom Codes (Local Institutions) For mobile payment providers, local banks without SWIFT codes, and other financial institutions, Paycrest uses custom 8-character codes built as: **4 letters from the institution's name** (where possible) + the **2-letter ISO country code** + **`PC`** (PayCrest). #### Examples: * **KUDANGPC** - Kuda (Nigeria): `KUDA` + `NG` + `PC` * **OPAYNGPC** - OPay (Nigeria): `OPAY` + `NG` + `PC` * **MONINGPC** - Moniepoint (Nigeria): `MONI` + `NG` + `PC` * **SAFAKEPC** - Safaricom M-Pesa (Kenya): `SAFA` + `KE` + `PC` * **AIRTKEPC** - Airtel Money (Kenya): `AIRT` + `KE` + `PC` For KES **Till** and **Paybill** off-ramps, keep **`SAFAKEPC`** (or the same mobile institution you use for M-Pesa) and set **`destination.recipient.metadata.channel`** to **`Till`** or **`Paybill`** (and **`businessNumber`** for Paybill). See **[Sender API Integration: KES mobile money](/implementation-guides/sender-api-integration#kes-mobile-money-m-pesa-till-paybill)**. ## Code Format Rules ### Currency Codes * **Format**: 3 uppercase letters * **Standard**: ISO 4217 * **Case**: Always uppercase * **Examples**: `NGN`, `KES`, `UGX` ### Institution Codes * **Format**: 8 characters * **Banks with a SWIFT/BIC**: the bank's 8-character SWIFT/BIC code * **Local Institutions (no SWIFT)**: 4 letters from the name + 2-letter ISO country code + `PC` * **Case**: Always uppercase * **Examples**: `GTBINGLA`, `KUDANGPC` ## API Usage When making API calls, always use the correct code format. For **new integrations**, use **[POST /v2/sender/orders](/api-reference/sender/initiate-payment-order-v2)** (off-ramp: stablecoin → fiat). Fiat currency is **`destination.currency`**; the bank or mobile-money institution is **`destination.recipient.institution`**. Crypto asset and chain are on **`source`** (`source.currency`, `source.network`). ```javascript theme={null} // v2 offramp — correct institution and currency codes (see OpenAPI for full required fields) const order = { amount: "100", source: { type: "crypto", currency: "USDT", network: "base", refundAddress: "0xYourRefundAddress", }, destination: { type: "fiat", currency: "NGN", // ISO 4217 — correct fiat currency code recipient: { institution: "GTBINGLA", // Correct institution code accountIdentifier: "1234567890", accountName: "John Doe", memo: "Payment", }, }, }; ``` Legacy **v1** **[POST /sender/orders](/api-reference/sender/initiate-payment-order)** (`https://api.paycrest.io/v1/...`) uses a flatter body (`amount`, `token`, `network`, `recipient`) with the **same** uppercase institution and currency strings; prefer v2 for new work. ## Finding Institution Codes Use the **[GET /institutions/](/api-reference/general/list-supported-institutions)** endpoint to get the complete list of supported institutions for any currency: ```bash theme={null} curl -X GET "https://api.paycrest.io/v2/institutions/NGN" \ -H "API-Key: your-api-key" ``` This endpoint returns all supported institutions with their codes, names, and types (bank or mobile\_money). > [!NOTE] > > Institution codes are case-sensitive and must be provided exactly as returned by the API. Always use the official codes from the API rather than guessing or using external SWIFT code databases. # Gateway Contract Addresses Source: https://docs.paycrest.io/resources/gateway-contract-addresses Deployment addresses for Paycrest Gateway contracts across all supported networks Paycrest Gateway contracts are deployed across multiple EVM-compatible networks. The table below shows the deployments the Paycrest Aggregator supports. ## Deployment Addresses | Network | Chain ID | Gateway Address | Status | | - | - | - | - | | **Ethereum** | 1 | `0x8d2C0D398832b814e3814802FF2dC8b8eF4381e5` | ✅ Live | | **Base** | 8453 | `0x30F6A8457F8E42371E204a9c103f2Bd42341dD0F` | ✅ Live | | **Polygon** | 137 | `0xfB411Cc6385Af50A562aFCb441864E9d541CDA67` | ✅ Live | | **BNB Smart Chain** | 56 | `0x1FA0EE7F9410F6fa49B7AD5Da72Cf01647090028` | ✅ Live | | **Arbitrum One** | 42161 | `0xE8bc3B607CfE68F47000E3d200310D49041148Fc` | ✅ Live | | **Celo** | 42220 | `0xF418217E3f81092eF44b81C5C8336e6A6fDB0E4b` | ✅ Live | ## Network Status Legend * **✅ Live**: Fully supported by the Paycrest Aggregator ## Contract Verification All Gateway contracts are verified on their respective network block explorers: * **Ethereum**: [Etherscan](https://etherscan.io/address/0x8d2C0D398832b814e3814802FF2dC8b8eF4381e5) * **Base**: [Basescan](https://basescan.org/address/0x30F6A8457F8E42371E204a9c103f2Bd42341dD0F) * **Polygon**: [Polygonscan](https://polygonscan.com/address/0xfB411Cc6385Af50A562aFCb441864E9d541CDA67) * **BNB Smart Chain**: [Bscscan](https://bscscan.com/address/0x1FA0EE7F9410F6fa49B7AD5Da72Cf01647090028) * **Arbitrum One**: [Arbiscan](https://arbiscan.io/address/0xE8bc3B607CfE68F47000E3d200310D49041148Fc) * **Celo**: [Celo Explorer](https://explorer.celo.org/address/0xF418217E3f81092eF44b81C5C8336e6A6fDB0E4b) ## Integration ### EVM networks To integrate with the Gateway contract directly on an EVM network, use the address for your target chain: ```javascript theme={null} import { getContract } from "viem"; // Example: Base network const GATEWAY_ADDRESS = "0x30F6A8457F8E42371E204a9c103f2Bd42341dD0F"; const gateway = getContract({ address: GATEWAY_ADDRESS, abi: GATEWAY_ABI, publicClient, walletClient }); ``` ### Starknet, Tron and Solana Orders on these networks go through the [Sender API](/implementation-guides/sender-api-integration) (`network: "starknet"`, `"tron"` or `"solana"`), not direct Gateway calls. The [Smart Contract Interaction](/implementation-guides/smart-contract-interaction) guide covers EVM Gateway calls. For detailed integration guides, see: * **[Sender API Integration](/implementation-guides/sender-api-integration)**: API-based integration (required for Starknet, Tron and Solana) * **[Smart Contract Interaction](/implementation-guides/smart-contract-interaction)**: Direct EVM contract integration > [!NOTE] > > Contract addresses vary by network. Always use the correct address for your target network and verify it on the block explorer before use. Check our [contracts repository](https://github.com/paycrest/contracts) for the latest deployment information. # Supported Currencies Source: https://docs.paycrest.io/resources/supported-currencies Complete list of supported fiat currencies, countries, and delivery channels Paycrest supports fiat currencies across multiple countries and regions, with delivery channels including bank transfers and mobile payments. New corridors launch only when committed liquidity providers are onboarded and tested. ## Active Corridors | Country | Flag | Currency | Code | Channels | | - | - | - | - | - | | **Nigeria** | 🇳🇬 | Nigerian Naira | NGN | Bank, Mobile | | **Kenya** | 🇰🇪 | Kenyan Shilling | KES | Bank, Mobile | | **Uganda** | 🇺🇬 | Ugandan Shilling | UGX | Bank, Mobile | | **Tanzania** | 🇹🇿 | Tanzanian Shilling | TZS | Bank, Mobile | ## Delivery Channel Matrix | Currency | Bank Transfer | Mobile / Wallet | | - | - | - | | **NGN** | ✅ | ✅ | | **KES** | ✅ | ✅ | | **UGX** | ✅ | ✅ | | **TZS** | ✅ | ✅ | ## Integration Examples ### Bank Transfer (Nigeria) ```javascript theme={null} const order = { amount: "100", source: { type: "crypto", currency: "USDT", network: "base", refundAddress: "0xYourAddress" }, destination: { type: "fiat", currency: "NGN", recipient: { institution: "GTBINGLA", accountIdentifier: "1234567890", accountName: "John Doe", memo: "Salary payment" } } }; ``` ### Mobile Money (Kenya) Phone M-Pesa, **Till** (buy goods), and **Paybill** all use a KES mobile institution (typically **`SAFAKEPC`**). Set **`destination.recipient.metadata.channel`** to **`Mobile`**, **`Till`**, or **`Paybill`**. Full rules and KYC notes are in **[Sender API Integration — KES mobile money](/implementation-guides/sender-api-integration#kes-mobile-money-m-pesa-till-paybill)**. **Phone M-Pesa** ```javascript theme={null} const order = { amount: "50", source: { type: "crypto", currency: "USDC", network: "base", refundAddress: "0xYourAddress" }, destination: { type: "fiat", currency: "KES", recipient: { institution: "SAFAKEPC", // Local (07…) or international (254…) MSISDN; API normalizes on create and verify-account accountIdentifier: "0712345678", accountName: "Jane Smith", memo: "Mobile payment", metadata: { channel: "Mobile" } } } }; ``` **Till** ```javascript theme={null} recipient: { institution: "SAFAKEPC", accountIdentifier: "123456", accountName: "Shop Name", memo: "Payment", metadata: { channel: "Till" } } ``` **Paybill** ```javascript theme={null} recipient: { institution: "SAFAKEPC", accountIdentifier: "INV-001", accountName: "Customer", memo: "Bill pay", metadata: { channel: "Paybill", businessNumber: "400200" } } ``` ## Rate Information Exchange rates are dynamic and depend on: * **Market conditions**: Real-time forex rates * **Provider competition**: Multiple providers competing per corridor * **Transaction volume**: Planning high volumes? Talk to us at [support@paycrest.io](mailto:support@paycrest.io) Use the [GET /rates](/api-reference/general/get-token-rate) endpoint to fetch the current achievable rate before creating an order. > [!NOTE] > > All supported currencies are actively monitored for compliance and regulatory requirements. Delivery times and fees may vary by provider and region. ## API Endpoints * **[GET /currencies](/api-reference/general/list-supported-currencies)** — Get all supported fiat currencies with current market rates * **[GET /institutions/](/api-reference/general/list-supported-institutions)** — Get supported banks and mobile payment providers for a specific currency > [!NOTE] > > Currency codes follow the [ISO 4217](https://en.wikipedia.org/wiki/ISO_4217) standard. Institution codes use SWIFT codes (first 7 characters) for international banks, or custom codes ending with `PC` for local institutions. See **[Code Standards](/resources/code-standards)** for details. # Supported Stablecoins Source: https://docs.paycrest.io/resources/supported-stablecoins Complete list of supported stablecoins and their network availability Paycrest supports three stablecoins across nine blockchain networks (six EVM chains plus Starknet, Tron and Solana). Use the [GET /tokens](/api-reference/general/list-supported-tokens) endpoint for the live list including contract addresses, decimals, and network availability. Solana orders are created through the v2 API only ([`POST /v2/sender/orders`](/api-reference/sender/initiate-payment-order-v2)). ## Stablecoin Overview | Stablecoin | Networks | Base Currency | Notes | | - | - | - | - | | **USDT** | Ethereum, Base, Arbitrum One, Polygon, BNB Smart Chain, Celo, Starknet, Tron, Solana | USD | Most widely supported | | **USDC** | Ethereum, Base, Arbitrum One, Polygon, BNB Smart Chain, Celo, Starknet, Solana | USD | Regulated, high security standards | | **cNGN** | Ethereum, Base, Polygon, BNB Smart Chain, Celo | NGN | Stablecoin pegged to the Nigerian Naira | ## Support Matrix | Stablecoin | Ethereum | Base | Arbitrum One | Polygon | BNB Smart Chain | Celo | Starknet | Tron | Solana | | - | - | - | - | - | - | - | - | - | - | | **USDT** | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | | **USDC** | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ❌ | ✅ | | **cNGN** | ✅ | ✅ | ❌ | ✅ | ✅ | ✅ | ❌ | ❌ | ❌ | ## Contract Addresses > [!WARNING] > > BNB Smart Chain USDT and USDC use **18 decimals** — not 6. All other chains use 6 decimals for USDT and USDC. Always fetch the `decimals` value from the [GET /tokens](/api-reference/general/list-supported-tokens) endpoint rather than hardcoding it. ### USDT | Network | Contract Address | Decimals | | - | - | - | | Ethereum | `0xdAC17F958D2ee523a2206206994597C13D831ec7` | 6 | | Base | `0xfde4C96c8593536E31F229EA8f37b2ADa2699bb2` | 6 | | Arbitrum One | `0xFd086bC7CD5C481DCC9C85ebE478A1C0b69FCbb9` | 6 | | Polygon | `0xc2132D05D31c914a87C6611C10748AEb04B58e8F` | 6 | | BNB Smart Chain | `0x55d398326f99059fF775485246999027B3197955` | **18** | | Celo | `0x48065fbBE25f71C9282ddf5e1cD6D6A887483D5e` | 6 | | Starknet | `0x068F5c6a61780768455de69077E07e89787839bf8166dEcfBf92B645209c0fB8` | 6 | | Tron | `TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t` | 6 | | Solana | `Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB` | 6 | ### USDC | Network | Contract Address | Decimals | | - | - | - | | Ethereum | `0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48` | 6 | | Base | `0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913` | 6 | | Arbitrum One | `0xaf88d065e77c8cC2239327C5EDb3A432268e5831` | 6 | | Polygon | `0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359` | 6 | | BNB Smart Chain | `0x8AC76a51cc950d9822D68b83fE1Ad97B32Cd580d` | **18** | | Celo | `0xcebA9300f2b948710d2653dD7B07f33A8B32118C` | 6 | | Starknet | `0x033068F6539f8e6e6b131e6B2B814e6c34A5224bC66947c47DaB9dFeE93b35fb` | 6 | | Solana | `EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v` | 6 | ### cNGN | Network | Contract Address | Decimals | | - | - | - | | Ethereum | `0x17CDB2a01e7a34CbB3DD4b83260B05d0274C8dab` | 6 | | Base | `0x46C85152bFe9f96829aA94755D9f915F9B10EF5F` | 6 | | Polygon | `0x52828daa48C1a9A06F37500882b42daf0bE04C3B` | 6 | | BNB Smart Chain | `0xa8AEA66B361a8d53e8865c62D142167Af28Af058` | 6 | | Celo | `0xF6829D7393dAe24509eb1E52eE8e572e2E271a4f` | 6 | ## Network Configuration When creating orders, specify the stablecoin and network using the `token` and `network` parameters (v1) or via the `source`/`destination` objects (v2). Use **`starknet`** for Starknet and **`tron`** for Tron. Tron and Solana orders are created through the v2 API only. > [tab] v2 API (recommended) > > ```javascript theme={null} > // Offramp: USDT on Base → NGN bank account > const order = { > amount: "100", > source: { > type: "crypto", > currency: "USDT", > network: "base", > refundAddress: "0xYourAddress" > }, > destination: { > type: "fiat", > currency: "NGN", > recipient: { > institution: "GTBINGLA", > accountIdentifier: "1234567890", > accountName: "John Doe", > memo: "Payment" > } > } > }; > ``` > [tab] v2 Starknet off-ramp > > ```javascript theme={null} > // Offramp: USDT on Starknet → NGN bank account > // refundAddress must be a Starknet address (0x + 63–64 hex chars) > const order = { > amount: "100", > source: { > type: "crypto", > currency: "USDT", > network: "starknet", > refundAddress: "0x046a056257607e1126a73b789bc6b56216e260261d4b54dd0809df46638bcbad" > }, > destination: { > type: "fiat", > currency: "NGN", > recipient: { > institution: "GTBINGLA", > accountIdentifier: "1234567890", > accountName: "John Doe", > memo: "Payment" > } > } > }; > ``` > [tab] v2 Tron off-ramp > > ```javascript theme={null} > // Offramp: USDT on Tron → NGN bank account > // refundAddress must be a Tron Base58 address (starts with T) > const order = { > amount: "100", > source: { > type: "crypto", > currency: "USDT", > network: "tron", > refundAddress: "TYourTronWalletAddress............." > }, > destination: { > type: "fiat", > currency: "NGN", > recipient: { > institution: "GTBINGLA", > accountIdentifier: "1234567890", > accountName: "John Doe", > memo: "Payment" > } > } > }; > ``` > [tab] v1 API (legacy) > > ```javascript theme={null} > // Offramp only: USDC on Base → NGN bank account > const order = { > amount: "100", > token: "USDC", > network: "base", > rate: "1500.50", > recipient: { > institution: "GTBINGLA", > accountIdentifier: "1234567890", > accountName: "John Doe", > currency: "NGN", > memo: "Payment" > } > }; > ``` > [!NOTE] > > **Starknet addresses** are felt-sized hex strings (`0x` + 63–64 hex digits). Do not use EVM checksum formatting. The zero address is rejected. > > **Tron addresses** are Base58Check and start with `T`. Do not pass EVM `0x` addresses when `network` is `tron`. > > **Solana addresses** are Base58 public keys, 32–44 characters. On off-ramp, `refundAddress` must be a Solana address when `network` is `solana`. On on-ramp, `destination.recipient.address` must be a Solana address when `destination.recipient.network` is `solana`, and that wallet must already have a token account for the stablecoin's mint. ## API Endpoints * **[GET /tokens](/api-reference/general/list-supported-tokens)** — Live list of all supported stablecoins with contract addresses, decimals, and network identifiers * **[GET /rates](/api-reference/general/get-token-rate)** — Get the current exchange rate for a token/amount/fiat pair > [!NOTE] > > Always retrieve the `decimals` value from the API before constructing token transfer transactions. Do not hardcode decimal values, as BNB Smart Chain USDT and USDC use 18 decimals while all other supported networks use 6. # Troubleshooting Source: https://docs.paycrest.io/resources/troubleshooting Common issues and solutions for Paycrest integration This guide helps you resolve common issues when integrating with the Paycrest Sender API. ## Common Issues > [accordion] Authentication Issues > > #### Invalid API Key > > If you're getting 401 Unauthorized errors: > >
    >
  • Verify your API key is correct and not expired
  • >
  • Ensure you're using the correct header: `API-Key` (not `X-API-Key`)
  • >
  • Check that your account has been KYC verified
  • >
  • Confirm your API key has the necessary permissions
  • >
> > #### Example Request > > ```bash theme={null} > curl -X GET "https://api.paycrest.io/v2/sender/orders" \ > -H "API-Key: YOUR_API_KEY" > ``` > [accordion] Order Creation Errors > > #### 400 Bad Request > > Common causes and solutions: > >
    >
  • **Invalid amount**: Amount must be a positive number
  • >
  • **Unsupported token**: Check supported tokens in the resources section
  • >
  • **Invalid network**: Ensure the network supports your chosen token
  • >
  • **Invalid Starknet address**: For `network: "starknet"`, use felt hex (`0x` + 63–64 hex digits), not an EVM checksum address
  • >
  • **Invalid Tron address**: For `network: "tron"`, use a Base58 address starting with `T`, not an EVM `0x` address
  • >
  • **Invalid Solana address**: For `network: "solana"`, `refundAddress` (off-ramp) and `destination.recipient.address` (on-ramp) must be Solana Base58 public keys, not EVM `0x` addresses
  • >
  • **"This network is available only via POST /v2/sender/orders"**: v1 endpoints do not accept Tron or Solana. Create Tron and Solana orders with [`POST /v2/sender/orders`](/api-reference/sender/initiate-payment-order-v2)
  • >
  • **"recipient … token account does not exist …"** (on-ramp to Solana): the recipient wallet has no token account for the stablecoin's mint. Have the user create it, then retry
  • >
  • **"Amount is below the minimum of 1 for this network"**: the amount must be at least 1 unit of the stablecoin
  • >
  • **Invalid `senderFeeAddress` on a Solana order**: for Solana orders, `senderFeeAddress` must be a Solana Base58 public key, like the order's other addresses
  • >
  • **Missing recipient details**: All recipient fields are required
  • >
  • **Invalid institution**: Check supported institutions for the currency
  • >
  • **Provider routing rejected**: `providerIds` and `providerId` are mutually exclusive; off-ramp queues cap at 3 entries and on-ramp at 1; entries must name providers you can route to. See [Pin a provider queue](/implementation-guides/sender-api-integration#pin-a-provider-queue)
  • >
> > #### 503 "Network temporarily unavailable" > > The message is one of: > >
    >
  • **"This network is temporarily unavailable; retry shortly or use another network"**
  • >
  • **"A quote for this amount is not available right now; retry shortly"**
  • >
> > Nothing was created. Retry shortly, or create the order on another network. > > #### The user's wallet will not send the deposit ("insufficient funds for gas") > > Not a Paycrest error — the wallet is refusing before broadcast. `providerAccount.amountToTransfer` is the token amount to send; the network fee for the user's own transfer is paid separately in the network's native token. > >
    >
  • **No native balance in the sending account**: holding the token is not enough. Wallets show a combined balance across accounts, so the native token often sits in a different account than the one sending
  • >
  • **Solana — the receive address's token account**: a transfer to a new receive address also creates its token account, currently about **0.0015 SOL** on top of the network fee, and not refunded
  • >
> > #### Deposit sent without the memo > > When `providerAccount.memo` is present, the deposit must include it; without it the deposit cannot be credited. Contact support with the order ID and transaction hash. > > #### "Recipient data too large for encryption" > > The recipient object is capped at **500 bytes** of JSON before encryption. The size check reserves room for a full 3-provider routing queue on **every** order — including orders that send no `providerIds` — because the aggregator may resolve one onto the order and it rides in the message hash at gateway submit. > >
    >
  • That reservation costs about **49 bytes** (**\~41** when you pin a `providerId`), leaving roughly **450 bytes** for `accountIdentifier` + `accountName` + `memo` + `metadata` combined
  • >
  • Trim `memo` first, then `metadata` — keep only `apiKey` and corridor-required keys like `channel`
  • >
  • `accountName` from [verify-account](/api-reference/general/verify-account) is often longer than what you supplied; count the resolved value
  • >
> > #### Example Error Response > > ```json theme={null} > { > "status": "error", > "message": "Invalid recipient details", > "errors": { > "recipient.accountIdentifier": "Account number is required", > "recipient.institution": "Institution not supported for NGN" > } > } > ``` > [accordion] Order Status Issues > > #### Order Stuck in Pending > > If your order has been in **pending** status for more than 10 minutes: > >
    >
  • Check if there are any network issues or maintenance
  • >
  • Verify the recipient details are correct
  • >
  • Contact support with your order ID
  • >
> > #### Order Refunded > > Common reasons for a refund: > >
    >
  • Insufficient provider liquidity
  • >
  • Recipient account issues
  • >
  • Compliance or regulatory restrictions
  • >
  • Network congestion or technical issues
  • >
> [accordion] Webhook Issues > > #### Webhooks Not Receiving > > Troubleshooting steps: > >
    >
  • Verify your webhook URL is publicly accessible
  • >
  • Check that your server returns 200 OK responses
  • >
  • Ensure your webhook endpoint can handle POST requests
  • >
  • Verify webhook signature for security
  • >
> > #### Inspect and replay deliveries > > You don't need to re-trigger the order flow to recover a missed event. Every send is logged as a delivery you can audit and replay: > >
    >
  • List failed deliveries: `GET /v2/sender/webhooks?status=failed`
  • >
  • Read the captured response body and error: `GET /v2/sender/webhooks/:id`
  • >
  • Replay the original payload: `POST /v2/sender/webhooks/:id/retry` (`?sync=true` returns the HTTP result inline; otherwise it's queued)
  • >
> > Failed deliveries (transport errors and non-2xx responses) are also retried automatically with exponential backoff for 24 hours before being marked `expired`. See the [webhook delivery logs & retry guide](/implementation-guides/sender-api-integration#webhook-delivery-logs--retry). > > #### Webhook Signature Verification > > > [tab] JavaScript > > > > ```javascript theme={null} > > const crypto = require('crypto'); > > > > function verifyWebhookSignature(rawBody, signature, secret) { > > const sig = (signature && String(signature).trim().toLowerCase()) || ''; > > const key = String(secret || '').trim(); > > if (!sig || !key) return false; > > > > const bodyBuf = Buffer.isBuffer(rawBody) ? rawBody : Buffer.from(rawBody, 'utf8'); > > const expected = crypto.createHmac('sha256', key).update(bodyBuf).digest('hex').toLowerCase(); > > if (expected.length !== sig.length) return false; > > try { > > return crypto.timingSafeEqual( > > Buffer.from(expected, 'utf8'), > > Buffer.from(sig, 'utf8') > > ); > > } catch { > > return false; > > } > > } > > ``` > > > [tab] Python > > > > ```python theme={null} > > import hmac > > import hashlib > > > > def verify_webhook_signature(raw_body, signature, secret): > > # raw_body is the raw request body bytes > > sig = (signature or "").strip().lower() > > body = raw_body if isinstance(raw_body, bytes) else raw_body.encode("utf-8") > > expected = hmac.new( > > secret.strip().encode("utf-8"), > > body, > > hashlib.sha256, > > ).hexdigest().lower() > > return hmac.compare_digest(expected, sig) > > ``` > > > [tab] Go > > > > ```go theme={null} > > package main > > > > import ( > > "crypto/hmac" > > "crypto/sha256" > > "encoding/hex" > > "strings" > > ) > > > > func verifyWebhookSignature(rawBody []byte, signature, secret string) bool { > > // rawBody is the raw request body bytes > > h := hmac.New(sha256.New, []byte(strings.TrimSpace(secret))) > > h.Write(rawBody) > > expected := hex.EncodeToString(h.Sum(nil)) > > sig := strings.ToLower(strings.TrimSpace(signature)) > > return hmac.Equal([]byte(expected), []byte(sig)) > > } > > ``` > [accordion] Network Issues > > #### Blockchain Network Problems > > If you're experiencing issues with specific networks: > >
    >
  • **High gas fees**: Consider using L2 networks like Base, Arbitrum, Polygon, or Celo
  • >
  • **Slow confirmations**: Some networks may have congestion
  • >
  • **Network maintenance**: Check our Telegram community for updates
  • >
> > #### Supported Networks > > > [card] Ethereum L2s > > > >
    > >
  • Base
  • > >
  • Arbitrum One
  • > >
  • Polygon
  • > >
  • Celo
  • > >
> > > [card] Other Networks > > > >
    > >
  • Ethereum
  • > >
  • BNB Smart Chain
  • > >
  • Starknet
  • > >
  • Tron
  • > >
## Error Codes Reference > [card] 4xx Client Errors > >
    >
  • **400**: Bad Request - Invalid parameters
  • >
  • **401**: Unauthorized - Invalid API key
  • >
  • **403**: Forbidden - Insufficient permissions
  • >
  • **404**: Not Found - Resource doesn't exist
  • >
  • **429**: Too Many Requests - Rate limit exceeded
  • >
> [card] 5xx Server Errors > >
    >
  • **500**: Internal Server Error
  • >
  • **502**: Bad Gateway
  • >
  • **503**: Service Unavailable
  • >
  • **504**: Gateway Timeout
  • >
## Rate Limits > [!NOTE] > > Paycrest implements rate limiting to ensure fair usage. Limits vary by endpoint and account tier. > [card] Unauthenticated > >
    >
  • **20 requests/second**
  • >
  • Applies to requests without a valid API key
  • >
> [card] Authenticated > >
    >
  • **500 requests/second**
  • >
  • Applies to requests with a valid API key
  • >
## Testing & Debugging **1. Enable Debug Logging** Add debug headers to see detailed request/response information: ```bash theme={null} curl -X POST "https://api.paycrest.io/v2/sender/orders" \ -H "API-Key: YOUR_API_KEY" \ -H "X-Debug: true" \ -H "Content-Type: application/json" \ -d '{"amount": "10", ...}' ``` **2. Check API Status** Monitor API status and performance:
  • Monitor response times and error rates
  • Set up alerts for critical endpoints
  • Join our Telegram community for real-time updates
**3. Contact Support** If you're still experiencing issues:
  • Email: \[[support@paycrest.io](mailto:support@paycrest.io)]\(mailto:[support@paycrest.io](mailto:support@paycrest.io))
  • Telegram: [Community Chat](https://t.me/+Stx-wLOdj49iNDM0)
  • Include order IDs and error details
## Best Practices > [card] Error Handling > >
    >
  • Always check response status codes
  • >
  • Implement exponential backoff for retries
  • >
  • Log errors with context for debugging
  • >
  • Handle network timeouts gracefully
  • >
> [card] Security > >
    >
  • Store API keys securely (use environment variables)
  • >
  • Verify webhook signatures
  • >
  • Use HTTPS for all API calls
  • >
  • Rotate API keys regularly
  • >
> [card] Performance > >
    >
  • Cache supported currencies and institutions
  • >
  • Use webhooks instead of polling
  • >
  • Implement connection pooling
  • >
  • Monitor rate limits
  • >
> [card] Monitoring > >
    >
  • Track order success/failure rates
  • >
  • Monitor response times
  • >
  • Set up alerts for critical failures
  • >
  • Log important events for audit trails
  • >
## Getting Help > [card] [Documentation](/api-reference) > > Browse our comprehensive API documentation with interactive examples > [card] [Community](https://t.me/+Stx-wLOdj49iNDM0) > > Join our Telegram community for peer support and discussions > [card] [Support Team](mailto:support@paycrest.io) > > Contact our technical support team for personalized assistance > [card] [GitHub Issues](https://github.com/paycrest/aggregator/issues) > > Report bugs and request features through our GitHub repository > [!NOTE] > > This troubleshooting guide covers the most common issues. For specific problems not covered here, please contact our support team with detailed information about your use case and any error messages you're seeing.