@binopartner/pay-sdk 0.3.4 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/README.md +19 -3
  2. package/dist/core/client.d.ts +9 -1
  3. package/dist/core/client.js +16 -1
  4. package/dist/core/errors.d.ts +7 -1
  5. package/dist/core/errors.js +6 -0
  6. package/dist/core/flows/promo.d.ts +49 -0
  7. package/dist/core/flows/promo.js +155 -0
  8. package/dist/core/flows/withdraw.d.ts +7 -1
  9. package/dist/core/flows/withdraw.js +56 -3
  10. package/dist/core/i18n/ar.js +55 -0
  11. package/dist/core/i18n/base.js +12 -0
  12. package/dist/core/i18n/cs.js +55 -0
  13. package/dist/core/i18n/de.js +55 -0
  14. package/dist/core/i18n/en.d.ts +55 -0
  15. package/dist/core/i18n/en.js +55 -0
  16. package/dist/core/i18n/es.js +55 -0
  17. package/dist/core/i18n/fr.js +55 -0
  18. package/dist/core/i18n/hi.js +55 -0
  19. package/dist/core/i18n/it.js +55 -0
  20. package/dist/core/i18n/ru.js +55 -0
  21. package/dist/core/i18n/tr.js +55 -0
  22. package/dist/core/i18n/ua.js +55 -0
  23. package/dist/core/index.d.ts +4 -0
  24. package/dist/core/index.js +2 -0
  25. package/dist/core/rules/bonus.d.ts +27 -0
  26. package/dist/core/rules/bonus.js +60 -0
  27. package/dist/core/types.d.ts +69 -0
  28. package/dist/core/wire.d.ts +18 -1
  29. package/dist/core/wire.js +79 -0
  30. package/dist/elements/Root.js +14 -7
  31. package/dist/elements/components/basic.js +4 -1
  32. package/dist/elements/components/bonus.d.ts +19 -0
  33. package/dist/elements/components/bonus.js +177 -0
  34. package/dist/elements/context.d.ts +3 -0
  35. package/dist/elements/hooks/promo.d.ts +37 -0
  36. package/dist/elements/hooks/promo.js +66 -0
  37. package/dist/elements/index.d.ts +7 -0
  38. package/dist/elements/index.js +2 -0
  39. package/dist/elements/presets/DepositForm.d.ts +2 -0
  40. package/dist/elements/presets/DepositForm.js +4 -2
  41. package/dist/elements/presets/WithdrawForm.d.ts +2 -0
  42. package/dist/elements/presets/WithdrawForm.js +3 -1
  43. package/dist/elements.css +394 -0
  44. package/package.json +1 -1
package/README.md CHANGED
@@ -266,11 +266,27 @@ Every component accepts `className`, `style` and `unstyled`, forwards its ref an
266
266
  | `RequisitesFrame`, `ReceiptUpload`, `Countdown`, `RedirectButton`, `Onramp` | Frame, receipt upload (RU deposits in raw mode; in frame mode the receipt is uploaded inside the frame), server-clock countdown, hosted page link, card onramp (Coindisco). The onramp is a link that opens it in a new tab; with `display="embed"` it is a frame (`height`, 640 px by default) with that link under it. Coindisco frames only on the origins listed in its dashboard: ask Binodex to list your site (`https://host`, each subdomain separately) before you turn the frame on. On a site that is not listed the frame stays blank and the link under it still works. `ref`, `className` and `style` go to the link. |
267
267
  | `SlippageWarning`, `SubmitButton`, `Status`, `BackButton`, `Qr` | |
268
268
  | `RestartButton`, `MethodNotice` | Cancel / new payment for card deposits (and a new withdrawal after a final status); the receipt notice under the amount for rails that may need a receipt. |
269
- | `DepositForm`, `WithdrawForm` | Full screens composed from the parts above, laid out like the binodex payment modal: a card with the title, the balance and a close button, the Crypto / Card tabs, the payment country and the bank tiles. Replace any piece: `<Pay.DepositForm components={{ MethodPicker: MyPicker }} />`. `<Pay.DepositForm onrampDisplay="embed" />` frames the card onramp (see `Onramp`). |
269
+ | `PromoCode` | The promo code of a deposit, see Promo codes. Renders nothing when promo codes are off or the backend does not know them. |
270
+ | `WithdrawBonus` | What a live promo bonus means for this withdrawal: locked, waiting for open positions, or the required burn consent. See Promo codes. |
271
+ | `DepositForm`, `WithdrawForm` | Full screens composed from the parts above, laid out like the binodex payment modal: a card with the title, the balance and a close button, the Crypto / Card tabs, the payment country and the bank tiles, the promo code under the methods and the bonus notice above the withdraw button. Replace any piece: `<Pay.DepositForm components={{ MethodPicker: MyPicker }} />`. `<Pay.DepositForm onrampDisplay="embed" />` frames the card onramp (see `Onramp`). |
270
272
 
271
273
  ### Hooks
272
274
 
