presign-guard-wallet 0.3.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -65,7 +65,7 @@ try {
65
65
  | `signers` | presign-guard's published signer | Accepted signer addresses |
66
66
  | `authority` | the Fizzl payout wallet | Wallet whose certificates also make a signer trusted (key rotation); `null` accepts only `signers` |
67
67
  | `limits` | | Spending limits per token, see [Spending limits](#spending-limits) |
68
- | `onOverLimit` | | `async (info) => boolean`: asked when a limit would be crossed; `true` signs anyway. Without it the wallet stops |
68
+ | `onOverLimit` | | `async (info) => boolean`: asked when a limit would be crossed; `true` signs anyway. Without it the wallet stops. Ready-made: [`telegramApprover`](#approve-from-your-phone-telegram) |
69
69
  | `onSpend` | | `(entry) => void` after each signed spend, e.g. for a log |
70
70
  | `store` | in memory | Where spending is kept; `fileStore(path)` from `presign-guard-wallet/file-store`, or your own |
71
71
 
@@ -128,6 +128,46 @@ Other contract calls (a swap that uses an allowance you already gave) spend noth
128
128
 
129
129
  These limits live in your agent's software: they stop a confused or manipulated agent, not someone who has the private key. For limits the chain enforces, use a smart account with session keys; the same budget can then be set there.
130
130
 
131
+ ### Approve from your phone (Telegram)
132
+
133
+ `onOverLimit` can be a Telegram bot: when a signature would cross a limit, you get a message with what the agent wants to sign, why it is over the limit and presign-guard's verdict, with **Approve** and **Deny** buttons. The agent waits for your tap.
134
+
135
+ 1. In Telegram, talk to [@BotFather](https://t.me/BotFather), send `/newbot` and keep the token it gives you secret (an environment variable, never in code).
136
+ 2. Send your new bot `/start`, then find your chat id:
137
+ ```bash
138
+ TELEGRAM_BOT_TOKEN=... node -e 'import("presign-guard-wallet/telegram").then(async (t) => console.log(await t.findTelegramChats({ token: process.env.TELEGRAM_BOT_TOKEN })))'
139
+ ```
140
+ 3. Use it:
141
+ ```js
142
+ import { telegramApprover } from "presign-guard-wallet/telegram";
143
+
144
+ const wallet = guardWallet(walletClient, {
145
+ pay,
146
+ limits: { tokens: { USDC: { perTx: "5", perDay: "20" } } },
147
+ onOverLimit: telegramApprover({
148
+ token: process.env.TELEGRAM_BOT_TOKEN,
149
+ chatId: process.env.TELEGRAM_CHAT_ID,
150
+ label: "research-agent",
151
+ timeoutMs: 10 * 60_000, // no answer in 10 minutes = Deny
152
+ }),
153
+ });
154
+ ```
155
+
156
+ Only the chat you name (or the `allowedUserIds` you list) can answer; anyone else's tap is refused. No server is needed: the wallet asks Telegram for your tap itself (long polling), so the bot must not have a webhook, and one bot serves one agent process at a time (a second process polling the same bot makes Telegram refuse both; the request then fails and nothing is signed). If Telegram cannot be reached, the wallet stops (`limit_unavailable`) rather than signing.
157
+
158
+ ### One budget for all your agents (wallet server)
159
+
160
+ With several agents, run the [wallet server](../wallet-server): one price rule and daily budget for all of them, approvals on its dashboard and on Telegram, and an activity log. The agent keeps its keys and still signs and pays itself; it only asks the server first.
161
+
162
+ ```js
163
+ const wallet = guardWallet(walletClient, {
164
+ pay,
165
+ server: { url: process.env.WALLET_SERVER_URL, key: process.env.WALLET_SERVER_KEY }, // instead of limits / onOverLimit / store
166
+ });
167
+ ```
168
+
169
+ If the server can't be reached the wallet stops (`limit_unavailable`); paused on the dashboard means `paused`.
170
+
131
171
  ## Signed verdicts
132
172
 
133
173
  presign-guard signs every paid verdict (EIP-191 over canonical JSON, with a hash of your request inside the signed body; see [Signed verdicts](https://github.com/Fizzl13/presign-guard#signed-verdicts)). The wallet checks that signature before it acts:
package/index.d.ts CHANGED
@@ -138,6 +138,8 @@ export interface GuardOptions {
138
138
  onSpend?: (entry: SpendEntry) => void;
139
139
  /** Where spending is kept. Default in memory (gone on a restart); fileStore from "presign-guard-wallet/file-store" for a file. */
140
140
  store?: SpendingStore;
141
+ /** A wallet server keeps the limits, the shared budget and the approvals for all your agents (instead of limits, onOverLimit and store). */
142
+ server?: { url: string; key: string; fetch?: typeof globalThis.fetch; requestTimeoutMs?: number };
141
143
  }
142
144
 
143
145
  /** The same wallet client; sendTransaction, writeContract and signTypedData are checked first. */
package/index.js CHANGED
@@ -29,13 +29,14 @@
29
29
  import { encodeFunctionData } from "viem";
30
30
  import { verifyReceipt, AUTHORITY } from "x402-safe-fetch";
31
31
  import { createLimiter, memoryStore } from "./limits.js";
32
+ import { createRemoteLimiter } from "./remote.js";
32
33
 
33
34
  export { memoryStore };
34
35
 
35
36
  export const PRESIGN_URL = "https://presign-guard.fizzl.eu";
36
37
  export const PRESIGN_SIGNERS = ["0xf084Ea47Ca4D99BB4De3ECB0332b316bE6521EaE"];
37
38
  export const SUPPORTED_CHAINS = [1, 10, 56, 137, 8453, 42161];
38
- export const VERSION = "0.3.0";
39
+ export const VERSION = "0.5.0";
39
40
  export const CREDIT_HEADER = "x-credit-key";
40
41
  const ROUTE = "POST /v1/check";
41
42
 
@@ -90,6 +91,7 @@ const GUARDED = new Set(["sendTransaction", "writeContract", "signTypedData"]);
90
91
  * @param {object} [options.limits] spending limits: { tokens: { USDC: { perTx, perDay }, … }, unknownTokens, allow, window }
91
92
  * @param {(info: object) => boolean|Promise<boolean>} [options.onOverLimit] asked when a limit would be crossed; true = sign anyway
92
93
  * @param {(entry: object) => void} [options.onSpend] after each signed spend
94
+ * @param {{url: string, key: string}} [options.server] a wallet server (fizzl wallet-server) keeps the limits, budget and approvals for all your agents
93
95
  * @param {object} [options.store] where spending is kept (default in memory; fileStore from presign-guard-wallet/file-store)
94
96
  */
95
97
  export function guardWallet(wallet, {
@@ -108,6 +110,7 @@ export function guardWallet(wallet, {
108
110
  onOverLimit,
109
111
  onSpend,
110
112
  store,
113
+ server,
111
114
  } = {}) {
112
115
  if (!wallet || typeof wallet !== "object") throw new TypeError("wallet must be a viem WalletClient");
113
116
  if (creditKey !== undefined && !/^pgc_[A-Za-z0-9_-]{43}$/.test(String(creditKey))) throw new TypeError("creditKey must be a presign-guard credit key (pgc_…)");
@@ -116,8 +119,10 @@ export function guardWallet(wallet, {
116
119
  if (!["stop", "allow"].includes(onError)) throw new TypeError('onError must be "stop" or "allow"');
117
120
  if (!["require", "off"].includes(verifyReceipts)) throw new TypeError('verifyReceipts must be "require" or "off"');
118
121
 
119
- if (limits === undefined && (onOverLimit || onSpend || store)) throw new TypeError("onOverLimit, onSpend and store need limits");
120
- const limiter = limits === undefined ? null : createLimiter(limits, { store, onOverLimit, onSpend });
122
+ if (server !== undefined && (limits !== undefined || onOverLimit || store)) throw new TypeError("with server, the limits and approvals live on the wallet server: leave out limits, onOverLimit and store");
123
+ if (server === undefined && limits === undefined && (onOverLimit || onSpend || store)) throw new TypeError("onOverLimit, onSpend and store need limits");
124
+ const limiter = server !== undefined ? createRemoteLimiter({ ...server, fetch: server.fetch ?? plainFetch, onSpend })
125
+ : limits === undefined ? null : createLimiter(limits, { store, onOverLimit, onSpend });
121
126
  let paused = false;
122
127
 
123
128
  let creditsLeft = null;
@@ -190,7 +195,7 @@ export function guardWallet(wallet, {
190
195
  throw new PresignBlockedError(`spending limits could not be checked (${err.message}); nothing was signed`, { code: "limit_unavailable", verdict, request });
191
196
  }
192
197
  if (!booked.ok) {
193
- const err = new PresignBlockedError(`not signed: ${booked.summary}`, { code: "over_limit", verdict, request });
198
+ const err = new PresignBlockedError(`not signed: ${booked.summary}`, { code: booked.paused ? "paused" : "over_limit", verdict, request });
194
199
  err.reasons = booked.reasons;
195
200
  throw err;
196
201
  }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "presign-guard-wallet",
3
- "version": "0.3.0",
4
- "description": "A viem wallet for AI agents that asks presign-guard ($0.01 over x402) before every transaction, contract write and typed-data signature, refuses to sign red, and keeps to per-token spending limits.",
3
+ "version": "0.5.0",
4
+ "description": "A viem wallet for AI agents that asks presign-guard ($0.01 over x402) before every transaction, contract write and typed-data signature, refuses to sign red, and keeps to per-token spending limits, with approval from your phone over the limit.",
5
5
  "type": "module",
6
6
  "exports": {
7
7
  ".": {
@@ -11,6 +11,13 @@
11
11
  "./file-store": {
12
12
  "types": "./file-store.d.ts",
13
13
  "default": "./file-store.js"
14
+ },
15
+ "./telegram": {
16
+ "types": "./telegram.d.ts",
17
+ "default": "./telegram.js"
18
+ },
19
+ "./limits": {
20
+ "default": "./limits.js"
14
21
  }
15
22
  },
16
23
  "main": "./index.js",
@@ -21,6 +28,9 @@
21
28
  "limits.js",
22
29
  "file-store.js",
23
30
  "file-store.d.ts",
31
+ "telegram.js",
32
+ "remote.js",
33
+ "telegram.d.ts",
24
34
  "README.md",
25
35
  "LICENSE"
26
36
  ],
@@ -53,7 +63,9 @@
53
63
  "drainer",
54
64
  "usdc",
55
65
  "spending-limits",
56
- "budget"
66
+ "budget",
67
+ "telegram",
68
+ "human-in-the-loop"
57
69
  ],
58
70
  "repository": {
59
71
  "type": "git",
package/remote.js ADDED
@@ -0,0 +1,50 @@
1
+ // Limits kept by a wallet server instead of in this process: one budget and
2
+ // one set of rules for all of an owner's agents, approvals on the server's
3
+ // dashboard or Telegram. Same interface as createLimiter in limits.js.
4
+ //
5
+ // The server only counts, asks and records; this agent still signs and pays
6
+ // itself, and its keys never leave it. When the server can't be reached, the
7
+ // wallet stops (limit_unavailable) instead of signing.
8
+
9
+ export function createRemoteLimiter({ url, key, fetch: fetchImpl = globalThis.fetch, requestTimeoutMs = 35_000, onSpend } = {}) {
10
+ if (typeof url !== "string" || !/^https?:\/\//.test(url)) throw new TypeError("server.url must be the wallet server's URL (https://…)");
11
+ if (typeof key !== "string" || !key.startsWith("awk_")) throw new TypeError("server.key must be an agent key (awk_…) made on the server's dashboard");
12
+ const base = url.replace(/\/$/, "");
13
+
14
+ async function call(method, path, body) {
15
+ const ctl = new AbortController();
16
+ const t = setTimeout(() => ctl.abort(), requestTimeoutMs);
17
+ try {
18
+ const res = await fetchImpl(`${base}${path}`, { method, headers: { authorization: `Bearer ${key}`, "content-type": "application/json", accept: "application/json" }, body: body === undefined ? undefined : JSON.stringify(body, (_k, v) => (typeof v === "bigint" ? v.toString() : v)), signal: ctl.signal });
19
+ const data = await res.json().catch(() => null);
20
+ if (!res.ok) throw new Error(`wallet server ${path}: ${data?.message ?? data?.error ?? `HTTP ${res.status}`}`);
21
+ return data;
22
+ } finally { clearTimeout(t); }
23
+ }
24
+
25
+ return {
26
+ remote: true,
27
+ async reserve({ method, request, verdict }) {
28
+ let r = await call("POST", "/v1/reserve", { method, request, verdict: verdict ?? null });
29
+ if (r.status === "ok") return { ok: true, entries: (r.entries ?? []).map((id) => ({ id })) };
30
+ if (r.status === "paused") return { ok: false, paused: true, summary: r.summary ?? "paused on the wallet server", reasons: [] };
31
+ if (r.status === "denied") return { ok: false, hardStop: true, summary: r.summary, reasons: r.reasons ?? [] };
32
+ if (r.status !== "pending") throw new Error(`wallet server: unexpected answer ${r.status}`);
33
+ // Over a limit: the owner decides on the dashboard or Telegram. Wait for it.
34
+ const id = r.approvalId, summary = r.summary, deadline = (r.expiresAt ?? Date.now() + 600_000) + 10_000;
35
+ while (Date.now() < deadline) {
36
+ const a = await call("GET", `/v1/approvals/${encodeURIComponent(id)}?wait=25`);
37
+ if (a.status === "approved") return { ok: true, entries: (a.entries ?? []).map((x) => ({ id: x })), approved: true };
38
+ if (a.status === "denied") return { ok: false, asked: true, summary: `${summary} (denied by the owner)`, reasons: [] };
39
+ if (a.status === "expired") return { ok: false, asked: true, summary: `${summary} (no answer in time)`, reasons: [] };
40
+ }
41
+ return { ok: false, asked: true, summary: `${summary} (no answer in time)`, reasons: [] };
42
+ },
43
+ async release(entries) { if (entries?.length) await call("POST", "/v1/release", { entries: entries.map((e) => e.id) }); },
44
+ spent(entries, result, info) {
45
+ for (const e of entries ?? []) { try { onSpend?.({ id: e.id, result, verdict: info?.verdict ?? null, receiptId: info?.verdict?.receipt?.request_id ?? null }); } catch (err) { console.warn(`[presign-guard-wallet] onSpend threw: ${err.message}`); } }
46
+ if (entries?.length) call("POST", "/v1/spent", { entries: entries.map((e) => e.id), result: typeof result === "string" ? result : null }).catch((err) => console.warn(`[presign-guard-wallet] ${err.message}`));
47
+ },
48
+ async spending() { return (await call("GET", "/v1/spending")).spending; },
49
+ };
50
+ }
package/telegram.d.ts ADDED
@@ -0,0 +1,22 @@
1
+ import type { OverLimitInfo } from "./index.js";
2
+
3
+ export interface TelegramApproverOptions {
4
+ /** Bot token from @BotFather. A secret: keep it in an environment variable. */
5
+ token: string;
6
+ /** Your chat with the bot: send it /start, then findTelegramChats({ token }). */
7
+ chatId: string | number;
8
+ /** Telegram user ids allowed to answer. Default: chatId (you, in a private chat). */
9
+ allowedUserIds?: Array<string | number>;
10
+ /** How long the agent waits for your tap. Default 10 minutes; no answer counts as Deny. */
11
+ timeoutMs?: number;
12
+ /** Name of the agent in the message. Default "Your agent". */
13
+ label?: string;
14
+ fetch?: typeof globalThis.fetch;
15
+ api?: string;
16
+ }
17
+
18
+ /** An onOverLimit for guardWallet: asks you on Telegram with Approve and Deny buttons. */
19
+ export declare function telegramApprover(options: TelegramApproverOptions): (info: OverLimitInfo) => Promise<boolean>;
20
+
21
+ /** The chats that sent your bot a message (send it /start first). */
22
+ export declare function findTelegramChats(options: { token: string; fetch?: typeof globalThis.fetch; api?: string }): Promise<Array<{ chatId: number; type: string; name: string; username: string | null }>>;
package/telegram.js ADDED
@@ -0,0 +1,152 @@
1
+ // Approve over-limit signatures from your phone, with a Telegram bot.
2
+ //
3
+ // import { telegramApprover } from "presign-guard-wallet/telegram";
4
+ // guardWallet(walletClient, { pay, limits, onOverLimit: telegramApprover({ token, chatId }) });
5
+ //
6
+ // When a signature would cross a limit, the bot sends you a message with what
7
+ // the agent wants to sign, why it is over the limit and presign-guard's verdict,
8
+ // with Approve and Deny buttons. The agent waits for your tap (default 10
9
+ // minutes); no answer in time counts as Deny. Only the people you allow
10
+ // (default: the chat itself, i.e. you in a private chat) can answer.
11
+ //
12
+ // No server needed: the wallet asks Telegram for button taps itself (long
13
+ // polling, getUpdates). So the bot must not have a webhook, and only one
14
+ // process at a time can poll one bot: give each agent process its own bot.
15
+ // The bot token is a secret: keep it in an environment variable.
16
+
17
+ const API = "https://api.telegram.org";
18
+ const escape = (s) => String(s ?? "").replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
19
+ const nonce = () => Math.random().toString(36).slice(2, 10) + Date.now().toString(36).slice(-4);
20
+
21
+ function client(token, fetchImpl, api) {
22
+ if (typeof token !== "string" || !/^\d+:[A-Za-z0-9_-]{20,}$/.test(token)) throw new TypeError("token must be a Telegram bot token (123456:ABC…), from @BotFather");
23
+ return async (method, body, signal) => {
24
+ const res = await fetchImpl(`${api}/bot${token}/${method}`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body ?? {}), signal });
25
+ const data = await res.json().catch(() => null);
26
+ if (!data?.ok) {
27
+ const err = new Error(`Telegram ${method} failed: ${data?.description ?? `HTTP ${res.status}`}`);
28
+ err.status = data?.error_code ?? res.status;
29
+ throw err;
30
+ }
31
+ return data.result;
32
+ };
33
+ }
34
+
35
+ // One poller per bot token in this process, shared by every waiting request.
36
+ const pollers = new Map();
37
+ function poller(token, call) {
38
+ let p = pollers.get(token);
39
+ if (p) return p;
40
+ p = { waiters: new Map(), offset: undefined, running: false, abort: null };
41
+ pollers.set(token, p);
42
+ p.start = () => {
43
+ if (p.running) return;
44
+ p.running = true;
45
+ (async () => {
46
+ while (p.waiters.size) {
47
+ p.abort = new AbortController();
48
+ let updates;
49
+ try {
50
+ updates = await call("getUpdates", { offset: p.offset, timeout: 25, allowed_updates: ["callback_query"] }, p.abort.signal);
51
+ } catch (err) {
52
+ if (!p.waiters.size) break; // aborted because nobody waits any more
53
+ if (err.status === 409 || err.status === 401 || err.status === 404) {
54
+ // A webhook, another process polling this bot, or a bad token: nobody can answer.
55
+ for (const w of p.waiters.values()) w.fail(err);
56
+ p.waiters.clear();
57
+ break;
58
+ }
59
+ await new Promise((ok) => setTimeout(ok, 2000)); // network hiccup: try again
60
+ continue;
61
+ }
62
+ for (const u of updates) {
63
+ p.offset = u.update_id + 1;
64
+ const q = u.callback_query;
65
+ const m = /^pgw:([a-z0-9]+):(y|n)$/.exec(q?.data ?? "");
66
+ const w = m && p.waiters.get(m[1]);
67
+ if (!w) { if (q?.id && m) call("answerCallbackQuery", { callback_query_id: q.id, text: "This request has already been decided or expired." }).catch(() => {}); continue; }
68
+ if (!w.allowed(q)) { call("answerCallbackQuery", { callback_query_id: q.id, text: "You are not allowed to answer this." }).catch(() => {}); continue; }
69
+ w.decide(m[2] === "y", q);
70
+ }
71
+ }
72
+ p.running = false;
73
+ if (p.waiters.size) p.start(); // someone started waiting while this loop was ending
74
+ })();
75
+ };
76
+ p.stopIfIdle = () => { if (!p.waiters.size) p.abort?.abort(); };
77
+ return p;
78
+ }
79
+
80
+ function messageFor(info, label) {
81
+ const lines = [`<b>${escape(label)} wants to sign something over your limit</b>`, ""];
82
+ lines.push(escape(info.summary));
83
+ const r = info.request ?? {};
84
+ lines.push("", `<code>${escape(info.method)}</code> · chain ${escape(r.chainId)}${r.to ? ` · to <code>${escape(r.to)}</code>` : ""}`);
85
+ const v = info.verdict?.verdict;
86
+ if (v) {
87
+ const codes = (info.verdict.reasons ?? []).filter((x) => x.severity !== "info").map((x) => x.code).join(", ");
88
+ lines.push(`presign-guard: <b>${escape(v)}</b>${codes ? ` (${escape(codes)})` : ""}`);
89
+ } else lines.push("presign-guard: no verdict for this one");
90
+ const spent = (info.spending ?? []).map((s) => `${escape(s.token)} ${escape(s.used)}${s.perDay ? ` / ${escape(s.perDay)}` : ""}`).join(" · ");
91
+ if (spent) lines.push(`spent this window: ${spent}`);
92
+ return lines.join("\n");
93
+ }
94
+
95
+ /**
96
+ * An onOverLimit for guardWallet that asks you on Telegram.
97
+ * @param {object} o
98
+ * @param {string} o.token bot token from @BotFather (keep it in an env var)
99
+ * @param {string|number} o.chatId your chat with the bot (see findTelegramChats)
100
+ * @param {Array<string|number>} [o.allowedUserIds] who may answer (default: chatId)
101
+ * @param {number} [o.timeoutMs] how long the agent waits (default 10 minutes); no answer = deny
102
+ * @param {string} [o.label] name of the agent in the message (default "Your agent")
103
+ * @param {typeof fetch} [o.fetch]
104
+ * @param {string} [o.api]
105
+ */
106
+ export function telegramApprover({ token, chatId, allowedUserIds, timeoutMs = 600_000, label = "Your agent", fetch: fetchImpl = globalThis.fetch, api = API } = {}) {
107
+ const call = client(token, fetchImpl, api);
108
+ if (chatId === undefined || chatId === null || chatId === "") throw new TypeError("chatId is required (send /start to your bot, then findTelegramChats({ token }))");
109
+ if (!(timeoutMs > 0)) throw new TypeError("timeoutMs must be a positive number of milliseconds");
110
+ const allowedIds = new Set((allowedUserIds ?? [chatId]).map(String));
111
+
112
+ return async function onOverLimit(info) {
113
+ const id = nonce();
114
+ const sent = await call("sendMessage", {
115
+ chat_id: chatId,
116
+ text: messageFor(info, label),
117
+ parse_mode: "HTML",
118
+ disable_web_page_preview: true,
119
+ reply_markup: { inline_keyboard: [[{ text: "Approve", callback_data: `pgw:${id}:y` }, { text: "Deny", callback_data: `pgw:${id}:n` }]] },
120
+ });
121
+ const p = poller(token, call);
122
+ const answer = await new Promise((resolve, reject) => {
123
+ const timer = setTimeout(() => { p.waiters.delete(id); p.stopIfIdle(); resolve({ ok: false, timeout: true }); }, timeoutMs);
124
+ p.waiters.set(id, {
125
+ allowed: (q) => allowedIds.has(String(q.from?.id)) && String(q.message?.chat?.id) === String(chatId),
126
+ decide: (ok, q) => { clearTimeout(timer); p.waiters.delete(id); p.stopIfIdle(); resolve({ ok, q }); },
127
+ fail: (err) => { clearTimeout(timer); reject(err); },
128
+ });
129
+ p.start();
130
+ });
131
+ const who = answer.q?.from?.username ? `@${answer.q.from.username}` : answer.q?.from?.first_name ?? "you";
132
+ const outcome = answer.timeout ? `<b>No answer in ${Math.round(timeoutMs / 60_000) || 1} min: not signed.</b>` : answer.ok ? `<b>Approved by ${escape(who)}: signing.</b>` : `<b>Denied by ${escape(who)}: not signed.</b>`;
133
+ if (answer.q?.id) call("answerCallbackQuery", { callback_query_id: answer.q.id, text: answer.ok ? "Approved" : "Denied" }).catch(() => {});
134
+ call("editMessageText", { chat_id: chatId, message_id: sent.message_id, text: `${messageFor(info, label)}\n\n${outcome}`, parse_mode: "HTML", disable_web_page_preview: true }).catch(() => {});
135
+ return answer.ok === true;
136
+ };
137
+ }
138
+
139
+ /**
140
+ * The chats that sent your bot a message (send it /start first). Use the chatId of yours.
141
+ * @returns {Promise<Array<{chatId: number, type: string, name: string, username: string|null}>>}
142
+ */
143
+ export async function findTelegramChats({ token, fetch: fetchImpl = globalThis.fetch, api = API } = {}) {
144
+ const call = client(token, fetchImpl, api);
145
+ const updates = await call("getUpdates", { timeout: 0, allowed_updates: ["message"] });
146
+ const chats = new Map();
147
+ for (const u of updates) {
148
+ const c = u.message?.chat;
149
+ if (c) chats.set(c.id, { chatId: c.id, type: c.type, name: [c.first_name, c.last_name].filter(Boolean).join(" ") || c.title || "", username: c.username ?? null });
150
+ }
151
+ return [...chats.values()];
152
+ }