@mboxcommunity/fragment-api-sdk 0.0.0-stage → 0.1.1

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,3 +1,65 @@
1
- # Temporary Holding Version
1
+ # @mboxcommunity/fragment-api-sdk (JavaScript / TypeScript)
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ JS/TS client for the [Fragment API](https://fragment.mboxcommunity.org)
4
+ — local-signing purchases of Telegram Stars/Premium, marketplace
5
+ items (usernames, +888 numbers, collectible gifts), Telegram Ads
6
+ credit, and NFT transfers. Mirrors the Python SDK's REST surface.
7
+
8
+ **Local signing:** your seed is used only on your machine — to derive
9
+ the public account object and to sign prepared payments *after* the
10
+ verification checklist (`src/verify.ts`, a port of the Python
11
+ checklist) passes. It is never transmitted.
12
+
13
+ ## Install
14
+
15
+ ```bash
16
+ npm install @mboxcommunity/fragment-api-sdk
17
+ ```
18
+
19
+ Requires Node 18+. Build from source: `npm install && npm run build`.
20
+
21
+ ## Usage
22
+
23
+ ```ts
24
+ import { FragmentAPI } from "@mboxcommunity/fragment-api-sdk";
25
+
26
+ const api = await FragmentAPI.create({
27
+ cookies: { stel_ssid: "…", stel_dt: "…", stel_token: "…" },
28
+ seed: "your 24 word mnemonic",
29
+ maxTonPerOrder: 5_000_000_000n, // mandatory spend limit (nanoton)
30
+ });
31
+
32
+ // Purchases
33
+ await api.buyStars("@durov", 100);
34
+ await api.buyPremium("@durov", 3);
35
+
36
+ // Marketplace
37
+ const found = await api.searchUsernames({ query: "shop", filter: "sale" });
38
+ const info = await api.usernameInfo("someusername"); // auction/sale state
39
+ await api.bidUsername("someusername", "120"); // bid 120 TON
40
+ await api.buyUsername("listedname"); // fixed-price buy
41
+ await api.bidNumber("88801234567", "500");
42
+ await api.buyGift("plushpepe-1234");
43
+
44
+ // Telegram Ads credit (TON only)
45
+ await api.buyAdsCredit("@mychannel", "25");
46
+
47
+ // Owned assets + NFT transfers (signed by the owner wallet)
48
+ const owned = await api.ownedUsernames();
49
+ await api.transferUsername("myname", "UQ…recipient…");
50
+
51
+ // Wallet, orders, queue, prices
52
+ await api.walletBalance();
53
+ await api.walletTransactions(20);
54
+ await api.createQueue([{ product: "stars", username: "@durov", amount: 100 }]);
55
+ await api.pricesFeed(); // {available, snapshot_at, stale, ttl_s, stars_ton}
56
+ ```
57
+
58
+ Every buy/bid/transfer method verifies the prepared payment locally
59
+ (structure, pinned addresses or principal coverage, fee ceiling,
60
+ spend limits, transfer payload decode + on-chain ownership) before
61
+ signing. A failed check throws `UntrustedPayment` and nothing is sent.
62
+
63
+ USDT note: like the Python SDK, USDT-denominated orders currently
64
+ stop at verification (`usdt_wallet` check) until the jetton payload
65
+ parser lands; TON orders are fully supported.
@@ -0,0 +1,112 @@
1
+ import { PreparedPayment } from "./verify";
2
+ export * from "./verify";
3
+ export declare const DEFAULT_BASE = "https://fragment-api.mboxcommunity.org";
4
+ /**
5
+ * Verify a webhook delivery's X-Fragment-Signature header.
6
+ *
7
+ * body: the RAW request body exactly as received (string or Buffer).
8
+ * signature: the X-Fragment-Signature header value ("sha256=<hex>").
9
+ * secret: the session's webhookSecret (returned once at session
10
+ * creation; the SDK stores it as api.webhookSecret). Returns true
11
+ * only on an exact HMAC-SHA256 match.
12
+ */
13
+ export declare function verifyWebhookSignature(body: string | Buffer, signature: string | null | undefined, secret: string): boolean;
14
+ export declare const SDK_UA: string;
15
+ export declare const PINNED_SERVICE_WALLETS: Set<string>;
16
+ export declare class SDKError extends Error {
17
+ code: string;
18
+ constructor(code: string, message?: string);
19
+ }
20
+ export interface FragmentAPIOptions {
21
+ apiKey?: string;
22
+ cookies: Record<string, string>;
23
+ /** 24-word TON mnemonic. Never leaves this machine. */
24
+ seed: string;
25
+ walletType?: "v4r2" | "w5";
26
+ base?: string;
27
+ maxTonPerOrder?: bigint;
28
+ maxUsdtPerOrder?: bigint;
29
+ maxFeePercent?: number;
30
+ }
31
+ export interface AccountObject {
32
+ address: string;
33
+ chain: string;
34
+ walletStateInit: string;
35
+ publicKey: string;
36
+ }
37
+ export declare class FragmentAPI {
38
+ readonly account: AccountObject;
39
+ private readonly opts;
40
+ private readonly ctx;
41
+ private sessionToken;
42
+ /** Session-scoped webhook secret, set at session creation. */
43
+ webhookSecret: string | null;
44
+ private constructor();
45
+ static create(opts: FragmentAPIOptions): Promise<FragmentAPI>;
46
+ private call;
47
+ private openSession;
48
+ private static unwrap;
49
+ buyStars(username: string, amount: number, opts?: BuyOptions): Promise<any>;
50
+ buyPremium(username: string, months: number, opts?: BuyOptions): Promise<any>;
51
+ private buy;
52
+ prices(): Promise<any>;
53
+ /** Polling snapshot; throws PRICES_UNAVAILABLE when the house
54
+ * session is absent/expired — prices are never invented. */
55
+ pricesFeed(): Promise<any>;
56
+ getOrder(orderId: string): Promise<any>;
57
+ walletBalance(): Promise<any>;
58
+ walletTransactions(limit?: number): Promise<any>;
59
+ /** Queue buy intents; the server prepares up to 5 items of a job
60
+ * in parallel. Signing stays per-order (see signPrepared). */
61
+ createQueue(items: Array<Record<string, unknown>>, callbackUrl?: string): Promise<any>;
62
+ getQueue(jobId: string): Promise<any>;
63
+ searchUsernames(q?: SearchOptions): Promise<any>;
64
+ searchNumbers(q?: SearchOptions): Promise<any>;
65
+ searchGifts(q?: SearchOptions & {
66
+ collection?: string;
67
+ view?: string;
68
+ }): Promise<any>;
69
+ private search;
70
+ usernameInfo(slug: string): Promise<any>;
71
+ numberInfo(number: string): Promise<any>;
72
+ giftInfo(slug: string): Promise<any>;
73
+ private itemInfo;
74
+ /** Bid `bid` TON on a username auction (verified + signed). */
75
+ bidUsername(slug: string, bid: string | number, opts?: BuyOptions): Promise<any>;
76
+ bidNumber(number: string, bid: string | number, opts?: BuyOptions): Promise<any>;
77
+ bidGift(slug: string, bid: string | number, opts?: BuyOptions): Promise<any>;
78
+ /** Buy a listed username at its sale price (instant buy). */
79
+ buyUsername(slug: string, opts?: BuyOptions): Promise<any>;
80
+ buyNumber(number: string, opts?: BuyOptions): Promise<any>;
81
+ buyGift(slug: string, opts?: BuyOptions): Promise<any>;
82
+ private marketplace;
83
+ /** Recharge a Telegram Ads account with `amount` TON of credit via
84
+ * Fragment (TON only). `account` is the Ads account identifier
85
+ * exactly as Fragment's ads UI shows it. */
86
+ buyAdsCredit(account: string, amount: string | number, opts?: BuyOptions): Promise<any>;
87
+ ownedUsernames(): Promise<any>;
88
+ ownedNumbers(): Promise<any>;
89
+ transferUsername(slug: string, toAddress: string): Promise<any>;
90
+ transferNumber(number: string, toAddress: string): Promise<any>;
91
+ transferGift(slug: string, toAddress: string, nftAddress?: string): Promise<any>;
92
+ private transfer;
93
+ private tonapiNftOwner;
94
+ /** Sign an ALREADY VERIFIED prepared payment and submit it. The
95
+ * buy methods run the matching checklist first; this stays public
96
+ * so queue-prepared orders can be signed + submitted one by one. */
97
+ signPrepared(order: {
98
+ id: string;
99
+ }, payment: PreparedPayment): Promise<any>;
100
+ }
101
+ export interface BuyOptions {
102
+ currency?: string;
103
+ idempotencyKey?: string;
104
+ maxCost?: string;
105
+ callbackUrl?: string;
106
+ }
107
+ export interface SearchOptions {
108
+ query?: string;
109
+ sort?: string;
110
+ filter?: string;
111
+ offset_id?: string;
112
+ }
package/dist/index.js ADDED
@@ -0,0 +1,447 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ exports.FragmentAPI = exports.SDKError = exports.PINNED_SERVICE_WALLETS = exports.SDK_UA = exports.DEFAULT_BASE = void 0;
18
+ exports.verifyWebhookSignature = verifyWebhookSignature;
19
+ /**
20
+ * Fragment API — JavaScript/TypeScript SDK with local signing.
21
+ *
22
+ * Mirrors the Python SDK (sdk/fragment_api_sdk.py): the seed is used
23
+ * ONLY on this machine — to derive the TON account object (public
24
+ * parts are sent to the API) and to sign prepared payments after the
25
+ * verification checklist in ./verify.ts passes. It is never
26
+ * transmitted. Signing uses @ton/ton wallet contracts directly (the
27
+ * same approach as the Python SDK's ton_helper.mjs).
28
+ *
29
+ * Spend limits are MANDATORY: nothing is signed until the caller sets
30
+ * per-order limits.
31
+ *
32
+ * Usage:
33
+ * const api = await FragmentAPI.create({
34
+ * cookies: {...}, seed: "24 words…", maxTonPerOrder: 5_000_000_000n});
35
+ * const order = await api.buyStars("@durov", 100);
36
+ *
37
+ * No API key is needed — sessions are keyless (your Fragment
38
+ * cookies are the credential). API keys are retired: the server
39
+ * rejects any request that presents one. Each session is issued a
40
+ * webhookSecret at creation (api.webhookSecret) for verifying
41
+ * webhook deliveries.
42
+ */
43
+ const node_crypto_1 = require("node:crypto");
44
+ const ton_1 = require("@ton/ton");
45
+ const crypto_1 = require("@ton/crypto");
46
+ const verify_1 = require("./verify");
47
+ __exportStar(require("./verify"), exports);
48
+ exports.DEFAULT_BASE = "https://fragment-api.mboxcommunity.org";
49
+ /**
50
+ * Verify a webhook delivery's X-Fragment-Signature header.
51
+ *
52
+ * body: the RAW request body exactly as received (string or Buffer).
53
+ * signature: the X-Fragment-Signature header value ("sha256=<hex>").
54
+ * secret: the session's webhookSecret (returned once at session
55
+ * creation; the SDK stores it as api.webhookSecret). Returns true
56
+ * only on an exact HMAC-SHA256 match.
57
+ */
58
+ function verifyWebhookSignature(body, signature, secret) {
59
+ if (!signature || !secret)
60
+ return false;
61
+ const raw = typeof body === "string" ? Buffer.from(body, "utf8") : body;
62
+ const expected = "sha256=" + (0, node_crypto_1.createHmac)("sha256", secret).update(raw).digest("hex");
63
+ const a = Buffer.from(expected);
64
+ const b = Buffer.from(String(signature).trim());
65
+ return a.length === b.length && (0, node_crypto_1.timingSafeEqual)(a, b);
66
+ }
67
+ // Explicit browser-like User-Agent: Cloudflare at our zone edge
68
+ // returns 1010/403 to default HTTP-client UAs.
69
+ exports.SDK_UA = "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 " +
70
+ "(KHTML, like Gecko) Chrome/126.0 Safari/537.36";
71
+ // Our service fee wallet, pinned in the SDK (a server can never
72
+ // rename it): the operator's Fragment wallet.
73
+ exports.PINNED_SERVICE_WALLETS = new Set([
74
+ "UQC3YLJkrL4hWykTbLNfR0oGjDm95f2wBhmllW5GdItX7fTA",
75
+ ]);
76
+ class SDKError extends Error {
77
+ code;
78
+ constructor(code, message = "") {
79
+ super(`${code}: ${message}`);
80
+ this.code = code;
81
+ }
82
+ }
83
+ exports.SDKError = SDKError;
84
+ async function deriveWallet(seed, walletType) {
85
+ const words = seed.trim().split(/\s+/);
86
+ const keyPair = await (0, crypto_1.mnemonicToPrivateKey)(words);
87
+ const wallet = walletType === "w5"
88
+ ? ton_1.WalletContractV5R1.create({ workchain: 0, publicKey: keyPair.publicKey })
89
+ : ton_1.WalletContractV4.create({ workchain: 0, publicKey: keyPair.publicKey });
90
+ const init = wallet.init;
91
+ const stateInit = (0, ton_1.beginCell)()
92
+ .storeUint(0b00110, 5)
93
+ .storeRef(init.code)
94
+ .storeRef(init.data)
95
+ .endCell();
96
+ return {
97
+ wallet,
98
+ secretKey: keyPair.secretKey,
99
+ addressFriendly: wallet.address.toString(),
100
+ account: {
101
+ address: wallet.address.toRawString(),
102
+ chain: "-239",
103
+ walletStateInit: stateInit.toBoc().toString("base64"),
104
+ publicKey: keyPair.publicKey.toString("hex"),
105
+ },
106
+ };
107
+ }
108
+ async function tonapiGet(path) {
109
+ const resp = await fetch("https://tonapi.io/v2" + path, {
110
+ headers: { Accept: "application/json", "User-Agent": exports.SDK_UA },
111
+ });
112
+ if (!resp.ok)
113
+ throw new SDKError("TONAPI_ERROR", `status ${resp.status}`);
114
+ return resp.json();
115
+ }
116
+ class FragmentAPI {
117
+ account;
118
+ opts;
119
+ ctx;
120
+ sessionToken = null;
121
+ /** Session-scoped webhook secret, set at session creation. */
122
+ webhookSecret = null;
123
+ constructor(opts, ctx) {
124
+ this.ctx = ctx;
125
+ this.account = ctx.account;
126
+ this.opts = {
127
+ cookies: opts.cookies,
128
+ seed: opts.seed,
129
+ walletType: opts.walletType ?? "v4r2",
130
+ base: (opts.base ?? exports.DEFAULT_BASE).replace(/\/$/, ""),
131
+ maxFeePercent: opts.maxFeePercent ?? 1.0,
132
+ apiKey: opts.apiKey,
133
+ maxTonPerOrder: opts.maxTonPerOrder,
134
+ maxUsdtPerOrder: opts.maxUsdtPerOrder,
135
+ };
136
+ }
137
+ static async create(opts) {
138
+ if (opts.maxTonPerOrder === undefined
139
+ && opts.maxUsdtPerOrder === undefined) {
140
+ throw new SDKError("LIMITS_REQUIRED", "set maxTonPerOrder / maxUsdtPerOrder");
141
+ }
142
+ if (!opts.cookies || !opts.seed) {
143
+ throw new SDKError("VALIDATION_ERROR", "cookies and seed are required");
144
+ }
145
+ const ctx = await deriveWallet(opts.seed, opts.walletType ?? "v4r2");
146
+ return new FragmentAPI(opts, ctx);
147
+ }
148
+ // ---------- HTTP ----------
149
+ async call(method, path, body, auth = false) {
150
+ const headers = {
151
+ "Content-Type": "application/json",
152
+ "User-Agent": exports.SDK_UA,
153
+ };
154
+ if (auth) {
155
+ if (!this.sessionToken)
156
+ await this.openSession();
157
+ headers.Authorization = `Bearer ${this.sessionToken}`;
158
+ }
159
+ let resp;
160
+ try {
161
+ resp = await fetch(this.opts.base + path, {
162
+ method, headers,
163
+ body: body !== undefined ? JSON.stringify(body) : undefined,
164
+ });
165
+ }
166
+ catch (e) {
167
+ throw new SDKError("NETWORK_ERROR", String(e).slice(0, 200));
168
+ }
169
+ const payload = await resp.json().catch(() => null);
170
+ if (!resp.ok || !payload) {
171
+ const err = (payload && payload.error) || {};
172
+ throw new SDKError(err.error_code || "HTTP_ERROR", err.message || `status ${resp.status}`);
173
+ }
174
+ return payload;
175
+ }
176
+ async openSession() {
177
+ // Keyless only — API keys are retired; the server rejects a
178
+ // request that presents one (API_KEYS_RETIRED), so the SDK never
179
+ // sends the legacy apiKey option any more.
180
+ const body = {
181
+ cookies: this.opts.cookies, account: this.account,
182
+ };
183
+ const out = await this.call("POST", "/api/v1/session", body);
184
+ if (!out.success) {
185
+ const err = out.error || {};
186
+ throw new SDKError(err.error_code || "AUTH_FAILED", err.message || "");
187
+ }
188
+ this.sessionToken = out.session_token;
189
+ // Session-scoped webhook secret (issued once, at creation):
190
+ // webhooks for this session's orders are signed with it. Verify
191
+ // deliveries with verifyWebhookSignature(body, signature,
192
+ // api.webhookSecret).
193
+ this.webhookSecret = out.webhook_secret ?? null;
194
+ }
195
+ static unwrap(out, key) {
196
+ if (!out.success) {
197
+ const err = out.error || {};
198
+ throw new SDKError(err.error_code || "REQUEST_FAILED", err.message || "");
199
+ }
200
+ return out[key];
201
+ }
202
+ // ---------- purchases ----------
203
+ async buyStars(username, amount, opts = {}) {
204
+ return this.buy("stars", username, { ...opts, amount });
205
+ }
206
+ async buyPremium(username, months, opts = {}) {
207
+ return this.buy("premium", username, { ...opts, months });
208
+ }
209
+ async buy(product, username, opts) {
210
+ const path = product === "premium"
211
+ ? "/api/v1/premium/buy" : "/api/v1/stars/buy";
212
+ const currency = opts.currency ?? "TON";
213
+ const out = await this.call("POST", path, {
214
+ username, currency, amount: opts.amount ?? null,
215
+ months: opts.months ?? null,
216
+ idempotency_key: opts.idempotencyKey ?? null,
217
+ max_cost: opts.maxCost ?? null,
218
+ callback_url: opts.callbackUrl ?? null,
219
+ }, true);
220
+ const order = FragmentAPI.unwrap(out, "order");
221
+ const payment = out.payment;
222
+ // THE trust boundary: verify before signing.
223
+ (0, verify_1.verifyPayment)({ product, currency }, payment, {
224
+ ownWalletAddress: this.account.address,
225
+ pinnedServiceWallets: exports.PINNED_SERVICE_WALLETS,
226
+ maxFeePercent: this.opts.maxFeePercent,
227
+ maxTonPerOrder: this.opts.maxTonPerOrder,
228
+ maxUsdtPerOrder: this.opts.maxUsdtPerOrder,
229
+ });
230
+ return this.signPrepared(order, payment);
231
+ }
232
+ // ---------- prices ----------
233
+ async prices() {
234
+ return this.call("GET", "/api/v1/prices");
235
+ }
236
+ /** Polling snapshot; throws PRICES_UNAVAILABLE when the house
237
+ * session is absent/expired — prices are never invented. */
238
+ async pricesFeed() {
239
+ return this.call("GET", "/api/v1/prices/feed");
240
+ }
241
+ // ---------- orders / wallet / queue ----------
242
+ async getOrder(orderId) {
243
+ const out = await this.call("GET", `/api/v1/orders/${orderId}`, undefined, true);
244
+ return out.order;
245
+ }
246
+ async walletBalance() {
247
+ const out = await this.call("GET", "/api/v1/wallet/balance", undefined, true);
248
+ return out.wallet;
249
+ }
250
+ async walletTransactions(limit = 20) {
251
+ const out = await this.call("GET", `/api/v1/wallet/transactions?limit=${limit}`, undefined, true);
252
+ return out.wallet;
253
+ }
254
+ /** Queue buy intents; the server prepares up to 5 items of a job
255
+ * in parallel. Signing stays per-order (see signPrepared). */
256
+ async createQueue(items, callbackUrl) {
257
+ const out = await this.call("POST", "/api/v1/queue", { items, callback_url: callbackUrl ?? null }, true);
258
+ return FragmentAPI.unwrap(out, "queue");
259
+ }
260
+ async getQueue(jobId) {
261
+ const out = await this.call("GET", `/api/v1/queue/${jobId}`, undefined, true);
262
+ return out.queue;
263
+ }
264
+ // ---------- marketplace ----------
265
+ async searchUsernames(q = {}) {
266
+ return this.search("usernames", q);
267
+ }
268
+ async searchNumbers(q = {}) {
269
+ return this.search("numbers", q);
270
+ }
271
+ async searchGifts(q = {}) {
272
+ return this.search("gifts", q);
273
+ }
274
+ async search(plural, q) {
275
+ const params = new URLSearchParams();
276
+ params.set("query", q.query ?? "");
277
+ const fields = {
278
+ sort: q.sort, filter: q.filter, offset_id: q.offset_id,
279
+ collection: q.collection, view: q.view,
280
+ };
281
+ for (const [k, v] of Object.entries(fields)) {
282
+ if (v)
283
+ params.set(k, v);
284
+ }
285
+ const out = await this.call("GET", `/api/v1/${plural}/search?${params}`, undefined, true);
286
+ return { items: out.items, next_offset_id: out.next_offset_id };
287
+ }
288
+ async usernameInfo(slug) {
289
+ return this.itemInfo("usernames", slug);
290
+ }
291
+ async numberInfo(number) {
292
+ return this.itemInfo("numbers", number);
293
+ }
294
+ async giftInfo(slug) {
295
+ return this.itemInfo("gifts", slug);
296
+ }
297
+ async itemInfo(plural, slug) {
298
+ const out = await this.call("GET", `/api/v1/${plural}/${slug}`, undefined, true);
299
+ return out.item;
300
+ }
301
+ /** Bid `bid` TON on a username auction (verified + signed). */
302
+ async bidUsername(slug, bid, opts = {}) {
303
+ return this.marketplace("usernames", slug, "bid", { ...opts, bid });
304
+ }
305
+ async bidNumber(number, bid, opts = {}) {
306
+ return this.marketplace("numbers", number, "bid", { ...opts, bid });
307
+ }
308
+ async bidGift(slug, bid, opts = {}) {
309
+ return this.marketplace("gifts", slug, "bid", { ...opts, bid });
310
+ }
311
+ /** Buy a listed username at its sale price (instant buy). */
312
+ async buyUsername(slug, opts = {}) {
313
+ return this.marketplace("usernames", slug, "buy", opts);
314
+ }
315
+ async buyNumber(number, opts = {}) {
316
+ return this.marketplace("numbers", number, "buy", opts);
317
+ }
318
+ async buyGift(slug, opts = {}) {
319
+ return this.marketplace("gifts", slug, "buy", opts);
320
+ }
321
+ async marketplace(plural, slug, action, opts) {
322
+ const body = {
323
+ idempotency_key: opts.idempotencyKey ?? null,
324
+ max_cost: opts.maxCost ?? null,
325
+ callback_url: opts.callbackUrl ?? null,
326
+ };
327
+ if (action === "bid")
328
+ body.bid = String(opts.bid);
329
+ const out = await this.call("POST", `/api/v1/${plural}/${slug}/${action}`, body, true);
330
+ const order = FragmentAPI.unwrap(out, "order");
331
+ const payment = out.payment;
332
+ const detail = order.detail || {};
333
+ (0, verify_1.verifyMarketplacePayment)(detail, payment, {
334
+ ownWalletAddress: this.account.address,
335
+ expectedPrincipalNano: BigInt(detail.principal_nano),
336
+ pinnedServiceWallets: exports.PINNED_SERVICE_WALLETS,
337
+ maxFeePercent: this.opts.maxFeePercent,
338
+ maxTonPerOrder: this.opts.maxTonPerOrder,
339
+ });
340
+ return this.signPrepared(order, payment);
341
+ }
342
+ // ---------- ads credit ----------
343
+ /** Recharge a Telegram Ads account with `amount` TON of credit via
344
+ * Fragment (TON only). `account` is the Ads account identifier
345
+ * exactly as Fragment's ads UI shows it. */
346
+ async buyAdsCredit(account, amount, opts = {}) {
347
+ const out = await this.call("POST", "/api/v1/ads/recharge", {
348
+ account, amount: String(amount),
349
+ idempotency_key: opts.idempotencyKey ?? null,
350
+ max_cost: opts.maxCost ?? null,
351
+ callback_url: opts.callbackUrl ?? null,
352
+ }, true);
353
+ const order = FragmentAPI.unwrap(out, "order");
354
+ const payment = out.payment;
355
+ const detail = order.detail || {};
356
+ (0, verify_1.verifyMarketplacePayment)(detail, payment, {
357
+ ownWalletAddress: this.account.address,
358
+ expectedPrincipalNano: BigInt(detail.principal_nano),
359
+ pinnedServiceWallets: exports.PINNED_SERVICE_WALLETS,
360
+ maxFeePercent: this.opts.maxFeePercent,
361
+ maxTonPerOrder: this.opts.maxTonPerOrder,
362
+ });
363
+ return this.signPrepared(order, payment);
364
+ }
365
+ // ---------- owned assets + NFT transfers ----------
366
+ async ownedUsernames() {
367
+ const out = await this.call("GET", "/api/v1/usernames/owned", undefined, true);
368
+ return out.owned;
369
+ }
370
+ async ownedNumbers() {
371
+ const out = await this.call("GET", "/api/v1/numbers/owned", undefined, true);
372
+ return out.owned;
373
+ }
374
+ async transferUsername(slug, toAddress) {
375
+ return this.transfer("usernames", slug, toAddress);
376
+ }
377
+ async transferNumber(number, toAddress) {
378
+ return this.transfer("numbers", number, toAddress);
379
+ }
380
+ async transferGift(slug, toAddress, nftAddress) {
381
+ return this.transfer("gifts", slug, toAddress, nftAddress);
382
+ }
383
+ async transfer(plural, slug, toAddress, nftAddress) {
384
+ const body = { to_address: toAddress };
385
+ if (nftAddress)
386
+ body.nft_address = nftAddress;
387
+ const out = await this.call("POST", `/api/v1/${plural}/${slug}/transfer`, body, true);
388
+ const order = FragmentAPI.unwrap(out, "order");
389
+ const payment = out.payment;
390
+ const detail = order.detail || {};
391
+ // Independent on-chain read (tonapi, SDK-side): the item must be
392
+ // in OUR wallet, in the pinned collection for its kind.
393
+ const { owner, collection } = await this.tonapiNftOwner(detail.nft_address, detail.kind);
394
+ (0, verify_1.verifyTransfer)(detail, payment, {
395
+ ownWalletAddress: this.account.address,
396
+ nftOwnerAddress: owner,
397
+ nftCollectionAddress: collection,
398
+ maxTonPerOrder: this.opts.maxTonPerOrder,
399
+ });
400
+ return this.signPrepared(order, payment);
401
+ }
402
+ async tonapiNftOwner(nftAddressRaw, kind) {
403
+ const own = this.account.address;
404
+ let path = `/accounts/${own}/nfts?limit=100`;
405
+ const pinned = verify_1.PINNED_COLLECTIONS[kind || ""];
406
+ if (pinned)
407
+ path += `&collection=${pinned}`;
408
+ const data = await tonapiGet(path);
409
+ for (const it of data.nft_items || []) {
410
+ if ((it.address || "").toLowerCase()
411
+ === (nftAddressRaw || "").toLowerCase()) {
412
+ return { owner: own, collection: it.collection?.address };
413
+ }
414
+ }
415
+ throw new SDKError("NFT_NOT_FOUND_ONCHAIN", `${nftAddressRaw} not in the wallet's NFTs`);
416
+ }
417
+ // ---------- signing ----------
418
+ /** Sign an ALREADY VERIFIED prepared payment and submit it. The
419
+ * buy methods run the matching checklist first; this stays public
420
+ * so queue-prepared orders can be signed + submitted one by one. */
421
+ async signPrepared(order, payment) {
422
+ const seqnoData = await tonapiGet(`/blockchain/accounts/${this.ctx.addressFriendly}`);
423
+ const seqno = Number(seqnoData.seqno || 0);
424
+ const validUntil = Math.min(Number(payment.valid_until), Math.floor(Date.now() / 1000) + verify_1.MAX_SIGNED_TTL_S);
425
+ const messages = payment.messages.map((m) => (0, ton_1.internal)({
426
+ to: ton_1.Address.parse(m.address),
427
+ value: BigInt(m.amount),
428
+ body: m.payload ? ton_1.Cell.fromBase64(m.payload) : undefined,
429
+ // @ton/core accepts a stateInit Cell at runtime (the Python
430
+ // helper passes it the same way); its .d.ts types it narrower.
431
+ init: m.stateInit ? ton_1.Cell.fromBase64(m.stateInit) : undefined,
432
+ }));
433
+ // V4/V5R1 createTransfer signatures differ in the .d.ts union;
434
+ // the runtime call is identical for both (as in ton_helper.mjs).
435
+ const transfer = this.ctx.wallet.createTransfer({
436
+ seqno,
437
+ secretKey: this.ctx.secretKey,
438
+ messages,
439
+ sendMode: 3,
440
+ timeout: validUntil,
441
+ });
442
+ const boc = transfer.toBoc().toString("base64");
443
+ const out = await this.call("POST", `/api/v1/orders/${order.id}/submit`, { boc }, true);
444
+ return FragmentAPI.unwrap(out, "order");
445
+ }
446
+ }
447
+ exports.FragmentAPI = FragmentAPI;
@@ -0,0 +1,77 @@
1
+ export declare const PINNED_FRAGMENT_ADDRESSES: Set<string>;
2
+ export declare const PINNED_COLLECTIONS: Record<string, string>;
3
+ export declare const DEFAULT_MAX_FEE_PERCENT = 0.01;
4
+ export declare const HARD_MAX_FEE_PERCENT = 5;
5
+ export declare const MAX_SIGNED_TTL_S = 120;
6
+ export declare const NFT_TRANSFER_OP = 1607220500;
7
+ export declare class UntrustedPayment extends Error {
8
+ check: string;
9
+ code: string;
10
+ constructor(check: string, detail?: string);
11
+ }
12
+ export interface PreparedMessage {
13
+ address: string;
14
+ amount: string;
15
+ payload?: string;
16
+ stateInit?: string;
17
+ role?: string;
18
+ }
19
+ export interface PreparedPayment {
20
+ valid_until: number;
21
+ network?: string;
22
+ from?: string;
23
+ messages: PreparedMessage[];
24
+ }
25
+ export interface VerifySummary {
26
+ fragment_amount: bigint;
27
+ fee_amount: bigint;
28
+ total_amount: bigint;
29
+ currency: string;
30
+ principal_amount?: bigint;
31
+ }
32
+ /** Checklist for Stars/Premium purchases (same as the Python SDK). */
33
+ export declare function verifyPayment(order: {
34
+ product?: string;
35
+ currency?: string;
36
+ }, payment: PreparedPayment, opts: {
37
+ ownWalletAddress: string;
38
+ ownUsdtWallet?: string;
39
+ pinnedServiceWallets: Set<string>;
40
+ maxFeePercent?: number;
41
+ maxTonPerOrder?: bigint;
42
+ maxUsdtPerOrder?: bigint;
43
+ }): VerifySummary;
44
+ /**
45
+ * Checklist for marketplace payments (bids, fixed-price buys, ads
46
+ * credit). Fragment sends these to the item's auction/NFT contract —
47
+ * not a pinned purchase address — so the checklist pins the ECONOMICS:
48
+ * fragment legs must cover the principal the client itself asked for,
49
+ * the fee leg obeys the pinned wallet + ceiling, and the grand total
50
+ * obeys the mandatory spend limit.
51
+ */
52
+ export declare function verifyMarketplacePayment(order: Record<string, unknown>, payment: PreparedPayment, opts: {
53
+ ownWalletAddress: string;
54
+ expectedPrincipalNano: bigint;
55
+ pinnedServiceWallets: Set<string>;
56
+ maxFeePercent?: number;
57
+ maxTonPerOrder?: bigint;
58
+ }): VerifySummary;
59
+ /**
60
+ * Checklist for a prepared NFT transfer. nftOwnerAddress /
61
+ * nftCollectionAddress come from the SDK's OWN tonapi read of the
62
+ * item (never from the API server).
63
+ */
64
+ export declare function verifyTransfer(order: {
65
+ kind?: string;
66
+ nft_address?: string;
67
+ to_address?: string;
68
+ amount_nano?: number;
69
+ }, payment: PreparedPayment, opts: {
70
+ ownWalletAddress: string;
71
+ nftOwnerAddress?: string;
72
+ nftCollectionAddress?: string;
73
+ maxTonPerOrder?: bigint;
74
+ }): {
75
+ total_amount: bigint;
76
+ currency: string;
77
+ };
package/dist/verify.js ADDED
@@ -0,0 +1,237 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.UntrustedPayment = exports.NFT_TRANSFER_OP = exports.MAX_SIGNED_TTL_S = exports.HARD_MAX_FEE_PERCENT = exports.DEFAULT_MAX_FEE_PERCENT = exports.PINNED_COLLECTIONS = exports.PINNED_FRAGMENT_ADDRESSES = void 0;
4
+ exports.verifyPayment = verifyPayment;
5
+ exports.verifyMarketplacePayment = verifyMarketplacePayment;
6
+ exports.verifyTransfer = verifyTransfer;
7
+ /**
8
+ * Prepared-payment verification — the local-signing safety checklist.
9
+ *
10
+ * TypeScript port of engine/verify.py (shared with the Python SDK).
11
+ * The SDK runs these checks BEFORE signing, on the customer's own
12
+ * machine. Any failure throws UntrustedPayment and nothing is signed.
13
+ */
14
+ const core_1 = require("@ton/core");
15
+ // Fragment's own receiving addresses, pinned in code (never trusted
16
+ // from a server response).
17
+ exports.PINNED_FRAGMENT_ADDRESSES = new Set([
18
+ "UQBAjaOyi2wGWlk-EDkSabqqnF-MrrwMadnwqrurKpkla4QB",
19
+ "UQCFJEP4WZ_mpdo0_kMEmsTgvrMHG7K_tWY16pQhKHwoOtFz",
20
+ "UQBeab7D38RIwypegbN7YZgQzwDbb8QfMMwY8ouJc3qPl4CJ",
21
+ ]);
22
+ // Telegram collectible collections on TON (verified via tonapi
23
+ // 2026-11-29). Gift collections are per-design, so no pinned gift
24
+ // collection exists — gift transfers pin ownership + payload instead.
25
+ exports.PINNED_COLLECTIONS = {
26
+ username: "EQCA14o1-VWhS2efqoh_9M1b_A9DtKTuoqfmkn83AbJzwnPi",
27
+ number: "EQAOQdwdw8kGftJCSFgOErM1mBjYPe4DBPq8-AhF6vr9si5N",
28
+ };
29
+ exports.DEFAULT_MAX_FEE_PERCENT = 0.01; // our service fee
30
+ exports.HARD_MAX_FEE_PERCENT = 5.0; // absolute cap
31
+ exports.MAX_SIGNED_TTL_S = 120; // signed message lifetime
32
+ exports.NFT_TRANSFER_OP = 0x5fcc3d14;
33
+ class UntrustedPayment extends Error {
34
+ check;
35
+ code = "UNTRUSTED_PAYMENT";
36
+ constructor(check, detail = "") {
37
+ super(`UNTRUSTED_PAYMENT [${check}] ${detail}`);
38
+ this.check = check;
39
+ }
40
+ }
41
+ exports.UntrustedPayment = UntrustedPayment;
42
+ function raw(addr) {
43
+ try {
44
+ return core_1.Address.parse(addr).toRawString().toLowerCase();
45
+ }
46
+ catch {
47
+ throw new UntrustedPayment("address", `unparseable: ${addr}`);
48
+ }
49
+ }
50
+ function checkNetworkPayer(payment, ownWallet) {
51
+ if (payment.network !== undefined && payment.network !== "-239") {
52
+ throw new UntrustedPayment("network", String(payment.network));
53
+ }
54
+ if (payment.from && payment.from !== ownWallet) {
55
+ throw new UntrustedPayment("payer", "payment.from is not the own wallet");
56
+ }
57
+ }
58
+ function feeCheck(fee, base, pinnedServiceWallets, maxFeePercent) {
59
+ if (!fee)
60
+ return 0n;
61
+ if (!pinnedServiceWallets.has(fee.address)) {
62
+ throw new UntrustedPayment("fee_address", fee.address);
63
+ }
64
+ const feeAmount = BigInt(fee.amount || "0");
65
+ if (base > 0n && Number(feeAmount) * 100 / Number(base) > maxFeePercent) {
66
+ throw new UntrustedPayment("fee_ceiling", `fee ${feeAmount} > ${maxFeePercent}% of ${base}`);
67
+ }
68
+ return feeAmount;
69
+ }
70
+ /** Checklist for Stars/Premium purchases (same as the Python SDK). */
71
+ function verifyPayment(order, payment, opts) {
72
+ const maxFeePercent = opts.maxFeePercent ?? exports.DEFAULT_MAX_FEE_PERCENT;
73
+ const msgs = payment.messages || [];
74
+ checkNetworkPayer(payment, opts.ownWalletAddress);
75
+ const roles = msgs.map((m) => m.role);
76
+ if (roles.includes("middle")) {
77
+ throw new UntrustedPayment("structure", "middle leg in a KYC order");
78
+ }
79
+ if (roles.filter((r) => r === "fragment").length !== 1) {
80
+ throw new UntrustedPayment("structure", `roles=${roles}`);
81
+ }
82
+ if (roles.some((r) => r !== "fragment" && r !== "fee")) {
83
+ throw new UntrustedPayment("structure", `unknown role in ${roles}`);
84
+ }
85
+ const frag = msgs[roles.indexOf("fragment")];
86
+ const fee = roles.includes("fee") ? msgs[roles.indexOf("fee")] : undefined;
87
+ const currency = (order.currency || "TON").toUpperCase();
88
+ if (currency === "TON") {
89
+ if (!exports.PINNED_FRAGMENT_ADDRESSES.has(frag.address)) {
90
+ throw new UntrustedPayment("fragment_address", frag.address);
91
+ }
92
+ }
93
+ else {
94
+ if (!opts.ownUsdtWallet) {
95
+ throw new UntrustedPayment("usdt_wallet", "own USDT wallet unknown");
96
+ }
97
+ if (frag.address !== opts.ownUsdtWallet) {
98
+ throw new UntrustedPayment("usdt_wallet", frag.address);
99
+ }
100
+ }
101
+ const fragAmount = BigInt(frag.amount || "0");
102
+ const feeAmount = feeCheck(fee, fragAmount, opts.pinnedServiceWallets, maxFeePercent);
103
+ const total = fragAmount + feeAmount;
104
+ if (currency === "TON") {
105
+ if (opts.maxTonPerOrder === undefined) {
106
+ throw new UntrustedPayment("limits", "maxTonPerOrder not set");
107
+ }
108
+ if (total > opts.maxTonPerOrder) {
109
+ throw new UntrustedPayment("limits", `total ${total} over TON limit`);
110
+ }
111
+ }
112
+ else {
113
+ if (opts.maxUsdtPerOrder === undefined) {
114
+ throw new UntrustedPayment("limits", "maxUsdtPerOrder not set");
115
+ }
116
+ if (total > opts.maxUsdtPerOrder) {
117
+ throw new UntrustedPayment("limits", `total ${total} over USDT limit`);
118
+ }
119
+ }
120
+ return { fragment_amount: fragAmount, fee_amount: feeAmount,
121
+ total_amount: total, currency };
122
+ }
123
+ /**
124
+ * Checklist for marketplace payments (bids, fixed-price buys, ads
125
+ * credit). Fragment sends these to the item's auction/NFT contract —
126
+ * not a pinned purchase address — so the checklist pins the ECONOMICS:
127
+ * fragment legs must cover the principal the client itself asked for,
128
+ * the fee leg obeys the pinned wallet + ceiling, and the grand total
129
+ * obeys the mandatory spend limit.
130
+ */
131
+ function verifyMarketplacePayment(order, payment, opts) {
132
+ const maxFeePercent = opts.maxFeePercent ?? exports.DEFAULT_MAX_FEE_PERCENT;
133
+ const msgs = payment.messages || [];
134
+ checkNetworkPayer(payment, opts.ownWalletAddress);
135
+ const roles = msgs.map((m) => m.role);
136
+ if (roles.includes("middle")) {
137
+ throw new UntrustedPayment("structure", "middle leg in a KYC order");
138
+ }
139
+ if (roles.some((r) => r !== "fragment" && r !== "fee")) {
140
+ throw new UntrustedPayment("structure", `unknown role in ${roles}`);
141
+ }
142
+ if (roles.filter((r) => r === "fragment").length < 1) {
143
+ throw new UntrustedPayment("structure", "no fragment leg");
144
+ }
145
+ if (roles.filter((r) => r === "fee").length > 1) {
146
+ throw new UntrustedPayment("structure", "multiple fee legs");
147
+ }
148
+ const principal = opts.expectedPrincipalNano;
149
+ const fragTotal = msgs.filter((m) => m.role === "fragment")
150
+ .reduce((s, m) => s + BigInt(m.amount || "0"), 0n);
151
+ const fee = msgs.find((m) => m.role === "fee");
152
+ if (fragTotal < principal) {
153
+ throw new UntrustedPayment("principal", `attached ${fragTotal} < principal ${principal}`);
154
+ }
155
+ const feeAmount = feeCheck(fee, principal, opts.pinnedServiceWallets, maxFeePercent);
156
+ const total = fragTotal + feeAmount;
157
+ if (opts.maxTonPerOrder === undefined) {
158
+ throw new UntrustedPayment("limits", "maxTonPerOrder not set");
159
+ }
160
+ if (total > opts.maxTonPerOrder) {
161
+ throw new UntrustedPayment("limits", `total ${total} over TON limit`);
162
+ }
163
+ return { fragment_amount: fragTotal, fee_amount: feeAmount,
164
+ total_amount: total, currency: "TON",
165
+ principal_amount: principal };
166
+ }
167
+ /**
168
+ * Checklist for a prepared NFT transfer. nftOwnerAddress /
169
+ * nftCollectionAddress come from the SDK's OWN tonapi read of the
170
+ * item (never from the API server).
171
+ */
172
+ function verifyTransfer(order, payment, opts) {
173
+ const msgs = payment.messages || [];
174
+ checkNetworkPayer(payment, opts.ownWalletAddress);
175
+ if (msgs.length !== 1 || msgs[0].role !== "transfer") {
176
+ throw new UntrustedPayment("structure", `roles=${msgs.map((m) => m.role)}`);
177
+ }
178
+ const msg = msgs[0];
179
+ if (raw(msg.address) !== raw(order.nft_address || "")) {
180
+ throw new UntrustedPayment("nft_address", msg.address);
181
+ }
182
+ const amount = BigInt(msg.amount || "0");
183
+ if (amount !== BigInt(order.amount_nano || 0)) {
184
+ throw new UntrustedPayment("amount", `${amount} != ${order.amount_nano}`);
185
+ }
186
+ if (opts.maxTonPerOrder === undefined) {
187
+ throw new UntrustedPayment("limits", "maxTonPerOrder not set");
188
+ }
189
+ if (amount > opts.maxTonPerOrder) {
190
+ throw new UntrustedPayment("limits", `total ${amount} over TON limit`);
191
+ }
192
+ if (!msg.payload) {
193
+ throw new UntrustedPayment("payload", "transfer payload missing");
194
+ }
195
+ let op, newOwner, forwardAmount;
196
+ try {
197
+ const s = core_1.Cell.fromBase64(msg.payload).beginParse();
198
+ op = s.loadUint(32);
199
+ s.loadUint(64); // query_id
200
+ newOwner = s.loadAddress();
201
+ s.loadAddress(); // response_destination
202
+ if (s.loadBit())
203
+ s.loadRef(); // custom_payload — skip
204
+ forwardAmount = s.loadCoins();
205
+ }
206
+ catch (e) {
207
+ throw new UntrustedPayment("payload", `undecodable: ${e}`);
208
+ }
209
+ if (op !== exports.NFT_TRANSFER_OP) {
210
+ throw new UntrustedPayment("payload", `op ${op.toString(16)}`);
211
+ }
212
+ if (!newOwner
213
+ || newOwner.toRawString().toLowerCase()
214
+ !== raw(order.to_address || "")) {
215
+ throw new UntrustedPayment("payload", "new_owner mismatch");
216
+ }
217
+ if (forwardAmount >= amount) {
218
+ throw new UntrustedPayment("payload", "forward_amount >= value");
219
+ }
220
+ if (!opts.nftOwnerAddress) {
221
+ throw new UntrustedPayment("ownership", "no independent owner read");
222
+ }
223
+ if (raw(opts.nftOwnerAddress) !== raw(opts.ownWalletAddress)) {
224
+ throw new UntrustedPayment("ownership", "NFT is not owned by the own wallet");
225
+ }
226
+ const kind = order.kind || "";
227
+ if (kind in exports.PINNED_COLLECTIONS) {
228
+ if (!opts.nftCollectionAddress) {
229
+ throw new UntrustedPayment("collection", "no collection read");
230
+ }
231
+ if (raw(opts.nftCollectionAddress)
232
+ !== raw(exports.PINNED_COLLECTIONS[kind])) {
233
+ throw new UntrustedPayment("collection", opts.nftCollectionAddress);
234
+ }
235
+ }
236
+ return { total_amount: amount, currency: "TON" };
237
+ }
package/package.json CHANGED
@@ -1,6 +1,29 @@
1
1
  {
2
+ "dependencies": {
3
+ "@ton/core": "^0.62.0",
4
+ "@ton/crypto": "^3.3.0",
5
+ "@ton/ton": "^15.1.0"
6
+ },
7
+ "description": "JavaScript/TypeScript SDK for the Fragment API (local signing: your seed never leaves your machine). Mirrors the Python SDK's REST surface \u2014 Stars/Premium, marketplace (usernames, +888 numbers, gifts), Telegram Ads credit, wallet, queue.",
8
+ "devDependencies": {
9
+ "@types/node": "^22.0.0",
10
+ "typescript": "^5.6.0"
11
+ },
12
+ "engines": {
13
+ "node": ">=18"
14
+ },
15
+ "files": [
16
+ "dist",
17
+ "README.md"
18
+ ],
19
+ "license": "MIT",
20
+ "main": "dist/index.js",
2
21
  "name": "@mboxcommunity/fragment-api-sdk",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
22
+ "scripts": {
23
+ "build": "tsc",
24
+ "prepare": "tsc"
25
+ },
26
+ "type": "commonjs",
27
+ "types": "dist/index.d.ts",
28
+ "version": "0.1.1"
6
29
  }