273
- `usePay()`, `usePayContext()`, `useBalance()`, `usePaymentMethods()`, `useDepositQuote(methodId, amount)`, `useCryptoDeposit({ chainId, currency })`, `useCreateDeposit()`, `useDeposit(id)`, `useAttachReceipt(id)`, `useOnramp()`, `useWithdrawQuote({ methodId, address, amount })`, `useCreateWithdrawal()`, `useWithdrawal(id)`, `useDepositFlow()`, `useWithdrawFlow()`, `useCountdown(expiresAt)`, `usePayEvents(handler)`, `usePayMessages()`. All of them read external stores through `useSyncExternalStore`; no data-fetching library is needed. Money is created only from event handlers (`submit`, `create`, `request`), never from effects, so React StrictMode cannot create a second deposit.
275
+ `usePay()`, `usePayContext()`, `useBalance()`, `usePaymentMethods()`, `useDepositQuote(methodId, amount)`, `useCryptoDeposit({ chainId, currency })`, `useCreateDeposit()`, `useDeposit(id)`, `useAttachReceipt(id)`, `useOnramp()`, `useWithdrawQuote({ methodId, address, amount })`, `useCreateWithdrawal()`, `useWithdrawal(id)`, `useDepositFlow()`, `useWithdrawFlow()`, `useCountdown(expiresAt)`, `usePayEvents(handler)`, `usePayMessages()`, `usePromoCode()`. All of them read external stores through `useSyncExternalStore`; no data-fetching library is needed. Money is created only from event handlers (`submit`, `create`, `request`), never from effects, so React StrictMode cannot create a second deposit.
276
+
277
+ ### Promo codes
278
+
279
+ `DepositForm` shows a collapsed «Have a promo code?» row under the methods (and under the deposit address). It opens a field (typed in capitals) with Apply: the code is checked first (`POST /broker/pay/bonuses/preview`), then attached to the next deposit (`POST /broker/pay/bonuses/attach`). A refused code shows its reason under the field (`BONUS_EXPIRED`, `USER_LIMIT_REACHED`, `FIRST_DEPOSIT_ONLY`, `MIN_DEPOSIT_NOT_MET`, `ACTIVE_BONUS_EXISTS`, …; a reason the SDK does not know reads as a plain refusal). An attached code shows its terms: the bonus, the minimum deposit, the deposit past which a capped percent bonus stops growing, how long the code is valid, the trading volume to reach and its deadline, when a withdrawal opens (at once, after a share of the volume, or after all of it), that a withdrawal burns the bonus left, and «Remove code». A bonus already credited shows as one line with the trading progress and no field. The block loads once per opened form, reloads after `deposit.credited`, and renders nothing while loading, when promo codes are off for the user (`enabled: false`) or on a backend without them (`NOT_FOUND`): the deposit form works the same either way.
280
+
281
+ Place it yourself with `<Pay.PromoCode />` anywhere inside a deposit `Pay.Root`, replace it with `components={{ PromoCode: Mine }}`, or build your own on `usePromoCode()`: `{ view, enabled, attached, active, preview, code, pending, reason, reasonText, error, errorText, open, close, setCode, apply, remove, refresh }`, where `view` is `"hidden" | "collapsed" | "editing" | "applied" | "active"`. In a withdraw root it stays `hidden` and makes no request.
282
+
283
+ **Withdrawals with a live bonus.** The context carries `withdrawal.bonus` (`{ status, bonusLeftUsd, progressPct, unlockPct, unlocked }`), and `WithdrawForm` shows `WithdrawBonus` above the button, with `data-gate`:
284
+
285
+ - `locked`: the trading volume does not open a withdrawal yet; the notice shows the progress against the share needed and the button stays off.
286
+ - `burn-pending`: the bonus is closing; the user closes their open positions first.
287
+ - `consent` / `ready`: a withdrawal burns what is left of the bonus (up to `bonusLeftUsd`). A required checkbox asks the user to agree; the button waits for it, and the withdrawal is sent with `confirm_burn_bonus: true`.
288
+
289
+ The server has the last word: `BONUS_WITHDRAWAL_LOCKED` (with `unlockPct` and `progressPct`), `BONUS_BURN_CONFIRM_REQUIRED`, `BONUS_BURN_PENDING`, `BONUS_CHANGED` and `OPEN_POSITIONS` are shown in words under the form, and the form reads the context again; `BONUS_CHANGED` also clears the consent, since another sum would burn. A custom layout gets `bonus`, `burnConsent` and `setBurnConsent` from `useWithdrawFlow()`.
274
290
 
275
291
  ### Theming
276
292
 
@@ -290,7 +306,7 @@ Every component accepts `className`, `style` and `unstyled`, forwards its ref an
290
306
 
291
307
  ### Headless core
292
308
 
293
- `@binopartner/pay-sdk/core` has no dependencies and no React: `createPayClient(options)` (session, token, host selection, typed calls, error codes), `createDepositFlow(client)` and `createWithdrawFlow(client)` (state machines with `subscribe`/`getSnapshot`, debounced quotes, polling, idempotency keys), plus the formatting and validation rules the elements use. Use it to build a UI in any framework.
309
+ `@binopartner/pay-sdk/core` has no dependencies and no React: `createPayClient(options)` (session, token, host selection, typed calls, error codes), `createDepositFlow(client)` and `createWithdrawFlow(client)` (state machines with `subscribe`/`getSnapshot`, debounced quotes, polling, idempotency keys), `createPromoFlow(client)` with `promoViewOf(state)` for promo codes (the client also has `getBonuses()`, `previewBonus(code, amountUsd?)`, `attachBonus(code)` and `detachBonus()`), plus the formatting and validation rules the elements use (`withdrawBonusGate`, `maxCountedDepositUsd`, `promoReasonKey`, …). Use it to build a UI in any framework.
294
310
 
295
311
  Amounts are written the way binodex writes them in every language: dollars as `$1250.00`, fiat grouped by its own currency with the symbol after a space (`formatMoney`: `5 007 ₽`, `1,00,000 ₹`), the amount to transfer on a paying screen with kopecks and hryvnia cents (`formatPayingAmount`: `22 227,00 ₽`), limits as `0.05 SOL` or `$10.00` (`formatMinLimit`).
296
312
 
@@ -3,7 +3,7 @@ import { type ServerClock } from "./clock.js";
3
3
  import { PayError } from "./errors.js";
4
4
  import { type PayEvent, type PayEventInput } from "./events.js";
5
5
  import { type ReadableStore } from "./store.js";
