@stridge/pay-kit 0.1.0-alpha.1 → 0.1.0-alpha.2

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/README.md CHANGED
@@ -1,340 +1,81 @@
1
1
  # @stridge/pay-kit
2
2
 
3
- Staging-only. Pin an exact version. Use the newest kit.
3
+ Put a Stridge Pay card in your React page. Checkout opens in the Stridge hub inside your page, or in a Stridge window when the browser needs one. The money goes to the destination that Stridge saved for your app.
4
4
 
5
- Put a Stridge payment in your React page. `PayElement` shows a pay card for one order or one deposit. When the customer pays, the Stridge window opens on the Stridge origin. Sign-in and signing run there, and the private keys never leave it. The account hook gives your page the customer's address after a sign-in, and the signature of a message that your page asks the customer to sign. The money goes to a destination saved for your app on the Stridge server, not to an address that your page chooses.
5
+ **Status:** alpha. The kit connects to the Stridge staging hub, and real coins move on it. Install an exact version, and upgrade to each new release on purpose.
6
6
 
7
- ## Read this first: the page event is not proof of payment
7
+ ## Install
8
+
9
+ ```sh
10
+ pnpm add --save-exact @stridge/pay-kit
11
+ ```
8
12
 
9
- `PayElement` tells your page what the Stridge window saw, through one `onEvent` callback. Each event has a `type`:
13
+ > **Warning:** Packages with near names and no `@stridge/` scope exist on the public registry. They are not ours. Install only `@stridge/pay-kit`.
10
14
 
11
- | `type` | What it means |
12
- | --- | --- |
13
- | `payment.observed` | The window saw a delivery for this payment. It carries `referenceId`, `mode`, `amount`, `method`, `receiptCode`, `transactionHash` (or `null`), `received` and `short`. `short` is `true` when less than the payment's target arrived. A short delivery does not pay the order. |
14
- | `checkout.closed` | The backend's checkout for this payment reached a final state: `completed`, `failed`, `canceled` or `expired`. It carries `approvedBaseUnits`, `deliveredBaseUnits` and `destinationTxs`. A `completed` checkout can still be short, and `destinationTxs` can be empty. One payment can have more than one checkout. |
15
- | `payment.on_hold` | The payment needs Stridge support and stays locked. Show the customer its `receiptCode`. A new order needs a new `referenceId`. |
16
- | `payment.unconfirmed` | The customer's wallet may have sent, and the window cannot confirm it yet. Never retry this `referenceId`. Check it on your server. |
17
- | `request.failed` | A sign-in or a fund request that the card ran for the customer failed. Read `error.code`. It says nothing about the payment. |
15
+ The kit needs React 19 and React DOM 19 as peer dependencies.
18
16
 
19
- No event proves that money arrived. The event runs in the customer's browser, so any script on the page can call your handler with any values. An event can also come again after a reload. Stridge gives your server no status read and no webhook for these payments today.
17
+ ## Check each payment on your server
20
18
 
21
- So your server must check each payment on the chain before you ship the order. Do these steps:
19
+ No event from the kit proves that money arrived. The events run in the customer's browser, so any script on the page can call your handler with any values. Stridge gives your server no status read and no webhook today. Check each payment on the chain before you ship the order:
22
20
 
23
- 1. Keep a copy of your saved destination in your server's configuration: the chain, the coin's contract address, the coin's decimals and your receiving address. Use the same values that Stridge saved for your app.
24
- 2. In `onEvent`, send the `referenceId` and the transaction hashes to your server. A `payment.observed` event has `transactionHash`. A `checkout.closed` event has `destinationTxs`.
21
+ 1. Keep your saved destination in your server's configuration: the chain, the coin's contract address, the coin's decimals and your receiving address.
22
+ 2. In `onEvent`, send the `referenceId` and the transaction hashes to your server.
25
23
  3. On your server, claim each hash for one order, once. Refuse a hash that another order already claimed.
26
24
  4. Read each transaction's receipt from the destination chain. Skip a transaction that did not succeed.
27
- 5. In the receipt, add up the ERC-20 `Transfer` logs whose contract is your coin and whose recipient is your address.
28
- 6. Convert the order's price to the coin's base units: the price in USD times 10 to the power of the coin's decimals. USDC and USDT on BSC have 18 decimals. Each other supported coin has 6.
25
+ 5. Add up the ERC-20 `Transfer` logs whose contract is your coin and whose recipient is your address.
26
+ 6. Convert the price to the coin's base units: the price in USD times 10 to the power of the coin's decimals. USDC and USDT on BSC have 18 decimals. Each other supported coin has 6.
29
27
  7. Mark the order paid only when the sum is equal to or more than the price.
30
28
 
31
- A delivery can be less than the price, because fees come off on some ways to pay. The event then has `short: true`. Your own policy decides what to do with a short payment.
32
-
33
- An event can carry no delivery hash, or only some of them. A Manual deposit can arrive as several transfers, and its `payment.observed` event names only the last one in `transactionHash`. So when the hashes you verified do not cover the price, keep the order pending. Then find each transfer to your address in a block explorer and match it to the order by hand, also when `transactionHash` is not `null`. Never use the event's `received` amount to fill the gap.
34
-
35
- This check has a weak point. A transaction hash is public, and nothing on the chain ties a transfer to your `referenceId`. A stranger can send another customer's hash for a different order of the same amount, before that customer's page sends it. The first claim wins. Examine each refused claim by hand.
36
-
37
- Later stages are not available yet. First, the backend will refuse a destination that your app did not save, and your server will read a payment's status by your own `referenceId`. After that, your server will create each payment.
38
-
39
- ## Install
40
-
41
- ```sh
42
- pnpm add --save-exact @stridge/pay-kit
43
- ```
44
-
45
- > **Warning:** Packages with near names and no `@stridge/` scope exist on the public registry. They are not ours. Install only `@stridge/pay-kit`.
46
-
47
- The kit needs React 19 and React DOM 19 as peer dependencies. It installs `@stridge/pay-sdk` as its own dependency. You import no stylesheet.
29
+ A transaction hash is public, and nothing on the chain ties a transfer to your `referenceId`. A stranger can send another customer's hash for an order of the same amount, and the first claim wins. Examine each refused claim by hand. When the hashes you checked do not cover the price, keep the order pending and match the transfers to your address in a block explorer.
48
30
 
