@usions/sdk 2.13.0 → 2.14.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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@usions/sdk",
3
- "version": "2.13.0",
3
+ "version": "2.14.0",
4
4
  "description": "Usion Mini App SDK for iframe games and services",
5
5
  "type": "module",
6
6
  "main": "src/modules/index.js",
package/src/browser.js CHANGED
@@ -69,7 +69,7 @@ var Usion = (function () {
69
69
  * Core Usion object with init, _post, _request
70
70
  */
71
71
  const core = {
72
- version: '2.13.0', // injected from package.json at build
72
+ version: '2.14.0', // injected from package.json at build
73
73
  config: {},
74
74
  _initialized: false,
75
75
  _initCallback: null,
@@ -426,6 +426,13 @@ var Usion = (function () {
426
426
  _balance: null,
427
427
  _balanceChangeHandler: null,
428
428
 
429
+ // Payment timing knobs (overridable, mainly for tests). The defaults are
430
+ // the production values.
431
+ _paymentTimeoutMs: 60000, // wait this long for the direct PAYMENT_SUCCESS
432
+ _recoveryPollMs: 2000, // gap between result-recovery re-queries
433
+ _recoveryMaxPolls: 10, // bounded recovery window after the timeout
434
+ _recoveryQueryTimeoutMs: 8000, // per re-query round-trip budget
435
+
429
436
  /**
430
437
  * Get current wallet balance
431
438
  * @returns {Promise<number>} Balance in credits
@@ -456,20 +463,69 @@ var Usion = (function () {
456
463
  },
457
464
 
458
465
  /**
459
- * Request payment from user with balance check
466
+ * Request payment from user with balance check.
467
+ *
468
+ * The charge is debited immediately by the host (escrow); the resolved
469
+ * value carries a `receiptToken` the mini-app server later settles/refunds.
470
+ *
471
+ * Reliability: if the host's PAYMENT_SUCCESS message is lost (network blip,
472
+ * backgrounded tab, race) the user may ALREADY be charged. Instead of
473
+ * rejecting at the timeout, this re-queries the host for the result and
474
+ * recovers the receipt token — so a dropped message never strands a paid
475
+ * charge. Pass `idempotencyKey` to additionally guarantee that any retry of
476
+ * the SAME intent reuses the SAME charge (the host + backend dedupe on it),
477
+ * so the user can never be charged twice even across reloads.
478
+ *
460
479
  * @param {number} amount - Credit amount to charge
461
480
  * @param {string} reason - Description shown to user
462
- * @param {object} data - Optional additional data
481
+ * @param {object} [data] - Optional options/payload. `data.idempotencyKey`
482
+ * (string) makes the charge safely retryable. Any other fields are
483
+ * forwarded to the host verbatim (backward compatible).
463
484
  * @returns {Promise} Resolves on payment success, rejects on failure
464
485
  */
465
486
  requestPayment: function(amount, reason, data) {
466
487
  const self = this;
467
488
 
489
+ const opts = (data && typeof data === 'object') ? data : null;
490
+ const idempotencyKey = (opts && typeof opts.idempotencyKey === 'string' && opts.idempotencyKey)
491
+ ? opts.idempotencyKey
492
+ : null;
493
+
468
494
  return new Promise(function(resolve, reject) {
469
495
  const requestId = getNextRequestId();
470
- const timeoutMs = 60000;
496
+ const timeoutMs = self._paymentTimeoutMs || 60000;
497
+ let settled = false;
498
+ let recoverTimer = null;
499
+
500
+ function cleanup() {
501
+ clearTimeout(timer);
502
+ if (recoverTimer) clearTimeout(recoverTimer);
503
+ window.removeEventListener('message', handler);
504
+ }
471
505
 
472
- // Listen for response
506
+ function finishResolve(response) {
507
+ if (settled) return;
508
+ settled = true;
509
+ cleanup();
510
+ // Update cached balance from the authoritative new balance, else
511
+ // best-effort subtract (no-op if balance is unknown).
512
+ if (response && response.newBalance !== undefined) {
513
+ self._balance = response.newBalance;
514
+ } else if (self._balance !== null) {
515
+ self._balance -= amount;
516
+ }
517
+ resolve(response);
518
+ }
519
+
520
+ function finishReject(error) {
521
+ if (settled) return;
522
+ settled = true;
523
+ cleanup();
524
+ reject(error);
525
+ }
526
+
527
+ // Direct response from the host. Kept registered through the recovery
528
+ // window so a late PAYMENT_SUCCESS still resolves.
473
529
  function handler(event) {
474
530
  // Only honor payment results from the trusted host shell — a forged
475
531
  // PAYMENT_SUCCESS must never resolve this promise.
@@ -483,32 +539,97 @@ var Usion = (function () {
483
539
  }
484
540
 
485
541
  // Only accept responses for this specific payment request.
486
- if (response._requestId !== requestId) {
542
+ if (!response || response._requestId !== requestId) {
487
543
  return;
488
544
  }
489
545
 
490
546
  if (response.type === 'PAYMENT_SUCCESS') {
491
- clearTimeout(timer);
492
- window.removeEventListener('message', handler);
493
- // Update cached balance
494
- if (response.newBalance !== undefined) {
495
- self._balance = response.newBalance;
496
- } else if (self._balance !== null) {
497
- self._balance -= amount;
498
- }
499
- resolve(response);
547
+ finishResolve(response);
500
548
  } else if (response.type === 'PAYMENT_FAILED') {
501
- clearTimeout(timer);
502
- window.removeEventListener('message', handler);
503
- reject(new Error(response.reason || 'Payment failed'));
549
+ finishReject(new Error(response.reason || 'Payment failed'));
550
+ }
551
+ }
552
+
553
+ // After the direct deadline, re-query the host for this payment's
554
+ // result instead of rejecting.
555
+ // succeeded -> resolve with the recovered token
556
+ // failed -> reject
557
+ // pending -> the modal is STILL OPEN / charge still in progress, so
558
+ // the charge is fully recoverable: keep waiting (do NOT
559
+ // count this toward the give-up cap). A slow user who
560
+ // confirms minutes later still resolves — via the next
561
+ // 'succeeded' poll or the direct handler, which stays
562
+ // registered. Without this, a charge made after we gave
563
+ // up would be stranded (the original bug, shifted to the
564
+ // slow-confirm case).
565
+ // none/other -> likely no charge; confirm twice then reject cleanly so
566
+ // a fresh requestPayment is safe.
567
+ // The bounded cap only governs the give-up paths (none-streak and a host
568
+ // that never answers the query at all, e.g. an older host shell).
569
+ function recoverPaymentResult() {
570
+ const pollMs = self._recoveryPollMs || 2000;
571
+ const maxPolls = self._recoveryMaxPolls || 10;
572
+ const queryTimeoutMs = self._recoveryQueryTimeoutMs || 8000;
573
+ let noneStreak = 0;
574
+ let errorStreak = 0;
575
+
576
+ function poll() {
577
+ if (settled) return;
578
+ Usion._request('PAYMENT_RESULT_QUERY', {
579
+ paymentRequestId: requestId,
580
+ idempotencyKey: idempotencyKey || undefined,
581
+ }, queryTimeoutMs).then(function(res) {
582
+ if (settled) return;
583
+ const status = res && res.status;
584
+ if (status === 'succeeded') {
585
+ finishResolve({
586
+ type: 'PAYMENT_SUCCESS',
587
+ _requestId: requestId,
588
+ newBalance: res.newBalance,
589
+ transactionId: res.transactionId,
590
+ receiptToken: res.receiptToken,
591
+ });
592
+ return;
593
+ }
594
+ if (status === 'failed') {
595
+ finishReject(new Error(res.reason || 'Payment failed'));
596
+ return;
597
+ }
598
+ if (status === 'pending') {
599
+ // Charge still recoverable — keep waiting, no give-up budget.
600
+ noneStreak = 0;
601
+ errorStreak = 0;
602
+ recoverTimer = setTimeout(poll, pollMs);
603
+ return;
604
+ }
605
+ // 'none' or unknown — host is confident no charge exists. Confirm
606
+ // twice (guards a host that simply hasn't recorded yet) then reject.
607
+ errorStreak = 0;
608
+ noneStreak += 1;
609
+ if (noneStreak >= 2) {
610
+ finishReject(new Error('Payment confirmation timeout'));
611
+ return;
612
+ }
613
+ recoverTimer = setTimeout(poll, pollMs);
614
+ }).catch(function() {
615
+ // Host didn't answer the query (e.g. an older host shell without
616
+ // PAYMENT_RESULT_QUERY support). Retry a bounded number of times,
617
+ // then fall back to the original timeout rejection.
618
+ if (settled) return;
619
+ errorStreak += 1;
620
+ if (errorStreak >= maxPolls) {
621
+ finishReject(new Error('Payment confirmation timeout'));
622
+ return;
623
+ }
624
+ recoverTimer = setTimeout(poll, pollMs);
625
+ });
504
626
  }
627
+
628
+ poll();
505
629
  }
506
630
 
507
631
  window.addEventListener('message', handler);
508
- const timer = setTimeout(function() {
509
- window.removeEventListener('message', handler);
510
- reject(new Error('Payment confirmation timeout'));
511
- }, timeoutMs);
632
+ const timer = setTimeout(recoverPaymentResult, timeoutMs);
512
633
 
513
634
  // Send payment request
514
635
  Usion._post({
@@ -516,7 +637,8 @@ var Usion = (function () {
516
637
  _requestId: requestId,
517
638
  amount: amount,
518
639
  reason: reason,
519
- data: data
640
+ data: data,
641
+ idempotencyKey: idempotencyKey || undefined,
520
642
  });
521
643
  });
522
644
  },
@@ -12,6 +12,13 @@ export function createWalletModule(Usion) {
12
12
  _balance: null,
13
13
  _balanceChangeHandler: null,
14
14
 
15
+ // Payment timing knobs (overridable, mainly for tests). The defaults are
16
+ // the production values.
17
+ _paymentTimeoutMs: 60000, // wait this long for the direct PAYMENT_SUCCESS
18
+ _recoveryPollMs: 2000, // gap between result-recovery re-queries
19
+ _recoveryMaxPolls: 10, // bounded recovery window after the timeout
20
+ _recoveryQueryTimeoutMs: 8000, // per re-query round-trip budget
21
+
15
22
  /**
16
23
  * Get current wallet balance
17
24
  * @returns {Promise<number>} Balance in credits
@@ -42,20 +49,69 @@ export function createWalletModule(Usion) {
42
49
  },
43
50
 
44
51
  /**
45
- * Request payment from user with balance check
52
+ * Request payment from user with balance check.
53
+ *
54
+ * The charge is debited immediately by the host (escrow); the resolved
55
+ * value carries a `receiptToken` the mini-app server later settles/refunds.
56
+ *
57
+ * Reliability: if the host's PAYMENT_SUCCESS message is lost (network blip,
58
+ * backgrounded tab, race) the user may ALREADY be charged. Instead of
59
+ * rejecting at the timeout, this re-queries the host for the result and
60
+ * recovers the receipt token — so a dropped message never strands a paid
61
+ * charge. Pass `idempotencyKey` to additionally guarantee that any retry of
62
+ * the SAME intent reuses the SAME charge (the host + backend dedupe on it),
63
+ * so the user can never be charged twice even across reloads.
64
+ *
46
65
  * @param {number} amount - Credit amount to charge
47
66
  * @param {string} reason - Description shown to user
48
- * @param {object} data - Optional additional data
67
+ * @param {object} [data] - Optional options/payload. `data.idempotencyKey`
68
+ * (string) makes the charge safely retryable. Any other fields are
69
+ * forwarded to the host verbatim (backward compatible).
49
70
  * @returns {Promise} Resolves on payment success, rejects on failure
50
71
  */
51
72
  requestPayment: function(amount, reason, data) {
52
73
  const self = this;
53
74
 
75
+ const opts = (data && typeof data === 'object') ? data : null;
76
+ const idempotencyKey = (opts && typeof opts.idempotencyKey === 'string' && opts.idempotencyKey)
77
+ ? opts.idempotencyKey
78
+ : null;
79
+
54
80
  return new Promise(function(resolve, reject) {
55
81
  const requestId = getNextRequestId();
56
- const timeoutMs = 60000;
82
+ const timeoutMs = self._paymentTimeoutMs || 60000;
83
+ let settled = false;
84
+ let recoverTimer = null;
85
+
86
+ function cleanup() {
87
+ clearTimeout(timer);
88
+ if (recoverTimer) clearTimeout(recoverTimer);
89
+ window.removeEventListener('message', handler);
90
+ }
91
+
92
+ function finishResolve(response) {
93
+ if (settled) return;
94
+ settled = true;
95
+ cleanup();
96
+ // Update cached balance from the authoritative new balance, else
97
+ // best-effort subtract (no-op if balance is unknown).
98
+ if (response && response.newBalance !== undefined) {
99
+ self._balance = response.newBalance;
100
+ } else if (self._balance !== null) {
101
+ self._balance -= amount;
102
+ }
103
+ resolve(response);
104
+ }
57
105
 
58
- // Listen for response
106
+ function finishReject(error) {
107
+ if (settled) return;
108
+ settled = true;
109
+ cleanup();
110
+ reject(error);
111
+ }
112
+
113
+ // Direct response from the host. Kept registered through the recovery
114
+ // window so a late PAYMENT_SUCCESS still resolves.
59
115
  function handler(event) {
60
116
  // Only honor payment results from the trusted host shell — a forged
61
117
  // PAYMENT_SUCCESS must never resolve this promise.
@@ -69,32 +125,97 @@ export function createWalletModule(Usion) {
69
125
  }
70
126
 
71
127
  // Only accept responses for this specific payment request.
72
- if (response._requestId !== requestId) {
128
+ if (!response || response._requestId !== requestId) {
73
129
  return;
74
130
  }
75
131
 
76
132
  if (response.type === 'PAYMENT_SUCCESS') {
77
- clearTimeout(timer);
78
- window.removeEventListener('message', handler);
79
- // Update cached balance
80
- if (response.newBalance !== undefined) {
81
- self._balance = response.newBalance;
82
- } else if (self._balance !== null) {
83
- self._balance -= amount;
84
- }
85
- resolve(response);
133
+ finishResolve(response);
86
134
  } else if (response.type === 'PAYMENT_FAILED') {
87
- clearTimeout(timer);
88
- window.removeEventListener('message', handler);
89
- reject(new Error(response.reason || 'Payment failed'));
135
+ finishReject(new Error(response.reason || 'Payment failed'));
136
+ }
137
+ }
138
+
139
+ // After the direct deadline, re-query the host for this payment's
140
+ // result instead of rejecting.
141
+ // succeeded -> resolve with the recovered token
142
+ // failed -> reject
143
+ // pending -> the modal is STILL OPEN / charge still in progress, so
144
+ // the charge is fully recoverable: keep waiting (do NOT
145
+ // count this toward the give-up cap). A slow user who
146
+ // confirms minutes later still resolves — via the next
147
+ // 'succeeded' poll or the direct handler, which stays
148
+ // registered. Without this, a charge made after we gave
149
+ // up would be stranded (the original bug, shifted to the
150
+ // slow-confirm case).
151
+ // none/other -> likely no charge; confirm twice then reject cleanly so
152
+ // a fresh requestPayment is safe.
153
+ // The bounded cap only governs the give-up paths (none-streak and a host
154
+ // that never answers the query at all, e.g. an older host shell).
155
+ function recoverPaymentResult() {
156
+ const pollMs = self._recoveryPollMs || 2000;
157
+ const maxPolls = self._recoveryMaxPolls || 10;
158
+ const queryTimeoutMs = self._recoveryQueryTimeoutMs || 8000;
159
+ let noneStreak = 0;
160
+ let errorStreak = 0;
161
+
162
+ function poll() {
163
+ if (settled) return;
164
+ Usion._request('PAYMENT_RESULT_QUERY', {
165
+ paymentRequestId: requestId,
166
+ idempotencyKey: idempotencyKey || undefined,
167
+ }, queryTimeoutMs).then(function(res) {
168
+ if (settled) return;
169
+ const status = res && res.status;
170
+ if (status === 'succeeded') {
171
+ finishResolve({
172
+ type: 'PAYMENT_SUCCESS',
173
+ _requestId: requestId,
174
+ newBalance: res.newBalance,
175
+ transactionId: res.transactionId,
176
+ receiptToken: res.receiptToken,
177
+ });
178
+ return;
179
+ }
180
+ if (status === 'failed') {
181
+ finishReject(new Error(res.reason || 'Payment failed'));
182
+ return;
183
+ }
184
+ if (status === 'pending') {
185
+ // Charge still recoverable — keep waiting, no give-up budget.
186
+ noneStreak = 0;
187
+ errorStreak = 0;
188
+ recoverTimer = setTimeout(poll, pollMs);
189
+ return;
190
+ }
191
+ // 'none' or unknown — host is confident no charge exists. Confirm
192
+ // twice (guards a host that simply hasn't recorded yet) then reject.
193
+ errorStreak = 0;
194
+ noneStreak += 1;
195
+ if (noneStreak >= 2) {
196
+ finishReject(new Error('Payment confirmation timeout'));
197
+ return;
198
+ }
199
+ recoverTimer = setTimeout(poll, pollMs);
200
+ }).catch(function() {
201
+ // Host didn't answer the query (e.g. an older host shell without
202
+ // PAYMENT_RESULT_QUERY support). Retry a bounded number of times,
203
+ // then fall back to the original timeout rejection.
204
+ if (settled) return;
205
+ errorStreak += 1;
206
+ if (errorStreak >= maxPolls) {
207
+ finishReject(new Error('Payment confirmation timeout'));
208
+ return;
209
+ }
210
+ recoverTimer = setTimeout(poll, pollMs);
211
+ });
90
212
  }
213
+
214
+ poll();
91
215
  }
92
216
 
93
217
  window.addEventListener('message', handler);
94
- const timer = setTimeout(function() {
95
- window.removeEventListener('message', handler);
96
- reject(new Error('Payment confirmation timeout'));
97
- }, timeoutMs);
218
+ const timer = setTimeout(recoverPaymentResult, timeoutMs);
98
219
 
99
220
  // Send payment request
100
221
  Usion._post({
@@ -102,7 +223,8 @@ export function createWalletModule(Usion) {
102
223
  _requestId: requestId,
103
224
  amount: amount,
104
225
  reason: reason,
105
- data: data
226
+ data: data,
227
+ idempotencyKey: idempotencyKey || undefined,
106
228
  });
107
229
  });
108
230
  },
package/types/index.d.ts CHANGED
@@ -43,6 +43,17 @@ export interface PaymentResponse {
43
43
  transactionId?: string;
44
44
  }
45
45
 
46
+ export interface PaymentOptions {
47
+ /**
48
+ * Optional idempotency key. When set, the host + backend dedupe on it so any
49
+ * retry of the SAME intent (network error, reload, double-tap) reuses the
50
+ * SAME charge instead of debiting again, and returns the same receiptToken.
51
+ * Omit for the legacy one-shot behavior.
52
+ */
53
+ idempotencyKey?: string;
54
+ [key: string]: any;
55
+ }
56
+
46
57
  // ─── User ────────────────────────────────────────────────────────
47
58
 
48
59
  export interface UserProfile {
@@ -82,7 +93,7 @@ export interface FileStorageModule {
82
93
  export interface WalletModule {
83
94
  getBalance(): Promise<number>;
84
95
  hasCredits(amount: number): Promise<boolean>;
85
- requestPayment(amount: number, reason: string, data?: Record<string, any>): Promise<PaymentResponse>;
96
+ requestPayment(amount: number, reason: string, data?: PaymentOptions): Promise<PaymentResponse>;
86
97
  onBalanceChange(callback: (balance: number) => void): UnsubscribeFn;
87
98
  }
88
99
 
@@ -768,7 +779,7 @@ export interface UsionSDK {
768
779
  getLaunchParams(): { path: string | null; ref: string | null; roomId: string | null };
769
780
 
770
781
  // Payments
771
- requestPayment(amount: number, reason: string, data?: Record<string, any>): Promise<PaymentResponse>;
782
+ requestPayment(amount: number, reason: string, data?: PaymentOptions): Promise<PaymentResponse>;
772
783
 
773
784
  // Service communication
774
785
  submit(data: Record<string, any>): void;