6
- import type { CreateDepositInput, CreateSession, CreateWithdrawalInput, CryptoDeposit, Deposit, DepositQuote, FiatDeposit, FrameTicket, PayActivity, PayContext, PayMethods, PayMode, PayTheme, QuoteWithdrawalInput, Withdrawal, WithdrawalQuoteResult } from "./types.js";
6
+ import type { BonusPreview, CreateDepositInput, CreateSession, CreateWithdrawalInput, CryptoDeposit, Deposit, DepositQuote, FiatDeposit, FrameTicket, PayActivity, PayBonuses, PayContext, PayMethods, PayMode, PayTheme, QuoteWithdrawalInput, Withdrawal, WithdrawalQuoteResult } from "./types.js";
7
7
  export declare const MAX_RECEIPT_BYTES: number;
8
8
  export type ClientStatus = "idle" | "session" | "ready" | "error";
9
9
  export interface ClientState {
@@ -59,6 +59,14 @@ export interface PayClient {
59
59
  }) => Promise<Withdrawal>;
60
60
  getWithdrawal: (id: string, signal?: AbortSignal) => Promise<Withdrawal>;
61
61
  getActivity: (since: number, signal?: AbortSignal) => Promise<PayActivity>;
62
+ /** Promo codes and the live bonus. Both modes. A backend without promo codes answers `NOT_FOUND`. */
63
+ getBonuses: (signal?: AbortSignal) => Promise<PayBonuses>;
64
+ /** What a code gives; a bad code is `valid: false` with a `reason`, never an error. Deposit mode. */
65
+ previewBonus: (code: string, amountUsd?: string | number, signal?: AbortSignal) => Promise<BonusPreview>;
66
+ /** Attaches a code to the next deposit. A refusal is `PROMO_CODE_REJECTED` with `details.reason`. Deposit mode. */
67
+ attachBonus: (code: string) => Promise<PayBonuses>;
68
+ /** Takes the attached code off. Deposit mode. */
69
+ detachBonus: () => Promise<PayBonuses>;
62
70
  widgetOrigins: () => string[];
63
71
  frameOrigins: (declared: readonly unknown[]) => string[];
64
72
  onEvent: (listener: (event: PayEvent) => void) => () => void;
@@ -4,7 +4,7 @@ import { createServerClock } from "./clock.js";
4
4
  import { PayError, isAbortError, toPayError } from "./errors.js";
5
5
  import { createEvent } from "./events.js";
6
6
  import { createEmitter, createStore } from "./store.js";
7
- import { IDEMPOTENCY_HEADER, PATHS, readActivity, readContext, readCryptoDepositResponse, readDeposit, readDepositQuote, readError, readFiatDepositResponse, readFrameTicket, readMethods, readOnramp, readWithdrawal, readWithdrawalQuote, toActivityQuery, toCreateDepositBody, toCreateWithdrawalBody, toCryptoDepositBody, toDepositQuoteQuery, toOnrampQuery, toQuoteWithdrawalBody, toReceiptBody, } from "./wire.js";
7
+ import { IDEMPOTENCY_HEADER, PATHS, readActivity, readBonusPreview, readBonuses, readContext, readCryptoDepositResponse, readDeposit, readDepositQuote, readError, readFiatDepositResponse, readFrameTicket, readMethods, readOnramp, readWithdrawal, readWithdrawalQuote, toActivityQuery, toBonusAttachBody, toBonusPreviewBody, toCreateDepositBody, toCreateWithdrawalBody, toCryptoDepositBody, toDepositQuoteQuery, toOnrampQuery, toQuoteWithdrawalBody, toReceiptBody, } from "./wire.js";
8
8
  export const MAX_RECEIPT_BYTES = 11 * 1024 * 1024;
9
9
  const IDEMPOTENCY_KEY = /^[A-Za-z0-9_-]{8,200}$/;
10
10
  export const createIdempotencyKey = () => {
@@ -267,6 +267,21 @@ export const createPayClient = (options) => {
267
267
  signal,
268
268
  read: readActivity,
269
269
  }),
270
+ getBonuses: (signal) => request({ method: "GET", path: PATHS.bonuses, signal, read: readBonuses }),
271
+ previewBonus: (code, amountUsd, signal) => request({
272
+ method: "POST",
273
+ path: PATHS.bonusPreview,
274
+ body: toBonusPreviewBody(code, amountUsd),
275
+ signal,
276
+ read: readBonusPreview,
277
+ }),
278
+ attachBonus: (code) => request({
279
+ method: "POST",
280
+ path: PATHS.bonusAttach,
281
+ body: toBonusAttachBody(code),
282
+ read: readBonuses,
283
+ }),
284
+ detachBonus: () => request({ method: "DELETE", path: PATHS.bonusAttach, read: readBonuses }),
270
285
  widgetOrigins: () => auth.widgetOrigins(),
271
286
  frameOrigins: (declared) => auth.frameOrigins(declared),
272
287
  onEvent: (listener) => emitter.subscribe(listener),
