@anywalletkit/wallet-ton 0.2.2 → 0.2.4
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/dist/index.cjs +14 -18
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +4 -4
- package/dist/index.d.ts +4 -4
- package/dist/index.js +15 -19
- package/dist/index.js.map +1 -1
- package/package.json +9 -6
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts","../src/buffer-global.ts","../src/types.ts","../src/errors.ts","../src/toncenter.ts","../src/emulation.ts","../src/wallet-v5r1.ts","../src/describe.ts","../src/read-only-account.ts","../src/account.ts","../src/manager.ts","../src/history.ts"],"sourcesContent":["import { installBufferGlobal } from './buffer-global.js'\ninstallBufferGlobal()\nexport { installBufferGlobal }\nexport * from './types.js'\nexport * from './errors.js'\nexport { createTonClient } from './client.js'\nexport { TonCenter, createTonRpc, tonCenterEndpoint, emulateExternal, parseEmulation, type TonAccountState, type TonAccountStatus, type GetMethodResult, type EmulationVerdict } from './toncenter.js'\nexport { emulateViaTonapi, parseTonapiConsequences, parseTonapiTrace, parseTonapiRisk, runEmulation, resolveEmulate, DEFAULT_TONAPI, type EmulationOutcome, type EmulationSource, type EmulateOptions } from './emulation.js'\nexport {\n V5R1_CODE_HEX, V5R1_OP, MAINNET_GLOBAL_ID, TESTNET_GLOBAL_ID, DEFAULT_SEND_MODE, MAX_ACTIONS,\n v5r1Code, v5r1WalletId, v5r1StateInit, v5r1Address, v5r1SigningMessage, v5r1PackSigned, v5r1PackUnsigned, v5r1ExternalMessage, parseV5R1Body,\n type V5R1Message, type V5R1SigningParams, type V5R1WalletIdParts, type ParsedV5R1Body,\n} from './wallet-v5r1.js'\nexport {\n describeTransaction, describeMessageRelaxed, decodeBody, commentCell, JETTON_TRANSFER_OP,\n type TonDescription, type TonDescribedMessage, type TonDescribedKind, type TonJettonDetails, type TonWarning, type TonWarningCode, type DecodedBody,\n} from './describe.js'\nexport { WalletAccountReadOnlyTon, SEND_MODE } from './read-only-account.js'\nexport { WalletAccountTon } from './account.js'\nexport { WalletManagerTon, TON_BASE_PATH, TON_MNEMONIC_PATH } from './manager.js'\nexport {\n createTonHistory, mapTonapiEvent, mapToncenterTransaction, mapActions as mapTonapiActions, valueFlowTransfers, rawTonAddress, tonExplorerTxUrl, HistoryUnavailableError,\n encodeCursor as encodeHistoryCursor, decodeCursor as decodeHistoryCursor,\n type TonHistoryOptions, type TonHistorySource, type TonHistoryPage, type TonChainTx, type TonHistoryRaw, type TonHistoryBackend, type TonHistoryCursor, type TonapiEvent, type TonapiAction, type V3Transaction, type HistoryFetch,\n} from './history.js'\nexport { WalletManagerTon as default } from './manager.js'\n","// @ton/core and @ton/crypto read the GLOBAL `Buffer` (Node convention). Browsers\n// and Hermes have none, so the package installs the `buffer` polyfill once, at\n// import time, only when it is missing. Node and React Native entries that\n// already set it are untouched. Called as a function from index.ts (not a bare\n// import): bundlers drop bare imports of modules they consider side-effect\n// free, and this one was silently dropped from dist before.\nimport { Buffer } from 'buffer'\n\n/**\n * Set `globalThis.Buffer` to the `buffer` polyfill when the runtime has none (Hermes, browsers).\n * Runs on import.\n */\nexport function installBufferGlobal(): void {\n const g = globalThis as { Buffer?: unknown }\n g.Buffer ??= Buffer\n}\n\ninstallBufferGlobal()\n","import type { Cell, StateInit } from '@ton/core'\n\n/** A toncenter v2 JSON-RPC endpoint (api keys there are meant for client-side wallets). */\nexport interface TonEndpoint { url: string; secretKey?: string }\n\n/** Anything that can answer a toncenter v2 JSON-RPC call (an endpoint wrapper, a test double, a proxy). */\nexport interface TonRpc {\n call<T = unknown>(method: string, params: Record<string, unknown>): Promise<T>\n}\n\n/** A toncenter endpoint (URL and optional key) or a ready `TonRpc`. */\nexport type TonProvider = TonEndpoint | TonRpc\n\n/**\n * Options for a TON wallet manager or account: toncenter endpoints, network, fee caps and emulation\n * before signing.\n */\nexport interface TonConfig {\n /** toncenter endpoint(s) or `TonRpc`(s). A list fails over in order. Omit for an offline (sign-only) wallet. */\n tonClient?: TonProvider | TonProvider[]\n /** Alias of `tonClient`. */\n provider?: TonProvider | TonProvider[]\n /** Extra rounds across the endpoint list after the first full pass (default 3). */\n retries?: number\n /** Per-request timeout in ms (default 15 000). */\n timeoutMs?: number\n /** Injectable fetch (tests, custom agents). Defaults to globalThis.fetch. */\n fetch?: typeof fetch\n /** Max fee (nanotons) for `transfer`. */\n transferMaxFee?: bigint | number\n /** Max fee (nanotons) for `sendTransaction` / `signTransaction`. */\n transactionMaxFee?: bigint | number\n /** toncenter v3 base used for receipts (default https://toncenter.com/api/v3). */\n indexerUrl?: string\n /** tonapi base used for fee rates and (by default) emulation (default https://tonapi.io/v2). */\n tonApiUrl?: string\n /** tonapi bearer key (sent as `Authorization: Bearer …`); also sent as X-API-Key to a toncenter-v3 emulator. */\n tonApiKey?: string\n /**\n * Preflight emulation of every send (zero-signed external). Default\n * `{kind: 'tonapi'}`: `POST {tonApiUrl}/wallet/emulate` (verdict + `risk`),\n * falling back to `/traces/emulate`. `{kind: 'toncenter-v3', url}` posts to a\n * toncenter `emulateTrace` endpoint instead. `false` = `estimateFee` only.\n * A non-zero compute exit, an aborted transaction, a failed action phase or a\n * failed FIRST-HOP internal message throws `SimulationError` before signing.\n */\n emulate?: TonEmulateConfig\n /** @deprecated Use `emulate: {kind: 'toncenter-v3', url}`. Still honoured when `emulate` is unset. */\n emulateUrl?: string\n /**\n * Allow a body whose emulated `risk.transfer_all_remaining_balance` is true\n * (send mode 128 / CARRY_ALL_BALANCE). Refused by default — nothing this\n * wallet builds does that, so it only ever comes from a foreign `bodyBoc`.\n */\n allowDrainingTransactions?: boolean\n /** Run the preflight (estimateFee + emulation when configured) before signing. Default true. */\n simulate?: boolean\n /** Seconds a signed external stays valid (default 60, max 600). */\n validUntilSeconds?: number\n /** Nanotons attached to a jetton transfer on top of `forwardTonAmount` (default 0.05 TON). */\n jettonAttachedValue?: bigint | number | string\n /**\n * 'mainnet' (ton:-239, default) or 'testnet' (ton:-3). Sets the CAIP-2 id, the address flags and the\n * wallet_id network (-239 / -3), so a testnet wallet has its own address and its signed messages are\n * not valid on mainnet (as in Tonkeeper and @ton/ton).\n */\n network?: 'mainnet' | 'testnet'\n /**\n * V5R1 wallet_id parts. Defaults (network id from `network`, subwallet 0) give the\n * addresses Tonkeeper and Tonhub derive for a key; change the subwallet only to\n * reach a wallet that was created with a different one. A networkGlobalId that\n * contradicts `network` is refused.\n */\n walletId?: { networkGlobalId?: number; subwalletNumber?: number }\n}\n\n/** One internal message. `value` in nanotons. `body`: text comment or a Cell; `bodyBoc`: the same as base64 BoC. */\nexport interface TonTransaction {\n to: string\n value: bigint | number | string\n /** Defaults to the flag in a friendly address (EQ… bounceable, UQ… not); raw addresses default to bounceable. */\n bounceable?: boolean\n body?: string | Cell\n /** Prebuilt message body as base64 BoC (e.g. an Omniston escrow payload). Ignored when `body` is set. */\n bodyBoc?: string\n /** StateInit to attach (deploys the destination): `{code, data}`, a StateInit cell, or its base64 BoC. */\n stateInit?: StateInit | Cell | string\n /** Send mode for this message (default PAY_GAS_SEPARATELY; IGNORE_ERRORS is always OR-ed in for externals). */\n sendMode?: number\n}\n\n/**\n * What `sendTransaction` / `signTransaction` accept: one message, several\n * messages in ONE external (up to 255 — swaps need it), or an already signed\n * V5R1 external-message body Cell.\n */\nexport type TonSendable = TonTransaction | TonTransaction[] | Cell\n\n/** A native TON or jetton transfer. Amount in nanotons or the jetton's base units. */\nexport interface TonTransferOptions {\n /** Jetton master address. Omit for native TON. */\n token?: string\n /** Wallet address that receives (for a jetton, its owner, not its jetton wallet). */\n recipient: string\n amount: bigint | number | string\n /** Jetton only: nanotons forwarded to the recipient with the transfer notification (default 1). */\n forwardTonAmount?: bigint | number | string\n /** Jetton only: forward payload — a text comment or a Cell (DEX / escrow payloads). */\n forwardPayload?: Cell | string\n /**\n * Text memo (a deposit memo, an exchange tag). Jetton: sent as the forward-payload comment (TEP-74);\n * native TON: the message comment. Cannot be combined with `forwardPayload`.\n */\n memo?: string\n /** Jetton only: custom payload cell (rarely needed; e.g. mintless jettons). */\n customPayload?: Cell\n /** Jetton only: where excess TON returns (default: this wallet). */\n responseDestination?: string\n /** Jetton only: query id (default random). */\n queryId?: bigint | number\n /** Jetton only: nanotons attached to the jetton-wallet call (default config.jettonAttachedValue + forwardTonAmount). */\n attachedValue?: bigint | number | string\n}\n\n/** toncenter `estimateFee` source fees, nanotons. */\nexport interface TonFees {\n inFwdFee: bigint\n storageFee: bigint\n gasFee: bigint\n fwdFee: bigint\n /** Sum of the four. */\n total: bigint\n}\n\n/**\n * Where to emulate a transaction before signing: tonapi, a toncenter v3 endpoint, or `false` for a\n * fee estimate only.\n */\nexport type TonEmulateConfig =\n | { kind: 'tonapi'; url?: string }\n | { kind: 'toncenter-v3'; url: string }\n | false\n\n/** What a message would move out of the wallet, per tonapi's `risk`. */\nexport interface TonRisk {\n /** Nanotons leaving the wallet (value + fees the emulator attributes). */\n ton: bigint\n jettons: Array<{ address: string; walletAddress: string; amount: bigint; symbol?: string; decimals?: number }>\n /** Send mode 128: the whole remaining balance goes with the message. */\n transferAllRemainingBalance: boolean\n}\n\n/**\n * Which service produced a simulation; `estimate-only` means fees were estimated without emulation.\n */\nexport type TonSimulationSource = 'tonapi' | 'toncenter-v3' | 'estimate-only'\n\n/**\n * Outcome of a simulation: the fees and, when emulated, whether the wallet transaction and its\n * actions succeeded.\n */\nexport type TonSimulation =\n | { ok: true; fees: TonFees; emulated: boolean; source: TonSimulationSource; exitCode?: number; actionSuccess?: boolean; risk?: TonRisk; warnings: string[] }\n | { ok: false; fees?: TonFees; emulated: true; source: Exclude<TonSimulationSource, 'estimate-only'>; reason: string; exitCode?: number; aborted?: boolean; risk?: TonRisk; warnings: string[] }\n\n/** Outcome of a sent wallet transaction, found by the body hash `sendTransaction` returned. */\nexport interface TonReceipt {\n /** The body hash that was returned by sendTransaction. */\n hash: string\n /** 1 when the wallet transaction completed without abort, 0 otherwise. */\n status: 0 | 1\n /** Logical time of the account transaction. */\n blockNumber: bigint\n /** Account transaction hash (base64). */\n transactionHash: string\n /** Fees of the account transaction, in nanotons. */\n totalFees: bigint\n /** The raw @ton/core Transaction. */\n raw: unknown\n}\n\n/** CAIP-2 ids of TON mainnet and testnet. */\nexport const CAIP2: Record<'mainnet' | 'testnet', string> = { mainnet: 'ton:-239', testnet: 'ton:-3' }\n","import { SignerError } from '@anywalletkit/core'\n\n/**\n * Refused before signing: the message would almost certainly misbehave or\n * strand funds (zero value, wrong network flag, exotic workchain, a\n * `valid_until` further away than the wallet contract tolerates…).\n */\nexport class UnsafeTransactionError extends SignerError {\n readonly code: string\n constructor(code: string, message: string) {\n super(message)\n this.name = 'UnsafeTransactionError'\n this.code = code\n }\n}\n\n/** Emulation of the external message failed (non-zero compute exit, aborted, action phase failed); nothing was signed or sent. */\nexport class SimulationError extends Error {\n readonly exitCode: number | undefined\n readonly aborted: boolean\n constructor(reason: string, details: { exitCode?: number; aborted?: boolean } = {}) {\n super(`Transaction simulation failed: ${reason}`)\n this.name = 'SimulationError'\n this.exitCode = details.exitCode\n this.aborted = details.aborted ?? false\n }\n}\n","/**\n * toncenter v2 JSON-RPC client — the handful of calls a wallet needs, with\n * failover across endpoints, timeouts, api keys and response-shape checks.\n * No axios, no dataloader, no caches: one `fetch` per call.\n */\nimport { NetworkError } from '@anywalletkit/core'\nimport { Buffer } from 'buffer'\nimport { Address, Cell, TupleReader, loadTransaction, type StateInit, type Transaction, type TupleItem } from '@ton/core'\nimport type { TonConfig, TonEndpoint, TonFees, TonProvider, TonRpc } from './types.js'\n\nconst DEFAULT_TIMEOUT_MS = 15_000\n\nconst isRpc = (p: TonProvider): p is TonRpc => typeof (p as TonRpc).call === 'function'\n\n/** JSON-RPC over one toncenter v2 endpoint. */\nexport function tonCenterEndpoint(endpoint: TonEndpoint, opts: { fetch?: typeof fetch; timeoutMs?: number } = {}): TonRpc {\n const url = endpoint.url\n const doFetch = opts.fetch ?? globalThis.fetch\n if (typeof doFetch !== 'function') throw new NetworkError('No fetch available; pass config.fetch', { provider: url })\n const timeoutMs = opts.timeoutMs ?? DEFAULT_TIMEOUT_MS\n return {\n async call<T>(method: string, params: Record<string, unknown>): Promise<T> {\n let res: Response\n try {\n res = await doFetch(url, {\n method: 'POST',\n headers: {\n 'content-type': 'application/json',\n accept: 'application/json',\n ...(endpoint.secretKey ? { 'X-API-Key': endpoint.secretKey } : {}),\n },\n body: JSON.stringify({ id: '1', jsonrpc: '2.0', method, params }),\n signal: AbortSignal.timeout(timeoutMs),\n })\n } catch (e) {\n throw new NetworkError(`${method}: ${e instanceof Error ? e.message : String(e)}`, { provider: url, cause: e })\n }\n let json: { ok?: boolean; result?: T; error?: unknown; code?: unknown }\n try { json = (await res.json()) as typeof json } catch (e) {\n throw new NetworkError(`${method}: HTTP ${res.status}, non-JSON body`, { provider: url, cause: e })\n }\n if (!res.ok || json.ok !== true) {\n const detail = typeof json.error === 'string' ? json.error : JSON.stringify(json.error ?? json)\n throw new NetworkError(`${method}: ${detail} (HTTP ${res.status})`, { provider: url })\n }\n return json.result as T\n },\n }\n}\n\n/** One RPC, or a failover RPC walking the configured list (`retries` extra rounds after the first full pass). */\nexport function createTonRpc(config: TonConfig): TonRpc | undefined {\n const target = config.tonClient ?? config.provider\n if (target === undefined) return undefined\n const list = (Array.isArray(target) ? target : [target]).map((p) =>\n isRpc(p) ? p : tonCenterEndpoint(p, { ...(config.fetch ? { fetch: config.fetch } : {}), ...(config.timeoutMs !== undefined ? { timeoutMs: config.timeoutMs } : {}) }),\n )\n if (list.length === 0) throw new Error(\"The 'tonClient' option cannot be set to an empty list.\")\n if (list.length === 1) return list[0]!\n const attempts = list.length + (config.retries ?? 3)\n return {\n async call<T>(method: string, params: Record<string, unknown>): Promise<T> {\n let lastError: unknown\n for (let i = 0; i < attempts; i++) {\n try { return await list[i % list.length]!.call<T>(method, params) } catch (e) { lastError = e }\n }\n throw new NetworkError(`All TON endpoints failed for ${method}`, { cause: lastError })\n },\n }\n}\n\n// ── Stack (de)serialization, toncenter v2 wire format ───────────────────────\n\nfunction serializeStackItem(item: TupleItem): [string, unknown] {\n switch (item.type) {\n case 'int': return ['num', item.value.toString()]\n case 'cell': return ['tvm.Cell', item.cell.toBoc().toString('base64')]\n case 'slice': return ['tvm.Slice', item.cell.toBoc().toString('base64')]\n case 'builder': return ['tvm.Builder', item.cell.toBoc().toString('base64')]\n default: throw new Error(`Unsupported stack item type: ${item.type}`)\n }\n}\n\nconst hexBigInt = (s: string): bigint => (s.startsWith('-') ? -BigInt(s.slice(1)) : BigInt(s))\nconst cellFromBase64 = (b64: string): Cell => Cell.fromBoc(Buffer.from(b64, 'base64'))[0]!\n\nfunction parseStackEntry(x: unknown): TupleItem {\n const o = x as Record<string, unknown>\n switch (o['@type']) {\n case 'tvm.list':\n case 'tvm.tuple': return { type: 'tuple', items: (o.elements as unknown[]).map(parseStackEntry) }\n case 'tvm.cell': return { type: 'cell', cell: cellFromBase64(o.bytes as string) }\n case 'tvm.stackEntryCell': return parseStackEntry(o.cell)\n case 'tvm.stackEntryTuple': return parseStackEntry(o.tuple)\n case 'tvm.stackEntryNumber': return parseStackEntry(o.number)\n case 'tvm.numberDecimal': return { type: 'int', value: BigInt(o.number as string) }\n default: throw new NetworkError(`Malformed stack entry: ${JSON.stringify(x)}`)\n }\n}\n\nfunction parseStackItem(s: unknown): TupleItem {\n if (!Array.isArray(s) || s.length < 2) throw new NetworkError(`Malformed stack item: ${JSON.stringify(s)}`)\n const [kind, value] = s as [string, unknown]\n switch (kind) {\n case 'num': return { type: 'int', value: hexBigInt(value as string) }\n case 'null': return { type: 'null' }\n case 'cell': return { type: 'cell', cell: cellFromBase64((value as { bytes: string }).bytes) }\n case 'slice': return { type: 'slice', cell: cellFromBase64((value as { bytes: string }).bytes) }\n case 'builder': return { type: 'builder', cell: cellFromBase64((value as { bytes: string }).bytes) }\n case 'tuple':\n case 'list': return { type: 'tuple', items: ((value as { elements: unknown[] }).elements ?? []).map(parseStackEntry) }\n default: throw new NetworkError(`Malformed stack item kind: ${kind}`)\n }\n}\n\n// ── Typed API ───────────────────────────────────────────────────────────────\n\n/** State of a TON account on chain. */\nexport type TonAccountStatus = 'active' | 'uninitialized' | 'frozen' | 'nonexist'\n\n/** Balance, status, code and data of an account. */\nexport interface TonAccountState {\n balance: bigint\n state: TonAccountStatus\n code: Cell | null\n data: Cell | null\n lastTransaction: { lt: string; hash: string } | null\n}\n\n/** Result of a contract get-method call. */\nexport interface GetMethodResult { exitCode: number; gasUsed: number; stack: TupleReader }\n\nconst need = <T>(cond: unknown, what: string, value: T): T => {\n if (!cond) throw new NetworkError(`Malformed toncenter response: ${what}`)\n return value\n}\n\n/** The toncenter calls a wallet uses, with parsed results. */\nexport class TonCenter {\n constructor(readonly rpc: TonRpc) {}\n\n /** Balance, status, code and data of an account. */\n async getAddressInformation(address: Address): Promise<TonAccountState> {\n const r = await this.rpc.call<Record<string, unknown>>('getAddressInformation', { address: address.toString() })\n need(r && typeof r === 'object' && typeof r.balance === 'string', 'getAddressInformation', r)\n const state = r.state as string\n const last = r.last_transaction_id as { lt?: string; hash?: string } | undefined\n return {\n balance: BigInt(r.balance as string),\n state: (['active', 'uninitialized', 'frozen', 'nonexist'] as const).includes(state as TonAccountStatus) ? (state as TonAccountStatus) : 'nonexist',\n code: typeof r.code === 'string' && r.code !== '' ? cellFromBase64(r.code) : null,\n data: typeof r.data === 'string' && r.data !== '' ? cellFromBase64(r.data) : null,\n lastTransaction: last && last.lt && last.lt !== '0' ? { lt: last.lt, hash: last.hash ?? '' } : null,\n }\n }\n\n /** Call a contract get-method; the result carries the exit code. */\n async runGetMethod(address: Address, method: string, stack: TupleItem[] = []): Promise<GetMethodResult> {\n const r = await this.rpc.call<Record<string, unknown>>('runGetMethod', {\n address: address.toString(), method, stack: stack.map(serializeStackItem),\n })\n need(r && typeof r === 'object' && typeof r.exit_code === 'number' && Array.isArray(r.stack), 'runGetMethod', r)\n return { exitCode: r.exit_code as number, gasUsed: Number(r.gas_used ?? 0), stack: new TupleReader((r.stack as unknown[]).map(parseStackItem)) }\n }\n\n /** Like runGetMethod but throws on a non-zero exit code. */\n async runGetMethodOk(address: Address, method: string, stack: TupleItem[] = []): Promise<GetMethodResult> {\n const r = await this.runGetMethod(address, method, stack)\n if (r.exitCode !== 0) throw new NetworkError(`Get method ${method} failed with exit_code: ${r.exitCode}`)\n return r\n }\n\n /** Broadcast a signed external message. */\n async sendBoc(message: Cell): Promise<void> {\n await this.rpc.call('sendBoc', { boc: message.toBoc().toString('base64') })\n }\n\n /** Broadcast and return the external-message hash (base64) toncenter reports. */\n async sendBocReturnHash(message: Cell): Promise<string> {\n const r = await this.rpc.call<{ hash?: string }>('sendBocReturnHash', { boc: message.toBoc().toString('base64') })\n return need(r && typeof r.hash === 'string', 'sendBocReturnHash', r.hash as string)\n }\n\n async getTransactions(address: Address, opts: { limit: number; lt?: string; hash?: string; archival?: boolean }): Promise<Transaction[]> {\n const params: Record<string, unknown> = { address: address.toString(), limit: opts.limit }\n if (opts.lt) params.lt = opts.lt\n if (opts.hash) params.hash = Buffer.from(opts.hash, 'base64').toString('hex')\n if (opts.archival) params.archival = true\n const r = await this.rpc.call<unknown>('getTransactions', params)\n need(Array.isArray(r), 'getTransactions', r)\n return (r as Array<{ data?: string }>).map((t) => {\n need(typeof t.data === 'string', 'getTransactions[].data', t)\n return loadTransaction(cellFromBase64(t.data as string).beginParse())\n })\n }\n\n async estimateFee(address: Address, args: { body: Cell; init?: StateInit; ignoreSignature?: boolean }): Promise<TonFees> {\n const r = await this.rpc.call<{ source_fees?: Record<string, unknown> }>('estimateFee', {\n address: address.toString(),\n body: args.body.toBoc().toString('base64'),\n init_code: args.init ? args.init.code!.toBoc().toString('base64') : '',\n init_data: args.init ? args.init.data!.toBoc().toString('base64') : '',\n ignore_chksig: args.ignoreSignature ?? true,\n })\n const f = r?.source_fees\n need(f && ['in_fwd_fee', 'storage_fee', 'gas_fee', 'fwd_fee'].every((k) => typeof f[k] === 'number' || typeof f[k] === 'string'), 'estimateFee', r)\n const fees = {\n inFwdFee: BigInt(f!.in_fwd_fee as number), storageFee: BigInt(f!.storage_fee as number),\n gasFee: BigInt(f!.gas_fee as number), fwdFee: BigInt(f!.fwd_fee as number),\n }\n return { ...fees, total: fees.inFwdFee + fees.storageFee + fees.gasFee + fees.fwdFee }\n }\n}\n\n// ── Emulation (toncenter v3 emulateTrace) ───────────────────────────────────\n\n/**\n * Whether an emulated wallet transaction succeeded: compute exit code, abort flag, action phase.\n */\nexport interface EmulationVerdict {\n ok: boolean\n exitCode?: number\n aborted?: boolean\n actionSuccess?: boolean\n reason?: string\n}\n\n/**\n * Reduce an `emulateTrace` response to a verdict for the ROOT transaction (the\n * wallet's own): compute-phase exit code, aborted flag, action-phase success.\n * Tolerant of the field spellings the v3 API has used (`description.compute_ph`\n * / `compute`, `action.success`); anything unrecognisable is a NetworkError, not\n * a silent pass.\n */\nexport function parseEmulation(json: unknown): EmulationVerdict {\n const j = json as Record<string, unknown> | null\n if (!j || typeof j !== 'object') throw new NetworkError('Malformed emulation response')\n if (typeof j.error === 'string') return { ok: false, reason: j.error }\n const txs = j.transactions as Record<string, Record<string, unknown>> | Array<Record<string, unknown>> | undefined\n const rootHash = (j.trace as { tx_hash?: string } | undefined)?.tx_hash\n let tx: Record<string, unknown> | undefined\n if (Array.isArray(txs)) tx = txs[0]\n else if (txs && typeof txs === 'object') tx = (rootHash && txs[rootHash]) || Object.values(txs)[0]\n if (!tx) {\n if (typeof j.exit_code === 'number') return verdict(j.exit_code, j.aborted === true, undefined)\n throw new NetworkError('Malformed emulation response: no transactions')\n }\n const d = (tx.description as Record<string, unknown> | undefined) ?? tx\n const compute = (d.compute_ph ?? d.compute) as Record<string, unknown> | undefined\n const action = d.action as Record<string, unknown> | undefined\n const exitCode = typeof compute?.exit_code === 'number' ? compute.exit_code : compute?.success === true ? 0 : undefined\n const actionSuccess = typeof action?.success === 'boolean' ? action.success : undefined\n if (exitCode === undefined && d.aborted === undefined && actionSuccess === undefined) throw new NetworkError('Malformed emulation response: no phases')\n return verdict(exitCode, d.aborted === true, actionSuccess)\n}\n\nfunction verdict(exitCode: number | undefined, aborted: boolean, actionSuccess: boolean | undefined): EmulationVerdict {\n const ok = !aborted && (exitCode === undefined || exitCode === 0) && actionSuccess !== false\n const reason = aborted ? 'transaction aborted' : exitCode !== undefined && exitCode !== 0 ? `compute phase exit_code ${exitCode}` : actionSuccess === false ? 'action phase failed' : undefined\n return { ok, ...(exitCode !== undefined ? { exitCode } : {}), aborted, ...(actionSuccess !== undefined ? { actionSuccess } : {}), ...(reason ? { reason } : {}) }\n}\n\n/** POST the external message to a toncenter v3 emulation endpoint and reduce the trace. */\nexport async function emulateExternal(url: string, message: Cell, opts: { fetch?: typeof fetch; timeoutMs?: number; apiKey?: string } = {}): Promise<EmulationVerdict> {\n const doFetch = opts.fetch ?? globalThis.fetch\n let res: Response\n try {\n res = await doFetch(url, {\n method: 'POST',\n headers: { 'content-type': 'application/json', accept: 'application/json', ...(opts.apiKey ? { 'X-API-Key': opts.apiKey } : {}) },\n body: JSON.stringify({ boc: message.toBoc().toString('base64'), ignore_chksig: true, include_code_data: false, with_actions: false }),\n signal: AbortSignal.timeout(opts.timeoutMs ?? DEFAULT_TIMEOUT_MS),\n })\n } catch (e) {\n throw new NetworkError(`emulate: ${e instanceof Error ? e.message : String(e)}`, { provider: url, cause: e })\n }\n let json: unknown\n try { json = await res.json() } catch (e) { throw new NetworkError(`emulate: HTTP ${res.status}, non-JSON body`, { provider: url, cause: e }) }\n if (!res.ok) {\n const err = (json as { error?: unknown; detail?: unknown })\n return { ok: false, reason: `HTTP ${res.status}: ${typeof err.error === 'string' ? err.error : JSON.stringify(err.detail ?? err.error ?? json)}` }\n }\n return parseEmulation(json)\n}\n","/**\n * Preflight emulation of a zero-signed external through tonapi\n * (`POST /v2/wallet/emulate`, fallback `POST /v2/traces/emulate`) or a\n * toncenter v3 `emulateTrace` endpoint. The verdict decides whether the\n * account signs at all; `risk` (tonapi only) summarises what would leave the\n * wallet so a foreign body cannot quietly drain it.\n *\n * tonapi shapes used (OpenAPI v2):\n * MessageConsequences = { trace: Trace, event: AccountEvent, risk: Risk }\n * Trace = { transaction: Transaction, interfaces: string[], children?: Trace[], emulated?: boolean }\n * Transaction.compute_phase = { skipped, skip_reason?, success?, exit_code?, exit_code_description? }\n * Transaction.action_phase = { success, result_code, … }\n * Transaction.{ success, aborted, bounce_phase? }\n * Risk = { transfer_all_remaining_balance, ton, jettons: [{ quantity, wallet_address: { address }, jetton: { address, symbol, decimals } }], nfts }\n */\nimport type { Cell } from '@ton/core'\nimport { NetworkError } from '@anywalletkit/core'\nimport { emulateExternal as emulateToncenter, type EmulationVerdict } from './toncenter.js'\nimport type { TonEmulateConfig, TonRisk } from './types.js'\n\nconst DEFAULT_TIMEOUT_MS = 15_000\n/** Default tonapi root used for emulation. */\nexport const DEFAULT_TONAPI = 'https://tonapi.io/v2'\n\n/** Service an emulation came from. */\nexport type EmulationSource = 'tonapi' | 'toncenter-v3'\n\n/** An emulation verdict with its source and any deeper failures. */\nexport interface EmulationOutcome extends EmulationVerdict {\n source: EmulationSource\n /** Failed/bounced transactions deeper than the first hop — informational. */\n warnings: string[]\n /** tonapi `risk`: what the message would move out of the wallet. */\n risk?: TonRisk\n}\n\ninterface TonapiTx {\n hash?: string\n account?: { address?: string } | string\n success?: boolean\n aborted?: boolean\n compute_phase?: { skipped?: boolean; skip_reason?: string; success?: boolean; exit_code?: number; exit_code_description?: string }\n action_phase?: { success?: boolean; result_code?: number; result_code_description?: string }\n bounce_phase?: string\n}\ninterface TonapiTrace { transaction?: TonapiTx; children?: TonapiTrace[] }\n\nfunction isObject(v: unknown): v is Record<string, unknown> {\n return !!v && typeof v === 'object' && !Array.isArray(v)\n}\n\n/**\n * A plain value transfer to an account that does not exist yet: the chain\n * credits the coins and leaves the account `uninit`; tonapi reports the hop as\n * `success: true, aborted: true, compute skipped (cskip_no_state)` with no\n * bounce phase. That is the normal shape of funding a fresh deposit address\n * (NEAR Intents TON deposits, 2026-10-09) — not a failure. A BOUNCEABLE\n * message to the same account bounces instead (`bounce_phase` set) and stays\n * fatal, since the value comes back minus fees.\n */\nfunction creditedUninit(tx: TonapiTx): boolean {\n const c = tx.compute_phase\n return tx.success === true && c?.skipped === true && c.skip_reason === 'cskip_no_state' && tx.bounce_phase === undefined && (tx.action_phase === undefined || tx.action_phase.success !== false)\n}\n\nfunction txFailure(tx: TonapiTx): string | undefined {\n const c = tx.compute_phase\n if (creditedUninit(tx)) return undefined\n if (tx.aborted === true) return 'aborted'\n if (c && c.skipped !== true && typeof c.exit_code === 'number' && c.exit_code !== 0) return `compute exit_code ${c.exit_code}${c.exit_code_description ? ` (${c.exit_code_description})` : ''}`\n if (c && c.skipped === true && tx.success === false) return `compute skipped${c.skip_reason ? ` (${c.skip_reason})` : ''}`\n if (tx.action_phase && tx.action_phase.success === false) return `action phase failed${typeof tx.action_phase.result_code === 'number' ? ` (code ${tx.action_phase.result_code})` : ''}`\n if (typeof tx.bounce_phase === 'string' && tx.bounce_phase !== 'TrPhaseBounceOk' && tx.success === false) return `bounced (${tx.bounce_phase})`\n if (tx.success === false) return 'failed'\n return undefined\n}\n\nfunction accountOf(tx: TonapiTx): string {\n return typeof tx.account === 'string' ? tx.account : tx.account?.address ?? '?'\n}\n\n/**\n * Reduce a tonapi `Trace` to a verdict. The root (the wallet's own transaction)\n * decides: compute exit ≠ 0, aborted or a failed action phase → not ok. A\n * failing FIRST-HOP child is also fatal: for every message this wallet builds\n * (TON to a contract, jetton transfer to its own jetton wallet) a bounced\n * first hop means the operation did not happen and the value comes back minus\n * fees. Deeper failures (e.g. a jetton notify the recipient's wallet rejects)\n * become warnings — the transfer itself already settled.\n */\nexport function parseTonapiTrace(trace: unknown): Omit<EmulationOutcome, 'source' | 'risk'> {\n if (!isObject(trace) || !isObject(trace.transaction)) throw new NetworkError('Malformed tonapi emulation: no root transaction')\n const root = trace.transaction as TonapiTx\n const compute = root.compute_phase\n const exitCode = compute && compute.skipped !== true && typeof compute.exit_code === 'number' ? compute.exit_code : compute?.success === true ? 0 : undefined\n const actionSuccess = typeof root.action_phase?.success === 'boolean' ? root.action_phase.success : undefined\n if (exitCode === undefined && actionSuccess === undefined && typeof root.success !== 'boolean' && typeof root.aborted !== 'boolean') {\n throw new NetworkError('Malformed tonapi emulation: root transaction has no phases')\n }\n const aborted = root.aborted === true\n const rootFailure = txFailure(root)\n const warnings: string[] = []\n let firstHopFailure: string | undefined\n const walk = (t: TonapiTrace, depth: number) => {\n for (const child of t.children ?? []) {\n const tx = child.transaction\n if (tx) {\n const f = txFailure(tx)\n if (f) {\n const line = `${accountOf(tx)}: ${f}`\n if (depth === 1) firstHopFailure ??= line\n else warnings.push(line)\n }\n }\n walk(child, depth + 1)\n }\n }\n walk(trace as TonapiTrace, 1)\n const reason = rootFailure ? (aborted ? 'transaction aborted' : rootFailure) : firstHopFailure ? `internal message failed — ${firstHopFailure}` : undefined\n return {\n ok: reason === undefined,\n ...(exitCode !== undefined ? { exitCode } : {}),\n aborted,\n ...(actionSuccess !== undefined ? { actionSuccess } : {}),\n ...(reason ? { reason } : {}),\n warnings,\n }\n}\n\n/** tonapi `Risk` → nanotons / jetton base units as bigints. Malformed → NetworkError. */\nexport function parseTonapiRisk(risk: unknown): TonRisk {\n if (!isObject(risk)) throw new NetworkError('Malformed tonapi emulation: no risk')\n const big = (v: unknown): bigint => {\n if (typeof v === 'bigint') return v\n if (typeof v === 'number' && Number.isFinite(v)) return BigInt(Math.trunc(v))\n if (typeof v === 'string' && /^-?\\d+$/.test(v)) return BigInt(v)\n throw new NetworkError('Malformed tonapi emulation: risk amount')\n }\n const jettons = Array.isArray(risk.jettons) ? risk.jettons : []\n return {\n ton: big(risk.ton ?? 0),\n transferAllRemainingBalance: risk.transfer_all_remaining_balance === true,\n jettons: jettons.map((j) => {\n if (!isObject(j)) throw new NetworkError('Malformed tonapi emulation: risk jetton')\n const jetton = isObject(j.jetton) ? j.jetton : {}\n const wallet = isObject(j.wallet_address) ? j.wallet_address : {}\n return {\n amount: big(j.quantity ?? 0),\n address: typeof jetton.address === 'string' ? jetton.address : '',\n walletAddress: typeof wallet.address === 'string' ? wallet.address : '',\n ...(typeof jetton.symbol === 'string' ? { symbol: jetton.symbol } : {}),\n ...(typeof jetton.decimals === 'number' ? { decimals: jetton.decimals } : {}),\n }\n }),\n }\n}\n\n/** tonapi `MessageConsequences` (wallet/emulate) → outcome with risk. */\nexport function parseTonapiConsequences(json: unknown): EmulationOutcome {\n if (!isObject(json)) throw new NetworkError('Malformed tonapi emulation response')\n if (typeof json.error === 'string') return { ok: false, reason: json.error, aborted: false, warnings: [], source: 'tonapi' }\n const verdict = parseTonapiTrace(json.trace)\n return { ...verdict, source: 'tonapi', risk: parseTonapiRisk(json.risk) }\n}\n\n/** Options for emulating a message through tonapi or toncenter v3. */\nexport interface EmulateOptions {\n fetch?: typeof fetch\n timeoutMs?: number\n /** tonapi bearer key / toncenter X-API-Key. */\n apiKey?: string\n}\n\nasync function post(doFetch: typeof fetch, url: string, body: unknown, opts: EmulateOptions): Promise<{ status: number; ok: boolean; json: unknown }> {\n let res: Response\n try {\n res = await doFetch(url, {\n method: 'POST',\n headers: { 'content-type': 'application/json', accept: 'application/json', ...(opts.apiKey ? { authorization: `Bearer ${opts.apiKey}` } : {}) },\n body: JSON.stringify(body),\n signal: AbortSignal.timeout(opts.timeoutMs ?? DEFAULT_TIMEOUT_MS),\n })\n } catch (e) {\n throw new NetworkError(`emulate: ${e instanceof Error ? e.message : String(e)}`, { provider: url, cause: e })\n }\n if (res.status === 404) return { status: 404, ok: false, json: undefined }\n let json: unknown\n try { json = await res.json() } catch (e) { throw new NetworkError(`emulate: HTTP ${res.status}, non-JSON body`, { provider: url, cause: e }) }\n return { status: res.status, ok: res.ok, json }\n}\n\nfunction httpFailure(status: number, json: unknown): EmulationOutcome {\n const err = isObject(json) ? json : {}\n const text = typeof err.error === 'string' ? err.error : JSON.stringify(err.detail ?? err.error ?? json)\n return { ok: false, reason: `HTTP ${status}: ${text}`, aborted: false, warnings: [], source: 'tonapi' }\n}\n\n/**\n * Emulate through tonapi: `/wallet/emulate` first (verdict + risk), then\n * `/traces/emulate` when the first is not served (404). The external carries a\n * zero signature; `ignore_signature_check=true` is sent on both calls.\n */\nexport async function emulateViaTonapi(baseUrl: string, message: Cell, opts: EmulateOptions = {}): Promise<EmulationOutcome> {\n const doFetch = opts.fetch ?? globalThis.fetch\n const base = baseUrl.replace(/\\/+$/, '')\n const boc = message.toBoc().toString('base64')\n const first = await post(doFetch, `${base}/wallet/emulate?ignore_signature_check=true`, { boc }, opts)\n if (first.status !== 404) {\n if (!first.ok) return httpFailure(first.status, first.json)\n return parseTonapiConsequences(first.json)\n }\n const second = await post(doFetch, `${base}/traces/emulate?ignore_signature_check=true`, { boc }, opts)\n if (second.status === 404) throw new NetworkError('emulate: tonapi serves neither /wallet/emulate nor /traces/emulate', { provider: base })\n if (!second.ok) return httpFailure(second.status, second.json)\n if (isObject(second.json) && typeof second.json.error === 'string') return { ok: false, reason: second.json.error, aborted: false, warnings: [], source: 'tonapi' }\n return { ...parseTonapiTrace(second.json), source: 'tonapi' }\n}\n\n/** Resolve the effective emulation config: explicit `emulate`, legacy `emulateUrl`, else tonapi by default. */\nexport function resolveEmulate(config: { emulate?: TonEmulateConfig; emulateUrl?: string; tonApiUrl?: string }): Exclude<TonEmulateConfig, false> | false {\n if (config.emulate === false) return false\n if (config.emulate) return config.emulate\n if (config.emulateUrl) return { kind: 'toncenter-v3', url: config.emulateUrl }\n return { kind: 'tonapi' }\n}\n\n/** Run the configured emulation for an external message. */\nexport async function runEmulation(config: { emulate?: TonEmulateConfig; emulateUrl?: string; tonApiUrl?: string; tonApiKey?: string; fetch?: typeof fetch; timeoutMs?: number }, message: Cell): Promise<EmulationOutcome | undefined> {\n const target = resolveEmulate(config)\n if (!target) return undefined\n const opts: EmulateOptions = {\n ...(config.fetch ? { fetch: config.fetch } : {}),\n ...(config.timeoutMs !== undefined ? { timeoutMs: config.timeoutMs } : {}),\n ...(config.tonApiKey ? { apiKey: config.tonApiKey } : {}),\n }\n if (target.kind === 'tonapi') return emulateViaTonapi(target.url ?? config.tonApiUrl ?? DEFAULT_TONAPI, message, opts)\n const v = await emulateToncenter(target.url, message, opts)\n return { ...v, aborted: v.aborted ?? false, source: 'toncenter-v3', warnings: [] }\n}\n","/**\n * Wallet V5R1 (the contract Tonkeeper \"W5\" and Tonhub deploy) without\n * @ton/ton: state init, address, the signed-external body and its parser.\n *\n * Contract code and wire layout follow @ton/ton's WalletContractV5R1\n * (Copyright (c) Whales Corp., MIT) and the reference contract\n * https://github.com/ton-blockchain/wallet-contract-v5 (commit 4fab977,\n * build/wallet_v5.compiled.json). Only the parts a sending wallet needs are\n * here: extensions and the internal/extension auth paths are not implemented.\n */\nimport { Buffer } from 'buffer'\nimport {\n Address, Cell, SendMode, beginCell, contractAddress, external, loadOutList, storeMessage, storeOutList,\n type MessageRelaxed, type OutActionSendMsg, type StateInit,\n} from '@ton/core'\n\n// https://github.com/ton-blockchain/wallet-contract-v5/blob/4fab977f4fae3a37c1aac216ed2b7e611a9bc2af/build/wallet_v5.compiled.json\n/** Code of the Wallet V5R1 contract (BoC hex). */\nexport const V5R1_CODE_HEX =\n 'b5ee9c7241021401000281000114ff00f4a413f4bcf2c80b01020120020d020148030402dcd020d749c120915b8f6320d70b1f2082106578746ebd21821073696e74bdb0925f03e082106578746eba8eb48020d72101d074d721fa4030fa44f828fa443058bd915be0ed44d0810141d721f4058307f40e6fa1319130e18040d721707fdb3ce03120d749810280b99130e070e2100f020120050c020120060902016e07080019adce76a2684020eb90eb85ffc00019af1df6a2684010eb90eb858fc00201480a0b0017b325fb51341c75c875c2c7e00011b262fb513435c280200019be5f0f6a2684080a0eb90fa02c0102f20e011e20d70b1f82107369676ebaf2e08a7f0f01e68ef0eda2edfb218308d722028308d723208020d721d31fd31fd31fed44d0d200d31f20d31fd3ffd70a000af90140ccf9109a28945f0adb31e1f2c087df02b35007b0f2d0845125baf2e0855036baf2e086f823bbf2d0882292f800de01a47fc8ca00cb1f01cf16c9ed542092f80fde70db3cd81003f6eda2edfb02f404216e926c218e4c0221d73930709421c700b38e2d01d72820761e436c20d749c008f2e09320d74ac002f2e09320d71d06c712c2005230b0f2d089d74cd7393001a4e86c128407bbf2e093d74ac000f2e093ed55e2d20001c000915be0ebd72c08142091709601d72c081c12e25210b1e30f20d74a111213009601fa4001fa44f828fa443058baf2e091ed44d0810141d718f405049d7fc8ca0040048307f453f2e08b8e14038307f45bf2e08c22d70a00216e01b3b0f2d090e2c85003cf1612f400c9ed54007230d72c08248e2d21f2e092d200ed44d0d2005113baf2d08f54503091319c01810140d721d70a00f2e08ee2c8ca0058cf16c9ed5493f2c08de20010935bdb31e1d74cd0b4d6c35e'\n\nlet codeCell: Cell | undefined\n/** The V5R1 contract code cell (parsed once). */\nexport function v5r1Code(): Cell {\n codeCell ??= Cell.fromBoc(Buffer.from(V5R1_CODE_HEX, 'hex'))[0]!\n return codeCell\n}\n\n/** Op codes of Wallet V5R1 messages. */\nexport const V5R1_OP = {\n signedExternal: 0x7369676e,\n signedInternal: 0x73696e74,\n extension: 0x6578746e,\n} as const\n\n/** Global id of TON mainnet, part of the V5R1 wallet id. */\nexport const MAINNET_GLOBAL_ID = -239\n/** Global id of TON testnet. */\nexport const TESTNET_GLOBAL_ID = -3\n/** PAY_GAS_SEPARATELY | IGNORE_ERRORS — the mode every external-message action carries. */\nexport const DEFAULT_SEND_MODE = SendMode.PAY_GAS_SEPARATELY | SendMode.IGNORE_ERRORS\n/** Most outgoing messages one V5R1 transaction can carry. */\nexport const MAX_ACTIONS = 255\n\nexport interface V5R1WalletIdParts { networkGlobalId?: number; workchain?: number; subwalletNumber?: number }\n\n/**\n * Serialized wallet_id (int32): `networkGlobalId XOR context`, where the client\n * context is {1 bit \"client\", int8 workchain, uint8 version (0 = v5r1), uint15 subwallet}.\n */\nexport function v5r1WalletId(parts: V5R1WalletIdParts = {}): bigint {\n const context = beginCell()\n .storeUint(1, 1)\n .storeInt(parts.workchain ?? 0, 8)\n .storeUint(0, 8)\n .storeUint(parts.subwalletNumber ?? 0, 15)\n .endCell().beginParse().loadInt(32)\n return BigInt(parts.networkGlobalId ?? MAINNET_GLOBAL_ID) ^ BigInt(context)\n}\n\n/** State init (code and data) of a V5R1 wallet for a public key. */\nexport function v5r1StateInit(publicKey: Uint8Array, walletId: bigint = v5r1WalletId()): StateInit {\n if (publicKey.length !== 32) throw new Error('V5R1: public key must be 32 bytes')\n const data = beginCell()\n .storeUint(1, 1) // signature auth allowed\n .storeUint(0, 32) // seqno\n .storeInt(walletId, 32)\n .storeBuffer(Buffer.from(publicKey), 32)\n .storeBit(0) // no extensions\n .endCell()\n return { code: v5r1Code(), data }\n}\n\n/** Address of the V5R1 wallet for a public key. */\nexport function v5r1Address(publicKey: Uint8Array, opts: { workchain?: number; walletId?: bigint } = {}): Address {\n return contractAddress(opts.workchain ?? 0, v5r1StateInit(publicKey, opts.walletId))\n}\n\nexport interface V5R1Message { message: MessageRelaxed; mode?: number }\n\nexport interface V5R1SigningParams {\n walletId: bigint\n /** Unix seconds. */\n validUntil: number\n seqno: number\n messages: V5R1Message[]\n}\n\n/** The cell that gets hashed and signed: op | wallet_id | valid_until | seqno | out-list ref | no extended actions. */\nexport function v5r1SigningMessage(p: V5R1SigningParams): Cell {\n if (p.messages.length > MAX_ACTIONS) throw new Error(`V5R1: at most ${MAX_ACTIONS} messages per external (got ${p.messages.length})`)\n const actions: OutActionSendMsg[] = p.messages.map((m) => ({\n type: 'sendMsg',\n // Externals must carry IGNORE_ERRORS or the wallet contract rejects them.\n mode: (m.mode ?? DEFAULT_SEND_MODE) | SendMode.IGNORE_ERRORS,\n outMsg: m.message,\n }))\n const outList = actions.length ? beginCell().store(storeOutList(actions)).endCell() : null\n return beginCell()\n .storeUint(V5R1_OP.signedExternal, 32)\n .storeInt(p.walletId, 32)\n .storeUint(p.validUntil, 32)\n .storeUint(p.seqno, 32)\n .storeMaybeRef(outList)\n .storeUint(0, 1)\n .endCell()\n}\n\n/** Signature goes at the tail (V5R1 layout). */\nexport function v5r1PackSigned(signing: Cell, signature: Uint8Array): Cell {\n if (signature.length !== 64) throw new Error('V5R1: signature must be 64 bytes')\n return beginCell().storeSlice(signing.beginParse()).storeBuffer(Buffer.from(signature), 64).endCell()\n}\n\n/** Same body with a zero signature — what `estimateFee(ignore_chksig)` and emulation take. */\nexport function v5r1PackUnsigned(signing: Cell): Cell {\n return v5r1PackSigned(signing, new Uint8Array(64))\n}\n\n/** The external-in message (as a cell, ready for sendBoc) carrying `body` to the wallet, with `init` when it is not deployed yet. */\nexport function v5r1ExternalMessage(to: Address, body: Cell, init?: StateInit): Cell {\n return beginCell().store(storeMessage(external({ to, body, ...(init ? { init } : {}) }))).endCell()\n}\n\nexport interface ParsedV5R1Body {\n op: number\n walletId: bigint\n validUntil: number\n seqno: number\n messages: Array<{ message: MessageRelaxed; mode: number }>\n /** True when the 64-byte tail signature is present (externals and internals carry one). */\n signed: boolean\n}\n\n/** Parse a signed (or zero-signed) V5R1 external body back into its messages. Returns null for anything else. */\nexport function parseV5R1Body(body: Cell): ParsedV5R1Body | null {\n try {\n const s = body.beginParse()\n const op = s.loadUint(32)\n if (op !== V5R1_OP.signedExternal && op !== V5R1_OP.signedInternal) return null\n const walletId = BigInt(s.loadInt(32))\n const validUntil = s.loadUint(32)\n const seqno = s.loadUint(32)\n const outList = s.loadMaybeRef()\n const hasExtended = s.loadBit()\n if (hasExtended) return null // extension management: not a plain send\n const messages: ParsedV5R1Body['messages'] = []\n if (outList) {\n for (const a of loadOutList(outList.beginParse())) {\n if (a.type !== 'sendMsg') return null\n messages.push({ message: a.outMsg, mode: a.mode })\n }\n }\n const signed = s.remainingBits >= 512\n return { op, walletId, validUntil, seqno, messages, signed }\n } catch {\n return null\n }\n}\n","/**\n * \"What am I signing\" for TON — offline. Decodes the messages of a\n * {@link TonSendable} (or a prebuilt V5R1 body) into human-checkable items and\n * flags the classic mistakes before any key is touched.\n */\nimport { Address, Cell, beginCell, type MessageRelaxed, type Slice } from '@ton/core'\nimport { parseV5R1Body } from './wallet-v5r1.js'\nimport type { TonSendable, TonTransaction } from './types.js'\n\n/** TEP-74 `transfer` op code of a jetton wallet. */\nexport const JETTON_TRANSFER_OP = 0x0f8a7ea5\nconst LARGE_FORWARD_NANOTON = 500_000_000n // 0.5 TON\n\n/** What one outgoing message does. */\nexport type TonDescribedKind = 'ton-transfer' | 'jetton-transfer' | 'contract-call'\n\n/** Fields of a TEP-74 jetton `transfer` body. */\nexport interface TonJettonDetails {\n queryId: bigint\n amount: bigint\n destination: string\n responseDestination: string | null\n forwardTonAmount: bigint\n forwardPayload: 'none' | 'comment' | 'cell'\n forwardComment?: string\n hasCustomPayload: boolean\n}\n\n/** One outgoing message of a wallet transaction, decoded. */\nexport interface TonDescribedMessage {\n kind: TonDescribedKind\n /** Destination as given (friendly) or raw `wc:hex`. */\n to: string\n value: bigint\n bounceable: boolean\n /** Test-only flag of a friendly address; undefined for raw addresses. */\n testOnly?: boolean\n /** Text comment (op 0). */\n comment?: string\n /** Body op code for contract calls (hex). */\n op?: string\n jetton?: TonJettonDetails\n hasStateInit: boolean\n bodyBits: number\n}\n\n/** Problems a TON description is flagged with. */\nexport type TonWarningCode =\n | 'zero-value'\n | 'non-bounceable-contract-call'\n | 'unknown-body'\n | 'large-forward-amount'\n | 'testnet-address'\n | 'mainnet-address'\n | 'exotic-workchain'\n | 'extended-actions'\n\n/** One flagged problem; `index` is the message it is about. */\nexport interface TonWarning { code: TonWarningCode; message: string; index?: number }\n\n/**\n * A TON wallet transaction decoded for a confirmation screen: each outgoing message and the\n * warnings.\n */\nexport interface TonDescription {\n kind: TonDescribedKind | 'mixed'\n items: TonDescribedMessage[]\n warnings: TonWarning[]\n /** Present when the input was a prebuilt V5R1 body. */\n external?: { seqno: number; validUntil: number; walletId: bigint; signed: boolean }\n}\n\n/** A message body decoded: empty, a text comment, a jetton transfer, or unknown. */\nexport type DecodedBody =\n | { type: 'empty' }\n | { type: 'comment'; text: string }\n | { type: 'jetton-transfer'; jetton: TonJettonDetails }\n | { type: 'op'; op: number }\n | { type: 'unknown' }\n\n/** Decode a message body cell. */\nexport function decodeBody(body: Cell): DecodedBody {\n const s = body.beginParse()\n if (s.remainingBits === 0 && s.remainingRefs === 0) return { type: 'empty' }\n if (s.remainingBits < 32) return { type: 'unknown' }\n const op = s.loadUint(32)\n try {\n if (op === 0) return { type: 'comment', text: s.loadStringTail() }\n if (op === JETTON_TRANSFER_OP) return { type: 'jetton-transfer', jetton: loadJettonTransfer(s) }\n } catch {\n return { type: 'unknown' }\n }\n return { type: 'op', op }\n}\n\nfunction loadJettonTransfer(s: Slice): TonJettonDetails {\n const queryId = s.loadUintBig(64)\n const amount = s.loadCoins()\n const destination = s.loadAddress()\n const responseDestination = s.loadMaybeAddress()\n const customPayload = s.loadMaybeRef()\n const forwardTonAmount = s.loadCoins()\n const inRef = s.loadBit()\n const payload: Slice = inRef ? s.loadRef().beginParse() : s\n let forwardPayload: TonJettonDetails['forwardPayload'] = 'none'\n let forwardComment: string | undefined\n if (payload.remainingBits > 0 || payload.remainingRefs > 0) {\n forwardPayload = 'cell'\n if (payload.remainingBits >= 32) {\n const p = payload.clone()\n if (p.loadUint(32) === 0) {\n try { forwardComment = p.loadStringTail(); forwardPayload = 'comment' } catch { /* not utf-8 */ }\n }\n }\n }\n return {\n queryId, amount, destination: destination.toString(), responseDestination: responseDestination ? responseDestination.toString() : null,\n forwardTonAmount, forwardPayload, ...(forwardComment !== undefined ? { forwardComment } : {}), hasCustomPayload: customPayload !== null,\n }\n}\n\nfunction parseTo(to: string): { to: string; bounceable: boolean; testOnly?: boolean; workchain: number } {\n if (Address.isFriendly(to)) {\n const f = Address.parseFriendly(to)\n return { to, bounceable: f.isBounceable, testOnly: f.isTestOnly, workchain: f.address.workChain }\n }\n const a = Address.parse(to)\n return { to: a.toRawString(), bounceable: true, workchain: a.workChain }\n}\n\nfunction bodyOf(tx: TonTransaction): Cell | undefined {\n if (tx.body instanceof Cell) return tx.body\n if (typeof tx.body === 'string') return tx.body === '' ? undefined : commentCell(tx.body)\n if (tx.bodyBoc) return Cell.fromBase64(tx.bodyBoc)\n return undefined\n}\n\n/** A text comment body (op 0 plus the text), as wallets show it. */\nexport function commentCell(text: string): Cell {\n return beginCell().storeUint(0, 32).storeStringTail(text).endCell()\n}\n\nfunction describeOne(\n i: number, to: ReturnType<typeof parseTo>, value: bigint, body: Cell | undefined, hasStateInit: boolean,\n bounceableOverride: boolean | undefined, warnings: TonWarning[], ctx: { network?: 'mainnet' | 'testnet' },\n): TonDescribedMessage {\n const bounceable = bounceableOverride ?? to.bounceable\n const decoded = body ? decodeBody(body) : ({ type: 'empty' } as DecodedBody)\n const base = { to: to.to, value, bounceable, ...(to.testOnly !== undefined ? { testOnly: to.testOnly } : {}), hasStateInit, bodyBits: body ? body.bits.length : 0 }\n if (value <= 0n) warnings.push({ code: 'zero-value', message: 'message carries no TON; it cannot pay for gas at the destination', index: i })\n if (to.workchain !== 0 && to.workchain !== -1) warnings.push({ code: 'exotic-workchain', message: `workchain ${to.workchain}`, index: i })\n if (ctx.network && to.testOnly !== undefined) {\n if (to.testOnly && ctx.network !== 'testnet') warnings.push({ code: 'testnet-address', message: 'test-only address on a mainnet wallet', index: i })\n if (!to.testOnly && ctx.network === 'testnet') warnings.push({ code: 'mainnet-address', message: 'mainnet address on a testnet wallet', index: i })\n }\n let item: TonDescribedMessage\n switch (decoded.type) {\n case 'empty': item = { kind: 'ton-transfer', ...base }; break\n case 'comment': item = { kind: 'ton-transfer', ...base, comment: decoded.text }; break\n case 'jetton-transfer':\n item = { kind: 'jetton-transfer', ...base, jetton: decoded.jetton, op: hex(JETTON_TRANSFER_OP) }\n if (decoded.jetton.forwardTonAmount > LARGE_FORWARD_NANOTON) warnings.push({ code: 'large-forward-amount', message: `forward_ton_amount ${decoded.jetton.forwardTonAmount} > 0.5 TON`, index: i })\n break\n case 'op': item = { kind: 'contract-call', ...base, op: hex(decoded.op) }; break\n default:\n item = { kind: 'contract-call', ...base }\n warnings.push({ code: 'unknown-body', message: 'message body could not be decoded', index: i })\n }\n if (item.kind !== 'ton-transfer' && !bounceable) {\n warnings.push({ code: 'non-bounceable-contract-call', message: 'contract call to a non-bounceable address: TON is lost if the call fails', index: i })\n }\n return item\n}\n\nconst hex = (n: number) => `0x${n.toString(16).padStart(8, '0')}`\n\n/** Describe one outgoing message and push its warnings into `warnings`. */\nexport function describeMessageRelaxed(i: number, m: MessageRelaxed, warnings: TonWarning[], ctx: { network?: 'mainnet' | 'testnet' } = {}): TonDescribedMessage {\n if (m.info.type !== 'internal') {\n warnings.push({ code: 'unknown-body', message: 'not an internal message', index: i })\n return { kind: 'contract-call', to: '', value: 0n, bounceable: false, hasStateInit: false, bodyBits: 0 }\n }\n const dest = m.info.dest\n const to = { to: dest.toString({ bounceable: m.info.bounce }), bounceable: m.info.bounce, workchain: dest.workChain }\n const body = m.body.bits.length === 0 && m.body.refs.length === 0 ? undefined : m.body\n return describeOne(i, to, m.info.value.coins, body, !!m.init, m.info.bounce, warnings, ctx)\n}\n\n/** Describe what a {@link TonSendable} will do. Offline; never throws on malformed bodies (they become warnings). */\nexport function describeTransaction(tx: TonSendable, ctx: { network?: 'mainnet' | 'testnet' } = {}): TonDescription {\n const warnings: TonWarning[] = []\n const items: TonDescribedMessage[] = []\n let external: TonDescription['external'] | undefined\n if (tx instanceof Cell) {\n const parsed = parseV5R1Body(tx)\n if (!parsed) {\n warnings.push({ code: 'unknown-body', message: 'not a V5R1 signed-external body' })\n return { kind: 'contract-call', items, warnings }\n }\n external = { seqno: parsed.seqno, validUntil: parsed.validUntil, walletId: parsed.walletId, signed: parsed.signed }\n parsed.messages.forEach((m, i) => items.push(describeMessageRelaxed(i, m.message, warnings, ctx)))\n } else {\n const list = Array.isArray(tx) ? tx : [tx]\n list.forEach((t, i) => {\n let to: ReturnType<typeof parseTo>\n try { to = parseTo(t.to) } catch {\n warnings.push({ code: 'unknown-body', message: `invalid address: ${t.to}`, index: i })\n items.push({ kind: 'contract-call', to: t.to, value: 0n, bounceable: false, hasStateInit: false, bodyBits: 0 })\n return\n }\n let body: Cell | undefined\n try { body = bodyOf(t) } catch { warnings.push({ code: 'unknown-body', message: 'bodyBoc is not a valid BoC', index: i }) }\n items.push(describeOne(i, to, BigInt(t.value), body, t.stateInit !== undefined, t.bounceable, warnings, ctx))\n })\n }\n const kinds = new Set(items.map((x) => x.kind))\n const kind: TonDescription['kind'] = kinds.size === 1 ? items[0]!.kind : kinds.size === 0 ? 'contract-call' : 'mixed'\n return { kind, items, warnings, ...(external ? { external } : {}) }\n}\n","import { NetworkError, type IWalletAccountReadOnly } from '@anywalletkit/core'\nimport { ed25519 } from '@noble/curves/ed25519.js'\nimport { Address, Cell, beginCell, internal, loadStateInit, type StateInit } from '@ton/core'\nimport { commentCell, describeTransaction, type TonDescription } from './describe.js'\nimport { UnsafeTransactionError } from './errors.js'\nimport { TonCenter, createTonRpc } from './toncenter.js'\nimport { runEmulation } from './emulation.js'\nimport {\n DEFAULT_SEND_MODE, MAINNET_GLOBAL_ID, TESTNET_GLOBAL_ID, v5r1Address, v5r1ExternalMessage, v5r1PackUnsigned, v5r1SigningMessage, v5r1StateInit, v5r1WalletId,\n type V5R1Message,\n} from './wallet-v5r1.js'\nimport { CAIP2, type TonConfig, type TonFees, type TonReceipt, type TonSendable, type TonSimulation, type TonTransaction, type TonTransferOptions } from './types.js'\n\nconst JETTON_TRANSFER_OP = 0x0f8a7ea5\nconst DEFAULT_JETTON_ATTACHED = 50_000_000n // 0.05 TON\nconst DEFAULT_INDEXER = 'https://toncenter.com/api/v3'\nconst DEFAULT_VALID_SECONDS = 60\nconst MAX_VALID_SECONDS = 600\n/** PAY_GAS_SEPARATELY | IGNORE_ERRORS, the mode every action in an external carries. */\nexport const SEND_MODE = DEFAULT_SEND_MODE\n\nconst utf8 = (s: string | Uint8Array) => (typeof s === 'string' ? new TextEncoder().encode(s) : s)\nconst hexToBytes = (h: string) => Uint8Array.from(h.match(/.{2}/g) ?? [], (b) => parseInt(b, 16))\nconst big = (v: bigint | number | string) => BigInt(v)\n\n/**\n * A TON V5R1 wallet without a key: balance, jetton balances, seqno, fee estimates, emulation,\n * receipts and signature checks.\n */\nexport class WalletAccountReadOnlyTon implements IWalletAccountReadOnly {\n readonly chain: string\n /** Ed25519 public key the wallet is derived from. */\n readonly publicKey: Uint8Array\n /** User-friendly address. */\n readonly address: string\n protected readonly _config: TonConfig\n protected readonly _walletId: bigint\n protected readonly _init: StateInit\n protected readonly _address: Address\n protected readonly _rpc: TonCenter | undefined\n\n constructor(publicKey: Uint8Array | string, config: TonConfig = {}) {\n this.publicKey = typeof publicKey === 'string' ? hexToBytes(publicKey) : publicKey\n this._config = config\n // The network_global_id inside wallet_id is the only thing that binds a signed external to one\n // network: a testnet wallet must carry -3, or every external it signs is also valid on mainnet\n // (same state init, address and wallet_id). It follows config.network; a contradicting override is refused.\n const networkGlobalId = config.network === 'testnet' ? TESTNET_GLOBAL_ID : MAINNET_GLOBAL_ID\n if (config.walletId?.networkGlobalId !== undefined && config.walletId.networkGlobalId !== networkGlobalId) {\n throw new UnsafeTransactionError('network-mismatch', `walletId.networkGlobalId ${config.walletId.networkGlobalId} contradicts network '${config.network ?? 'mainnet'}' (expected ${networkGlobalId}): externals signed this way would be valid on the other network.`)\n }\n this._walletId = v5r1WalletId({ networkGlobalId, ...(config.walletId?.subwalletNumber !== undefined ? { subwalletNumber: config.walletId.subwalletNumber } : {}) })\n this._init = v5r1StateInit(this.publicKey, this._walletId)\n this._address = v5r1Address(this.publicKey, { walletId: this._walletId })\n this.address = this._address.toString({ bounceable: false, testOnly: config.network === 'testnet' })\n this.chain = CAIP2[config.network ?? 'mainnet']\n const rpc = createTonRpc(config)\n this._rpc = rpc ? new TonCenter(rpc) : undefined\n }\n\n protected requireRpc(what: string): TonCenter {\n if (!this._rpc) throw new NetworkError(`The wallet must be connected to a provider (toncenter) to ${what}.`)\n return this._rpc\n }\n\n /** The user-friendly address. */\n async getAddress(): Promise<string> { return this.address }\n\n /** Native balance in nanotons. */\n async getBalance(): Promise<bigint> {\n return (await this.requireRpc('get balances').getAddressInformation(this._address)).balance\n }\n\n /** Current seqno — 0 until the wallet contract is deployed. Always fetched fresh. */\n async getSeqno(): Promise<number> {\n const rpc = this.requireRpc('read the seqno')\n const state = await rpc.getAddressInformation(this._address)\n if (state.state !== 'active') return 0\n return (await rpc.runGetMethodOk(this._address, 'seqno')).stack.readNumber()\n }\n\n /** Resolve this wallet's jetton wallet for a jetton master. */\n async getJettonWalletAddress(token: string): Promise<Address> {\n const rpc = this.requireRpc('resolve jetton wallets')\n const r = await rpc.runGetMethodOk(Address.parse(token), 'get_wallet_address', [\n { type: 'slice', cell: beginCell().storeAddress(this._address).endCell() },\n ])\n return r.stack.readAddress()\n }\n\n /**\n * Read a jetton wallet and prove it is ours for `token`: `get_wallet_data`\n * must name this wallet as owner and `token` as master. The master's own\n * `get_wallet_address` answer is not trusted on its own — a fake master could\n * point at our real wallet of another jetton (e.g. USDT).\n */\n protected async jettonWalletData(token: string, jw: Address): Promise<bigint> {\n const stack = (await this.requireRpc('read jetton wallets').runGetMethodOk(jw, 'get_wallet_data')).stack\n const balance = stack.readBigNumber()\n const owner = stack.readAddress()\n const master = stack.readAddress()\n if (!owner.equals(this._address) || !master.equals(Address.parse(token))) {\n throw new UnsafeTransactionError('jetton-wallet', `The jetton wallet ${jw.toString()} does not belong to this wallet for ${token}.`)\n }\n return balance\n }\n\n /**\n * Jetton balance in base units, read from this wallet's jetton wallet; 0 when it does not exist.\n */\n async getTokenBalance(token: string): Promise<bigint> {\n const rpc = this.requireRpc('get token balances')\n const jw = await this.getJettonWalletAddress(token)\n if ((await rpc.getAddressInformation(jw)).state !== 'active') return 0n // never received this jetton\n return this.jettonWalletData(token, jw)\n }\n\n // ── Message building ──────────────────────────────────────────────────────\n\n protected stateInitOf(src: TonTransaction['stateInit']): StateInit | undefined {\n if (src === undefined) return undefined\n if (typeof src === 'string') return loadStateInit(Cell.fromBase64(src).beginParse())\n if (src instanceof Cell) return loadStateInit(src.beginParse())\n return src\n }\n\n protected transactionMessage(tx: TonTransaction): V5R1Message {\n const value = big(tx.value)\n if (value <= 0n) throw new UnsafeTransactionError('zero-value', 'TON message value must be positive.')\n let address: Address\n let bounceable = true\n let testOnly: boolean | undefined\n if (Address.isFriendly(tx.to)) {\n const f = Address.parseFriendly(tx.to)\n address = f.address; bounceable = f.isBounceable; testOnly = f.isTestOnly\n } else {\n address = Address.parse(tx.to)\n }\n if (address.workChain !== 0 && address.workChain !== -1) throw new UnsafeTransactionError('exotic-workchain', `Refusing to send to workchain ${address.workChain}.`)\n const testnet = this._config.network === 'testnet'\n if (testOnly !== undefined && testOnly !== testnet) {\n throw new UnsafeTransactionError('network-mismatch', testOnly ? 'Test-only address on a mainnet wallet.' : 'Mainnet address on a testnet wallet.')\n }\n const body = tx.body instanceof Cell ? tx.body : typeof tx.body === 'string' ? (tx.body === '' ? undefined : commentCell(tx.body)) : tx.bodyBoc ? Cell.fromBase64(tx.bodyBoc) : undefined\n const init = this.stateInitOf(tx.stateInit)\n const message = internal({ to: address, value, bounce: tx.bounceable ?? bounceable, ...(body ? { body } : {}), ...(init ? { init } : {}) })\n return { message, ...(tx.sendMode !== undefined ? { mode: tx.sendMode } : {}) }\n }\n\n protected async jettonTransferMessage(o: TonTransferOptions): Promise<V5R1Message> {\n const amount = big(o.amount)\n if (amount <= 0n) throw new UnsafeTransactionError('zero-value', 'Jetton amount must be positive.')\n const recipient = Address.parse(o.recipient)\n const jw = await this.getJettonWalletAddress(o.token!)\n await this.jettonWalletData(o.token!, jw)\n const forwardTonAmount = o.forwardTonAmount !== undefined ? big(o.forwardTonAmount) : 1n\n if (o.memo !== undefined && o.forwardPayload !== undefined) throw new UnsafeTransactionError('memo-and-payload', 'Pass either memo or forwardPayload, not both: a jetton transfer carries one forward payload.')\n const payload = o.forwardPayload ?? o.memo\n const forwardPayload = payload === undefined ? null : typeof payload === 'string' ? commentCell(payload) : payload\n const body = beginCell()\n .storeUint(JETTON_TRANSFER_OP, 32)\n .storeUint(o.queryId !== undefined ? BigInt(o.queryId) : randomQueryId(), 64)\n .storeCoins(amount)\n .storeAddress(recipient)\n .storeAddress(o.responseDestination ? Address.parse(o.responseDestination) : this._address)\n .storeMaybeRef(o.customPayload ?? null)\n .storeCoins(forwardTonAmount)\n .storeMaybeRef(forwardPayload) // either-ref form: payloads always travel in a ref\n .endCell()\n const attached = o.attachedValue !== undefined\n ? big(o.attachedValue)\n : (this._config.jettonAttachedValue !== undefined ? big(this._config.jettonAttachedValue) : DEFAULT_JETTON_ATTACHED) + forwardTonAmount\n return { message: internal({ to: jw, value: attached, bounce: true, body }) }\n }\n\n protected toMessages(tx: TonTransaction | TonTransaction[]): V5R1Message[] {\n const list = Array.isArray(tx) ? tx : [tx]\n if (list.length === 0) throw new UnsafeTransactionError('empty', 'Nothing to send.')\n return list.map((t) => this.transactionMessage(t))\n }\n\n protected validUntil(): number {\n const seconds = this._config.validUntilSeconds ?? DEFAULT_VALID_SECONDS\n if (!Number.isInteger(seconds) || seconds <= 0 || seconds > MAX_VALID_SECONDS) {\n throw new UnsafeTransactionError('valid-until', `validUntilSeconds must be an integer between 1 and ${MAX_VALID_SECONDS}.`)\n }\n return Math.floor(Date.now() / 1000) + seconds\n }\n\n /** The cell to sign for `messages` at the CURRENT seqno (fetched fresh every time). */\n protected async signingCell(messages: V5R1Message[]): Promise<{ signing: Cell; seqno: number; validUntil: number }> {\n const seqno = await this.getSeqno()\n const validUntil = this.validUntil()\n return { signing: v5r1SigningMessage({ walletId: this._walletId, validUntil, seqno, messages }), seqno, validUntil }\n }\n\n // ── Fees / preflight ──────────────────────────────────────────────────────\n\n /** StateInit to attach to an external when the wallet is not deployed yet. */\n protected async initIfNeeded(): Promise<StateInit | undefined> {\n const state = await this.requireRpc('read the account state').getAddressInformation(this._address)\n return state.state === 'active' ? undefined : this._init\n }\n\n /** in_fwd + storage + gas + fwd from toncenter's estimateFee (signature ignored). */\n async estimateFees(body: Cell): Promise<TonFees> {\n const rpc = this.requireRpc('quote transfers')\n const init = await this.initIfNeeded()\n return rpc.estimateFee(this._address, { body, ...(init ? { init } : {}), ignoreSignature: true })\n }\n\n /**\n * Preflight an external body: fees via estimateFee and, unless\n * `config.emulate === false`, a trace emulation (tonapi by default, see\n * {@link TonConfig.emulate}) whose compute/action phases — and the first-hop\n * internal messages — decide `ok`. Never throws for a failing emulation,\n * only for transport problems or a malformed emulator response.\n */\n async simulateBody(body: Cell): Promise<TonSimulation> {\n const fees = await this.estimateFees(body)\n const init = await this.initIfNeeded()\n const outcome = await runEmulation(this._config, v5r1ExternalMessage(this._address, body, init))\n if (!outcome) return { ok: true, fees, emulated: false, source: 'estimate-only', warnings: [] }\n const common = {\n fees, emulated: true as const, source: outcome.source, warnings: outcome.warnings,\n ...(outcome.exitCode !== undefined ? { exitCode: outcome.exitCode } : {}),\n ...(outcome.risk ? { risk: outcome.risk } : {}),\n }\n if (outcome.ok) return { ok: true, ...common, ...(outcome.actionSuccess !== undefined ? { actionSuccess: outcome.actionSuccess } : {}) }\n return { ok: false, ...common, reason: outcome.reason ?? 'emulation failed', ...(outcome.aborted !== undefined ? { aborted: outcome.aborted } : {}) }\n }\n\n /** Preflight a {@link TonSendable} (unsigned body, current seqno). */\n async simulateTransaction(tx: TonSendable): Promise<TonSimulation> {\n const body = tx instanceof Cell ? tx : v5r1PackUnsigned((await this.signingCell(this.toMessages(tx))).signing)\n return this.simulateBody(body)\n }\n\n /** Estimated fee of a transaction, in nanotons. */\n async quoteSendTransaction(tx: TonSendable): Promise<{ fee: bigint }> {\n const body = tx instanceof Cell ? tx : v5r1PackUnsigned((await this.signingCell(this.toMessages(tx))).signing)\n return { fee: (await this.estimateFees(body)).total }\n }\n\n /** Estimated fee of a transfer, in nanotons. */\n async quoteTransfer(o: TonTransferOptions): Promise<{ fee: bigint }> {\n const message = o.token ? await this.jettonTransferMessage(o) : this.transactionMessage({ to: o.recipient, value: o.amount, ...(o.memo !== undefined ? { body: o.memo } : {}) })\n const { signing } = await this.signingCell([message])\n return { fee: (await this.estimateFees(v5r1PackUnsigned(signing))).total }\n }\n\n /** Offline description of what `tx` does — see {@link describeTransaction}. */\n describe(tx: TonSendable): TonDescription {\n return describeTransaction(tx, { network: this._config.network ?? 'mainnet' })\n }\n\n /**\n * Receipt for a body hash returned by sendTransaction: toncenter v3 maps the\n * message body hash to the account transaction, which is then fetched.\n */\n async getTransactionReceipt(hash: string): Promise<TonReceipt | undefined> {\n const rpc = this.requireRpc('fetch transaction receipts')\n const base = this._config.indexerUrl ?? DEFAULT_INDEXER\n const doFetch = this._config.fetch ?? globalThis.fetch\n const res = await doFetch(`${base}/transactionsByMessage?${new URLSearchParams({ body_hash: hash, limit: '1' })}`, { signal: AbortSignal.timeout(this._config.timeoutMs ?? 15_000) })\n if (!res.ok) throw new NetworkError(`toncenter v3 ${res.status}`, { provider: base })\n const { transactions } = (await res.json()) as { transactions?: Array<{ account: string; hash: string; lt: string }> }\n const found = transactions?.[0]\n if (!found) return undefined\n const account = Address.parse(found.account)\n let tx\n try { [tx] = await rpc.getTransactions(account, { limit: 1, hash: found.hash }) }\n catch { [tx] = await rpc.getTransactions(account, { limit: 1, lt: found.lt, hash: found.hash, archival: true }) }\n if (!tx) return undefined\n const d = tx.description as { type: string; aborted?: boolean }\n return { hash, status: d.type === 'generic' && !d.aborted ? 1 : 0, blockNumber: tx.lt, transactionHash: tx.hash().toString('base64'), totalFees: tx.totalFees.coins, raw: tx }\n }\n\n /** ed25519 over the raw message bytes; `signature` hex. */\n async verify(message: string | Uint8Array, signature: string): Promise<boolean> {\n try { return ed25519.verify(hexToBytes(signature), utf8(message), this.publicKey) } catch { return false }\n }\n}\n\nfunction randomQueryId(): bigint {\n const r = new Uint32Array(2)\n globalThis.crypto.getRandomValues(r)\n return (BigInt(r[0]!) << 32n) | BigInt(r[1]!)\n}\n","import { LocalSigner, requireCurve, type IWalletAccount, type IWalletAccountReadOnly, type Signer, type TransferResult } from '@anywalletkit/core'\nimport { Cell } from '@ton/core'\nimport { SimulationError, UnsafeTransactionError } from './errors.js'\nimport { WalletAccountReadOnlyTon } from './read-only-account.js'\nimport { v5r1ExternalMessage, v5r1PackSigned, v5r1PackUnsigned, type V5R1Message } from './wallet-v5r1.js'\nimport type { TonConfig, TonSendable, TonTransferOptions } from './types.js'\n\nconst toHex = (u8: Uint8Array) => Array.from(u8, (b) => b.toString(16).padStart(2, '0')).join('')\n\n/**\n * Signing TON account on Wallet V5R1. It never holds a key: the V5R1 body is\n * signed by `signer.sign(signingCell.hash(), {scheme: 'ed25519', context:\n * 'ton-external'})` — a {@link LocalSigner} for seed wallets, anything else\n * (hardware, MPC, backend) through `externalSigner()`.\n *\n * Every send runs: hard checks → fresh seqno → preflight on the zero-signed\n * body (estimateFee, emulation when configured, fee cap) → sign → broadcast.\n * The preflight body carries a zero signature, so the signer is only asked\n * once the transaction has passed.\n */\nexport class WalletAccountTon extends WalletAccountReadOnlyTon implements IWalletAccount {\n /** seqno and fees come from the network before signing. */\n readonly needsNetwork = true\n /** Derivation path, `ton-mnemonic`, or `external`. */\n readonly path: string\n /** The signer that holds the key. */\n readonly signer: Signer\n private _readOnly: WalletAccountReadOnlyTon | undefined\n\n /** `publicKey` is the signer's 32-byte ed25519 key; the V5R1 address derives from it synchronously. */\n constructor(signer: Signer, publicKey: Uint8Array, path: string, config: TonConfig = {}) {\n super(publicKey, config)\n this.signer = requireCurve(signer, 'ed25519')\n this.path = path\n }\n\n /** Back-compat: wrap a raw derived key in a {@link LocalSigner} (the account takes ownership; it cannot derive). */\n static fromPrivateKey(privateKey: Uint8Array, publicKey: Uint8Array, path: string, config: TonConfig = {}): WalletAccountTon {\n return new WalletAccountTon(LocalSigner.fromPrivateKey('ed25519', privateKey, publicKey, path), publicKey, path, config)\n }\n\n /** Account index for the standard m/44'/607'/i' path. */\n get index(): number | undefined {\n const m = /^m\\/44'\\/607'\\/(\\d+)'$/.exec(this.path)\n return m ? Number(m[1]) : undefined\n }\n\n /** Hex ed25519 signature over the raw message bytes (ton_proof and the like). */\n async sign(message: string | Uint8Array): Promise<string> {\n const bytes = typeof message === 'string' ? new TextEncoder().encode(message) : message\n return toHex(await this.signer.sign(bytes, { scheme: 'ed25519', context: 'ton-message' }))\n }\n\n private checkMaxFee(fee: bigint, limit: bigint | number | undefined, op: string) {\n if (limit !== undefined && fee > BigInt(limit)) throw new Error(`Exceeded maximum fee cost for ${op} operation.`)\n }\n\n /**\n * Checks → seqno → preflight → signed body. The preflight runs on the\n * zero-signed body (ignore_chksig), so nothing is signed before it passes.\n */\n private async prepare(messages: V5R1Message[], limit: bigint | number | undefined, op: string): Promise<{ body: Cell; fee: bigint }> {\n // The wallet sends with IGNORE_ERRORS: a message whose value exceeds the\n // balance is silently dropped by the action phase — the external still\n // \"succeeds\", the seqno moves, the fee is paid and nothing leaves\n // (2026-10-09: a 2 GRAM deposit on a 0.46 GRAM balance). Refuse up front,\n // and again after emulation if the risk shows less TON leaving than asked.\n const want = messages.reduce((sum, m) => sum + (m.message.info.type === 'internal' ? m.message.info.value.coins : 0n), 0n)\n if (want > 0n) {\n const balance = await this.getBalance()\n if (balance < want) throw new UnsafeTransactionError('insufficient-balance', `Insufficient TON balance: the messages carry ${want} nanotons, the wallet holds ${balance} (fees come on top).`)\n }\n const { signing } = await this.signingCell(messages)\n const fee = await this.preflight(v5r1PackUnsigned(signing), limit, op, want)\n const signature = await this.signer.sign(new Uint8Array(signing.hash()), { scheme: 'ed25519', context: 'ton-external' })\n return { body: v5r1PackSigned(signing, signature), fee }\n }\n\n private async preflight(body: Cell, limit: bigint | number | undefined, op: string, expectedTonOut?: bigint): Promise<bigint> {\n if (this._config.simulate === false) {\n if (limit === undefined) return 0n\n const fee = (await this.estimateFees(body)).total\n this.checkMaxFee(fee, limit, op)\n return fee\n }\n const sim = await this.simulateBody(body)\n if (!sim.ok) throw new SimulationError(sim.reason, { ...(sim.exitCode !== undefined ? { exitCode: sim.exitCode } : {}), ...(sim.aborted !== undefined ? { aborted: sim.aborted } : {}) })\n if (sim.risk?.transferAllRemainingBalance && this._config.allowDrainingTransactions !== true) {\n throw new UnsafeTransactionError('drain', 'Refusing a message that carries the whole remaining balance (send mode 128); set allowDrainingTransactions to override.')\n }\n if (expectedTonOut !== undefined && sim.risk && sim.risk.ton < expectedTonOut) {\n throw new SimulationError(`The emulation shows only ${sim.risk.ton} nanotons leaving the wallet for messages carrying ${expectedTonOut}: a message would be dropped (insufficient balance for value + fees).`)\n }\n this.checkMaxFee(sim.fees.total, limit, op)\n return sim.fees.total\n }\n\n /** Sign without broadcasting. Returns the external-message BODY as base64 BoC (pass it back to sendTransaction as a Cell). */\n async signTransaction(tx: TonSendable): Promise<string> {\n if (tx instanceof Cell) {\n await this.preflight(tx, this._config.transactionMaxFee, 'transaction')\n return tx.toBoc().toString('base64')\n }\n const { body } = await this.prepare(this.toMessages(tx), this._config.transactionMaxFee, 'transaction')\n return body.toBoc().toString('base64')\n }\n\n private async broadcast(body: Cell): Promise<string> {\n const rpc = this.requireRpc('send transactions')\n const init = await this.initIfNeeded()\n await rpc.sendBoc(v5r1ExternalMessage(this._address, body, init))\n return body.hash().toString('hex')\n }\n\n /** Sign and broadcast; `hash` is the body hash (hex) — resolve it with getTransactionReceipt. */\n async sendTransaction(tx: TonSendable): Promise<TransferResult> {\n this.requireRpc('send transactions')\n const { body, fee } = tx instanceof Cell\n ? { body: tx, fee: await this.preflight(tx, this._config.transactionMaxFee, 'transaction') }\n : await this.prepare(this.toMessages(tx), this._config.transactionMaxFee, 'transaction')\n return { hash: await this.broadcast(body), fee }\n }\n\n /** TON (no `token`) or jetton transfer. */\n async transfer(o: TonTransferOptions): Promise<TransferResult> {\n this.requireRpc('transfer tokens')\n const message = o.token ? await this.jettonTransferMessage(o) : this.transactionMessage({ to: o.recipient, value: o.amount, ...(o.memo !== undefined ? { body: o.memo } : {}) })\n const { body, fee } = await this.prepare([message], this._config.transferMaxFee, 'transfer')\n return { hash: await this.broadcast(body), fee }\n }\n\n /** The same wallet as a {@link WalletAccountReadOnlyTon}. */\n toReadOnlyAccount(): IWalletAccountReadOnly {\n this._readOnly ??= new WalletAccountReadOnlyTon(this.publicKey, this._config)\n return this._readOnly\n }\n\n /** Disposes the signer: a local key is zeroized, an external one is released. */\n dispose(): void {\n this.signer.dispose()\n }\n}\n","import { LocalSigner, SignerError, WalletManager, isSeedSigner, zeroize, type FeeRates, type Signer } from '@anywalletkit/core'\nimport { mnemonicToPrivateKey } from '@ton/crypto'\nimport { WalletAccountTon } from './account.js'\nimport { WalletAccountReadOnlyTon } from './read-only-account.js'\nimport type { TonConfig } from './types.js'\n\n/** Base derivation path for BIP-39 seeds; account `i` is at `m/44'/607'/i'`. */\nexport const TON_BASE_PATH = \"m/44'/607'\"\n/** Path label of the account a TON-native (Tonkeeper-style) mnemonic yields — there is exactly one. */\nexport const TON_MNEMONIC_PATH = 'ton-mnemonic'\nimport { DEFAULT_TONAPI } from './emulation.js'\n\n/**\n * One seed → TON accounts at m/44'/607'/i' (SLIP-10 ed25519) on Wallet V5R1 —\n * the derivation Trust Wallet and Ledger use for a BIP-39 phrase. Paths\n * may be relative to m/44'/607' (\"0'\") or full.\n *\n * Built with an ed25519 `Signer` instead of a seed, the manager wraps it:\n * - a derivable `SeedSigner` sitting at `m/44'/607'` yields `getAccount(i)` → `i'` children;\n * - a `SeedSigner` at a leaf, or any external signer, is `getAccount(0)` (path = the\n * signer's path, or 'external'); other indexes/paths throw.\n *\n * Tonkeeper-style 24-word TON mnemonics (not BIP-39) are imported with\n * {@link WalletManagerTon.fromTonMnemonic}; they yield one account at `ton-mnemonic`.\n */\nexport class WalletManagerTon extends WalletManager<WalletAccountTon, TonConfig> {\n constructor(seedOrSigner: string | Uint8Array | Signer, config: TonConfig = {}) {\n super(seedOrSigner, config)\n }\n\n\n /**\n * Import a TON-native mnemonic (24 words, Tonkeeper / Tonhub / MyTonWallet\n * default): PBKDF2 per @ton/crypto, one ed25519 key, one V5R1 account at\n * path `ton-mnemonic` with the address those wallets show.\n */\n static async fromTonMnemonic(words: string[] | string, config: TonConfig = {}): Promise<WalletManagerTon> {\n const list = (Array.isArray(words) ? words : words.trim().split(/\\s+/)).map((w) => w.toLowerCase())\n if (list.length !== 24) throw new Error('A TON mnemonic has 24 words.')\n const pair = await mnemonicToPrivateKey(list)\n const privateKey = new Uint8Array(pair.secretKey.subarray(0, 32)) // nacl secret key = seed || public key\n const publicKey = new Uint8Array(pair.publicKey)\n zeroize(new Uint8Array(pair.secretKey.buffer, pair.secretKey.byteOffset, pair.secretKey.byteLength))\n return new WalletManagerTon(LocalSigner.fromPrivateKey('ed25519', privateKey, publicKey, TON_MNEMONIC_PATH), config)\n }\n\n async getAccount(index = 0): Promise<WalletAccountTon> {\n const external = this.externalSigner()\n if (external && !(isSeedSigner(external) && external.path === TON_BASE_PATH)) {\n // A leaf signer (TON mnemonic, hardware, MPC…) is exactly one account.\n if (index !== 0) throw new SignerError(`This signer yields a single account (index 0); ${index} is not derivable from it.`)\n return this.fromSigner(external, this.singlePath(external))\n }\n return this.getAccountByPath(`${TON_BASE_PATH}/${index}'`)\n }\n\n async getAccountByPath(path: string): Promise<WalletAccountTon> {\n const external = this.externalSigner()\n if (external) {\n const single = this.singlePath(external)\n const full = path === single || path.startsWith('m/') ? path : `${TON_BASE_PATH}/${path}`\n return this.fromSigner(external, full)\n }\n const full = path.startsWith('m/') ? path : `${TON_BASE_PATH}/${path}`\n const cached = this._accounts.get(full)\n if (cached) return cached\n const signer = LocalSigner.leafFromSeed(this.seedBytes(), 'ed25519', full)\n const account = new WalletAccountTon(signer, signer.publicKey, full, this._config)\n this._accounts.set(full, account)\n return account\n }\n\n /** The one path a non-derivable signer answers to: its own, or 'external'. */\n private singlePath(signer: Signer): string {\n return isSeedSigner(signer) ? signer.path : 'external'\n }\n\n /** Resolve `path` against an injected signer: the signer itself, or a child when it can derive there. */\n private async fromSigner(signer: Signer, path: string): Promise<WalletAccountTon> {\n this.requireSigner('ed25519')\n let leaf: Signer = signer\n let key = this.singlePath(signer)\n if (isSeedSigner(signer)) {\n if (path === signer.path) key = path\n else if (path.startsWith(`${signer.path}/`)) { leaf = await (signer.deriveLeaf ?? signer.derive).call(signer, path.slice(signer.path.length + 1)); key = path }\n else throw new SignerError(`This signer yields a single account at path '${signer.path}'; it cannot provide ${path}.`)\n } else if (path !== `${TON_BASE_PATH}/0'` && path !== 'external') {\n throw new SignerError(`An external signer yields a single account; ${path} is not derivable from it.`)\n }\n const cached = this._accounts.get(key)\n if (cached) return cached\n const account = new WalletAccountTon(leaf, await leaf.getPublicKey(), key, this._config)\n this._accounts.set(key, account)\n return account\n }\n\n /** Watch-only account for a public key (hex or bytes) — TON addresses derive from the key, not the other way round. */\n getReadOnlyAccount(publicKey: Uint8Array | string): WalletAccountReadOnlyTon {\n return new WalletAccountReadOnlyTon(publicKey, this._config)\n }\n\n /** Gas price from config param 21 via tonapi (normal = fast there; slow = ×0.8 here). */\n async getFeeRates(): Promise<FeeRates> {\n const doFetch = this._config.fetch ?? globalThis.fetch\n const res = await doFetch(`${this._config.tonApiUrl ?? DEFAULT_TONAPI}/blockchain/config/raw`, { signal: AbortSignal.timeout(this._config.timeoutMs ?? 15_000) })\n const json = (await res.json()) as { config: { config_param21: { gas_limits_prices: { gas_flat_pfx: { other: { gas_prices_ext: { gas_price: number } } } } } } }\n const normal = BigInt(Math.round(json.config.config_param21.gas_limits_prices.gas_flat_pfx.other.gas_prices_ext.gas_price / 65_536))\n return { slow: (normal * 80n) / 100n, normal, fast: normal }\n }\n\n}\n","/**\n * Activity history for TON: a `HistorySource` over tonapi account events\n * (`/v2/accounts/{a}/events`, keyless or with a Bearer key) with toncenter v3\n * (`/api/v3/transactions`) as a reduced fallback.\n *\n * tonapi groups a whole trace (the wallet's message and everything it caused)\n * into one event with typed actions; each action becomes native / jetton\n * transfers and the first contract-level action becomes `call`. The fee is\n * tonapi's `extra` (what the account lost beyond its actions). toncenter sees\n * only the account's own transactions: TON in / out and op codes, no jettons.\n * Addresses are kept raw (`0:…`, lowercase) as both indexers return them;\n * recognizers normalize. `fetch` + `AbortSignal.timeout` only — Hermes-safe.\n */\nimport { Address } from '@ton/core'\nimport { Buffer } from 'buffer'\nimport type { ChainCall, ChainTransfer, ChainTx, HistoryPage, HistoryQuery, HistorySource } from '@anywalletkit/core'\nimport { CAIP2 } from './types.js'\n\n// ── Public types ─────────────────────────────────────────────────────────────\n\nexport type HistoryFetch = (\n input: string,\n init?: { method?: string; headers?: Record<string, string>; signal?: AbortSignal },\n) => Promise<{ ok: boolean; status: number; json(): Promise<unknown> }>\n\n/** Which indexer answered: tonapi events or toncenter v3 transactions. */\nexport type TonHistoryBackend = 'tonapi' | 'toncenter'\n\n/** Options for `createTonHistory`: tonapi first, toncenter v3 as the fallback. */\nexport interface TonHistoryOptions {\n /** tonapi root. Default `https://tonapi.io` (`https://testnet.tonapi.io` on testnet). `null` disables tonapi. */\n tonapiUrl?: string | null\n /** tonapi Bearer key. Keyless tonapi allows ~1 request/s. */\n apiKey?: string\n /** toncenter root for the v3 fallback. Default `https://toncenter.com` (`https://testnet.toncenter.com`). `null` disables it. */\n toncenterUrl?: string | null\n /** toncenter `X-API-Key`. */\n toncenterApiKey?: string\n network?: 'mainnet' | 'testnet'\n fetch?: HistoryFetch\n /** tonapi requests per second. Default 1 without a key, 10 with one. */\n rateLimit?: number\n /** Per request, ms. Default 15 000. */\n timeoutMs?: number\n}\n\nexport interface TonHistoryRaw {\n backend: TonHistoryBackend\n /** The tonapi account event, or the toncenter v3 transaction row. */\n event: unknown\n /** tonapi flagged the event as scam. */\n scam?: boolean\n /** tonapi `value_flow` for the account when it had to be fetched to recover jetton movements. */\n valueFlow?: unknown\n}\n\nexport interface TonChainTx extends ChainTx {\n /** Mirrors `raw.scam`; the app hides these by default. */\n scam?: boolean\n raw: TonHistoryRaw\n}\n\nexport interface TonHistoryPage extends HistoryPage {\n items: TonChainTx[]\n backend?: TonHistoryBackend\n}\n\n/**\n * TON history from tonapi events with a toncenter v3 fallback. Build it with `createTonHistory`.\n */\nexport interface TonHistorySource extends HistorySource {\n listActivity(address: string, query?: HistoryQuery): Promise<TonHistoryPage>\n getTransaction(hash: string, address: string): Promise<TonChainTx | undefined>\n}\n\n/** Every configured history backend failed (or none was configured). */\nexport class HistoryUnavailableError extends Error {\n readonly chain: string\n readonly reason: string\n readonly attempts: readonly string[]\n constructor(chain: string, reason: string, attempts: readonly string[] = []) {\n super(`History unavailable for ${chain}: ${reason}`)\n this.name = 'HistoryUnavailableError'\n this.chain = chain\n this.reason = reason\n this.attempts = attempts\n }\n}\n\nconst DEFAULT_LIMIT = 25\nconst MAX_LIMIT = 100\nconst DEFAULT_TIMEOUT_MS = 15_000\n\n// ── Cursor: an exclusive `lt` upper bound, base64 JSON ───────────────────────\n\nexport interface TonHistoryCursor {\n v: 1\n b: TonHistoryBackend\n /** Next page = events / transactions with `lt < this` (decimal string). */\n lt: string\n}\n\nexport function encodeCursor(c: TonHistoryCursor): string {\n return Buffer.from(JSON.stringify(c), 'utf8').toString('base64')\n}\n\nexport function decodeCursor(s: string): TonHistoryCursor {\n let parsed: unknown\n try {\n parsed = JSON.parse(Buffer.from(s, 'base64').toString('utf8'))\n } catch {\n throw new Error('@anywalletkit/wallet-ton: malformed history cursor')\n }\n const c = parsed as Partial<TonHistoryCursor> | null\n if (!c || c.v !== 1 || (c.b !== 'tonapi' && c.b !== 'toncenter') || typeof c.lt !== 'string' || !/^\\d+$/.test(c.lt)) {\n throw new Error('@anywalletkit/wallet-ton: malformed history cursor')\n }\n return { v: 1, b: c.b, lt: c.lt }\n}\n\n// ── Helpers ──────────────────────────────────────────────────────────────────\n\nclass TokenBucket {\n private tokens: number\n private last = Date.now()\n private chain: Promise<void> = Promise.resolve()\n constructor(private readonly rate: number, private readonly burst = Math.max(1, Math.ceil(rate))) {\n this.tokens = burst\n }\n acquire(): Promise<void> {\n const next = this.chain.then(() => this.take())\n this.chain = next.catch(() => undefined)\n return next\n }\n private refill(): void {\n const now = Date.now()\n this.tokens = Math.min(this.burst, this.tokens + ((now - this.last) / 1000) * this.rate)\n this.last = now\n }\n private async take(): Promise<void> {\n this.refill()\n if (this.tokens >= 1) {\n this.tokens -= 1\n return\n }\n await new Promise((r) => setTimeout(r, Math.ceil(((1 - this.tokens) / this.rate) * 1000)))\n this.refill()\n this.tokens = Math.max(0, this.tokens - 1)\n }\n}\n\nfunction timeoutSignal(ms: number): AbortSignal | undefined {\n const ctor = (globalThis as { AbortSignal?: { timeout?: (ms: number) => AbortSignal } }).AbortSignal\n return typeof ctor?.timeout === 'function' ? ctor.timeout(ms) : undefined\n}\n\n/** Any spelling → raw lowercase `wc:hex`; unparsable input is returned as-is. */\nexport function rawTonAddress(a: string): string {\n try {\n return Address.parse(a).toRawString().toLowerCase()\n } catch {\n return a.toLowerCase()\n }\n}\n\nconst big = (v: unknown): bigint => {\n if (typeof v === 'bigint') return v\n if (typeof v === 'number' && Number.isFinite(v)) return BigInt(Math.trunc(v))\n if (typeof v === 'string' && /^-?\\d+$/.test(v)) return BigInt(v)\n return 0n\n}\n\nconst isHexOp = (s: unknown): s is string => typeof s === 'string' && /^0x[0-9a-f]{1,8}$/i.test(s)\n\n// ── tonapi shapes (what the mapper reads) ────────────────────────────────────\n\ninterface TonapiAccount { address: string; is_wallet?: boolean; is_scam?: boolean; name?: string }\ninterface TonapiJetton { address: string; symbol?: string; decimals?: number; name?: string }\nexport interface TonapiAction {\n type: string\n status: 'ok' | 'failed' | string\n [body: string]: unknown\n}\nexport interface TonapiEvent {\n event_id: string\n account?: TonapiAccount\n timestamp: number\n lt: number | string\n in_progress: boolean\n is_scam: boolean\n actions: TonapiAction[]\n /** Account-scoped events only: TON the account lost beyond its actions (negative = fees). */\n extra?: number\n value_flow?: Array<{ account: TonapiAccount; ton: number; jettons?: Array<{ jetton: TonapiJetton; quantity: number | string }> }>\n}\n\ninterface MappedActions {\n transfers: ChainTransfer[]\n call?: ChainCall\n /** Who initiated the event as far as the first action tells. */\n initiator?: string\n /** The event needs `value_flow` to recover a jetton movement tonapi did not spell out (unstake requests). */\n needsValueFlow?: { counterparty: string }\n}\n\nconst jettonMeta = (j: TonapiJetton | undefined): Pick<ChainTransfer, 'symbol' | 'decimals'> => {\n const m: Pick<ChainTransfer, 'symbol' | 'decimals'> = {}\n if (j?.symbol !== undefined) m.symbol = j.symbol\n if (j?.decimals !== undefined) m.decimals = j.decimals\n return m\n}\n\nconst addr = (a: unknown): string | undefined => (typeof a === 'object' && a !== null && typeof (a as TonapiAccount).address === 'string' ? (a as TonapiAccount).address.toLowerCase() : typeof a === 'string' ? a.toLowerCase() : undefined)\nconst isWallet = (a: unknown): boolean => typeof a === 'object' && a !== null && (a as TonapiAccount).is_wallet === true\n\n/** tonapi actions → transfers + the contract call. Only `ok` actions move value. */\nexport function mapActions(actions: TonapiAction[]): MappedActions {\n const out: MappedActions = { transfers: [] }\n const native = (from: string | undefined, to: string | undefined, amount: bigint) => {\n if (from === undefined || to === undefined || amount <= 0n) return\n out.transfers.push({ token: null, from, to, amount })\n }\n const jetton = (j: TonapiJetton | undefined, from: string | undefined, to: string | undefined, amount: bigint) => {\n if (!j || from === undefined || to === undefined || amount <= 0n) return\n out.transfers.push({ token: j.address.toLowerCase(), from, to, amount, standard: 'jetton', ...jettonMeta(j) })\n }\n const setCall = (c: ChainCall | undefined) => {\n if (c && !out.call) out.call = c\n }\n const init = (a: string | undefined) => {\n if (out.initiator === undefined && a !== undefined) out.initiator = a\n }\n for (const a of actions) {\n const b = (a[a.type] ?? {}) as Record<string, unknown>\n const ok = a.status === 'ok'\n switch (a.type) {\n case 'TonTransfer': {\n const from = addr(b.sender), to = addr(b.recipient)\n init(from)\n if (ok) native(from, to, big(b.amount))\n break\n }\n case 'JettonTransfer': {\n const from = addr(b.sender) ?? addr(b.senders_wallet), to = addr(b.recipient) ?? addr(b.recipients_wallet)\n init(from)\n if (ok) jetton(b.jetton as TonapiJetton, from, to, big(b.amount))\n // A jetton sent to a contract with a forward payload is a call; tonapi surfaces the op as \"Call: 0x…\".\n if (to !== undefined && b.recipient !== undefined && !isWallet(b.recipient)) {\n const c: ChainCall = { to, method: 'jetton_transfer' }\n const m = typeof b.comment === 'string' ? /^Call:\\s*(0x[0-9a-f]+)/i.exec(b.comment) : null\n if (m) c.data = m[1]!.toLowerCase()\n setCall(c)\n }\n break\n }\n case 'JettonMint': {\n const j = b.jetton as TonapiJetton | undefined\n if (ok) jetton(j, j?.address.toLowerCase(), addr(b.recipient) ?? addr(b.recipients_wallet), big(b.amount))\n break\n }\n case 'JettonBurn': {\n const j = b.jetton as TonapiJetton | undefined\n const from = addr(b.sender) ?? addr(b.senders_wallet)\n init(from)\n if (ok) jetton(j, from, j?.address.toLowerCase(), big(b.amount))\n setCall(j ? { to: j.address.toLowerCase(), method: 'jetton_burn' } : undefined)\n break\n }\n case 'JettonSwap': {\n const user = addr(b.user_wallet), router = addr(b.router)\n init(user)\n if (ok) {\n native(user, router, big(b.ton_in))\n jetton(b.jetton_master_in as TonapiJetton | undefined, user, router, big(b.amount_in))\n native(router, user, big(b.ton_out))\n jetton(b.jetton_master_out as TonapiJetton | undefined, router, user, big(b.amount_out))\n }\n if (router !== undefined) setCall({ to: router, method: 'swap' })\n break\n }\n case 'SmartContractExec': {\n const executor = addr(b.executor), contract = addr(b.contract)\n init(executor)\n if (ok) native(executor, contract, big(b.ton_attached))\n if (contract !== undefined) {\n const c: ChainCall = { to: contract }\n if (isHexOp(b.operation)) c.data = b.operation.toLowerCase()\n else if (typeof b.operation === 'string' && b.operation) c.method = b.operation\n setCall(c)\n }\n break\n }\n case 'DepositStake': {\n const staker = addr(b.staker), pool = addr(b.pool)\n init(staker)\n if (ok) native(staker, pool, big(b.amount))\n if (pool !== undefined) setCall({ to: pool, method: 'stake' })\n break\n }\n case 'WithdrawStakeRequest': {\n const staker = addr(b.staker), pool = addr(b.pool)\n init(staker)\n if (ok && b.amount !== undefined) native(staker, pool, big(b.amount))\n if (pool !== undefined) {\n setCall({ to: pool, method: 'unstake' })\n // tonapi does not spell out the pool-token burn; `value_flow` has it.\n if (ok) out.needsValueFlow ??= { counterparty: pool }\n }\n break\n }\n case 'WithdrawStake': {\n const staker = addr(b.staker), pool = addr(b.pool)\n init(pool)\n if (ok) native(pool, staker, big(b.amount))\n if (pool !== undefined) setCall({ to: pool, method: 'withdraw_stake' })\n break\n }\n case 'ElectionsDepositStake':\n case 'ElectionsRecoverStake': {\n const staker = addr(b.staker)\n init(staker)\n // The elector has no address in the action; keep the movement against the elector pseudo-account.\n if (ok) a.type === 'ElectionsDepositStake' ? native(staker, '-1:3333333333333333333333333333333333333333333333333333333333333333', big(b.amount)) : native('-1:3333333333333333333333333333333333333333333333333333333333333333', staker, big(b.amount))\n break\n }\n case 'Subscribe':\n case 'UnSubscribe': {\n const subscriber = addr(b.subscriber), beneficiary = addr(b.beneficiary), subscription = addr(b.subscription)\n init(subscriber)\n if (ok && a.type === 'Subscribe') native(subscriber, beneficiary, big(b.amount))\n if (subscription !== undefined) setCall({ to: subscription, method: a.type === 'Subscribe' ? 'subscribe' : 'unsubscribe' })\n break\n }\n case 'NftPurchase': {\n const buyer = addr(b.buyer), seller = addr(b.seller), nft = addr(b.nft)\n init(buyer)\n if (ok) native(buyer, seller, big((b.amount as { value?: unknown } | undefined)?.value ?? b.amount))\n if (nft !== undefined) setCall({ to: nft, method: 'nft_purchase' })\n break\n }\n case 'ContractDeploy': {\n const deployed = addr(b.address)\n if (deployed !== undefined) setCall({ to: deployed, method: 'deploy' })\n break\n }\n default:\n // NftItemTransfer, AuctionBid, DomainRenew, Unknown…: nothing to account for.\n break\n }\n }\n return out\n}\n\n/** The account's jetton deltas from `value_flow` as transfers against `counterparty`. */\nexport function valueFlowTransfers(event: TonapiEvent, own: string, counterparty: string): ChainTransfer[] {\n const flow = event.value_flow?.find((v) => addr(v.account) === own)\n const out: ChainTransfer[] = []\n for (const j of flow?.jettons ?? []) {\n const q = big(j.quantity)\n if (q === 0n) continue\n const t: ChainTransfer = { token: j.jetton.address.toLowerCase(), from: q < 0n ? own : counterparty, to: q < 0n ? counterparty : own, amount: q < 0n ? -q : q, standard: 'jetton', ...jettonMeta(j.jetton) }\n out.push(t)\n }\n return out\n}\n\nexport function mapTonapiEvent(chain: string, address: string, own: string, event: TonapiEvent, valueFlow?: TonapiEvent): TonChainTx {\n const mapped = mapActions(event.actions ?? [])\n const transfers = mapped.transfers\n const raw: TonHistoryRaw = { backend: 'tonapi', event }\n if (mapped.needsValueFlow && valueFlow) {\n raw.valueFlow = valueFlow.value_flow\n const extra = valueFlowTransfers(valueFlow, own, mapped.needsValueFlow.counterparty)\n for (const t of extra) if (!transfers.some((x) => x.token === t.token && x.from === t.from && x.to === t.to && x.amount === t.amount)) transfers.push(t)\n }\n const from = mapped.initiator ?? own\n const involves = (t: ChainTransfer) => t.from === own || t.to === own\n const primary = transfers.find((t) => t.token !== null && involves(t)) ?? transfers.find(involves) ?? transfers[0]\n const to = mapped.call?.to ?? primary?.to ?? null\n let nativeValue = 0n\n for (const t of transfers) if (t.token === null && t.from === from) nativeValue += t.amount\n const actions = event.actions ?? []\n const status: ChainTx['status'] = event.in_progress ? 'pending' : actions.length > 0 && actions.every((a) => a.status !== 'ok') ? 'failed' : 'confirmed'\n const out: TonChainTx = {\n chain, hash: event.event_id, time: event.timestamp, status, address, from, to, nativeValue, transfers, block: big(event.lt), raw,\n }\n if (typeof event.extra === 'number' && event.extra < 0) out.fee = BigInt(-event.extra)\n if (mapped.call) out.call = mapped.call\n if (event.is_scam) {\n out.scam = true\n raw.scam = true\n }\n return out\n}\n\n// ── toncenter v3 shapes ──────────────────────────────────────────────────────\n\ninterface V3Message {\n source?: string | null\n destination?: string | null\n value?: string | null\n opcode?: string | null\n decoded_opcode?: string | null\n}\nexport interface V3Transaction {\n account: string\n /** base64. */\n hash: string\n lt: string\n now: number\n total_fees: string\n description?: { aborted?: boolean; compute_ph?: { success?: boolean; exit_code?: number; skipped?: boolean }; action?: { success?: boolean } }\n in_msg?: V3Message | null\n out_msgs?: V3Message[]\n}\n\nconst TEXT_COMMENT_OP = '0x00000000'\n\n/** Reduced mapping: TON in / out and op codes of the account's own transaction; jettons are not visible here. */\nexport function mapToncenterTransaction(chain: string, address: string, row: V3Transaction): TonChainTx {\n const own = row.account.toLowerCase()\n const hash = Buffer.from(row.hash, 'base64').toString('hex')\n const d = row.description\n const failed = d?.aborted === true || (d?.compute_ph?.skipped !== true && d?.compute_ph?.success === false) || d?.action?.success === false\n const transfers: ChainTransfer[] = []\n let from = own\n let to: string | null = null\n let call: ChainCall | undefined\n const source = row.in_msg?.source ? row.in_msg.source.toLowerCase() : undefined\n if (source === undefined) {\n // External message: the wallet acted. Its outgoing messages are the transfers.\n for (const m of row.out_msgs ?? []) {\n const dest = m.destination?.toLowerCase()\n if (!dest) continue\n const value = big(m.value)\n if (value > 0n) transfers.push({ token: null, from: own, to: dest, amount: value })\n if (!call && m.opcode && m.opcode !== TEXT_COMMENT_OP) {\n call = { to: dest, data: m.opcode.toLowerCase() }\n if (m.decoded_opcode) call.method = m.decoded_opcode\n }\n to ??= dest\n }\n } else {\n from = source\n to = own\n const value = big(row.in_msg?.value)\n if (value > 0n) transfers.push({ token: null, from: source, to: own, amount: value })\n const op = row.in_msg?.opcode\n if (op && op !== TEXT_COMMENT_OP) {\n call = { to: own, data: op.toLowerCase() }\n if (row.in_msg?.decoded_opcode) call.method = row.in_msg.decoded_opcode\n }\n }\n let nativeValue = 0n\n for (const t of transfers) if (t.token === null && t.from === from) nativeValue += t.amount\n const out: TonChainTx = {\n chain, hash, time: row.now, status: failed ? 'failed' : 'confirmed', address, from, to: call?.to ?? to, nativeValue, transfers, fee: big(row.total_fees), block: big(row.lt),\n raw: { backend: 'toncenter', event: row },\n }\n if (call) out.call = call\n return out\n}\n\n// ── Source ───────────────────────────────────────────────────────────────────\n\n/** Tonviewer link for a transaction. */\nexport function tonExplorerTxUrl(hash: string, network: 'mainnet' | 'testnet' = 'mainnet'): string {\n return `https://${network === 'testnet' ? 'testnet.' : ''}tonviewer.com/transaction/${hash}`\n}\n\n/**\n * A `HistorySource` for TON: tonapi account events first, toncenter v3 when\n * tonapi is down or disabled. Both page by `lt`, so a cursor from one backend\n * resumes on the other.\n */\nexport function createTonHistory(options: TonHistoryOptions = {}): TonHistorySource {\n const network = options.network ?? 'mainnet'\n const chain = CAIP2[network]\n const fetchFn: HistoryFetch = options.fetch ?? ((globalThis as { fetch?: HistoryFetch }).fetch as HistoryFetch)\n if (typeof fetchFn !== 'function') throw new Error('@anywalletkit/wallet-ton: no global fetch; pass `fetch` in the options')\n const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS\n const tonapiUrl = options.tonapiUrl === null ? undefined : (options.tonapiUrl ?? (network === 'testnet' ? 'https://testnet.tonapi.io' : 'https://tonapi.io')).replace(/\\/+$/, '')\n const toncenterUrl = options.toncenterUrl === null ? undefined : (options.toncenterUrl ?? (network === 'testnet' ? 'https://testnet.toncenter.com' : 'https://toncenter.com')).replace(/\\/+$/, '')\n if (!tonapiUrl && !toncenterUrl) throw new Error('@anywalletkit/wallet-ton: createTonHistory needs tonapi or toncenter')\n const tonapiBucket = new TokenBucket(options.rateLimit ?? (options.apiKey ? 10 : 1))\n const toncenterBucket = new TokenBucket(options.toncenterApiKey ? 10 : 1)\n\n async function getJson(backend: TonHistoryBackend, url: string, headers: Record<string, string>): Promise<{ status: number; body: unknown }> {\n await (backend === 'tonapi' ? tonapiBucket : toncenterBucket).acquire()\n let res: Awaited<ReturnType<HistoryFetch>>\n try {\n const signal = timeoutSignal(timeoutMs)\n res = await fetchFn(url, { headers: { accept: 'application/json', ...headers }, ...(signal ? { signal } : {}) })\n } catch (e) {\n throw new Error(`${backend}: ${e instanceof Error ? e.message : String(e)}`)\n }\n let body: unknown\n try {\n body = await res.json()\n } catch {\n body = undefined\n }\n return { status: res.status, body }\n }\n\n const tonapiHeaders = () => (options.apiKey ? { authorization: `Bearer ${options.apiKey}` } : {})\n const toncenterHeaders = () => (options.toncenterApiKey ? { 'x-api-key': options.toncenterApiKey } : {})\n\n const fail = (backend: TonHistoryBackend, r: { status: number; body: unknown }): never => {\n const msg = typeof r.body === 'object' && r.body !== null && typeof (r.body as { error?: unknown }).error === 'string' ? (r.body as { error: string }).error : ''\n throw new Error(`${backend}: HTTP ${r.status}${msg ? ` ${msg}` : ''}`)\n }\n\n async function tonapiEventFull(eventId: string): Promise<TonapiEvent | undefined> {\n const r = await getJson('tonapi', `${tonapiUrl}/v2/events/${eventId}`, tonapiHeaders())\n if (r.status === 404) return undefined\n if (r.status !== 200) fail('tonapi', r)\n return r.body as TonapiEvent\n }\n\n async function finishTonapi(address: string, own: string, event: TonapiEvent): Promise<TonChainTx> {\n const probe = mapActions(event.actions ?? [])\n let flow: TonapiEvent | undefined\n if (probe.needsValueFlow) {\n try {\n flow = await tonapiEventFull(event.event_id)\n } catch {\n flow = undefined // best effort: the row still carries the call\n }\n }\n return mapTonapiEvent(chain, address, own, event, flow)\n }\n\n async function tonapiPage(address: string, own: string, limit: number, before?: string): Promise<TonHistoryPage> {\n if (!tonapiUrl) throw new Error('tonapi: disabled')\n const q = `limit=${limit}${before ? `&before_lt=${before}` : ''}`\n const r = await getJson('tonapi', `${tonapiUrl}/v2/accounts/${encodeURIComponent(address)}/events?${q}`, tonapiHeaders())\n if (r.status !== 200) fail('tonapi', r)\n const body = r.body as { events?: TonapiEvent[]; next_from?: number | string } | undefined\n const events = body?.events ?? []\n const items: TonChainTx[] = []\n for (const e of events) items.push(await finishTonapi(address, own, e))\n const page: TonHistoryPage = { items, backend: 'tonapi' }\n if (events.length >= limit) {\n const last = events[events.length - 1]!\n page.cursor = encodeCursor({ v: 1, b: 'tonapi', lt: String(body?.next_from ?? last.lt) })\n }\n return page\n }\n\n async function toncenterPage(address: string, limit: number, before?: string): Promise<TonHistoryPage> {\n if (!toncenterUrl) throw new Error('toncenter: disabled')\n const endLt = before ? (BigInt(before) - 1n).toString() : undefined\n const q = `account=${encodeURIComponent(address)}&limit=${limit}&sort=desc${endLt ? `&end_lt=${endLt}` : ''}`\n const r = await getJson('toncenter', `${toncenterUrl}/api/v3/transactions?${q}`, toncenterHeaders())\n if (r.status !== 200) fail('toncenter', r)\n const rows = (r.body as { transactions?: V3Transaction[] } | undefined)?.transactions ?? []\n const items = rows.map((row) => mapToncenterTransaction(chain, address, row))\n const page: TonHistoryPage = { items, backend: 'toncenter' }\n if (rows.length >= limit) page.cursor = encodeCursor({ v: 1, b: 'toncenter', lt: rows[rows.length - 1]!.lt })\n return page\n }\n\n const backends: TonHistoryBackend[] = [...(tonapiUrl ? ['tonapi' as const] : []), ...(toncenterUrl ? ['toncenter' as const] : [])]\n\n return {\n chain,\n\n async listActivity(address: string, query: HistoryQuery = {}): Promise<TonHistoryPage> {\n const limit = Math.min(MAX_LIMIT, Math.max(1, Math.floor(query.limit ?? DEFAULT_LIMIT)))\n const cursor = query.cursor ? decodeCursor(query.cursor) : undefined\n const own = rawTonAddress(address)\n const ordered = cursor ? [...backends].sort((a, b) => (a === cursor.b ? -1 : b === cursor.b ? 1 : 0)) : backends\n const attempts: string[] = []\n for (const b of ordered) {\n try {\n let page = b === 'tonapi' ? await tonapiPage(address, own, limit, cursor?.lt) : await toncenterPage(address, limit, cursor?.lt)\n if (query.since !== undefined) {\n const since = query.since\n if (page.items.some((t) => t.time < since)) delete page.cursor\n page = { ...page, items: page.items.filter((t) => t.time >= since) }\n }\n return page\n } catch (e) {\n attempts.push(e instanceof Error ? e.message : String(e))\n }\n }\n throw new HistoryUnavailableError(chain, attempts[attempts.length - 1] ?? 'no backend configured', attempts)\n },\n\n async getTransaction(hash: string, address: string): Promise<TonChainTx | undefined> {\n const own = rawTonAddress(address)\n const attempts: string[] = []\n for (const b of backends) {\n try {\n if (b === 'tonapi') {\n const r = await getJson('tonapi', `${tonapiUrl}/v2/accounts/${encodeURIComponent(address)}/events/${encodeURIComponent(hash)}`, tonapiHeaders())\n if (r.status === 404) return undefined\n if (r.status !== 200) fail('tonapi', r)\n return await finishTonapi(address, own, r.body as TonapiEvent)\n }\n const r = await getJson('toncenter', `${toncenterUrl}/api/v3/transactions?hash=${encodeURIComponent(hash)}`, toncenterHeaders())\n if (r.status !== 200) fail('toncenter', r)\n const rows = (r.body as { transactions?: V3Transaction[] } | undefined)?.transactions ?? []\n const row = rows.find((x) => x.account.toLowerCase() === own) ?? rows[0]\n return row ? mapToncenterTransaction(chain, address, row) : undefined\n } catch (e) {\n attempts.push(e instanceof Error ? e.message : String(e))\n }\n }\n throw new HistoryUnavailableError(chain, attempts[attempts.length - 1] ?? 'no backend configured', attempts)\n },\n\n explorerTxUrl(hash: string): string {\n return tonExplorerTxUrl(hash, network)\n },\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACMA,oBAAuB;AAMhB,SAAS,sBAA4B;AAC1C,QAAM,IAAI;AACV,IAAE,WAAW;AACf;AAEA,oBAAoB;;;ACqKb,IAAM,QAA+C,EAAE,SAAS,YAAY,SAAS,SAAS;;;ACtLrG,kBAA4B;AAOrB,IAAM,yBAAN,cAAqC,wBAAY;AAAA,EAC7C;AAAA,EACT,YAAY,MAAc,SAAiB;AACzC,UAAM,OAAO;AACb,SAAK,OAAO;AACZ,SAAK,OAAO;AAAA,EACd;AACF;AAGO,IAAM,kBAAN,cAA8B,MAAM;AAAA,EAChC;AAAA,EACA;A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,IAAI,CAAC,IAAI,cAAc,CAAC;AAC/I,gBAAIA,GAAE,WAAW,IAAK,QAAO;AAC7B,gBAAIA,GAAE,WAAW,IAAK,MAAK,UAAUA,EAAC;AACtC,mBAAO,MAAM,aAAa,SAAS,KAAKA,GAAE,IAAmB;AAAA,UAC/D;AACA,gBAAM,IAAI,MAAM,QAAQ,aAAa,GAAG,YAAY,6BAA6B,mBAAmB,IAAI,CAAC,IAAI,iBAAiB,CAAC;AAC/H,cAAI,EAAE,WAAW,IAAK,MAAK,aAAa,CAAC;AACzC,gBAAM,OAAQ,EAAE,MAAyD,gBAAgB,CAAC;AAC1F,gBAAM,MAAM,KAAK,KAAK,CAAC,MAAM,EAAE,QAAQ,YAAY,MAAM,GAAG,KAAK,KAAK,CAAC;AACvE,iBAAO,MAAM,wBAAwB,OAAO,SAAS,GAAG,IAAI;AAAA,QAC9D,SAAS,GAAG;AACV,mBAAS,KAAK,aAAa,QAAQ,EAAE,UAAU,OAAO,CAAC,CAAC;AAAA,QAC1D;AAAA,MACF;AACA,YAAM,IAAI,wBAAwB,OAAO,SAAS,SAAS,SAAS,CAAC,KAAK,yBAAyB,QAAQ;AAAA,IAC7G;AAAA,IAEA,cAAc,MAAsB;AAClC,aAAO,iBAAiB,MAAM,OAAO;AAAA,IACvC;AAAA,EACF;AACF;;;AXxmBA,oBAAoB;","names":["import_core","import_buffer","import_core","DEFAULT_TIMEOUT_MS","big","verdict","import_buffer","import_core","import_core","external","import_core","JETTON_TRANSFER_OP","import_core","import_core","external","full","import_core","import_buffer","DEFAULT_TIMEOUT_MS","big","r"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/buffer-global.ts","../src/types.ts","../src/errors.ts","../src/toncenter.ts","../src/emulation.ts","../src/wallet-v5r1.ts","../src/describe.ts","../src/read-only-account.ts","../src/account.ts","../src/manager.ts","../src/history.ts"],"sourcesContent":["import { installBufferGlobal } from './buffer-global.js'\ninstallBufferGlobal()\nexport { installBufferGlobal }\nexport * from './types.js'\nexport * from './errors.js'\nexport { createTonClient } from './client.js'\nexport { TonCenter, createTonRpc, tonCenterEndpoint, emulateExternal, parseEmulation, type TonAccountState, type TonAccountStatus, type GetMethodResult, type EmulationVerdict } from './toncenter.js'\nexport { emulateViaTonapi, parseTonapiConsequences, parseTonapiTrace, parseTonapiRisk, runEmulation, resolveEmulate, DEFAULT_TONAPI, type EmulationOutcome, type EmulationSource, type EmulateOptions } from './emulation.js'\nexport {\n V5R1_CODE_HEX, V5R1_OP, MAINNET_GLOBAL_ID, TESTNET_GLOBAL_ID, DEFAULT_SEND_MODE, MAX_ACTIONS,\n v5r1Code, v5r1WalletId, v5r1StateInit, v5r1Address, v5r1SigningMessage, v5r1PackSigned, v5r1PackUnsigned, v5r1ExternalMessage, parseV5R1Body,\n type V5R1Message, type V5R1SigningParams, type V5R1WalletIdParts, type ParsedV5R1Body,\n} from './wallet-v5r1.js'\nexport {\n describeTransaction, describeMessageRelaxed, decodeBody, commentCell, JETTON_TRANSFER_OP,\n type TonDescription, type TonDescribedMessage, type TonDescribedKind, type TonJettonDetails, type TonWarning, type TonWarningCode, type DecodedBody,\n} from './describe.js'\nexport { WalletAccountReadOnlyTon, SEND_MODE } from './read-only-account.js'\nexport { WalletAccountTon } from './account.js'\nexport { WalletManagerTon, TON_BASE_PATH, TON_MNEMONIC_PATH } from './manager.js'\nexport {\n createTonHistory, mapTonapiEvent, mapToncenterTransaction, mapActions as mapTonapiActions, valueFlowTransfers, rawTonAddress, tonExplorerTxUrl, HistoryUnavailableError,\n encodeCursor as encodeHistoryCursor, decodeCursor as decodeHistoryCursor,\n type TonHistoryOptions, type TonHistorySource, type TonHistoryPage, type TonChainTx, type TonHistoryRaw, type TonHistoryBackend, type TonHistoryCursor, type TonapiEvent, type TonapiAction, type V3Transaction, type HistoryFetch,\n} from './history.js'\nexport { WalletManagerTon as default } from './manager.js'\n","// @ton/core and @ton/crypto read the GLOBAL `Buffer` (Node convention). Browsers\n// and Hermes have none, so the package installs the `buffer` polyfill once, at\n// import time, only when it is missing. Node and React Native entries that\n// already set it are untouched. Called as a function from index.ts (not a bare\n// import): bundlers drop bare imports of modules they consider side-effect\n// free, and this one was silently dropped from dist before.\nimport { Buffer } from 'buffer'\n\n/**\n * Set `globalThis.Buffer` to the `buffer` polyfill when the runtime has none (Hermes, browsers).\n * Runs on import.\n */\nexport function installBufferGlobal(): void {\n const g = globalThis as { Buffer?: unknown }\n g.Buffer ??= Buffer\n}\n\ninstallBufferGlobal()\n","import type { Cell, StateInit } from '@ton/core'\n\n/** A toncenter v2 JSON-RPC endpoint (api keys there are meant for client-side wallets). */\nexport interface TonEndpoint { url: string; secretKey?: string }\n\n/** Anything that can answer a toncenter v2 JSON-RPC call (an endpoint wrapper, a test double, a proxy). */\nexport interface TonRpc {\n call<T = unknown>(method: string, params: Record<string, unknown>): Promise<T>\n}\n\n/** A toncenter endpoint (URL and optional key) or a ready `TonRpc`. */\nexport type TonProvider = TonEndpoint | TonRpc\n\n/**\n * Options for a TON wallet manager or account: toncenter endpoints, network, fee caps and emulation\n * before signing.\n */\nexport interface TonConfig {\n /** toncenter endpoint(s) or `TonRpc`(s). A list fails over in order. Omit for an offline (sign-only) wallet. */\n tonClient?: TonProvider | TonProvider[]\n /** Alias of `tonClient`. */\n provider?: TonProvider | TonProvider[]\n /** Extra rounds across the endpoint list after the first full pass (default 3). */\n retries?: number\n /** Per-request timeout in ms (default 15 000). */\n timeoutMs?: number\n /** Injectable fetch (tests, custom agents). Defaults to globalThis.fetch. */\n fetch?: typeof fetch\n /** Max fee (nanotons) for `transfer`. */\n transferMaxFee?: bigint | number\n /** Max fee (nanotons) for `sendTransaction` / `signTransaction`. */\n transactionMaxFee?: bigint | number\n /** toncenter v3 base used for receipts (default https://toncenter.com/api/v3). */\n indexerUrl?: string\n /** tonapi base used for fee rates and (by default) emulation (default https://tonapi.io/v2). */\n tonApiUrl?: string\n /** tonapi bearer key (sent as `Authorization: Bearer …`); also sent as X-API-Key to a toncenter-v3 emulator. */\n tonApiKey?: string\n /**\n * Preflight emulation of every send (zero-signed external). Default\n * `{kind: 'tonapi'}`: `POST {tonApiUrl}/wallet/emulate` (verdict + `risk`),\n * falling back to `/traces/emulate`. `{kind: 'toncenter-v3', url}` posts to a\n * toncenter `emulateTrace` endpoint instead. `false` = `estimateFee` only.\n * A non-zero compute exit, an aborted transaction, a failed action phase or a\n * failed FIRST-HOP internal message throws `SimulationError` before signing.\n */\n emulate?: TonEmulateConfig\n /** @deprecated Use `emulate: {kind: 'toncenter-v3', url}`. Still honoured when `emulate` is unset. */\n emulateUrl?: string\n /**\n * Allow a body whose emulated `risk.transfer_all_remaining_balance` is true\n * (send mode 128 / CARRY_ALL_BALANCE). Refused by default — nothing this\n * wallet builds does that, so it only ever comes from a foreign `bodyBoc`.\n */\n allowDrainingTransactions?: boolean\n /** Run the preflight (estimateFee + emulation when configured) before signing. Default true. */\n simulate?: boolean\n /** Seconds a signed external stays valid (default 60, max 600). */\n validUntilSeconds?: number\n /** Nanotons attached to a jetton transfer on top of `forwardTonAmount` (default 0.05 TON). */\n jettonAttachedValue?: bigint | number | string\n /**\n * 'mainnet' (ton:-239, default) or 'testnet' (ton:-3). Sets the CAIP-2 id, the address flags and the\n * wallet_id network (-239 / -3), so a testnet wallet has its own address and its signed messages are\n * not valid on mainnet (as in Tonkeeper and @ton/ton).\n */\n network?: 'mainnet' | 'testnet'\n /**\n * V5R1 wallet_id parts. Defaults (network id from `network`, subwallet 0) give the\n * addresses Tonkeeper and Tonhub derive for a key; change the subwallet only to\n * reach a wallet that was created with a different one. A networkGlobalId that\n * contradicts `network` is refused.\n */\n walletId?: { networkGlobalId?: number; subwalletNumber?: number }\n}\n\n/** One internal message. `value` in nanotons. `body`: text comment or a Cell; `bodyBoc`: the same as base64 BoC. */\nexport interface TonTransaction {\n to: string\n value: bigint | number | string\n /** Defaults to the flag in a friendly address (EQ… bounceable, UQ… not); raw addresses default to bounceable. */\n bounceable?: boolean\n body?: string | Cell\n /** Prebuilt message body as base64 BoC (e.g. an Omniston escrow payload). Ignored when `body` is set. */\n bodyBoc?: string\n /** StateInit to attach (deploys the destination): `{code, data}`, a StateInit cell, or its base64 BoC. */\n stateInit?: StateInit | Cell | string\n /** Send mode for this message (default PAY_GAS_SEPARATELY; IGNORE_ERRORS is always OR-ed in for externals). */\n sendMode?: number\n}\n\n/**\n * What `sendTransaction` / `signTransaction` accept: one message, several\n * messages in ONE external (up to 255 — swaps need it), or an already signed\n * V5R1 external-message body Cell.\n */\nexport type TonSendable = TonTransaction | TonTransaction[] | Cell\n\n/** A native TON or jetton transfer. Amount in nanotons or the jetton's base units. */\nexport interface TonTransferOptions {\n /** Jetton master address. Omit for native TON. */\n token?: string\n /** Wallet address that receives (for a jetton, its owner, not its jetton wallet). */\n recipient: string\n amount: bigint | number | string\n /** Jetton only: nanotons forwarded to the recipient with the transfer notification (default 1). */\n forwardTonAmount?: bigint | number | string\n /** Jetton only: forward payload — a text comment or a Cell (DEX / escrow payloads). */\n forwardPayload?: Cell | string\n /**\n * Text memo (a deposit memo, an exchange tag). Jetton: sent as the forward-payload comment (TEP-74);\n * native TON: the message comment. Cannot be combined with `forwardPayload`.\n */\n memo?: string\n /** Jetton only: custom payload cell (rarely needed; e.g. mintless jettons). */\n customPayload?: Cell\n /** Jetton only: where excess TON returns (default: this wallet). */\n responseDestination?: string\n /** Jetton only: query id (default random). */\n queryId?: bigint | number\n /** Jetton only: nanotons attached to the jetton-wallet call (default config.jettonAttachedValue + forwardTonAmount). */\n attachedValue?: bigint | number | string\n}\n\n/** toncenter `estimateFee` source fees, nanotons. */\nexport interface TonFees {\n inFwdFee: bigint\n storageFee: bigint\n gasFee: bigint\n fwdFee: bigint\n /** Sum of the four. */\n total: bigint\n}\n\n/**\n * Where to emulate a transaction before signing: tonapi, a toncenter v3 endpoint, or `false` for a\n * fee estimate only.\n */\nexport type TonEmulateConfig =\n | { kind: 'tonapi'; url?: string }\n | { kind: 'toncenter-v3'; url: string }\n | false\n\n/** What a message would move out of the wallet, per tonapi's `risk`. */\nexport interface TonRisk {\n /** Nanotons leaving the wallet (value + fees the emulator attributes). */\n ton: bigint\n jettons: Array<{ address: string; walletAddress: string; amount: bigint; symbol?: string; decimals?: number }>\n /** Send mode 128: the whole remaining balance goes with the message. */\n transferAllRemainingBalance: boolean\n}\n\n/**\n * Which service produced a simulation; `estimate-only` means fees were estimated without emulation.\n */\nexport type TonSimulationSource = 'tonapi' | 'toncenter-v3' | 'estimate-only'\n\n/**\n * Outcome of a simulation: the fees and, when emulated, whether the wallet transaction and its\n * actions succeeded.\n */\nexport type TonSimulation =\n | { ok: true; fees: TonFees; emulated: boolean; source: TonSimulationSource; exitCode?: number; actionSuccess?: boolean; risk?: TonRisk; warnings: string[] }\n | { ok: false; fees?: TonFees; emulated: true; source: Exclude<TonSimulationSource, 'estimate-only'>; reason: string; exitCode?: number; aborted?: boolean; risk?: TonRisk; warnings: string[] }\n\n/** Outcome of a sent wallet transaction, found by the body hash `sendTransaction` returned. */\nexport interface TonReceipt {\n /** The body hash that was returned by sendTransaction. */\n hash: string\n /** 1 when the wallet transaction completed without abort, 0 otherwise. */\n status: 0 | 1\n /** Logical time of the account transaction. */\n blockNumber: bigint\n /** Account transaction hash (base64). */\n transactionHash: string\n /** Fees of the account transaction, in nanotons. */\n totalFees: bigint\n /** The raw @ton/core Transaction. */\n raw: unknown\n}\n\n/** CAIP-2 ids of TON mainnet and testnet. */\nexport const CAIP2: Record<'mainnet' | 'testnet', string> = { mainnet: 'ton:-239', testnet: 'ton:-3' }\n","import { SignerError } from '@anywalletkit/core'\n\n/**\n * Refused before signing: the message would almost certainly misbehave or\n * strand funds (zero value, wrong network flag, exotic workchain, a\n * `valid_until` further away than the wallet contract tolerates…).\n */\nexport class UnsafeTransactionError extends SignerError {\n readonly code: string\n constructor(code: string, message: string) {\n super(message)\n this.name = 'UnsafeTransactionError'\n this.code = code\n }\n}\n\n/** Emulation of the external message failed (non-zero compute exit, aborted, action phase failed); nothing was signed or sent. */\nexport class SimulationError extends Error {\n readonly exitCode: number | undefined\n readonly aborted: boolean\n constructor(reason: string, details: { exitCode?: number; aborted?: boolean } = {}) {\n super(`Transaction simulation failed: ${reason}`)\n this.name = 'SimulationError'\n this.exitCode = details.exitCode\n this.aborted = details.aborted ?? false\n }\n}\n","/**\n * toncenter v2 JSON-RPC client — the handful of calls a wallet needs, with\n * failover across endpoints, timeouts, api keys and response-shape checks.\n * No axios, no dataloader, no caches: one `fetch` per call.\n */\nimport { NetworkError } from '@anywalletkit/core'\nimport { Buffer } from 'buffer'\nimport { Address, Cell, TupleReader, loadTransaction, type StateInit, type Transaction, type TupleItem } from '@ton/core'\nimport type { TonConfig, TonEndpoint, TonFees, TonProvider, TonRpc } from './types.js'\n\nconst DEFAULT_TIMEOUT_MS = 15_000\n\nconst isRpc = (p: TonProvider): p is TonRpc => typeof (p as TonRpc).call === 'function'\n\n/** JSON-RPC over one toncenter v2 endpoint. */\nexport function tonCenterEndpoint(endpoint: TonEndpoint, opts: { fetch?: typeof fetch; timeoutMs?: number } = {}): TonRpc {\n const url = endpoint.url\n const doFetch = opts.fetch ?? globalThis.fetch\n if (typeof doFetch !== 'function') throw new NetworkError('No fetch available; pass config.fetch', { provider: url })\n const timeoutMs = opts.timeoutMs ?? DEFAULT_TIMEOUT_MS\n return {\n async call<T>(method: string, params: Record<string, unknown>): Promise<T> {\n let res: Response\n try {\n res = await doFetch(url, {\n method: 'POST',\n headers: {\n 'content-type': 'application/json',\n accept: 'application/json',\n ...(endpoint.secretKey ? { 'X-API-Key': endpoint.secretKey } : {}),\n },\n body: JSON.stringify({ id: '1', jsonrpc: '2.0', method, params }),\n signal: AbortSignal.timeout(timeoutMs),\n })\n } catch (e) {\n throw new NetworkError(`${method}: ${e instanceof Error ? e.message : String(e)}`, { provider: url, cause: e })\n }\n let json: { ok?: boolean; result?: T; error?: unknown; code?: unknown }\n try { json = (await res.json()) as typeof json } catch (e) {\n throw new NetworkError(`${method}: HTTP ${res.status}, non-JSON body`, { provider: url, cause: e })\n }\n if (!res.ok || json.ok !== true) {\n const detail = typeof json.error === 'string' ? json.error : JSON.stringify(json.error ?? json)\n throw new NetworkError(`${method}: ${detail} (HTTP ${res.status})`, { provider: url })\n }\n return json.result as T\n },\n }\n}\n\n/** One RPC, or a failover RPC walking the configured list (`retries` extra rounds after the first full pass). */\nexport function createTonRpc(config: TonConfig): TonRpc | undefined {\n const target = config.tonClient ?? config.provider\n if (target === undefined) return undefined\n const list = (Array.isArray(target) ? target : [target]).map((p) =>\n isRpc(p) ? p : tonCenterEndpoint(p, { ...(config.fetch ? { fetch: config.fetch } : {}), ...(config.timeoutMs !== undefined ? { timeoutMs: config.timeoutMs } : {}) }),\n )\n if (list.length === 0) throw new Error(\"The 'tonClient' option cannot be set to an empty list.\")\n if (list.length === 1) return list[0]!\n const attempts = list.length + (config.retries ?? 3)\n return {\n async call<T>(method: string, params: Record<string, unknown>): Promise<T> {\n let lastError: unknown\n for (let i = 0; i < attempts; i++) {\n try { return await list[i % list.length]!.call<T>(method, params) } catch (e) { lastError = e }\n }\n throw new NetworkError(`All TON endpoints failed for ${method}`, { cause: lastError })\n },\n }\n}\n\n// ── Stack (de)serialization, toncenter v2 wire format ───────────────────────\n\nfunction serializeStackItem(item: TupleItem): [string, unknown] {\n switch (item.type) {\n case 'int': return ['num', item.value.toString()]\n case 'cell': return ['tvm.Cell', item.cell.toBoc().toString('base64')]\n case 'slice': return ['tvm.Slice', item.cell.toBoc().toString('base64')]\n case 'builder': return ['tvm.Builder', item.cell.toBoc().toString('base64')]\n default: throw new Error(`Unsupported stack item type: ${item.type}`)\n }\n}\n\nconst hexBigInt = (s: string): bigint => (s.startsWith('-') ? -BigInt(s.slice(1)) : BigInt(s))\nconst cellFromBase64 = (b64: string): Cell => Cell.fromBoc(Buffer.from(b64, 'base64'))[0]!\n\nfunction parseStackEntry(x: unknown): TupleItem {\n const o = x as Record<string, unknown>\n switch (o['@type']) {\n case 'tvm.list':\n case 'tvm.tuple': return { type: 'tuple', items: (o.elements as unknown[]).map(parseStackEntry) }\n case 'tvm.cell': return { type: 'cell', cell: cellFromBase64(o.bytes as string) }\n case 'tvm.stackEntryCell': return parseStackEntry(o.cell)\n case 'tvm.stackEntryTuple': return parseStackEntry(o.tuple)\n case 'tvm.stackEntryNumber': return parseStackEntry(o.number)\n case 'tvm.numberDecimal': return { type: 'int', value: BigInt(o.number as string) }\n default: throw new NetworkError(`Malformed stack entry: ${JSON.stringify(x)}`)\n }\n}\n\nfunction parseStackItem(s: unknown): TupleItem {\n if (!Array.isArray(s) || s.length < 2) throw new NetworkError(`Malformed stack item: ${JSON.stringify(s)}`)\n const [kind, value] = s as [string, unknown]\n switch (kind) {\n case 'num': return { type: 'int', value: hexBigInt(value as string) }\n case 'null': return { type: 'null' }\n case 'cell': return { type: 'cell', cell: cellFromBase64((value as { bytes: string }).bytes) }\n case 'slice': return { type: 'slice', cell: cellFromBase64((value as { bytes: string }).bytes) }\n case 'builder': return { type: 'builder', cell: cellFromBase64((value as { bytes: string }).bytes) }\n case 'tuple':\n case 'list': return { type: 'tuple', items: ((value as { elements: unknown[] }).elements ?? []).map(parseStackEntry) }\n default: throw new NetworkError(`Malformed stack item kind: ${kind}`)\n }\n}\n\n// ── Typed API ───────────────────────────────────────────────────────────────\n\n/** State of a TON account on chain. */\nexport type TonAccountStatus = 'active' | 'uninitialized' | 'frozen' | 'nonexist'\n\n/** Balance, status, code and data of an account. */\nexport interface TonAccountState {\n balance: bigint\n state: TonAccountStatus\n code: Cell | null\n data: Cell | null\n lastTransaction: { lt: string; hash: string } | null\n}\n\n/** Result of a contract get-method call. */\nexport interface GetMethodResult { exitCode: number; gasUsed: number; stack: TupleReader }\n\nconst need = <T>(cond: unknown, what: string, value: T): T => {\n if (!cond) throw new NetworkError(`Malformed toncenter response: ${what}`)\n return value\n}\n\n/** The toncenter calls a wallet uses, with parsed results. */\nexport class TonCenter {\n constructor(readonly rpc: TonRpc) {}\n\n /** Balance, status, code and data of an account. */\n async getAddressInformation(address: Address): Promise<TonAccountState> {\n const r = await this.rpc.call<Record<string, unknown>>('getAddressInformation', { address: address.toString() })\n need(r && typeof r === 'object' && typeof r.balance === 'string', 'getAddressInformation', r)\n const state = r.state as string\n const last = r.last_transaction_id as { lt?: string; hash?: string } | undefined\n return {\n balance: BigInt(r.balance as string),\n state: (['active', 'uninitialized', 'frozen', 'nonexist'] as const).includes(state as TonAccountStatus) ? (state as TonAccountStatus) : 'nonexist',\n code: typeof r.code === 'string' && r.code !== '' ? cellFromBase64(r.code) : null,\n data: typeof r.data === 'string' && r.data !== '' ? cellFromBase64(r.data) : null,\n lastTransaction: last && last.lt && last.lt !== '0' ? { lt: last.lt, hash: last.hash ?? '' } : null,\n }\n }\n\n /** Call a contract get-method; the result carries the exit code. */\n async runGetMethod(address: Address, method: string, stack: TupleItem[] = []): Promise<GetMethodResult> {\n const r = await this.rpc.call<Record<string, unknown>>('runGetMethod', {\n address: address.toString(), method, stack: stack.map(serializeStackItem),\n })\n need(r && typeof r === 'object' && typeof r.exit_code === 'number' && Array.isArray(r.stack), 'runGetMethod', r)\n return { exitCode: r.exit_code as number, gasUsed: Number(r.gas_used ?? 0), stack: new TupleReader((r.stack as unknown[]).map(parseStackItem)) }\n }\n\n /** Like runGetMethod but throws on a non-zero exit code. */\n async runGetMethodOk(address: Address, method: string, stack: TupleItem[] = []): Promise<GetMethodResult> {\n const r = await this.runGetMethod(address, method, stack)\n if (r.exitCode !== 0) throw new NetworkError(`Get method ${method} failed with exit_code: ${r.exitCode}`)\n return r\n }\n\n /** Broadcast a signed external message. */\n async sendBoc(message: Cell): Promise<void> {\n await this.rpc.call('sendBoc', { boc: message.toBoc().toString('base64') })\n }\n\n /** Broadcast and return the external-message hash (base64) toncenter reports. */\n async sendBocReturnHash(message: Cell): Promise<string> {\n const r = await this.rpc.call<{ hash?: string }>('sendBocReturnHash', { boc: message.toBoc().toString('base64') })\n return need(r && typeof r.hash === 'string', 'sendBocReturnHash', r.hash as string)\n }\n\n async getTransactions(address: Address, opts: { limit: number; lt?: string; hash?: string; archival?: boolean }): Promise<Transaction[]> {\n const params: Record<string, unknown> = { address: address.toString(), limit: opts.limit }\n if (opts.lt) params.lt = opts.lt\n if (opts.hash) params.hash = Buffer.from(opts.hash, 'base64').toString('hex')\n if (opts.archival) params.archival = true\n const r = await this.rpc.call<unknown>('getTransactions', params)\n need(Array.isArray(r), 'getTransactions', r)\n return (r as Array<{ data?: string }>).map((t) => {\n need(typeof t.data === 'string', 'getTransactions[].data', t)\n return loadTransaction(cellFromBase64(t.data as string).beginParse())\n })\n }\n\n async estimateFee(address: Address, args: { body: Cell; init?: StateInit; ignoreSignature?: boolean }): Promise<TonFees> {\n const r = await this.rpc.call<{ source_fees?: Record<string, unknown> }>('estimateFee', {\n address: address.toString(),\n body: args.body.toBoc().toString('base64'),\n init_code: args.init ? args.init.code!.toBoc().toString('base64') : '',\n init_data: args.init ? args.init.data!.toBoc().toString('base64') : '',\n ignore_chksig: args.ignoreSignature ?? true,\n })\n const f = r?.source_fees\n need(f && ['in_fwd_fee', 'storage_fee', 'gas_fee', 'fwd_fee'].every((k) => typeof f[k] === 'number' || typeof f[k] === 'string'), 'estimateFee', r)\n const fees = {\n inFwdFee: BigInt(f!.in_fwd_fee as number), storageFee: BigInt(f!.storage_fee as number),\n gasFee: BigInt(f!.gas_fee as number), fwdFee: BigInt(f!.fwd_fee as number),\n }\n return { ...fees, total: fees.inFwdFee + fees.storageFee + fees.gasFee + fees.fwdFee }\n }\n}\n\n// ── Emulation (toncenter v3 emulateTrace) ───────────────────────────────────\n\n/**\n * Whether an emulated wallet transaction succeeded: compute exit code, abort flag, action phase.\n */\nexport interface EmulationVerdict {\n ok: boolean\n exitCode?: number\n aborted?: boolean\n actionSuccess?: boolean\n reason?: string\n}\n\n/**\n * Reduce an `emulateTrace` response to a verdict for the ROOT transaction (the\n * wallet's own): compute-phase exit code, aborted flag, action-phase success.\n * Tolerant of the field spellings the v3 API has used (`description.compute_ph`\n * / `compute`, `action.success`); anything unrecognisable is a NetworkError, not\n * a silent pass.\n */\nexport function parseEmulation(json: unknown): EmulationVerdict {\n const j = json as Record<string, unknown> | null\n if (!j || typeof j !== 'object') throw new NetworkError('Malformed emulation response')\n if (typeof j.error === 'string') return { ok: false, reason: j.error }\n const txs = j.transactions as Record<string, Record<string, unknown>> | Array<Record<string, unknown>> | undefined\n const rootHash = (j.trace as { tx_hash?: string } | undefined)?.tx_hash\n let tx: Record<string, unknown> | undefined\n if (Array.isArray(txs)) tx = txs[0]\n else if (txs && typeof txs === 'object') tx = (rootHash && txs[rootHash]) || Object.values(txs)[0]\n if (!tx) {\n if (typeof j.exit_code === 'number') return verdict(j.exit_code, j.aborted === true, undefined)\n throw new NetworkError('Malformed emulation response: no transactions')\n }\n const d = (tx.description as Record<string, unknown> | undefined) ?? tx\n const compute = (d.compute_ph ?? d.compute) as Record<string, unknown> | undefined\n const action = d.action as Record<string, unknown> | undefined\n const exitCode = typeof compute?.exit_code === 'number' ? compute.exit_code : compute?.success === true ? 0 : undefined\n const actionSuccess = typeof action?.success === 'boolean' ? action.success : undefined\n if (exitCode === undefined && d.aborted === undefined && actionSuccess === undefined) throw new NetworkError('Malformed emulation response: no phases')\n return verdict(exitCode, d.aborted === true, actionSuccess)\n}\n\nfunction verdict(exitCode: number | undefined, aborted: boolean, actionSuccess: boolean | undefined): EmulationVerdict {\n const ok = !aborted && (exitCode === undefined || exitCode === 0) && actionSuccess !== false\n const reason = aborted ? 'transaction aborted' : exitCode !== undefined && exitCode !== 0 ? `compute phase exit_code ${exitCode}` : actionSuccess === false ? 'action phase failed' : undefined\n return { ok, ...(exitCode !== undefined ? { exitCode } : {}), aborted, ...(actionSuccess !== undefined ? { actionSuccess } : {}), ...(reason ? { reason } : {}) }\n}\n\n/** POST the external message to a toncenter v3 emulation endpoint and reduce the trace. */\nexport async function emulateExternal(url: string, message: Cell, opts: { fetch?: typeof fetch; timeoutMs?: number; apiKey?: string } = {}): Promise<EmulationVerdict> {\n const doFetch = opts.fetch ?? globalThis.fetch\n let res: Response\n try {\n res = await doFetch(url, {\n method: 'POST',\n headers: { 'content-type': 'application/json', accept: 'application/json', ...(opts.apiKey ? { 'X-API-Key': opts.apiKey } : {}) },\n body: JSON.stringify({ boc: message.toBoc().toString('base64'), ignore_chksig: true, include_code_data: false, with_actions: false }),\n signal: AbortSignal.timeout(opts.timeoutMs ?? DEFAULT_TIMEOUT_MS),\n })\n } catch (e) {\n throw new NetworkError(`emulate: ${e instanceof Error ? e.message : String(e)}`, { provider: url, cause: e })\n }\n let json: unknown\n try { json = await res.json() } catch (e) { throw new NetworkError(`emulate: HTTP ${res.status}, non-JSON body`, { provider: url, cause: e }) }\n if (!res.ok) {\n const err = (json as { error?: unknown; detail?: unknown })\n return { ok: false, reason: `HTTP ${res.status}: ${typeof err.error === 'string' ? err.error : JSON.stringify(err.detail ?? err.error ?? json)}` }\n }\n return parseEmulation(json)\n}\n","/**\n * Preflight emulation of a zero-signed external through tonapi\n * (`POST /v2/wallet/emulate`, fallback `POST /v2/traces/emulate`) or a\n * toncenter v3 `emulateTrace` endpoint. The verdict decides whether the\n * account signs at all; `risk` (tonapi only) summarises what would leave the\n * wallet so a foreign body cannot quietly drain it.\n *\n * tonapi shapes used (OpenAPI v2):\n * MessageConsequences = { trace: Trace, event: AccountEvent, risk: Risk }\n * Trace = { transaction: Transaction, interfaces: string[], children?: Trace[], emulated?: boolean }\n * Transaction.compute_phase = { skipped, skip_reason?, success?, exit_code?, exit_code_description? }\n * Transaction.action_phase = { success, result_code, … }\n * Transaction.{ success, aborted, bounce_phase? }\n * Risk = { transfer_all_remaining_balance, ton, jettons: [{ quantity, wallet_address: { address }, jetton: { address, symbol, decimals } }], nfts }\n */\nimport type { Cell } from '@ton/core'\nimport { NetworkError } from '@anywalletkit/core'\nimport { emulateExternal as emulateToncenter, type EmulationVerdict } from './toncenter.js'\nimport type { TonEmulateConfig, TonRisk } from './types.js'\n\nconst DEFAULT_TIMEOUT_MS = 15_000\n/** Default tonapi root used for emulation. */\nexport const DEFAULT_TONAPI = 'https://tonapi.io/v2'\n\n/** Service an emulation came from. */\nexport type EmulationSource = 'tonapi' | 'toncenter-v3'\n\n/** An emulation verdict with its source and any deeper failures. */\nexport interface EmulationOutcome extends EmulationVerdict {\n source: EmulationSource\n /** Failed/bounced transactions deeper than the first hop — informational. */\n warnings: string[]\n /** tonapi `risk`: what the message would move out of the wallet. */\n risk?: TonRisk\n}\n\ninterface TonapiTx {\n hash?: string\n account?: { address?: string } | string\n success?: boolean\n aborted?: boolean\n compute_phase?: { skipped?: boolean; skip_reason?: string; success?: boolean; exit_code?: number; exit_code_description?: string }\n action_phase?: { success?: boolean; result_code?: number; result_code_description?: string }\n bounce_phase?: string\n}\ninterface TonapiTrace { transaction?: TonapiTx; children?: TonapiTrace[] }\n\nfunction isObject(v: unknown): v is Record<string, unknown> {\n return !!v && typeof v === 'object' && !Array.isArray(v)\n}\n\n/**\n * A plain value transfer to an account that does not exist yet: the chain\n * credits the coins and leaves the account `uninit`; tonapi reports the hop as\n * `success: true, aborted: true, compute skipped (cskip_no_state)` with no\n * bounce phase. That is the normal shape of funding a fresh deposit address\n * (NEAR Intents TON deposits, 2026-10-09) — not a failure. A BOUNCEABLE\n * message to the same account bounces instead (`bounce_phase` set) and stays\n * fatal, since the value comes back minus fees.\n */\nfunction creditedUninit(tx: TonapiTx): boolean {\n const c = tx.compute_phase\n return tx.success === true && c?.skipped === true && c.skip_reason === 'cskip_no_state' && tx.bounce_phase === undefined && (tx.action_phase === undefined || tx.action_phase.success !== false)\n}\n\nfunction txFailure(tx: TonapiTx): string | undefined {\n const c = tx.compute_phase\n if (creditedUninit(tx)) return undefined\n if (tx.aborted === true) return 'aborted'\n if (c && c.skipped !== true && typeof c.exit_code === 'number' && c.exit_code !== 0) return `compute exit_code ${c.exit_code}${c.exit_code_description ? ` (${c.exit_code_description})` : ''}`\n if (c && c.skipped === true && tx.success === false) return `compute skipped${c.skip_reason ? ` (${c.skip_reason})` : ''}`\n if (tx.action_phase && tx.action_phase.success === false) return `action phase failed${typeof tx.action_phase.result_code === 'number' ? ` (code ${tx.action_phase.result_code})` : ''}`\n if (typeof tx.bounce_phase === 'string' && tx.bounce_phase !== 'TrPhaseBounceOk' && tx.success === false) return `bounced (${tx.bounce_phase})`\n if (tx.success === false) return 'failed'\n return undefined\n}\n\nfunction accountOf(tx: TonapiTx): string {\n return typeof tx.account === 'string' ? tx.account : tx.account?.address ?? '?'\n}\n\n/**\n * Reduce a tonapi `Trace` to a verdict. The root (the wallet's own transaction)\n * decides: compute exit ≠ 0, aborted or a failed action phase → not ok. A\n * failing FIRST-HOP child is also fatal: for every message this wallet builds\n * (TON to a contract, jetton transfer to its own jetton wallet) a bounced\n * first hop means the operation did not happen and the value comes back minus\n * fees. Deeper failures (e.g. a jetton notify the recipient's wallet rejects)\n * become warnings — the transfer itself already settled.\n */\nexport function parseTonapiTrace(trace: unknown): Omit<EmulationOutcome, 'source' | 'risk'> {\n if (!isObject(trace) || !isObject(trace.transaction)) throw new NetworkError('Malformed tonapi emulation: no root transaction')\n const root = trace.transaction as TonapiTx\n const compute = root.compute_phase\n const exitCode = compute && compute.skipped !== true && typeof compute.exit_code === 'number' ? compute.exit_code : compute?.success === true ? 0 : undefined\n const actionSuccess = typeof root.action_phase?.success === 'boolean' ? root.action_phase.success : undefined\n if (exitCode === undefined && actionSuccess === undefined && typeof root.success !== 'boolean' && typeof root.aborted !== 'boolean') {\n throw new NetworkError('Malformed tonapi emulation: root transaction has no phases')\n }\n const aborted = root.aborted === true\n const rootFailure = txFailure(root)\n const warnings: string[] = []\n let firstHopFailure: string | undefined\n const walk = (t: TonapiTrace, depth: number) => {\n for (const child of t.children ?? []) {\n const tx = child.transaction\n if (tx) {\n const f = txFailure(tx)\n if (f) {\n const line = `${accountOf(tx)}: ${f}`\n if (depth === 1) firstHopFailure ??= line\n else warnings.push(line)\n }\n }\n walk(child, depth + 1)\n }\n }\n walk(trace as TonapiTrace, 1)\n const reason = rootFailure ? (aborted ? 'transaction aborted' : rootFailure) : firstHopFailure ? `internal message failed — ${firstHopFailure}` : undefined\n return {\n ok: reason === undefined,\n ...(exitCode !== undefined ? { exitCode } : {}),\n aborted,\n ...(actionSuccess !== undefined ? { actionSuccess } : {}),\n ...(reason ? { reason } : {}),\n warnings,\n }\n}\n\n/** tonapi `Risk` → nanotons / jetton base units as bigints. Malformed → NetworkError. */\nexport function parseTonapiRisk(risk: unknown): TonRisk {\n if (!isObject(risk)) throw new NetworkError('Malformed tonapi emulation: no risk')\n const big = (v: unknown): bigint => {\n if (typeof v === 'bigint') return v\n if (typeof v === 'number' && Number.isFinite(v)) return BigInt(Math.trunc(v))\n if (typeof v === 'string' && /^-?\\d+$/.test(v)) return BigInt(v)\n throw new NetworkError('Malformed tonapi emulation: risk amount')\n }\n const jettons = Array.isArray(risk.jettons) ? risk.jettons : []\n return {\n ton: big(risk.ton ?? 0),\n transferAllRemainingBalance: risk.transfer_all_remaining_balance === true,\n jettons: jettons.map((j) => {\n if (!isObject(j)) throw new NetworkError('Malformed tonapi emulation: risk jetton')\n const jetton = isObject(j.jetton) ? j.jetton : {}\n const wallet = isObject(j.wallet_address) ? j.wallet_address : {}\n return {\n amount: big(j.quantity ?? 0),\n address: typeof jetton.address === 'string' ? jetton.address : '',\n walletAddress: typeof wallet.address === 'string' ? wallet.address : '',\n ...(typeof jetton.symbol === 'string' ? { symbol: jetton.symbol } : {}),\n ...(typeof jetton.decimals === 'number' ? { decimals: jetton.decimals } : {}),\n }\n }),\n }\n}\n\n/** tonapi `MessageConsequences` (wallet/emulate) → outcome with risk. */\nexport function parseTonapiConsequences(json: unknown): EmulationOutcome {\n if (!isObject(json)) throw new NetworkError('Malformed tonapi emulation response')\n if (typeof json.error === 'string') return { ok: false, reason: json.error, aborted: false, warnings: [], source: 'tonapi' }\n const verdict = parseTonapiTrace(json.trace)\n return { ...verdict, source: 'tonapi', risk: parseTonapiRisk(json.risk) }\n}\n\n/** Options for emulating a message through tonapi or toncenter v3. */\nexport interface EmulateOptions {\n fetch?: typeof fetch\n timeoutMs?: number\n /** tonapi bearer key / toncenter X-API-Key. */\n apiKey?: string\n}\n\nasync function post(doFetch: typeof fetch, url: string, body: unknown, opts: EmulateOptions): Promise<{ status: number; ok: boolean; json: unknown }> {\n let res: Response\n try {\n res = await doFetch(url, {\n method: 'POST',\n headers: { 'content-type': 'application/json', accept: 'application/json', ...(opts.apiKey ? { authorization: `Bearer ${opts.apiKey}` } : {}) },\n body: JSON.stringify(body),\n signal: AbortSignal.timeout(opts.timeoutMs ?? DEFAULT_TIMEOUT_MS),\n })\n } catch (e) {\n throw new NetworkError(`emulate: ${e instanceof Error ? e.message : String(e)}`, { provider: url, cause: e })\n }\n if (res.status === 404) return { status: 404, ok: false, json: undefined }\n let json: unknown\n try { json = await res.json() } catch (e) { throw new NetworkError(`emulate: HTTP ${res.status}, non-JSON body`, { provider: url, cause: e }) }\n return { status: res.status, ok: res.ok, json }\n}\n\nfunction httpFailure(status: number, json: unknown): EmulationOutcome {\n const err = isObject(json) ? json : {}\n const text = typeof err.error === 'string' ? err.error : JSON.stringify(err.detail ?? err.error ?? json)\n return { ok: false, reason: `HTTP ${status}: ${text}`, aborted: false, warnings: [], source: 'tonapi' }\n}\n\n/**\n * Emulate through tonapi: `/wallet/emulate` first (verdict + risk), then\n * `/traces/emulate` when the first is not served (404). The external carries a\n * zero signature; `ignore_signature_check=true` is sent on both calls.\n */\nexport async function emulateViaTonapi(baseUrl: string, message: Cell, opts: EmulateOptions = {}): Promise<EmulationOutcome> {\n const doFetch = opts.fetch ?? globalThis.fetch\n const base = baseUrl.replace(/\\/+$/, '')\n const boc = message.toBoc().toString('base64')\n const first = await post(doFetch, `${base}/wallet/emulate?ignore_signature_check=true`, { boc }, opts)\n if (first.status !== 404) {\n if (!first.ok) return httpFailure(first.status, first.json)\n return parseTonapiConsequences(first.json)\n }\n const second = await post(doFetch, `${base}/traces/emulate?ignore_signature_check=true`, { boc }, opts)\n if (second.status === 404) throw new NetworkError('emulate: tonapi serves neither /wallet/emulate nor /traces/emulate', { provider: base })\n if (!second.ok) return httpFailure(second.status, second.json)\n if (isObject(second.json) && typeof second.json.error === 'string') return { ok: false, reason: second.json.error, aborted: false, warnings: [], source: 'tonapi' }\n return { ...parseTonapiTrace(second.json), source: 'tonapi' }\n}\n\n/** Resolve the effective emulation config: explicit `emulate`, legacy `emulateUrl`, else tonapi by default. */\nexport function resolveEmulate(config: { emulate?: TonEmulateConfig; emulateUrl?: string; tonApiUrl?: string }): Exclude<TonEmulateConfig, false> | false {\n if (config.emulate === false) return false\n if (config.emulate) return config.emulate\n if (config.emulateUrl) return { kind: 'toncenter-v3', url: config.emulateUrl }\n return { kind: 'tonapi' }\n}\n\n/** Run the configured emulation for an external message. */\nexport async function runEmulation(config: { emulate?: TonEmulateConfig; emulateUrl?: string; tonApiUrl?: string; tonApiKey?: string; fetch?: typeof fetch; timeoutMs?: number }, message: Cell): Promise<EmulationOutcome | undefined> {\n const target = resolveEmulate(config)\n if (!target) return undefined\n const opts: EmulateOptions = {\n ...(config.fetch ? { fetch: config.fetch } : {}),\n ...(config.timeoutMs !== undefined ? { timeoutMs: config.timeoutMs } : {}),\n ...(config.tonApiKey ? { apiKey: config.tonApiKey } : {}),\n }\n if (target.kind === 'tonapi') return emulateViaTonapi(target.url ?? config.tonApiUrl ?? DEFAULT_TONAPI, message, opts)\n const v = await emulateToncenter(target.url, message, opts)\n return { ...v, aborted: v.aborted ?? false, source: 'toncenter-v3', warnings: [] }\n}\n","/**\n * Wallet V5R1 (the contract Tonkeeper \"W5\" and Tonhub deploy) without\n * @ton/ton: state init, address, the signed-external body and its parser.\n *\n * Contract code and wire layout follow @ton/ton's WalletContractV5R1\n * (Copyright (c) Whales Corp., MIT) and the reference contract\n * https://github.com/ton-blockchain/wallet-contract-v5 (commit 4fab977,\n * build/wallet_v5.compiled.json). Only the parts a sending wallet needs are\n * here: extensions and the internal/extension auth paths are not implemented.\n */\nimport { Buffer } from 'buffer'\nimport {\n Address, Cell, SendMode, beginCell, contractAddress, external, loadOutList, storeMessage, storeOutList,\n type MessageRelaxed, type OutActionSendMsg, type StateInit,\n} from '@ton/core'\n\n// https://github.com/ton-blockchain/wallet-contract-v5/blob/4fab977f4fae3a37c1aac216ed2b7e611a9bc2af/build/wallet_v5.compiled.json\n/** Code of the Wallet V5R1 contract (BoC hex). */\nexport const V5R1_CODE_HEX =\n 'b5ee9c7241021401000281000114ff00f4a413f4bcf2c80b01020120020d020148030402dcd020d749c120915b8f6320d70b1f2082106578746ebd21821073696e74bdb0925f03e082106578746eba8eb48020d72101d074d721fa4030fa44f828fa443058bd915be0ed44d0810141d721f4058307f40e6fa1319130e18040d721707fdb3ce03120d749810280b99130e070e2100f020120050c020120060902016e07080019adce76a2684020eb90eb85ffc00019af1df6a2684010eb90eb858fc00201480a0b0017b325fb51341c75c875c2c7e00011b262fb513435c280200019be5f0f6a2684080a0eb90fa02c0102f20e011e20d70b1f82107369676ebaf2e08a7f0f01e68ef0eda2edfb218308d722028308d723208020d721d31fd31fd31fed44d0d200d31f20d31fd3ffd70a000af90140ccf9109a28945f0adb31e1f2c087df02b35007b0f2d0845125baf2e0855036baf2e086f823bbf2d0882292f800de01a47fc8ca00cb1f01cf16c9ed542092f80fde70db3cd81003f6eda2edfb02f404216e926c218e4c0221d73930709421c700b38e2d01d72820761e436c20d749c008f2e09320d74ac002f2e09320d71d06c712c2005230b0f2d089d74cd7393001a4e86c128407bbf2e093d74ac000f2e093ed55e2d20001c000915be0ebd72c08142091709601d72c081c12e25210b1e30f20d74a111213009601fa4001fa44f828fa443058baf2e091ed44d0810141d718f405049d7fc8ca0040048307f453f2e08b8e14038307f45bf2e08c22d70a00216e01b3b0f2d090e2c85003cf1612f400c9ed54007230d72c08248e2d21f2e092d200ed44d0d2005113baf2d08f54503091319c01810140d721d70a00f2e08ee2c8ca0058cf16c9ed5493f2c08de20010935bdb31e1d74cd0b4d6c35e'\n\nlet codeCell: Cell | undefined\n/** The V5R1 contract code cell (parsed once). */\nexport function v5r1Code(): Cell {\n codeCell ??= Cell.fromBoc(Buffer.from(V5R1_CODE_HEX, 'hex'))[0]!\n return codeCell\n}\n\n/** Op codes of Wallet V5R1 messages. */\nexport const V5R1_OP = {\n signedExternal: 0x7369676e,\n signedInternal: 0x73696e74,\n extension: 0x6578746e,\n} as const\n\n/** Global id of TON mainnet, part of the V5R1 wallet id. */\nexport const MAINNET_GLOBAL_ID = -239\n/** Global id of TON testnet. */\nexport const TESTNET_GLOBAL_ID = -3\n/** PAY_GAS_SEPARATELY | IGNORE_ERRORS — the mode every external-message action carries. */\nexport const DEFAULT_SEND_MODE = SendMode.PAY_GAS_SEPARATELY | SendMode.IGNORE_ERRORS\n/** Most outgoing messages one V5R1 transaction can carry. */\nexport const MAX_ACTIONS = 255\n\nexport interface V5R1WalletIdParts { networkGlobalId?: number; workchain?: number; subwalletNumber?: number }\n\n/**\n * Serialized wallet_id (int32): `networkGlobalId XOR context`, where the client\n * context is {1 bit \"client\", int8 workchain, uint8 version (0 = v5r1), uint15 subwallet}.\n */\nexport function v5r1WalletId(parts: V5R1WalletIdParts = {}): bigint {\n const context = beginCell()\n .storeUint(1, 1)\n .storeInt(parts.workchain ?? 0, 8)\n .storeUint(0, 8)\n .storeUint(parts.subwalletNumber ?? 0, 15)\n .endCell().beginParse().loadInt(32)\n return BigInt(parts.networkGlobalId ?? MAINNET_GLOBAL_ID) ^ BigInt(context)\n}\n\n/** State init (code and data) of a V5R1 wallet for a public key. */\nexport function v5r1StateInit(publicKey: Uint8Array, walletId: bigint = v5r1WalletId()): StateInit {\n if (publicKey.length !== 32) throw new Error('V5R1: public key must be 32 bytes')\n const data = beginCell()\n .storeUint(1, 1) // signature auth allowed\n .storeUint(0, 32) // seqno\n .storeInt(walletId, 32)\n .storeBuffer(Buffer.from(publicKey), 32)\n .storeBit(0) // no extensions\n .endCell()\n return { code: v5r1Code(), data }\n}\n\n/** Address of the V5R1 wallet for a public key. */\nexport function v5r1Address(publicKey: Uint8Array, opts: { workchain?: number; walletId?: bigint } = {}): Address {\n return contractAddress(opts.workchain ?? 0, v5r1StateInit(publicKey, opts.walletId))\n}\n\nexport interface V5R1Message { message: MessageRelaxed; mode?: number }\n\nexport interface V5R1SigningParams {\n walletId: bigint\n /** Unix seconds. */\n validUntil: number\n seqno: number\n messages: V5R1Message[]\n}\n\n/** The cell that gets hashed and signed: op | wallet_id | valid_until | seqno | out-list ref | no extended actions. */\nexport function v5r1SigningMessage(p: V5R1SigningParams): Cell {\n if (p.messages.length > MAX_ACTIONS) throw new Error(`V5R1: at most ${MAX_ACTIONS} messages per external (got ${p.messages.length})`)\n const actions: OutActionSendMsg[] = p.messages.map((m) => ({\n type: 'sendMsg',\n // Externals must carry IGNORE_ERRORS or the wallet contract rejects them.\n mode: (m.mode ?? DEFAULT_SEND_MODE) | SendMode.IGNORE_ERRORS,\n outMsg: m.message,\n }))\n const outList = actions.length ? beginCell().store(storeOutList(actions)).endCell() : null\n return beginCell()\n .storeUint(V5R1_OP.signedExternal, 32)\n .storeInt(p.walletId, 32)\n .storeUint(p.validUntil, 32)\n .storeUint(p.seqno, 32)\n .storeMaybeRef(outList)\n .storeUint(0, 1)\n .endCell()\n}\n\n/** Signature goes at the tail (V5R1 layout). */\nexport function v5r1PackSigned(signing: Cell, signature: Uint8Array): Cell {\n if (signature.length !== 64) throw new Error('V5R1: signature must be 64 bytes')\n return beginCell().storeSlice(signing.beginParse()).storeBuffer(Buffer.from(signature), 64).endCell()\n}\n\n/** Same body with a zero signature — what `estimateFee(ignore_chksig)` and emulation take. */\nexport function v5r1PackUnsigned(signing: Cell): Cell {\n return v5r1PackSigned(signing, new Uint8Array(64))\n}\n\n/** The external-in message (as a cell, ready for sendBoc) carrying `body` to the wallet, with `init` when it is not deployed yet. */\nexport function v5r1ExternalMessage(to: Address, body: Cell, init?: StateInit): Cell {\n return beginCell().store(storeMessage(external({ to, body, ...(init ? { init } : {}) }))).endCell()\n}\n\nexport interface ParsedV5R1Body {\n op: number\n walletId: bigint\n validUntil: number\n seqno: number\n messages: Array<{ message: MessageRelaxed; mode: number }>\n /** True when the 64-byte tail signature is present (externals and internals carry one). */\n signed: boolean\n}\n\n/** Parse a signed (or zero-signed) V5R1 external body back into its messages. Returns null for anything else. */\nexport function parseV5R1Body(body: Cell): ParsedV5R1Body | null {\n try {\n const s = body.beginParse()\n const op = s.loadUint(32)\n if (op !== V5R1_OP.signedExternal && op !== V5R1_OP.signedInternal) return null\n const walletId = BigInt(s.loadInt(32))\n const validUntil = s.loadUint(32)\n const seqno = s.loadUint(32)\n const outList = s.loadMaybeRef()\n const hasExtended = s.loadBit()\n if (hasExtended) return null // extension management: not a plain send\n const messages: ParsedV5R1Body['messages'] = []\n if (outList) {\n for (const a of loadOutList(outList.beginParse())) {\n if (a.type !== 'sendMsg') return null\n messages.push({ message: a.outMsg, mode: a.mode })\n }\n }\n const signed = s.remainingBits >= 512\n return { op, walletId, validUntil, seqno, messages, signed }\n } catch {\n return null\n }\n}\n","/**\n * \"What am I signing\" for TON — offline. Decodes the messages of a\n * {@link TonSendable} (or a prebuilt V5R1 body) into human-checkable items and\n * flags the classic mistakes before any key is touched.\n */\nimport { Address, Cell, beginCell, type MessageRelaxed, type Slice } from '@ton/core'\nimport { parseV5R1Body } from './wallet-v5r1.js'\nimport type { TonSendable, TonTransaction } from './types.js'\n\n/** TEP-74 `transfer` op code of a jetton wallet. */\nexport const JETTON_TRANSFER_OP = 0x0f8a7ea5\nconst LARGE_FORWARD_NANOTON = 500_000_000n // 0.5 TON\n\n/** What one outgoing message does. */\nexport type TonDescribedKind = 'ton-transfer' | 'jetton-transfer' | 'contract-call'\n\n/** Fields of a TEP-74 jetton `transfer` body. */\nexport interface TonJettonDetails {\n queryId: bigint\n amount: bigint\n destination: string\n responseDestination: string | null\n forwardTonAmount: bigint\n forwardPayload: 'none' | 'comment' | 'cell'\n forwardComment?: string\n hasCustomPayload: boolean\n}\n\n/** One outgoing message of a wallet transaction, decoded. */\nexport interface TonDescribedMessage {\n kind: TonDescribedKind\n /** Destination as given (friendly) or raw `wc:hex`. */\n to: string\n value: bigint\n bounceable: boolean\n /** Test-only flag of a friendly address; undefined for raw addresses. */\n testOnly?: boolean\n /** Text comment (op 0). */\n comment?: string\n /** Body op code for contract calls (hex). */\n op?: string\n jetton?: TonJettonDetails\n hasStateInit: boolean\n bodyBits: number\n}\n\n/** Problems a TON description is flagged with. */\nexport type TonWarningCode =\n | 'zero-value'\n | 'non-bounceable-contract-call'\n | 'unknown-body'\n | 'large-forward-amount'\n | 'testnet-address'\n | 'mainnet-address'\n | 'exotic-workchain'\n | 'extended-actions'\n\n/** One flagged problem; `index` is the message it is about. */\nexport interface TonWarning { code: TonWarningCode; message: string; index?: number }\n\n/**\n * A TON wallet transaction decoded for a confirmation screen: each outgoing message and the\n * warnings.\n */\nexport interface TonDescription {\n kind: TonDescribedKind | 'mixed'\n items: TonDescribedMessage[]\n warnings: TonWarning[]\n /** Present when the input was a prebuilt V5R1 body. */\n external?: { seqno: number; validUntil: number; walletId: bigint; signed: boolean }\n}\n\n/** A message body decoded: empty, a text comment, a jetton transfer, or unknown. */\nexport type DecodedBody =\n | { type: 'empty' }\n | { type: 'comment'; text: string }\n | { type: 'jetton-transfer'; jetton: TonJettonDetails }\n | { type: 'op'; op: number }\n | { type: 'unknown' }\n\n/** Decode a message body cell. */\nexport function decodeBody(body: Cell): DecodedBody {\n const s = body.beginParse()\n if (s.remainingBits === 0 && s.remainingRefs === 0) return { type: 'empty' }\n if (s.remainingBits < 32) return { type: 'unknown' }\n const op = s.loadUint(32)\n try {\n if (op === 0) return { type: 'comment', text: s.loadStringTail() }\n if (op === JETTON_TRANSFER_OP) return { type: 'jetton-transfer', jetton: loadJettonTransfer(s) }\n } catch {\n return { type: 'unknown' }\n }\n return { type: 'op', op }\n}\n\nfunction loadJettonTransfer(s: Slice): TonJettonDetails {\n const queryId = s.loadUintBig(64)\n const amount = s.loadCoins()\n const destination = s.loadAddress()\n const responseDestination = s.loadMaybeAddress()\n const customPayload = s.loadMaybeRef()\n const forwardTonAmount = s.loadCoins()\n const inRef = s.loadBit()\n const payload: Slice = inRef ? s.loadRef().beginParse() : s\n let forwardPayload: TonJettonDetails['forwardPayload'] = 'none'\n let forwardComment: string | undefined\n if (payload.remainingBits > 0 || payload.remainingRefs > 0) {\n forwardPayload = 'cell'\n if (payload.remainingBits >= 32) {\n const p = payload.clone()\n if (p.loadUint(32) === 0) {\n try { forwardComment = p.loadStringTail(); forwardPayload = 'comment' } catch { /* not utf-8 */ }\n }\n }\n }\n return {\n queryId, amount, destination: destination.toString(), responseDestination: responseDestination ? responseDestination.toString() : null,\n forwardTonAmount, forwardPayload, ...(forwardComment !== undefined ? { forwardComment } : {}), hasCustomPayload: customPayload !== null,\n }\n}\n\nfunction parseTo(to: string): { to: string; bounceable: boolean; testOnly?: boolean; workchain: number } {\n if (Address.isFriendly(to)) {\n const f = Address.parseFriendly(to)\n return { to, bounceable: f.isBounceable, testOnly: f.isTestOnly, workchain: f.address.workChain }\n }\n const a = Address.parse(to)\n return { to: a.toRawString(), bounceable: true, workchain: a.workChain }\n}\n\nfunction bodyOf(tx: TonTransaction): Cell | undefined {\n if (tx.body instanceof Cell) return tx.body\n if (typeof tx.body === 'string') return tx.body === '' ? undefined : commentCell(tx.body)\n if (tx.bodyBoc) return Cell.fromBase64(tx.bodyBoc)\n return undefined\n}\n\n/** A text comment body (op 0 plus the text), as wallets show it. */\nexport function commentCell(text: string): Cell {\n return beginCell().storeUint(0, 32).storeStringTail(text).endCell()\n}\n\nfunction describeOne(\n i: number, to: ReturnType<typeof parseTo>, value: bigint, body: Cell | undefined, hasStateInit: boolean,\n bounceableOverride: boolean | undefined, warnings: TonWarning[], ctx: { network?: 'mainnet' | 'testnet' },\n): TonDescribedMessage {\n const bounceable = bounceableOverride ?? to.bounceable\n const decoded = body ? decodeBody(body) : ({ type: 'empty' } as DecodedBody)\n const base = { to: to.to, value, bounceable, ...(to.testOnly !== undefined ? { testOnly: to.testOnly } : {}), hasStateInit, bodyBits: body ? body.bits.length : 0 }\n if (value <= 0n) warnings.push({ code: 'zero-value', message: 'message carries no TON; it cannot pay for gas at the destination', index: i })\n if (to.workchain !== 0 && to.workchain !== -1) warnings.push({ code: 'exotic-workchain', message: `workchain ${to.workchain}`, index: i })\n if (ctx.network && to.testOnly !== undefined) {\n if (to.testOnly && ctx.network !== 'testnet') warnings.push({ code: 'testnet-address', message: 'test-only address on a mainnet wallet', index: i })\n if (!to.testOnly && ctx.network === 'testnet') warnings.push({ code: 'mainnet-address', message: 'mainnet address on a testnet wallet', index: i })\n }\n let item: TonDescribedMessage\n switch (decoded.type) {\n case 'empty': item = { kind: 'ton-transfer', ...base }; break\n case 'comment': item = { kind: 'ton-transfer', ...base, comment: decoded.text }; break\n case 'jetton-transfer':\n item = { kind: 'jetton-transfer', ...base, jetton: decoded.jetton, op: hex(JETTON_TRANSFER_OP) }\n if (decoded.jetton.forwardTonAmount > LARGE_FORWARD_NANOTON) warnings.push({ code: 'large-forward-amount', message: `forward_ton_amount ${decoded.jetton.forwardTonAmount} > 0.5 TON`, index: i })\n break\n case 'op': item = { kind: 'contract-call', ...base, op: hex(decoded.op) }; break\n default:\n item = { kind: 'contract-call', ...base }\n warnings.push({ code: 'unknown-body', message: 'message body could not be decoded', index: i })\n }\n if (item.kind !== 'ton-transfer' && !bounceable) {\n warnings.push({ code: 'non-bounceable-contract-call', message: 'contract call to a non-bounceable address: TON is lost if the call fails', index: i })\n }\n return item\n}\n\nconst hex = (n: number) => `0x${n.toString(16).padStart(8, '0')}`\n\n/** Describe one outgoing message and push its warnings into `warnings`. */\nexport function describeMessageRelaxed(i: number, m: MessageRelaxed, warnings: TonWarning[], ctx: { network?: 'mainnet' | 'testnet' } = {}): TonDescribedMessage {\n if (m.info.type !== 'internal') {\n warnings.push({ code: 'unknown-body', message: 'not an internal message', index: i })\n return { kind: 'contract-call', to: '', value: 0n, bounceable: false, hasStateInit: false, bodyBits: 0 }\n }\n const dest = m.info.dest\n const to = { to: dest.toString({ bounceable: m.info.bounce }), bounceable: m.info.bounce, workchain: dest.workChain }\n const body = m.body.bits.length === 0 && m.body.refs.length === 0 ? undefined : m.body\n return describeOne(i, to, m.info.value.coins, body, !!m.init, m.info.bounce, warnings, ctx)\n}\n\n/** Describe what a {@link TonSendable} will do. Offline; never throws on malformed bodies (they become warnings). */\nexport function describeTransaction(tx: TonSendable, ctx: { network?: 'mainnet' | 'testnet' } = {}): TonDescription {\n const warnings: TonWarning[] = []\n const items: TonDescribedMessage[] = []\n let external: TonDescription['external'] | undefined\n if (tx instanceof Cell) {\n const parsed = parseV5R1Body(tx)\n if (!parsed) {\n warnings.push({ code: 'unknown-body', message: 'not a V5R1 signed-external body' })\n return { kind: 'contract-call', items, warnings }\n }\n external = { seqno: parsed.seqno, validUntil: parsed.validUntil, walletId: parsed.walletId, signed: parsed.signed }\n parsed.messages.forEach((m, i) => items.push(describeMessageRelaxed(i, m.message, warnings, ctx)))\n } else {\n const list = Array.isArray(tx) ? tx : [tx]\n list.forEach((t, i) => {\n let to: ReturnType<typeof parseTo>\n try { to = parseTo(t.to) } catch {\n warnings.push({ code: 'unknown-body', message: `invalid address: ${t.to}`, index: i })\n items.push({ kind: 'contract-call', to: t.to, value: 0n, bounceable: false, hasStateInit: false, bodyBits: 0 })\n return\n }\n let body: Cell | undefined\n try { body = bodyOf(t) } catch { warnings.push({ code: 'unknown-body', message: 'bodyBoc is not a valid BoC', index: i }) }\n items.push(describeOne(i, to, BigInt(t.value), body, t.stateInit !== undefined, t.bounceable, warnings, ctx))\n })\n }\n const kinds = new Set(items.map((x) => x.kind))\n const kind: TonDescription['kind'] = kinds.size === 1 ? items[0]!.kind : kinds.size === 0 ? 'contract-call' : 'mixed'\n return { kind, items, warnings, ...(external ? { external } : {}) }\n}\n","import { NetworkError, type IWalletAccountReadOnly } from '@anywalletkit/core'\nimport { ed25519 } from '@noble/curves/ed25519.js'\nimport { Address, Cell, beginCell, internal, loadStateInit, type StateInit } from '@ton/core'\nimport { commentCell, describeTransaction, type TonDescription } from './describe.js'\nimport { UnsafeTransactionError } from './errors.js'\nimport { TonCenter, createTonRpc } from './toncenter.js'\nimport { runEmulation } from './emulation.js'\nimport {\n DEFAULT_SEND_MODE, MAINNET_GLOBAL_ID, TESTNET_GLOBAL_ID, v5r1Address, v5r1ExternalMessage, v5r1PackUnsigned, v5r1SigningMessage, v5r1StateInit, v5r1WalletId,\n type V5R1Message,\n} from './wallet-v5r1.js'\nimport { CAIP2, type TonConfig, type TonFees, type TonReceipt, type TonSendable, type TonSimulation, type TonTransaction, type TonTransferOptions } from './types.js'\n\nconst JETTON_TRANSFER_OP = 0x0f8a7ea5\nconst DEFAULT_JETTON_ATTACHED = 50_000_000n // 0.05 TON\nconst DEFAULT_INDEXER = 'https://toncenter.com/api/v3'\nconst DEFAULT_VALID_SECONDS = 60\nconst MAX_VALID_SECONDS = 600\n/** PAY_GAS_SEPARATELY | IGNORE_ERRORS, the mode every action in an external carries. */\nexport const SEND_MODE = DEFAULT_SEND_MODE\n\nconst utf8 = (s: string | Uint8Array) => (typeof s === 'string' ? new TextEncoder().encode(s) : s)\nconst hexToBytes = (h: string) => Uint8Array.from(h.match(/.{2}/g) ?? [], (b) => parseInt(b, 16))\nconst big = (v: bigint | number | string) => BigInt(v)\n\n/**\n * A TON V5R1 wallet without a key: balance, jetton balances, seqno, fee estimates, emulation,\n * receipts and signature checks.\n */\nexport class WalletAccountReadOnlyTon implements IWalletAccountReadOnly {\n readonly chain: string\n /** Ed25519 public key the wallet is derived from. */\n readonly publicKey: Uint8Array\n /** User-friendly address. */\n readonly address: string\n protected readonly _config: TonConfig\n protected readonly _walletId: bigint\n protected readonly _init: StateInit\n protected readonly _address: Address\n protected readonly _rpc: TonCenter | undefined\n\n constructor(publicKey: Uint8Array | string, config: TonConfig = {}) {\n this.publicKey = typeof publicKey === 'string' ? hexToBytes(publicKey) : publicKey\n this._config = config\n // The network_global_id inside wallet_id is the only thing that binds a signed external to one\n // network: a testnet wallet must carry -3, or every external it signs is also valid on mainnet\n // (same state init, address and wallet_id). It follows config.network; a contradicting override is refused.\n const networkGlobalId = config.network === 'testnet' ? TESTNET_GLOBAL_ID : MAINNET_GLOBAL_ID\n if (config.walletId?.networkGlobalId !== undefined && config.walletId.networkGlobalId !== networkGlobalId) {\n throw new UnsafeTransactionError('network-mismatch', `walletId.networkGlobalId ${config.walletId.networkGlobalId} contradicts network '${config.network ?? 'mainnet'}' (expected ${networkGlobalId}): externals signed this way would be valid on the other network.`)\n }\n this._walletId = v5r1WalletId({ networkGlobalId, ...(config.walletId?.subwalletNumber !== undefined ? { subwalletNumber: config.walletId.subwalletNumber } : {}) })\n this._init = v5r1StateInit(this.publicKey, this._walletId)\n this._address = v5r1Address(this.publicKey, { walletId: this._walletId })\n this.address = this._address.toString({ bounceable: false, testOnly: config.network === 'testnet' })\n this.chain = CAIP2[config.network ?? 'mainnet']\n const rpc = createTonRpc(config)\n this._rpc = rpc ? new TonCenter(rpc) : undefined\n }\n\n protected requireRpc(what: string): TonCenter {\n if (!this._rpc) throw new NetworkError(`The wallet must be connected to a provider (toncenter) to ${what}.`)\n return this._rpc\n }\n\n /** The user-friendly address. */\n async getAddress(): Promise<string> { return this.address }\n\n /** Native balance in nanotons. */\n async getBalance(): Promise<bigint> {\n return (await this.requireRpc('get balances').getAddressInformation(this._address)).balance\n }\n\n /** Current seqno — 0 until the wallet contract is deployed. Always fetched fresh. */\n async getSeqno(): Promise<number> {\n const rpc = this.requireRpc('read the seqno')\n const state = await rpc.getAddressInformation(this._address)\n if (state.state !== 'active') return 0\n return (await rpc.runGetMethodOk(this._address, 'seqno')).stack.readNumber()\n }\n\n /** Resolve this wallet's jetton wallet for a jetton master. */\n async getJettonWalletAddress(token: string): Promise<Address> {\n const rpc = this.requireRpc('resolve jetton wallets')\n const r = await rpc.runGetMethodOk(Address.parse(token), 'get_wallet_address', [\n { type: 'slice', cell: beginCell().storeAddress(this._address).endCell() },\n ])\n return r.stack.readAddress()\n }\n\n /**\n * Read a jetton wallet and prove it is ours for `token`: `get_wallet_data`\n * must name this wallet as owner and `token` as master. The master's own\n * `get_wallet_address` answer is not trusted on its own — a fake master could\n * point at our real wallet of another jetton (e.g. USDT).\n */\n protected async jettonWalletData(token: string, jw: Address): Promise<bigint> {\n const stack = (await this.requireRpc('read jetton wallets').runGetMethodOk(jw, 'get_wallet_data')).stack\n const balance = stack.readBigNumber()\n const owner = stack.readAddress()\n const master = stack.readAddress()\n if (!owner.equals(this._address) || !master.equals(Address.parse(token))) {\n throw new UnsafeTransactionError('jetton-wallet', `The jetton wallet ${jw.toString()} does not belong to this wallet for ${token}.`)\n }\n return balance\n }\n\n /**\n * Jetton balance in base units, read from this wallet's jetton wallet; 0 when it does not exist.\n */\n async getTokenBalance(token: string): Promise<bigint> {\n const rpc = this.requireRpc('get token balances')\n const jw = await this.getJettonWalletAddress(token)\n if ((await rpc.getAddressInformation(jw)).state !== 'active') return 0n // never received this jetton\n return this.jettonWalletData(token, jw)\n }\n\n // ── Message building ──────────────────────────────────────────────────────\n\n protected stateInitOf(src: TonTransaction['stateInit']): StateInit | undefined {\n if (src === undefined) return undefined\n if (typeof src === 'string') return loadStateInit(Cell.fromBase64(src).beginParse())\n if (src instanceof Cell) return loadStateInit(src.beginParse())\n return src\n }\n\n protected transactionMessage(tx: TonTransaction): V5R1Message {\n const value = big(tx.value)\n if (value <= 0n) throw new UnsafeTransactionError('zero-value', 'TON message value must be positive.')\n let address: Address\n let bounceable = true\n let testOnly: boolean | undefined\n if (Address.isFriendly(tx.to)) {\n const f = Address.parseFriendly(tx.to)\n address = f.address; bounceable = f.isBounceable; testOnly = f.isTestOnly\n } else {\n address = Address.parse(tx.to)\n }\n if (address.workChain !== 0 && address.workChain !== -1) throw new UnsafeTransactionError('exotic-workchain', `Refusing to send to workchain ${address.workChain}.`)\n const testnet = this._config.network === 'testnet'\n if (testOnly !== undefined && testOnly !== testnet) {\n throw new UnsafeTransactionError('network-mismatch', testOnly ? 'Test-only address on a mainnet wallet.' : 'Mainnet address on a testnet wallet.')\n }\n const body = tx.body instanceof Cell ? tx.body : typeof tx.body === 'string' ? (tx.body === '' ? undefined : commentCell(tx.body)) : tx.bodyBoc ? Cell.fromBase64(tx.bodyBoc) : undefined\n const init = this.stateInitOf(tx.stateInit)\n const message = internal({ to: address, value, bounce: tx.bounceable ?? bounceable, ...(body ? { body } : {}), ...(init ? { init } : {}) })\n return { message, ...(tx.sendMode !== undefined ? { mode: tx.sendMode } : {}) }\n }\n\n protected async jettonTransferMessage(o: TonTransferOptions): Promise<V5R1Message> {\n const amount = big(o.amount)\n if (amount <= 0n) throw new UnsafeTransactionError('zero-value', 'Jetton amount must be positive.')\n const recipient = Address.parse(o.recipient)\n const jw = await this.getJettonWalletAddress(o.token!)\n await this.jettonWalletData(o.token!, jw)\n const forwardTonAmount = o.forwardTonAmount !== undefined ? big(o.forwardTonAmount) : 1n\n if (o.memo !== undefined && o.forwardPayload !== undefined) throw new UnsafeTransactionError('memo-and-payload', 'Pass either memo or forwardPayload, not both: a jetton transfer carries one forward payload.')\n const payload = o.forwardPayload ?? o.memo\n const forwardPayload = payload === undefined ? null : typeof payload === 'string' ? commentCell(payload) : payload\n const body = beginCell()\n .storeUint(JETTON_TRANSFER_OP, 32)\n .storeUint(o.queryId !== undefined ? BigInt(o.queryId) : randomQueryId(), 64)\n .storeCoins(amount)\n .storeAddress(recipient)\n .storeAddress(o.responseDestination ? Address.parse(o.responseDestination) : this._address)\n .storeMaybeRef(o.customPayload ?? null)\n .storeCoins(forwardTonAmount)\n .storeMaybeRef(forwardPayload) // either-ref form: payloads always travel in a ref\n .endCell()\n const attached = o.attachedValue !== undefined\n ? big(o.attachedValue)\n : (this._config.jettonAttachedValue !== undefined ? big(this._config.jettonAttachedValue) : DEFAULT_JETTON_ATTACHED) + forwardTonAmount\n return { message: internal({ to: jw, value: attached, bounce: true, body }) }\n }\n\n protected toMessages(tx: TonTransaction | TonTransaction[]): V5R1Message[] {\n const list = Array.isArray(tx) ? tx : [tx]\n if (list.length === 0) throw new UnsafeTransactionError('empty', 'Nothing to send.')\n return list.map((t) => this.transactionMessage(t))\n }\n\n protected validUntil(): number {\n const seconds = this._config.validUntilSeconds ?? DEFAULT_VALID_SECONDS\n if (!Number.isInteger(seconds) || seconds <= 0 || seconds > MAX_VALID_SECONDS) {\n throw new UnsafeTransactionError('valid-until', `validUntilSeconds must be an integer between 1 and ${MAX_VALID_SECONDS}.`)\n }\n return Math.floor(Date.now() / 1000) + seconds\n }\n\n /** The cell to sign for `messages` at the CURRENT seqno (fetched fresh every time). */\n protected async signingCell(messages: V5R1Message[]): Promise<{ signing: Cell; seqno: number; validUntil: number }> {\n const seqno = await this.getSeqno()\n const validUntil = this.validUntil()\n return { signing: v5r1SigningMessage({ walletId: this._walletId, validUntil, seqno, messages }), seqno, validUntil }\n }\n\n // ── Fees / preflight ──────────────────────────────────────────────────────\n\n /** StateInit to attach to an external when the wallet is not deployed yet. */\n protected async initIfNeeded(): Promise<StateInit | undefined> {\n const state = await this.requireRpc('read the account state').getAddressInformation(this._address)\n return state.state === 'active' ? undefined : this._init\n }\n\n /** in_fwd + storage + gas + fwd from toncenter's estimateFee (signature ignored). */\n async estimateFees(body: Cell): Promise<TonFees> {\n const rpc = this.requireRpc('quote transfers')\n const init = await this.initIfNeeded()\n return rpc.estimateFee(this._address, { body, ...(init ? { init } : {}), ignoreSignature: true })\n }\n\n /**\n * Preflight an external body: fees via estimateFee and, unless\n * `config.emulate === false`, a trace emulation (tonapi by default, see\n * {@link TonConfig.emulate}) whose compute/action phases — and the first-hop\n * internal messages — decide `ok`. Never throws for a failing emulation,\n * only for transport problems or a malformed emulator response.\n */\n async simulateBody(body: Cell): Promise<TonSimulation> {\n const fees = await this.estimateFees(body)\n const init = await this.initIfNeeded()\n const outcome = await runEmulation(this._config, v5r1ExternalMessage(this._address, body, init))\n if (!outcome) return { ok: true, fees, emulated: false, source: 'estimate-only', warnings: [] }\n const common = {\n fees, emulated: true as const, source: outcome.source, warnings: outcome.warnings,\n ...(outcome.exitCode !== undefined ? { exitCode: outcome.exitCode } : {}),\n ...(outcome.risk ? { risk: outcome.risk } : {}),\n }\n if (outcome.ok) return { ok: true, ...common, ...(outcome.actionSuccess !== undefined ? { actionSuccess: outcome.actionSuccess } : {}) }\n return { ok: false, ...common, reason: outcome.reason ?? 'emulation failed', ...(outcome.aborted !== undefined ? { aborted: outcome.aborted } : {}) }\n }\n\n /** Preflight a {@link TonSendable} (unsigned body, current seqno). */\n async simulateTransaction(tx: TonSendable): Promise<TonSimulation> {\n const body = tx instanceof Cell ? tx : v5r1PackUnsigned((await this.signingCell(this.toMessages(tx))).signing)\n return this.simulateBody(body)\n }\n\n /** Estimated fee of a transaction, in nanotons. */\n async quoteSendTransaction(tx: TonSendable): Promise<{ fee: bigint }> {\n const body = tx instanceof Cell ? tx : v5r1PackUnsigned((await this.signingCell(this.toMessages(tx))).signing)\n return { fee: (await this.estimateFees(body)).total }\n }\n\n /** Estimated fee of a transfer, in nanotons. */\n async quoteTransfer(o: TonTransferOptions): Promise<{ fee: bigint }> {\n const message = o.token ? await this.jettonTransferMessage(o) : this.transactionMessage({ to: o.recipient, value: o.amount, ...(o.memo !== undefined ? { body: o.memo } : {}) })\n const { signing } = await this.signingCell([message])\n return { fee: (await this.estimateFees(v5r1PackUnsigned(signing))).total }\n }\n\n /** Offline description of what `tx` does — see {@link describeTransaction}. */\n describe(tx: TonSendable): TonDescription {\n return describeTransaction(tx, { network: this._config.network ?? 'mainnet' })\n }\n\n /**\n * Receipt for a body hash returned by sendTransaction: toncenter v3 maps the\n * message body hash to the account transaction, which is then fetched.\n */\n async getTransactionReceipt(hash: string): Promise<TonReceipt | undefined> {\n const rpc = this.requireRpc('fetch transaction receipts')\n const base = this._config.indexerUrl ?? DEFAULT_INDEXER\n const doFetch = this._config.fetch ?? globalThis.fetch\n const res = await doFetch(`${base}/transactionsByMessage?${new URLSearchParams({ body_hash: hash, limit: '1' })}`, { signal: AbortSignal.timeout(this._config.timeoutMs ?? 15_000) })\n if (!res.ok) throw new NetworkError(`toncenter v3 ${res.status}`, { provider: base })\n const { transactions } = (await res.json()) as { transactions?: Array<{ account: string; hash: string; lt: string }> }\n const found = transactions?.[0]\n if (!found) return undefined\n const account = Address.parse(found.account)\n let tx\n try { [tx] = await rpc.getTransactions(account, { limit: 1, hash: found.hash }) }\n catch { [tx] = await rpc.getTransactions(account, { limit: 1, lt: found.lt, hash: found.hash, archival: true }) }\n if (!tx) return undefined\n const d = tx.description as { type: string; aborted?: boolean }\n return { hash, status: d.type === 'generic' && !d.aborted ? 1 : 0, blockNumber: tx.lt, transactionHash: tx.hash().toString('base64'), totalFees: tx.totalFees.coins, raw: tx }\n }\n\n /** ed25519 over the raw message bytes; `signature` hex. */\n async verify(message: string | Uint8Array, signature: string): Promise<boolean> {\n try { return ed25519.verify(hexToBytes(signature), utf8(message), this.publicKey) } catch { return false }\n }\n}\n\nfunction randomQueryId(): bigint {\n const r = new Uint32Array(2)\n globalThis.crypto.getRandomValues(r)\n return (BigInt(r[0]!) << 32n) | BigInt(r[1]!)\n}\n","import { LocalSigner, feeLimit, requireCurve, type IWalletAccount, type IWalletAccountReadOnly, type Signer, type TransferResult, type WriteOptions } from '@anywalletkit/core'\nimport { Cell } from '@ton/core'\nimport { SimulationError, UnsafeTransactionError } from './errors.js'\nimport { WalletAccountReadOnlyTon } from './read-only-account.js'\nimport { v5r1ExternalMessage, v5r1PackSigned, v5r1PackUnsigned, type V5R1Message } from './wallet-v5r1.js'\nimport type { TonConfig, TonSendable, TonTransferOptions } from './types.js'\n\nconst toHex = (u8: Uint8Array) => Array.from(u8, (b) => b.toString(16).padStart(2, '0')).join('')\n\n/**\n * Signing TON account on Wallet V5R1. It never holds a key: the V5R1 body is\n * signed by `signer.sign(signingCell.hash(), {scheme: 'ed25519', context:\n * 'ton-external'})` — a {@link LocalSigner} for seed wallets, anything else\n * (hardware, MPC, backend) through `externalSigner()`.\n *\n * Every send runs: hard checks → fresh seqno → preflight on the zero-signed\n * body (estimateFee, emulation when configured, fee cap) → sign → broadcast.\n * The preflight body carries a zero signature, so the signer is only asked\n * once the transaction has passed.\n */\nexport class WalletAccountTon extends WalletAccountReadOnlyTon implements IWalletAccount {\n /** seqno and fees come from the network before signing. */\n readonly needsNetwork = true\n /** Derivation path, `ton-mnemonic`, or `external`. */\n readonly path: string\n /** The signer that holds the key. */\n readonly signer: Signer\n private _readOnly: WalletAccountReadOnlyTon | undefined\n\n /** `publicKey` is the signer's 32-byte ed25519 key; the V5R1 address derives from it synchronously. */\n constructor(signer: Signer, publicKey: Uint8Array, path: string, config: TonConfig = {}) {\n super(publicKey, config)\n this.signer = requireCurve(signer, 'ed25519')\n this.path = path\n }\n\n /** Back-compat: wrap a raw derived key in a {@link LocalSigner} (the account takes ownership; it cannot derive). */\n static fromPrivateKey(privateKey: Uint8Array, publicKey: Uint8Array, path: string, config: TonConfig = {}): WalletAccountTon {\n return new WalletAccountTon(LocalSigner.fromPrivateKey('ed25519', privateKey, publicKey, path), publicKey, path, config)\n }\n\n /** Account index for the standard m/44'/607'/i' path. */\n get index(): number | undefined {\n const m = /^m\\/44'\\/607'\\/(\\d+)'$/.exec(this.path)\n return m ? Number(m[1]) : undefined\n }\n\n /** Hex ed25519 signature over the raw message bytes (ton_proof and the like). */\n async sign(message: string | Uint8Array): Promise<string> {\n const bytes = typeof message === 'string' ? new TextEncoder().encode(message) : message\n return toHex(await this.signer.sign(bytes, { scheme: 'ed25519', context: 'ton-message' }))\n }\n\n private checkMaxFee(fee: bigint, limit: bigint | number | undefined, op: string) {\n if (limit !== undefined && fee > BigInt(limit)) throw new Error(`Exceeded maximum fee cost for ${op} operation.`)\n }\n\n /**\n * Checks → seqno → preflight → signed body. The preflight runs on the\n * zero-signed body (ignore_chksig), so nothing is signed before it passes.\n */\n private async prepare(messages: V5R1Message[], limit: bigint | number | undefined, op: string): Promise<{ body: Cell; fee: bigint }> {\n // The wallet sends with IGNORE_ERRORS: a message whose value exceeds the\n // balance is silently dropped by the action phase — the external still\n // \"succeeds\", the seqno moves, the fee is paid and nothing leaves\n // (2026-10-09: a 2 GRAM deposit on a 0.46 GRAM balance). Refuse up front,\n // and again after emulation if the risk shows less TON leaving than asked.\n const want = messages.reduce((sum, m) => sum + (m.message.info.type === 'internal' ? m.message.info.value.coins : 0n), 0n)\n if (want > 0n) {\n const balance = await this.getBalance()\n if (balance < want) throw new UnsafeTransactionError('insufficient-balance', `Insufficient TON balance: the messages carry ${want} nanotons, the wallet holds ${balance} (fees come on top).`)\n }\n const { signing } = await this.signingCell(messages)\n const fee = await this.preflight(v5r1PackUnsigned(signing), limit, op, want)\n const signature = await this.signer.sign(new Uint8Array(signing.hash()), { scheme: 'ed25519', context: 'ton-external' })\n return { body: v5r1PackSigned(signing, signature), fee }\n }\n\n private async preflight(body: Cell, limit: bigint | number | undefined, op: string, expectedTonOut?: bigint): Promise<bigint> {\n if (this._config.simulate === false) {\n if (limit === undefined) return 0n\n const fee = (await this.estimateFees(body)).total\n this.checkMaxFee(fee, limit, op)\n return fee\n }\n const sim = await this.simulateBody(body)\n if (!sim.ok) throw new SimulationError(sim.reason, { ...(sim.exitCode !== undefined ? { exitCode: sim.exitCode } : {}), ...(sim.aborted !== undefined ? { aborted: sim.aborted } : {}) })\n if (sim.risk?.transferAllRemainingBalance && this._config.allowDrainingTransactions !== true) {\n throw new UnsafeTransactionError('drain', 'Refusing a message that carries the whole remaining balance (send mode 128); set allowDrainingTransactions to override.')\n }\n if (expectedTonOut !== undefined && sim.risk && sim.risk.ton < expectedTonOut) {\n throw new SimulationError(`The emulation shows only ${sim.risk.ton} nanotons leaving the wallet for messages carrying ${expectedTonOut}: a message would be dropped (insufficient balance for value + fees).`)\n }\n this.checkMaxFee(sim.fees.total, limit, op)\n return sim.fees.total\n }\n\n /** Sign without broadcasting. Returns the external-message BODY as base64 BoC (pass it back to sendTransaction as a Cell). */\n async signTransaction(tx: TonSendable, options: WriteOptions = {}): Promise<string> {\n if (tx instanceof Cell) {\n await this.preflight(tx, feeLimit(this._config.transactionMaxFee, options), 'transaction')\n return tx.toBoc().toString('base64')\n }\n const { body } = await this.prepare(this.toMessages(tx), feeLimit(this._config.transactionMaxFee, options), 'transaction')\n return body.toBoc().toString('base64')\n }\n\n private async broadcast(body: Cell): Promise<string> {\n const rpc = this.requireRpc('send transactions')\n const init = await this.initIfNeeded()\n await rpc.sendBoc(v5r1ExternalMessage(this._address, body, init))\n return body.hash().toString('hex')\n }\n\n /** Sign and broadcast; `hash` is the body hash (hex) — resolve it with getTransactionReceipt. */\n async sendTransaction(tx: TonSendable, options: WriteOptions = {}): Promise<TransferResult> {\n this.requireRpc('send transactions')\n const { body, fee } = tx instanceof Cell\n ? { body: tx, fee: await this.preflight(tx, feeLimit(this._config.transactionMaxFee, options), 'transaction') }\n : await this.prepare(this.toMessages(tx), feeLimit(this._config.transactionMaxFee, options), 'transaction')\n return { hash: await this.broadcast(body), fee }\n }\n\n /** TON (no `token`) or jetton transfer. */\n async transfer(o: TonTransferOptions, writeOptions: WriteOptions = {}): Promise<TransferResult> {\n this.requireRpc('transfer tokens')\n const message = o.token ? await this.jettonTransferMessage(o) : this.transactionMessage({ to: o.recipient, value: o.amount, ...(o.memo !== undefined ? { body: o.memo } : {}) })\n const { body, fee } = await this.prepare([message], feeLimit(this._config.transferMaxFee, writeOptions), 'transfer')\n return { hash: await this.broadcast(body), fee }\n }\n\n /** The same wallet as a {@link WalletAccountReadOnlyTon}. */\n toReadOnlyAccount(): IWalletAccountReadOnly {\n this._readOnly ??= new WalletAccountReadOnlyTon(this.publicKey, this._config)\n return this._readOnly\n }\n\n /** Disposes the signer: a local key is zeroized, an external one is released. */\n dispose(): void {\n this.signer.dispose()\n }\n}\n","import { LocalSigner, SignerError, WalletManager, isSeedSigner, zeroize, type FeeRates, type Signer } from '@anywalletkit/core'\nimport { mnemonicToPrivateKey } from '@ton/crypto'\nimport { WalletAccountTon } from './account.js'\nimport { WalletAccountReadOnlyTon } from './read-only-account.js'\nimport type { TonConfig } from './types.js'\n\n/** Base derivation path for BIP-39 seeds; account `i` is at `m/44'/607'/i'`. */\nexport const TON_BASE_PATH = \"m/44'/607'\"\n/** Path label of the account a TON-native (Tonkeeper-style) mnemonic yields — there is exactly one. */\nexport const TON_MNEMONIC_PATH = 'ton-mnemonic'\nimport { DEFAULT_TONAPI } from './emulation.js'\n\n/**\n * One seed → TON accounts at m/44'/607'/i' (SLIP-10 ed25519) on Wallet V5R1 —\n * the derivation Trust Wallet and Ledger use for a BIP-39 phrase. Paths\n * may be relative to m/44'/607' (\"0'\") or full.\n *\n * Built with an ed25519 `Signer` instead of a seed, the manager wraps it:\n * - a derivable `SeedSigner` sitting at `m/44'/607'` yields `getAccount(i)` → `i'` children;\n * - a `SeedSigner` at a leaf, or any external signer, is `getAccount(0)` (path = the\n * signer's path, or 'external'); other indexes/paths throw.\n *\n * Tonkeeper-style 24-word TON mnemonics (not BIP-39) are imported with\n * {@link WalletManagerTon.fromTonMnemonic}; they yield one account at `ton-mnemonic`.\n */\nexport class WalletManagerTon extends WalletManager<WalletAccountTon, TonConfig> {\n constructor(seedOrSigner: string | Uint8Array | Signer, config: TonConfig = {}) {\n super(seedOrSigner, config)\n }\n\n\n /**\n * Import a TON-native mnemonic (24 words, Tonkeeper / Tonhub / MyTonWallet\n * default): PBKDF2 per @ton/crypto, one ed25519 key, one V5R1 account at\n * path `ton-mnemonic` with the address those wallets show.\n */\n static async fromTonMnemonic(words: string[] | string, config: TonConfig = {}): Promise<WalletManagerTon> {\n const list = (Array.isArray(words) ? words : words.trim().split(/\\s+/)).map((w) => w.toLowerCase())\n if (list.length !== 24) throw new Error('A TON mnemonic has 24 words.')\n const pair = await mnemonicToPrivateKey(list)\n const privateKey = new Uint8Array(pair.secretKey.subarray(0, 32)) // nacl secret key = seed || public key\n const publicKey = new Uint8Array(pair.publicKey)\n zeroize(new Uint8Array(pair.secretKey.buffer, pair.secretKey.byteOffset, pair.secretKey.byteLength))\n return new WalletManagerTon(LocalSigner.fromPrivateKey('ed25519', privateKey, publicKey, TON_MNEMONIC_PATH), config)\n }\n\n async getAccount(index = 0): Promise<WalletAccountTon> {\n const external = this.externalSigner()\n if (external && !(isSeedSigner(external) && external.path === TON_BASE_PATH)) {\n // A leaf signer (TON mnemonic, hardware, MPC…) is exactly one account.\n if (index !== 0) throw new SignerError(`This signer yields a single account (index 0); ${index} is not derivable from it.`)\n return this.fromSigner(external, this.singlePath(external))\n }\n return this.getAccountByPath(`${TON_BASE_PATH}/${index}'`)\n }\n\n async getAccountByPath(path: string): Promise<WalletAccountTon> {\n const external = this.externalSigner()\n if (external) {\n const single = this.singlePath(external)\n const full = path === single || path.startsWith('m/') ? path : `${TON_BASE_PATH}/${path}`\n return this.fromSigner(external, full)\n }\n const full = path.startsWith('m/') ? path : `${TON_BASE_PATH}/${path}`\n const cached = this._accounts.get(full)\n if (cached) return cached\n return this.cachedAccount(full, () => {\n const signer = LocalSigner.leafFromSeed(this.seedBytes(), 'ed25519', full)\n return new WalletAccountTon(signer, signer.publicKey, full, this._config)\n })\n }\n\n /** The one path a non-derivable signer answers to: its own, or 'external'. */\n private singlePath(signer: Signer): string {\n return isSeedSigner(signer) ? signer.path : 'external'\n }\n\n /** Resolve `path` against an injected signer: the signer itself, or a child when it can derive there. */\n private async fromSigner(signer: Signer, path: string): Promise<WalletAccountTon> {\n this.requireSigner('ed25519')\n let rel: string | undefined\n let key = this.singlePath(signer)\n if (isSeedSigner(signer)) {\n if (path === signer.path) key = path\n else if (path.startsWith(`${signer.path}/`)) { rel = path.slice(signer.path.length + 1); key = path }\n else throw new SignerError(`This signer yields a single account at path '${signer.path}'; it cannot provide ${path}.`)\n } else if (path !== `${TON_BASE_PATH}/0'` && path !== 'external') {\n throw new SignerError(`An external signer yields a single account; ${path} is not derivable from it.`)\n }\n return this.signerAccount(key, signer, rel, (leaf, publicKey) => new WalletAccountTon(leaf, publicKey, key, this._config))\n }\n\n /** Watch-only account for a public key (hex or bytes) — TON addresses derive from the key, not the other way round. */\n getReadOnlyAccount(publicKey: Uint8Array | string): WalletAccountReadOnlyTon {\n return new WalletAccountReadOnlyTon(publicKey, this._config)\n }\n\n /** Gas price from config param 21 via tonapi (normal = fast there; slow = ×0.8 here). */\n async getFeeRates(): Promise<FeeRates> {\n const doFetch = this._config.fetch ?? globalThis.fetch\n const res = await doFetch(`${this._config.tonApiUrl ?? DEFAULT_TONAPI}/blockchain/config/raw`, { signal: AbortSignal.timeout(this._config.timeoutMs ?? 15_000) })\n const json = (await res.json()) as { config: { config_param21: { gas_limits_prices: { gas_flat_pfx: { other: { gas_prices_ext: { gas_price: number } } } } } } }\n const normal = BigInt(Math.round(json.config.config_param21.gas_limits_prices.gas_flat_pfx.other.gas_prices_ext.gas_price / 65_536))\n return { slow: (normal * 80n) / 100n, normal, fast: normal }\n }\n\n}\n","/**\n * Activity history for TON: a `HistorySource` over tonapi account events\n * (`/v2/accounts/{a}/events`, keyless or with a Bearer key) with toncenter v3\n * (`/api/v3/transactions`) as a reduced fallback.\n *\n * tonapi groups a whole trace (the wallet's message and everything it caused)\n * into one event with typed actions; each action becomes native / jetton\n * transfers and the first contract-level action becomes `call`. The fee is\n * tonapi's `extra` (what the account lost beyond its actions). toncenter sees\n * only the account's own transactions: TON in / out and op codes, no jettons.\n * Addresses are kept raw (`0:…`, lowercase) as both indexers return them;\n * recognizers normalize. `fetch` + `AbortSignal.timeout` only — Hermes-safe.\n */\nimport { Address } from '@ton/core'\nimport { Buffer } from 'buffer'\nimport type { ChainCall, ChainTransfer, ChainTx, HistoryPage, HistoryQuery, HistorySource } from '@anywalletkit/core'\nimport { CAIP2 } from './types.js'\n\n// ── Public types ─────────────────────────────────────────────────────────────\n\nexport type HistoryFetch = (\n input: string,\n init?: { method?: string; headers?: Record<string, string>; signal?: AbortSignal },\n) => Promise<{ ok: boolean; status: number; json(): Promise<unknown> }>\n\n/** Which indexer answered: tonapi events or toncenter v3 transactions. */\nexport type TonHistoryBackend = 'tonapi' | 'toncenter'\n\n/** Options for `createTonHistory`: tonapi first, toncenter v3 as the fallback. */\nexport interface TonHistoryOptions {\n /** tonapi root. Default `https://tonapi.io` (`https://testnet.tonapi.io` on testnet). `null` disables tonapi. */\n tonapiUrl?: string | null\n /** tonapi Bearer key. Keyless tonapi allows ~1 request/s. */\n apiKey?: string\n /** toncenter root for the v3 fallback. Default `https://toncenter.com` (`https://testnet.toncenter.com`). `null` disables it. */\n toncenterUrl?: string | null\n /** toncenter `X-API-Key`. */\n toncenterApiKey?: string\n network?: 'mainnet' | 'testnet'\n fetch?: HistoryFetch\n /** tonapi requests per second. Default 1 without a key, 10 with one. */\n rateLimit?: number\n /** Per request, ms. Default 15 000. */\n timeoutMs?: number\n}\n\nexport interface TonHistoryRaw {\n backend: TonHistoryBackend\n /** The tonapi account event, or the toncenter v3 transaction row. */\n event: unknown\n /** tonapi flagged the event as scam. */\n scam?: boolean\n /** tonapi `value_flow` for the account when it had to be fetched to recover jetton movements. */\n valueFlow?: unknown\n}\n\nexport interface TonChainTx extends ChainTx {\n /** Mirrors `raw.scam`; the app hides these by default. */\n scam?: boolean\n raw: TonHistoryRaw\n}\n\nexport interface TonHistoryPage extends HistoryPage {\n items: TonChainTx[]\n backend?: TonHistoryBackend\n}\n\n/**\n * TON history from tonapi events with a toncenter v3 fallback. Build it with `createTonHistory`.\n */\nexport interface TonHistorySource extends HistorySource {\n listActivity(address: string, query?: HistoryQuery): Promise<TonHistoryPage>\n getTransaction(hash: string, address: string): Promise<TonChainTx | undefined>\n}\n\n/** Every configured history backend failed (or none was configured). */\nexport class HistoryUnavailableError extends Error {\n readonly chain: string\n readonly reason: string\n readonly attempts: readonly string[]\n constructor(chain: string, reason: string, attempts: readonly string[] = []) {\n super(`History unavailable for ${chain}: ${reason}`)\n this.name = 'HistoryUnavailableError'\n this.chain = chain\n this.reason = reason\n this.attempts = attempts\n }\n}\n\nconst DEFAULT_LIMIT = 25\nconst MAX_LIMIT = 100\nconst DEFAULT_TIMEOUT_MS = 15_000\n\n// ── Cursor: an exclusive `lt` upper bound, base64 JSON ───────────────────────\n\nexport interface TonHistoryCursor {\n v: 1\n b: TonHistoryBackend\n /** Next page = events / transactions with `lt < this` (decimal string). */\n lt: string\n}\n\nexport function encodeCursor(c: TonHistoryCursor): string {\n return Buffer.from(JSON.stringify(c), 'utf8').toString('base64')\n}\n\nexport function decodeCursor(s: string): TonHistoryCursor {\n let parsed: unknown\n try {\n parsed = JSON.parse(Buffer.from(s, 'base64').toString('utf8'))\n } catch {\n throw new Error('@anywalletkit/wallet-ton: malformed history cursor')\n }\n const c = parsed as Partial<TonHistoryCursor> | null\n if (!c || c.v !== 1 || (c.b !== 'tonapi' && c.b !== 'toncenter') || typeof c.lt !== 'string' || !/^\\d+$/.test(c.lt)) {\n throw new Error('@anywalletkit/wallet-ton: malformed history cursor')\n }\n return { v: 1, b: c.b, lt: c.lt }\n}\n\n// ── Helpers ──────────────────────────────────────────────────────────────────\n\nclass TokenBucket {\n private tokens: number\n private last = Date.now()\n private chain: Promise<void> = Promise.resolve()\n constructor(private readonly rate: number, private readonly burst = Math.max(1, Math.ceil(rate))) {\n this.tokens = burst\n }\n acquire(): Promise<void> {\n const next = this.chain.then(() => this.take())\n this.chain = next.catch(() => undefined)\n return next\n }\n private refill(): void {\n const now = Date.now()\n this.tokens = Math.min(this.burst, this.tokens + ((now - this.last) / 1000) * this.rate)\n this.last = now\n }\n private async take(): Promise<void> {\n this.refill()\n if (this.tokens >= 1) {\n this.tokens -= 1\n return\n }\n await new Promise((r) => setTimeout(r, Math.ceil(((1 - this.tokens) / this.rate) * 1000)))\n this.refill()\n this.tokens = Math.max(0, this.tokens - 1)\n }\n}\n\nfunction timeoutSignal(ms: number): AbortSignal | undefined {\n const ctor = (globalThis as { AbortSignal?: { timeout?: (ms: number) => AbortSignal } }).AbortSignal\n return typeof ctor?.timeout === 'function' ? ctor.timeout(ms) : undefined\n}\n\n/** Any spelling → raw lowercase `wc:hex`; unparsable input is returned as-is. */\nexport function rawTonAddress(a: string): string {\n try {\n return Address.parse(a).toRawString().toLowerCase()\n } catch {\n return a.toLowerCase()\n }\n}\n\nconst big = (v: unknown): bigint => {\n if (typeof v === 'bigint') return v\n if (typeof v === 'number' && Number.isFinite(v)) return BigInt(Math.trunc(v))\n if (typeof v === 'string' && /^-?\\d+$/.test(v)) return BigInt(v)\n return 0n\n}\n\nconst isHexOp = (s: unknown): s is string => typeof s === 'string' && /^0x[0-9a-f]{1,8}$/i.test(s)\n\n// ── tonapi shapes (what the mapper reads) ────────────────────────────────────\n\ninterface TonapiAccount { address: string; is_wallet?: boolean; is_scam?: boolean; name?: string }\ninterface TonapiJetton { address: string; symbol?: string; decimals?: number; name?: string }\nexport interface TonapiAction {\n type: string\n status: 'ok' | 'failed' | string\n [body: string]: unknown\n}\nexport interface TonapiEvent {\n event_id: string\n account?: TonapiAccount\n timestamp: number\n lt: number | string\n in_progress: boolean\n is_scam: boolean\n actions: TonapiAction[]\n /** Account-scoped events only: TON the account lost beyond its actions (negative = fees). */\n extra?: number\n value_flow?: Array<{ account: TonapiAccount; ton: number; jettons?: Array<{ jetton: TonapiJetton; quantity: number | string }> }>\n}\n\ninterface MappedActions {\n transfers: ChainTransfer[]\n call?: ChainCall\n /** Who initiated the event as far as the first action tells. */\n initiator?: string\n /** The event needs `value_flow` to recover a jetton movement tonapi did not spell out (unstake requests). */\n needsValueFlow?: { counterparty: string }\n}\n\nconst jettonMeta = (j: TonapiJetton | undefined): Pick<ChainTransfer, 'symbol' | 'decimals'> => {\n const m: Pick<ChainTransfer, 'symbol' | 'decimals'> = {}\n if (j?.symbol !== undefined) m.symbol = j.symbol\n if (j?.decimals !== undefined) m.decimals = j.decimals\n return m\n}\n\nconst addr = (a: unknown): string | undefined => (typeof a === 'object' && a !== null && typeof (a as TonapiAccount).address === 'string' ? (a as TonapiAccount).address.toLowerCase() : typeof a === 'string' ? a.toLowerCase() : undefined)\nconst isWallet = (a: unknown): boolean => typeof a === 'object' && a !== null && (a as TonapiAccount).is_wallet === true\n\n/** tonapi actions → transfers + the contract call. Only `ok` actions move value. */\nexport function mapActions(actions: TonapiAction[]): MappedActions {\n const out: MappedActions = { transfers: [] }\n const native = (from: string | undefined, to: string | undefined, amount: bigint) => {\n if (from === undefined || to === undefined || amount <= 0n) return\n out.transfers.push({ token: null, from, to, amount })\n }\n const jetton = (j: TonapiJetton | undefined, from: string | undefined, to: string | undefined, amount: bigint) => {\n if (!j || from === undefined || to === undefined || amount <= 0n) return\n out.transfers.push({ token: j.address.toLowerCase(), from, to, amount, standard: 'jetton', ...jettonMeta(j) })\n }\n const setCall = (c: ChainCall | undefined) => {\n if (c && !out.call) out.call = c\n }\n const init = (a: string | undefined) => {\n if (out.initiator === undefined && a !== undefined) out.initiator = a\n }\n for (const a of actions) {\n const b = (a[a.type] ?? {}) as Record<string, unknown>\n const ok = a.status === 'ok'\n switch (a.type) {\n case 'TonTransfer': {\n const from = addr(b.sender), to = addr(b.recipient)\n init(from)\n if (ok) native(from, to, big(b.amount))\n break\n }\n case 'JettonTransfer': {\n const from = addr(b.sender) ?? addr(b.senders_wallet), to = addr(b.recipient) ?? addr(b.recipients_wallet)\n init(from)\n if (ok) jetton(b.jetton as TonapiJetton, from, to, big(b.amount))\n // A jetton sent to a contract with a forward payload is a call; tonapi surfaces the op as \"Call: 0x…\".\n if (to !== undefined && b.recipient !== undefined && !isWallet(b.recipient)) {\n const c: ChainCall = { to, method: 'jetton_transfer' }\n const m = typeof b.comment === 'string' ? /^Call:\\s*(0x[0-9a-f]+)/i.exec(b.comment) : null\n if (m) c.data = m[1]!.toLowerCase()\n setCall(c)\n }\n break\n }\n case 'JettonMint': {\n const j = b.jetton as TonapiJetton | undefined\n if (ok) jetton(j, j?.address.toLowerCase(), addr(b.recipient) ?? addr(b.recipients_wallet), big(b.amount))\n break\n }\n case 'JettonBurn': {\n const j = b.jetton as TonapiJetton | undefined\n const from = addr(b.sender) ?? addr(b.senders_wallet)\n init(from)\n if (ok) jetton(j, from, j?.address.toLowerCase(), big(b.amount))\n setCall(j ? { to: j.address.toLowerCase(), method: 'jetton_burn' } : undefined)\n break\n }\n case 'JettonSwap': {\n const user = addr(b.user_wallet), router = addr(b.router)\n init(user)\n if (ok) {\n native(user, router, big(b.ton_in))\n jetton(b.jetton_master_in as TonapiJetton | undefined, user, router, big(b.amount_in))\n native(router, user, big(b.ton_out))\n jetton(b.jetton_master_out as TonapiJetton | undefined, router, user, big(b.amount_out))\n }\n if (router !== undefined) setCall({ to: router, method: 'swap' })\n break\n }\n case 'SmartContractExec': {\n const executor = addr(b.executor), contract = addr(b.contract)\n init(executor)\n if (ok) native(executor, contract, big(b.ton_attached))\n if (contract !== undefined) {\n const c: ChainCall = { to: contract }\n if (isHexOp(b.operation)) c.data = b.operation.toLowerCase()\n else if (typeof b.operation === 'string' && b.operation) c.method = b.operation\n setCall(c)\n }\n break\n }\n case 'DepositStake': {\n const staker = addr(b.staker), pool = addr(b.pool)\n init(staker)\n if (ok) native(staker, pool, big(b.amount))\n if (pool !== undefined) setCall({ to: pool, method: 'stake' })\n break\n }\n case 'WithdrawStakeRequest': {\n const staker = addr(b.staker), pool = addr(b.pool)\n init(staker)\n if (ok && b.amount !== undefined) native(staker, pool, big(b.amount))\n if (pool !== undefined) {\n setCall({ to: pool, method: 'unstake' })\n // tonapi does not spell out the pool-token burn; `value_flow` has it.\n if (ok) out.needsValueFlow ??= { counterparty: pool }\n }\n break\n }\n case 'WithdrawStake': {\n const staker = addr(b.staker), pool = addr(b.pool)\n init(pool)\n if (ok) native(pool, staker, big(b.amount))\n if (pool !== undefined) setCall({ to: pool, method: 'withdraw_stake' })\n break\n }\n case 'ElectionsDepositStake':\n case 'ElectionsRecoverStake': {\n const staker = addr(b.staker)\n init(staker)\n // The elector has no address in the action; keep the movement against the elector pseudo-account.\n if (ok) a.type === 'ElectionsDepositStake' ? native(staker, '-1:3333333333333333333333333333333333333333333333333333333333333333', big(b.amount)) : native('-1:3333333333333333333333333333333333333333333333333333333333333333', staker, big(b.amount))\n break\n }\n case 'Subscribe':\n case 'UnSubscribe': {\n const subscriber = addr(b.subscriber), beneficiary = addr(b.beneficiary), subscription = addr(b.subscription)\n init(subscriber)\n if (ok && a.type === 'Subscribe') native(subscriber, beneficiary, big(b.amount))\n if (subscription !== undefined) setCall({ to: subscription, method: a.type === 'Subscribe' ? 'subscribe' : 'unsubscribe' })\n break\n }\n case 'NftPurchase': {\n const buyer = addr(b.buyer), seller = addr(b.seller), nft = addr(b.nft)\n init(buyer)\n if (ok) native(buyer, seller, big((b.amount as { value?: unknown } | undefined)?.value ?? b.amount))\n if (nft !== undefined) setCall({ to: nft, method: 'nft_purchase' })\n break\n }\n case 'ContractDeploy': {\n const deployed = addr(b.address)\n if (deployed !== undefined) setCall({ to: deployed, method: 'deploy' })\n break\n }\n default:\n // NftItemTransfer, AuctionBid, DomainRenew, Unknown…: nothing to account for.\n break\n }\n }\n return out\n}\n\n/** The account's jetton deltas from `value_flow` as transfers against `counterparty`. */\nexport function valueFlowTransfers(event: TonapiEvent, own: string, counterparty: string): ChainTransfer[] {\n const flow = event.value_flow?.find((v) => addr(v.account) === own)\n const out: ChainTransfer[] = []\n for (const j of flow?.jettons ?? []) {\n const q = big(j.quantity)\n if (q === 0n) continue\n const t: ChainTransfer = { token: j.jetton.address.toLowerCase(), from: q < 0n ? own : counterparty, to: q < 0n ? counterparty : own, amount: q < 0n ? -q : q, standard: 'jetton', ...jettonMeta(j.jetton) }\n out.push(t)\n }\n return out\n}\n\nexport function mapTonapiEvent(chain: string, address: string, own: string, event: TonapiEvent, valueFlow?: TonapiEvent): TonChainTx {\n const mapped = mapActions(event.actions ?? [])\n const transfers = mapped.transfers\n const raw: TonHistoryRaw = { backend: 'tonapi', event }\n if (mapped.needsValueFlow && valueFlow) {\n raw.valueFlow = valueFlow.value_flow\n const extra = valueFlowTransfers(valueFlow, own, mapped.needsValueFlow.counterparty)\n for (const t of extra) if (!transfers.some((x) => x.token === t.token && x.from === t.from && x.to === t.to && x.amount === t.amount)) transfers.push(t)\n }\n const from = mapped.initiator ?? own\n const involves = (t: ChainTransfer) => t.from === own || t.to === own\n const primary = transfers.find((t) => t.token !== null && involves(t)) ?? transfers.find(involves) ?? transfers[0]\n const to = mapped.call?.to ?? primary?.to ?? null\n let nativeValue = 0n\n for (const t of transfers) if (t.token === null && t.from === from) nativeValue += t.amount\n const actions = event.actions ?? []\n const status: ChainTx['status'] = event.in_progress ? 'pending' : actions.length > 0 && actions.every((a) => a.status !== 'ok') ? 'failed' : 'confirmed'\n const out: TonChainTx = {\n chain, hash: event.event_id, time: event.timestamp, status, address, from, to, nativeValue, transfers, block: big(event.lt), raw,\n }\n if (typeof event.extra === 'number' && event.extra < 0) out.fee = BigInt(-event.extra)\n if (mapped.call) out.call = mapped.call\n if (event.is_scam) {\n out.scam = true\n raw.scam = true\n }\n return out\n}\n\n// ── toncenter v3 shapes ──────────────────────────────────────────────────────\n\ninterface V3Message {\n source?: string | null\n destination?: string | null\n value?: string | null\n opcode?: string | null\n decoded_opcode?: string | null\n}\nexport interface V3Transaction {\n account: string\n /** base64. */\n hash: string\n lt: string\n now: number\n total_fees: string\n description?: { aborted?: boolean; compute_ph?: { success?: boolean; exit_code?: number; skipped?: boolean }; action?: { success?: boolean } }\n in_msg?: V3Message | null\n out_msgs?: V3Message[]\n}\n\nconst TEXT_COMMENT_OP = '0x00000000'\n\n/** Reduced mapping: TON in / out and op codes of the account's own transaction; jettons are not visible here. */\nexport function mapToncenterTransaction(chain: string, address: string, row: V3Transaction): TonChainTx {\n const own = row.account.toLowerCase()\n const hash = Buffer.from(row.hash, 'base64').toString('hex')\n const d = row.description\n const failed = d?.aborted === true || (d?.compute_ph?.skipped !== true && d?.compute_ph?.success === false) || d?.action?.success === false\n const transfers: ChainTransfer[] = []\n let from = own\n let to: string | null = null\n let call: ChainCall | undefined\n const source = row.in_msg?.source ? row.in_msg.source.toLowerCase() : undefined\n if (source === undefined) {\n // External message: the wallet acted. Its outgoing messages are the transfers.\n for (const m of row.out_msgs ?? []) {\n const dest = m.destination?.toLowerCase()\n if (!dest) continue\n const value = big(m.value)\n if (value > 0n) transfers.push({ token: null, from: own, to: dest, amount: value })\n if (!call && m.opcode && m.opcode !== TEXT_COMMENT_OP) {\n call = { to: dest, data: m.opcode.toLowerCase() }\n if (m.decoded_opcode) call.method = m.decoded_opcode\n }\n to ??= dest\n }\n } else {\n from = source\n to = own\n const value = big(row.in_msg?.value)\n if (value > 0n) transfers.push({ token: null, from: source, to: own, amount: value })\n const op = row.in_msg?.opcode\n if (op && op !== TEXT_COMMENT_OP) {\n call = { to: own, data: op.toLowerCase() }\n if (row.in_msg?.decoded_opcode) call.method = row.in_msg.decoded_opcode\n }\n }\n let nativeValue = 0n\n for (const t of transfers) if (t.token === null && t.from === from) nativeValue += t.amount\n const out: TonChainTx = {\n chain, hash, time: row.now, status: failed ? 'failed' : 'confirmed', address, from, to: call?.to ?? to, nativeValue, transfers, fee: big(row.total_fees), block: big(row.lt),\n raw: { backend: 'toncenter', event: row },\n }\n if (call) out.call = call\n return out\n}\n\n// ── Source ───────────────────────────────────────────────────────────────────\n\n/** Tonviewer link for a transaction. */\nexport function tonExplorerTxUrl(hash: string, network: 'mainnet' | 'testnet' = 'mainnet'): string {\n return `https://${network === 'testnet' ? 'testnet.' : ''}tonviewer.com/transaction/${hash}`\n}\n\n/**\n * A `HistorySource` for TON: tonapi account events first, toncenter v3 when\n * tonapi is down or disabled. Both page by `lt`, so a cursor from one backend\n * resumes on the other.\n */\nexport function createTonHistory(options: TonHistoryOptions = {}): TonHistorySource {\n const network = options.network ?? 'mainnet'\n const chain = CAIP2[network]\n const fetchFn: HistoryFetch = options.fetch ?? ((globalThis as { fetch?: HistoryFetch }).fetch as HistoryFetch)\n if (typeof fetchFn !== 'function') throw new Error('@anywalletkit/wallet-ton: no global fetch; pass `fetch` in the options')\n const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS\n const tonapiUrl = options.tonapiUrl === null ? undefined : (options.tonapiUrl ?? (network === 'testnet' ? 'https://testnet.tonapi.io' : 'https://tonapi.io')).replace(/\\/+$/, '')\n const toncenterUrl = options.toncenterUrl === null ? undefined : (options.toncenterUrl ?? (network === 'testnet' ? 'https://testnet.toncenter.com' : 'https://toncenter.com')).replace(/\\/+$/, '')\n if (!tonapiUrl && !toncenterUrl) throw new Error('@anywalletkit/wallet-ton: createTonHistory needs tonapi or toncenter')\n const tonapiBucket = new TokenBucket(options.rateLimit ?? (options.apiKey ? 10 : 1))\n const toncenterBucket = new TokenBucket(options.toncenterApiKey ? 10 : 1)\n\n async function getJson(backend: TonHistoryBackend, url: string, headers: Record<string, string>): Promise<{ status: number; body: unknown }> {\n await (backend === 'tonapi' ? tonapiBucket : toncenterBucket).acquire()\n let res: Awaited<ReturnType<HistoryFetch>>\n try {\n const signal = timeoutSignal(timeoutMs)\n res = await fetchFn(url, { headers: { accept: 'application/json', ...headers }, ...(signal ? { signal } : {}) })\n } catch (e) {\n throw new Error(`${backend}: ${e instanceof Error ? e.message : String(e)}`)\n }\n let body: unknown\n try {\n body = await res.json()\n } catch {\n body = undefined\n }\n return { status: res.status, body }\n }\n\n const tonapiHeaders = () => (options.apiKey ? { authorization: `Bearer ${options.apiKey}` } : {})\n const toncenterHeaders = () => (options.toncenterApiKey ? { 'x-api-key': options.toncenterApiKey } : {})\n\n const fail = (backend: TonHistoryBackend, r: { status: number; body: unknown }): never => {\n const msg = typeof r.body === 'object' && r.body !== null && typeof (r.body as { error?: unknown }).error === 'string' ? (r.body as { error: string }).error : ''\n throw new Error(`${backend}: HTTP ${r.status}${msg ? ` ${msg}` : ''}`)\n }\n\n async function tonapiEventFull(eventId: string): Promise<TonapiEvent | undefined> {\n const r = await getJson('tonapi', `${tonapiUrl}/v2/events/${eventId}`, tonapiHeaders())\n if (r.status === 404) return undefined\n if (r.status !== 200) fail('tonapi', r)\n return r.body as TonapiEvent\n }\n\n async function finishTonapi(address: string, own: string, event: TonapiEvent): Promise<TonChainTx> {\n const probe = mapActions(event.actions ?? [])\n let flow: TonapiEvent | undefined\n if (probe.needsValueFlow) {\n try {\n flow = await tonapiEventFull(event.event_id)\n } catch {\n flow = undefined // best effort: the row still carries the call\n }\n }\n return mapTonapiEvent(chain, address, own, event, flow)\n }\n\n async function tonapiPage(address: string, own: string, limit: number, before?: string): Promise<TonHistoryPage> {\n if (!tonapiUrl) throw new Error('tonapi: disabled')\n const q = `limit=${limit}${before ? `&before_lt=${before}` : ''}`\n const r = await getJson('tonapi', `${tonapiUrl}/v2/accounts/${encodeURIComponent(address)}/events?${q}`, tonapiHeaders())\n if (r.status !== 200) fail('tonapi', r)\n const body = r.body as { events?: TonapiEvent[]; next_from?: number | string } | undefined\n const events = body?.events ?? []\n const items: TonChainTx[] = []\n for (const e of events) items.push(await finishTonapi(address, own, e))\n const page: TonHistoryPage = { items, backend: 'tonapi' }\n if (events.length >= limit) {\n const last = events[events.length - 1]!\n page.cursor = encodeCursor({ v: 1, b: 'tonapi', lt: String(body?.next_from ?? last.lt) })\n }\n return page\n }\n\n async function toncenterPage(address: string, limit: number, before?: string): Promise<TonHistoryPage> {\n if (!toncenterUrl) throw new Error('toncenter: disabled')\n const endLt = before ? (BigInt(before) - 1n).toString() : undefined\n const q = `account=${encodeURIComponent(address)}&limit=${limit}&sort=desc${endLt ? `&end_lt=${endLt}` : ''}`\n const r = await getJson('toncenter', `${toncenterUrl}/api/v3/transactions?${q}`, toncenterHeaders())\n if (r.status !== 200) fail('toncenter', r)\n const rows = (r.body as { transactions?: V3Transaction[] } | undefined)?.transactions ?? []\n const items = rows.map((row) => mapToncenterTransaction(chain, address, row))\n const page: TonHistoryPage = { items, backend: 'toncenter' }\n if (rows.length >= limit) page.cursor = encodeCursor({ v: 1, b: 'toncenter', lt: rows[rows.length - 1]!.lt })\n return page\n }\n\n const backends: TonHistoryBackend[] = [...(tonapiUrl ? ['tonapi' as const] : []), ...(toncenterUrl ? ['toncenter' as const] : [])]\n\n return {\n chain,\n\n async listActivity(address: string, query: HistoryQuery = {}): Promise<TonHistoryPage> {\n const limit = Math.min(MAX_LIMIT, Math.max(1, Math.floor(query.limit ?? DEFAULT_LIMIT)))\n const cursor = query.cursor ? decodeCursor(query.cursor) : undefined\n const own = rawTonAddress(address)\n const ordered = cursor ? [...backends].sort((a, b) => (a === cursor.b ? -1 : b === cursor.b ? 1 : 0)) : backends\n const attempts: string[] = []\n for (const b of ordered) {\n try {\n let page = b === 'tonapi' ? await tonapiPage(address, own, limit, cursor?.lt) : await toncenterPage(address, limit, cursor?.lt)\n if (query.since !== undefined) {\n const since = query.since\n if (page.items.some((t) => t.time < since)) delete page.cursor\n page = { ...page, items: page.items.filter((t) => t.time >= since) }\n }\n return page\n } catch (e) {\n attempts.push(e instanceof Error ? e.message : String(e))\n }\n }\n throw new HistoryUnavailableError(chain, attempts[attempts.length - 1] ?? 'no backend configured', attempts)\n },\n\n async getTransaction(hash: string, address: string): Promise<TonChainTx | undefined> {\n const own = rawTonAddress(address)\n const attempts: string[] = []\n for (const b of backends) {\n try {\n if (b === 'tonapi') {\n const r = await getJson('tonapi', `${tonapiUrl}/v2/accounts/${encodeURIComponent(address)}/events/${encodeURIComponent(hash)}`, tonapiHeaders())\n if (r.status === 404) return undefined\n if (r.status !== 200) fail('tonapi', r)\n return await finishTonapi(address, own, r.body as TonapiEvent)\n }\n const r = await getJson('toncenter', `${toncenterUrl}/api/v3/transactions?hash=${encodeURIComponent(hash)}`, toncenterHeaders())\n if (r.status !== 200) fail('toncenter', r)\n const rows = (r.body as { transactions?: V3Transaction[] } | undefined)?.transactions ?? []\n const row = rows.find((x) => x.account.toLowerCase() === own) ?? rows[0]\n return row ? mapToncenterTransaction(chain, address, row) : undefined\n } catch (e) {\n attempts.push(e instanceof Error ? e.message : String(e))\n }\n }\n throw new HistoryUnavailableError(chain, attempts[attempts.length - 1] ?? 'no backend configured', attempts)\n },\n\n explorerTxUrl(hash: string): string {\n return tonExplorerTxUrl(hash, network)\n },\n }\n}\n"],"mappings":";;;;;;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C;AACvE,iBAAO,MAAM,wBAAwB,OAAO,SAAS,GAAG,IAAI;AAAA,QAC9D,SAAS,GAAG;AACV,mBAAS,KAAK,aAAa,QAAQ,EAAE,UAAU,OAAO,CAAC,CAAC;AAAA,QAC1D;AAAA,MACF;AACA,YAAM,IAAI,wBAAwB,OAAO,SAAS,SAAS,SAAS,CAAC,KAAK,yBAAyB,QAAQ;AAAA,IAC7G;AAAA,IAEA,cAAc,MAAsB;AAClC,aAAO,iBAAiB,MAAM,OAAO;AAAA,IACvC;AAAA,EACF;AACF;;;AXxmBA,oBAAoB;","names":["import_core","import_buffer","import_core","DEFAULT_TIMEOUT_MS","big","verdict","import_buffer","import_core","import_core","external","import_core","JETTON_TRANSFER_OP","import_core","import_core","external","full","import_core","import_buffer","DEFAULT_TIMEOUT_MS","big","r"]}
|