@mystars-tg/faas-sdk 0.1.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 MyStars.tg
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,177 @@
1
+ # @mystars-tg/faas-sdk
2
+
3
+ [![npm](https://img.shields.io/npm/v/@mystars-tg/faas-sdk.svg)](https://www.npmjs.com/package/@mystars-tg/faas-sdk) [![license](https://img.shields.io/npm/l/@mystars-tg/faas-sdk.svg)](LICENSE) [![API contract](https://img.shields.io/badge/FaaS%20API-v1.9.0-blue.svg)](https://mystars.tg/docs)
4
+
5
+ Official TypeScript/JavaScript SDK for the **MyStars FaaS** API — buy Telegram **Stars** &
6
+ **Premium** for any `@username`, paid in **TON** or **USDT (TON)**.
7
+
8
+ Works in Node ≥18, Deno, Bun, Cloudflare Workers, and the browser (the core has **zero crypto
9
+ dependencies**). The opt-in wallet module (`@mystars-tg/faas-wallet`) and CLI (`@mystars-tg/faas-cli`) ship
10
+ separately.
11
+
12
+ > Compatible with FaaS API **v1.9.0**.
13
+
14
+ 📖 Full interactive API reference: **[mystars.tg/docs](https://mystars.tg/docs)**.
15
+
16
+ ## Install
17
+
18
+ ```bash
19
+ npm install @mystars-tg/faas-sdk
20
+ ```
21
+
22
+ ## Get an API key
23
+
24
+ Keys are issued inside the MyStars Telegram bot — open [@my_stars_tg_bot](https://t.me/my_stars_tg_bot),
25
+ tap **API access**, and copy your `X-Api-Key`. No dashboard, no signup form.
26
+
27
+ ## Quick start
28
+
29
+ ```ts
30
+ import { MyStarsClient } from "@mystars-tg/faas-sdk";
31
+
32
+ const client = MyStarsClient.production(process.env.MYSTARS_API_KEY!);
33
+
34
+ // 1. Quote the price
35
+ const quote = await client.getPricing({ type: "stars", quantity: 100, payment_currency: "ton" });
36
+ console.log(`Pay ${quote.amount} ${quote.currency}`);
37
+
38
+ // 2. (optional) Check the recipient first
39
+ const check = await client.checkRecipient({ type: "stars", recipient: { username: "durov" } });
40
+ if (!check.eligible) throw new Error(check.telegram_message ?? "recipient ineligible");
41
+
42
+ // 3. Create the order. Pass a STABLE idempotencyKey derived from your own order id
43
+ // so a retry (even after a crash) returns the SAME order instead of a duplicate.
44
+ // Omit it and the SDK auto-generates a uuid that only dedupes within ONE call's retries.
45
+ const order = await client.createOrder(
46
+ {
47
+ type: "stars",
48
+ recipient: { username: "durov" },
49
+ quantity: 100,
50
+ payment_currency: "ton",
51
+ callback_url: "https://your-app.example.com/webhooks/mystars",
52
+ },
53
+ { idempotencyKey: `order-${myOrderId}` },
54
+ );
55
+
56
+ // 4. Pay it: send order.payment.amount to order.payment.pay_to_address
57
+ // with the on-chain comment order.payment.memo (the bare order UUID).
58
+ console.log(order.payment);
59
+
60
+ // 5. Track it until it's delivered (or failed/reversed/expired)
61
+ const finished = await client.waitForOrder(order.order_id, {
62
+ onUpdate: (o) => console.log("status:", o.status),
63
+ });
64
+ console.log("done:", finished.status, finished.purchase_tx);
65
+ ```
66
+
67
+ ## Errors
68
+
69
+ Every failure is a typed subclass of `MyStarsApiError` (itself a `MyStarsError`):
70
+
71
+ ```ts
72
+ import { RecipientIneligibleError, RateLimitError } from "@mystars-tg/faas-sdk";
73
+
74
+ try {
75
+ await client.createOrder({ type: "premium", recipient: { username: "durov" }, months: 3 });
76
+ } catch (err) {
77
+ if (err instanceof RecipientIneligibleError) {
78
+ // err.telegramMessage: the buyer-facing reason to show your user.
79
+ // For the structured reason ("already_subscribed" | "not_found" | "ineligible"),
80
+ // call client.checkRecipient(...) first and read its `reason`.
81
+ } else if (err instanceof RateLimitError) {
82
+ // err.retryAfterMs, err.kind: "general" | "order_cap"
83
+ }
84
+ }
85
+ ```
86
+
87
+ The client retries transient failures (network, timeout, 502/503/504, 500, and the general 429 —
88
+ honoring `Retry-After`, capped at `maxDelayMs`) automatically and idempotency-safely. Configure or
89
+ disable via the `retry` option.
90
+
91
+ ### Recovering a `createOrder` that failed
92
+
93
+ When `createOrder` throws you can't always tell whether the order was created server-side. The thrown
94
+ `MyStarsApiError` carries the `idempotencyKey` that was used — retry with that exact key to get the
95
+ idempotent replay instead of a duplicate deliverable:
96
+
97
+ ```ts
98
+ try {
99
+ await client.createOrder(params, { idempotencyKey: `order-${myOrderId}` });
100
+ } catch (err) {
101
+ if (err instanceof MyStarsApiError && err.idempotencyKey) {
102
+ // Safe: same key → server returns the original order (replayed:true), never a 2nd order.
103
+ await client.createOrder(params, { idempotencyKey: err.idempotencyKey });
104
+ }
105
+ }
106
+ ```
107
+
108
+ ## Pagination
109
+
110
+ ```ts
111
+ // Auto-paginate every order:
112
+ for await (const order of client.listOrders({ status: "delivered" })) {
113
+ console.log(order.order_id);
114
+ }
115
+
116
+ // Or page-by-page:
117
+ const pager = client.listOrders({ limit: 100 });
118
+ const first = await pager.page();
119
+ const next = first.next_cursor ? await pager.page(first.next_cursor) : null;
120
+ ```
121
+
122
+ ## Reference
123
+
124
+ | Method | Endpoint |
125
+ |---|---|
126
+ | `listCurrencies()` | `GET /v1/currencies` |
127
+ | `listProducts()` | `GET /v1/products` |
128
+ | `getPricing(params)` | `GET /v1/pricing` |
129
+ | `checkRecipient(params)` | `POST /v1/recipients/check` |
130
+ | `createOrder(params, opts?)` | `POST /v1/orders` |
131
+ | `listOrders(params?)` | `GET /v1/orders` |
132
+ | `getOrder(id)` | `GET /v1/orders/:id` |
133
+ | `cancelOrder(id)` | `POST /v1/orders/:id/cancel` |
134
+ | `waitForOrder(id, opts?)` | polls `GET /v1/orders/:id` |
135
+ | `reconcile(opts)` | diffs `listOrders` vs your store to catch webhook-missed terminal transitions |
136
+
137
+ ## Webhooks
138
+
139
+ ```ts
140
+ import { constructEvent, expressWebhook } from "@mystars-tg/faas-sdk";
141
+
142
+ // Verify manually (verify over the RAW body, then dedup on order_id):
143
+ const event = await constructEvent(rawBody, req.headers["x-faas-signature"], WEBHOOK_SECRET);
144
+
145
+ // Or use the Express adapter (mount express.raw() on the route):
146
+ app.post("/webhooks/mystars", express.raw({ type: "*/*" }), expressWebhook({
147
+ secret: WEBHOOK_SECRET,
148
+ onEvent: async (event) => { /* event.order_id, event.status, event.purchase_tx */ },
149
+ }));
150
+ ```
151
+
152
+ `verifyWebhookSignature` / `constructEvent` handle the 24h secret-rotation header
153
+ (`"current,previous"`) automatically. A `fastifyWebhook` adapter is also exported.
154
+
155
+ ## Your own retail markup
156
+
157
+ ```ts
158
+ import { applyRetailMarkup } from "@mystars-tg/faas-sdk";
159
+
160
+ const quote = await client.getPricing({ type: "stars", quantity: 100, payment_currency: "usdt_ton" });
161
+ const retail = applyRetailMarkup(quote, { marginPct: 15, passThroughProcessingFee: true });
162
+ // retail.total → what to charge your customer; retail.profit → your gross margin.
163
+ ```
164
+
165
+ Uses the exact two-stage cent-ceil the server uses, so your retail math never drifts a cent.
166
+
167
+ ## Pay an order (non-custodial)
168
+
169
+ ```ts
170
+ import { buildPaymentRequest } from "@mystars-tg/faas-sdk";
171
+
172
+ const req = buildPaymentRequest(order.payment);
173
+ // req.tonDeeplink / req.qrPayload (TON), or req.tonConnect for tonConnectUI.sendTransaction({ messages })
174
+ ```
175
+
176
+ Holds no keys. For wallet generation + signing/broadcasting from your own wallet, see
177
+ `@mystars-tg/faas-wallet` (upcoming).