@@ -1,4 +1,4 @@
1
- export declare const SERVER_ERROR_CODES: readonly ["UNAUTHENTICATED", "ORIGIN_MISMATCH", "MODE_NOT_ALLOWED", "PAY_API_DISABLED", "NOT_FOUND", "VALIDATION_FAILED", "METHOD_UNAVAILABLE", "AMOUNT_TOO_SMALL", "AMOUNT_TOO_LARGE", "INVALID_ADDRESS", "UNSUPPORTED_ROUTE", "SELF_WALLET", "RECIPIENT_BLOCKED", "INSUFFICIENT_BALANCE", "WITHDRAWALS_RESTRICTED", "ACCOUNT_FROZEN", "WITHDRAWAL_IN_PROGRESS", "TWO_FA_REQUIRED", "TWO_FA_INVALID", "TWO_FA_REUSED", "TWO_FA_LOCKED", "DAILY_CAP", "RATE_LIMITED", "IDEMPOTENCY_CONFLICT", "IDEMPOTENCY_IN_PROGRESS", "PROVIDER_UNAVAILABLE", "INTERNAL_ERROR"];
1
+ export declare const SERVER_ERROR_CODES: readonly ["UNAUTHENTICATED", "ORIGIN_MISMATCH", "MODE_NOT_ALLOWED", "PAY_API_DISABLED", "NOT_FOUND", "VALIDATION_FAILED", "METHOD_UNAVAILABLE", "AMOUNT_TOO_SMALL", "AMOUNT_TOO_LARGE", "INVALID_ADDRESS", "UNSUPPORTED_ROUTE", "SELF_WALLET", "RECIPIENT_BLOCKED", "INSUFFICIENT_BALANCE", "WITHDRAWALS_RESTRICTED", "ACCOUNT_FROZEN", "WITHDRAWAL_IN_PROGRESS", "TWO_FA_REQUIRED", "TWO_FA_INVALID", "TWO_FA_REUSED", "TWO_FA_LOCKED", "DAILY_CAP", "RATE_LIMITED", "IDEMPOTENCY_CONFLICT", "IDEMPOTENCY_IN_PROGRESS", "PROVIDER_UNAVAILABLE", "INTERNAL_ERROR", "PROMO_CODE_REJECTED", "BONUS_WITHDRAWAL_LOCKED", "BONUS_BURN_CONFIRM_REQUIRED", "BONUS_BURN_PENDING", "BONUS_CHANGED", "OPEN_POSITIONS"];
2
2
  export declare const CLIENT_ERROR_CODES: readonly ["SESSION_FAILED", "PAY_API_UNAVAILABLE", "INVALID_API_BASE", "HOST_UNREACHABLE", "NETWORK_ERROR", "INVALID_RESPONSE", "REQUISITES_FRAME_UNAVAILABLE", "UNKNOWN"];
3
3
  export type ServerErrorCode = (typeof SERVER_ERROR_CODES)[number];
4
4
  export type ClientErrorCode = (typeof CLIENT_ERROR_CODES)[number];
@@ -10,6 +10,12 @@ export interface PayErrorDetails {
10
10
  currency?: string;
11
11
  retryAfterSeconds?: number;
12
12
  withdrawalId?: string;
13
+ /** Why a promo code was refused (`PROMO_CODE_REJECTED`), for example `BONUS_EXPIRED`. */
14
+ reason?: string;
15
+ /** `BONUS_WITHDRAWAL_LOCKED`: the share of the bonus trading volume (0-100) that opens a withdrawal. */
16
+ unlockPct?: number;
17
+ /** `BONUS_WITHDRAWAL_LOCKED`: how much of the bonus trading volume is done, percent. */
18
+ progressPct?: number;
13
19
  }
14
20
  export declare const isServerErrorCode: (value: unknown) => value is ServerErrorCode;
