import { AxiosInstance } from 'axios'; export { fromNano, toNano } from '@ton/ton'; /** * Credentials and runtime configuration for a {@link Fragment} client. */ /** Credentials grabbed from an authenticated fragment.com session + TON providers. */ interface FragmentCredentials { /** Per-request CSRF hash from the Fragment page (`?hash=...`). */ hash?: string; /** Cookie: `stel_ssid`. */ stelSsid?: string; /** Cookie: `stel_dt` (timezone offset, e.g. `"-180"`). */ stelDt?: string; /** Cookie: `stel_token`. */ stelToken?: string; /** Cookie: `stel_ton_token`. */ stelTonToken?: string; /** API key for toncenter.com (balances + sending TON). */ toncenterApiKey?: string; /** API key for tonconsole / tonapi.io (alternative balance source). */ tonconsoleApiKey?: string; /** Wallet mnemonic seed (space-separated words) — only needed to send TON. */ walletSeed?: string; } /** Full client configuration: credentials plus transport options. */ interface FragmentConfig extends FragmentCredentials { /** Request timeout in milliseconds (default `30000`). */ timeout?: number; /** * Inject a custom axios instance — primarily for testing * (e.g. with `axios-mock-adapter`). */ axiosInstance?: AxiosInstance; } /** Credentials with all fields present (empty string when unset). */ type ResolvedCredentials = Required; /** * Structured error type returned inside {@link Result} objects. * * Errors are never thrown by the public API — every method returns * `{ ok: false, error: FragmentError }` on failure. `FragmentError` still * extends `Error` so it carries a stack trace and works with `instanceof`. */ /** Discriminator describing the category of a failure. */ type FragmentErrorCode = /** Bad or missing input parameters. */ "VALIDATION" /** Missing/invalid credentials, or a 401/403 from Fragment. */ | "AUTH" /** Transport failure: timeout, DNS, connection reset, etc. */ | "NETWORK" /** The remote API responded but signalled an error (non-2xx or `ok: false`). */ | "API" /** The response could not be parsed into the expected shape. */ | "PARSE" /** A resource was not found (e.g. nickname has no recipient). */ | "NOT_FOUND" /** Wallet balance is lower than the requested transfer amount. */ | "INSUFFICIENT_FUNDS" /** Anything that doesn't fit the buckets above. */ | "UNKNOWN"; /** Extra context attached to a {@link FragmentError}. */ interface FragmentErrorOptions { /** HTTP status code, when the failure came from an HTTP response. */ status?: number; /** The underlying error / payload that caused this one. */ cause?: unknown; /** Arbitrary structured details (e.g. the raw API body). */ details?: unknown; } declare class FragmentError extends Error { readonly code: FragmentErrorCode; readonly status?: number; readonly details?: unknown; constructor(code: FragmentErrorCode, message: string, options?: FragmentErrorOptions); /** Serialize to a plain object (safe for logging / JSON). */ toJSON(): { name: string; code: FragmentErrorCode; message: string; status?: number; }; } /** * A discriminated-union result type. Every public method resolves to one of * these instead of throwing. * * ```ts * const res = await client.stars.getPrice({ quantity: 50 }); * if (res.ok) { * console.log(res.data.curPrice.TON); * } else { * console.error(res.error.code, res.error.message); * } * ``` */ interface Ok { ok: true; data: T; } interface Err { ok: false; error: E; } type Result = Ok | Err; /** Build a success result. */ declare function ok(data: T): Ok; /** Build a failure result. */ declare function err(error: E): Err; /** Type guard narrowing a {@link Result} to its success branch. */ declare function isOk(result: Result): result is Ok; /** Type guard narrowing a {@link Result} to its failure branch. */ declare function isErr(result: Result): result is Err; /** * Thin axios wrapper. Every method returns a {@link Result} — transport and * HTTP errors are mapped to a structured {@link FragmentError} instead of being * thrown. */ interface HttpClientOptions { /** Inject a pre-built axios instance (used by tests). */ axiosInstance?: AxiosInstance; /** Request timeout in ms (default `30000`). Ignored if `axiosInstance` is set. */ timeout?: number; } interface RequestOptions { params?: Record; headers?: Record; } declare class HttpClient { /** The underlying axios instance (exposed so tests can mock it). */ readonly axios: AxiosInstance; constructor(options?: HttpClientOptions); /** POST `application/x-www-form-urlencoded`, parse a JSON response. */ postForm(url: string, data: Record, options?: RequestOptions): Promise>; /** * POST `application/x-www-form-urlencoded` and return both the parsed JSON * body and any `Set-Cookie` headers. Used by the TON Connect proof flow, which * mints a fresh `stel_ton_token` delivered via `Set-Cookie`. */ postFormRaw(url: string, data: Record, options?: RequestOptions): Promise>; /** GET, parse a JSON response. */ getJson(url: string, options?: RequestOptions): Promise>; /** GET, return the raw response body as text. */ getText(url: string, options?: RequestOptions): Promise>; private request; private toFragmentError; } /** * Shared runtime state handed to every service: the resolved (mutable) * credentials and the HTTP client. */ declare class FragmentContext { /** Live credentials — mutated by `update()` and `auth.fetchHash()`. */ credentials: ResolvedCredentials; readonly http: HttpClient; constructor(config?: FragmentConfig); /** Merge in new credential values. */ update(creds: Partial): void; /** `https://fragment.com/api?hash=...` for the configured hash. */ apiUrl(): string; apiHeaders(): Record; htmlHeaders(): Record; } /** Base class for all services — just holds the shared context. */ declare abstract class BaseService { protected readonly ctx: FragmentContext; constructor(ctx: FragmentContext); } /** * Public domain types and method parameter objects. * * Result *data* shapes we build ourselves use camelCase. A few types mirror raw * Fragment API responses and keep the wire field names (e.g. `req_id`). */ interface FetchHashParams { /** Page to scrape the api hash from. Defaults to `https://fragment.com/`. */ url?: string; } interface FetchHashData { hash: string; } interface NickToHashParams { /** The @username to look up (without the `@`). */ nickname: string; } /** Raw Fragment API response for a username search. */ interface NickToHashData { ok: boolean; found?: { myself?: boolean; recipient: string; photo?: string; name?: string; }; error?: string; [key: string]: unknown; } interface DecodePayloadParams { /** Base64-encoded payload string. */ payload: string; } interface DecodePayloadData { /** The original (un-decoded) base64 payload. */ payload: string; /** The decoded, human-readable comment text. */ decoded: string; } interface GetStarsPriceParams { /** Number of stars (number or numeric string). */ quantity: number | string; } interface StarsPrice { ok: boolean; curPrice: { /** Price in TON, e.g. `"0.2774"`. */ TON: string; /** Price in USD, e.g. `"1.5"`. */ USDT: string; }; } /** Payment method accepted by Fragment's Stars checkout. */ type StarsPaymentMethod = "ton" | "usdt_ton" | "usdt_eth" | "usdt_pol" | "usdc_eth" | "usdc_base" | "usdc_pol"; interface InitStarsPaymentParams { /** Recipient hash (from {@link NickToHashData}). */ recipient: string; /** Amount of stars to buy. */ quantity: number; /** * Payment currency/chain. Defaults to `"ton"` (native TON, signable with a * wallet seed via {@link V4R2Service.send}). */ paymentMethod?: StarsPaymentMethod; } /** Raw Fragment API response for `initBuyStarsRequest`. */ interface PaymentInit { req_id: string; myself?: boolean; to_bot?: boolean; amount: string; /** Set by Fragment when no TON wallet is connected to the account. */ need_ton?: boolean; error?: string; [key: string]: unknown; } interface GetPaymentInfoParams { /** The `req_id` returned by {@link StarsService.initPayment}. */ requestId: string; /** Whether to reveal the sender's name to the recipient. Defaults to `false`. */ showSender?: boolean; /** * TON Connect account JSON for the wallet that will pay. Fragment's website * sends this **with the `getBuyStarsLink` call itself** (see the generic * `Wallet.sendTransaction` in `auction.js`), which is how Fragment binds the * order to the paying wallet and returns a usable `confirm_method` / * `confirm_params`. **Omitting it means the on-chain TON is never matched to * the order, so Stars are not credited** even though the TON debits. Build it * with {@link WalletService.getAccount}. */ account?: TonConnectAccount; /** Optional device override; a default Tonkeeper hint is used otherwise. */ device?: TonConnectDevice; } interface PaymentMessage { address: string; amount: string; payload: string; } /** Raw Fragment API response for `getBuyStarsLink`. */ interface PaymentInfo { ok: boolean; transaction?: { validUntil?: number; from?: string; messages: PaymentMessage[]; }; /** * Fragment-side method that **must** be POSTed after the TON transfer lands, * carrying `{account, device, boc, ...confirm_params}`. Without this final * call Fragment never matches the on-chain payment to the `req_id`, so Stars * are not credited — even though the TON debits successfully. */ confirm_method?: string; /** Extra fields Fragment expects in the {@link confirm_method} POST. */ confirm_params?: Record; /** Set by Fragment when the purchase needs extra verification. */ need_verify?: boolean; error?: string; [key: string]: unknown; } /** * TON Connect-style account JSON Fragment expects in the post-broadcast confirm * call. Build with {@link WalletService.getAccount} from your `walletSeed`. */ interface TonConnectAccount { /** Raw address, e.g. `0:00b9fa57...`. */ address: string; /** Public key in hex (no `0x` prefix). */ publicKey: string; /** `"-239"` for mainnet, `"-3"` for testnet. */ chain: string; /** Base64 BoC of the wallet's StateInit cell. */ walletStateInit: string; } /** * TON Connect-style device JSON sent alongside {@link TonConnectAccount}. * Fragment doesn't verify the contents, so a hardcoded "Tonkeeper" hint is * enough. */ interface TonConnectDevice { platform: string; appName: string; appVersion: string; maxProtocolVersion: number; features: unknown[]; } /** * A signed TON Connect `ton_proof` — the wallet's proof of ownership Fragment * verifies in `checkTonProofAuth`. Shape matches `wallet.connectItems.tonProof.proof` * on fragment.com. Build with {@link WalletService.signTonProof}. */ interface TonProof { /** Unix seconds when the proof was signed. */ timestamp: number; /** The app domain the proof is bound to (e.g. `fragment.com`). */ domain: { lengthBytes: number; value: string; }; /** Base64 ed25519 signature over the TON Connect proof message. */ signature: string; /** The challenge Fragment issued (its page's `ton_proof`). */ payload: string; /** Base64 BoC of the wallet StateInit. */ state_init?: string; } interface SignTonProofParams { /** The `ton_proof` challenge issued by Fragment (scraped from its page). */ payload: string; /** App domain to bind the proof to. Defaults to `"fragment.com"`. */ domain?: string; } interface ConnectTonWalletData { /** Whether Fragment accepted the proof (`verified: true`). */ verified: boolean; /** The fresh `stel_ton_token` minted by Fragment (also stored on the client). */ tonToken?: string; } interface ConfirmStarsPaymentParams { /** `confirm_method` returned by {@link StarsService.getPaymentInfo}. */ method: string; /** `confirm_params` returned by {@link StarsService.getPaymentInfo}. */ params?: Record; /** TonConnect account JSON for the wallet that paid. */ account: TonConnectAccount; /** Base64 BoC of the external message that was broadcast on-chain. */ boc: string; /** Optional device override; a default Tonkeeper hint is used otherwise. */ device?: TonConnectDevice; } interface ConfirmStarsPaymentData { ok: boolean; [key: string]: unknown; } interface PurchaseStarsParams { /** Recipient hash (from {@link NickToHashData}). */ recipient: string; /** Amount of stars to buy. */ quantity: number; /** Whether to reveal the sender's name to the recipient. Defaults to `false`. */ showSender?: boolean; /** Optional device override; a default Tonkeeper hint is used otherwise. */ device?: TonConnectDevice; /** * Wait for the TON transfer to be confirmed on-chain before returning * (Fragment credits Stars off the confirmed payment). Defaults to `true`. */ waitForConfirmation?: boolean; } interface WaitConfirmationParams { /** Base64 BoC of the broadcast external message (from {@link SendTonData}). */ boc: string; /** Sender wallet address; derived from `walletSeed` when omitted. */ address?: string; /** Overall timeout in ms. Defaults to `90000`. */ timeoutMs?: number; /** Poll interval in ms. Defaults to `5000`. */ pollIntervalMs?: number; } interface WaitConfirmationData { /** The on-chain transaction hash (base64) that consumed the message. */ txHash: string; } interface PurchaseStarsData { /** The `req_id` of the matched Fragment order. */ reqId: string; /** TON amount sent, in human form (e.g. `0.4561`). */ amount: number; /** TON amount sent, in exact nanoTON. */ amountNano: string; /** Destination address (Fragment's collector wallet). */ destination: string; /** Sender wallet (derived from {@link FragmentCredentials.walletSeed}). */ sender: string; /** Base64 BoC of the external message that was broadcast. */ boc: string; /** On-chain tx hash once confirmed (empty if `waitForConfirmation: false`). */ txHash: string; } interface GetPremiumPriceParams { /** Subscription length in months (default `12`). */ months?: number; } interface PremiumOption { duration: string | null; priceTon: string | null; priceUsd: string | null; sale: string | null; } interface PremiumPrice { options: PremiumOption[]; tonRate: number | null; } interface LiteServer { ip: number; port: number; id: { "@type": string; key: string; }; /** Human-readable dotted IP, added by {@link TonService.getRandomLiteServer}. */ ip_readable?: string; [key: string]: unknown; } interface TonGlobalConfig { liteservers: LiteServer[]; [key: string]: unknown; } interface GetBalanceParams { /** TON wallet address to query. */ address: string; } interface WalletBalance { nano: number; ton: number; source: "toncenter" | "tonconsole"; } interface SendTonParams { /** Recipient TON address. */ destinationAddress: string; /** * Amount in human TON (e.g. `0.21`). Provide this **or** {@link amountNano}. * Convenient, but goes through a decimal→nano conversion. */ amount?: number; /** * Exact amount in nanoTON (e.g. Fragment's `msg.amount` string). Provide this * **or** {@link amount}. Preferred when forwarding a Fragment payment — it is * exact and avoids float rounding / the `/1e9` mistake. */ amountNano?: string | bigint; /** Optional plain **text** comment. Ignored if {@link payloadCell} is set. */ payload?: string; /** * Exact message body as a **base64 BoC cell** (e.g. Fragment's `msg.payload`). * Preferred for Stars/Fragment payments — it is byte-identical to what the * website sends via TON Connect, so Fragment matches the `Ref#…`. A * re-encoded text comment may not match. */ payloadCell?: string; } /** A wallet address in both user-friendly and raw forms. */ interface WalletAddress { /** User-friendly form, e.g. `EQAAuf...` / `UQAAuf...`. */ friendly: string; /** Raw form, e.g. `0:00b9fa57...` — compare this with a Fragment `transaction.from`. */ raw: string; } interface SendTonData { destination: string; /** Amount sent, in human TON. */ amount: number; /** Amount sent, in exact nanoTON. */ amountNano: string; payload: string; /** Sender wallet address. */ sender: string; /** * Base64 BoC of the external message that was broadcast — pass this verbatim * as `boc` to {@link StarsService.confirmPayment}. Fragment matches Stars * orders by this BoC, so it must come from the same signed message we sent. */ boc: string; balanceBefore: { nano: number; ton: number; }; } interface UserProfile { name?: string; username?: string; avatar?: string | null; verified?: boolean; wallet?: string; walletVerified?: boolean; } interface Session { device?: string; status?: string; location?: string; datetime?: string; dateText?: string; sessionId?: string; } interface SessionList { account: { username?: string; avatar?: string; tonWallet?: string; [key: string]: unknown; }; sessions: Session[]; } /** Authenticated account info: profile and active sessions. */ declare class AccountService extends BaseService { /** * Get the authenticated account's Fragment profile. * * @example * ```ts * const res = await client.account.getProfile(); * if (res.ok) console.log(res.data.username, res.data.wallet); * ``` */ getProfile(): Promise>; /** * Get the list of active sessions plus basic account info. * * @example * ```ts * const res = await client.account.getSessions(); * if (res.ok) console.log(res.data.account.username, res.data.sessions.length); * ``` */ getSessions(): Promise>; } /** Exported for unit testing. */ declare function parseProfile(html: string): UserProfile; /** Exported for unit testing. */ declare function parseSessions(html: string): SessionList; /** Session / authentication helpers. */ declare class AuthService extends BaseService { /** * Scrape the per-session api `hash` from a Fragment page and store it in the * client config, so you don't have to copy it by hand. * * Requires the `stel_*` cookies to already be configured. The extracted hash * is saved into the client (subsequent calls use it automatically). * * @example * ```ts * const res = await client.auth.fetchHash(); * if (res.ok) console.log("hash:", res.data.hash); * ``` */ fetchHash({ url, }?: FetchHashParams): Promise>; } /** Telegram Premium gift pricing (scraped from the gift page). */ declare class PremiumService extends BaseService { /** * Get Telegram Premium gift pricing options for a given duration. * * @example * ```ts * const res = await client.premium.getPrice({ months: 12 }); * if (res.ok) console.log(res.data.tonRate, res.data.options); * ``` */ getPrice({ months, }?: GetPremiumPriceParams): Promise>; } /** Exported for unit testing. */ declare function parsePremium(html: string): PremiumPrice; /** v4r2 wallet transfers. */ declare class V4R2Service extends BaseService { /** * Send TON from your v4r2 wallet, attaching an optional text comment. * * Requires `toncenterApiKey` and `walletSeed`. Performs a balance check * before broadcasting. * * Pass the amount **either** as `amount` (human TON, e.g. `0.21`) **or** * `amountNano` (exact nanoTON, e.g. Fragment's `msg.amount`). Prefer * `amountNano` when forwarding a Fragment payment — it's exact and avoids the * float-division footgun. * * @example * ```ts * // human amount * await client.ton.wallet.v4r2.send({ destinationAddress: "UQ...", amount: 0.21 }); * * // exact Fragment payment — pass amount + payload straight from getPaymentInfo * await client.ton.wallet.v4r2.send({ * destinationAddress: msg.address, * amountNano: msg.amount, // "456100000" * payloadCell: msg.payload, // exact BoC cell, byte-matches the site * }); * ``` */ send({ destinationAddress, amount, amountNano, payload, payloadCell, }: SendTonParams): Promise>; } /** TON wallet operations: balance + nested v4r2 transfers. */ declare class WalletService extends BaseService { readonly v4r2: V4R2Service; constructor(ctx: FragmentContext); /** * Derive your wallet's v4r2 address from the configured `walletSeed` — no * network. Compare `raw` with a Fragment `transaction.from` to confirm the * payment will originate from the wallet the order expects. * * @example * ```ts * const me = await client.ton.wallet.getAddress(); * if (me.ok) console.log(me.data.friendly, me.data.raw); * ``` */ getAddress(): Promise>; /** * Build the TON Connect-style account JSON Fragment expects in the * post-broadcast confirm call (see {@link StarsService.confirmPayment}). * * The shape matches what `tonConnectUI.wallet.account` carries on * fragment.com — raw address, hex public key, mainnet chain, and the BoC of * the wallet's StateInit. * * @example * ```ts * const account = await client.ton.wallet.getAccount(); * if (account.ok) console.log(account.data.address); * ``` */ getAccount(): Promise>; /** * Sign a TON Connect `ton_proof` challenge with your `walletSeed`. * * Wallet-side of Fragment's TON Connect login. Normally you don't call this * directly — {@link connectTonWallet} scrapes the challenge and runs the whole * handshake for you. */ signTonProof({ payload, domain, }: SignTonProofParams): Promise>; /** * Establish a **fully-proven** TON Connect session with Fragment from your * `walletSeed`, and store the fresh `stel_ton_token` on the client. * * Fragment accepts an ordinary `stel_ton_token` for *creating* Stars orders, * but it only **credits** a purchase when the paying wallet's TON Connect * session was proven this session (`checkTonProofAuth` → `verified: true`) — * the same handshake fragment.com runs on every page load. Without it the TON * debits but Stars never arrive. {@link StarsService.purchase} calls this * automatically; call it yourself before a manual buy flow. * * @example * ```ts * const c = await client.ton.wallet.connectTonWallet(); * if (c.ok && c.data.verified) console.log("session proven ✅"); * ``` */ connectTonWallet({ url, }?: { url?: string; }): Promise>; /** * Poll toncenter until the broadcast external message lands in a confirmed * transaction — the same wait the working Go client does before it considers a * purchase done. Fragment credits Stars off the confirmed on-chain payment, so * this both confirms success and gives Fragment's watcher time to see it. * * @example * ```ts * const tx = await client.ton.wallet.v4r2.send({ ... }); * if (tx.ok) await client.ton.wallet.waitForConfirmation({ boc: tx.data.boc }); * ``` */ waitForConfirmation({ boc, address, timeoutMs, pollIntervalMs, }: WaitConfirmationParams): Promise>; /** * Check a TON wallet balance. Uses toncenter when `toncenterApiKey` is set, * otherwise tonconsole (tonapi.io) when `tonconsoleApiKey` is set. * * @example * ```ts * const res = await client.ton.wallet.getBalance({ address: "UQ..." }); * if (res.ok) console.log(res.data.ton); * ``` */ getBalance({ address, }: GetBalanceParams): Promise>; private balanceFromToncenter; private balanceFromTonconsole; } /** Telegram Stars: pricing and the purchase flow. */ declare class StarsService extends BaseService { private readonly wallet; constructor(ctx: FragmentContext, wallet: WalletService); /** * Get the current price for a given quantity of Telegram Stars. * * @example * ```ts * const res = await client.stars.getPrice({ quantity: 5050 }); * if (res.ok) console.log(res.data.curPrice.TON, res.data.curPrice.USDT); * ``` */ getPrice({ quantity, }: GetStarsPriceParams): Promise>; /** * Initialize a Stars purchase for a recipient. * * Sends `payment_method` (default `"ton"`) — this is **required** by Fragment; * omitting it yields `Access denied`. If the Fragment account has no connected * wallet, the response carries `need_ton`, surfaced here as an `AUTH` error. * * @example * ```ts * const res = await client.stars.initPayment({ recipient, quantity: 50 }); * if (res.ok) console.log(res.data.req_id, res.data.amount); * ``` */ initPayment({ recipient, quantity, paymentMethod, }: InitStarsPaymentParams): Promise>; /** Sync the session's Stars buy state (TON price) like the website's poller. */ private syncBuyState; /** * Get the on-chain transaction (address, amount, payload) for a Stars purchase * initialized with {@link StarsService.initPayment}. The returned * `transaction.messages[0]` can be signed and broadcast with * {@link V4R2Service.send}. * * @example * ```ts * const info = await client.stars.getPaymentInfo({ requestId }); * if (info.ok) { * const msg = info.data.transaction!.messages[0]!; * // msg.address, msg.amount, msg.payload * } * ``` */ getPaymentInfo({ requestId, showSender, account, device, }: GetPaymentInfoParams): Promise>; /** * Tell Fragment that a Stars TON payment has been broadcast. * * The website does this automatically after TonConnect signs the transfer * (see `Wallet.sendTransaction` in `auction.js`). It POSTs the `confirm_method` * returned by {@link getPaymentInfo} with `{account, device, boc, ...confirm_params}`. * **Without this call Fragment never matches the on-chain TON to the order**, * so Stars are not credited — even though the TON debits successfully. * * @example * ```ts * const tx = await client.ton.wallet.v4r2.send({ ... }); * const account = await client.ton.wallet.getAccount(); * if (tx.ok && account.ok) { * await client.stars.confirmPayment({ * method: info.data.confirm_method!, * params: info.data.confirm_params, * account: account.data, * boc: tx.data.boc, * }); * } * ``` */ confirmPayment({ method, params, account, device, boc, }: ConfirmStarsPaymentParams): Promise>; /** * High-level Stars purchase — runs Fragment's real flow end-to-end: * `initBuyStarsRequest` → `getBuyStarsLink` (bound to your wallet `account`) * → broadcast the TON transfer → wait for on-chain confirmation. * * This mirrors a known-good headless implementation: Fragment credits Stars * off the confirmed on-chain payment matched to the order — there is **no * post-broadcast `confirm_method` POST** and **no TON Connect proof** in this * path (both are available as {@link confirmPayment} / {@link WalletService.connectTonWallet} * for the website-style flow, but are not needed here). * * Requires `walletSeed` and `toncenterApiKey` in addition to the usual * `stel_*` cookies + `hash`. **The paying wallet must be the one connected to * your Fragment session** (v4r2, derived from `walletSeed`). * * @example * ```ts * const user = await client.users.nickToHash({ nickname: "maksim_dremin" }); * if (!user.ok) return; * const res = await client.stars.purchase({ * recipient: user.data.found!.recipient, * quantity: 50, * }); * if (res.ok) console.log("Stars sent:", res.data.amount, "TON, tx", res.data.txHash); * ``` */ purchase({ recipient, quantity, showSender, device, waitForConfirmation, }: PurchaseStarsParams): Promise>; } /** Convert a (possibly signed) int32 IP to a dotted-decimal string. */ declare function intToIp(ipInt: number): string; /** TON blockchain: liteservers and wallet operations. */ declare class TonService extends BaseService { readonly wallet: WalletService; constructor(ctx: FragmentContext); /** Fetch the full TON global config (contains the liteserver list). */ getLiteServers(): Promise>; /** * Pick a random liteserver, with the integer IP resolved to a readable * `ip_readable` field. * * @example * ```ts * const res = await client.ton.getRandomLiteServer(); * if (res.ok) console.log(res.data.ip_readable, res.data.port); * ``` */ getRandomLiteServer(): Promise>; } /** Username lookups against the Fragment API. */ declare class UsersService extends BaseService { /** * Resolve a Telegram nickname to its Fragment `recipient` hash. * * @example * ```ts * const res = await client.users.nickToHash({ nickname: "durov" }); * if (res.ok) console.log(res.data.found?.recipient); * ``` */ nickToHash({ nickname, }: NickToHashParams): Promise>; } /** Stateless helpers (no network). */ declare class UtilsService extends BaseService { /** * Decode a base64 transaction payload into its readable comment text. * * @example * ```ts * const res = client.utils.decodePayload({ payload: "te6ccg..." }); * if (res.ok) console.log(res.data.decoded); * ``` */ decodePayload({ payload, }: DecodePayloadParams): Result; /** * Convert human TON to exact nanoTON (1 TON = 1e9 nanoTON), with no floating * point. `toTon("0.4561")` → `456100000n`. */ toNano(ton: string | number): bigint; /** * Convert nanoTON to a human TON decimal string. `fromNano("456100000")` → * `"0.4561"`. Safe alternative to `Number(nano) / 1e9`. */ fromNano(nano: string | bigint): string; } /** * Main entry point — a class-based, fully-typed client for Fragment.com. * * ```ts * import { Fragment } from "telegram-fragment-api"; * * const client = new Fragment({ * hash: "...", * stelSsid: "...", * stelToken: "...", * stelTonToken: "...", * toncenterApiKey: "...", * walletSeed: "word1 word2 ...", * }); * * const res = await client.stars.getPrice({ quantity: 5050 }); * if (res.ok) console.log(res.data.curPrice.TON); * else console.error(res.error.code, res.error.message); * ``` */ declare class Fragment { private readonly ctx; /** Session / authentication helpers (`fetchHash`). */ readonly auth: AuthService; /** Username lookups (`nickToHash`). */ readonly users: UsersService; /** Stateless helpers (`decodePayload`). */ readonly utils: UtilsService; /** Telegram Stars (`getPrice`, `initPayment`, `getPaymentInfo`). */ readonly stars: StarsService; /** Telegram Premium (`getPrice`). */ readonly premium: PremiumService; /** TON blockchain (`getRandomLiteServer`, `wallet.getBalance`, `wallet.v4r2.send`). */ readonly ton: TonService; /** Authenticated account info (`getProfile`, `getSessions`). */ readonly account: AccountService; constructor(config?: FragmentConfig); /** Update credentials at runtime (chainable). */ configure(credentials: Partial): this; /** A read-only snapshot of the current credentials. */ getCredentials(): ResolvedCredentials; } /** * Pure base64 payload decoder (no network). Extracts the readable comment text * carried by a Fragment transaction cell. */ /** * Decode a Fragment transaction `payload` (base64 cell) into the readable * comment text it carries, e.g. `"50 Telegram Stars\n\nRef#Im2y5itd6"`. */ declare function decodePayload(payload: string): string; export { AccountService, AuthService, type ConfirmStarsPaymentData, type ConfirmStarsPaymentParams, type ConnectTonWalletData, type DecodePayloadData, type DecodePayloadParams, type Err, type FetchHashData, type FetchHashParams, Fragment, type FragmentConfig, type FragmentCredentials, FragmentError, type FragmentErrorCode, type FragmentErrorOptions, type GetBalanceParams, type GetPaymentInfoParams, type GetPremiumPriceParams, type GetStarsPriceParams, type InitStarsPaymentParams, type LiteServer, type NickToHashData, type NickToHashParams, type Ok, type PaymentInfo, type PaymentInit, type PaymentMessage, type PremiumOption, type PremiumPrice, PremiumService, type PurchaseStarsData, type PurchaseStarsParams, type ResolvedCredentials, type Result, type SendTonData, type SendTonParams, type Session, type SessionList, type SignTonProofParams, type StarsPaymentMethod, type StarsPrice, StarsService, type TonConnectAccount, type TonConnectDevice, type TonGlobalConfig, type TonProof, TonService, type UserProfile, UsersService, UtilsService, V4R2Service, type WaitConfirmationData, type WaitConfirmationParams, type WalletAddress, type WalletBalance, WalletService, decodePayload, Fragment as default, err, intToIp, isErr, isOk, ok, parsePremium, parseProfile, parseSessions };