49
31
  ## Quick start
50
32
 
51
- `PayProvider` and `PayElement` are client components. Put them in a file that starts with `"use client"` when you use the Next.js App Router.
33
+ `PayProvider` and `PayElement` are client components. In the Next.js App Router, put them in a file that starts with `"use client"`.
52
34
 
53
35
  ```tsx
54
36
  "use client";
55
37
 
56
38
  import { PayElement, PayProvider, type PayEvent } from "@stridge/pay-kit";
57
39
 
58
- /** Sends the page's report to your server, which checks the payment on the chain. */
59
- function reportToServer(referenceId: string, hashes: readonly string[]): void {
60
- void fetch("/api/orders/check", {
61
- method: "POST",
62
- headers: { "Content-Type": "application/json" },
63
- body: JSON.stringify({ referenceId, hashes }),
64
- });
40
+ /** The delivery hashes that an event names. */
41
+ function hashesOf(event: PayEvent): readonly string[] {
42
+ if (event.type === "checkout.closed") return event.destinationTxs;
43
+ if (event.type === "payment.observed" && event.transactionHash !== null) return [event.transactionHash];
44
+ return [];
65
45
  }
66
46
 
47
+ /** Sends the hashes to your server, which checks the payment on the chain. */
67
48
  function handlePayEvent(event: PayEvent): void {
68
- switch (event.type) {
69
- case "payment.observed":
70
- reportToServer(event.referenceId, event.transactionHash === null ? [] : [event.transactionHash]);
71
- break;
72
- case "checkout.closed":
73
- reportToServer(event.referenceId, event.destinationTxs);
74
- break;
75
- case "payment.on_hold":
76
- case "payment.unconfirmed":
77
- console.info(`Order ${event.referenceId} needs a check. Receipt code: ${event.receiptCode}`);
78
- break;
79
- case "request.failed":
80
- console.info(`The ${event.request} request failed: ${event.error.code}`);
81
- break;
82
- }
49
+ if (event.type !== "payment.observed" && event.type !== "checkout.closed") return;
50
+ void fetch("/api/orders/check", {
51
+ method: "POST",
52
+ headers: { "Content-Type": "application/json" },
53
+ body: JSON.stringify({ referenceId: event.referenceId, hashes: hashesOf(event) }),
54
+ });
83
55
  }
84
56
 
85
57
  export function Checkout({ order }: { order: { id: string; total: string } }) {
86
- return (
87
- <PayProvider appId="app_…" environment="sandbox">
88
- <PayElement referenceId={order.id} amount={order.total} description="Blue shirt" onEvent={handlePayEvent} />
89
- </PayProvider>
90
- );
58
+ return (
59
+ <PayProvider appId="app_…">
60
+ <PayElement referenceId={order.id} amount={order.total} onEvent={handlePayEvent} />
61
+ </PayProvider>
62
+ );
91
63
  }
92
64
  ```
93
65
 