15
21
  export declare class PayError extends Error {
@@ -26,6 +26,12 @@ export const SERVER_ERROR_CODES = [
26
26
  "IDEMPOTENCY_IN_PROGRESS",
27
27
  "PROVIDER_UNAVAILABLE",
28
28
  "INTERNAL_ERROR",
29
+ "PROMO_CODE_REJECTED",
30
+ "BONUS_WITHDRAWAL_LOCKED",
31
+ "BONUS_BURN_CONFIRM_REQUIRED",
32
+ "BONUS_BURN_PENDING",
33
+ "BONUS_CHANGED",
34
+ "OPEN_POSITIONS",
29
35
  ];
30
36
  export const CLIENT_ERROR_CODES = [
31
37
  "SESSION_FAILED",
@@ -0,0 +1,49 @@
1
+ import type { PayClient } from "../client.js";
2
+ import { type PayError } from "../errors.js";
3
+ import type { BonusPreview, PayBonuses } from "../types.js";
4
+ import type { FlowStore } from "./deposit.js";
5
+ /**
6
+ * `unavailable`: promo codes cannot be shown at all, because the backend predates them
7
+ * (`GET /pay/bonuses` is `NOT_FOUND`) or its answer could not be read. The deposit form
8
+ * works the same without them.
9
+ */
10
+ export type PromoStatus = "idle" | "loading" | "ready" | "unavailable";
11
+ export type PromoPending = "preview" | "attach" | "detach";
12
+ export interface PromoFlowState {
13
+ status: PromoStatus;
14
+ bonuses: PayBonuses | null;
15
+ /** The code field is open. */
16
+ open: boolean;
17
+ /** The typed code, in capitals. */
18
+ code: string;
19
+ pending: PromoPending | null;
20
+ /** The last valid preview: the terms of the code being attached or just attached. */
21
+ preview: BonusPreview | null;
22
+ /** Why the last code was refused (`BONUS_REJECT_REASONS`, or a reason this SDK does not know). */
23
+ reason: string | null;
24
+ /** A request that failed for another cause: network, server, session. */
25
+ error: PayError | null;
26
+ }
27
+ export interface PromoFlowActions {
28
+ /** Loads the bonuses once; later calls do nothing. */
29
+ start: () => void;
30
+ open: () => void;
31
+ close: () => void;
32
+ setCode: (raw: string) => void;
33
+ /** Previews the typed code, then attaches it when it is valid. */
34
+ apply: () => Promise<void>;
35
+ /** Takes the attached code off. */
36
+ remove: () => Promise<void>;
37
+ refresh: () => Promise<void>;
38
+ destroy: () => void;
39
+ }
40
+ export type PromoFlow = FlowStore<PromoFlowState, PromoFlowActions>;
41
+ /**
42
+ * What a promo block shows: nothing (`hidden`, promo codes are unavailable, still
43
+ * loading, or off with no bonus running), a collapsed row, the code field, the attached
44
+ * code with its terms, or the bonus already being traded through. A credited bonus is
45
+ * shown even when new codes are off: it still runs, and a withdrawal still burns it.
46
+ */
47
+ export type PromoView = "hidden" | "collapsed" | "editing" | "applied" | "active";
48
+ export declare const promoViewOf: (state: PromoFlowState) => PromoView;
49
+ export declare const createPromoFlow: (client: PayClient) => PromoFlow;
@@ -0,0 +1,155 @@
1
+ import { isAbortError, toPayError } from "../errors.js";
2
+ import { normalizePromoCode } from "../rules/bonus.js";
3
+ import { createStore } from "../store.js";
4
+ export const promoViewOf = (state) => {
5
+ const bonuses = state.bonuses;
6
+ if (state.status !== "ready" || !bonuses)
7
+ return "hidden";
8
+ if (bonuses.active)
9
+ return "active";
10
+ if (!bonuses.enabled)
11
+ return "hidden";
12
+ if (bonuses.attached)
13
+ return "applied";
14
+ return state.open ? "editing" : "collapsed";
15
+ };
16
+ const INITIAL = {
17
+ status: "idle",
18
+ bonuses: null,
19
+ open: false,
20
+ code: "",
21
+ pending: null,
22
+ preview: null,
23
+ reason: null,
24
+ error: null,
25
+ };
26
+ // Reasons after which the code field is the wrong thing to show: the bonuses are read again.
27
+ const STALE_REASONS = new Set(["ACTIVE_BONUS_EXISTS", "SYSTEM_DISABLED"]);
28
+ export const createPromoFlow = (client) => {
29
+ const store = createStore(INITIAL);
30
+ const get = store.getSnapshot;
31
+ const set = store.set;
32
+ let loadController = null;
33
+ let unsubscribe = null;
34
+ let started = false;
35
+ let destroyed = false;
36
+ let intent = 0;
37
+ const load = () => {
38
+ loadController?.abort();
39
+ const controller = new AbortController();
40
+ loadController = controller;
41
+ if (!get().bonuses)
42
+ set({ status: "loading" });
43
+ return client.getBonuses(controller.signal).then((bonuses) => {
44
+ if (destroyed || controller.signal.aborted)
45
+ return;
46
+ set({ status: "ready", bonuses });
47
+ }, (error) => {
48
+ if (destroyed || controller.signal.aborted || isAbortError(error))
49
+ return;
50
+ // A refresh that fails keeps what is on screen; a first load hides the block.
51
+ if (!get().bonuses)
52
+ set({ status: "unavailable" });
53
+ });
54
+ };
55
+ const fail = (error, scope) => {
56
+ const payError = toPayError(error);
57
+ set({ pending: null, error: payError });
58
+ client.emit({ type: "error", code: payError.code, scope });
59
+ };
60
+ const refuse = (reason) => {
61
+ set({ pending: null, preview: null, reason });
62
+ if (STALE_REASONS.has(reason))
63
+ void load();
64
+ };
65
+ const actions = {
66
+ start: () => {
67
+ if (started || destroyed)
68
+ return;
69
+ started = true;
70
+ // A deposit credited turns the attached code into the bonus being traded through.
71
+ unsubscribe = client.onEvent((event) => {
72
+ if (event.type === "deposit.credited" && !destroyed)
73
+ void load();
74
+ });
75
+ void load();
76
+ },
77
+ open: () => {
78
+ if (!get().open)
79
+ set({ open: true });
80
+ },
81
+ close: () => {
82
+ if (get().pending)
83
+ return;
84
+ set({ open: false, reason: null, error: null });
85
+ },
86
+ setCode: (raw) => {
87
+ if (get().pending)
88
+ return;
89
+ const code = normalizePromoCode(raw);
90
+ if (code === get().code)
91
+ return;
92
+ set({ code, reason: null, error: null });
93
+ },
94
+ apply: async () => {
95
+ const s = get();
96
+ const code = s.code;
97
+ if (!code || s.pending || !s.bonuses?.enabled || s.bonuses.active || s.bonuses.attached)
98
+ return;
99
+ const token = ++intent;
100
+ set({ pending: "preview", preview: null, reason: null, error: null });
101
+ try {
102
+ const preview = await client.previewBonus(code);
103
+ if (destroyed || token !== intent)
104
+ return;
105
+ if (!preview.valid) {
106
+ refuse(preview.reason ?? "BONUS_CODE_NOT_FOUND");
107
+ return;
108
+ }
109
+ set({ pending: "attach", preview });
110
+ const bonuses = await client.attachBonus(preview.code || code);
111
+ if (destroyed || token !== intent)
112
+ return;
113
+ set({ pending: null, bonuses, code: "", open: false });
114
+ }
115
+ catch (error) {
116
+ if (destroyed || token !== intent || isAbortError(error))
117
+ return;
118
+ const payError = toPayError(error);
119
+ if (payError.code === "PROMO_CODE_REJECTED")
120
+ refuse(payError.details.reason ?? "UNKNOWN");
121
+ else
122
+ fail(payError, "bonus.attach");
123
+ }
124
+ },
125
+ remove: async () => {
126
+ const s = get();
127
+ if (s.pending || !s.bonuses?.attached)
128
+ return;
129
+ const token = ++intent;
130
+ set({ pending: "detach", reason: null, error: null });
131
+ try {
132
+ const bonuses = await client.detachBonus();
133
+ if (destroyed || token !== intent)
134
+ return;
135
+ // The field opens empty: someone who took a code off often has another one.
136
+ set({ pending: null, bonuses, preview: null, code: "", open: true });
137
+ }
138
+ catch (error) {
139
+ if (destroyed || token !== intent || isAbortError(error))
140
+ return;
141
+ fail(error, "bonus.detach");
142
+ }
143
+ },
144
+ refresh: () => (destroyed ? Promise.resolve() : load()),
145
+ destroy: () => {
146
+ if (destroyed)
147
+ return;
148
+ destroyed = true;
149
+ loadController?.abort();
150
+ unsubscribe?.();
151
+ unsubscribe = null;
152
+ },
153
+ };
154
+ return { getSnapshot: store.getSnapshot, subscribe: store.subscribe, actions };
155
+ };
@@ -1,7 +1,7 @@
1
1
  import { type Timers } from "../api-base.js";
2
2
  import type { PayClient } from "../client.js";
3
3
  import { PayError } from "../errors.js";
4
- import type { CryptoMethod, PayContext, PayMethods, SlippageWarning, Withdrawal, WithdrawalQuote } from "../types.js";
4
+ import type { CryptoMethod, PayContext, PayMethods, SlippageWarning, Withdrawal, WithdrawalBonus, WithdrawalQuote } from "../types.js";
5
5
  import type { FlowStore } from "./deposit.js";
6
6
  export type WithdrawStep = "loading" | "form" | "quoting" | "slippage-confirm" | "two-factor" | "submitting" | "status" | "error";
7
7
  export interface WithdrawFlowState {
@@ -19,6 +19,10 @@ export interface WithdrawFlowState {
19
19
  acceptedSlippagePct: number | null;
20
20
  twoFactorRequired: boolean;
21
21
  twoFactorCode: string;
22
+ /** The live promo bonus from the context: it may lock the withdrawal or be burned by it. */
23
+ bonus: WithdrawalBonus | null;
24
+ /** The user agreed that the withdrawal burns what is left of the bonus. */
25
+ burnConsent: boolean;
22
26
  withdrawal: Withdrawal | null;
23
27
  submitError: PayError | null;
24
28
  error: PayError | null;
@@ -31,6 +35,8 @@ export interface WithdrawFlowActions {
31
35
  setMax: () => void;
32
36
  acceptSlippage: () => void;
33
37
  setTwoFactorCode: (value: string) => void;
38
+ /** Sends `confirm_burn_bonus: true` with the withdrawal; needed while a bonus is live. */
39
+ setBurnConsent: (value: boolean) => void;
34
40
  submit: () => Promise<void>;
35
41
  requote: () => void;
36
42
  refreshContext: () => Promise<void>;
@@ -5,6 +5,7 @@ import { PayError, isAbortError, toPayError } from "../errors.js";
5
5
  import { compareDecimal, isPositiveDecimal, sanitizeAmountInput, toFixed2 } from "../money.js";
6
6
  import { createPoller } from "../poll.js";
7
7
  import { isValidWithdrawAddress } from "../rules/address.js";
8
+ import { withdrawBonusGate } from "../rules/bonus.js";
8
9
  import { acceptSlippagePct } from "../rules/slippage.js";
9
10
  import { createStore } from "../store.js";
10
11
  const INITIAL = {
@@ -22,6 +23,8 @@ const INITIAL = {
22
23
  acceptedSlippagePct: null,
23
24
  twoFactorRequired: false,
24
25
  twoFactorCode: "",
26
+ bonus: null,
27
+ burnConsent: false,
25
28
  withdrawal: null,
26
29
  submitError: null,
27
30
  error: null,
@@ -34,6 +37,14 @@ const TERMINAL = new Set([
34
37
  ]);
35
38
  export const isTerminalWithdrawal = (withdrawal) => TERMINAL.has(withdrawal.status);
36
39
  const TWO_FA_CODES = new Set(["TWO_FA_REQUIRED", "TWO_FA_INVALID", "TWO_FA_REUSED", "TWO_FA_LOCKED"]);
40
+ // The server saw a bonus the form did not, or a different one: the context is read again.
41
+ const BONUS_CODES = new Set([
42
+ "BONUS_WITHDRAWAL_LOCKED",
43
+ "BONUS_BURN_CONFIRM_REQUIRED",
44
+ "BONUS_BURN_PENDING",
45
+ "BONUS_CHANGED",
46
+ "OPEN_POSITIONS",
47
+ ]);
37
48
  export const withdrawableOf = (context) => context ? (context.balance.withdrawable ?? context.balance.available) : null;
38
49
  export const withdrawAmountHint = (amount, method, methods, context) => {
39
50
  if (!amount)
@@ -59,6 +70,21 @@ export const withdrawAmountHint = (amount, method, methods, context) => {
59
70
  }
60
71
  return null;
61
72
  };
73
+ // What the form already knows the server would refuse, as the error the server would send.
74
+ const bonusBlock = (gate, bonus) => {
75
+ switch (gate) {
76
+ case "burn-pending":
77
+ return new PayError("BONUS_BURN_PENDING");
78
+ case "locked":
79
+ return new PayError("BONUS_WITHDRAWAL_LOCKED", "BONUS_WITHDRAWAL_LOCKED", {
80
+ details: bonus ? { unlockPct: bonus.unlockPct, progressPct: bonus.progressPct } : {},
81
+ });
82
+ case "consent":
83
+ return new PayError("BONUS_BURN_CONFIRM_REQUIRED");
84
+ default:
85
+ return null;
86
+ }
87
+ };
62
88
  export const createWithdrawFlow = (client, options = {}) => {
63
89
  const timers = options.timers ?? defaultTimers;
64
90
  const store = createStore(INITIAL);
@@ -73,6 +99,10 @@ export const createWithdrawFlow = (client, options = {}) => {
73
99
  let destroyed = false;
74
100
  let started = false;
75
101
  let intent = 0;
102
+ const applyContext = (context) => {
103
+ const bonus = context.withdrawal?.bonus ?? null;
104
+ set({ context, bonus, ...(bonus ? {} : { burnConsent: false }) });
105
+ };
76
106
  const clearQuote = () => {
77
107
  if (quoteTimer !== null)
78
108
  timers.clearTimeout(quoteTimer);
@@ -204,8 +234,8 @@ export const createWithdrawFlow = (client, options = {}) => {
204
234
  if (destroyed || controller.signal.aborted)
205
235
  return;
206
236
  const crypto = methods.methods.filter((entry) => entry.kind === "crypto");
237
+ applyContext(context);
207
238
  set({
208
- context,
209
239
  methods,
210
240
  method: get().method ?? crypto[0] ?? null,
211
241
  twoFactorRequired: context.withdrawal?.twoFactorRequired ?? false,
@@ -290,12 +320,21 @@ export const createWithdrawFlow = (client, options = {}) => {
290
320
  return;
291
321
  set({ twoFactorCode, submitError: null });
292
322
  },
323
+ setBurnConsent: (value) => {
324
+ if (value === get().burnConsent || formLocked())
325
+ return;
326
+ const submitError = get().submitError;
327
+ set({
328
+ burnConsent: value,
329
+ ...(submitError?.code === "BONUS_BURN_CONFIRM_REQUIRED" ? { submitError: null } : {}),
330
+ });
331
+ },
293
332
  requote: () => runQuote(0),
294
333
  refreshContext: async () => {
295
334
  try {
296
335
  const context = await client.getContext();
297
336
  if (!destroyed) {
298
- set({ context });
337
+ applyContext(context);
299
338
  validate();
300
339
  }
301
340
  }
@@ -310,6 +349,12 @@ export const createWithdrawFlow = (client, options = {}) => {
310
349
  const { addressError, amountError } = validate();
311
350
  if (addressError || amountError)
312
351
  return;
352
+ const gate = withdrawBonusGate(s.bonus, s.burnConsent);
353
+ const blocked = bonusBlock(gate, s.bonus);
354
+ if (blocked) {
355
+ set({ submitError: blocked });
356
+ return;
357
+ }
313
358
  if (s.twoFactorRequired && s.twoFactorCode.length !== 6) {
314
359
  set({ step: "two-factor" });
315
360
  return;
@@ -321,6 +366,7 @@ export const createWithdrawFlow = (client, options = {}) => {
321
366
  quote: s.quote,
322
367
  ...(s.acceptedSlippagePct !== null ? { acceptSlippagePct: s.acceptedSlippagePct } : {}),
323
368
  ...(s.twoFactorRequired && s.twoFactorCode ? { twoFactorCode: s.twoFactorCode } : {}),
369
+ ...(gate === "ready" ? { confirmBurnBonus: true } : {}),
324
370
  };
325
371
  const idempotencyKey = intents.keyFor(toCreateWithdrawalBody(input));
326
372
  const token = intent;
@@ -349,7 +395,7 @@ export const createWithdrawFlow = (client, options = {}) => {
349
395
  .getContext()
350
396
  .then((context) => {
351
397
  if (!destroyed)
352
- set({ context });
398
+ applyContext(context);
353
399
  return context.withdrawal?.inFlightId ?? null;
354
400
  })
355
401
  .catch(() => null);
@@ -360,6 +406,12 @@ export const createWithdrawFlow = (client, options = {}) => {
360
406
  return;
361
407
  }
362
408
  }
409
+ if (BONUS_CODES.has(payError.code)) {
410
+ // A changed bonus burns another sum: the consent is asked again.
411
+ if (payError.code === "BONUS_CHANGED")
412
+ set({ burnConsent: false });
413
+ void actions.refreshContext();
414
+ }
363
415
  if (TWO_FA_CODES.has(payError.code)) {
364
416
  set({
365
417
  step: "two-factor",
@@ -395,6 +447,7 @@ export const createWithdrawFlow = (client, options = {}) => {
395
447
  quote: null,
396
448
  quoteError: null,
397
449
  twoFactorCode: "",
450
+ burnConsent: false,
398
451
  withdrawal: null,
399
452
  });
400
453
  void actions.refreshContext();
@@ -311,4 +311,59 @@ export const ar = {
311
311
  "fiat.in.statusFailed": "لم تنجح عملية الدفع",
312
312
  "fiat.in.statusExpired": "انتهت مهلة الدفع",
313
313
  "fiat.in.scanQr": "امسح الرمز في تطبيق البنك لإتمام الدفع.",
314
+ "promo.toggle": "هل لديك رمز ترويجي؟",
315
+ "promo.label": "الرمز الترويجي",
316
+ "promo.placeholder": "أدخل الرمز",
317
+ "promo.apply": "تطبيق",
318
+ "promo.checking": "جارٍ التحقق…",
319
+ "promo.hide": "إخفاء الرمز الترويجي",
320
+ "promo.applied": "مُطبَّق",
321
+ "promo.remove": "إزالة الرمز",
322
+ "promo.headlinePercent": "+{pct}% على إيداعك",
323
+ "promo.headlinePercentCap": "+{pct}% على إيداعك، حتى {max}",
324
+ "promo.headlineFixed": "+{amount} على إيداعك",
325
+ "promo.minDeposit": "الحد الأدنى للإيداع",
326
+ "promo.maxDeposit": "تُحتسب المكافأة على الإيداع حتى",
327
+ "promo.expiresIn": "الرمز صالح لمدة",
328
+ "promo.wager": "حقّق حجم تداول يساوي {multiplier}× المكافأة خلال {duration} من إضافتها.",
329
+ "promo.wagerNoDeadline": "حقّق حجم تداول يساوي {multiplier}× المكافأة بعد إضافتها.",
330
+ "promo.unlockAnytime": "يمكنك السحب في أي وقت.",
331
+ "promo.unlockPartial": "يُفتح السحب بعد تحقيق {pct}% من هذا الحجم.",
332
+ "promo.unlockFull": "يُفتح السحب بعد تحقيق الحجم بالكامل.",
333
+ "promo.burn": "السحب يُلغي ما تبقّى من المكافأة في تلك اللحظة.",
334
+ "promo.firstDepositOnly": "للإيداع الأول فقط.",
335
+ "promo.activeTitle": "المكافأة {code}",
336
+ "promo.activeProgress": "الحجم {wagered} من {goal}",
337
+ "promo.activeLeft": "متبقٍ {duration}",
338
+ "promo.activeBurnPending": "ستُغلق المكافأة عند إغلاق مراكزك المفتوحة.",
339
+ "promo.reason.BONUS_CODE_NOT_FOUND": "هذا الرمز غير موجود.",
340
+ "promo.reason.BONUS_INACTIVE": "هذا الرمز غير مفعّل.",
341
+ "promo.reason.BONUS_EXPIRED": "انتهت صلاحية هذا الرمز.",
342
+ "promo.reason.USAGE_LIMIT_REACHED": "استُنفد عدد مرات استخدام هذا الرمز.",
343
+ "promo.reason.USER_LIMIT_REACHED": "لقد استخدمت هذا الرمز من قبل.",
344
+ "promo.reason.FIRST_DEPOSIT_ONLY": "هذا الرمز للإيداع الأول فقط.",
345
+ "promo.reason.MIN_DEPOSIT_NOT_MET": "الإيداع أقل من الحد الأدنى لهذا الرمز.",
346
+ "promo.reason.ACTIVE_BONUS_EXISTS": "لديك مكافأة نشطة بالفعل.",
347
+ "promo.reason.SYSTEM_DISABLED": "الرموز الترويجية غير متاحة حاليًا.",
348
+ "promo.reason.UNKNOWN": "لا يمكن تطبيق هذا الرمز.",
349
+ "duration.days": "{count} ي",
350
+ "duration.hours": "{count} س",
351
+ "duration.minutes": "{count} د",
352
+ "withdrawBonus.lockedTitle": "السحب مقفل بسبب المكافأة",
353
+ "withdrawBonus.lockedPartial": "يُفتح السحب عند تداول {unlock}% من حجم المكافأة.",
354
+ "withdrawBonus.lockedFull": "يُفتح السحب عند تداول حجم المكافأة بالكامل.",
355
+ "withdrawBonus.progress": "تم تداول {progress}% من {unlock}% المطلوبة",
356
+ "withdrawBonus.pendingTitle": "جارٍ إغلاق المكافأة",
357
+ "withdrawBonus.pendingBody": "أغلق مراكزك المفتوحة. ستُلغى المكافأة عند إغلاقها، وبعدها يمكنك السحب.",
358
+ "withdrawBonus.burnTitle": "السحب يُلغي المكافأة",
359
+ "withdrawBonus.burnBody": "سيُلغى ما تبقّى من المكافأة في رصيدك، حتى {amount}، مع هذا السحب.",
360
+ "withdrawBonus.burnBodyGeneric": "سيُلغى ما تبقّى من المكافأة في رصيدك مع هذا السحب.",
361
+ "withdrawBonus.consent": "أفهم أن ما تبقّى من المكافأة سيُلغى",
362
+ "error.PROMO_CODE_REJECTED": "لا يمكن تطبيق هذا الرمز الترويجي.",
363
+ "error.BONUS_WITHDRAWAL_LOCKED": "السحب مقفل حتى تحقيق حجم تداول المكافأة.",
364
+ "error.BONUS_WITHDRAWAL_LOCKED_PCT": "يُفتح السحب عند {unlock}% من حجم المكافأة. وصلت إلى {progress}%.",
365
+ "error.BONUS_BURN_CONFIRM_REQUIRED": "أكّد أن السحب سيُلغي ما تبقّى من المكافأة.",
366
+ "error.BONUS_BURN_PENDING": "لا تزال المكافأة قيد الإغلاق. أغلق مراكزك المفتوحة أولًا.",
367
+ "error.BONUS_CHANGED": "تغيّرت مكافأتك. راجع الشروط وحاول مرة أخرى.",
368
+ "error.OPEN_POSITIONS": "أغلق مراكزك المفتوحة قبل السحب.",
314
369
  };
@@ -1,4 +1,5 @@
1
1
  import { formatMoney } from "../money.js";
2
+ import { promoReasonKey, wholePercent } from "../rules/bonus.js";
2
3
  import { enUi } from "./en-ui.js";
3
4
  export const LOCALES = ["en", "ru", "de", "ua", "es", "fr", "hi", "tr", "ar", "it", "cs"];
4
5
  const INTL_LOCALE = {
@@ -80,6 +81,17 @@ export const errorMessage = (t, error, locale = "en") => {
80
81
  return (details.field === "file" && details.max) || details.field === "file_base64"
81
82
  ? t("error.FILE_TOO_LARGE")
82
83
  : t("error.VALIDATION_FAILED");
84
+ case "PROMO_CODE_REJECTED":
85
+ return t(promoReasonKey(details.reason));
86
+ case "BONUS_WITHDRAWAL_LOCKED": {
87
+ const unlock = details.unlockPct;
88
+ return unlock !== undefined && unlock > 0 && unlock < 100 && details.progressPct !== undefined
89
+ ? t("error.BONUS_WITHDRAWAL_LOCKED_PCT", {
90
+ unlock: wholePercent(unlock),
91
+ progress: wholePercent(details.progressPct),
92
+ })
93
+ : t("error.BONUS_WITHDRAWAL_LOCKED");
94
+ }
83
95
  default:
84
96
  return t(`error.${code}`);
85
97
  }