Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 2 additions & 4 deletions docs.json
Original file line number Diff line number Diff line change
Expand Up @@ -232,10 +232,9 @@
{
"group": "Payment integration",
"pages": [
"ecosystem/ton-pay/payment-integration/transfer",
"ecosystem/ton-pay/payment-integration/payments-react",
"ecosystem/ton-pay/payment-integration/payments-tonconnect",
"ecosystem/ton-pay/payment-integration/status-info"
"ecosystem/ton-pay/payment-integration/payments-server-side",
"ecosystem/ton-pay/payment-integration/migration"
]
},
{
Expand All @@ -245,7 +244,6 @@
"ecosystem/ton-pay/ui-integration/button-js"
]
},
"ecosystem/ton-pay/webhooks",
"ecosystem/ton-pay/api-reference"
]
},
Expand Down
167 changes: 137 additions & 30 deletions ecosystem/ton-pay/api-reference.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -5,66 +5,174 @@ sidebarTitle: "API reference"

import { Aside } from "/snippets/aside.jsx";

TypeScript exports for the TON Pay SDK packages `@ton-pay/api` and `@ton-pay/ui-react`. To install the packages, use:
TypeScript exports for the TON Pay [`v0.4`](https://www.npmjs.com/package/@ton-pay/api?activeTab=versions) packages.

## Install

```bash
npm install @ton-pay/api @ton-pay/ui-react
npm install @ton-pay/ui-react
```

Install `@ton-pay/api` separately only when server-side helpers are required.

## `@ton-pay/ui-react`

```ts
import { TonPayWidget } from "@ton-pay/ui-react";
import type {
TonPayWidgetProps,
WidgetErrorPayload,
WidgetRouteChangedPayload,
WidgetSuccessPayload,
} from "@ton-pay/ui-react";
```

### `TonPayWidget`

Self-contained React component that:

- resolves the TON Pay base URL from `chain`;
- creates and caches widget sessions;
- preloads the hosted iframe;
- maps merchant checkout props to widget intent;
- opens the checkout UI;
- forwards widget lifecycle callbacks.

### `TonPayWidgetProps`

```ts
type TonPayWidgetProps = {
amount: number | string;
recipientWalletAddress: string;
asset?: string;
bgColor?: string;
borderRadius?: number | string;
chain?: "mainnet" | "testnet";
className?: string;
comment?: string;
currency?: string;
disabled?: boolean;
fontFamily?: string;
height?: number | string;
isLoading?: boolean;
itemTitle?: string;
onClose?: () => void;
onError?: (payload: WidgetErrorPayload) => void;
onReady?: () => void;
onRouteChange?: (payload: WidgetRouteChangedPayload) => void;
onSuccess?: (payload: WidgetSuccessPayload) => void;
referenceId?: string;
style?: React.CSSProperties;
text?: string;
textColor?: string;
variant?: "long" | "short";
width?: number | string;
};
```

<Aside type="note">
`chain` defaults to `mainnet`. `TonPayWidget` selects the TON Pay base URL internally, so the host app does not need to pass it as a prop.
Comment on lines +36 to +74
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[HIGH] Ambiguous currency and asset prop behavior in widget API reference

The TonPayWidgetProps type defines both asset?: string; and currency?: string; as optional props without explaining their relationship or precedence. Elsewhere in the documentation, asset is presented as the primary way to select the token, which makes the additional undocumented currency prop ambiguous and potentially conflicting. This can confuse readers about which prop to use, and may lead to misuse or incorrect assumptions when passing values into the widget.

Please leave a reaction 👍/👎 to this suggestion to improve future reviews for everyone!

</Aside>

### `WidgetErrorPayload`

```ts
type WidgetErrorPayload = {
code:
| "unknown"
| "invalid_intent"
| "route_blocked"
| "wallet_disconnected"
| "storage_access_denied"
| "network_error"
| "setup_required"
| "setup_failed"
| "unlock_failed"
| "payment_failed"
| "insufficient_balance"
| "signless_stopped";
message: string;
recoverable: boolean;
route?: string;
};
```

### `WidgetRouteChangedPayload`

```ts
type WidgetRouteChangedPayload = {
pathname: string;
search: string;
};
```

## Imports
### `WidgetSuccessPayload`

```ts
type WidgetSuccessPayload = {
action: "setup" | "payment" | "topup" | "withdraw" | "reset";
reference?: string;
referenceId?: string;
sessionId?: string;
txHash?: string;
walletAddress?: string;
};
```

### Checkout prop notes

- `comment` – payment comment added to the blockchain transaction. It maps to `commentToRecipient`.
- `itemTitle` – UI-only text displayed in the widget.

## `@ton-pay/api`

```ts
// API helpers
import {
TON,
USDT,
createTonPayTransfer,
getTonPayTransferByBodyHash,
getTonPayTransferByReference,
type CompletedTonPayTransferInfo,
type CreateTonPayTransferParams,
type CreateTonPayTransferResponse,
verifySignature,
type TransferCompletedWebhookPayload,
type TransferRefundedWebhookPayload,
type WebhookPayload,
} from "@ton-pay/api";

// React UI
import { TonPayButton, useTonPay } from "@ton-pay/ui-react";
```

## Functions
Use `@ton-pay/api` for backend and non-widget flows such as:

- transfer creation for TON Connect or custom payment flows;
- transfer status lookup by `reference` or `bodyBase64Hash`;
- MoonPay helper calls outside the hosted widget flow.

### Functions

### `createTonPayTransfer(params, options?)`
#### `createTonPayTransfer(params, options?)`

Build a canonical message and return tracking identifiers.

- `params`: `CreateTonPayTransferParams`.
- `options`: `APIOptions`.
- `options.chain`: `mainnet | testnet`.

### `getTonPayTransferByBodyHash(bodyHash, options?)`
#### `getTonPayTransferByBodyHash(bodyHash, options?)`

Fetch a transfer by Base64 hash of the signed message body content (payload).

- `bodyHash`: Base64 hash of the signed message body content (payload). Use `bodyBase64Hash` from `createTonPayTransfer`.
- `options`: `APIOptions`.
- Return `CompletedTonPayTransferInfo`.

### `getTonPayTransferByReference(reference, options?)`
#### `getTonPayTransferByReference(reference, options?)`

Fetch a transfer by reference.

- `reference`: use the `reference` returned by `createTonPayTransfer`.
- `options`: `APIOptions`.
- Return `CompletedTonPayTransferInfo`.

### `useTonPay(options?)`

A React hook. Connect a wallet through [TON Connect](/ecosystem/ton-connect/overview) and send a transaction.

- `pay(getMessage)`: Receive `senderAddr`, request `{ message }` from the factory, and send through TON Connect. Resolve `{ txResult, ...factoryReturn }`.

### `TonPayButton`

Prebuilt button. Handle wallet connect or disconnect flow and call `handlePay`.

## Types: `@ton-pay/api`
### Types: `@ton-pay/api`

### `CreateTonPayTransferParams`

Expand Down Expand Up @@ -118,13 +226,13 @@ type CompletedTonPayTransferInfo = {
```

- `status`: `pending`, `success`, or `error`;
- `errorCode`: TON Pay error codes in [Check status and retrieve info](/ecosystem/ton-pay/payment-integration/status-info).
- `errorCode`: TON Pay error code returned for failed transfers, when available.

### `APIOptions`

```ts
type APIOptions = {
chain: "mainnet" | "testnet";
chain?: "mainnet" | "testnet";
};
```

Expand Down Expand Up @@ -153,7 +261,6 @@ import { TON, USDT } from "@ton-pay/api";

All API helpers throw `Error` with an HTTP `cause` if the network call fails. For example, `createTonPayTransfer` may throw "Failed to create TON Pay transfer".

## Peer dependencies
## See also

- [`@tonconnect/ui-react`](https://www.npmjs.com/package/@tonconnect/ui-react) – React UI kit for TON Connect SDK.
- [React 18](https://react.dev/) or later and `react-dom` 18 or later.
- End-to-end [server-side integration](/ecosystem/ton-pay/payment-integration/payments-server-side) examples
87 changes: 18 additions & 69 deletions ecosystem/ton-pay/on-ramp.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -5,87 +5,36 @@ sidebarTitle: "On-ramp"

import { Aside } from '/snippets/aside.jsx';

The TON Pay SDK includes a built-in fiat-to-crypto on-ramp powered by [MoonPay](https://www.moonpay.com/). It allows users to top up their wallets with a bank card directly from the payment modal.
TON Pay includes a built-in fiat-to-crypto on-ramp powered by [MoonPay](https://www.moonpay.com/). Within `TonPayWidget`, MoonPay appears as an embedded top-up step when the user needs additional funds to complete checkout.

## How it works

When a user opens the payment modal and the connected wallet balance is insufficient, the SDK offers a "Top up by card" option. The flow proceeds as follows:

1. Balance check. The SDK verifies whether the connected wallet has funds to complete the payment.
1. Geographic and limit check. The SDK verifies that card purchases are supported in the user's region and retrieves the provider's minimum and maximum purchase limits.
1. Amount calculation. The SDK computes the required top-up amount, clamped to the provider's minimum.
1. Widget rendering. The MoonPay purchase widget loads in an iframe. The purchase transfers funds directly to the user's wallet.
1. Balance polling. After the provider reports transaction completion, the SDK polls the wallet balance every 5 seconds.
1. Auto-pay. Once the wallet balance becomes sufficient, the SDK displays a modal to complete the merchant payment.

Funds are always credited to the user’s wallet before any transfer to the merchant occurs.

## How to enable

The [`TonPayButton` React component](/ecosystem/ton-pay/ui-integration/button-react) enables the on-ramp by default. To turn it off, set `isOnRampAvailable` to `false`:

```tsx
<TonPayButton
isOnRampAvailable={false}
// ... other props
/>
```

When `isOnRampAvailable` is `false`, the "Top up by card" option is hidden. Payments can only be completed using the current wallet balance.

## Supported assets
It allows users to purchase crypto with a bank card and receive it directly in the wallet used for the payment. The merchant payment is completed after the funds arrive and the balance is sufficient.

The SDK supports the following assets for on-ramp top-ups:

| Token | Master address |
| :------------- | :------------------------------------------------- |
| TON | Native |
| USDT | `EQCxE6mUtQJKFnGfaROTKOt1lZbDiiX1kCixRv7Nw2Id_sDs` |
| DOGS | `EQCvxJy4eG8hyHBFsZ7eePxrRsUQSFE_jpptRAYBmcG_DOGS` |
| Notcoin | `EQAvlWFDxGF2lXm67y4yzC17wYKD9A0guwPkMs1gOsM__NOT` |
| Hamster Kombat | `EQAJ8uWd7EBqsmpSWaRdf_I-8R8-XHwh3gsNKhy-UrdrPcUo` |
| Catizen | `EQD-cvR0Nz6XAyRBvbhz-abTrRC6sI5tvHvvpeQraV9UAAD7` |

## Geographic restrictions

Before displaying the card top-up option, the SDK checks the user's geographic eligibility with the MoonPay provider. If card purchases are not supported in the user's country, the option is not displayed.

The SDK performs this check using the user's IP address. If the integration proxies requests or omits the original client IP address, provide the user's IP explicitly using the `userIp` prop.

## Purchase limits

The SDK retrieves minimum and maximum purchase limits from MoonPay for the target asset. These limits are enforced automatically:
## How it works

- If the calculated top-up amount is below the minimum, the SDK increases it to `minAmount * 1.05`.
- The provider determines the maximum purchase amount; this cannot be overridden.
When the user opens `TonPayWidget`, TON Pay evaluates the checkout state. If the wallet balance is insufficient, the hosted flow offers an on-ramp step.

Limits use the quote currency returned by the provider, e.g., USD, and vary by region and payment method.
1. Balance check. TON Pay verifies whether the connected wallet has enough funds for the requested payment.
1. MoonPay availability check. TON Pay checks whether the session is eligible for MoonPay, including regional availability, supported assets, and provider-side limits.
1. Amount calculation. TON Pay calculates the top-up amount required to continue checkout.
1. Widget rendering. If the session is eligible, the MoonPay purchase widget opens inside the hosted TON Pay flow.
1. Wallet funding. The purchased assets are sent directly to the user's wallet, not to the merchant.
1. Checkout resume. After the balance becomes sufficient, the user can continue and complete the merchant payment in the same flow.

## Props reference
## Regional availability

| Prop | Type | Default | Description |
| :------------------ | :-------- | :------ | :---------------------------------------------------- |
| `isOnRampAvailable` | `boolean` | `true` | Show or hide the card top-up option. |
| `userIp` | `string` | – | User's IP address for the geographic check; optional. |
TON Pay offers the on-ramp step only in regions where MoonPay supports purchases. If unavailable, the widget does not offer card-based top-ups, and checkout can proceed only with the existing balance or externally added funds.

## Iframe events
Availability also depends on provider rules for the selected asset, payment method, and transaction amount.

The on-ramp widget communicates through `postMessage`. The SDK handles the following events internally:
## Merchant integration

| Event | Description |
| :------------------------------------------------ | :-------------------------------------------------------------------------------------- |
| `TONPAY_IFRAME_LOADED` | The on-ramp widget loaded successfully. |
| `TONPAY_MOONPAY_EVENT` (`onTransactionCompleted`) | The MoonPay purchase completes successfully. The SDK starts polling the wallet balance. |
| `TONPAY_MOONPAY_EVENT` (`onTransactionFailed`) | The MoonPay purchase failed. The user may retry the transaction. |
| `TONPAY_PAYMENT_ERROR` | On-ramp widget initialization error; e.g., the link expired. |
No additional on-ramp setup is required for the default hosted flow. Render [`TonPayWidget`](/ecosystem/ton-pay/ui-integration/button-react) with the checkout parameters, and TON Pay determines whether to show the MoonPay top-up step.

Merchants using `TonPayButton` do not need to handle these events manually.
For [custom server-side flows](/ecosystem/ton-pay/payment-integration/payments-server-side) instead of the hosted widget, use `@ton-pay/api`, including MoonPay-related helper calls outside the widget flow.
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Verify whether public docs in this repo explicitly document MoonPay helper calls in `@ton-pay/api`.
rg -n -C3 'MoonPay|moonpay' ecosystem/ton-pay
rg -n -C3 '@ton-pay/api|createTonPayTransfer|getTonPayTransferByReference|getTonPayTransferByBodyHash' ecosystem/ton-pay

Repository: ton-org/docs

Length of output: 21078


🏁 Script executed:

# Check if there are any MoonPay-specific function signatures or details in api-reference.mdx
sed -n '127,250p' ecosystem/ton-pay/api-reference.mdx | head -100

Repository: ton-org/docs

Length of output: 2425


Replace vague "MoonPay-related helper calls" with actual documented capabilities.

Line 33 references "MoonPay-related helper calls" as part of @ton-pay/api, but the API reference lists this only as a generic bullet point with no concrete function names or documentation. The three exported functions (createTonPayTransfer, getTonPayTransferByBodyHash, getTonPayTransferByReference) do not mention MoonPay in their descriptions. Developers searching for MoonPay-specific helpers will find nothing. Replace with concrete, documented capabilities:

✏️ Suggested rewording
-For [custom server-side flows](/ecosystem/ton-pay/payment-integration/payments-server-side) instead of the hosted widget, use `@ton-pay/api`, including MoonPay-related helper calls outside the widget flow.
+For [custom server-side flows](/ecosystem/ton-pay/payment-integration/payments-server-side) instead of the hosted widget, use `@ton-pay/api` for transfer creation, status lookups, and merchant-side reconciliation.
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
For [custom server-side flows](/ecosystem/ton-pay/payment-integration/payments-server-side) instead of the hosted widget, use `@ton-pay/api`, including MoonPay-related helper calls outside the widget flow.
For [custom server-side flows](/ecosystem/ton-pay/payment-integration/payments-server-side) instead of the hosted widget, use `@ton-pay/api` for transfer creation, status lookups, and merchant-side reconciliation.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@ecosystem/ton-pay/on-ramp.mdx` at line 33, Replace the vague phrase
"MoonPay-related helper calls" with concrete documented capabilities provided by
`@ton-pay/api`: list the exported functions createTonPayTransfer,
getTonPayTransferByBodyHash, and getTonPayTransferByReference and briefly
describe each (e.g., createTonPayTransfer — creates and signs a TON transfer for
MoonPay payouts; getTonPayTransferByBodyHash — fetches transfer metadata by
request body hash; getTonPayTransferByReference — retrieves transfer by provider
reference id). Update the sentence to point readers to these specific functions
so developers can find MoonPay-related helpers directly in the API reference.


<Aside
type="note"
title="Processing times and fees"
title="Processing times and provider rules"
>
MoonPay purchases require on-chain confirmation and are not processed immediately. The SDK monitors the transaction status through automatic balance polling.

The SDK adds a 5% buffer to top-up amounts to account for MoonPay fees and price fluctuations.
MoonPay purchases are subject to provider availability, limits, fees, and confirmation time. TON Pay continues checkout only after the purchased funds reach the user's wallet.
</Aside>
13 changes: 9 additions & 4 deletions ecosystem/ton-pay/overview.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -91,16 +91,21 @@ TON Pay SDK is compatible with TON wallets through the [TON Connect protocol](/e

While the SDK provides full programmatic control over payments, built-in UI components reduce integration time.

The `TonPayButton` React component handles wallet connection, transaction signing, loading states, and error notifications out of the box without requiring manual integration with TON Connect hooks or UI state management. It also covers common edge cases such as duplicate submissions, wallet disconnects, and user-visible errors.
- UI components render a payment button and open the hosted TON Pay widget.
- The host application passes checkout parameters such as amount, recipient wallet address, asset, and comment.
- TON Pay handles session bootstrap, checkout routing, wallet connection, transaction signing, and result handling.

For most web applications, the UI layer provides a functional checkout flow. The guide on [how to add a TON Pay button using React](/ecosystem/ton-pay/ui-integration/button-react) provides step-by-step instructions.
UI components provide a complete checkout experience for web applications. Select an integration based on the application stack:

- React – React component [`TonPayWidget`](/ecosystem/ton-pay/ui-integration/button-react).
- JavaScript – framework-agnostic SDK [`@ton-pay/ui`](/ecosystem/ton-pay/ui-integration/button-js).

## How TON Pay works

1. TON Pay backend generates a transaction message.
1. The user reviews and signs the transaction in the wallet.
1. The wallet presents the transaction for review and requires a signature.
1. The transaction is executed and confirmed on the TON blockchain.
1. TON Pay backend monitors the transaction status and sends webhook notifications to the application upon completion.
1. After submitting a payment for signing, the SDK allows the application to track its status using `reference` or `bodyBase64Hash`.

## Security

Expand Down
Loading
Loading