94
- Replace `app_…` with the app id that Stridge issued for your app, and copy it exactly. It is `app_` followed by a 26-character uppercase ULID. Stridge must also register your page's origin for that app id.
95
-
96
- Keep `referenceId` the same for one order. The same `referenceId` with another mode, amount or description is refused, so a new order needs a new `referenceId`. `amount` is a decimal string in USD, with at most two decimals, more than 0 and at most `100000.00`.
97
-
98
- ### A deposit where the customer chooses the amount
99
-
100
- Set `mode="deposit"` and leave `amount` out. The window then asks "How much?".
101
-
102
- ```tsx
103
- <PayElement referenceId={topUp.id} mode="deposit" description="Account top-up" onEvent={handlePayEvent} />
104
- ```
105
-
106
- You can add `min` and `max` (decimal strings, as `amount`). `firstStep="method"` opens the window on the ways to pay and asks the amount after. A deposit with a fixed `amount` takes no `min`, `max` or `firstStep`.
107
-
108
- ### The account hook
109
-
110
- The customer's Stridge sign-in, signing and Fund are in a second entry, `@stridge/pay-kit/account`. Call `usePayAccount` in a component inside `PayProvider`.
111
-
112
- ```tsx
113
- "use client";
114
-
115
- import { isPayError } from "@stridge/pay-kit";
116
- import { usePayAccount } from "@stridge/pay-kit/account";
117
-
118
- export function SignInButton() {
119
- const account = usePayAccount();
120
- if (account.status === "signed-in") return <p>{account.evmAddress}</p>;
121
- return (
122
- <button
123
- type="button"
124
- disabled={account.busy}
125
- onClick={() => {
126
- account.signIn().catch((error: unknown) => {
127
- if (!isPayError(error, "cancelled")) console.error(error);
128
- });
129
- }}
130
- >
131
- Sign in
132
- </button>
133
- );
134
- }
135
- ```
136
-
137
- Call `signIn`, `sign`, `signOut`, `disconnect` and `fund` directly in the customer's click, before any `await`. A request can open the Stridge window, and the browser blocks a window that does not open from a click.
138
-
139
- - `signIn()` resolves with `{ evmAddress }`.
140
- - `sign(message)` shows the Stridge confirm screen and resolves with the signature. With no session, it signs the customer in first.
141
- - `signOut()` ends the Stridge session in this browser, for every app that shares it. `disconnect()` removes this app only.
142
- - `fund({ start })` opens Fund on the `"fund"` or `"home"` screen. It needs a signed-in session, and it resolves when the customer closes Fund.
143
-
144
- ## Props
145
-
146
- ### `PayProvider`
147
-
148
- | Prop | Type | Required | Meaning |
149
- | --- | --- | --- | --- |
150
- | `appId` | `string` | Yes | The app id that Stridge issued for your app. A change starts a new provider lifetime. |
151
- | `environment` | `"sandbox" \| "live"` | Yes | The Stridge environment to connect to. See [Environments](#environments). |
152
- | `children` | `ReactNode` | Yes | Your tree. `PayElement` and the hooks work anywhere inside it. |
153
- | `theme` | `"dark" \| "light" \| "system"` | No | The colour scheme of the card and the Stridge window. `"system"` follows the browser. The default is `"dark"`. |
154
- | `onConnected` | `(event: PayConnectedEvent) => void` | No | Called once for each new address that the provider sees signed in. It is not proof of a live signing session. |
155
- | `dialogAriaHiddenAdapter` | `PayDialogAriaHiddenAdapter` | No | Lets your modal manager set the `aria-hidden` value of the kit's dialog. See [Host modal accessibility](#host-modal-accessibility). |
156
-
157
- ### `PayElement`
158
-
159
- | Prop | Type | Required | Meaning |
160
- | --- | --- | --- | --- |
161
- | `referenceId` | `string` | Yes | Your own id for this payment, 1 to 128 characters. Keep it the same for one order. |
162
- | `amount` | `string` | Yes, except for a deposit with a chosen amount | The price in USD, as a decimal string such as `"24.00"`. |
163
- | `mode` | `"payment" \| "deposit"` | No | What the request is. The default is `"payment"`. |
164
- | `min` | `string` | No | The least amount a customer can choose, for a deposit with no `amount`. |
165
- | `max` | `string` | No | The most a customer can choose, for a deposit with no `amount`. |
166
- | `firstStep` | `"amount" \| "method"` | No | For a deposit with no `amount`: ask the amount first (the default) or the way to pay first. |
167
- | `description` | `string` | No | The line the window shows for what the customer pays for. The kit trims it. It must then be 1 to 64 UTF-16 code units, with no control character, bidirectional override or isolate mark. A changed `description` needs a new `referenceId`. |
168
- | `destination` | `` `ckr_${string}` `` or `{ address, asset }` | No | Which saved destination pays. Leave it out to use your app's default. See [Where the money goes](#where-the-money-goes). |
169
- | `onEvent` | `(event: PayEvent) => void` | No | Called with each event of the payment. See [the events](#read-this-first-the-page-event-is-not-proof-of-payment). |
170
- | `loading` | `ReactNode` | No | Shown in place of the kit's placeholder while the card loads. |
171
- | `fallback` | `ReactNode` or `(context) => ReactNode` | No | Shown in place of each failure view. A function gets `retry` and `reason` (`"hub-frame"`, `"internal"` or `"unreachable"`). |
172
- | `className` | `string` | No | A class on the card's outer node. |
173
- | `style` | `CSSProperties` | No | Inline styles on the card's outer node. |
174
-
175
- `PayElement` throws a `TypeError` during render for a prop it does not take and for a value it refuses.
176
-
177
- ## The words that mean two things
178
-
179
- | Word | Its one meaning in this kit | The other meaning it is not |
180
- | --- | --- | --- |
181
- | deposit | `mode="deposit"`: a request where the customer adds money, such as an account top-up, with a fixed or chosen amount. It goes to the same saved destination as a payment. | "Manual deposit", one of the ways to pay, where the customer sends coins to an address made for one order (`method: "transfer"` in the event). |
182
- | checkout | The backend's checkout: the route that pays your destination. `checkout.closed` reports its final state. One payment can have more than one. | Your shop's checkout page, or the Stridge window. Neither of them closes a checkout. |
183
- | account | The customer's Stridge sign-in and Stridge Wallet (`@stridge/pay-kit/account`, `usePayAccount`). `method: "account"` means that the customer paid from the Stridge Wallet. | Your business's own Stridge setup, or the customer's account in your app. |
184
- | reference | `referenceId`: your own id for the payment. | The short code on the customer's receipt. That code is `receiptCode`. |
185
-
186
- ## Environments
187
-
188
- `environment` is `"sandbox"` or `"live"`.
189
-
190
- - `"sandbox"` connects to the Stridge hub at `https://universal.stridge.dev/`. Real coins move on it.
191
- - `"live"` has no hub yet. `PayProvider` throws a `TypeError` during render: `PayProvider: the "live" environment has no hub yet. Use environment="sandbox".`
192
-
193
- Any other value throws a `TypeError` too.
194
-
195
- ## Where the money goes
196
-
197
- Your destination (a chain, a coin and your address) is saved on the Stridge server as a checkout rule of your app. Your page names no address.
198
-
199
- - **No `destination`.** The server pays your app's default rule. This is the normal case. If your app has no default rule, the window stops and shows the developer line "This app has no default destination. Save one, or pass `destination`."
200
- - **A rule id, such as `destination="ckr_…"`.** That saved rule pays.
201
- - **`{ address, asset }`.** The address with its CAIP-19 asset id, such as `eip155:8453/erc20:0x…`. It pays only when it is one of your app's saved rules. An address never goes without its asset.
202
-
203
- > **Warning:** An app that Stridge's hub list marks as a test app can also pay an address that is not saved. This test-app mark is not the `"sandbox"` environment, and real coins move under both. Never rely on the test-app mark to pay a free address. A business app has no test-app mark, so it pays only its saved destinations.
204
-
205
- The saved default never replaces a destination that your page names. When the server answers another rule, asset or address, the window refuses the payment, sends nothing and shows a developer line that names both. Today the server answers with the default rule whenever the app has one. So, for an app with a default rule, a page that names another rule always stops.
206
-
207
- The window pays only a dollar token on an EVM chain: USDC or USDT, and on Tempo only USDC (listed as `USDC.e`). The server's asset registry must list it.
208
-
209
- A changed `destination` takes effect with the next Pay of the same `referenceId`.
210
-
211
- ## Ways to pay
212
-
213
- The customer picks a way to pay in the window's "Pay with" list. Which rows show depends on your app's setup, the customer, your destination's coin and chain, and the amount.
214
-
215
- "Card or bank" and "Manual deposit" stay in the list when they cannot serve this payment. The row is then dimmed and does nothing, and its second line gives the reason. The reason is "Starts at" and the least amount, "Can’t pay in" and the coin and chain that the payment network lacks, or "Not available here". A Stridge Wallet row whose balance cannot be read is also disabled. It keeps its usual second line.
216
-
217
- The Stridge Wallet row shows only for an app that Stridge marks as a test app. For any other app, the row is not in the list.
218
-
219
- ## Content security policy and the frame
220
-
221
- The kit frames the Stridge hub and adds inline `<style>` elements to your page. A strict content security policy needs these values:
222
-
223
- | Directive | Value | Why |
224
- | --- | --- | --- |
225
- | `frame-src` | `https://universal.stridge.dev` for `"sandbox"` | The provider's hidden hub frame and each card's frame load from the hub's origin. |
226
- | `style-src` | `'unsafe-inline'` | The kit adds `<style>` elements and has no nonce option. See the list below. |
227
-
228
- The kit adds these `<style>` elements:
229
-
230
- - one stylesheet for each card's outer node and the kit's default views, added once for each document;
231
- - one backdrop rule inside the provider's `<dialog>`, for the provider's lifetime;
232
- - one scroll-lock rule while the Stridge overlay shows.
233
-
234
- Two more rules apply to the frame and the window:
235
-
236
- - The hub sends its own `frame-ancestors`. It lists your origin only when Stridge registers that origin for your app id. An unregistered origin gets no hub frame, or the `app-suspended` error.
237
- - The Stridge window needs its opener. Do not send `Cross-Origin-Opener-Policy: same-origin`, because it cuts the link to every window your page opens. Send `same-origin-allow-popups`.
238
-
239
- ## Errors
240
-
241
- A failed request rejects with a `PayError`. Read its `code`. `isPayError(error)` returns `true` for a `PayError`, also for a copy from a second bundle, and `isPayError(error, code)` also checks the code. With `rate-limited`, `retryAfterSeconds` is the wait in seconds when the hub sent one.
242
-
243
- | Code | Meaning |
244
- | --- | --- |
245
- | `cancelled` | The customer closed the dialog. |
246
- | `busy` | Another request is still in progress. |
247
- | `not-initialized` | A request arrived before the hub's connection started. |
248
- | `signed-out` | The request needs a session, and there is none. |
249
- | `refused` | The signature was refused, by the provider or by the hub. |
250
- | `outcome-unknown` | The signature's outcome is unknown. Never retry it automatically. |
251
- | `cosignature-required` | The request waits for a second approval that nothing will give. |
252
- | `session-locked` | The session's `csrf_token` is lost. |
253
- | `app-suspended` | The backend refuses this app id, or the hub refuses your page's origin for it. |
254
- | `rate-limited` | Too many requests. |
255
- | `wallet-closed` | The customer's wallet is closed. |
256
- | `wallet-not-ready` | The customer's wallet is still being created after the wait ran out. |
257
- | `network` | The hub could not reach the Stridge server. |
258
- | `internal` | Any other failure. |
259
- | `unavailable` | The hub never completed its connection, reloaded during the request, or never opened Fund in time. |
260
- | `popup-blocked` | The browser refused to open the Stridge window, usually because the request did not start in the customer's click. |
261
-
262
- These are configuration faults. Correct them in your code or your setup, not with a retry:
263
-
264
- - A `TypeError` during render: a wrong `environment`, an `appId` that is not the issued id copied exactly (`app_` and a 26-character uppercase ULID), or a wrong `PayElement` prop. The message names the fault.
265
- - `app-suspended`: ask Stridge to register your page's origin for your app id, and check the app id.
266
- - `unavailable` on every request: the hub frame never connected. The kit writes one console warning that starts with `[pay-kit]` and names the cause. Check `frame-src`, the registered origin and `Cross-Origin-Opener-Policy`.
267
- - `popup-blocked`: start the request in the click handler, before any `await`.
268
-
269
- Invalid local arguments, such as an empty `sign` message, reject with a `TypeError`. Never retry a signature or a payment automatically after an unknown outcome.
270
-
271
- ## Styling
272
-
273
- You can style the card's outer node today. It has:
274
-
275
- - the class `stridge-pay-element`, plus your `className`;
276
- - the attribute `data-stridge-pay-element`;
277
- - `data-view`: `"frame"` while the card shows, or `"skeleton"`, `"loading"`, `"fallback"`, `"failed"` or `"connecting"` while a view covers it;
278
- - `data-shape`: `"lanes"` for the Pay card, `"bar"` for every other element;
279
- - `aria-busy="true"` while the card loads;
280
- - your `style`.
281
-
282
- The kit reserves a block size on the outer node while a view covers the frame: 184 px for the Pay card, 62 px for every other element. Its layout rules use `:where()`, so any class of yours wins over them. The card's content inside the frame is drawn by the hub. Change its colours with `theme` and `accent`.
283
-
284
- ## Host modal accessibility
285
-
286
- Pause your own focus trap while `usePaySnapshot().overlayOpen` is `true`.
287
-
288
- If your app's modal manager sets `aria-hidden` on page content, pass `dialogAriaHiddenAdapter` to `PayProvider`. The adapter tells the kit which `aria-hidden` value its dialog must have while the kit is not presenting. The kit restores that exact value each time its overlay closes.
289
-
290
- ```tsx
291
- import type { PayDialogAriaHiddenAdapter } from "@stridge/pay-kit";
292
-
293
- /** Define it once, outside any component. `readHostIntent` and `subscribeToHostIntent` come from your modal manager. */
294
- const dialogAriaHiddenAdapter: PayDialogAriaHiddenAdapter = (register) => {
295
- const signal = register(readHostIntent());
296
- const unsubscribe = subscribeToHostIntent((value) => signal(value));
297
- signal(readHostIntent());
298
- return unsubscribe;
299
- };
300
- ```
301
-
302
- ### The adapter contract
303
-
304
- A value is `null`, `"false"`, or `"true"`. `null` means the dialog has no `aria-hidden` attribute.
305
-
306
- - The kit calls the adapter once, after the provider first commits. StrictMode does not call it a second time.
307
- - The adapter calls `register` synchronously with the initial value and returns a cleanup function. An adapter that holds no resources returns a cleanup that does nothing.
308
- - `register` returns a signal. Call the signal each time the host's value changes, and also when the host repeats the same value. Each call replaces the previous value.
309
- - One adapter covers every host modal. The host combines them into one value.
310
- - An invalid value throws a `TypeError`. After the provider is disposed, the signal returns `false` and checks nothing.
311
- - Keep the adapter function stable for the provider's lifetime. A different function throws a `TypeError`. To add, replace, or remove the adapter, change the provider's `key`, `environment`, or `appId`.
312
- - If the adapter throws before it returns its cleanup, the adapter must release its own host resources.
313
-
314
- ### What the kit does with the value
315
-
316
- - While the kit presents, a signal stores the new value. The kit does not hide its dialog.
317
- - Before the kit opens the dialog and moves focus into it, the kit removes the dialog's `aria-hidden` attribute.
318
- - On close, the kit closes the dialog with no attribute and then writes the latest value. A signal that the native close sends synchronously, before that write, counts.
319
- - While the dialog is closed, a signal stores the value for the next close or for disposal. The kit does not write to the closed dialog.
320
- - A direct write to the attribute never replaces a signaled value.
321
- - A temporary unmount, such as StrictMode's effect replay, keeps the registration. On final disposal of the provider or of the channel, the kit retires the signal before any callback runs. The kit then writes the last value to the old dialog, removes what it owns, and calls the adapter's cleanup once.
322
-
323
- ### Without an adapter
324
-
325
- The kit records the attribute's value before it opens and watches later writes to the attribute. On close, the kit restores the value it saw last.
66
+ Replace `app_…` with the app id that Stridge issued for your app. Keep `referenceId` the same for one order, and use a new `referenceId` for a new order. `amount` is the price in USD, as a decimal string such as `"24.00"`.
326
67
 
327
- One case goes wrong. If the host set `"true"` before the kit opened or while it was open, the host's later removal can come after the attribute is already gone. That removal changes nothing, so the kit does not see it and restores the old `"true"`. To get no attribute through this path, write `"false"` and then remove the attribute in the same synchronous block. If the kit's observer runs between the two writes, the kit restores `"false"`.
68
+ The example needs a default destination saved for your app. It passes no `destination`, so each payment goes to that default. When your app has no default, the hub stops checkout and asks for a destination.
328
69
 
329
- ### Host requirements and limits
70
+ ## Content security policy and the Stridge window
330
71
 
331
- The kit changes only the `aria-hidden` attribute of its own dialog. The dialog and its iframe stay in the page for the provider's lifetime. The kit does not change siblings or ancestors.
72
+ The kit frames the Stridge hub. The hub loads only on your app's allowed sites (Stridge adds them for you during the Preview). A strict content security policy needs these values:
332
73
 
333
- Your modal manager must:
74
+ - `frame-src https://universal.stridge.dev`, because the hub and each card load from that origin.
75
+ - `style-src 'unsafe-inline'`, because the kit adds inline `<style>` elements and has no nonce option.
334
76
 
335
- - leave the presenting kit dialog out of its own `aria-hidden` writes, or send those changes through the adapter;
336
- - pause its focus trap while `usePaySnapshot().overlayOpen` is `true`.
77
+ The Stridge window needs its link to your page. Do not send `Cross-Origin-Opener-Policy: same-origin`, because it cuts that link. Send `Cross-Origin-Opener-Policy: same-origin-allow-popups`, or no such header.
337
78
 
338
- The kit does not support `aria-hidden` on an ancestor of its dialog, `inert` on its dialog, a focus trap that does not pause, or repeated competing writes.
79
+ ## Documentation
339
80
 
340
- No modal library or library version is tested yet, and no native accessibility behavior is verified. Chrome focus, the accessibility tree, screen readers, background isolation, zoom, and scrolling need separate checks. Other browsers are not covered yet.
81
+ The full guide is at [docs.stridge.com/pay](https://docs.stridge.com/pay). It goes live with the docs release.
@@ -6,8 +6,10 @@ import { ReactNode } from "react";
6
6
  * hub shows every ceremony inside its own iframe, or in the Stridge window (a window on the hub's origin) when the hub
7
7
  * reports the `popup` transport.
8
8
  *
9
- * - **Environment.** `environment` picks the hub the provider frames: `"sandbox"` frames the Stridge sandbox hub;
10
- * `"live"` has no hub yet and throws, as does any other value.
9
+ * - **Hub.** The provider frames the Stridge staging hub (`HUB_ADDRESS`), or the address our own apps set with
10
+ * `HubAddressOverride`. It takes no `environment` prop. In JavaScript, a leftover `environment="sandbox"` logs one
11
+ * `[pay-kit]` warning per page (once per process on a server), and any other value throws a `TypeError` before
12
+ * anything is framed.
11
13
  * - **One channel per hub and `appId`.** Created with the internal provider channel factory during render
12
14
  * without side effects (lazily, and again when the hub or `appId` change),
13
15
  * published on `PayChannelContext` around `children`.
@@ -39,8 +41,8 @@ import { ReactNode } from "react";
39
41
  * `Cross-Origin-Opener-Policy: same-origin` cuts it as soon as the hub page loads; send `same-origin-allow-popups`, or
40
42
  * no such header. A cut link rejects the request with `unavailable` and logs a warning that names the header.
41
43
  *
42
- * The dialog and its iframe live outside the React tree. An invalid `environment`, `appId`, or `theme` throws
43
- * a `TypeError` during render: a configuration error for the nearest error boundary.
44
+ * The dialog and its iframe live outside the React tree. An invalid `appId` or `theme`, or a leftover `environment`
45
+ * other than `"sandbox"`, throws a `TypeError` during render: a configuration error for the nearest error boundary.
44
46
  */
45
47
  declare function PayProvider(props: PayProviderProps): ReactNode;
46
48
  //#endregion
@@ -1 +1 @@
1
- "use client";import{PayError as e}from"../errors/PayError.js";import{PayChannelContext as t}from"./context.js";import{createProviderChannel as n}from"../channel/createAppChannel.js";import{createDialogAriaHiddenIntent as r}from"../channel/createDialogAriaHiddenIntent.js";import{createElementClient as i}from"../core/createElementClient.js";import{createElementStartGate as a}from"../core/elementStartGate.js";import{subscribeToNothing as o}from"../shared/presentation/subscribeToNothing.js";import{createProviderChannelDisposalBridge as s,createProviderLifetime as c}from"./createProviderLifetime.js";import{PayElementClientContext as l,PayElementFrameContext as u,PayElementThemeContext as d}from"./elementContext.js";import{HubAddressOverrideContext as f,resolveHubAddress as p}from"./hubAddress.js";import{use as m,useEffect as h,useLayoutEffect as g,useRef as _,useState as v,useSyncExternalStore as y}from"react";import{HUB_FRAME_NAME_PATTERN as b,MAX_MESSAGE_ID_LENGTH as x}from"@stridge/pay-sdk";import{jsx as S}from"react/jsx-runtime";const C=`dark`;function w(){return typeof window>`u`||typeof window.matchMedia!=`function`?null:window.matchMedia(`(prefers-color-scheme: dark)`)}function T(e){let t=w();return t===null?()=>{}:(t.addEventListener(`change`,e),()=>{t.removeEventListener(`change`,e)})}function E(){let e=w();return e===null?C:e.matches?`dark`:`light`}function D(){return C}function O(e){let t=e===`system`,n=y(t?T:o,E,D);return t?n:e}const k=Object.freeze({frames:null,port:null}),A=Object.freeze({phase:`none`});function j(e){let t=e.iframe;if(t===null)return null;let n=t.name,r=t.ownerDocument,i=t.contentWindow;return!n||n.length>x||!b.test(n)||i===null?null:{frame:t,name:n,document:r,window:i}}function M(e,t,n){let r=()=>e.iframe===t.frame&&t.frame.name===t.name&&t.frame.ownerDocument===t.document&&t.frame.isConnected&&t.document.documentElement.contains(t.frame)&&t.document.defaultView===globalThis.window&&t.frame.contentWindow===t.window;return n()&&r()&&r()&&e.iframe===t.frame&&t.frame.name===t.name&&t.frame.ownerDocument===t.document&&t.frame.isConnected&&n()}function N(t,o,l,u){let d=u===void 0?void 0:r(u),f=s(),p,m,h={disposalBridge:f,...d===void 0?{}:{dialogAriaHiddenIntent:d},bindMenu(e){p=e},bindDiagnostics(e){m=e}},g=n({hubUrl:t,appId:o,appearance:l},h),_=!1,v=l,y,b=A,x=k,S=null,C=!1,w=new Set,T=new Set,E=new Map;function D(){let e=[...E];E.clear();for(let[t,n]of e)n(),t.abort()}let O=c({channel:g,...h,finalize(){let e=b.phase===`none`?null:b.client,t=S;b=A,S=null,T.clear();let n=[];for(let r of[D,()=>t?.(),()=>e?.destroy()])try{r()}catch(e){n.push(e)}if(n.length>0)throw n[0]}}),N=()=>_&&!O.disposed;function P(){let e=b;if(!N()||e.phase!==`started`)return D(),!1;!M(g,e.root,N)&&b===e&&(b={phase:`lost`,client:e.client});let t=b===e&&N();return t||D(),t}function F(e){return P()&&b.phase===`started`&&b.root===e}function I(e){if(!(!N()||w.has(e.evmAddress))){w.add(e.evmAddress);try{y?.(e)}catch{}}}function L(){if(N()){if(b.phase===`started`||b.phase===`lost`){P();return}if(!C){C=!0;try{let e=x;b.phase===`loading`&&!M(g,b.root,N)&&V(),b.phase===`none`&&z(),b.phase===`loading`&&g.getSnapshot().connection===`ready`&&B(),x!==e&&R(x)}finally{C=!1}}}}function R(e){for(let t of T){if(x!==e||e.port!==null&&!P())return;t()}}function z(){let n=j(g);if(n===null||!M(g,n,N))return;let r=a(P),s=i({hubUrl:t,appId:o,appearance:v,hubFrame:n.name,startGate:r.gate,onConnected(e){P()&&I(e)},showMenu(t,r,i){if(!F(n)||p===void 0||r.aborted)return Promise.reject(new e(`cancelled`,`The account menu root is no longer current`));let a=new AbortController,o=()=>{a.abort(),c()},s=()=>r.removeEventListener(`abort`,o),c=()=>{E.delete(a),s()};E.set(a,s),r.addEventListener(`abort`,o,{once:!0}),r.aborted&&a.abort();try{let e=p.showMenu(t,a.signal,i===void 0?void 0:{element:i.element,onEnd(e){c(),F(n)&&!a.signal.aborted&&i.onEnd(e)}});return F(n)||a.abort(),e.catch(e=>{throw c(),e})}catch(e){return c(),a.abort(),Promise.reject(e)}}});if(!M(g,n,N)){s.destroy();return}let c={reserve(e){let t=()=>b.phase===`loading`&&b.frames===c&&M(g,n,N);if(!t())return null;try{let n=s.createHandle(e);if(t())return n;n.destroy()}catch{}return null}};b={phase:`loading`,root:n,client:s,frames:c,start:r},x=Object.freeze({frames:c,port:null})}function B(){if(b.phase!==`loading`)return;let{root:e,client:t,frames:n,start:r}=b;if(!M(g,e,N)){V();return}b={phase:`started`,root:e,client:t},x=Object.freeze({frames:n,port:{createHandle(e){if(!P())throw Error(`PayProvider: the element root binding is no longer current`);let n=t.createHandle(e);if(!P())throw n.destroy(),Error(`PayProvider: the element root changed during handle creation`);return n},adopt(e){if(!P())throw e.destroy(),Error(`PayProvider: the element root binding is no longer current`)}}}),r.open(),P()}function V(){if(b.phase!==`loading`)return;let{client:e}=b;b=A,x=k,e.destroy()}let H={hubOrigin:g.hubOrigin,get iframe(){return g.iframe},getSnapshot:()=>g.getSnapshot(),subscribe:e=>g.subscribe(e),mount:e=>g.mount(e),unmount:()=>g.unmount(),setAppearance:e=>g.setAppearance(e),signIn:()=>g.signIn(),sign:e=>g.sign(e),signOut:()=>g.signOut(),disconnect:e=>g.disconnect(e),fund:e=>g.fund(e),dispose:()=>g.dispose()},U=H.signIn;return H.signIn=()=>{let e=j(g);return U().then(t=>(e!==null&&M(g,e,N)&&I(t),t))},{adapter:u,hubUrl:t,appId:o,channel:H,lifetime:O,composition:{commit(e,t,n){_=!0,y=t,v=e,m?.setEnabled(n),!(!N()||b.phase===`none`)&&b.client.setAppearance(e)},releaseCommit(){_=!1,m?.setEnabled(!1),D()},start(){S===null&&(S=g.subscribe(L));let e=O.acquire();try{L()}catch(e){try{O.dispose()}catch{}throw e}return e},subscribe(e){return T.add(e),()=>{T.delete(e)}},snapshot:()=>x}}}function P(e){let{environment:n,appId:r,children:i,dialogAriaHiddenAdapter:a}=e,o=p(n,m(f)),s=O(e.theme??`dark`),[c,b]=v(()=>N(o,r,{theme:s},a)),x=c;if(c.hubUrl!==o||c.appId!==r)x=N(o,r,{theme:s},a),b(x);else if(c.adapter!==a)throw TypeError(`PayProvider: dialogAriaHiddenAdapter must stay stable for a provider lifetime; change the provider key or hub/app identity to replace it`);let C=x.channel;g(()=>{x.composition.commit({theme:s},e.onConnected,e.diagnostics??!1)},[x,s,e.onConnected,e.diagnostics]),g(()=>()=>x.composition.releaseCommit(),[x]),h(()=>x.composition.start(),[x]);let w=y(x.composition.subscribe,x.composition.snapshot,()=>k),T=_(null);return h(()=>{let e=T.current;e!==null&&e.channel===C&&e.theme!==s&&C.setAppearance({theme:s}),T.current={channel:C,theme:s}},[C,s]),S(u,{value:w.frames,children:S(l,{value:w.port,children:S(d,{value:s,children:S(t,{value:C,children:i})})})})}export{P as PayProvider};
1
+ "use client";import{PayError as e}from"../errors/PayError.js";import{PayChannelContext as t}from"./context.js";import{createProviderChannel as n}from"../channel/createAppChannel.js";import{createDialogAriaHiddenIntent as r}from"../channel/createDialogAriaHiddenIntent.js";import{createElementClient as i}from"../core/createElementClient.js";import{createElementStartGate as a}from"../core/elementStartGate.js";import{subscribeToNothing as o}from"../shared/presentation/subscribeToNothing.js";import{createProviderChannelDisposalBridge as s,createProviderLifetime as c}from"./createProviderLifetime.js";import{PayElementClientContext as l,PayElementFrameContext as u,PayElementThemeContext as d}from"./elementContext.js";import{HubAddressOverrideContext as f,resolveHubAddress as p}from"./hubAddress.js";import{use as m,useEffect as h,useLayoutEffect as g,useRef as _,useState as v,useSyncExternalStore as y}from"react";import{HUB_FRAME_NAME_PATTERN as b,MAX_MESSAGE_ID_LENGTH as x}from"@stridge/pay-sdk";import{jsx as S}from"react/jsx-runtime";const C=`dark`;function w(){return typeof window>`u`||typeof window.matchMedia!=`function`?null:window.matchMedia(`(prefers-color-scheme: dark)`)}function T(e){let t=w();return t===null?()=>{}:(t.addEventListener(`change`,e),()=>{t.removeEventListener(`change`,e)})}function E(){let e=w();return e===null?C:e.matches?`dark`:`light`}function D(){return C}function O(e){let t=e===`system`,n=y(t?T:o,E,D);return t?n:e}const k=Object.freeze({frames:null,port:null}),A=Object.freeze({phase:`none`});function j(e){let t=e.iframe;if(t===null)return null;let n=t.name,r=t.ownerDocument,i=t.contentWindow;return!n||n.length>x||!b.test(n)||i===null?null:{frame:t,name:n,document:r,window:i}}function M(e,t,n){let r=()=>e.iframe===t.frame&&t.frame.name===t.name&&t.frame.ownerDocument===t.document&&t.frame.isConnected&&t.document.documentElement.contains(t.frame)&&t.document.defaultView===globalThis.window&&t.frame.contentWindow===t.window;return n()&&r()&&r()&&e.iframe===t.frame&&t.frame.name===t.name&&t.frame.ownerDocument===t.document&&t.frame.isConnected&&n()}function N(t,o,l,u){let d=u===void 0?void 0:r(u),f=s(),p,m,h={disposalBridge:f,...d===void 0?{}:{dialogAriaHiddenIntent:d},bindMenu(e){p=e},bindDiagnostics(e){m=e}},g=n({hubUrl:t,appId:o,appearance:l},h),_=!1,v=l,y,b=A,x=k,S=null,C=!1,w=new Set,T=new Set,E=new Map;function D(){let e=[...E];E.clear();for(let[t,n]of e)n(),t.abort()}let O=c({channel:g,...h,finalize(){let e=b.phase===`none`?null:b.client,t=S;b=A,S=null,T.clear();let n=[];for(let r of[D,()=>t?.(),()=>e?.destroy()])try{r()}catch(e){n.push(e)}if(n.length>0)throw n[0]}}),N=()=>_&&!O.disposed;function P(){let e=b;if(!N()||e.phase!==`started`)return D(),!1;!M(g,e.root,N)&&b===e&&(b={phase:`lost`,client:e.client});let t=b===e&&N();return t||D(),t}function F(e){return P()&&b.phase===`started`&&b.root===e}function I(e){if(!(!N()||w.has(e.evmAddress))){w.add(e.evmAddress);try{y?.(e)}catch{}}}function L(){if(N()){if(b.phase===`started`||b.phase===`lost`){P();return}if(!C){C=!0;try{let e=x;b.phase===`loading`&&!M(g,b.root,N)&&V(),b.phase===`none`&&z(),b.phase===`loading`&&g.getSnapshot().connection===`ready`&&B(),x!==e&&R(x)}finally{C=!1}}}}function R(e){for(let t of T){if(x!==e||e.port!==null&&!P())return;t()}}function z(){let n=j(g);if(n===null||!M(g,n,N))return;let r=a(P),s=i({hubUrl:t,appId:o,appearance:v,hubFrame:n.name,startGate:r.gate,onConnected(e){P()&&I(e)},showMenu(t,r,i){if(!F(n)||p===void 0||r.aborted)return Promise.reject(new e(`cancelled`,`The account menu root is no longer current`));let a=new AbortController,o=()=>{a.abort(),c()},s=()=>r.removeEventListener(`abort`,o),c=()=>{E.delete(a),s()};E.set(a,s),r.addEventListener(`abort`,o,{once:!0}),r.aborted&&a.abort();try{let e=p.showMenu(t,a.signal,i===void 0?void 0:{element:i.element,onEnd(e){c(),F(n)&&!a.signal.aborted&&i.onEnd(e)}});return F(n)||a.abort(),e.catch(e=>{throw c(),e})}catch(e){return c(),a.abort(),Promise.reject(e)}}});if(!M(g,n,N)){s.destroy();return}let c={reserve(e){let t=()=>b.phase===`loading`&&b.frames===c&&M(g,n,N);if(!t())return null;try{let n=s.createHandle(e);if(t())return n;n.destroy()}catch{}return null}};b={phase:`loading`,root:n,client:s,frames:c,start:r},x=Object.freeze({frames:c,port:null})}function B(){if(b.phase!==`loading`)return;let{root:e,client:t,frames:n,start:r}=b;if(!M(g,e,N)){V();return}b={phase:`started`,root:e,client:t},x=Object.freeze({frames:n,port:{createHandle(e){if(!P())throw Error(`PayProvider: the element root binding is no longer current`);let n=t.createHandle(e);if(!P())throw n.destroy(),Error(`PayProvider: the element root changed during handle creation`);return n},adopt(e){if(!P())throw e.destroy(),Error(`PayProvider: the element root binding is no longer current`)}}}),r.open(),P()}function V(){if(b.phase!==`loading`)return;let{client:e}=b;b=A,x=k,e.destroy()}let H={hubOrigin:g.hubOrigin,get iframe(){return g.iframe},getSnapshot:()=>g.getSnapshot(),subscribe:e=>g.subscribe(e),mount:e=>g.mount(e),unmount:()=>g.unmount(),setAppearance:e=>g.setAppearance(e),signIn:()=>g.signIn(),sign:e=>g.sign(e),signOut:()=>g.signOut(),disconnect:e=>g.disconnect(e),fund:e=>g.fund(e),dispose:()=>g.dispose()},U=H.signIn;return H.signIn=()=>{let e=j(g);return U().then(t=>(e!==null&&M(g,e,N)&&I(t),t))},{adapter:u,hubUrl:t,appId:o,channel:H,lifetime:O,composition:{commit(e,t,n){_=!0,y=t,v=e,m?.setEnabled(n),!(!N()||b.phase===`none`)&&b.client.setAppearance(e)},releaseCommit(){_=!1,m?.setEnabled(!1),D()},start(){S===null&&(S=g.subscribe(L));let e=O.acquire();try{L()}catch(e){try{O.dispose()}catch{}throw e}return e},subscribe(e){return T.add(e),()=>{T.delete(e)}},snapshot:()=>x}}}function P(e){let{appId:n,children:r,dialogAriaHiddenAdapter:i}=e,a=p(e.environment,m(f)),o=O(e.theme??`dark`),[s,c]=v(()=>N(a,n,{theme:o},i)),b=s;if(s.hubUrl!==a||s.appId!==n)b=N(a,n,{theme:o},i),c(b);else if(s.adapter!==i)throw TypeError(`PayProvider: dialogAriaHiddenAdapter must stay stable for a provider lifetime; change the provider key or hub/app identity to replace it`);let x=b.channel;g(()=>{b.composition.commit({theme:o},e.onConnected,e.diagnostics??!1)},[b,o,e.onConnected,e.diagnostics]),g(()=>()=>b.composition.releaseCommit(),[b]),h(()=>b.composition.start(),[b]);let C=y(b.composition.subscribe,b.composition.snapshot,()=>k),w=_(null);return h(()=>{let e=w.current;e!==null&&e.channel===x&&e.theme!==o&&x.setAppearance({theme:o}),w.current={channel:x,theme:o}},[x,o]),S(u,{value:C.frames,children:S(l,{value:C.port,children:S(d,{value:o,children:S(t,{value:x,children:r})})})})}export{P as PayProvider};
@@ -1 +1 @@
1
- "use client";import{createContext as e}from"react";const t={sandbox:`https://universal.stridge.dev/`,live:null},n=e(null);n.displayName=`HubAddressOverrideContext`;function r(e,n){if(e!==`sandbox`&&e!==`live`)throw TypeError(`PayProvider: environment must be "sandbox" or "live".`);let r=t[e];if(r===null)throw TypeError(`PayProvider: the "${e}" environment has no hub yet. Use environment="sandbox".`);return n??r}export{t as HUB_ADDRESSES,n as HubAddressOverrideContext,r as resolveHubAddress};
1
+ "use client";import{HUB_ADDRESS as e}from"./hubAddressValue.js";import{createContext as t}from"react";const n=t(null);n.displayName=`HubAddressOverrideContext`;const r=`PayProvider no longer takes "environment". Delete the prop. The kit connects to the Stridge staging hub.`,i=Symbol.for(`@stridge/pay-kit/leftover-environment-warned`);let a=!1;function o(){if(typeof document>`u`){if(a)return;a=!0}else{let e=document;if(e[i])return;e[i]=!0}console.warn(`[pay-kit] ${r}`)}function s(e,t){if(e===`sandbox`)o();else if(e!==void 0)throw TypeError(r);return t??`https://universal.stridge.dev/`}export{e as HUB_ADDRESS,n as HubAddressOverrideContext,s as resolveHubAddress};
@@ -0,0 +1 @@
1
+ const e=`https://universal.stridge.dev/`;export{e as HUB_ADDRESS};
@@ -21,11 +21,6 @@ interface PayProviderProps {
21
21
  * @internal
22
22
  */
23
23
  diagnostics?: boolean;
24
- /**
25
- * The Stridge environment the provider connects to: `"sandbox"` or `"live"`. `"live"` has no hub yet and throws a
26
- * configuration error; use `"sandbox"`.
27
- */
28
- environment: "sandbox" | "live";
29
24
  /**
30
25
  * The app id the backend issued for this app. A change replaces the provider lifetime.
31
26
  */
@@ -122,7 +122,8 @@ interface PaymentUnconfirmedEvent {
122
122
  interface PayRequestFailedEvent {
123
123
  readonly type: "request.failed";
124
124
  /**
125
- * The request that failed.
125
+ * The request that failed. Today the hub reports only `"sign-in"` and `"fund"`. `"sign-out"`, `"disconnect"` and
126
+ * `"pay"` are reserved: a later hub can report them without a kit release, so handle an unknown value too.
126
127
  */
127
128
  readonly request: "sign-in" | "sign-out" | "disconnect" | "fund" | "pay";
128
129
  /**
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@stridge/pay-kit",
3
- "version": "0.1.0-alpha.1",
3
+ "version": "0.1.0-alpha.2",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "files": [