From f8e927cf926b66f465da3b218bc2428bbf9528da Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 10:13:15 -0300 Subject: [PATCH 001/410] test(format): pin amount formatting boundaries --- tests/format-amount.test.ts | 109 ++++++++++++++++++++++++++++++++++++ 1 file changed, 109 insertions(+) diff --git a/tests/format-amount.test.ts b/tests/format-amount.test.ts index 59e7fe73..46d9ff34 100644 --- a/tests/format-amount.test.ts +++ b/tests/format-amount.test.ts @@ -1,6 +1,7 @@ import { test, expect } from "bun:test"; import { copyableHtml, + escapeHtml, formatAmount, formatCompactTokenDisplay, formatRate, @@ -8,6 +9,7 @@ import { formatTokenDisplay, formatUsdValue, } from "../src/utils/format-amount"; +import type { FormatOptions } from "../src/utils/format-amount"; test("formatSignedPercent keeps a compact signed label", () => { expect(formatSignedPercent(0.184)).toBe("+18.4%"); @@ -15,12 +17,29 @@ test("formatSignedPercent keeps a compact signed label", () => { expect(formatSignedPercent(0)).toBe("0%"); }); +test.each<[number, string]>([ + [-0, "0%"], + [0.00001, "+0%"], + [0.0104, "+1.04%"], + [0.0999, "+9.99%"], + [0.1, "+10%"], + [0.10051, "+10.1%"], + [-0.10051, "-10.1%"], +])("formatSignedPercent(%p) is %s", (value, expected) => { + expect(formatSignedPercent(value)).toBe(expected); +}); + test("copyableHtml wraps escaped text in a Telegram tap-to-copy code tag", () => { expect(copyableHtml("4.006348202")).toBe("4.006348202"); expect(copyableHtml('5 & "y"')).toBe("5 & <x> "y""); expect(copyableHtml(undefined)).toBe(""); }); +test("escapeHtml displays missing values as blank and keeps a numeric zero", () => { + expect(escapeHtml(null)).toBe(""); + expect(escapeHtml(0)).toBe("0"); +}); + test("formatAmount formats basic integer", () => { expect(formatAmount(123456, 5)).toBe("1.23456"); }); @@ -73,6 +92,51 @@ test("formatAmount default maxFractionDigits equals decimals", () => { expect(formatAmount(1, 18)).toBe("0.000000000000000001"); }); +test.each<[string, number | bigint | string, number, FormatOptions, string]>([ + ["number zero", 0, 2, { trim: false }, "0.00"], + ["negative number zero", -0, 2, { trim: false }, "-0.00"], + ["negative fraction truncates to negative zero", -0.9, 2, {}, "-0"], + ["negative number", -123, 2, {}, "-1.23"], + ["bigint zero", 0n, 2, {}, "0"], + ["unsigned integer string", "00123", 2, {}, "1.23"], + ["negative integer string", " -00123 ", 2, {}, "-1.23"], + ["positive integer string", " +00123 ", 2, {}, "1.23"], + ["large unsigned integer string", " 9007199254740993 ", 2, {}, "90071992547409.93"], + ["large negative integer string", " -9007199254740993 ", 2, {}, "-90071992547409.93"], + ["large positive integer string", " +9007199254740993 ", 2, {}, "90071992547409.93"], + ["negative decimal string", "-12.9", 2, {}, "-0.12"], + ["negative decimal string truncates to negative zero", "-0.9", 2, {}, "-0"], + ["positive decimal string truncates to zero", "+0.9", 2, {}, "0"], + ["no token decimals", 123n, 0, { trim: false }, "123"], + ["below the whole-unit rounding boundary", 149n, 2, { maxFractionDigits: 0 }, "1"], + ["at the whole-unit rounding boundary", 150n, 2, { maxFractionDigits: 0 }, "2"], + [ + "rounds a negative amount away from zero at the boundary", + -150n, + 2, + { maxFractionDigits: 0 }, + "-2", + ], + ["at the fractional rounding boundary", 9995n, 3, { maxFractionDigits: 2, trim: false }, "10.00"], + ["below the fractional rounding boundary", 9994n, 3, { maxFractionDigits: 2 }, "9.99"], + [ + "carry into the first visible fractional digit", + 95n, + 4, + { maxFractionDigits: 3, trim: false }, + "0.010", + ], + [ + "bigint above Number.MAX_SAFE_INTEGER", + -123456789012345678901234567890n, + 6, + {}, + "-123456789012345678901234.56789", + ], +])("formatAmount handles %s", (_label, raw, decimals, options, expected) => { + expect(formatAmount(raw, decimals, options)).toBe(expected); +}); + test("formatTokenDisplay respects provided decimals", () => { expect( formatTokenDisplay(1.2, { @@ -97,6 +161,15 @@ test("formatTokenDisplay handles non-finite values", () => { expect(formatTokenDisplay(Number.NaN)).toBe("0"); }); +test.each<[number, number | undefined, string]>([ + [1000, undefined, "1,000"], + [1.002, undefined, "1.002"], + [1.002, Number.POSITIVE_INFINITY, "1.002"], + [1.002, 0, "1"], +])("formatTokenDisplay(%p) with %p decimals is %s", (value, decimals, expected) => { + expect(formatTokenDisplay(value, decimals === undefined ? {} : { decimals })).toBe(expected); +}); + test("formatCompactTokenDisplay abbreviates thousands", () => { expect(formatCompactTokenDisplay("267,980")).toBe("267.9k"); }); @@ -119,6 +192,23 @@ test("formatCompactTokenDisplay scales to large suffixes", () => { expect(formatCompactTokenDisplay(1_000_000_000_000_000)).toBe("1P"); }); +test.each<[number | string, string]>([ + [999, "999"], + [1_000, "1k"], + [" 2,345.99 ", "2.3k"], + [10_010, "10k"], + [1_000_000_000_000_000_000, "1E"], + ["1,000,000,000,000,000,000,000", "1000E"], + ["-0.10500", "-0.105"], + ["-0", "0"], + ["-0.00000005", "-0.000000"], + ["", "0"], + [" 23 - ", " 23 - "], + [" 23 + ", " 23 + "], +])("formatCompactTokenDisplay(%p) is %s", (value, expected) => { + expect(formatCompactTokenDisplay(value)).toBe(expected); +}); + test("formatCompactTokenDisplay falls back to raw string for invalid numbers", () => { expect(formatCompactTokenDisplay("not-a-number")).toBe("not-a-number"); expect(formatCompactTokenDisplay(" ")).toBe("0"); @@ -210,3 +300,22 @@ test("formatCompactTokenDisplay treats missing values as zero and keeps non-nume test("formatRate falls back to exponential for extremely small values", () => { expect(formatRate(4e-13)).toBe("4.00e-13"); }); + +test.each<[number, string]>([ + [1.23456, "1.2346"], + [1, "1"], + [0.123456, "0.1235"], + [0.01, "0.01"], + [0.00987654, "0.009877"], + [0.0001, "0.0001"], + [0.0000987654, "0.00009877"], + [0.000001, "0.000001"], + [0.000000987654, "0.0000009877"], + [0.00000001, "0.00000001"], + [0.00000000987654, "0.000000009877"], + [0.000000000001, "0.000000000001"], + [0.0000000000004, "4.00e-13"], + [1.23e30, "1.23e+30"], +])("formatRate(%p) is %s", (value, expected) => { + expect(formatRate(value)).toBe(expected); +}); From e48c340832ff42a64ab25338e875b9e875682608 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 10:27:59 -0300 Subject: [PATCH 002/410] test(bot): verify formatter and command boundaries --- src/handlers/game.ts | 20 +-- src/services/contract-capital.ts | 9 +- src/utils/arg-parsing.ts | 20 ++- src/utils/bot-helpers/error-response.ts | 13 +- src/utils/callback-registry.ts | 8 +- src/utils/concurrency.ts | 19 +-- src/utils/fee-budget-refresh.ts | 15 ++- src/utils/format-amount.ts | 150 ++++++++--------------- src/utils/format-time.ts | 6 +- src/utils/game-challenge.ts | 15 ++- tests/account-errors.test.ts | 10 ++ tests/arg-parsing.test.ts | 21 +++- tests/bot-helpers.error-response.test.ts | 15 ++- tests/buy-alerts.service.test.ts | 43 ++++++- tests/callback-registry.test.ts | 60 +++++++++ tests/concurrency.test.ts | 36 ++++++ tests/constants.dynamic.test.ts | 17 +++ tests/contract-capital.test.ts | 47 ++++++- tests/contract-idl.test.ts | 5 +- tests/finance-backfill-worker.test.ts | 22 ++++ tests/format-amount.test.ts | 30 +++++ tests/format-time.test.ts | 1 + tests/game-challenge.test.ts | 29 +++++ tests/game-handler.coinflip.test.ts | 59 +++++++++ tests/helpers/grammy.ts | 22 ++++ 25 files changed, 512 insertions(+), 180 deletions(-) create mode 100644 tests/callback-registry.test.ts create mode 100644 tests/concurrency.test.ts create mode 100644 tests/helpers/grammy.ts diff --git a/src/handlers/game.ts b/src/handlers/game.ts index c02cb1d0..5138d02c 100644 --- a/src/handlers/game.ts +++ b/src/handlers/game.ts @@ -24,12 +24,12 @@ export type GameTokenOverride = { export type CoinflipDeps = { isGroupChat: (ctx: Context) => boolean; showInteractiveSetup: ( - ctx: Context & { message?: any }, + ctx: Context, telegramId: bigint, tokenOverride?: GameTokenOverride, ) => Promise; createGameViaCommand: ( - ctx: Context & { message?: any }, + ctx: Context, args: string[], telegramId: bigint, challenge?: ChallengedPlayer[], @@ -40,10 +40,10 @@ export type CoinflipDeps = { getMaxPlayers: () => number; }; -export async function handleCoinflipCommand(ctx: Context & { message?: any }, deps: CoinflipDeps) { +export async function handleCoinflipCommand(ctx: Context, deps: CoinflipDeps) { // DM games are allowed but will be forced to public visibility - const telegramId = await getRequiredTelegramIdForContext(ctx, "coinflip command"); + const telegramId = await getRequiredTelegramIdForContext(ctx, handleCoinflipCommand.name); if (telegramId == null) { return; } @@ -80,10 +80,11 @@ export async function handleCoinflipCommand(ctx: Context & { message?: any }, de await replyEphemeralToSender(ctx, replyRefusal); return; } - const args = findNamedUsers(ctx.message)?.args ?? ctx.message?.text?.trim().split(/\s+/) ?? []; + const message = ctx.message; + const args = findNamedUsers(message)?.args ?? (message?.text ?? "").trim().split(/\s+/); // Replies to another chat or forum topic name no one here, so they cannot be // challenges; refuse them instead of opening a game anyone could join. - if (ctx.message?.external_reply) { + if (message?.external_reply) { await replyEphemeralToSender(ctx, CHALLENGE_SAME_CHAT_MESSAGE); return; } @@ -95,9 +96,10 @@ export async function handleCoinflipCommand(ctx: Context & { message?: any }, de await replyEphemeralToSender(ctx, CHALLENGE_NEEDS_AMOUNT_MESSAGE, { parse_mode: "HTML" }); return; } - const override = input.token - ? await deps.resolveTokenOverride(input.token, ctx.chat?.id) - : undefined; + const override = + input.token && message + ? await deps.resolveTokenOverride(input.token, message.chat.id) + : undefined; if (input.token && !override) { await replyEphemeralToSender(ctx, "Token unavailable. Check its symbol or address."); return; diff --git a/src/services/contract-capital.ts b/src/services/contract-capital.ts index 25f20153..428df4a3 100644 --- a/src/services/contract-capital.ts +++ b/src/services/contract-capital.ts @@ -5,6 +5,7 @@ import { PDAManager } from "../utils/pda"; const UPGRADEABLE_LOADER = new PublicKey("BPFLoaderUpgradeab1e11111111111111111111111"); const PROGRAM_ACCOUNT_TAG = 2; +const VERIFICATION_COMMITMENT = "confirmed"; type GameTokenAccount = { publicKey: PublicKey; @@ -24,12 +25,12 @@ const getProgramDataAddress = (data: Buffer): PublicKey => { }; export async function getContractCapitalLamports( - connection: Connection, + connection: Pick, program: TimbaProgram, policyMints: readonly string[], includeGameTokenAccounts = false, ): Promise { - const programInfo = await connection.getAccountInfo(program.programId, "confirmed"); + const programInfo = await connection.getAccountInfo(program.programId, VERIFICATION_COMMITMENT); if (!programInfo || !programInfo.owner.equals(UPGRADEABLE_LOADER)) { throw new Error("Unable to verify the Timba program account"); } @@ -71,7 +72,7 @@ export async function getContractCapitalLamports( const targets = [...expectedOwners.values()]; const accounts = await connection.getMultipleAccountsInfo( targets.map(({ address }) => address), - "confirmed", + VERIFICATION_COMMITMENT, ); return accounts.reduce((total, account, index) => { @@ -83,7 +84,7 @@ export async function getContractCapitalLamports( return total; } if (!account || !account.owner.equals(expected.owner)) { - throw new Error(`Unable to verify contract account ${expected?.address.toBase58() ?? index}`); + throw new Error(`Unable to verify contract account ${expected.address.toBase58()}`); } return total + BigInt(account.lamports); }, 0n); diff --git a/src/utils/arg-parsing.ts b/src/utils/arg-parsing.ts index 766164bf..ca04bcf5 100644 --- a/src/utils/arg-parsing.ts +++ b/src/utils/arg-parsing.ts @@ -23,18 +23,16 @@ export function inferMaxPlayers( ? amountArgIndex + 2 // amount, token, players : amountArgIndex + 1; // amount, players - if (args.length > playersIndex) { - const candidate = args[playersIndex]; - if (typeof candidate === "string") { - const trimmed = candidate.trim(); - // Only accept pure integer strings (no decimals, no suffixes like "4x") - if (/^\d+$/.test(trimmed)) { - const maybe = Number(trimmed); - if (maybe < minPlayers || maybe > maxPlayers) { - return { ok: false, error: `Players must be between ${minPlayers}-${maxPlayers}.` }; - } - return { ok: true, value: maybe, source: "arg" }; + const candidate = args[playersIndex]; + if (candidate !== undefined) { + const trimmed = candidate.trim(); + // Only accept pure integer strings (no decimals, no suffixes like "4x") + if (/^\d+$/.test(trimmed)) { + const maybe = Number(trimmed); + if (maybe < minPlayers || maybe > maxPlayers) { + return { ok: false, error: `Players must be between ${minPlayers}-${maxPlayers}.` }; } + return { ok: true, value: maybe, source: "arg" }; } } diff --git a/src/utils/bot-helpers/error-response.ts b/src/utils/bot-helpers/error-response.ts index c0ead461..5cfa0ead 100644 --- a/src/utils/bot-helpers/error-response.ts +++ b/src/utils/bot-helpers/error-response.ts @@ -11,14 +11,14 @@ export async function handleTransactionError( ctx: Context, error: unknown, processingMessageId: number, - wallet: WalletManager, + wallet?: WalletManager, ): Promise { const userFriendlyError = await formatUserFriendlyError(error, wallet); await ctx.api.editMessageText(ctx.chat!.id, processingMessageId, userFriendlyError, { parse_mode: "HTML", }); if (error && typeof error === "object") { - (error as any).__alreadyNotified = true; + Object.assign(error, { __alreadyNotified: true }); } } @@ -31,10 +31,15 @@ export async function handleCommandError( ctx: Context, error: unknown, commandName: string, - wallet: WalletManager, + wallet?: WalletManager, ): Promise { console.error(`Error in ${commandName} command:`, error); - if (error && typeof error === "object" && (error as any).__alreadyNotified) { + if ( + typeof error === "object" && + error !== null && + "__alreadyNotified" in error && + error.__alreadyNotified + ) { return; } const userFriendlyError = await formatUserFriendlyError(error, wallet); diff --git a/src/utils/callback-registry.ts b/src/utils/callback-registry.ts index 4852f3b6..d60fd3ce 100644 --- a/src/utils/callback-registry.ts +++ b/src/utils/callback-registry.ts @@ -1,4 +1,4 @@ -import type { Bot, Context, NextFunction } from "grammy"; +import type { Bot, Context, Filter, NextFunction } from "grammy"; export type CallbackPrefixHandlerOptions = { logLabel?: string; @@ -37,15 +37,15 @@ export const createCallbackPrefixRegistrar = ({ return (prefix, handler, options = {}) => { bot.on( "callback_query", - wrapCallbackHandler( + wrapCallbackHandler>( async (ctx, next) => { - const callbackData = ctx.callbackQuery?.data; + const callbackData = ctx.callbackQuery.data; if (!callbackData?.startsWith(prefix)) { return await next(); } const payload = callbackData.slice(prefix.length); - await handler(ctx, { raw: callbackData, payload }, () => next()); + await handler(ctx, { raw: callbackData, payload }, next); }, { action: options.logLabel ?? `${prefix} handler`, diff --git a/src/utils/concurrency.ts b/src/utils/concurrency.ts index 5e52cbaa..af6e1f1d 100644 --- a/src/utils/concurrency.ts +++ b/src/utils/concurrency.ts @@ -6,23 +6,14 @@ export const mapWithConcurrency = async ( limit: number, mapper: (item: TItem, index: number) => Promise, ): Promise => { - if (items.length === 0) { - return []; - } - const safeLimit = Number.isFinite(limit) ? Math.trunc(limit) : 0; - const workerCount = Math.max(1, Math.min(items.length, safeLimit || 1)); - const results = new Array(items.length); - let nextIndex = 0; + const workerCount = Math.min(items.length, Math.max(1, safeLimit)); + const results: TResult[] = []; + const entries = items.entries(); const workers = Array.from({ length: workerCount }, async () => { - while (true) { - const index = nextIndex; - nextIndex += 1; - if (index >= items.length) { - return; - } - results[index] = await mapper(items[index]!, index); + for (const [index, item] of entries) { + results[index] = await mapper(item, index); } }); diff --git a/src/utils/fee-budget-refresh.ts b/src/utils/fee-budget-refresh.ts index 98f2c126..94d33b2a 100644 --- a/src/utils/fee-budget-refresh.ts +++ b/src/utils/fee-budget-refresh.ts @@ -8,7 +8,10 @@ export type DynamicFeeBudgetSnapshot = { }; export const refreshDynamicFeeBudgets = async ( - feeBudget: FeeBudgetProvider, + feeBudget: Pick< + FeeBudgetProvider, + "getSingleTransactionLamports" | "getGameSafetyBufferLamports" | "getJitSwapFeeBufferLamports" + >, ): Promise => { const [singleTransactionLamports, gameSafetyBufferLamports, jitSwapBufferLamports] = await Promise.all([ @@ -17,15 +20,11 @@ export const refreshDynamicFeeBudgets = async ( feeBudget.getJitSwapFeeBufferLamports(), ]); - applyDynamicFeeBudgets({ - singleTransactionLamports, - gameSafetyBufferLamports, - jitSwapBufferLamports, - }); - - return { + const snapshot = { singleTransactionLamports, gameSafetyBufferLamports, jitSwapBufferLamports, }; + applyDynamicFeeBudgets(snapshot); + return snapshot; }; diff --git a/src/utils/format-amount.ts b/src/utils/format-amount.ts index b4bcfeba..a71cf99f 100644 --- a/src/utils/format-amount.ts +++ b/src/utils/format-amount.ts @@ -35,9 +35,9 @@ export function copyableHtml(value: unknown): string { function toBigIntString(value: number | string | bigint): { sign: string; digits: string } { if (typeof value === "bigint") { - const sign = value < 0n ? "-" : ""; - const digits = (value < 0n ? -value : value).toString(); - return { sign, digits }; + return value < 0n + ? { sign: "-", digits: (-value).toString() } + : { sign: "", digits: value.toString() }; } if (typeof value === "number") { // value should represent an integer count of smallest units @@ -76,56 +76,21 @@ export function formatAmount( const { maxFractionDigits = decimals, trim = true } = opts; const { sign, digits } = toBigIntString(raw); - // Pad digits so we can slice integer/fraction reliably - const needed = Math.max(decimals + 1 - digits.length, 0); - const padded = (needed > 0 ? "0".repeat(needed) : "") + digits; - - let integerPart = decimals === 0 ? padded : padded.slice(0, -decimals) || "0"; - let fractionalFull = decimals === 0 ? "" : padded.slice(-decimals).padStart(decimals, "0"); - + // Always reserve at least one digit before the decimal point. + const padded = digits.padStart(decimals + 1, "0"); + const integerEnd = padded.length - decimals; const desired = Math.max(0, Math.min(maxFractionDigits, decimals)); - - // Rounding - if (decimals === 0 || desired === 0) { - // Round based on first fractional digit if any - const roundDigit = fractionalFull[0] || "0"; - if (roundDigit >= "5") { - const inc = (BigInt(integerPart) + 1n).toString(); - integerPart = inc; - } - fractionalFull = ""; - } - - let fractionalOut = ""; - if (decimals > 0 && desired > 0) { - const shown = fractionalFull.slice(0, desired); - const roundDigit = fractionalFull[desired] || "0"; - - if (roundDigit >= "5") { - const combinedVal = BigInt(integerPart + shown) + 1n; - const combinedStr = combinedVal.toString(); - const intLen = combinedStr.length - shown.length; - if (intLen >= 0) { - integerPart = combinedStr.slice(0, intLen); - fractionalOut = combinedStr.slice(intLen).padStart(shown.length, "0"); - } else { - // carry expanded only into fractional part - integerPart = "0"; - fractionalOut = combinedStr.padStart(shown.length, "0"); - } - } else { - fractionalOut = shown; - } - } - - // Trim trailing zeros if requested - if (trim && fractionalOut) { - fractionalOut = fractionalOut.replace(/0+$/, ""); - } - - const intOut = integerPart === "" ? "0" : integerPart; - const signed = sign + intOut + (fractionalOut ? "." + fractionalOut : ""); - return signed; + const roundAt = integerEnd + desired; + const shown = padded.slice(0, roundAt); + // An absent next digit is NaN, so it does not trigger rounding. + const rounded = + Number(padded[roundAt]) >= 5 + ? (BigInt(shown) + 1n).toString().padStart(desired + 1, "0") + : shown; + const split = rounded.length - desired; + const fractional = rounded.slice(split); + const fractionalOut = trim ? fractional.replace(/0+$/, "") : fractional; + return sign + rounded.slice(0, split) + (fractionalOut ? "." + fractionalOut : ""); } export function formatTokenDisplay(value: number, options: FormatTokenDisplayOptions = {}): string { @@ -133,18 +98,14 @@ export function formatTokenDisplay(value: number, options: FormatTokenDisplayOpt return "0"; } - const decimals = - typeof options.decimals === "number" && Number.isFinite(options.decimals) - ? Math.max(0, Math.min(Math.trunc(options.decimals), 6)) - : undefined; - + const decimals = options.decimals ?? NaN; let precision: number; - if (decimals !== undefined) { - precision = decimals; + if (Number.isFinite(decimals)) { + precision = Math.max(0, Math.min(Math.trunc(decimals), 6)); } else { - const [, fractional = ""] = value.toString().split("."); - const trimmed = fractional.replace(/0+$/, ""); - precision = Math.min(trimmed.length, 6); + const decimal = value.toString(); + // A negative exponent here means more fractional places than we can display. + precision = decimal.includes("e-") ? 6 : Math.min(decimal.split(".")[1]?.length ?? 0, 6); } const maximumFractionDigits = precision; @@ -161,7 +122,7 @@ export function formatCompactTokenDisplay(value: string | number): string { return "0"; } - const rawString = typeof value === "string" ? value : String(value); + const rawString = String(value); const normalized = rawString.replace(/,/g, "").trim(); const numeric = Number(normalized); @@ -172,19 +133,14 @@ export function formatCompactTokenDisplay(value: string | number): string { const sign = numeric < 0 ? "-" : ""; let absValue = Math.abs(numeric); - const suffixes = ["", "k", "M", "B", "T", "P", "E"] as const; - let suffixIndex = 0; - - while (absValue >= 1000 && suffixIndex < suffixes.length - 1) { + let suffix = ""; + for (const nextSuffix of ["k", "M", "B", "T", "P", "E"]) { + if (absValue < 1000) break; absValue /= 1000; - suffixIndex += 1; + suffix = nextSuffix; } - if (suffixIndex === 0) { - if (normalized === "") { - return "0"; - } - + if (suffix === "") { const [, fractional = ""] = normalized.split("."); const trimmedFraction = fractional.replace(/0+$/, ""); const precision = Math.min(trimmedFraction.length, 6); @@ -197,10 +153,7 @@ export function formatCompactTokenDisplay(value: string | number): string { } const truncated = Math.floor(absValue * 10) / 10; - let formatted = truncated.toFixed(1); - formatted = formatted.replace(/\.0$/, ""); - - return `${sign}${formatted}${suffixes[suffixIndex]}`; + return `${sign}${trimFixed(truncated.toFixed(1))}${suffix}`; } export function formatUsdValue(value: number, options: FormatUsdValueOptions = {}): string { @@ -231,42 +184,35 @@ export function formatUsdValue(value: number, options: FormatUsdValueOptions = { return approximate ? `≈ $${formatted}` : formatted; } +function trimFixed(value: string): string { + // toFixed uses exponential notation for large numbers. Do not trim its exponent. + return value.includes("e") ? value : value.replace(/0+$/, "").replace(/\.$/, ""); +} + export function formatSignedPercent(value: number): string { if (!Number.isFinite(value) || value === 0) { return "0%"; } const abs = Math.abs(value) * 100; - const digits = abs >= 10 ? abs.toFixed(1) : abs.toFixed(2); - const trimmed = digits.replace(/0+$/, "").replace(/\.$/, ""); - return `${value > 0 ? "+" : "-"}${trimmed}%`; + const wholePercent = Math.trunc(abs); + const digits = abs.toFixed(wholePercent >= 10 ? 1 : 2); + return `${Math.sign(value) === 1 ? "+" : "-"}${trimFixed(digits)}%`; } +const RATE_PRECISION = [ + [0.01, 4], + [0.0001, 6], + [0.000001, 8], + [0.00000001, 10], + [0.000000000001, 12], +] as const; + export function formatRate(value: number): string { if (!Number.isFinite(value) || value <= 0) { return "0"; } - let formatted: string; - if (value >= 1) { - formatted = value.toFixed(4); - } else if (value >= 0.01) { - formatted = value.toFixed(4); - } else if (value >= 0.0001) { - formatted = value.toFixed(6); - } else if (value >= 0.000001) { - formatted = value.toFixed(8); - } else if (value >= 0.00000001) { - formatted = value.toFixed(10); - } else if (value >= 0.000000000001) { - formatted = value.toFixed(12); - } else { - formatted = value.toExponential(2); - } - - if (formatted.includes("e")) { - return formatted; - } - - return formatted.replace(/0+$/, "").replace(/\.$/, ""); + const precision = RATE_PRECISION.find(([minimum]) => value >= minimum)?.[1]; + return precision === undefined ? value.toExponential(2) : trimFixed(value.toFixed(precision)); } diff --git a/src/utils/format-time.ts b/src/utils/format-time.ts index 9064df4e..7773e23d 100644 --- a/src/utils/format-time.ts +++ b/src/utils/format-time.ts @@ -3,10 +3,8 @@ * Examples: 10s, 45m, 1h 20m, 3d */ export function formatDuration(seconds: number): string { - if (seconds < 0) return "0s"; - - // Round to nearest integer for seconds - const totalSeconds = Math.round(seconds); + // Round to the nearest second and clamp negative durations to zero. + const totalSeconds = Math.max(0, Math.round(seconds)); if (totalSeconds < 60) { return `${totalSeconds}s`; diff --git a/src/utils/game-challenge.ts b/src/utils/game-challenge.ts index 2ea20ef7..e8c52b03 100644 --- a/src/utils/game-challenge.ts +++ b/src/utils/game-challenge.ts @@ -57,12 +57,11 @@ const CHALLENGE_BOT_MESSAGE = "You can't challenge a bot."; export const CHALLENGE_REPLY_OR_NAME_MESSAGE = "To challenge someone, reply to their message or name them without replying."; -const namesUser = (named: Pick, user: User): boolean => - named.user - ? named.user.id === user.id - : !!user.username && - !!named.username && - normalizeUsername(named.username) === normalizeUsername(user.username); +const namesUser = (named: Pick, user: User): boolean => { + if (named.user) return named.user.id === user.id; + const username = normalizeUsername(user.username ?? ""); + return username !== "" && username === normalizeUsername(named.username ?? ""); +}; /** * Why a coinflip that replies to someone and also names someone cannot open, or @@ -153,8 +152,8 @@ const tooManyChallengedMessage = (maxChallenged: number): string => // Someone picked from Telegram's list and the same username typed are one person. const nameKey = (named: Pick): string => { - const username = named.user ? named.user.username : named.username; - return username ? `@${normalizeUsername(username)}` : `id ${named.user?.id}`; + if (named.user && !named.user.username) return `id ${named.user.id}`; + return `@${normalizeUsername(named.user?.username ?? named.username ?? "")}`; }; /** diff --git a/tests/account-errors.test.ts b/tests/account-errors.test.ts index 33fe93c3..86443558 100644 --- a/tests/account-errors.test.ts +++ b/tests/account-errors.test.ts @@ -13,4 +13,14 @@ describe("missing account detection", () => { test("does not classify RPC failures as missing accounts", () => { expect(isMissingAccountError(new Error("RPC timeout while fetching account"))).toBe(false); }); + + test.each<[string, unknown, boolean]>([ + ["legacy code", { code: "AccountNotFound" }, true], + ["adapter code", { code: "ACCOUNT_NOT_FOUND" }, true], + ["timeout code", { code: "ETIMEDOUT" }, false], + ["non-text message", { message: { toString: () => "Account not found" } }, false], + ["multiline account address", new Error("Account\n\nABC\n\nnot found"), true], + ])("classifies %s", (_label, error, expected) => { + expect(isMissingAccountError(error)).toBe(expected); + }); }); diff --git a/tests/arg-parsing.test.ts b/tests/arg-parsing.test.ts index bd837efb..909de24e 100644 --- a/tests/arg-parsing.test.ts +++ b/tests/arg-parsing.test.ts @@ -16,9 +16,7 @@ test("coinflip: amount only uses default players", () => { }); test("coinflip: amount + players parses players", () => { - const res = cf(["/cf", "10", "3"], false); - expect(res.ok).toBe(true); - if (res.ok) expect(res.value).toBe(3); + expect(cf(["/cf", "10", "3"], false)).toEqual({ ok: true, value: 3, source: "arg" }); }); test("coinflip: amount + token keeps default players", () => { @@ -137,7 +135,18 @@ test("accepts exact boundaries (min/max)", () => { }); test("rejects defaults that fall outside allowed bounds", () => { - const res = inferMaxPlayers(["/cf", "10"], 1, false, 150, 2, 100); - expect(res.ok).toBe(false); - if (!res.ok) expect(res.error).toContain("2-100"); + for (const invalid of [1, 150]) { + expect(inferMaxPlayers(["/cf", "10"], 1, false, invalid, 2, 100)).toEqual({ + ok: false, + error: "Players must be between 2-100.", + }); + } +}); + +test("uses the default at the inclusive upper limit when the player argument is absent", () => { + expect(inferMaxPlayers(["/cf", "10"], 1, false, 100, 2, 100)).toEqual({ + ok: true, + value: 100, + source: "default", + }); }); diff --git a/tests/bot-helpers.error-response.test.ts b/tests/bot-helpers.error-response.test.ts index ffa0130a..445e1d32 100644 --- a/tests/bot-helpers.error-response.test.ts +++ b/tests/bot-helpers.error-response.test.ts @@ -1,4 +1,5 @@ import { afterEach, beforeEach, describe, expect, mock, spyOn, test } from "bun:test"; +import type { Context } from "grammy"; import { handleCommandError, handleTransactionError, @@ -8,7 +9,7 @@ const NO_ROUTE = "Jupiter error: no route found"; function makeCtx(messageId?: number) { const editMessageText = mock(async () => true); - const reply = mock(async () => ({ message_id: 99 })); + const reply = mock(async (..._args: Parameters) => ({ message_id: 99 })); const ctx = { chat: { id: -100 }, message: messageId === undefined ? undefined : { message_id: messageId }, @@ -122,4 +123,16 @@ describe("handleCommandError", () => { expect(reply).toHaveBeenCalledTimes(1); }); + + test("replies for primitive errors without looking for a notification flag", async () => { + const { ctx, reply } = makeCtx(1); + + await handleCommandError(ctx, "plain failure", "sell"); + + expect(reply).toHaveBeenCalledTimes(1); + expect(reply.mock.calls[0]).toEqual([ + expect.stringContaining("Something went wrong"), + expect.objectContaining({ reply_to_message_id: 1 }), + ]); + }); }); diff --git a/tests/buy-alerts.service.test.ts b/tests/buy-alerts.service.test.ts index 0a476f06..c84e05f1 100644 --- a/tests/buy-alerts.service.test.ts +++ b/tests/buy-alerts.service.test.ts @@ -1,4 +1,4 @@ -import { expect, test } from "bun:test"; +import { expect, spyOn, test } from "bun:test"; import { ChatDatabase } from "../src/utils/chat-database"; import { resetTestDatabase } from "./helpers/database"; import { createBuyAlertService } from "../src/services/buy-alerts/service"; @@ -129,3 +129,44 @@ test("buy alert service ingests externally observed buys through the publisher", expect(sent[0]?.chatId).toBe(-21); expect(sent[0]?.text).toContain("BUY - TIMBA"); }); + +test("previews a buy for the chat's default mint and only sends it to that chat", async () => { + resetTestDatabase("chat-settings.sqlite"); + ChatDatabase.resetForTesting(); + const chatDb = ChatDatabase.getInstance(); + const chatMint = "So11111111111111111111111111111111111111112"; + chatDb.upsertChatBuyAlerts(-22, { enabled: true }); + const sent: Array<{ chatId: number; text: string }> = []; + let watched: readonly string[] = []; + const fetchPairs = spyOn(globalThis, "fetch").mockImplementation( + Object.assign(async () => Response.json([]), { preconnect: () => {} }), + ); + const service = createBuyAlertService({ + chatDb, + getTokenManager: () => ({ + getChatDefaultToken: (chatId) => + chatId === -22 ? { token_mint: chatMint, token_ticker: "SOL" } : null, + getDefaultToken: () => ({ tokenMint: TIMBA_MINT, tokenTicker: "TIMBA" }), + }), + sendHtml: async (chatId, text) => { + sent.push({ chatId, text }); + }, + feed: { + setMints: (mints) => { + watched = mints; + }, + onTrade: () => {}, + stop: () => {}, + }, + }); + + try { + service.start(); + expect(watched).toEqual([chatMint]); + await service.sendTest(-22); + expect(sent).toEqual([{ chatId: -22, text: expect.stringContaining("BUY - SOL") }]); + } finally { + service.stop(); + fetchPairs.mockRestore(); + } +}); diff --git a/tests/callback-registry.test.ts b/tests/callback-registry.test.ts new file mode 100644 index 00000000..a94be2e7 --- /dev/null +++ b/tests/callback-registry.test.ts @@ -0,0 +1,60 @@ +import { expect, test } from "bun:test"; +import { Bot } from "grammy"; +import type { CallbackQuery } from "grammy/types"; +import { + createCallbackPrefixRegistrar, + type WrapCallbackHandler, +} from "../src/utils/callback-registry"; +import { testBotInfo } from "./helpers/grammy"; + +test("routes only matching callback data and gives the wrapper the right action context", async () => { + const bot = new Bot("42:test-token", { botInfo: testBotInfo }); + const calls: string[] = []; + const options: Parameters[1][] = []; + const wrap: WrapCallbackHandler = (handler, config) => { + options.push(config); + return async (ctx, next) => { + await handler(ctx, next); + }; + }; + const register = createCallbackPrefixRegistrar({ bot, wrapCallbackHandler: wrap }); + register( + "pay_", + async (_ctx, data, next) => { + calls.push(`pay ${data.raw} ${data.payload}`); + await next(); + }, + { logLabel: "payment confirmation", errorAck: "Could not confirm" }, + ); + register("cancel_", () => { + calls.push("cancelled"); + }); + bot.on("callback_query", (ctx) => { + calls.push(`fallback ${ctx.callbackQuery.id}`); + }); + + const base = { + from: { id: 23, is_bot: false, first_name: "Tester" }, + inline_message_id: "inline-test-message", + chat_instance: "chat-test-instance", + }; + const updates: CallbackQuery[] = [ + { ...base, id: "payment", data: "pay_150" }, + { ...base, id: "unmatched", data: "show_pay_150" }, + { ...base, id: "game", game_short_name: "test-game" }, + ]; + for (const [index, callback_query] of updates.entries()) { + await bot.handleUpdate({ update_id: index, callback_query }); + } + + expect(calls).toEqual([ + "pay pay_150 150", + "fallback payment", + "fallback unmatched", + "fallback game", + ]); + expect(options).toEqual([ + { action: "payment confirmation", errorAck: "Could not confirm" }, + { action: "cancel_ handler", errorAck: undefined }, + ]); +}); diff --git a/tests/concurrency.test.ts b/tests/concurrency.test.ts new file mode 100644 index 00000000..1422fa3e --- /dev/null +++ b/tests/concurrency.test.ts @@ -0,0 +1,36 @@ +import { expect, mock, test } from "bun:test"; +import { mapWithConcurrency } from "../src/utils/concurrency"; + +test("maps empty input without calling the mapper", async () => { + const mapper = mock(async (value: number) => value * 2); + + expect(await mapWithConcurrency([], 3, mapper)).toEqual([]); + expect(mapper).not.toHaveBeenCalled(); +}); + +test("starts only two jobs and keeps input order when another job finishes first", async () => { + const slow = Promise.withResolvers(); + const fast = Promise.withResolvers(); + const mapper = mock((value: string, index: number) => { + if (index === 0) return slow.promise; + if (index === 1) return fast.promise; + return Promise.resolve(value.toUpperCase()); + }); + + const pending = mapWithConcurrency(["a", "b", "c"], 2, mapper); + expect(mapper.mock.calls).toEqual([ + ["a", 0], + ["b", 1], + ]); + + fast.resolve("B"); + await Promise.resolve(); + expect(mapper.mock.calls).toEqual([ + ["a", 0], + ["b", 1], + ["c", 2], + ]); + + slow.resolve("A"); + await expect(pending).resolves.toEqual(["A", "B", "C"]); +}); diff --git a/tests/constants.dynamic.test.ts b/tests/constants.dynamic.test.ts index 36560fc2..a06b2818 100644 --- a/tests/constants.dynamic.test.ts +++ b/tests/constants.dynamic.test.ts @@ -14,6 +14,7 @@ import { getCoinflipVideoId, getGiveawayVideoId, } from "../src/utils/constants"; +import { refreshDynamicFeeBudgets } from "../src/utils/fee-budget-refresh"; const originalMinSolForTx = MIN_SOL_FOR_TX; const originalGameBuffer = MIN_SOL_BALANCE_FOR_GAMES_LAMPORTS; @@ -30,6 +31,22 @@ afterEach(() => { }); describe("dynamic constants", () => { + test("refreshes all three fee limits from the same provider snapshot", async () => { + const snapshot = await refreshDynamicFeeBudgets({ + getSingleTransactionLamports: async () => 2_000_000, + getGameSafetyBufferLamports: async () => 600_000, + getJitSwapFeeBufferLamports: async () => 300_000, + }); + + expect(snapshot).toEqual({ + singleTransactionLamports: 2_000_000, + gameSafetyBufferLamports: 600_000, + jitSwapBufferLamports: 300_000, + }); + expect(MIN_SOL_FOR_TX).toBe(0.002); + expect(MIN_SOL_BALANCE_FOR_GAMES_LAMPORTS).toBe(600_000); + expect(JIT_SWAP_FEE_BUFFER_LAMPORTS).toBe(300_000); + }); test("applyDynamicFeeBudgets ignores non-positive updates", () => { applyDynamicFeeBudgets({ singleTransactionLamports: -10, diff --git a/tests/contract-capital.test.ts b/tests/contract-capital.test.ts index a382809d..aea5b8d7 100644 --- a/tests/contract-capital.test.ts +++ b/tests/contract-capital.test.ts @@ -1,8 +1,9 @@ -import { describe, expect, test } from "bun:test"; -import { TOKEN_PROGRAM_ID } from "#token"; -import { Keypair, PublicKey } from "#solana"; +import { describe, expect, mock, test } from "bun:test"; +import { getAssociatedTokenAddress, TOKEN_PROGRAM_ID } from "#token"; +import { Keypair, PublicKey, type Connection } from "#solana"; import { getContractCapitalLamports } from "../src/services/contract-capital"; +import { PDAManager } from "../src/utils/pda"; const LOADER = new PublicKey("BPFLoaderUpgradeab1e11111111111111111111111"); @@ -187,6 +188,46 @@ describe("contract capital verification failures", () => { ); }); + test("reads each permanent account at confirmed commitment and requires program data", async () => { + const { programId, programData, programDataBytes } = await setup(); + const mint = (await Keypair.generate()).publicKey; + const oracle = await PDAManager.getOraclePDA(programId); + const vault = await PDAManager.getGameVaultPDA(mint, programId); + const vaultAta = await getAssociatedTokenAddress(mint, vault, true, TOKEN_PROGRAM_ID); + const getAccountInfo = mock(async () => ({ + owner: LOADER, + data: programDataBytes, + lamports: 100n, + executable: true, + rentEpoch: 0n, + space: 36n, + })); + const getMultipleAccountsInfo = mock(async () => [ + { + owner: LOADER, + data: programDataBytes, + lamports: 100n, + executable: true, + rentEpoch: 0n, + space: 36n, + }, + null, + null, + null, + ]); + + await expect( + getContractCapitalLamports({ getAccountInfo, getMultipleAccountsInfo }, { programId }, [ + mint.toBase58(), + ]), + ).rejects.toThrow(`Unable to verify contract account ${programData.toBase58()}`); + expect(getAccountInfo).toHaveBeenCalledWith(programId, "confirmed"); + expect(getMultipleAccountsInfo).toHaveBeenCalledWith( + [programId, programData, oracle, vaultAta], + "confirmed", + ); + }); + test("rejects an RPC response with more accounts than requested", async () => { const { programId, programDataBytes } = await setup(); const connection = { diff --git a/tests/contract-idl.test.ts b/tests/contract-idl.test.ts index 60baba66..023be23d 100644 --- a/tests/contract-idl.test.ts +++ b/tests/contract-idl.test.ts @@ -1,7 +1,10 @@ import { describe, expect, test } from "bun:test"; -import { getContractIdl, parseContractVersion } from "../src/utils/contract-idl"; +import { contractVersion, getContractIdl, parseContractVersion } from "../src/utils/contract-idl"; describe("contract ABI", () => { + test("selects the contract from the deployment environment", () => { + expect(contractVersion).toBe(parseContractVersion(process.env["CONTRACT_VERSION"])); + }); test("uses the v0.3 game-vault account lists", () => { const v030 = getContractIdl("0.3.0"); const accounts = (instructionName: string) => { diff --git a/tests/finance-backfill-worker.test.ts b/tests/finance-backfill-worker.test.ts index 6f2534c7..3742cb9a 100644 --- a/tests/finance-backfill-worker.test.ts +++ b/tests/finance-backfill-worker.test.ts @@ -94,6 +94,28 @@ describe("finance backfill worker scheduling", () => { worker.stop(); }); + test("checks again six hours after a fully indexed batch with default settings", async () => { + const worker = new FinanceBackfillWorker(async () => batch(true)); + + worker.start(); + await fire(); + + expect(delays()).toEqual([10_000, 21_600_000]); + worker.stop(); + }); + + test("does not retry a failing backfill less than 15 minutes apart after reaching the cap", async () => { + const worker = new FinanceBackfillWorker(async () => { + throw new Error("rpc down"); + }); + + worker.start(); + for (let failure = 0; failure < 7; failure += 1) await fire(); + + expect(delays()).toEqual([10_000, 30_000, 60_000, 120_000, 240_000, 480_000, 900_000, 900_000]); + worker.stop(); + }); + test("start is idempotent and waits the initial delay", () => { const worker = new FinanceBackfillWorker(async () => batch(false), options); diff --git a/tests/format-amount.test.ts b/tests/format-amount.test.ts index 46d9ff34..407f2cce 100644 --- a/tests/format-amount.test.ts +++ b/tests/format-amount.test.ts @@ -1,4 +1,5 @@ import { test, expect } from "bun:test"; +import fc from "fast-check"; import { copyableHtml, escapeHtml, @@ -25,6 +26,7 @@ test.each<[number, string]>([ [0.1, "+10%"], [0.10051, "+10.1%"], [-0.10051, "-10.1%"], + [1e28, "+1e+30%"], ])("formatSignedPercent(%p) is %s", (value, expected) => { expect(formatSignedPercent(value)).toBe(expected); }); @@ -137,6 +139,28 @@ test.each<[string, number | bigint | string, number, FormatOptions, string]>([ expect(formatAmount(raw, decimals, options)).toBe(expected); }); +test("formatAmount rounds and pads exact bigint amounts", () => { + fc.assert( + fc.property( + fc.bigInt({ min: -(10n ** 35n), max: 10n ** 35n }), + fc.integer({ min: 0, max: 18 }), + fc.integer({ min: 0, max: 18 }), + (raw, decimals, maxFractionDigits) => { + const shown = Math.min(decimals, maxFractionDigits); + const factor = 10n ** BigInt(decimals - shown); + const magnitude = raw < 0n ? -raw : raw; + const rounded = (magnitude + factor / 2n) / factor; + const scale = 10n ** BigInt(shown); + const sign = raw < 0n ? "-" : ""; + const fraction = (rounded % scale).toString().padStart(shown, "0"); + const expected = `${sign}${rounded / scale}${shown === 0 ? "" : `.${fraction}`}`; + expect(formatAmount(raw, decimals, { maxFractionDigits, trim: false })).toBe(expected); + }, + ), + { seed: 451 }, + ); +}); + test("formatTokenDisplay respects provided decimals", () => { expect( formatTokenDisplay(1.2, { @@ -166,6 +190,8 @@ test.each<[number, number | undefined, string]>([ [1.002, undefined, "1.002"], [1.002, Number.POSITIVE_INFINITY, "1.002"], [1.002, 0, "1"], + [1e-7, undefined, "0.000000"], + [-1.2e-10, undefined, "-0.000000"], ])("formatTokenDisplay(%p) with %p decimals is %s", (value, decimals, expected) => { expect(formatTokenDisplay(value, decimals === undefined ? {} : { decimals })).toBe(expected); }); @@ -197,11 +223,15 @@ test.each<[number | string, string]>([ [1_000, "1k"], [" 2,345.99 ", "2.3k"], [10_010, "10k"], + [2_300_000, "2.3M"], + [2_300_000_000_000, "2.3T"], [1_000_000_000_000_000_000, "1E"], ["1,000,000,000,000,000,000,000", "1000E"], ["-0.10500", "-0.105"], + [" 12.3400 ", "12.34"], ["-0", "0"], ["-0.00000005", "-0.000000"], + ["0.100000000000000003", "0.100000"], ["", "0"], [" 23 - ", " 23 - "], [" 23 + ", " 23 + "], diff --git a/tests/format-time.test.ts b/tests/format-time.test.ts index becd65b6..253bcd6d 100644 --- a/tests/format-time.test.ts +++ b/tests/format-time.test.ts @@ -3,6 +3,7 @@ import { describe, expect, test } from "bun:test"; describe("formatDuration", () => { test("formats seconds", () => { + expect(formatDuration(-10.5)).toBe("0s"); expect(formatDuration(0)).toBe("0s"); expect(formatDuration(10)).toBe("10s"); expect(formatDuration(59)).toBe("59s"); diff --git a/tests/game-challenge.test.ts b/tests/game-challenge.test.ts index f30db2af..9535a226 100644 --- a/tests/game-challenge.test.ts +++ b/tests/game-challenge.test.ts @@ -18,6 +18,14 @@ const reply = (replyToMessage: Record) => ({ reply_to_message: replyToMessage }) as any; describe("resolveChallengeTarget", () => { + test("uses a player label for a user whose profile has no visible name", () => { + expect( + resolveChallengeTarget( + reply({ from: { id: 5150, is_bot: false, first_name: " " } }), + CREATOR, + ), + ).toEqual({ telegramId: "5150", displayName: "Player" }); + }); test("a reply to a user with a username challenges them by @username", () => { expect( resolveChallengeTarget( @@ -150,6 +158,9 @@ describe("challengeKeepsOut", () => { }); describe("findChallengeNames", () => { + test("does not find a challenge when the update has no message", () => { + expect(findChallengeNames(undefined)).toBeNull(); + }); const text = "/cf 5 @rival"; test("a command that replies to no one is read for every name", () => { @@ -590,6 +601,24 @@ describe("resolveNamedChallenges", () => { }); }); + test("a picked account with no cached username and its current handle share one seat", async () => { + const users = directory(); + const [rival] = PEOPLE; + if (!rival) throw new Error("Expected a rival fixture"); + const picked = findNamedUsers({ + text: "/cf 5 Ana @rival", + entities: [ + { type: "text_mention", offset: 6, length: 3, user: { ...rival, username: undefined } }, + ], + }); + if (!picked) throw new Error("Expected the command to name a player"); + + expect(await resolveNamedChallenges(group(), picked, CREATOR, users, 2)).toEqual({ + challenge: [{ telegramId: "5150", displayName: "Ana" }], + }); + expect(users.lookups).toEqual(["@rival"]); + }); + test("a single name that cannot be challenged is still told to reply", async () => { expect( await resolveNamedChallenges(group(), names("/cf 5 @ghost @Ghost"), CREATOR, directory(), 3), diff --git a/tests/game-handler.coinflip.test.ts b/tests/game-handler.coinflip.test.ts index 2ae9dcf5..99b672c4 100644 --- a/tests/game-handler.coinflip.test.ts +++ b/tests/game-handler.coinflip.test.ts @@ -1,6 +1,7 @@ import { describe, expect, test } from "bun:test"; import { handleCoinflipCommand } from "../src/handlers/game"; import { createTelegramContext } from "./helpers/fixtures"; +import { makeTestTelegramContext } from "./helpers/grammy"; // The test sender (id 1) is the only one who sees these refusals in the group. const ONLY_SENDER = { ephemeral_message_parameters: { receiver_user_id: 1 } }; @@ -80,6 +81,64 @@ describe("game handler: coinflip command", () => { expect(commandCalls[0].telegramId).toBe(1n); }); + test("keeps command fields separate when users type extra whitespace", async () => { + const ctx = makeTestTelegramContext({ + update_id: 1, + message: { + message_id: 1, + date: 0, + chat: { id: -100, type: "group", title: "Synthetic group" }, + from: { id: 1, is_bot: false, first_name: "Tester" }, + text: " /cf 25\t SOL ", + }, + }); + const calls: string[][] = []; + const deps = { + isGroupChat: () => true, + showInteractiveSetup: async () => { + throw new Error("An amount should not open setup"); + }, + createGameViaCommand: async (_ctx: unknown, args: string[]) => { + calls.push(args); + }, + resolveTokenOverride: async () => null, + usernames: { findTelegramIdByUsername: () => null }, + getMaxPlayers: () => 100, + }; + + await handleCoinflipCommand(ctx, deps); + + expect(calls).toEqual([["/cf", "25", "SOL"]]); + }); + + test("opens setup when an inline action has a sender but no message text", async () => { + const ctx = makeTestTelegramContext({ + update_id: 1, + callback_query: { + id: "test-query", + from: { id: 7, is_bot: false, first_name: "Tester" }, + inline_message_id: "test-inline-message", + chat_instance: "test-chat-instance", + data: "coinflip_setup", + }, + }); + const setupFor: bigint[] = []; + await handleCoinflipCommand(ctx, { + isGroupChat: () => false, + showInteractiveSetup: async (_ctx, telegramId) => { + setupFor.push(telegramId); + }, + createGameViaCommand: async () => { + throw new Error("No amount was provided"); + }, + resolveTokenOverride: async () => null, + usernames: { findTelegramIdByUsername: () => null }, + getMaxPlayers: () => 100, + }); + + expect(setupFor).toEqual([7n]); + }); + test("token-only argument opens interactive setup with override", async () => { const ctx: any = createTelegramContext("/cf TIMBA"); const interactiveCalls: any[] = []; diff --git a/tests/helpers/grammy.ts b/tests/helpers/grammy.ts new file mode 100644 index 00000000..72b34cbf --- /dev/null +++ b/tests/helpers/grammy.ts @@ -0,0 +1,22 @@ +import { Api, Context } from "grammy"; +import type { Update, UserFromGetMe } from "grammy/types"; + +export const testBotInfo: UserFromGetMe = { + id: 42, + is_bot: true, + first_name: "Test Bot", + username: "test_bot", + can_join_groups: true, + can_read_all_group_messages: false, + supports_inline_queries: false, + can_connect_to_business: false, + has_main_web_app: false, + has_topics_enabled: false, + allows_users_to_create_topics: false, + can_manage_bots: false, + supports_join_request_queries: false, +}; + +export function makeTestTelegramContext(update: Update): Context { + return new Context(update, new Api("42:test-token"), testBotInfo); +} From 03fff316119e6529b8050cc55cfdbe816e66f055 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 10:44:11 -0300 Subject: [PATCH 003/410] fix(bot): verify trade, alert, and callback boundaries --- src/services/buy-alerts/holder.ts | 8 +- src/services/buy-alerts/keyboard.ts | 35 +++---- src/services/buy-alerts/parser.ts | 13 +-- src/services/buy-alerts/resolve.ts | 23 ++--- src/services/buy-alerts/swap-event.ts | 26 +++-- src/services/lightning/usd.ts | 34 +++++-- src/utils/admin-payer-surcharge.ts | 25 +++-- src/utils/amount.ts | 58 +++-------- src/utils/base-database.ts | 30 +++--- src/utils/callback-data.ts | 131 +++++++++++------------- src/utils/expiring-cache.ts | 56 ++--------- tests/admin-payer-surcharge.test.ts | 38 +++++++ tests/amount.trade-evaluation.test.ts | 139 +++++++++++++++++++++++++- tests/base-database.internals.test.ts | 27 +++++ tests/buy-alerts.holder.test.ts | 15 +++ tests/buy-alerts.keyboard.test.ts | 27 ++++- tests/buy-alerts.parser.test.ts | 18 ++++ tests/buy-alerts.resolve.test.ts | 32 +++++- tests/buy-alerts.swap-event.test.ts | 18 ++++ tests/callback-data.test.ts | 139 ++++++++++++++++++++++++++ tests/database-reset.test.ts | 22 ++++ tests/decimal-amount.test.ts | 1 + tests/expiring-cache.test.ts | 81 ++++++++++----- tests/lightning.usd.test.ts | 28 ++++++ tests/trade-amount.test.ts | 19 ++++ 25 files changed, 748 insertions(+), 295 deletions(-) create mode 100644 tests/buy-alerts.parser.test.ts create mode 100644 tests/callback-data.test.ts create mode 100644 tests/lightning.usd.test.ts diff --git a/src/services/buy-alerts/holder.ts b/src/services/buy-alerts/holder.ts index a7974aec..d87695e2 100644 --- a/src/services/buy-alerts/holder.ts +++ b/src/services/buy-alerts/holder.ts @@ -25,13 +25,13 @@ export function isNewHolderFromBalances(args: { return true; } - const uiAmount = pre.uiTokenAmount?.uiAmount; - if (typeof uiAmount === "number" && Number.isFinite(uiAmount)) { + const uiAmount = pre.uiTokenAmount?.uiAmount ?? NaN; + if (Number.isFinite(uiAmount)) { return uiAmount <= 0; } - const raw = pre.uiTokenAmount?.amount?.trim(); - if (raw != null && raw !== "") { + const raw = pre.uiTokenAmount?.amount; + if (raw != null) { try { return BigInt(raw) <= 0n; } catch { diff --git a/src/services/buy-alerts/keyboard.ts b/src/services/buy-alerts/keyboard.ts index b3b2df33..9284cd30 100644 --- a/src/services/buy-alerts/keyboard.ts +++ b/src/services/buy-alerts/keyboard.ts @@ -10,23 +10,18 @@ export function buyAlertCallbackData(mint: string): string { } function normalizeMint(mint: string): string | null { - const trimmed = mint.trim(); - if (!trimmed) { - return null; - } try { - return new PublicKey(trimmed).toBase58(); + return new PublicKey(mint.trim()).toBase58(); } catch { return null; } } export function parseBuyAlertMint(callbackData: string | undefined): string | null { - const raw = String(callbackData ?? ""); - if (!raw.startsWith(BUY_ALERT_CALLBACK_PREFIX)) { + if (!callbackData?.startsWith(BUY_ALERT_CALLBACK_PREFIX)) { return null; } - return normalizeMint(raw.slice(BUY_ALERT_CALLBACK_PREFIX.length)); + return normalizeMint(callbackData.slice(BUY_ALERT_CALLBACK_PREFIX.length)); } export function buyAlertStartPayload(mint: string): string { @@ -34,32 +29,28 @@ export function buyAlertStartPayload(mint: string): string { } export function parseBuyAlertStartPayload(payload: string | undefined): string | null { - const raw = String(payload ?? "").trim(); - if (!raw.startsWith(BUY_ALERT_START_PREFIX)) { + const raw = payload?.trim(); + if (!raw?.startsWith(BUY_ALERT_START_PREFIX)) { return null; } return normalizeMint(raw.slice(BUY_ALERT_START_PREFIX.length)); } export function parseBuyAlertStartText(text: string | undefined): string | null { - const match = String(text ?? "").match(/^\/start(?:@\w+)?\s+(\S+)/i); + const match = text?.match(/^\/start(?:@\w+)?\s+(\S+)/i); if (!match?.[1]) { return null; } return parseBuyAlertStartPayload(match[1]); } -export function buyAlertDeepLinkUrl(botUsername: string, mint: string): string { - const username = botUsername.trim().replace(/^@+/, ""); - return `https://t.me/${username}?start=${buyAlertStartPayload(mint)}`; +export function buyAlertDeepLinkUrl(botUsername: string, mint: string): string | null { + const username = /^@*([a-z0-9_]+)$/i.exec(botUsername.trim())?.[1]; + return username ? `https://t.me/${username}?start=${buyAlertStartPayload(mint)}` : null; } export function buyAlertButtonLabel(ticker: string | undefined): string { - const symbol = ticker?.trim().replace(/\s+/g, "") || "TOKEN"; - const label = `BUY ${symbol.toUpperCase()}`; - if (label.length <= BUY_ALERT_BUTTON_MAX) { - return label; - } + const symbol = ticker?.replace(/\s/g, "") || "TOKEN"; return `BUY ${symbol.toUpperCase().slice(0, BUY_ALERT_BUTTON_MAX - 4)}`; } @@ -69,9 +60,9 @@ export function createBuyAlertKeyboard( botUsername?: string, ): InlineKeyboard { const label = buyAlertButtonLabel(ticker); - const username = botUsername?.trim(); - if (username) { - return new InlineKeyboard().url(label, buyAlertDeepLinkUrl(username, mint)); + const url = botUsername ? buyAlertDeepLinkUrl(botUsername, mint) : null; + if (url) { + return new InlineKeyboard().url(label, url); } return new InlineKeyboard().text(label, buyAlertCallbackData(mint)); } diff --git a/src/services/buy-alerts/parser.ts b/src/services/buy-alerts/parser.ts index b473d338..88079f97 100644 --- a/src/services/buy-alerts/parser.ts +++ b/src/services/buy-alerts/parser.ts @@ -1,14 +1,11 @@ import type { BuyDex } from "./types"; +const PUMP_POOLS = new Set(["pump", "pump-amm", "pump-fun", "pumpfun", "pumpswap"]); + export function mapDexFromPool(pool: string | null | undefined): BuyDex { - const normalized = pool?.trim().toLowerCase() ?? ""; - if ( - normalized === "pump" || - normalized === "pump-amm" || - normalized === "pump-fun" || - normalized === "pumpfun" || - normalized === "pumpswap" - ) { + if (pool == null) return "unknown"; + const normalized = pool.trim().toLowerCase(); + if (PUMP_POOLS.has(normalized)) { return "pump"; } if (normalized.startsWith("raydium")) { diff --git a/src/services/buy-alerts/resolve.ts b/src/services/buy-alerts/resolve.ts index 22c54f27..e56bd602 100644 --- a/src/services/buy-alerts/resolve.ts +++ b/src/services/buy-alerts/resolve.ts @@ -12,11 +12,12 @@ export function resolveBuyAlertToken( chatDefault: { token_mint: string; token_ticker: string } | null | undefined, botDefault: { tokenMint: string; tokenTicker: string }, ): ResolvedBuyAlertToken { - const overrideMint = config?.token_mint?.trim(); + const { token_mint, token_ticker } = config ?? {}; + const overrideMint = token_mint?.trim(); if (overrideMint) { return { mint: overrideMint, - ticker: config?.token_ticker?.trim() || "TOKEN", + ticker: token_ticker?.trim() || "TOKEN", }; } @@ -34,29 +35,27 @@ export function resolveBuyAlertToken( } export function formatMinSolLabel(minSolLamports: number | null | undefined): string { - if (minSolLamports == null || minSolLamports <= 0) { + const lamports = minSolLamports ?? 0; + if (lamports <= 0) { return "Off"; } - const formatted = (minSolLamports / LAMPORTS_PER_SOL) - .toFixed(9) - .replace(/0+$/, "") - .replace(/\.$/, ""); + const formatted = (lamports / LAMPORTS_PER_SOL).toFixed(9).replace(/0+$/, "").replace(/\.$/, ""); return `${formatted} SOL`; } export function parseMinSolInput(raw: string): ParsedMinSol { const trimmed = raw.trim().toLowerCase().replace(/,/g, "."); - if (!trimmed) { - return { ok: false }; - } if (trimmed === "off" || trimmed === "none") { return { ok: true, minSolLamports: null }; } - const numeric = trimmed.replace(/\s*sol\s*$/i, "").trim(); + const numeric = trimmed.endsWith("sol") ? trimmed.slice(0, -3) : trimmed; + if (!numeric) { + return { ok: false }; + } const sol = Number(numeric); - if (!Number.isFinite(sol) || sol < 0) { + if (!Number.isFinite(sol)) { return { ok: false }; } if (sol === 0) { diff --git a/src/services/buy-alerts/swap-event.ts b/src/services/buy-alerts/swap-event.ts index b458fc07..43e9640c 100644 --- a/src/services/buy-alerts/swap-event.ts +++ b/src/services/buy-alerts/swap-event.ts @@ -21,23 +21,19 @@ export function buyEventFromSwap(input: SwapBuyInput): BuyEvent | null { return null; } - const decimals = Number.isFinite(input.outputDecimals) ? input.outputDecimals : 0; - const rawOut = Number(input.outputAmountRaw); - if (!Number.isFinite(rawOut) || rawOut <= 0) { - return null; - } - const tokenAmount = decimals > 0 ? rawOut / 10 ** decimals : rawOut; + const decimals = Number.isFinite(input.outputDecimals) ? Math.max(0, input.outputDecimals) : 0; + const tokenAmount = Number(input.outputAmountRaw) / 10 ** decimals; if (!Number.isFinite(tokenAmount) || tokenAmount <= 0) { return null; } const inputMint = input.inputMint.trim(); - const inputDecimals = - typeof input.inputDecimals === "number" && Number.isFinite(input.inputDecimals) - ? Math.max(0, Math.trunc(input.inputDecimals)) - : inputMint === WSOL_MINT - ? 9 - : 0; + const requestedDecimals = input.inputDecimals ?? NaN; + const inputDecimals = Number.isFinite(requestedDecimals) + ? Math.max(0, Math.trunc(requestedDecimals)) + : inputMint === WSOL_MINT + ? 9 + : 0; const rawIn = Number(input.inputAmountRaw); const inputAmount = Number.isFinite(rawIn) && rawIn > 0 ? rawIn / 10 ** inputDecimals : null; let solAmount: number | null = null; @@ -47,16 +43,18 @@ export function buyEventFromSwap(input: SwapBuyInput): BuyEvent | null { } } + const inputSymbol = input.inputTicker?.trim() || (inputMint === WSOL_MINT ? "SOL" : null); + return { signature, mint: outputMint, trader, solAmount, inputAmount, - inputSymbol: input.inputTicker?.trim() || (inputMint === WSOL_MINT ? "SOL" : null), + inputSymbol, tokenAmount, dex: "unknown", dexId: "jupiter", - quoteSymbol: input.inputTicker?.trim() || (inputMint === WSOL_MINT ? "SOL" : null), + quoteSymbol: inputSymbol, }; } diff --git a/src/services/lightning/usd.ts b/src/services/lightning/usd.ts index 231b710e..0c8bd2c4 100644 --- a/src/services/lightning/usd.ts +++ b/src/services/lightning/usd.ts @@ -13,13 +13,15 @@ export function depositUsdLimits(market: DepositMarket) { export function usdToSats(input: string, market: DepositMarket): string { const normalized = input.trim().replace(/^\$/, ""); - if (!/^\d+(\.\d{1,2})?$/.test(normalized) || Number(normalized) <= 0) - throw new DepositInputError("Enter a positive USD amount, such as 20 or 20.50."); const usd = Number(normalized); + if (!/^\d+(\.\d{1,2})?$/.test(normalized) || usd <= 0) + throw new DepositInputError("Enter a positive USD amount, such as 20 or 20.50."); const { min, max } = depositUsdLimits(market); if (usd < min || usd > max) throw new DepositInputError(`Choose an amount between ${usdLabel(min)} and ${usdLabel(max)}.`); - const sats = Math.ceil((usd * 1e8) / market.btcUsd); + // Convert the decimal input to cents before scaling to avoid one extra sat at a boundary. + const cents = Math.round(usd * 100); + const sats = Math.ceil((cents * 1e6) / market.btcUsd); if (!Number.isSafeInteger(sats) || sats < market.minSats || sats > market.maxSats) throw new DepositInputError("The deposit limits have changed. Choose another amount."); return String(sats); @@ -27,12 +29,22 @@ export function usdToSats(input: string, market: DepositMarket): string { export function depositUsdPresets(market: DepositMarket): number[] { const { min, max } = depositUsdLimits(market); - const presets = [10, 25, 50].filter((amount) => amount >= min && amount <= max); - if (presets.length === 3) return presets; - const candidates = [Math.ceil(min / 5) * 5, 100, 250, 500, 1000, 2500, 5000, 10000, 25000]; - for (const amount of candidates) { - if (amount >= min && amount <= max && !presets.includes(amount)) presets.push(amount); - if (presets.length === 3) break; - } - return presets.sort((a, b) => a - b); + const candidates = [ + 10, + 25, + 50, + Math.ceil(min / 5) * 5, + 100, + 250, + 500, + 1000, + 2500, + 5000, + 10000, + 25000, + ]; + return [...new Set(candidates)] + .filter((amount) => amount >= min && amount <= max) + .slice(0, 3) + .sort((a, b) => a - b); } diff --git a/src/utils/admin-payer-surcharge.ts b/src/utils/admin-payer-surcharge.ts index 78663d3c..20cd2c0c 100644 --- a/src/utils/admin-payer-surcharge.ts +++ b/src/utils/admin-payer-surcharge.ts @@ -78,22 +78,31 @@ export function calculateAdminPayerFeeBps(options: AdminPayerSurchargeOptions): maxFeeBps = MAX_REFERRAL_FEE_BPS, } = options; + const fallback = clampBps( + Number.isFinite(baseFeeBps) ? baseFeeBps : minFeeBps, + minFeeBps, + maxFeeBps, + ); + const pricesAndAmounts = [ + tradeAmountRaw, + tradePriceUsd, + deficitLamports, + solPriceUsd, + baseFeeBps, + ]; if ( - tradeAmountRaw <= 0 || + !Number.isInteger(tradeDecimals) || tradeDecimals < 0 || - tradePriceUsd <= 0 || - deficitLamports <= 0 || - solPriceUsd <= 0 || - baseFeeBps <= 0 + !pricesAndAmounts.every((value) => Number.isFinite(value) && value > 0) ) { - return clampBps(baseFeeBps, minFeeBps, maxFeeBps); + return fallback; } const tradeUsd = (tradeAmountRaw / Math.pow(10, tradeDecimals)) * tradePriceUsd; const deficitUsd = (deficitLamports / LAMPORTS_PER_SOL) * solPriceUsd; - if (tradeUsd <= 0 || deficitUsd <= 0) { - return clampBps(baseFeeBps, minFeeBps, maxFeeBps); + if (!Number.isFinite(tradeUsd) || tradeUsd === 0 || !Number.isFinite(deficitUsd)) { + return fallback; } const extraBps = Math.ceil((deficitUsd / tradeUsd) * 10_000); diff --git a/src/utils/amount.ts b/src/utils/amount.ts index cce7d1a1..53768709 100644 --- a/src/utils/amount.ts +++ b/src/utils/amount.ts @@ -66,8 +66,9 @@ export const parseTradeAmountInput = (amount: string): TradeAmountParseResult => } if (trimmed.includes("%")) { - const percentage = Number.parseFloat(trimmed.replace(/%/g, "")); - if (!Number.isFinite(percentage) || percentage <= 0 || percentage > 100) { + const match = /^([+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?)\s*%$/i.exec(trimmed); + const percentage = Number(match?.[1]); + if (!(percentage > 0 && percentage <= 100)) { throw new Error("Invalid percentage format"); } @@ -127,22 +128,13 @@ export const evaluateTradeAmount = ({ const parsed = parseTradeAmountInput(amount); const isSolAsset = assetTicker === "SOL"; - const ensureTokenBalance = (): TradeTokenBalanceSnapshot => { + const getTokenSnapshot = (): TradeTokenBalanceSnapshot => { if (!tokenBalance || tokenBalance.balance <= 0) { throw new Error(`No ${assetTicker} balance found`); } return tokenBalance; }; - let cachedTokenBalance: TradeTokenBalanceSnapshot | null = null; - const getTokenSnapshot = (): TradeTokenBalanceSnapshot => { - if (cachedTokenBalance) { - return cachedTokenBalance; - } - cachedTokenBalance = ensureTokenBalance(); - return cachedTokenBalance; - }; - const resolveSolSpendable = (): number => { const spendable = applySolFeeBuffer ? Math.max(0, solBalance - solFeeBufferLamports) @@ -174,9 +166,9 @@ export const evaluateTradeAmount = ({ if (isSolAsset) { const spendableLamports = resolveSolSpendable(); const bufferLamports = Math.max(0, userSolBufferLamports ?? 0); - const availableLamports = Math.max(0, spendableLamports - bufferLamports); + const availableLamports = spendableLamports - bufferLamports; - if (bufferLamports >= spendableLamports || availableLamports <= 0) { + if (availableLamports <= 0) { const formattedBuffer = formatSol?.(bufferLamports) ?? `${bufferLamports} lamports`; throw new Error( insufficientSolMaxBufferMessage ?? @@ -218,10 +210,7 @@ export const evaluateTradeAmount = ({ throw new Error("Percentage results in zero amount"); } - const formatted = formatAmount(rawAmount, decimals, { - maxFractionDigits: decimals, - trim: true, - }); + const formatted = formatAmount(rawAmount, decimals); return { kind: "percentage", @@ -238,10 +227,7 @@ export const evaluateTradeAmount = ({ throw new Error("Percentage results in zero amount"); } - const formatted = formatAmount(rawAmount, tokenSnapshot.decimals, { - maxFractionDigits: tokenSnapshot.decimals, - trim: true, - }); + const formatted = formatAmount(rawAmount, tokenSnapshot.decimals); const displayOverride = formatDisplayAmount(rawAmount); const displayAmount = displayOverride ?? formatted; @@ -254,9 +240,7 @@ export const evaluateTradeAmount = ({ }; } - const rawAmount = parseDecimalAmount(parsed.normalized, decimals, { - returnType: "number", - }); + const rawAmount = parseDecimalAmount(parsed.normalized, decimals); if (isSolAsset) { const feeBuffer = applySolFeeBuffer ? solFeeBufferLamports : 0; @@ -296,31 +280,19 @@ export const presentTradeAmount = ( params: EvaluateTradeAmountParams, ): PresentedTradeAmountResult => { const evaluation = evaluateTradeAmount(params); - - const decimalsForFallback = - params.assetTicker === "SOL" - ? params.decimals - : (params.tokenBalance?.decimals ?? params.decimals); - - const fallbackFormatted = formatAmount(evaluation.rawAmount, decimalsForFallback, { - maxFractionDigits: decimalsForFallback, - trim: true, - }); - - const { normalizedAmount } = evaluation; + const decimals = + params.assetTicker !== "SOL" && params.tokenBalance + ? params.tokenBalance.decimals + : params.decimals; const displayAmount = evaluation.displayAmount || - (evaluation.kind === "max" && normalizedAmount === "max" - ? "max" - : params.assetTicker === "SOL" - ? (params.formatSol?.(evaluation.rawAmount) ?? fallbackFormatted) - : (params.formatToken?.(evaluation.rawAmount, decimalsForFallback) ?? fallbackFormatted)); + (evaluation.kind === "max" ? "max" : formatAmount(evaluation.rawAmount, decimals)); return { kind: evaluation.kind, rawAmount: evaluation.rawAmount, - normalizedAmount, + normalizedAmount: evaluation.normalizedAmount, displayAmount, }; }; diff --git a/src/utils/base-database.ts b/src/utils/base-database.ts index 58d1aa53..d6bbce5c 100644 --- a/src/utils/base-database.ts +++ b/src/utils/base-database.ts @@ -48,12 +48,12 @@ export function clearDatabaseForTesting(db: Database): void { export abstract class BaseDatabase { protected db: Database; private readonly name: string; - private readonly statements = new Map(); + private readonly statements = new Map>(); protected constructor(filename: string, initStatements: string[], name: string) { const resolvedFilename = resolveDatabaseFilename(filename); this.name = name; - this.db = new Database(resolvedFilename, { create: true }); + this.db = new Database(resolvedFilename); try { // WAL + synchronous=NORMAL turns each write from a blocking journal fsync on @@ -72,7 +72,7 @@ export abstract class BaseDatabase { } } - private prepare(sql: string): Statement { + private prepare(sql: string): Statement { const cached = this.statements.get(sql); if (cached) return cached; @@ -80,20 +80,20 @@ export abstract class BaseDatabase { for (const statement of this.statements.values()) statement.finalize(); this.statements.clear(); } - const statement = this.db.prepare(sql); + const statement = this.db.prepare(sql); this.statements.set(sql, statement); return statement; } protected run( sql: string, - params: SQLQueryBindings | SQLQueryBindings[] = [], + params?: SQLQueryBindings | SQLQueryBindings[], operation: string = "running statement", ): Changes { try { const stmt = this.prepare(sql); const normalizedParams = this.normalizeParams(params); - return stmt.run(...(normalizedParams as any)); + return stmt.run(...normalizedParams); } catch (error) { return this.handleError(`during ${operation}`, error); } @@ -101,13 +101,13 @@ export abstract class BaseDatabase { protected get( sql: string, - params: SQLQueryBindings | SQLQueryBindings[] = [], + params?: SQLQueryBindings | SQLQueryBindings[], operation: string = "executing query", ): T | null { try { const stmt = this.prepare(sql); const normalizedParams = this.normalizeParams(params); - const result = stmt.get(...(normalizedParams as any)) as T | undefined; + const result = stmt.get(...normalizedParams) as T | null; return result ?? null; } catch (error) { return this.handleError(`during ${operation}`, error); @@ -116,13 +116,13 @@ export abstract class BaseDatabase { protected all( sql: string, - params: SQLQueryBindings | SQLQueryBindings[] = [], + params?: SQLQueryBindings | SQLQueryBindings[], operation: string = "executing query", ): T[] { try { const stmt = this.prepare(sql); const normalizedParams = this.normalizeParams(params); - return stmt.all(...(normalizedParams as any)) as T[]; + return stmt.all(...normalizedParams) as T[]; } catch (error) { return this.handleError(`during ${operation}`, error); } @@ -130,15 +130,11 @@ export abstract class BaseDatabase { protected getCount( sql: string, - params: SQLQueryBindings | SQLQueryBindings[] = [], + params?: SQLQueryBindings | SQLQueryBindings[], operation: string = "executing count query", ): number { - try { - const result = this.get<{ count: number }>(sql, params, operation); - return result?.count ?? 0; - } catch (error) { - this.handleError(`during ${operation}`, error); - } + const result = this.get<{ count: number }>(sql, params, operation); + return result?.count ?? 0; } private normalizeParams( diff --git a/src/utils/callback-data.ts b/src/utils/callback-data.ts index 7ce80046..e458cc37 100644 --- a/src/utils/callback-data.ts +++ b/src/utils/callback-data.ts @@ -1,10 +1,13 @@ import type { GameType } from "../types"; +import { formatAmount } from "./format-amount"; export const CALLBACK_DATA_LIMIT = 64; const CALLBACK_SEPARATOR = "|"; const AMOUNT_SEPARATOR = ":"; const ALPHABET = "0123456789abcdefghijklmnopqrstuvwxyz"; +// A Solana token stores the decimal count in one unsigned byte. +const MAX_AMOUNT_SCALE = 255; const CALLBACK_PREFIX = { confirmGame: "cg", @@ -22,7 +25,7 @@ const toGameTypeCode = (gameType: GameType): "c" | "g" => { return gameType === "coinflip" ? "c" : "g"; }; -const fromGameTypeCode = (code: string): GameType | null => { +const fromGameTypeCode = (code: string | undefined): GameType | null => { if (code === "c") return "coinflip"; if (code === "g") return "giveaway"; return null; @@ -30,57 +33,46 @@ const fromGameTypeCode = (code: string): GameType | null => { const decodeBase36ToBigInt = (value: string): bigint | null => { if (value.length === 0) return null; - const isNegative = value.startsWith("-"); - const raw = isNegative ? value.slice(1) : value; let result = 0n; - for (const char of raw.toLowerCase()) { + for (const char of value.toLowerCase()) { const idx = ALPHABET.indexOf(char); if (idx === -1) return null; result = result * 36n + BigInt(idx); } - return isNegative ? -result : result; + return result; }; const encodeUnsigned = (value: number): string | null => { - if (!Number.isFinite(value) || value < 0) return null; - const rounded = Math.round(value); - if (rounded < 0) return null; - return rounded.toString(36); + return value < 0 ? null : encodeSigned(value); }; const encodeSigned = (value: number): string | null => { - if (!Number.isFinite(value)) return null; const rounded = Math.round(value); - return rounded.toString(36); + return Number.isSafeInteger(rounded) ? rounded.toString(36) : null; }; const decodeUnsigned = (value: string | undefined): number | null => { - if (!value) return null; - const parsed = Number.parseInt(value, 36); - if (!Number.isFinite(parsed) || parsed < 0) return null; - return parsed; + const parsed = decodeSigned(value); + return parsed === null || parsed < 0 ? null : parsed; }; const decodeSigned = (value: string | undefined): number | null => { - if (!value) return null; + if (!value || !/^-?[0-9a-z]+$/i.test(value)) return null; const parsed = Number.parseInt(value, 36); - if (!Number.isFinite(parsed)) return null; - return parsed; + return Number.isSafeInteger(parsed) ? parsed : null; }; const normalizeAmount = (amount: string): { digits: bigint; scale: number } | null => { if (typeof amount !== "string") return null; const trimmed = amount.trim(); if (!/^\d+(?:\.\d+)?$/.test(trimmed)) return null; - const [intPartRaw = "0", fractionRaw = ""] = trimmed.split("."); - const intPart = intPartRaw.replace(/^0+(?=\d)/, "") || "0"; - const fraction = fractionRaw.replace(/0+$/, ""); - const scale = fraction.length; - const digitsString = `${intPart}${fraction}`; - const digits = digitsString.length > 0 ? BigInt(digitsString) : 0n; - return { digits, scale }; + const decimalPoint = trimmed.indexOf("."); + if (decimalPoint === -1) return { digits: BigInt(trimmed), scale: 0 }; + const fraction = trimmed.slice(decimalPoint + 1).replace(/0+$/, ""); + if (fraction.length > MAX_AMOUNT_SCALE) return null; + return { digits: BigInt(trimmed.slice(0, decimalPoint) + fraction), scale: fraction.length }; }; const encodeAmount = (amount: string): string | null => { @@ -93,22 +85,14 @@ const encodeAmount = (amount: string): string | null => { const decodeAmount = (encoded: string | undefined): string | null => { if (!encoded) return null; - const [scaleStr, digitsStr] = encoded.split(AMOUNT_SEPARATOR); - if (scaleStr === undefined || digitsStr === undefined) return null; - const scale = Number.parseInt(scaleStr, 36); - if (!Number.isFinite(scale) || scale < 0) return null; - const digits = decodeBase36ToBigInt(digitsStr); + const separator = encoded.indexOf(AMOUNT_SEPARATOR); + if (separator < 1) return null; + const scale = decodeUnsigned(encoded.slice(0, separator)); + if (scale === null || scale > MAX_AMOUNT_SCALE) return null; + const digits = decodeBase36ToBigInt(encoded.slice(separator + 1)); if (digits === null) return null; - const decimal = digits.toString(10); - if (scale === 0) { - return decimal; - } - - const padded = decimal.padStart(scale + 1, "0"); - const intPart = padded.slice(0, -scale) || "0"; - const fracPart = padded.slice(-scale).replace(/0+$/, ""); - return fracPart.length > 0 ? `${intPart}.${fracPart}` : intPart; + return formatAmount(digits, scale); }; const encodeCreatorId = (creatorId?: string): string | null => { @@ -140,10 +124,8 @@ const decodeCreatorId = (encoded: string | undefined): string | null => { }; const buildCallback = (parts: string[]): string | null => { - if (parts.some((part) => part === "")) return null; const payload = parts.join(CALLBACK_SEPARATOR); - if (Buffer.byteLength(payload, "utf-8") > CALLBACK_DATA_LIMIT) return null; - return payload; + return isCallbackSafeLength(payload) ? payload : null; }; const parseCallbackParts = ( @@ -151,7 +133,7 @@ const parseCallbackParts = ( expectedPrefix: CallbackPrefix, totalParts: number, ): string[] | null => { - if (!data) return null; + if (!data || !isCallbackSafeLength(data)) return null; const parts = data.split(CALLBACK_SEPARATOR); if (parts[0] !== expectedPrefix) return null; if (parts.length !== totalParts) return null; @@ -197,13 +179,13 @@ export const decodeGameConfirmPayload = ( ): EncodedGameConfirmPayload | null => { const parts = parseCallbackParts(data, CALLBACK_PREFIX.confirmGame, 8); if (!parts) return null; - const gameType = fromGameTypeCode(parts[1]!); - const amount = decodeAmount(parts[2]!); - const players = decodeUnsigned(parts[3]!); - const timeoutSeconds = decodeUnsigned(parts[4]!); - const minPlayers = decodeUnsigned(parts[5]!); + const gameType = fromGameTypeCode(parts[1]); + const amount = decodeAmount(parts[2]); + const players = decodeUnsigned(parts[3]); + const timeoutSeconds = decodeUnsigned(parts[4]); + const minPlayers = decodeUnsigned(parts[5]); const isPrivate = parts[6] === "1"; - const creatorId = decodeCreatorId(parts[7]!); + const creatorId = decodeCreatorId(parts[7]); if ( !gameType || @@ -260,11 +242,11 @@ export const decodeTimeoutChangePayload = ( ): EncodedTimeoutChangePayload | null => { const parts = parseCallbackParts(data, CALLBACK_PREFIX.timeoutChange, 6); if (!parts) return null; - const gameType = fromGameTypeCode(parts[1]!); - const amount = decodeAmount(parts[2]!); - const players = decodeUnsigned(parts[3]!); - const deltaMinutes = decodeSigned(parts[4]!); - const creatorId = decodeCreatorId(parts[5]!); + const gameType = fromGameTypeCode(parts[1]); + const amount = decodeAmount(parts[2]); + const players = decodeUnsigned(parts[3]); + const deltaMinutes = decodeSigned(parts[4]); + const creatorId = decodeCreatorId(parts[5]); if (!gameType || amount === null || players === null || deltaMinutes === null || !creatorId) { return null; @@ -312,11 +294,11 @@ export const decodeVisibilityPayload = ( ): EncodedVisibilityPayload | null => { const parts = parseCallbackParts(data, CALLBACK_PREFIX.visibility, 6); if (!parts) return null; - const gameType = fromGameTypeCode(parts[1]!); - const amount = decodeAmount(parts[2]!); - const players = decodeUnsigned(parts[3]!); + const gameType = fromGameTypeCode(parts[1]); + const amount = decodeAmount(parts[2]); + const players = decodeUnsigned(parts[3]); const isPrivate = parts[4] === "1"; - const creatorId = decodeCreatorId(parts[5]!); + const creatorId = decodeCreatorId(parts[5]); if (!gameType || amount === null || players === null || !creatorId) { return null; @@ -364,11 +346,11 @@ export const decodeMinPlayersChangePayload = ( ): EncodedMinPlayersChangePayload | null => { const parts = parseCallbackParts(data, CALLBACK_PREFIX.minPlayersChange, 6); if (!parts) return null; - const gameType = fromGameTypeCode(parts[1]!); - const amount = decodeAmount(parts[2]!); - const players = decodeUnsigned(parts[3]!); - const deltaPlayers = decodeSigned(parts[4]!); - const creatorId = decodeCreatorId(parts[5]!); + const gameType = fromGameTypeCode(parts[1]); + const amount = decodeAmount(parts[2]); + const players = decodeUnsigned(parts[3]); + const deltaPlayers = decodeSigned(parts[4]); + const creatorId = decodeCreatorId(parts[5]); if (!gameType || amount === null || players === null || deltaPlayers === null || !creatorId) { return null; @@ -410,9 +392,9 @@ export const decodeAmountSelectionPayload = ( ): EncodedAmountSelectionPayload | null => { const parts = parseCallbackParts(data, CALLBACK_PREFIX.amountSelection, 4); if (!parts) return null; - const gameType = fromGameTypeCode(parts[1]!); - const amount = decodeAmount(parts[2]!); - const creatorId = decodeCreatorId(parts[3]!); + const gameType = fromGameTypeCode(parts[1]); + const amount = decodeAmount(parts[2]); + const creatorId = decodeCreatorId(parts[3]); if (!gameType || amount === null || !creatorId) { return null; @@ -455,10 +437,10 @@ export const decodePlayersSelectionPayload = ( ): EncodedPlayersSelectionPayload | null => { const parts = parseCallbackParts(data, CALLBACK_PREFIX.playersSelection, 5); if (!parts) return null; - const gameType = fromGameTypeCode(parts[1]!); - const amount = decodeAmount(parts[2]!); - const players = decodeUnsigned(parts[3]!); - const creatorId = decodeCreatorId(parts[4]!); + const gameType = fromGameTypeCode(parts[1]); + const amount = decodeAmount(parts[2]); + const players = decodeUnsigned(parts[3]); + const creatorId = decodeCreatorId(parts[4]); if (!gameType || amount === null || players === null || !creatorId) { return null; @@ -499,9 +481,9 @@ export const decodeCustomPlayersPayload = ( ): EncodedCustomPlayersPayload | null => { const parts = parseCallbackParts(data, CALLBACK_PREFIX.customPlayers, 4); if (!parts) return null; - const gameType = fromGameTypeCode(parts[1]!); - const amount = decodeAmount(parts[2]!); - const creatorId = decodeCreatorId(parts[3]!); + const gameType = fromGameTypeCode(parts[1]); + const amount = decodeAmount(parts[2]); + const creatorId = decodeCreatorId(parts[3]); if (!gameType || amount === null || !creatorId) { return null; @@ -515,6 +497,5 @@ export const decodeCustomPlayersPayload = ( }; export const isCallbackSafeLength = (callback: string | undefined | null) => { - if (!callback) return false; - return Buffer.byteLength(callback, "utf-8") <= CALLBACK_DATA_LIMIT; + return Boolean(callback && Buffer.byteLength(callback) <= CALLBACK_DATA_LIMIT); }; diff --git a/src/utils/expiring-cache.ts b/src/utils/expiring-cache.ts index ae7bd193..f3d629eb 100644 --- a/src/utils/expiring-cache.ts +++ b/src/utils/expiring-cache.ts @@ -11,38 +11,14 @@ export interface ExpiringCache { clear(): void; } -const NO_TTL = 0; - class ExpiringCacheImpl implements ExpiringCache { private readonly entries = new Map(); - private readonly staleEntries = new Map(); - private readonly timers = new Map>(); constructor(private readonly defaultTtlMs: number) {} setWithTTL(key: string, value: TValue, ttlMs: number = this.defaultTtlMs): void { - this.clearTimer(key); - this.staleEntries.delete(key); - - const ttl = ttlMs > NO_TTL ? ttlMs : this.defaultTtlMs; - const expiresAt = ttl > NO_TTL ? Date.now() + ttl : Number.POSITIVE_INFINITY; - - if (ttl > NO_TTL) { - const timer = setTimeout(() => { - const entry = this.entries.get(key); - if (entry && entry.expiresAt <= Date.now()) { - this.entries.delete(key); - this.staleEntries.set(key, entry.value); - } - this.timers.delete(key); - }, ttl); - if (typeof (timer as NodeJS.Timeout).unref === "function") { - (timer as NodeJS.Timeout).unref(); - } - this.timers.set(key, timer); - } - - this.entries.set(key, { value, expiresAt }); + const ttl = Number.isFinite(ttlMs) && ttlMs > 0 ? ttlMs : this.defaultTtlMs; + this.entries.set(key, { value, expiresAt: Date.now() + ttl }); } get(key: string): TValue | undefined { @@ -52,8 +28,8 @@ class ExpiringCacheImpl implements ExpiringCache { } if (entry.expiresAt <= Date.now()) { - this.entries.delete(key); - this.staleEntries.set(key, entry.value); + // Keep the stale value for peek(). A clock adjustment must not revive it. + entry.expiresAt = Number.NEGATIVE_INFINITY; return undefined; } @@ -61,17 +37,11 @@ class ExpiringCacheImpl implements ExpiringCache { } peek(key: string): TValue | undefined { - const entry = this.entries.get(key); - if (entry) { - return entry.value; - } - return this.staleEntries.get(key); + return this.entries.get(key)?.value; } delete(key: string): boolean { - const existed = this.entries.delete(key) || this.staleEntries.delete(key); - this.clearTimer(key); - return existed; + return this.entries.delete(key); } has(key: string): boolean { @@ -79,24 +49,12 @@ class ExpiringCacheImpl implements ExpiringCache { } clear(): void { - for (const key of this.timers.keys()) { - this.clearTimer(key); - } this.entries.clear(); - this.staleEntries.clear(); - } - - private clearTimer(key: string): void { - const timer = this.timers.get(key); - if (timer) { - clearTimeout(timer); - this.timers.delete(key); - } } } export const createExpiringCache = (defaultTtlMs: number): ExpiringCache => { - if (defaultTtlMs <= NO_TTL) { + if (!Number.isFinite(defaultTtlMs) || defaultTtlMs <= 0) { throw new Error("ExpiringCache requires a positive default TTL"); } diff --git a/tests/admin-payer-surcharge.test.ts b/tests/admin-payer-surcharge.test.ts index 927b141d..ecafba5f 100644 --- a/tests/admin-payer-surcharge.test.ts +++ b/tests/admin-payer-surcharge.test.ts @@ -3,6 +3,7 @@ import { calculateAdminPayerFeeBps, calculateReferralFeeBps, computeRequiredAdminLamports, + type AdminPayerSurchargeOptions, } from "../src/utils/admin-payer-surcharge"; describe("calculateAdminPayerFeeBps", () => { @@ -75,6 +76,43 @@ describe("calculateAdminPayerFeeBps", () => { }); describe("calculateAdminPayerFeeBps degenerate values", () => { + const trade = { + baseFeeBps: 85, + tradeAmountRaw: 100, + tradeDecimals: 0, + tradePriceUsd: 2, + deficitLamports: 1_000_000, + solPriceUsd: 200, + }; + + test("charges the exact surcharge for a zero-decimal token priced above a dollar", () => { + expect(calculateAdminPayerFeeBps(trade)).toBe(95); + }); + + test.each<[keyof AdminPayerSurchargeOptions, number]>([ + ["tradeAmountRaw", 0], + ["tradeAmountRaw", -1], + ["tradeAmountRaw", NaN], + ["tradeDecimals", -1], + ["tradeDecimals", 0.5], + ["tradePriceUsd", 0], + ["tradePriceUsd", -1], + ["tradePriceUsd", Infinity], + ["deficitLamports", -1], + ["solPriceUsd", 0], + ["solPriceUsd", -1], + ["solPriceUsd", NaN], + ])("keeps the base fee for invalid %s (%p)", (field, value) => { + expect(calculateAdminPayerFeeBps({ ...trade, [field]: value })).toBe(85); + }); + + test("falls back to the minimum when the base fee is not usable", () => { + for (const baseFeeBps of [0, -1, NaN]) { + expect( + calculateAdminPayerFeeBps({ ...trade, baseFeeBps, deficitLamports: 100_000_000 }), + ).toBe(50); + } + }); test("returns the clamped base fee when the trade value underflows to zero", () => { expect( calculateAdminPayerFeeBps({ diff --git a/tests/amount.trade-evaluation.test.ts b/tests/amount.trade-evaluation.test.ts index 5bbeb844..c9af6d6f 100644 --- a/tests/amount.trade-evaluation.test.ts +++ b/tests/amount.trade-evaluation.test.ts @@ -3,7 +3,121 @@ import { evaluateTradeAmount, presentTradeAmount } from "../src/utils/amount"; const token = (balance: number, decimals = 6) => ({ balance, decimals }); +describe("evaluateTradeAmount SOL balance boundaries", () => { + const sol = { assetTicker: "SOL", decimals: 9, solBalance: 100_000_000 }; + + test("allows spending the exact balance when no fee reservation is requested", () => { + expect( + evaluateTradeAmount({ ...sol, amount: "0.1", solFeeBufferLamports: 50_000_000 }), + ).toEqual({ + kind: "absolute", + rawAmount: 100_000_000, + displayAmount: undefined, + normalizedAmount: "0.1", + }); + }); + + test("rejects one unit beyond an unbuffered SOL balance", () => { + expect(() => evaluateTradeAmount({ ...sol, amount: "0.100000001" })).toThrow( + "Insufficient SOL balance", + ); + }); + + test("leaves the safety reserve behind and presents max without a formatter", () => { + expect(presentTradeAmount({ ...sol, amount: "max", userSolBufferLamports: 1 })).toEqual({ + kind: "max", + rawAmount: 99_999_999, + normalizedAmount: "max", + displayAmount: "max", + }); + }); + + test("allows spending down to the exact fee reserve", () => { + const defaults = { ...sol, applySolFeeBuffer: true, solFeeBufferLamports: 25_000_000 }; + expect(evaluateTradeAmount({ ...defaults, amount: "0.075" }).rawAmount).toBe(75_000_000); + expect(() => evaluateTradeAmount({ ...defaults, amount: "0.075000001" })).toThrow( + "Insufficient SOL balance for this purchase", + ); + }); + + test("calculates percentages against the spendable balance", () => { + expect( + evaluateTradeAmount({ + ...sol, + amount: "50%", + applySolFeeBuffer: true, + solFeeBufferLamports: 20_000_000, + }), + ).toEqual({ + kind: "percentage", + rawAmount: 40_000_000, + displayAmount: undefined, + normalizedAmount: "0.04", + }); + }); + + test("shows the reserve when fees use all SOL and no display callback is provided", () => { + expect(() => + evaluateTradeAmount({ + ...sol, + amount: "max", + applySolFeeBuffer: true, + solFeeBufferLamports: sol.solBalance, + }), + ).toThrow("Not enough SOL to cover purchase and fees (keep ~100000000 lamports for fees)"); + }); + + test("omits fee hints when the reserve is zero or the caller suppresses it", () => { + expect(() => + evaluateTradeAmount({ ...sol, solBalance: 0, amount: "max", applySolFeeBuffer: true }), + ).toThrow(/^Not enough SOL to cover purchase and fees$/); + expect(() => + evaluateTradeAmount({ + ...sol, + amount: "max", + applySolFeeBuffer: true, + solFeeBufferLamports: sol.solBalance, + omitSolFeeBufferHint: true, + }), + ).toThrow(/^Not enough SOL to cover purchase and fees$/); + }); + + test("names the safety reserve if max would leave no spendable SOL", () => { + expect(() => + evaluateTradeAmount({ ...sol, amount: "max", userSolBufferLamports: sol.solBalance }), + ).toThrow("Not enough SOL to keep 100000000 lamports as a safety buffer when using max amount"); + }); +}); + describe("evaluateTradeAmount token edge cases", () => { + test("accepts spending the exact token balance", () => { + expect( + evaluateTradeAmount({ + amount: "1.23", + assetTicker: "TOK", + decimals: 2, + solBalance: 0, + tokenBalance: token(123, 2), + }), + ).toEqual({ + kind: "absolute", + rawAmount: 123, + displayAmount: undefined, + normalizedAmount: "1.23", + }); + }); + + test("rejects spending one raw unit above the token balance", () => { + expect(() => + evaluateTradeAmount({ + amount: "1.24", + assetTicker: "TOK", + decimals: 2, + solBalance: 0, + tokenBalance: token(123, 2), + }), + ).toThrow("Insufficient token balance"); + }); test("rejects a token trade when no balance snapshot exists", () => { expect(() => evaluateTradeAmount({ amount: "1", assetTicker: "BONK", decimals: 5, solBalance: 1e9 }), @@ -95,9 +209,30 @@ describe("presentTradeAmount display fallbacks", () => { assetTicker: "USDC", decimals: 6, solBalance: 0, - tokenBalance: token(5_000_000, 6), + tokenBalance: token(5_000_000, 0), + }).displayAmount, + ).toBe("1500000"); + expect( + presentTradeAmount({ + amount: "1.5", + assetTicker: "TOK", + decimals: 3, + solBalance: 0, + tokenBalance: token(5_000, 2), + }).displayAmount, + ).toBe("15"); + }); + + test("uses the exact amount if a display callback produces an empty string", () => { + expect( + presentTradeAmount({ + amount: "0.5", + assetTicker: "SOL", + decimals: 9, + solBalance: 1_000_000_000, + formatSol: () => "", }).displayAmount, - ).toBe("1.5"); + ).toBe("0.5"); }); test("prefers the provided formatters", () => { diff --git a/tests/base-database.internals.test.ts b/tests/base-database.internals.test.ts index a0912dc1..f6f96720 100644 --- a/tests/base-database.internals.test.ts +++ b/tests/base-database.internals.test.ts @@ -30,6 +30,16 @@ class ProbeDatabase extends BaseDatabase { return this.getCount(sql, params, "counting probes"); } + unbound() { + const insert = this.run("INSERT INTO probe VALUES (3, 'third')"); + return { + insert, + get: this.get<{ label: string }>("SELECT label FROM probe WHERE id = 3"), + all: this.all<{ label: string }>("SELECT label FROM probe"), + count: this.getCount("SELECT count(*) AS count FROM probe"), + }; + } + close() { this.db.close(); } @@ -52,6 +62,14 @@ afterEach(() => { }); describe("BaseDatabase statement cache", () => { + test("reuses a compiled SQL statement on repeat reads", () => { + const query = "SELECT 1 AS n"; + expect(db.select(query)).toEqual([{ n: 1 }]); + const first = db.cachedStatement(query); + expect(db.select(query)).toEqual([{ n: 1 }]); + expect(db.cachedStatement(query)).toBe(first); + }); + test("drops every cached statement once the cache reaches its limit and keeps working", () => { for (let i = 0; i < 256; i += 1) { expect(db.select(`SELECT ${i} AS n`)).toEqual([{ n: i }]); @@ -73,6 +91,14 @@ describe("BaseDatabase statement cache", () => { }); describe("BaseDatabase.getCount", () => { + test("runs queries with no bindings or operation label", () => { + const result = db.unbound(); + expect(result.insert.changes).toBe(1); + expect(result.get).toEqual({ label: "third" }); + expect(result.all).toEqual([{ label: "third" }]); + expect(result.count).toBe(1); + }); + test("returns the count column, or zero when the query yields no row", () => { db.insert(1, "a"); db.insert(2, "b"); @@ -83,6 +109,7 @@ describe("BaseDatabase.getCount", () => { test("logs and rethrows when the underlying query fails", () => { expect(() => db.count("SELECT COUNT(*) AS count FROM missing_table")).toThrow(/missing_table/); const messages = errorSpy.mock.calls.map((call: unknown[]) => String(call[0])); + expect(messages).toHaveLength(1); expect( messages.some((m: string) => m.includes("[Probe DB] Error during counting probes:")), ).toBe(true); diff --git a/tests/buy-alerts.holder.test.ts b/tests/buy-alerts.holder.test.ts index 40703182..39012951 100644 --- a/tests/buy-alerts.holder.test.ts +++ b/tests/buy-alerts.holder.test.ts @@ -57,6 +57,20 @@ describe("isNewHolderFromBalances edge cases", () => { ).toBe(false); }); + test("does not take balances from a different owner or an incomplete row", () => { + expect( + isNewHolderFromBalances({ + mint, + owner, + preTokenBalances: [ + { owner, uiTokenAmount: { uiAmount: 3 } }, + { mint, uiTokenAmount: { uiAmount: 3 } }, + { mint, owner: "other", uiTokenAmount: { uiAmount: 3 } }, + ], + }), + ).toBe(true); + }); + test("falls back to the raw amount when uiAmount is missing", () => { expect(withPre({ uiAmount: null, amount: "0" })).toBe(true); expect(withPre({ uiAmount: null, amount: " 1500 " })).toBe(false); @@ -104,6 +118,7 @@ describe("detectNewHolder", () => { expect( await detectNewHolder({ getParsedTransaction: async () => ({ meta: null }) }, event), ).toBeNull(); + expect(warnSpy).not.toHaveBeenCalled(); }); test("skips the lookup for blank and synthetic test signatures", async () => { diff --git a/tests/buy-alerts.keyboard.test.ts b/tests/buy-alerts.keyboard.test.ts index c37672c2..1d744401 100644 --- a/tests/buy-alerts.keyboard.test.ts +++ b/tests/buy-alerts.keyboard.test.ts @@ -24,6 +24,11 @@ test("parseBuyAlertMint accepts a valid mint and rejects junk", () => { expect(parseBuyAlertMint("buy_alert_not-a-mint")).toBeNull(); expect(parseBuyAlertMint("swap_to_SOL_USDC")).toBeNull(); expect(parseBuyAlertMint(undefined)).toBeNull(); + expect(buyAlertCallbackData(` ${TIMBA_MINT} `)).toBe(`${BUY_ALERT_CALLBACK_PREFIX}${TIMBA_MINT}`); + expect(parseBuyAlertMint(`${BUY_ALERT_CALLBACK_PREFIX} ${TIMBA_MINT} `)).toBe(TIMBA_MINT); + expect( + parseBuyAlertMint(`${"x".repeat(BUY_ALERT_CALLBACK_PREFIX.length)}${TIMBA_MINT}`), + ).toBeNull(); }); test("createBuyAlertKeyboard labels Buy with the group ticker", () => { @@ -40,7 +45,7 @@ test("createBuyAlertKeyboard uses a DM start link when the bot username is known const button = keyboard.inline_keyboard[0]?.[0]; expect(button?.text).toBe("BUY MAGAIBA"); expect(button && "url" in button ? button.url : undefined).toBe( - buyAlertDeepLinkUrl("playtimbabot", TIMBA_MINT), + `https://t.me/playtimbabot?start=ba_${TIMBA_MINT}`, ); expect(buyAlertStartPayload(TIMBA_MINT).length).toBeLessThanOrEqual(64); }); @@ -59,6 +64,17 @@ test("malformed start payloads do not hijack /start", () => { expect(parseBuyAlertStartText("/start leftover")).toBeNull(); expect(parseBuyAlertStartPayload("ba_")).toBeNull(); expect(parseBuyAlertStartPayload(undefined)).toBeNull(); + expect(parseBuyAlertStartPayload(`xx_${TIMBA_MINT}`)).toBeNull(); + expect(parseBuyAlertStartPayload(` ba_${TIMBA_MINT}\t`)).toBe(TIMBA_MINT); + expect(parseBuyAlertStartText(undefined)).toBeNull(); + expect(parseBuyAlertStartText(`quoted /start ba_${TIMBA_MINT}`)).toBeNull(); + expect(parseBuyAlertStartText(`/START@playtimbabot \tba_${TIMBA_MINT}`)).toBe(TIMBA_MINT); +}); + +test("builds a Telegram deep link from a copied bot handle and mint", () => { + expect(buyAlertDeepLinkUrl(" @@playtimbabot ", ` ${TIMBA_MINT} `)).toBe( + `https://t.me/playtimbabot?start=ba_${TIMBA_MINT}`, + ); }); test("buyAlertButtonLabel falls back and stays within Telegram's button limit", () => { @@ -68,6 +84,8 @@ test("buyAlertButtonLabel falls back and stays within Telegram's button limit", const label = buyAlertButtonLabel(long); expect(label.startsWith("BUY ")).toBe(true); expect(label.length).toBeLessThanOrEqual(64); + expect(buyAlertButtonLabel(" abc \tXY ")).toBe("BUY ABCXY"); + expect(buyAlertButtonLabel("x".repeat(60))).toBe(`BUY ${"X".repeat(60)}`); }); test("createBuyAlertKeyboard ignores a blank bot username", () => { @@ -77,3 +95,10 @@ test("createBuyAlertKeyboard ignores a blank bot username", () => { buyAlertCallbackData(TIMBA_MINT), ); }); + +test("invalid bot handles use a Telegram callback instead of a broken link", () => { + expect(buyAlertDeepLinkUrl("wrong@handle", TIMBA_MINT)).toBeNull(); + const button = createBuyAlertKeyboard(TIMBA_MINT, "TIMBA", "wrong@handle") + .inline_keyboard[0]?.[0]; + expect(button).toMatchObject({ callback_data: buyAlertCallbackData(TIMBA_MINT) }); +}); diff --git a/tests/buy-alerts.parser.test.ts b/tests/buy-alerts.parser.test.ts new file mode 100644 index 00000000..525dded3 --- /dev/null +++ b/tests/buy-alerts.parser.test.ts @@ -0,0 +1,18 @@ +import { expect, test } from "bun:test"; +import { mapDexFromPool } from "../src/services/buy-alerts/parser"; +import type { BuyDex } from "../src/services/buy-alerts/types"; + +test.each<[string | null | undefined, BuyDex]>([ + ["pump", "pump"], + ["pump-amm", "pump"], + ["pump-fun", "pump"], + ["pumpfun", "pump"], + [" PumpSwap ", "pump"], + [" Raydium-clmm ", "raydium"], + ["not-raydium", "unknown"], + ["", "unknown"], + [null, "unknown"], + [undefined, "unknown"], +])("recognizes the DEX from provider pool %p as %s", (pool, dex) => { + expect(mapDexFromPool(pool)).toBe(dex); +}); diff --git a/tests/buy-alerts.resolve.test.ts b/tests/buy-alerts.resolve.test.ts index 97311495..9828c766 100644 --- a/tests/buy-alerts.resolve.test.ts +++ b/tests/buy-alerts.resolve.test.ts @@ -13,8 +13,8 @@ test("resolveBuyAlertToken prefers an explicit chat override", () => { { chat_id: 1, enabled: true, - token_mint: "override-mint", - token_ticker: "MAGAIBA", + token_mint: " override-mint ", + token_ticker: " MAGAIBA ", min_sol_lamports: null, media_file_id: null, media_type: null, @@ -27,6 +27,26 @@ test("resolveBuyAlertToken prefers an explicit chat override", () => { ).toEqual({ mint: "override-mint", ticker: "MAGAIBA" }); }); +test("keeps the override mint even when the chat has not set a symbol", () => { + expect( + resolveBuyAlertToken( + { + chat_id: 1, + enabled: true, + token_mint: "override-mint", + token_ticker: null, + min_sol_lamports: null, + media_file_id: null, + media_type: null, + set_by_telegram_id: "1", + updated_at: 1, + }, + null, + botDefault, + ), + ).toEqual({ mint: "override-mint", ticker: "TOKEN" }); +}); + test("resolveBuyAlertToken falls back to chat default then bot default", () => { expect( resolveBuyAlertToken(null, { token_mint: "chat-mint", token_ticker: "CHAT" }, botDefault), @@ -40,6 +60,8 @@ test("resolveBuyAlertToken falls back to chat default then bot default", () => { test("formatMinSolLabel describes the configured floor", () => { expect(formatMinSolLabel(null)).toBe("Off"); + expect(formatMinSolLabel(0)).toBe("Off"); + expect(formatMinSolLabel(-1)).toBe("Off"); expect(formatMinSolLabel(50_000_000)).toBe("0.05 SOL"); expect(formatMinSolLabel(100_000_000)).toBe("0.1 SOL"); expect(formatMinSolLabel(1_000_000_000)).toBe("1 SOL"); @@ -50,9 +72,15 @@ test("parseMinSolInput accepts custom amounts and treats 0 as off", () => { expect(parseMinSolInput("0,25 SOL")).toEqual({ ok: true, minSolLamports: 250_000_000 }); expect(parseMinSolInput("2")).toEqual({ ok: true, minSolLamports: 2_000_000_000 }); expect(parseMinSolInput("off")).toEqual({ ok: true, minSolLamports: null }); + expect(parseMinSolInput(" NONE ")).toEqual({ ok: true, minSolLamports: null }); + expect(parseMinSolInput("0.001sol")).toEqual({ ok: true, minSolLamports: 1_000_000 }); + expect(parseMinSolInput("10000 SOL")).toEqual({ ok: true, minSolLamports: 10_000_000_000_000 }); expect(parseMinSolInput("0")).toEqual({ ok: true, minSolLamports: null }); expect(parseMinSolInput("")).toEqual({ ok: false }); expect(parseMinSolInput("nope")).toEqual({ ok: false }); expect(parseMinSolInput("0.0000001")).toEqual({ ok: false }); expect(parseMinSolInput("999999")).toEqual({ ok: false }); + expect(parseMinSolInput("-1 SOL")).toEqual({ ok: false }); + expect(parseMinSolInput("SOL 2")).toEqual({ ok: false }); + expect(parseMinSolInput("SOL")).toEqual({ ok: false }); }); diff --git a/tests/buy-alerts.swap-event.test.ts b/tests/buy-alerts.swap-event.test.ts index 1722af6e..fbb31780 100644 --- a/tests/buy-alerts.swap-event.test.ts +++ b/tests/buy-alerts.swap-event.test.ts @@ -109,6 +109,24 @@ test("buyEventFromSwap defaults SOL input to 9 decimals and labels it SOL", () = }); }); +test("buyEventFromSwap normalizes the quoted SOL mint, ticker and missing precision", () => { + expect( + buyEventFromSwap({ + ...base, + inputMint: ` ${WSOL_MINT} `, + inputTicker: " SOL ", + inputDecimals: Infinity, + outputDecimals: -2, + }), + ).toMatchObject({ + solAmount: 0.5, + inputAmount: 0.5, + inputSymbol: "SOL", + quoteSymbol: "SOL", + tokenAmount: 1000, + }); +}); + test("buyEventFromSwap defaults unknown token input to raw units without a symbol", () => { expect(buyEventFromSwap({ ...base, inputMint: "Other", inputAmountRaw: "42" })).toMatchObject({ solAmount: null, diff --git a/tests/callback-data.test.ts b/tests/callback-data.test.ts new file mode 100644 index 00000000..824f153c --- /dev/null +++ b/tests/callback-data.test.ts @@ -0,0 +1,139 @@ +import { expect, test } from "bun:test"; +import fc from "fast-check"; +import * as callback from "../src/utils/callback-data"; + +const base = { gameType: "coinflip" as const, amount: "0.0100200", creatorId: "9007199254740993" }; +const common = { ...base, amount: "0.01002" }; +const confirm = { ...base, players: 2, timeoutSeconds: 3600, minPlayers: 2, isPrivate: false }; +const timeout = { ...base, players: 2, deltaMinutes: -20 }; +const visibility = { ...base, players: 2, isPrivate: true }; +const minimum = { ...base, players: 2, deltaPlayers: -1 }; +const players = { ...base, players: 2 }; + +const fixtures = [ + { + name: "confirmation", + encode: () => callback.encodeGameConfirmPayload(confirm), + decode: callback.decodeGameConfirmPayload, + expected: { ...confirm, ...common }, + invalid: [1, 2, 3, 4, 5, 7], + }, + { + name: "timeout change", + encode: () => callback.encodeTimeoutChangePayload(timeout), + decode: callback.decodeTimeoutChangePayload, + expected: { ...timeout, ...common }, + invalid: [1, 2, 3, 4, 5], + }, + { + name: "visibility", + encode: () => callback.encodeVisibilityPayload(visibility), + decode: callback.decodeVisibilityPayload, + expected: { ...visibility, ...common }, + invalid: [1, 2, 3, 5], + }, + { + name: "minimum players", + encode: () => callback.encodeMinPlayersChangePayload(minimum), + decode: callback.decodeMinPlayersChangePayload, + expected: { ...minimum, ...common }, + invalid: [1, 2, 3, 4, 5], + }, + { + name: "amount selection", + encode: () => callback.encodeAmountSelectionPayload(base), + decode: callback.decodeAmountSelectionPayload, + expected: common, + invalid: [1, 2, 3], + }, + { + name: "players selection", + encode: () => callback.encodePlayersSelectionPayload(players), + decode: callback.decodePlayersSelectionPayload, + expected: { ...players, ...common }, + invalid: [1, 2, 3, 4], + }, + { + name: "custom players", + encode: () => callback.encodeCustomPlayersPayload(base), + decode: callback.decodeCustomPlayersPayload, + expected: common, + invalid: [1, 2, 3], + }, +]; + +for (const fixture of fixtures) { + test("round-trips " + fixture.name + " and refuses malformed fields", () => { + const payload = fixture.encode(); + if (!payload) throw new Error("Expected a valid fixture"); + expect(fixture.decode(payload)).toEqual(fixture.expected); + expect(fixture.decode(undefined)).toBeNull(); + expect(fixture.decode(payload + "|")).toBeNull(); + expect(fixture.decode(payload.replace(/^[^|]+/, "unknown"))).toBeNull(); + for (const index of fixture.invalid) { + const parts = payload.split("|"); + parts[index] = "!"; + expect(fixture.decode(parts.join("|"))).toBeNull(); + } + }); +} + +test("includes the exact 64-byte Telegram boundary", () => { + const payload = callback.encodeAmountSelectionPayload({ + ...base, + amount: "1", + creatorId: "x".repeat(40), + }); + if (!payload) throw new Error("Expected the exact-limit payload"); + expect(Buffer.byteLength(payload)).toBe(64); + expect(callback.isCallbackSafeLength(payload)).toBe(true); + expect( + callback.encodeAmountSelectionPayload({ ...base, amount: "1", creatorId: "x".repeat(41) }), + ).toBeNull(); + expect(callback.isCallbackSafeLength("é".repeat(32))).toBe(true); + expect(callback.isCallbackSafeLength("é".repeat(33))).toBe(false); + expect(callback.isCallbackSafeLength("")).toBe(false); +}); + +test("round-trips Unicode creator IDs as text", () => { + const payload = { ...base, gameType: "giveaway" as const, amount: "7", creatorId: "club-é-🟢" }; + expect( + callback.decodeCustomPlayersPayload(callback.encodeCustomPlayersPayload(payload) ?? undefined), + ).toEqual(payload); +}); + +test("preserves token precision through the highest decimal count", () => { + const valid = { ...base, amount: "0." + "0".repeat(254) + "1" }; + expect( + callback.decodeAmountSelectionPayload( + callback.encodeAmountSelectionPayload(valid) ?? undefined, + ), + ).toEqual(valid); + expect( + callback.encodeAmountSelectionPayload({ ...valid, amount: "0." + "0".repeat(255) + "1" }), + ).toBeNull(); +}); + +test("keeps decimal amounts exact through callback encoding", () => { + fc.assert( + fc.property( + fc.bigInt({ min: 0n, max: 10n ** 20n }), + fc.integer({ min: 0, max: 18 }), + (value, scale) => { + const divisor = 10n ** BigInt(scale); + const integer = String(value / divisor); + const places = String(value % divisor) + .padStart(scale, "0") + .replace(/0+$/, ""); + const amount = places ? integer + "." + places : integer; + const payload = { ...base, amount: " 000" + amount + " ", creatorId: "12345" }; + expect( + callback.decodeAmountSelectionPayload( + callback.encodeAmountSelectionPayload(payload) ?? undefined, + ), + ).toEqual({ ...payload, amount }); + }, + ), + { seed: 451 }, + ); +}); diff --git a/tests/database-reset.test.ts b/tests/database-reset.test.ts index 8a870a22..641aa4ad 100644 --- a/tests/database-reset.test.ts +++ b/tests/database-reset.test.ts @@ -82,6 +82,28 @@ describe("database reset", () => { } }); + test("preserves a SQLite URI instead of making it a bot data path", () => { + const uri = "file:synthetic-reset?mode=memory&cache=shared"; + expect(database.resolveDatabaseFilename(uri)).toBe(uri); + }); + + test("clears a user table ending in sqlite_ without erasing internal statistics", () => { + const db = new Database(":memory:"); + try { + db.run("CREATE TABLE ordinary_sqlite_ (id INTEGER PRIMARY KEY, label TEXT)"); + db.run("CREATE INDEX label_idx ON ordinary_sqlite_(label)"); + db.run("INSERT INTO ordinary_sqlite_ VALUES (1, 'test')"); + db.run("ANALYZE"); + const stats = db.query("SELECT * FROM sqlite_stat1").all(); + expect(stats).not.toEqual([]); + database.clearDatabaseForTesting(db); + expect(db.query("SELECT * FROM ordinary_sqlite_").all()).toEqual([]); + expect(db.query("SELECT * FROM sqlite_stat1").all()).toEqual(stats); + } finally { + db.close(); + } + }); + test("clears foreign-key tables without changing foreign-key enforcement", () => { const db = new Database(":memory:"); try { diff --git a/tests/decimal-amount.test.ts b/tests/decimal-amount.test.ts index 95b819bd..1b2baf81 100644 --- a/tests/decimal-amount.test.ts +++ b/tests/decimal-amount.test.ts @@ -11,6 +11,7 @@ test("rejects precision loss before constructing a transfer", () => { test("retains bot zero and safe-number policies around exact conversion", () => { expect(() => parseDecimalAmount("0", 0)).toThrow("greater than zero"); expect(parseDecimalAmount("0", 0, { allowZero: true })).toBe(0); + expect(parseDecimalAmount("9007199254740991", 0)).toBe(Number.MAX_SAFE_INTEGER); expect(() => parseDecimalAmount("9007199254740993", 0)).toThrow("too large"); expect(parseDecimalAmount("9007199254740993", 0, { returnType: "bigint" })).toBe( 9007199254740993n, diff --git a/tests/expiring-cache.test.ts b/tests/expiring-cache.test.ts index 4e8abbb4..cea8a756 100644 --- a/tests/expiring-cache.test.ts +++ b/tests/expiring-cache.test.ts @@ -1,55 +1,82 @@ -import { describe, expect, test } from "bun:test"; +import { afterEach, beforeEach, describe, expect, spyOn, test } from "bun:test"; import { createExpiringCache } from "../src/utils/expiring-cache"; -describe("createExpiringCache", () => { - test("throws when default TTL is non-positive", () => { - expect(() => createExpiringCache(0)).toThrow("positive default TTL"); - }); +test.each([0, -1, NaN, Infinity])("rejects invalid default TTL %p", (ttl) => { + expect(() => createExpiringCache(ttl)).toThrow("positive default TTL"); }); -describe("ExpiringCache behavior", () => { - test("entries expire and peek returns stale values", async () => { - const cache = createExpiringCache(20); - cache.setWithTTL("key", 42); +describe("ExpiringCache", () => { + let now: number; + let clock: ReturnType; + + beforeEach(() => { + now = 1000; + clock = spyOn(Date, "now").mockImplementation(() => now); + }); + afterEach(() => clock.mockRestore()); - expect(cache.get("key")).toBe(42); - await new Promise((resolve) => setTimeout(resolve, 30)); + test("expires at the exact deadline and never revives an expired value", () => { + const cache = createExpiringCache(20); + cache.setWithTTL("key", 0); + now += 19; + expect(cache.get("key")).toBe(0); + expect(cache.has("key")).toBe(true); + now += 1; expect(cache.get("key")).toBeUndefined(); - expect(cache.peek("key")).toBe(42); expect(cache.has("key")).toBe(false); + expect(cache.peek("key")).toBe(0); + now -= 5; + expect(cache.get("key")).toBeUndefined(); }); - test("delete removes entries and cancels timers", async () => { + test("replacing a stale value starts a new deadline with the explicit TTL", () => { const cache = createExpiringCache(20); - cache.setWithTTL("key", "value", 50); + cache.setWithTTL("key", "old"); + now += 30; + expect(cache.get("key")).toBeUndefined(); + cache.setWithTTL("key", "new", 50); + now += 49; + expect(cache.get("key")).toBe("new"); + now += 1; + expect(cache.get("key")).toBeUndefined(); + expect(cache.peek("key")).toBe("new"); + }); - cache.delete("key"); + test("deletes fresh and stale data and reports whether a key existed", () => { + const cache = createExpiringCache(20); + cache.setWithTTL("fresh", "one", 50); + cache.setWithTTL("stale", "two"); + now += 20; + expect(cache.get("stale")).toBeUndefined(); - await new Promise((resolve) => setTimeout(resolve, 60)); - expect(cache.peek("key")).toBeUndefined(); - expect(cache.get("key")).toBeUndefined(); + expect(cache.delete("stale")).toBe(true); + expect(cache.delete("fresh")).toBe(true); + expect(cache.delete("missing")).toBe(false); + expect(cache.peek("stale")).toBeUndefined(); + expect(cache.get("fresh")).toBeUndefined(); }); - test("clear removes all entries and timers", async () => { + test("clears fresh and stale data together", () => { const cache = createExpiringCache(20); cache.setWithTTL("a", "one", 40); - cache.setWithTTL("b", "two", 40); + cache.setWithTTL("b", "two", 10); + now += 10; + expect(cache.get("b")).toBeUndefined(); cache.clear(); - await new Promise((resolve) => setTimeout(resolve, 50)); - expect(cache.peek("a")).toBeUndefined(); expect(cache.peek("b")).toBeUndefined(); }); - test("non-positive ttl arguments fall back to default ttl", async () => { + test.each([0, -1, NaN, Infinity])("uses the default TTL for invalid override %p", (ttl) => { const cache = createExpiringCache(20); - cache.setWithTTL("key", 1, 0); + cache.setWithTTL("key", 1, ttl); - await new Promise((resolve) => setTimeout(resolve, 25)); - - expect(cache.peek("key")).toBe(1); + now += 19; + expect(cache.get("key")).toBe(1); + now += 1; expect(cache.get("key")).toBeUndefined(); + expect(cache.peek("key")).toBe(1); }); }); diff --git a/tests/lightning.usd.test.ts b/tests/lightning.usd.test.ts new file mode 100644 index 00000000..cb0eaca8 --- /dev/null +++ b/tests/lightning.usd.test.ts @@ -0,0 +1,28 @@ +import { expect, test } from "bun:test"; +import { depositUsdLimits, depositUsdPresets, usdToSats } from "../src/services/lightning/usd"; + +test("accepts a copied USD amount at both inclusive Lightning limits", () => { + const market = { btcUsd: 100_000, minSats: 25_000, maxSats: 50_000 }; + expect(usdToSats(" $25.00 ", market)).toBe("25000"); + expect(usdToSats("50.00", market)).toBe("50000"); + expect(() => usdToSats("24.99", market)).toThrow("between $25.00 and $50.00"); + expect(() => usdToSats("50.01", market)).toThrow("between $25.00 and $50.00"); + expect(() => usdToSats("0", market)).toThrow("Enter a positive USD amount"); + expect(() => usdToSats("25$", market)).toThrow("Enter a positive USD amount"); +}); + +test("uses exact input cents before rounding to satoshis at the upper limit", () => { + const market = { btcUsd: 10_220, minSats: 15_000, maxSats: 50_000 }; + expect(depositUsdLimits(market)).toEqual({ min: 1.54, max: 5.11 }); + expect(usdToSats("$5.11", market)).toBe("50000"); +}); + +test.each<[number, number, number[]]>([ + [5_000, 250_000, [10, 25, 50]], + [10_000, 50_000, [10, 25, 50]], + [25_000, 100_000, [25, 50, 100]], + [95_000, 5_000_000, [95, 100, 250]], + [256_000, 300_000, [260]], +])("uses at most three unique, inclusive presets for %i–%i sats", (minSats, maxSats, expected) => { + expect(depositUsdPresets({ btcUsd: 100_000, minSats, maxSats })).toEqual(expected); +}); diff --git a/tests/trade-amount.test.ts b/tests/trade-amount.test.ts index 413a7463..d5381bc8 100644 --- a/tests/trade-amount.test.ts +++ b/tests/trade-amount.test.ts @@ -15,6 +15,25 @@ describe("parseTradeAmountInput", () => { }); }); + test.each(["0%", "Infinity%", "1%2", "2 SOL%", "10%%", "0x10%"])( + "rejects a percentage that does not specify a valid positive share (%s)", + (amount) => { + expect(() => parseTradeAmountInput(amount)).toThrow("Invalid percentage format"); + }, + ); + + test.each<[string, number]>([ + ["100 %", 100], + [".5%", 0.5], + [".05%", 0.05], + ["+3.5%", 3.5], + ["1e1%", 10], + ["15e-1%", 1.5], + ["5e01%", 50], + ])("parses the whole percentage expression %s", (amount, percentage) => { + expect(parseTradeAmountInput(amount)).toEqual({ kind: "percentage", percentage }); + }); + test("parses numeric input", () => { expect(parseTradeAmountInput(" 1.5 ")).toEqual({ kind: "absolute", From 483d0d428644b21914c9b44df7cb4aa3b2440613 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 10:53:39 -0300 Subject: [PATCH 004/410] fix(services): verify Lightning and hold mark boundaries --- src/services/hold-marks.ts | 15 +- src/services/lightning/fixedfloat.ts | 21 +- src/services/lightning/service.ts | 33 ++- src/services/lightning/store.ts | 12 +- src/utils/base-database.ts | 8 +- src/utils/callback-data.ts | 18 +- src/utils/hold-marks-database.ts | 9 +- tests/base-database.internals.test.ts | 24 ++ tests/callback-data.test.ts | 17 ++ tests/hold-marks-database.test.ts | 24 ++ tests/hold-marks.test.ts | 42 +++- tests/lightning-deposits.test.ts | 210 +++++++++++++++++- tests/lightning.fixedfloat.boundaries.test.ts | 184 +++++++++++++++ tests/lightning.usd.test.ts | 15 ++ 14 files changed, 573 insertions(+), 59 deletions(-) create mode 100644 tests/lightning.fixedfloat.boundaries.test.ts diff --git a/src/services/hold-marks.ts b/src/services/hold-marks.ts index 4f448a5c..33eed101 100644 --- a/src/services/hold-marks.ts +++ b/src/services/hold-marks.ts @@ -7,6 +7,9 @@ export type HoldMarkStore = { delete(wallet: string, mint: string): void; }; +const usablePrice = (price: number | undefined): price is number => + Number.isFinite(price) && (price ?? 0) > 0; + export function createMemoryHoldMarkStore(): HoldMarkStore { const rows = new Map(); const keyFor = (wallet: string, mint: string) => `${wallet}\0${mint}`; @@ -16,7 +19,7 @@ export function createMemoryHoldMarkStore(): HoldMarkStore { }, set(wallet, mint, priceUsd) { const key = keyFor(wallet, mint); - if (!rows.has(key)) { + if (usablePrice(priceUsd) && !rows.has(key)) { rows.set(key, priceUsd); } }, @@ -38,7 +41,7 @@ export function createMemoryHoldMarkStore(): HoldMarkStore { export function applyHoldMarks(args: { walletAddress: string; - marks: Array<{ mint: string; priceUsd: number }>; + marks: Array<{ mint?: string; priceUsd: number }>; store: HoldMarkStore; }): Map { const percents = new Map(); @@ -50,12 +53,12 @@ export function applyHoldMarks(args: { for (const mark of args.marks) { const mint = mark.mint?.trim(); const priceUsd = mark.priceUsd; - if (!mint || isQuoteMint(mint) || !(priceUsd > 0) || !Number.isFinite(priceUsd)) { + if (!mint || isQuoteMint(mint) || !usablePrice(priceUsd)) { continue; } const saved = args.store.get(wallet, mint); - if (saved == null || !(saved > 0) || !Number.isFinite(saved)) { + if (!usablePrice(saved)) { args.store.set(wallet, mint, priceUsd); continue; } @@ -85,7 +88,7 @@ function collectMints(mints: Iterable | undefined): Set { return collected; } for (const mint of mints) { - const trimmed = mint?.trim(); + const trimmed = mint.trim(); if (trimmed) { collected.add(trimmed); } @@ -112,7 +115,7 @@ export function pruneHoldMarks( } for (const mint of store.listMints(wallet)) { - const confirmedGone = dropUnseen ? !held.has(mint) : scanned.has(mint) && !held.has(mint); + const confirmedGone = (dropUnseen || scanned.has(mint)) && !held.has(mint); if (confirmedGone) { store.delete(wallet, mint); } diff --git a/src/services/lightning/fixedfloat.ts b/src/services/lightning/fixedfloat.ts index b356ce4d..b71ab05d 100644 --- a/src/services/lightning/fixedfloat.ts +++ b/src/services/lightning/fixedfloat.ts @@ -5,8 +5,10 @@ import { readProtectedSecretFile } from "../../utils/secrets"; export function fixedFloatConfig(env: Readonly> = process.env) { if (env["FIXEDFLOAT_ENABLED"] !== "true") return null; - const secret = (name: string) => - env[`${name}_FILE`] ? readProtectedSecretFile(env[`${name}_FILE`]!, name) : env[name]?.trim(); + const secret = (name: string) => { + const filename = env[`${name}_FILE`]; + return filename ? readProtectedSecretFile(filename, name) : env[name]?.trim(); + }; const key = secret("FIXEDFLOAT_API_KEY"); const apiSecret = secret("FIXEDFLOAT_API_SECRET"); if (!key || !apiSecret) throw new Error("FixedFloat credentials are required when enabled"); @@ -77,7 +79,7 @@ export class FixedFloatError extends Error { } export function satsToBtc(sats: string): string { - if (!/^[1-9]\d{0,14}$/.test(sats) || BigInt(sats) > 2_100_000_000_000_000n) + if (!/^[1-9]\d{0,15}$/.test(sats) || BigInt(sats) > 2_100_000_000_000_000n) throw new DepositInputError("Enter a positive whole number of sats."); return `${BigInt(sats) / 100_000_000n}.${(BigInt(sats) % 100_000_000n).toString().padStart(8, "0")}`; } @@ -86,20 +88,23 @@ export function satsToBtc(sats: string): string { export function invoiceMatchesSats(invoice: string, sats: string): boolean { if (invoice.length > 3000 || !/^[0-9a-z]+$/i.test(invoice)) return false; const match = invoice.toLowerCase().match(/^lnbc([1-9]\d*)([munp]?)1/); - if (!match) return false; - const units = BigInt(match[1]!); + if (!match?.[1]) return false; + const units = BigInt(match[1]); + const unit = match[2] ?? ""; const scale: Record = { "": 100_000_000_000n, m: 100_000_000n, u: 100_000n, n: 100n, }; - const msats = match[2] === "p" ? units / 10n : units * scale[match[2]!]!; - return (match[2] !== "p" || units % 10n === 0n) && msats === BigInt(sats) * 1000n; + const expected = BigInt(sats) * 1000n; + if (unit === "p") return units === expected * 10n; + const multiplier = scale[unit]; + return multiplier !== undefined && units * multiplier === expected; } export class FixedFloatClient { - private requests: { at: number; weight: number }[] = []; + private requests = new Array<{ at: number; weight: number }>(); constructor( private readonly config: { key: string; secret: string; refcode: string }, private readonly fetcher: typeof fetch = fetch, diff --git a/src/services/lightning/service.ts b/src/services/lightning/service.ts index 6d16ec8c..b7df024b 100644 --- a/src/services/lightning/service.ts +++ b/src/services/lightning/service.ts @@ -6,7 +6,12 @@ import { invoiceMatchesSats, type FixedFloatOrder, } from "./fixedfloat"; -import { DepositStore, type Deposit } from "./store"; +import { + DEPOSIT_POLL_INTERVAL_MS, + DEPOSIT_QUOTE_TTL_MS, + DepositStore, + type Deposit, +} from "./store"; export class LightningDeposits { private polling = false; @@ -47,7 +52,7 @@ export class LightningDeposits { const deposit = this.store.get(id); if (!deposit || deposit.owner !== owner) throw new Error("Deposit not found."); if (!this.store.admit(id, owner)) { - if (deposit.state === "quoted" && deposit.created < Date.now() - 60_000) + if (deposit.state === "quoted" && deposit.created < Date.now() - DEPOSIT_QUOTE_TTL_MS) this.store.cancelQuote(id, owner); return this.store.get(id)!; } @@ -103,14 +108,16 @@ export class LightningDeposits { deposit.id, state, order, - Date.now() + (["emergency", "expired"].includes(state) ? 300_000 : 30_000), + Date.now() + + (["emergency", "expired"].includes(state) ? 300_000 : DEPOSIT_POLL_INTERVAL_MS), ); } catch { this.store.update( deposit.id, deposit.state, undefined, - Date.now() + Math.min(300_000, 30_000 * 2 ** Math.min(deposit.attempts, 4)), + Date.now() + + Math.min(300_000, DEPOSIT_POLL_INTERVAL_MS * 2 ** Math.min(deposit.attempts, 4)), deposit.attempts + 1, ); } @@ -135,22 +142,28 @@ export function hasSettlementTransfer(tx: unknown, destination: string, expected ]; let received = 0n; for (const raw of instructions) { + if (typeof raw !== "object" || raw === null) continue; const ix = raw as { program?: string; programId?: { toString(): string }; parsed?: { type?: string; info?: { destination?: string; lamports?: number | string } }; }; + const parsed = ix.parsed; + const info = parsed?.info; if ( ix.program !== "system" || ix.programId?.toString() !== "11111111111111111111111111111111" || - !["transfer", "transferWithSeed"].includes(ix.parsed?.type ?? "") || - ix.parsed?.info?.destination !== destination + (parsed?.type !== "transfer" && parsed?.type !== "transferWithSeed") || + info?.destination !== destination ) continue; - const lamports = ix.parsed.info.lamports; - if (typeof lamports === "number" && Number.isSafeInteger(lamports) && lamports > 0) - received += BigInt(lamports); - else if (typeof lamports === "string" && /^\d+$/.test(lamports)) received += BigInt(lamports); + const lamports = info.lamports; + if (typeof lamports === "string") { + if (/^\d+$/.test(lamports)) received += BigInt(lamports); + } else { + const numeric = lamports ?? NaN; + if (Number.isSafeInteger(numeric)) received += BigInt(Math.max(0, numeric)); + } } return received >= expected; } diff --git a/src/services/lightning/store.ts b/src/services/lightning/store.ts index 3d6108ac..95e810e4 100644 --- a/src/services/lightning/store.ts +++ b/src/services/lightning/store.ts @@ -4,6 +4,9 @@ import { chmodSync } from "node:fs"; import { resolveDatabaseFilename } from "../../utils/base-database"; import type { FixedFloatOrder } from "./fixedfloat"; +export const DEPOSIT_QUOTE_TTL_MS = 60_000; +export const DEPOSIT_POLL_INTERVAL_MS = 30_000; + export type Deposit = { id: string; owner: string; @@ -25,7 +28,8 @@ export class DepositStore { private readonly key: Buffer; constructor(secret: string, filename = "lightning.sqlite", recoverCreating = false) { const path = resolveDatabaseFilename(filename); - this.db = new Database(path, { create: true, strict: true }); + // Stryker disable next-line ObjectLiteral,BooleanLiteral: All normal queries supply every positional binding; keep strict mode to catch future missing bindings. + this.db = new Database(path, { strict: true }); if (path !== ":memory:") chmodSync(path, 0o600); this.key = createHash("sha256").update(`timba-fixedfloat-v1:${secret}`).digest(); this.db @@ -92,7 +96,7 @@ export class DepositStore { active(owner: string) { this.db.run( "UPDATE lightning_deposits SET state='expired' WHERE owner=? AND state='quoted' AND created < ?", - [owner, Date.now() - 60_000], + [owner, Date.now() - DEPOSIT_QUOTE_TTL_MS], ); return this.decode( this.db @@ -121,7 +125,7 @@ export class DepositStore { return ( this.db.run( "UPDATE lightning_deposits SET state='creating' WHERE id=? AND owner=? AND state='quoted' AND created>=?", - [id, owner, Date.now() - 60_000], + [id, owner, Date.now() - DEPOSIT_QUOTE_TTL_MS], ).changes === 1 ); } @@ -135,7 +139,7 @@ export class DepositStore { id: string, state: string, order?: FixedFloatOrder, - nextPoll = Date.now() + 30_000, + nextPoll = Date.now() + DEPOSIT_POLL_INTERVAL_MS, attempts = 0, ) { const changedStatus = order && this.get(id)?.order?.status !== order.status; diff --git a/src/utils/base-database.ts b/src/utils/base-database.ts index d6bbce5c..a7a0726f 100644 --- a/src/utils/base-database.ts +++ b/src/utils/base-database.ts @@ -137,13 +137,7 @@ export abstract class BaseDatabase { return result?.count ?? 0; } - private normalizeParams( - params: SQLQueryBindings | SQLQueryBindings[] | undefined, - ): SQLQueryBindings[] { - if (params === undefined) { - return []; - } - + private normalizeParams(params: SQLQueryBindings | SQLQueryBindings[] = []): SQLQueryBindings[] { return Array.isArray(params) ? params : [params]; } diff --git a/src/utils/callback-data.ts b/src/utils/callback-data.ts index e458cc37..eb634029 100644 --- a/src/utils/callback-data.ts +++ b/src/utils/callback-data.ts @@ -65,7 +65,6 @@ const decodeSigned = (value: string | undefined): number | null => { }; const normalizeAmount = (amount: string): { digits: bigint; scale: number } | null => { - if (typeof amount !== "string") return null; const trimmed = amount.trim(); if (!/^\d+(?:\.\d+)?$/.test(trimmed)) return null; const decimalPoint = trimmed.indexOf("."); @@ -84,12 +83,12 @@ const encodeAmount = (amount: string): string | null => { }; const decodeAmount = (encoded: string | undefined): string | null => { - if (!encoded) return null; - const separator = encoded.indexOf(AMOUNT_SEPARATOR); + const raw = encoded ?? ""; + const separator = raw.indexOf(AMOUNT_SEPARATOR); if (separator < 1) return null; - const scale = decodeUnsigned(encoded.slice(0, separator)); + const scale = decodeUnsigned(raw.slice(0, separator)); if (scale === null || scale > MAX_AMOUNT_SCALE) return null; - const digits = decodeBase36ToBigInt(encoded.slice(separator + 1)); + const digits = decodeBase36ToBigInt(raw.slice(separator + 1)); if (digits === null) return null; return formatAmount(digits, scale); @@ -106,18 +105,17 @@ const encodeCreatorId = (creatorId?: string): string | null => { }; const decodeCreatorId = (encoded: string | undefined): string | null => { - if (!encoded || encoded.length < 2) return null; - const mode = encoded.charAt(0); - const value = encoded.slice(1); + const mode = encoded?.charAt(0); + const value = encoded?.slice(1) ?? ""; if (mode === "n") { const decoded = decodeBase36ToBigInt(value); - return decoded !== null ? decoded.toString(10) : null; + return decoded?.toString(10) ?? null; } if (mode === "s") { // base64url decoding never throws; invalid characters are skipped. - return Buffer.from(value, "base64url").toString("utf8"); + return Buffer.from(value, "base64url").toString("utf8") || null; } return null; diff --git a/src/utils/hold-marks-database.ts b/src/utils/hold-marks-database.ts index 007152f1..08f981e4 100644 --- a/src/utils/hold-marks-database.ts +++ b/src/utils/hold-marks-database.ts @@ -38,7 +38,7 @@ export class HoldMarksDatabase extends BaseDatabase { [wallet, mint], "get hold mark", ); - if (!row || !(row.price_usd > 0)) { + if (!row || !(row.price_usd > 0) || !Number.isFinite(row.price_usd)) { return undefined; } return row.price_usd; @@ -49,9 +49,10 @@ export class HoldMarksDatabase extends BaseDatabase { return; } this.run( - `INSERT OR IGNORE INTO hold_marks (wallet, mint, price_usd, seen_at) - VALUES (?, ?, ?, ?)`, - [wallet, mint, priceUsd, Date.now()], + `INSERT INTO hold_marks (wallet, mint, price_usd, seen_at) VALUES (?, ?, ?, ?) + ON CONFLICT(wallet, mint) DO UPDATE SET price_usd = excluded.price_usd, seen_at = excluded.seen_at + WHERE hold_marks.price_usd <= 0 OR hold_marks.price_usd > ?`, + [wallet, mint, priceUsd, Date.now(), Number.MAX_VALUE], "set hold mark", ); } diff --git a/tests/base-database.internals.test.ts b/tests/base-database.internals.test.ts index f6f96720..9b388932 100644 --- a/tests/base-database.internals.test.ts +++ b/tests/base-database.internals.test.ts @@ -40,6 +40,20 @@ class ProbeDatabase extends BaseDatabase { }; } + failWithDefaultLabel(method: "run" | "get" | "all" | "count") { + const sql = "SELECT * FROM missing"; + switch (method) { + case "run": + return this.run(sql); + case "get": + return this.get(sql); + case "all": + return this.all(sql); + case "count": + return this.getCount(sql); + } + } + close() { this.db.close(); } @@ -91,6 +105,16 @@ describe("BaseDatabase statement cache", () => { }); describe("BaseDatabase.getCount", () => { + test.each<["run" | "get" | "all" | "count", string]>([ + ["run", "running statement"], + ["get", "executing query"], + ["all", "executing query"], + ["count", "executing count query"], + ])("includes default operation context for a failed %s", (method, action) => { + expect(() => db.failWithDefaultLabel(method)).toThrow("missing"); + expect(errorSpy).toHaveBeenCalledTimes(1); + expect(errorSpy.mock.calls[0]?.[0]).toBe(`[Probe DB] Error during ${action}:`); + }); test("runs queries with no bindings or operation label", () => { const result = db.unbound(); expect(result.insert.changes).toBe(1); diff --git a/tests/callback-data.test.ts b/tests/callback-data.test.ts index 824f153c..0726c440 100644 --- a/tests/callback-data.test.ts +++ b/tests/callback-data.test.ts @@ -102,6 +102,23 @@ test("round-trips Unicode creator IDs as text", () => { ).toEqual(payload); }); +test("matches creator IDs by their whole value and refuses empty encoded amounts", () => { + const payload = { ...base, amount: "1", creatorId: "42players" }; + expect( + callback.decodeAmountSelectionPayload( + callback.encodeAmountSelectionPayload(payload) ?? undefined, + ), + ).toEqual(payload); + for (const parts of [ + ["ga", "c", "0:", "n1"], + ["ga", "c", "0:1", "n!"], + ["ga", "c", "0:1", "n"], + ["ga", "c", "", "n1"], + ]) { + expect(callback.decodeAmountSelectionPayload(parts.join("|"))).toBeNull(); + } +}); + test("preserves token precision through the highest decimal count", () => { const valid = { ...base, amount: "0." + "0".repeat(254) + "1" }; expect( diff --git a/tests/hold-marks-database.test.ts b/tests/hold-marks-database.test.ts index 71d0f80c..5c0db4d8 100644 --- a/tests/hold-marks-database.test.ts +++ b/tests/hold-marks-database.test.ts @@ -1,7 +1,9 @@ import { afterEach, beforeEach, expect, test } from "bun:test"; +import { Database } from "bun:sqlite"; import { createHoldMarksDatabaseStore, HoldMarksDatabase } from "../src/utils/hold-marks-database"; import { applyHoldMarks } from "../src/services/hold-marks"; import { resetTestDatabase } from "./helpers/database"; +import { resolveDatabaseFilename } from "../src/utils/base-database"; const TIMBA = "F3A1baCgv4TF79TSjdMTvpMDtNv8DJvHZwNc9DG8pump"; const WALLET = "wallet-db-1"; @@ -66,6 +68,28 @@ test("hold marks ignore non-positive and non-finite prices", () => { expect(db.listMints(WALLET)).toEqual([]); }); +test("a valid quote replaces invalid legacy marks in SQLite", () => { + const db = HoldMarksDatabase.getInstance(); + const seed = new Database(resolveDatabaseFilename("hold-marks.sqlite")); + try { + const insert = seed.query( + "INSERT INTO hold_marks (wallet,mint,price_usd,seen_at) VALUES (?,?,?,0)", + ); + insert.run(WALLET, TIMBA, 0); + insert.run("another-wallet", TIMBA, Infinity); + } finally { + seed.close(); + } + for (const walletAddress of [WALLET, "another-wallet"]) { + const store = createHoldMarksDatabaseStore(); + expect(store.get(walletAddress, TIMBA)).toBeUndefined(); + expect( + applyHoldMarks({ walletAddress, marks: [{ mint: TIMBA, priceUsd: 2 }], store }).size, + ).toBe(0); + expect(db.getPrice(walletAddress, TIMBA)).toBe(2); + } +}); + test("deleting a missing hold mark is a no-op", () => { const db = HoldMarksDatabase.getInstance(); diff --git a/tests/hold-marks.test.ts b/tests/hold-marks.test.ts index 2f6b511e..12af8ffb 100644 --- a/tests/hold-marks.test.ts +++ b/tests/hold-marks.test.ts @@ -1,4 +1,4 @@ -import { expect, test } from "bun:test"; +import { expect, mock, test } from "bun:test"; import { WSOL_MINT } from "../src/utils/constants"; import { USDC_MINT } from "../src/services/positions"; import { @@ -22,6 +22,26 @@ test("applyHoldMarks stores the first mark and does not invent a percent", () => expect(store.get(WALLET, TIMBA)).toBeCloseTo(0.00000551, 12); }); +test("normalizes a copied wallet and mint and ignores invalid stored prices", () => { + const store = createMemoryHoldMarkStore(); + for (const invalid of [0, -1, NaN, Infinity]) store.set(WALLET, TIMBA, invalid); + expect(store.get(WALLET, TIMBA)).toBeUndefined(); + expect( + applyHoldMarks({ + walletAddress: ` ${WALLET} `, + marks: [{ mint: ` ${TIMBA} `, priceUsd: 2 }], + store, + }), + ).toEqual(new Map()); + store.set(WALLET, TIMBA, 9); + expect(store.get(WALLET, TIMBA)).toBe(2); + expect( + applyHoldMarks({ walletAddress: WALLET, marks: [{ mint: TIMBA, priceUsd: 3 }], store }).get( + TIMBA, + ), + ).toBe(0.5); +}); + test("applyHoldMarks reports price change since the first hold mark", () => { const store = createMemoryHoldMarkStore(); applyHoldMarks({ @@ -45,10 +65,7 @@ test("applyHoldMarks does not prime a mark on a failed or zero price", () => { expect( applyHoldMarks({ walletAddress: WALLET, - marks: [ - { mint: TIMBA, priceUsd: 0 }, - { mint: TIMBA, priceUsd: Number.NaN }, - ], + marks: [{ priceUsd: 2 }, { mint: TIMBA, priceUsd: 0 }, { mint: TIMBA, priceUsd: Number.NaN }], store, }).size, ).toBe(0); @@ -105,15 +122,17 @@ test("pruneHoldMarks drops marks for tokens that left the wallet", () => { test("pruneHoldMarks does not treat an empty list as a full exit", () => { const store = createMemoryHoldMarkStore(); + const listMints = mock(store.listMints); applyHoldMarks({ walletAddress: WALLET, marks: [{ mint: TIMBA, priceUsd: 0.00000551069 }], store, }); - pruneHoldMarks(WALLET, [], store); + pruneHoldMarks(WALLET, [], { ...store, listMints }, { scannedMints: [" "] }); expect(store.get(WALLET, TIMBA)).toBeCloseTo(0.00000551069, 12); + expect(listMints).not.toHaveBeenCalled(); }); test("a successful empty or partial holdings list does not re-anchor a hold mark", () => { @@ -154,6 +173,17 @@ test("pruneHoldMarks only drops marks for mints this fetch scanned", () => { expect(store.get(WALLET, USDC_MINT)).toBeUndefined(); }); +test("a partial scan with padded mints keeps held marks and drops a confirmed exit", () => { + const store = createMemoryHoldMarkStore(); + store.set(WALLET, TIMBA, 2); + store.set(WALLET, "confirmed-sold", 4); + store.set(WALLET, "unscanned", 6); + pruneHoldMarks(` ${WALLET} `, [` ${TIMBA} `], store, { + scannedMints: [` ${TIMBA} `, " confirmed-sold ", " "], + }); + expect(store.listMints(WALLET).sort()).toEqual([TIMBA, "unscanned"].sort()); +}); + test("a complete empty census drops the mark so the next hold starts fresh", () => { const store = createMemoryHoldMarkStore(); applyHoldMarks({ diff --git a/tests/lightning-deposits.test.ts b/tests/lightning-deposits.test.ts index 8d1ec13d..68c3ffd8 100644 --- a/tests/lightning-deposits.test.ts +++ b/tests/lightning-deposits.test.ts @@ -1,4 +1,4 @@ -import { describe, test, expect } from "bun:test"; +import { describe, mock, spyOn, test, expect } from "bun:test"; import { createHmac } from "node:crypto"; import { FixedFloatClient, @@ -33,9 +33,114 @@ describe("Lightning deposits", () => { test("formats sats without floating point rounding", () => { expect(satsToBtc("1")).toBe("0.00000001"); expect(satsToBtc("10000")).toBe("0.00010000"); - for (const invalid of ["0", "-1", "1.2", "1e8", " 1"]) + expect(satsToBtc("2100000000000000")).toBe("21000000.00000000"); + for (const invalid of ["0", "-1", "1.2", "1e8", " 1", "2100000000000001"]) expect(() => satsToBtc(invalid)).toThrow(); }); + + test("an existing quote avoids repeat provider calls and invalid sats never reach the provider", async () => { + const db = store(); + const getQuote = mock(async () => quote); + const deposits = new LightningDeposits( + db, + { getQuote, create: async () => order(), order: async () => order() }, + async () => false, + ); + try { + const first = await deposits.quote("1", destination, "10000"); + expect(await deposits.quote("1", destination, "10000")).toEqual(first); + await expect(deposits.quote("2", destination, "0")).rejects.toThrow( + "positive whole number of sats", + ); + expect(getQuote).toHaveBeenCalledTimes(1); + } finally { + db.close(); + } + }); + + test.each<[string, (fixture: FixedFloatOrder) => FixedFloatOrder]>([ + [ + "wrong payment network", + (fixture) => ({ ...fixture, from: { ...fixture.from, code: "BTC" } }), + ], + ["wrong settlement asset", (fixture) => ({ ...fixture, to: { ...fixture.to, code: "ETH" } })], + [ + "wrong quoted amount", + (fixture) => ({ ...fixture, from: { ...fixture.from, amount: "0.00015000" } }), + ], + [ + "expired at the current second", + (fixture) => ({ ...fixture, time: { expiration: 1720000000 } }), + ], + ])("keeps the recovery order but hides the invoice for %s", async (_label, change) => { + const db = store(); + const clock = spyOn(Date, "now").mockReturnValue(1_720_000_000_000); + const fixture = change(order()); + const deposits = new LightningDeposits( + db, + { getQuote: async () => quote, create: async () => fixture, order: async () => fixture }, + async () => false, + ); + try { + const pending = await deposits.quote("1", destination, "10000"); + const created = await deposits.create(pending.id, "1"); + expect(created.state).toBe("unknown"); + expect(created.order).toEqual(fixture); + expect(depositMessage(created).text).not.toContain(fixture.from.address); + } finally { + clock.mockRestore(); + db.close(); + } + }); + + test("a provider rejection is recorded as a retry-safe failure, not an ambiguous invoice", async () => { + const db = store(); + const deposits = new LightningDeposits( + db, + { + getQuote: async () => quote, + create: async () => { + throw new FixedFloatError(true); + }, + order: async () => order(), + }, + async () => false, + ); + try { + const quoted = await deposits.quote("1", destination, "10000"); + expect(await deposits.create(quoted.id, "1")).toMatchObject({ state: "failed", order: null }); + } finally { + db.close(); + } + }); + + test("does not overlap pollers and waits for a confirmed transfer when an order has no payout transaction", async () => { + const db = store(); + const response = Promise.withResolvers(); + const getOrder = mock(() => response.promise); + const confirm = mock(async () => true); + const deposits = new LightningDeposits( + db, + { getQuote: async () => quote, create: async () => order(), order: getOrder }, + confirm, + ); + try { + const missingOrder = db.quote("missing", destination, "10000", "0.02"); + db.update(missingOrder.id, "active", undefined, 0); + const valid = db.quote("valid", destination, "10000", "0.02"); + db.update(valid.id, "active", order(), 0); + const first = deposits.poll(); + const second = deposits.poll(); + response.resolve({ ...order(), status: "DONE" }); + await Promise.all([first, second]); + expect(getOrder).toHaveBeenCalledTimes(1); + expect(confirm).not.toHaveBeenCalled(); + expect(db.get(valid.id)).toMatchObject({ state: "settling", attempts: 0 }); + expect(db.get(missingOrder.id)).toMatchObject({ state: "active", attempts: 0 }); + } finally { + db.close(); + } + }); test("signs exactly the JSON bytes sent and does not retry an ambiguous create", async () => { let calls = 0; const fetcher = (async (_url: unknown, init: RequestInit) => { @@ -184,7 +289,7 @@ describe("Lightning deposits", () => { }); }); -import { mkdtempSync, readFileSync, rmSync } from "node:fs"; +import { mkdtempSync, readFileSync, rmSync, statSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; @@ -205,15 +310,112 @@ test("restart restores orders, hides plaintext tokens, and preserves ambiguous r expect(db.get(creating.id)?.state).toBe("unknown"); expect(db.get(oldQuote.id)?.state).toBe("expired"); expect(db.admit(oldQuote.id, "3")).toBe(false); - expect(() => db.abandonUnknown(pending.id, "test evidence")).toThrow(); + expect(() => db.abandonUnknown(pending.id, "test evidence")).toThrow("Only unknown requests"); + expect(() => db.abandonUnknown(creating.id, " ")).toThrow("Recovery reason is required"); + expect(db.get(creating.id)?.state).toBe("unknown"); db.abandonUnknown(creating.id, "synthetic provider evidence: no payable order"); expect(db.get(creating.id)?.state).toBe("failed"); db.close(); + const wrongKey = new DepositStore("different-synthetic-key", path); + try { + expect(() => wrongKey.get(pending.id)).toThrow(); + } finally { + wrongKey.close(); + } } finally { rmSync(directory, { recursive: true, force: true }); } }); +test("an ordinary close and reopen preserves a quote and uses a private journal", () => { + const directory = mkdtempSync(join(tmpdir(), "timba-lightning-default-")); + const previous = process.env["BOT_DB_DIR"]; + process.env["BOT_DB_DIR"] = directory; + try { + const db = new DepositStore("synthetic-key"); + const pending = db.quote("1", destination, "10000", "0.02"); + db.close(); + expect(() => db.get(pending.id)).toThrow(); + expect(statSync(join(directory, "lightning.sqlite")).mode & 0o777).toBe(0o600); + const reopened = new DepositStore("synthetic-key"); + try { + expect(reopened.get(pending.id)?.state).toBe("quoted"); + reopened.update("absent", "active", order()); + expect(reopened.get("absent")).toBeNull(); + } finally { + reopened.close(); + } + } finally { + if (previous === undefined) delete process.env["BOT_DB_DIR"]; + else process.env["BOT_DB_DIR"] = previous; + rmSync(directory, { recursive: true, force: true }); + } +}); + +test("expires old quotes and schedules a fresh poll after 30 seconds", () => { + let now = 1_720_000_000_000; + const clock = spyOn(Date, "now").mockImplementation(() => now); + const db = store(); + try { + const pending = db.quote("1", destination, "10000", "0.02"); + now += 60_000; + expect(db.active("1")?.id).toBe(pending.id); + now += 1; + expect(db.active("1")).toBeNull(); + expect(db.get(pending.id)?.state).toBe("expired"); + const active = db.quote("1", destination, "10000", "0.02"); + db.update(active.id, "active", order()); + expect(db.due(now + 29_999)).toEqual([]); + expect(db.due(now + 30_000).map(({ id }) => id)).toEqual([active.id]); + } finally { + db.close(); + clock.mockRestore(); + } +}); + +test("only counts parsed native transfers with positive whole lamports", () => { + const valid = { + program: "system", + programId: "11111111111111111111111111111111", + parsed: { type: "transferWithSeed", info: { destination, lamports: "7" } }, + }; + const inner = (instructions: unknown[]) => ({ + transaction: {}, + meta: { err: null, innerInstructions: [{ instructions }] }, + }); + expect(hasSettlementTransfer(null, destination, 7n)).toBe(false); + expect(hasSettlementTransfer(inner([valid]), destination, 0n)).toBe(false); + expect(hasSettlementTransfer(inner([valid]), destination, 7n)).toBe(true); + expect(hasSettlementTransfer(inner([null, {}, valid]), destination, 7n)).toBe(true); + expect( + hasSettlementTransfer( + inner([ + { ...valid, program: "spl-token" }, + { ...valid, programId: "fake-other-program" }, + { ...valid, programId: undefined }, + { ...valid, parsed: undefined }, + { ...valid, parsed: { type: "transfer" } }, + { ...valid, parsed: { type: "not-transfer", info: { destination, lamports: 7 } } }, + ]), + destination, + 1n, + ), + ).toBe(false); + expect( + hasSettlementTransfer( + inner([ + ...["-1", "1.5", 0, -1, 0.5, Infinity, undefined].map((lamports) => ({ + ...valid, + parsed: { type: "transfer", info: { destination, lamports } }, + })), + valid, + ]), + destination, + 7n, + ), + ).toBe(true); +}); + test("unresolved lists only ambiguous deposits for operator review", () => { const db = store(); const active = db.quote("1", destination, "10000", "0.02"); diff --git a/tests/lightning.fixedfloat.boundaries.test.ts b/tests/lightning.fixedfloat.boundaries.test.ts new file mode 100644 index 00000000..0125e6db --- /dev/null +++ b/tests/lightning.fixedfloat.boundaries.test.ts @@ -0,0 +1,184 @@ +import { expect, test } from "bun:test"; +import { mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { + fixedFloatConfig, + FixedFloatClient, + invoiceMatchesSats, + OrderSchema, +} from "../src/services/lightning/fixedfloat"; + +const config = { key: "fake-key", secret: "fake-secret", refcode: "fake-ref" }; +const env = { + FIXEDFLOAT_ENABLED: "true", + FIXEDFLOAT_API_KEY: " fake-key ", + FIXEDFLOAT_API_SECRET: " fake-secret ", + FIXEDFLOAT_REFCODE: " fake-ref ", +}; +const currencies = [ + { code: "BTCLN", coin: "BTC", network: "LN", recv: 1, send: 1 }, + { code: "SOL", coin: "SOL", network: "SOL", recv: 1, send: 1 }, +]; +const price = { + from: { code: "BTCLN", amount: "0.001", min: "0.0001", max: "0.002", usd: "100" }, + to: { code: "SOL", amount: "0.02", usd: "100" }, + errors: [] as string[], +}; +const order = { + id: "TEST01", + token: "test-token", + type: "float", + status: "NEW", + time: { expiration: 1 }, + from: { code: "BTCLN", amount: "0.0001", address: "synthetic-invoice" }, + to: { code: "SOL", amount: "0.02", address: "synthetic-destination" }, +}; + +function useFetch(fn: (url: string, init?: RequestInit) => Response): typeof fetch { + return Object.assign( + async (url: Parameters[0], init?: RequestInit) => fn(String(url), init), + { + preconnect: () => {}, + }, + ); +} + +function marketClient(available: typeof currencies = currencies, quote = price) { + return new FixedFloatClient( + config, + useFetch((url) => + Response.json({ + code: 0, + data: url.endsWith("/ccies") ? available : quote, + }), + ), + ); +} + +test("reads protected fixture credentials first, and trims environment values", () => { + expect(fixedFloatConfig(env)).toEqual(config); + expect(() => fixedFloatConfig({ ...env, FIXEDFLOAT_API_KEY: undefined })).toThrow( + "credentials are required", + ); + expect(() => fixedFloatConfig({ ...env, FIXEDFLOAT_API_SECRET: undefined })).toThrow( + "credentials are required", + ); + for (const FIXEDFLOAT_REFCODE of [undefined, "!ref", "ref!", "r".repeat(65)]) { + expect(() => fixedFloatConfig({ ...env, FIXEDFLOAT_REFCODE })).toThrow( + "FIXEDFLOAT_REFCODE is required", + ); + } + + const folder = mkdtempSync(join(tmpdir(), "synthetic-ff-credentials-")); + try { + const file = join(folder, "key.txt"); + writeFileSync(file, " fake-file-key\n", { mode: 0o600 }); + expect(fixedFloatConfig({ ...env, FIXEDFLOAT_API_KEY_FILE: file })).toEqual({ + ...config, + key: "fake-file-key", + }); + const empty = join(folder, "empty.txt"); + writeFileSync(empty, "", { mode: 0o600 }); + expect(() => fixedFloatConfig({ ...env, FIXEDFLOAT_API_SECRET_FILE: empty })).toThrow( + "FIXEDFLOAT_API_SECRET", + ); + } finally { + rmSync(folder, { recursive: true, force: true }); + } +}); + +test("validates the entire order ID, decimal text, rate type, and provider status", () => { + for (const id of ["!TEST01", "TEST01!", "TEST010"]) { + expect(OrderSchema.safeParse({ ...order, id }).success).toBe(false); + } + for (const amount of ["junk0.02", "0.02 coins"]) { + expect(OrderSchema.safeParse({ ...order, to: { ...order.to, amount } }).success).toBe(false); + } + expect(OrderSchema.parse({ ...order, type: "fixed", status: "WITHDRAW" })).toMatchObject({ + type: "fixed", + status: "WITHDRAW", + }); + expect(OrderSchema.parse({ ...order, status: "PENDING" }).status).toBe("PENDING"); + expect(OrderSchema.parse({ ...order, status: "EXCHANGE" }).status).toBe("EXCHANGE"); +}); + +test("accepts exact whole sats in long invoices but refuses invalid boundaries and partial sats", () => { + const prefix = "lnbc1u1"; + const max = prefix + "x".repeat(3000 - prefix.length); + expect(invoiceMatchesSats(max, "100")).toBe(true); + expect(invoiceMatchesSats(max + "x", "100")).toBe(false); + expect(invoiceMatchesSats("!" + max.slice(0, 2999), "100")).toBe(false); + expect(invoiceMatchesSats(prefix + "x!", "100")).toBe(false); + expect(invoiceMatchesSats("x" + prefix + "x", "100")).toBe(false); + expect(invoiceMatchesSats("lnbc11synthetic", "100000000")).toBe(true); + expect(invoiceMatchesSats("lnbc10000p1synthetic", "1")).toBe(true); + expect(invoiceMatchesSats("lnbc10001p1synthetic", "1")).toBe(false); +}); + +test("requires the advertised route and checks response asset codes", async () => { + const [btc, sol] = currencies; + if (!btc || !sol) throw new Error("Expected currencies"); + for (const rows of [ + [{ ...btc, code: "BTC" }, sol], + [{ ...btc, coin: "ETH" }, sol], + [btc, { ...sol, code: "XSOL" }], + [btc, { ...sol, coin: "ETH" }], + [btc, { ...sol, send: 0 }], + ]) + await expect(marketClient(rows).getMarket()).rejects.toThrow( + "deposits are temporarily unavailable", + ); + + for (const invalid of [ + { ...price, from: { ...price.from, code: "BTC" } }, + { ...price, to: { ...price.to, code: "ETH" } }, + ]) + await expect(marketClient(currencies, invalid).getMarket()).rejects.toMatchObject({ + retrySafe: true, + }); +}); + +test("accepts both limit notices for market discovery and includes exact quote boundaries", async () => { + const market = marketClient(currencies, { ...price, errors: ["LIMIT_MIN", "LIMIT_MAX"] }); + await expect(market.getMarket()).resolves.toEqual({ + btcUsd: 100_000, + minSats: 10_000, + maxSats: 200_000, + }); + await expect(market.getQuote("10000")).rejects.toMatchObject({ retrySafe: true }); + for (const sats of ["10000", "200000"]) + await expect(marketClient().getQuote(sats)).resolves.toEqual(price); + + const fixedLimit = { ...price, from: { ...price.from, max: price.from.min } }; + await expect(marketClient(currencies, fixedLimit).getMarket()).resolves.toEqual({ + btcUsd: 100_000, + minSats: 10_000, + maxSats: 10_000, + }); + for (const fields of [{ usd: "0" }, { min: "0" }, { min: "0.003" }]) { + const invalid = { ...price, from: { ...price.from, ...fields } }; + await expect(marketClient(currencies, invalid).getMarket()).rejects.toMatchObject({ + retrySafe: true, + }); + } +}); + +test("sends signed JSON without redirects and resets the budget at the exact minute boundary", async () => { + let now = 1_000; + const fetcher = useFetch((url, init) => { + expect(url).toBe("https://ff.io/api/v2/order"); + expect(init?.method).toBe("POST"); + expect(init?.redirect).toBe("error"); + expect(new Headers(init?.headers).get("Content-Type")).toBe("application/json; charset=UTF-8"); + expect(new Headers(init?.headers).get("X-API-KEY")).toBe("fake-key"); + return Response.json({ code: 0, data: order }); + }); + const client = new FixedFloatClient(config, fetcher, () => now); + await Promise.all(Array.from({ length: 200 }, () => client.order("TEST01", "test-token"))); + await expect(client.order("TEST01", "test-token")).rejects.toThrow( + "FixedFloat is temporarily unavailable", + ); + now += 60_000; + await expect(client.order("TEST01", "test-token")).resolves.toMatchObject({ id: "TEST01" }); +}); diff --git a/tests/lightning.usd.test.ts b/tests/lightning.usd.test.ts index cb0eaca8..8742432c 100644 --- a/tests/lightning.usd.test.ts +++ b/tests/lightning.usd.test.ts @@ -17,6 +17,21 @@ test("uses exact input cents before rounding to satoshis at the upper limit", () expect(usdToSats("$5.11", market)).toBe("50000"); }); +test("rejects rounded USD bounds when very large quotes no longer map to a permitted sat amount", () => { + const lower = { + btcUsd: 99_562.88686022162, + minSats: 8_833_522_863_177_727, + maxSats: 9_000_000_000_000_000, + }; + const upper = { btcUsd: 144_230.54629005492, minSats: 1, maxSats: 1_096_694_547_892_548 }; + expect(() => usdToSats(depositUsdLimits(lower).min.toFixed(2), lower)).toThrow( + "The deposit limits have changed", + ); + expect(() => usdToSats(depositUsdLimits(upper).max.toFixed(2), upper)).toThrow( + "The deposit limits have changed", + ); +}); + test.each<[number, number, number[]]>([ [5_000, 250_000, [10, 25, 50]], [10_000, 50_000, [10, 25, 50]], From 751843e32aa242a273907cfea644e7ce6e0219d4 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 11:11:03 -0300 Subject: [PATCH 005/410] fix(alerts): cover buy alerts and preserve formatter compatibility --- src/services/buy-alerts/dexscreener.ts | 98 ++++-------- src/services/buy-alerts/formatter.ts | 69 ++++---- src/services/buy-alerts/pool-trades.ts | 49 +++--- src/services/buy-alerts/publisher.ts | 41 +++-- src/utils/arg-parsing.ts | 2 +- src/utils/callback-data.ts | 1 + src/utils/concurrency.ts | 2 +- src/utils/expiring-cache.ts | 27 +++- src/utils/format-amount.ts | 26 ++-- tests/buy-alerts.dexscreener.test.ts | 105 ++++++++++++- tests/buy-alerts.formatter.test.ts | 85 +++++++++- .../buy-alerts.pool-trades-edge-cases.test.ts | 57 +++++++ tests/buy-alerts.pool-trades.test.ts | 11 +- tests/buy-alerts.publisher.test.ts | 147 ++++++++++++++++-- tests/expiring-cache.test.ts | 61 +++++++- tests/format-amount.test.ts | 17 ++ 16 files changed, 603 insertions(+), 195 deletions(-) diff --git a/src/services/buy-alerts/dexscreener.ts b/src/services/buy-alerts/dexscreener.ts index 8bbe42fb..ec094507 100644 --- a/src/services/buy-alerts/dexscreener.ts +++ b/src/services/buy-alerts/dexscreener.ts @@ -7,6 +7,14 @@ const DEXSCREENER_TOKEN_URL = "https://api.dexscreener.com/latest/dex/tokens"; const PAIR_CACHE_TTL_MS = 30_000; const PAIR_FETCH_TIMEOUT_MS = 5_000; +const tokenSchema = z + .object({ + address: z.string().optional(), + name: z.string().optional(), + symbol: z.string().optional(), + }) + .passthrough(); + const pairSchema = z .object({ chainId: z.string().optional(), @@ -28,22 +36,8 @@ const pairSchema = z .passthrough() .optional(), pairAddress: z.string().optional(), - quoteToken: z - .object({ - address: z.string().optional(), - name: z.string().optional(), - symbol: z.string().optional(), - }) - .passthrough() - .optional(), - baseToken: z - .object({ - name: z.string().optional(), - symbol: z.string().optional(), - address: z.string().optional(), - }) - .passthrough() - .optional(), + quoteToken: tokenSchema.optional(), + baseToken: tokenSchema.optional(), }) .passthrough(); @@ -56,8 +50,7 @@ const tokenResponseSchema = z const pairCache = createExpiringCache(PAIR_CACHE_TTL_MS); function toFiniteNumber(value: number | string | null | undefined): number | null { - if (value == null) return null; - const numeric = typeof value === "number" ? value : Number(value); + const numeric = Number(value ?? NaN); return Number.isFinite(numeric) ? numeric : null; } @@ -65,10 +58,7 @@ function liquidityUsd(pair: z.infer): number { return toFiniteNumber(pair.liquidity?.usd) ?? 0; } -function mapPairStats(pair: z.infer, mint?: string): PairStats { - const normalizedMint = mint?.trim() ?? ""; - const targetIsQuote = - normalizedMint.length > 0 && pair.quoteToken?.address?.trim() === normalizedMint; +function mapPairStats(pair: z.infer, targetIsQuote: boolean): PairStats { const token = targetIsQuote ? pair.quoteToken : pair.baseToken; const counterToken = targetIsQuote ? pair.baseToken : pair.quoteToken; @@ -93,36 +83,19 @@ export function selectSolanaPairs( pairs: Array> | null | undefined, mint?: string, ): PairStats[] { - if (!pairs || pairs.length === 0) { - return []; + const target = mint?.trim(); + const ranked: Array<{ pair: z.infer; base: boolean; quote: boolean }> = []; + for (const pair of pairs ?? []) { + if (pair.chainId?.toLowerCase() !== "solana") continue; + const base = !target || pair.baseToken?.address?.trim() === target; + const quote = Boolean(target) && pair.quoteToken?.address?.trim() === target; + if (base || quote) ranked.push({ pair, base, quote }); } - const normalizedMint = mint?.trim() ?? ""; - const ranked = pairs.filter((pair) => { - if ((pair.chainId ?? "").toLowerCase() !== "solana") { - return false; - } - if (!normalizedMint) { - return true; - } - return ( - pair.baseToken?.address?.trim() === normalizedMint || - pair.quoteToken?.address?.trim() === normalizedMint - ); - }); - - ranked.sort((a, b) => { - if (normalizedMint) { - const aIsBase = a.baseToken?.address?.trim() === normalizedMint; - const bIsBase = b.baseToken?.address?.trim() === normalizedMint; - if (aIsBase !== bIsBase) { - return aIsBase ? -1 : 1; - } - } - return liquidityUsd(b) - liquidityUsd(a); - }); - - return ranked.map((pair) => mapPairStats(pair, normalizedMint)); + ranked.sort( + (a, b) => Number(b.base) - Number(a.base) || liquidityUsd(b.pair) - liquidityUsd(a.pair), + ); + return ranked.map(({ pair, quote }) => mapPairStats(pair, quote)); } export function selectSolanaPair( @@ -147,13 +120,12 @@ export async function fetchDexScreenerPoolStats( } try { - const response = await withTimeout( - (signal) => - fetchImpl(`${DEXSCREENER_TOKEN_URL}/${encodeURIComponent(normalizedMint)}`, { - method: "GET", - signal, - }), - PAIR_FETCH_TIMEOUT_MS, + const response = await fetchImpl( + `${DEXSCREENER_TOKEN_URL}/${encodeURIComponent(normalizedMint)}`, + { + method: "GET", + signal: AbortSignal.timeout(PAIR_FETCH_TIMEOUT_MS), + }, ); if (!response.ok) { pairCache.setWithTTL(normalizedMint, []); @@ -161,7 +133,7 @@ export async function fetchDexScreenerPoolStats( } const payload = tokenResponseSchema.parse(await response.json()); - const stats = selectSolanaPairs(payload.pairs ?? [], normalizedMint); + const stats = selectSolanaPairs(payload.pairs, normalizedMint); pairCache.setWithTTL(normalizedMint, stats); return stats; } catch { @@ -170,16 +142,6 @@ export async function fetchDexScreenerPoolStats( } } -async function withTimeout(factory: (signal: AbortSignal) => Promise, timeoutMs: number) { - const controller = new AbortController(); - const timer = setTimeout(() => controller.abort(), timeoutMs); - try { - return await factory(controller.signal); - } finally { - clearTimeout(timer); - } -} - export async function fetchDexScreenerPairStats( mint: string, fetchImpl: FetchLike = globalThis.fetch as unknown as FetchLike, diff --git a/src/services/buy-alerts/formatter.ts b/src/services/buy-alerts/formatter.ts index 212b6a9c..14ef6bdf 100644 --- a/src/services/buy-alerts/formatter.ts +++ b/src/services/buy-alerts/formatter.ts @@ -1,4 +1,10 @@ -import { copyableHtml, escapeHtml, formatRate, formatUsdValue } from "../../utils/format-amount"; +import { + copyableHtml, + escapeHtml, + formatRate, + formatUsdValue, + trimFixed, +} from "../../utils/format-amount"; import { NetworkDetector } from "../../utils/network-detector"; import type { BuyDex, BuyEvent, PairStats } from "./types"; @@ -9,40 +15,28 @@ export type FormatBuyAlertInput = { solPriceUsd?: number | null; }; -function formatSolAmount(sol: number): string { - if (!Number.isFinite(sol) || sol <= 0) { - return "0"; - } - const formatted = sol.toFixed(4).replace(/0+$/, "").replace(/\.$/, ""); - return formatted || "0"; -} +const positiveFinite = (value: number | null | undefined): value is number => + Number.isFinite(value) && (value ?? 0) > 0; export function formatMarketCapUsd(value: number): string { if (!Number.isFinite(value) || value <= 0) { return ""; } - const abs = Math.abs(value); - const format = (scaled: number, suffix: string) => { - const text = scaled.toFixed(2).replace(/0+$/, "").replace(/\.$/, ""); - return `${text}${suffix}`; - }; + const format = (scaled: number, suffix: string) => `${trimFixed(scaled.toFixed(2))}${suffix}`; - if (abs >= 1_000_000_000) return format(value / 1_000_000_000, "B"); - if (abs >= 1_000_000) return format(value / 1_000_000, "M"); - if (abs >= 1_000) return format(value / 1_000, "K"); + if (value >= 1_000_000_000) return format(value / 1_000_000_000, "B"); + if (value >= 1_000_000) return format(value / 1_000_000, "M"); + if (value >= 1_000) return format(value / 1_000, "K"); return format(value, ""); } export function formatBuyTokenAmount(value: number): string { - if (!Number.isFinite(value) || value <= 0) { - return "0"; - } - return formatMarketCapUsd(value); + return formatMarketCapUsd(value) || "0"; } function format24hChange(value: number): string { - const abs = Math.abs(value).toFixed(2).replace(/0+$/, "").replace(/\.$/, ""); + const abs = trimFixed(Math.abs(value).toFixed(2)); if (value > 0) return `+${abs}%`; if (value < 0) return `-${abs}%`; return "0%"; @@ -60,17 +54,17 @@ export function dexMark(dex: BuyDex, dexId?: string | null): string { } export function dexLabel(dex: BuyDex, dexId?: string | null): string { - const fromPair = dexId?.trim().toLowerCase() ?? ""; - if (fromPair.startsWith("raydium")) return "Raydium AMM"; + const original = dexId?.trim(); + const fromPair = original?.toLowerCase(); + if (fromPair?.startsWith("raydium")) return "Raydium AMM"; if (fromPair === "pumpswap" || fromPair === "pump-amm") return "PumpSwap"; if (fromPair === "pumpfun" || fromPair === "pump") return "Pump.fun"; - if (fromPair === "meteora" || fromPair.startsWith("meteora")) return "Meteora"; + if (fromPair?.startsWith("meteora")) return "Meteora"; if (fromPair === "orca" || fromPair === "whirlpool") return "Orca"; if (fromPair === "jupiter") return "Jupiter"; if (dex === "raydium") return "Raydium AMM"; if (dex === "pump") return "Pump.fun"; - if (fromPair) return dexId!.trim(); - return "Unknown"; + return original || "Unknown"; } function linkedLabel(url: string | null, label: string): string { @@ -95,11 +89,6 @@ export function formatBuyAlertMessage({ const walletLabel = formatWalletLabel(event.trader); const walletUrl = NetworkDetector.buildSolscanAccountUrl(event.trader); const txUrl = NetworkDetector.buildSolscanTxUrl(event.signature); - const spentSol = formatSolAmount(event.solAmount ?? 0); - const spentUsd = - solPriceUsd && solPriceUsd > 0 && event.solAmount != null && event.solAmount > 0 - ? formatUsdValue(event.solAmount * solPriceUsd) - : null; const gotAmount = formatBuyTokenAmount(event.tokenAmount); const quote = escapeHtml( event.quoteSymbol?.trim() || event.inputSymbol?.trim() || pair?.quoteSymbol || "Unknown", @@ -109,11 +98,13 @@ export function formatBuyAlertMessage({ const mark = dexMark(event.dex, sourceDexId); let spentLine = "Spent: Unknown"; - if (event.solAmount != null && event.solAmount > 0) { - spentLine = spentUsd - ? `Spent: ${copyableHtml(spentSol)} SOL ($${escapeHtml(spentUsd)})` - : `Spent: ${copyableHtml(spentSol)} SOL`; - } else if (event.inputAmount != null && event.inputAmount > 0) { + if (positiveFinite(event.solAmount)) { + const spentSol = trimFixed(event.solAmount.toFixed(4)); + spentLine = `Spent: ${copyableHtml(spentSol)} SOL`; + if (positiveFinite(solPriceUsd)) { + spentLine += ` ($${escapeHtml(formatUsdValue(event.solAmount * solPriceUsd))})`; + } + } else if (positiveFinite(event.inputAmount)) { const inputAmount = formatBuyTokenAmount(event.inputAmount); const inputSymbol = event.inputSymbol?.trim(); spentLine = inputSymbol @@ -131,13 +122,13 @@ export function formatBuyAlertMessage({ ]; const priceBits: string[] = []; - if (pair?.priceUsd && pair.priceUsd > 0) { + if (positiveFinite(pair?.priceUsd)) { priceBits.push(`$${escapeHtml(formatRate(pair.priceUsd))}`); } if (txUrl) { priceBits.push(linkedLabel(txUrl, "[Txn]")); } - if (priceBits.length > 0) { + if (priceBits.length) { lines.push(`Price: ${priceBits.join(" | ")}`); } @@ -145,7 +136,7 @@ export function formatBuyAlertMessage({ lines.push("New Holder!"); } - const marketCap = pair?.marketCapUsd ? formatMarketCapUsd(pair.marketCapUsd) : ""; + const marketCap = formatMarketCapUsd(pair?.marketCapUsd ?? 0); if (marketCap) { lines.push(`📈 MarketCap: $${escapeHtml(marketCap)}`); } diff --git a/src/services/buy-alerts/pool-trades.ts b/src/services/buy-alerts/pool-trades.ts index 87476eba..fe2fd8d5 100644 --- a/src/services/buy-alerts/pool-trades.ts +++ b/src/services/buy-alerts/pool-trades.ts @@ -30,8 +30,8 @@ export function parseRetryAfterMs(value: string | null, nowMs = Date.now()): num if (!normalized) return null; const seconds = Number(normalized); - if (Number.isFinite(seconds) && seconds >= 0) { - return Math.round(seconds * 1_000); + if (Number.isFinite(seconds)) { + return seconds < 0 ? null : Math.round(seconds * 1_000); } const retryAt = Date.parse(normalized); @@ -58,11 +58,8 @@ export function rememberSignature( return false; } known.add(signature); - while (known.size > max) { - const oldest = known.values().next().value; - if (oldest == null) { - break; - } + for (const oldest of known) { + if (!(known.size > max)) break; known.delete(oldest); } return true; @@ -94,8 +91,7 @@ const geckoTradesResponseSchema = z .passthrough(); function parseFiniteNumber(value: number | string | undefined): number | null { - if (value == null) return null; - const numeric = typeof value === "number" ? value : Number(value); + const numeric = Number(value ?? NaN); if (!Number.isFinite(numeric) || numeric < 0) { return null; } @@ -119,6 +115,7 @@ export function parseGeckoPoolTrade( } const attrs = parsed.data.attributes; + const signature = attrs.tx_hash.trim(); const toMint = (attrs.to_token_address ?? "").trim(); const fromMint = (attrs.from_token_address ?? "").trim(); if (toMint !== mint) { @@ -128,36 +125,27 @@ export function parseGeckoPoolTrade( const trader = (attrs.tx_from_address ?? "").trim(); const tokenAmount = parseFiniteNumber(attrs.to_token_amount); const fromAmount = parseFiniteNumber(attrs.from_token_amount); - if (!trader || tokenAmount == null || tokenAmount <= 0) { + if (!signature || !trader || tokenAmount == null || tokenAmount <= 0) { return null; } const solAmount = isSolMint(fromMint) && fromAmount != null && fromAmount > 0 ? fromAmount : null; + const symbol = inputSymbol?.trim() || (isSolMint(fromMint) ? "SOL" : null); return { - signature: attrs.tx_hash.trim(), + signature, mint, trader, solAmount, inputAmount: fromAmount, - inputSymbol: inputSymbol?.trim() || (isSolMint(fromMint) ? "SOL" : null), + inputSymbol: symbol, tokenAmount, dex: mapDexFromPool(dexId), dexId: dexId?.trim() || null, - quoteSymbol: inputSymbol?.trim() || (isSolMint(fromMint) ? "SOL" : null), + quoteSymbol: symbol, }; } -async function withTimeout(factory: (signal: AbortSignal) => Promise, timeoutMs: number) { - const controller = new AbortController(); - const timer = setTimeout(() => controller.abort(), timeoutMs); - try { - return await factory(controller.signal); - } finally { - clearTimeout(timer); - } -} - export type PoolTradePollerOptions = { fetchPairStats?: (mint: string) => Promise; fetchPoolStats?: (mint: string) => Promise; @@ -171,14 +159,13 @@ export type PoolTradePollerOptions = { }; async function fetchGeckoTrades(pairAddress: string): Promise { - const response = await withTimeout( - (signal) => - fetch(`${GECKO_POOL_TRADES_URL}/${encodeURIComponent(pairAddress)}/trades`, { - method: "GET", - headers: { accept: "application/json" }, - signal, - }), - TRADE_FETCH_TIMEOUT_MS, + const response = await fetch( + `${GECKO_POOL_TRADES_URL}/${encodeURIComponent(pairAddress)}/trades`, + { + method: "GET", + headers: { accept: "application/json" }, + signal: AbortSignal.timeout(TRADE_FETCH_TIMEOUT_MS), + }, ); if (response.status === 429) { throw new GeckoRateLimitError(parseRetryAfterMs(response.headers.get("retry-after"))); diff --git a/src/services/buy-alerts/publisher.ts b/src/services/buy-alerts/publisher.ts index 8b7fd32f..8da9e1f9 100644 --- a/src/services/buy-alerts/publisher.ts +++ b/src/services/buy-alerts/publisher.ts @@ -26,7 +26,7 @@ export type BuyAlertTokenSource = { }; export type BuyAlertPublisherDeps = { - chatDb: ChatDatabase; + chatDb: Pick; tokenManager: BuyAlertTokenSource; sendHtml: ( chatId: number, @@ -90,32 +90,27 @@ export function createBuyAlertPublisher(deps: BuyAlertPublisherDeps) { const current = now(); const windowStart = current - 60_000; const stamps = (chatWindows.get(chatId) ?? []).filter((stamp) => stamp > windowStart); - if (stamps.length >= maxAlertsPerMinute) { - chatWindows.set(chatId, stamps); - return false; - } - stamps.push(current); + const allowed = stamps.length < maxAlertsPerMinute; + if (allowed) stamps.push(current); chatWindows.set(chatId, stamps); - return true; + return allowed; }; - const matchesMint = (chatId: number, mint: string, enabledOnly = true): boolean => { + const matchesMint = (chatId: number, mint: string): boolean => { const config = deps.chatDb.getChatBuyAlerts(chatId); - if (enabledOnly && !config?.enabled) { + if (!config?.enabled) { return false; } return resolveForChat(chatId).mint === mint; }; const belowMinimum = (chatId: number, solAmount: number | null): boolean => { - const minLamports = deps.chatDb.getChatBuyAlerts(chatId)?.min_sol_lamports; - if (minLamports == null || minLamports <= 0) { + const minLamports = deps.chatDb.getChatBuyAlerts(chatId)?.min_sol_lamports ?? 0; + if (minLamports <= 0) { return false; } - if (solAmount == null || solAmount <= 0) { - return true; - } - return solAmount * LAMPORTS_PER_SOL + 1e-9 < minLamports; + const lamports = (solAmount ?? 0) * LAMPORTS_PER_SOL; + return !Number.isFinite(lamports) || lamports + 1e-9 < minLamports; }; const enrichEvent = async (event: BuyEvent): Promise => { @@ -125,8 +120,7 @@ export function createBuyAlertPublisher(deps: BuyAlertPublisherDeps) { if (!deps.resolveNewHolder) { return event; } - const newHolder = await deps.resolveNewHolder(event); - return newHolder == null ? event : { ...event, newHolder }; + return { ...event, newHolder: await deps.resolveNewHolder(event) }; }; const resolveMedia = (chatId: number): BuyAlertMedia | null => { @@ -218,14 +212,14 @@ export function createBuyAlertPublisher(deps: BuyAlertPublisherDeps) { let posted = 0; for (const config of targets) { - if (await publishToChat(config.chat_id, enriched, pair, solPriceUsd ?? null)) { + if (await publishToChat(config.chat_id, enriched, pair, solPriceUsd)) { deliveredChats.add(config.chat_id); posted += 1; } } - if (deliveredChats.size > 0) { + if (deliveredChats.size) { deliveredSignatures.set(event.signature, { - chatIds: new Set(deliveredChats), + chatIds: deliveredChats, expiresAt: now() + SIGNATURE_TTL_MS, }); } @@ -248,7 +242,7 @@ export function createBuyAlertPublisher(deps: BuyAlertPublisherDeps) { dex: pair?.dexId?.toLowerCase().includes("raydium") ? "raydium" : "pump", newHolder: true, }; - await publishToChat(chatId, event, pair, solPriceUsd ?? null); + await publishToChat(chatId, event, pair, solPriceUsd); }, }; } @@ -256,13 +250,14 @@ export function createBuyAlertPublisher(deps: BuyAlertPublisherDeps) { export function resolveBuyAlertMedia( config: ChatBuyAlertConfig | null | undefined, ): BuyAlertMedia | null { - const fileId = config?.media_file_id?.trim(); + if (!config) return null; + const fileId = config.media_file_id?.trim(); if (!fileId || fileId === CHAT_MEDIA_DISABLED_SENTINEL) { return null; } return { fileId, - mediaType: config?.media_type ?? "video", + mediaType: config.media_type ?? "video", }; } diff --git a/src/utils/arg-parsing.ts b/src/utils/arg-parsing.ts index ca04bcf5..82fee1d9 100644 --- a/src/utils/arg-parsing.ts +++ b/src/utils/arg-parsing.ts @@ -24,7 +24,7 @@ export function inferMaxPlayers( : amountArgIndex + 1; // amount, players const candidate = args[playersIndex]; - if (candidate !== undefined) { + if (typeof candidate === "string") { const trimmed = candidate.trim(); // Only accept pure integer strings (no decimals, no suffixes like "4x") if (/^\d+$/.test(trimmed)) { diff --git a/src/utils/callback-data.ts b/src/utils/callback-data.ts index eb634029..9df42772 100644 --- a/src/utils/callback-data.ts +++ b/src/utils/callback-data.ts @@ -65,6 +65,7 @@ const decodeSigned = (value: string | undefined): number | null => { }; const normalizeAmount = (amount: string): { digits: bigint; scale: number } | null => { + if (typeof amount !== "string") return null; const trimmed = amount.trim(); if (!/^\d+(?:\.\d+)?$/.test(trimmed)) return null; const decimalPoint = trimmed.indexOf("."); diff --git a/src/utils/concurrency.ts b/src/utils/concurrency.ts index af6e1f1d..634353fc 100644 --- a/src/utils/concurrency.ts +++ b/src/utils/concurrency.ts @@ -8,7 +8,7 @@ export const mapWithConcurrency = async ( ): Promise => { const safeLimit = Number.isFinite(limit) ? Math.trunc(limit) : 0; const workerCount = Math.min(items.length, Math.max(1, safeLimit)); - const results: TResult[] = []; + const results = Array(items.length); const entries = items.entries(); const workers = Array.from({ length: workerCount }, async () => { diff --git a/src/utils/expiring-cache.ts b/src/utils/expiring-cache.ts index f3d629eb..cc23a024 100644 --- a/src/utils/expiring-cache.ts +++ b/src/utils/expiring-cache.ts @@ -13,15 +13,23 @@ export interface ExpiringCache { class ExpiringCacheImpl implements ExpiringCache { private readonly entries = new Map(); + private readonly timers = new Map>(); constructor(private readonly defaultTtlMs: number) {} setWithTTL(key: string, value: TValue, ttlMs: number = this.defaultTtlMs): void { + this.cancelTimer(key); const ttl = Number.isFinite(ttlMs) && ttlMs > 0 ? ttlMs : this.defaultTtlMs; this.entries.set(key, { value, expiresAt: Date.now() + ttl }); + const timer = setTimeout(() => { + this.freshEntry(key); + this.timers.delete(key); + }, ttl); + if (typeof timer.unref === "function") timer.unref(); + this.timers.set(key, timer); } - get(key: string): TValue | undefined { + private freshEntry(key: string): { value: TValue; expiresAt: number } | undefined { const entry = this.entries.get(key); if (!entry) { return undefined; @@ -33,7 +41,11 @@ class ExpiringCacheImpl implements ExpiringCache { return undefined; } - return entry.value; + return entry; + } + + get(key: string): TValue | undefined { + return this.freshEntry(key)?.value; } peek(key: string): TValue | undefined { @@ -41,6 +53,7 @@ class ExpiringCacheImpl implements ExpiringCache { } delete(key: string): boolean { + this.cancelTimer(key); return this.entries.delete(key); } @@ -49,8 +62,18 @@ class ExpiringCacheImpl implements ExpiringCache { } clear(): void { + for (const timer of this.timers.values()) clearTimeout(timer); + this.timers.clear(); this.entries.clear(); } + + private cancelTimer(key: string): void { + const timer = this.timers.get(key); + if (timer) { + clearTimeout(timer); + this.timers.delete(key); + } + } } export const createExpiringCache = (defaultTtlMs: number): ExpiringCache => { diff --git a/src/utils/format-amount.ts b/src/utils/format-amount.ts index a71cf99f..40bdde89 100644 --- a/src/utils/format-amount.ts +++ b/src/utils/format-amount.ts @@ -78,19 +78,19 @@ export function formatAmount( // Always reserve at least one digit before the decimal point. const padded = digits.padStart(decimals + 1, "0"); - const integerEnd = padded.length - decimals; + let integerPart = decimals === 0 ? padded : padded.slice(0, -decimals) || "0"; + const fractional = decimals === 0 ? "" : padded.slice(-decimals); const desired = Math.max(0, Math.min(maxFractionDigits, decimals)); - const roundAt = integerEnd + desired; - const shown = padded.slice(0, roundAt); - // An absent next digit is NaN, so it does not trigger rounding. - const rounded = - Number(padded[roundAt]) >= 5 - ? (BigInt(shown) + 1n).toString().padStart(desired + 1, "0") - : shown; - const split = rounded.length - desired; - const fractional = rounded.slice(split); - const fractionalOut = trim ? fractional.replace(/0+$/, "") : fractional; - return sign + rounded.slice(0, split) + (fractionalOut ? "." + fractionalOut : ""); + let fractionalOut = fractional.slice(0, desired); + if ((fractional[desired] ?? "") >= "5") { + const width = fractionalOut.length; + const rounded = (BigInt(integerPart + fractionalOut) + 1n).toString().padStart(width + 1, "0"); + const split = rounded.length - width; + integerPart = rounded.slice(0, split); + fractionalOut = rounded.slice(split); + } + if (trim) fractionalOut = fractionalOut.replace(/0+$/, ""); + return sign + integerPart + (fractionalOut ? "." + fractionalOut : ""); } export function formatTokenDisplay(value: number, options: FormatTokenDisplayOptions = {}): string { @@ -184,7 +184,7 @@ export function formatUsdValue(value: number, options: FormatUsdValueOptions = { return approximate ? `≈ $${formatted}` : formatted; } -function trimFixed(value: string): string { +export function trimFixed(value: string): string { // toFixed uses exponential notation for large numbers. Do not trim its exponent. return value.includes("e") ? value : value.replace(/0+$/, "").replace(/\.$/, ""); } diff --git a/tests/buy-alerts.dexscreener.test.ts b/tests/buy-alerts.dexscreener.test.ts index 66c0d909..ba4c9811 100644 --- a/tests/buy-alerts.dexscreener.test.ts +++ b/tests/buy-alerts.dexscreener.test.ts @@ -1,4 +1,5 @@ -import { expect, setSystemTime, test } from "bun:test"; +import { expect, mock, setSystemTime, spyOn, test } from "bun:test"; +import type { FetchLike } from "../src/types"; import { fetchDexScreenerPairStats, fetchDexScreenerPoolStats, @@ -7,6 +8,108 @@ import { __test_clearDexScreenerCache, } from "../src/services/buy-alerts/dexscreener"; +const wirePair = { + chainId: "SOLANA", + dexId: " raydium ", + url: " https://dexscreener.com/solana/pair ", + pairAddress: " pair-old ", + priceUsd: "0.01", + fdv: "1234.5", + priceChange: { h24: "-7" }, + liquidity: { usd: "100" }, + baseToken: { address: " mint ", name: " ", symbol: " TOKEN " }, + quoteToken: { address: " usdc ", symbol: " USDC " }, +}; + +test("normalizes the provider fields and uses FDV when market cap is absent", () => { + const [stats] = selectSolanaPairs( + [ + { ...wirePair, chainId: undefined, pairAddress: "missing-chain" }, + { chainId: "solana", baseToken: {}, quoteToken: {}, pairAddress: "unrelated" }, + { chainId: "solana", quoteToken: {}, pairAddress: "unmatched" }, + wirePair, + { chainId: "solana", baseToken: { address: "mint" }, pairAddress: "no-counter" }, + ], + " mint ", + ); + expect(stats).toEqual({ + priceUsd: 0.01, + marketCapUsd: 1234.5, + priceChangeH24: -7, + url: "https://dexscreener.com/solana/pair", + dexId: "raydium", + pairAddress: "pair-old", + quoteSymbol: "USDC", + tokenName: "TOKEN", + }); + expect(selectSolanaPairs([wirePair], " usdc ")).toEqual([ + { + priceUsd: null, + marketCapUsd: null, + priceChangeH24: null, + url: "https://dexscreener.com/solana/pair", + dexId: "raydium", + pairAddress: "pair-old", + quoteSymbol: "TOKEN", + tokenName: "USDC", + }, + ]); +}); + +test("keeps a stale provider result when a fresh payload uses the wrong field shape", async () => { + __test_clearDexScreenerCache(); + const start = new Date("2026-01-01T00:00:00Z"); + setSystemTime(start); + try { + const previous = await fetchDexScreenerPoolStats("mint", async () => + Response.json({ pairs: [wirePair] }), + ); + expect(previous).toHaveLength(1); + setSystemTime(new Date(start.getTime() + 31_000)); + for (const broken of [ + { pairs: "not an array" }, + ...[ + { fdv: true }, + { liquidity: { usd: true } }, + { priceChange: { h24: [] } }, + { quoteToken: { address: 4 } }, + { baseToken: { name: 4 } }, + ].map((patch) => ({ + pairs: [{ ...wirePair, pairAddress: "bad-new-pair", ...patch }], + })), + ]) { + expect(await fetchDexScreenerPoolStats("mint", async () => Response.json(broken))).toEqual( + previous, + ); + } + } finally { + setSystemTime(); + } +}); + +test("opens the exact pool URL with a deadline and cache clear forces a fresh request", async () => { + __test_clearDexScreenerCache(); + const controller = new AbortController(); + const timeout = spyOn(AbortSignal, "timeout").mockReturnValue(controller.signal); + const fetcher = mock(async () => Response.json({ pairs: [wirePair] })); + try { + expect(await fetchDexScreenerPoolStats(" mint ", fetcher)).toHaveLength(1); + expect(fetcher).toHaveBeenCalledWith("https://api.dexscreener.com/latest/dex/tokens/mint", { + method: "GET", + signal: controller.signal, + }); + expect(timeout).toHaveBeenCalledWith(5000); + expect(await fetchDexScreenerPoolStats("mint", fetcher)).toHaveLength(1); + expect(fetcher).toHaveBeenCalledTimes(1); + __test_clearDexScreenerCache(); + fetcher.mockImplementation(async () => Response.json({ pairs: null })); + expect(await fetchDexScreenerPoolStats("mint", fetcher)).toEqual([]); + expect(fetcher).toHaveBeenCalledTimes(2); + } finally { + timeout.mockRestore(); + } +}); + test("selectSolanaPair prefers the highest-liquidity Solana pair", () => { const stats = selectSolanaPair([ { diff --git a/tests/buy-alerts.formatter.test.ts b/tests/buy-alerts.formatter.test.ts index d113308d..2f140bb7 100644 --- a/tests/buy-alerts.formatter.test.ts +++ b/tests/buy-alerts.formatter.test.ts @@ -6,7 +6,7 @@ import { formatBuyTokenAmount, formatMarketCapUsd, } from "../src/services/buy-alerts/formatter"; -import type { BuyEvent } from "../src/services/buy-alerts/types"; +import type { BuyEvent, PairStats } from "../src/services/buy-alerts/types"; const event: BuyEvent = { signature: "5Ksig", @@ -57,6 +57,9 @@ test("formatBuyAlertMessage matches the MAGAIBA buy-bot layout", () => { expect(text).toContain("DexScreener"); expect(text).not.toContain("Tap to copy"); expect(text).toContain("https://solscan.io/tx/5Ksig"); + expect(text).toContain('Price: $0.000152 | [Txn]'); + expect(text.split("\n")[1]).toBe(""); + expect(text.split("\n").at(-2)).toBe(""); } finally { if (originalNetwork === undefined) { Reflect.deleteProperty(process.env, "SOLANA_NETWORK"); @@ -103,6 +106,20 @@ test("dexLabel maps explicit venue metadata and preserves unknown venues", () => expect(dexLabel("unknown", null)).toBe("Unknown"); }); +test.each([ + [" RAYDIUM-clmm ", "Raydium AMM"], + ["pump-amm", "PumpSwap"], + ["pump", "Pump.fun"], + ["pumpfun", "Pump.fun"], + ["meteora-dlmm", "Meteora"], + ["orca", "Orca"], + ["whirlpool", "Orca"], + ["jupiter", "Jupiter"], + [" Lifinity ", "Lifinity"], +])("labels provider venue %s", (dex, label) => { + expect(dexLabel("unknown", dex)).toBe(label); +}); + test("formatBuyAlertMessage prefers the event venue over the market-data pair", () => { const text = formatBuyAlertMessage({ event: { @@ -167,6 +184,15 @@ test("formatMarketCapUsd uses MAGAIBA-style suffixes", () => { expect(formatMarketCapUsd(1_500_000)).toBe("1.5M"); }); +test.each<[number, string]>([ + [901.01, "901.01"], + [1_000, "1K"], + [1_000_000, "1M"], + [1_000_000_000, "1B"], +])("compact market value %i displays %s", (value, expected) => { + expect(formatMarketCapUsd(value)).toBe(expected); +}); + test("formatMarketCapUsd hides missing or invalid market caps", () => { expect(formatMarketCapUsd(0)).toBe(""); expect(formatMarketCapUsd(-5)).toBe(""); @@ -181,3 +207,60 @@ test("formatBuyTokenAmount shows 0 for invalid amounts and compacts real ones", expect(formatBuyTokenAmount(Number.POSITIVE_INFINITY)).toBe("0"); expect(formatBuyTokenAmount(1_270_000)).toBe("1.27M"); }); + +const quietPair: PairStats = { + priceUsd: 0, + marketCapUsd: 0, + priceChangeH24: -0, + url: null, + dexId: " meteora-dlmm ", + quoteSymbol: "SOL", + pairAddress: "pair-test", + tokenName: " ", +}; + +test("labeled fields stay truthful when no SOL valuation or explorer link is available", () => { + const original = process.env.SOLANA_NETWORK; + process.env.SOLANA_NETWORK = "http://localhost:8899"; + try { + const text = formatBuyAlertMessage({ + event: { + ...event, + trader: "1234567890", + signature: "", + dex: "unknown", + solAmount: 1.002, + inputSymbol: " DAI ", + newHolder: false, + }, + ticker: "TOK", + pair: quietPair, + solPriceUsd: 0, + }); + expect(text).toContain("💰 BUY - <Wrapped>\n\n1234567890\n"); + expect(text).toContain("Spent: 1.002 SOL\n"); + expect(text).toContain("DEX: ☄️ Meteora DAI\n"); + expect(text).toContain("24h: 0%"); + expect(text).not.toContain("Price:"); + expect(text).not.toContain("MarketCap:"); + expect(text).not.toContain("([ + [0, 2, "Spent: 2"], + [null, 0, "Spent: Unknown"], + [Infinity, 3, "Spent: 3"], + [null, Infinity, "Spent: Unknown"], +])("falls back from unavailable SOL %p to input %p", (solAmount, inputAmount, expected) => { + const text = formatBuyAlertMessage({ + event: { ...event, solAmount, inputAmount, inputSymbol: undefined }, + ticker: "TOK", + pair: { ...quietPair, tokenName: null }, + solPriceUsd: 15, + }); + expect(text.split("\n").find((line) => line.startsWith("Spent:"))).toBe(expected); +}); diff --git a/tests/buy-alerts.pool-trades-edge-cases.test.ts b/tests/buy-alerts.pool-trades-edge-cases.test.ts index c620c94a..cae46d90 100644 --- a/tests/buy-alerts.pool-trades-edge-cases.test.ts +++ b/tests/buy-alerts.pool-trades-edge-cases.test.ts @@ -58,6 +58,12 @@ describe("rememberSignature", () => { expect([...known]).toEqual(["b", "c"]); expect(rememberSignature(known, "c", 2)).toBe(false); }); + + test("an unspecified numeric limit does not evict known signatures", () => { + const known = new Set(["first"]); + expect(rememberSignature(known, "second", NaN)).toBe(true); + expect([...known]).toEqual(["first", "second"]); + }); }); describe("parseGeckoPoolTrade rejects unusable payloads", () => { @@ -79,10 +85,40 @@ describe("parseGeckoPoolTrade rejects unusable payloads", () => { expect( parseGeckoPoolTrade(mint, trade("sig", undefined, { to_token_amount: "lots" })), ).toBeNull(); + expect(parseGeckoPoolTrade(mint, trade("sig", undefined, { to_token_amount: 0 }))).toBeNull(); // An unusable input amount only drops the SOL amount, not the whole buy. const event = parseGeckoPoolTrade(mint, trade("sig", undefined, { from_token_amount: "-1" })); expect(event).toMatchObject({ signature: "sig", solAmount: null, inputAmount: null }); }); + + test("requires a real signature and normalizes the wallet, mint, ticker, and venue", () => { + expect(parseGeckoPoolTrade(mint, trade(" "))).toBeNull(); + expect( + parseGeckoPoolTrade( + mint, + trade(" sig ", undefined, { + tx_from_address: " fake-trader ", + from_token_address: ` ${WSOL_MINT} `, + to_token_address: ` ${mint} `, + from_token_amount: 2, + to_token_amount: "3", + }), + " Raydium CLMM ", + " SOL ", + ), + ).toEqual({ + signature: "sig", + mint, + trader: "fake-trader", + solAmount: 2, + tokenAmount: 3, + inputAmount: 2, + inputSymbol: "SOL", + quoteSymbol: "SOL", + dex: "raydium", + dexId: "Raydium CLMM", + }); + }); }); describe("pool trade poller", () => { @@ -92,6 +128,27 @@ describe("pool trade poller", () => { now: () => 0, }; + test("includes the exact watch start boundary but skips earlier and undated buys", async () => { + const start = Date.parse("2026-09-03T20:00:00Z"); + const observed: string[] = []; + const poller = track( + createPoolTradePoller({ + ...base, + now: () => start, + fetchPoolStats: async () => [pool(" p0 "), pool("p0"), pool(" ")], + fetchTrades: async () => ({ + data: [trade("boundary", start), trade("undated"), trade("before", start - 1)], + }), + }), + ); + poller.onTrade(({ signature }) => { + observed.push(signature); + }); + poller.setMints([` ${mint} `, mint, " "]); + await poller.pollNow(); + expect(observed).toEqual(["boundary"]); + }); + test("a throwing error handler is logged and does not break polling", async () => { const errorSpy = spyOn(console, "error").mockImplementation(() => {}); try { diff --git a/tests/buy-alerts.pool-trades.test.ts b/tests/buy-alerts.pool-trades.test.ts index e3631d80..381eb9bb 100644 --- a/tests/buy-alerts.pool-trades.test.ts +++ b/tests/buy-alerts.pool-trades.test.ts @@ -49,6 +49,10 @@ test("parseGeckoPoolTrade skips trades whose output is another mint", () => { test("parseRetryAfterMs accepts seconds and HTTP dates", () => { const now = Date.parse("2026-09-03T20:00:00.000Z"); expect(parseRetryAfterMs("30", now)).toBe(30_000); + expect(parseRetryAfterMs(" 0.125 ", now)).toBe(125); + expect(parseRetryAfterMs("0", now)).toBe(0); + expect(parseRetryAfterMs("-1", now)).toBeNull(); + expect(parseRetryAfterMs("Thu, 03 Sep 2026 19:59:59 GMT", now)).toBe(0); expect(parseRetryAfterMs("Thu, 03 Sep 2026 20:00:45 GMT", now)).toBe(45_000); expect(parseRetryAfterMs("invalid", now)).toBeNull(); }); @@ -575,6 +579,9 @@ describe("pool trade poller defaults", () => { }; test("fetches GeckoTerminal trades for the encoded pool address", async () => { + const deadline = new AbortController(); + const timeout = spyOn(AbortSignal, "timeout").mockReturnValue(deadline.signal); + spies.push(timeout); const calls = stubFetch(() => Response.json({ data: [geckoBuy] })); const received: BuyEvent[] = []; const poller = createPoolTradePoller({ @@ -592,7 +599,9 @@ describe("pool trade poller defaults", () => { "https://api.geckoterminal.com/api/v2/networks/solana/pools/pair%2Fwith%20space/trades", ); expect(calls[0]!.init.headers).toEqual({ accept: "application/json" }); - expect(calls[0]!.init.signal).toBeInstanceOf(AbortSignal); + expect(calls[0]!.init.signal).toBe(deadline.signal); + expect(calls[0]!.init.method).toBe("GET"); + expect(timeout).toHaveBeenCalledWith(5000); // The first snapshot only primes the pool. expect(received).toEqual([]); }); diff --git a/tests/buy-alerts.publisher.test.ts b/tests/buy-alerts.publisher.test.ts index c0c14d18..5c47aee7 100644 --- a/tests/buy-alerts.publisher.test.ts +++ b/tests/buy-alerts.publisher.test.ts @@ -1,8 +1,13 @@ import { beforeEach, expect, spyOn, test } from "bun:test"; import { ChatDatabase } from "../src/utils/chat-database"; import { resetTestDatabase } from "./helpers/database"; -import { attachBuyAlertFeed, createBuyAlertPublisher } from "../src/services/buy-alerts/publisher"; -import type { BuyEvent } from "../src/services/buy-alerts/types"; +import { + attachBuyAlertFeed, + createBuyAlertPublisher, + resolveBuyAlertMedia, +} from "../src/services/buy-alerts/publisher"; +import type { BuyEvent, PairStats } from "../src/services/buy-alerts/types"; +import { CHAT_MEDIA_DISABLED_SENTINEL } from "../src/utils/constants"; const TIMBA_MINT = "F3A1baCgv4TF79TSjdMTvpMDtNv8DJvHZwNc9DG8pump"; @@ -77,6 +82,11 @@ test("publisher rate-limits a noisy chat", async () => { const third = await publisher.publish(event({ signature: "c" })); expect(third.posted).toBe(0); expect(third.skipped).toContain("rate:-9"); + + clock = 60_999; + expect((await publisher.publish(event({ signature: "d" }))).skipped).toEqual(["rate:-9"]); + clock = 61_000; + expect((await publisher.publish(event({ signature: "e" }))).posted).toBe(1); }); test("publisher watches only enabled-chat mints and can send a test", async () => { @@ -330,7 +340,11 @@ test("publisher forgets delivered signatures after the deduplication TTL", async expect((await publisher.publish(event({ signature: "ttl-signature" }))).posted).toBe(1); expect((await publisher.publish(event({ signature: "ttl-signature" }))).posted).toBe(0); - clock += 60 * 60 * 1000 + 1; + clock += 3_599_999; + expect((await publisher.publish(event({ signature: "ttl-signature" }))).skipped).toEqual([ + "duplicate", + ]); + clock += 1; expect((await publisher.publish(event({ signature: "ttl-signature" }))).posted).toBe(1); expect(sent).toBe(2); }); @@ -364,10 +378,7 @@ test("publisher treats a signature still being delivered as a duplicate", async const chatDb = ChatDatabase.getInstance(); chatDb.upsertChatBuyAlerts(-11, { enabled: true }); - let releasePair!: () => void; - const pairGate = new Promise((resolve) => { - releasePair = () => resolve(null); - }); + const pairGate = Promise.withResolvers(); const sent: number[] = []; const publisher = createBuyAlertPublisher({ chatDb, @@ -375,14 +386,13 @@ test("publisher treats a signature still being delivered as a duplicate", async sendHtml: async (chatId) => { sent.push(chatId); }, - fetchPairStats: () => pairGate, + fetchPairStats: () => pairGate.promise, }); const first = publisher.publish(event({ signature: "in-flight" })); - const concurrent = await publisher.publish(event({ signature: "in-flight" })); - expect(concurrent).toEqual({ posted: 0, skipped: ["duplicate"] }); - - releasePair(); + const concurrent = publisher.publish(event({ signature: "in-flight" })); + pairGate.resolve(null); + expect(await concurrent).toEqual({ posted: 0, skipped: ["duplicate"] }); expect(await first).toEqual({ posted: 1, skipped: [] }); expect(sent).toEqual([-11]); }); @@ -398,7 +408,7 @@ test("publisher skips chats whose alerts were disabled after being listed", asyn chatDb: { getEnabledChatBuyAlerts: () => enabledSnapshot, getChatBuyAlerts: (chatId: number) => chatDb.getChatBuyAlerts(chatId), - } as unknown as ChatDatabase, + }, tokenManager, sendHtml: async (chatId) => { sent.push(chatId); @@ -413,6 +423,117 @@ test("publisher skips chats whose alerts were disabled after being listed", asyn expect(sent).toEqual([]); }); +test("allows the exact lamport minimum but rejects missing and non-finite SOL sizes", async () => { + const chatDb = ChatDatabase.getInstance(); + chatDb.upsertChatBuyAlerts(-1, { enabled: true, min_sol_lamports: 1 }); + const posted: string[] = []; + const publisher = createBuyAlertPublisher({ + chatDb, + tokenManager, + fetchPairStats: async () => null, + sendHtml: async (_chatId, html) => { + posted.push(html); + }, + }); + for (const [index, solAmount] of [null, 0, -1, 0.5e-9, NaN, Infinity].entries()) { + expect(await publisher.publish(event({ signature: `dust-${index}`, solAmount }))).toEqual({ + posted: 0, + skipped: ["dust:-1"], + }); + } + expect(await publisher.publish(event({ signature: "at-minimum", solAmount: 1e-9 }))).toEqual({ + posted: 1, + skipped: [], + }); + expect(posted).toHaveLength(1); +}); + +test("preview uses the selected pool label, SOL conversion, and configured Telegram media", async () => { + const chatDb = ChatDatabase.getInstance(); + chatDb.upsertChatBuyAlerts(-1, { enabled: false, media_file_id: " video-id " }); + const pair: PairStats = { + priceUsd: null, + marketCapUsd: null, + priceChangeH24: null, + url: null, + dexId: "Raydium CLMM", + quoteSymbol: "SOL", + pairAddress: null, + tokenName: null, + }; + const sent: Array<{ html: string; media: unknown }> = []; + const publisher = createBuyAlertPublisher({ + chatDb, + tokenManager, + fetchPairStats: async () => pair, + fetchSolPriceUsd: async () => 100, + sendHtml: async (_id, html, media) => { + sent.push({ html, media }); + }, + }); + await publisher.sendTest(-1); + expect(sent).toEqual([ + { + html: expect.stringContaining("Spent: 1.8998 SOL ($189.98)"), + media: { fileId: "video-id", mediaType: "video" }, + }, + ]); + expect(sent[0]?.html).toContain("Raydium AMM"); + expect(sent[0]?.html).toContain("111111...1112"); + chatDb.upsertChatBuyAlerts(-1, { media_file_id: CHAT_MEDIA_DISABLED_SENTINEL }); + expect(resolveBuyAlertMedia(chatDb.getChatBuyAlerts(-1))).toBeNull(); + expect(resolveBuyAlertMedia(null)).toBeNull(); +}); + +test("refreshing a partially delivered signature does not block expiry of an older neighbor", async () => { + let now = 1_000; + const chatDb = ChatDatabase.getInstance(); + chatDb.upsertChatBuyAlerts(-1, { enabled: true }); + const publisher = createBuyAlertPublisher({ + chatDb, + tokenManager, + fetchPairStats: async () => null, + now: () => now, + sendHtml: async () => {}, + }); + expect((await publisher.publish(event({ signature: "old" }))).posted).toBe(1); + now += 15_000; + expect((await publisher.publish(event({ signature: "neighbor" }))).posted).toBe(1); + now += 15_000; + chatDb.upsertChatBuyAlerts(-2, { enabled: true }); + expect((await publisher.publish(event({ signature: "old" }))).posted).toBe(1); + now = 3_616_000; + expect((await publisher.publish(event({ signature: "old" }))).skipped).toEqual(["duplicate"]); + expect((await publisher.publish(event({ signature: "neighbor" }))).posted).toBe(2); + now -= 5_000; + expect((await publisher.publish(event({ signature: "neighbor" }))).skipped).toEqual([ + "duplicate", + ]); +}); + +test("sweeps an expired signature at the exact window boundary even when a different buy arrives", async () => { + let now = 1_000; + const chatDb = ChatDatabase.getInstance(); + chatDb.upsertChatBuyAlerts(-1, { enabled: true }); + const publisher = createBuyAlertPublisher({ + chatDb, + tokenManager, + fetchPairStats: async () => null, + now: () => now, + sendHtml: async () => {}, + }); + expect((await publisher.publish(event({ signature: "first" }))).posted).toBe(1); + now = 3_541_000; + expect((await publisher.publish(event({ signature: "minute-before" }))).posted).toBe(1); + now = 3_601_000; + expect((await publisher.publish(event({ signature: "boundary" }))).posted).toBe(1); + now -= 1; + expect((await publisher.publish(event({ signature: "first" }))).posted).toBe(1); + expect((await publisher.publish(event({ signature: "minute-before" }))).skipped).toEqual([ + "duplicate", + ]); +}); + test("attachBuyAlertFeed forwards trades and logs publish failures", async () => { let handler: ((event: BuyEvent) => void) | undefined; const feed = { diff --git a/tests/expiring-cache.test.ts b/tests/expiring-cache.test.ts index cea8a756..9b6d4e01 100644 --- a/tests/expiring-cache.test.ts +++ b/tests/expiring-cache.test.ts @@ -1,10 +1,69 @@ -import { afterEach, beforeEach, describe, expect, spyOn, test } from "bun:test"; +import { afterEach, beforeEach, describe, expect, spyOn, test, vi } from "bun:test"; import { createExpiringCache } from "../src/utils/expiring-cache"; test.each([0, -1, NaN, Infinity])("rejects invalid default TTL %p", (ttl) => { expect(() => createExpiringCache(ttl)).toThrow("positive default TTL"); }); +test("expiry is permanent after the timer fires even if the clock rolls back before the first read", () => { + vi.useFakeTimers({ now: 1_000 }); + try { + const cache = createExpiringCache(20); + cache.setWithTTL("price", 42); + vi.advanceTimersByTime(20); + const clock = spyOn(Date, "now").mockReturnValue(1_010); + try { + expect(cache.get("price")).toBeUndefined(); + expect(cache.peek("price")).toBe(42); + } finally { + clock.mockRestore(); + } + } finally { + vi.useRealTimers(); + } +}); + +test("replacing, deleting, and clearing cache entries cancel pending timers", () => { + vi.useFakeTimers({ now: 1_000 }); + try { + const cache = createExpiringCache(20); + cache.setWithTTL("a", 1); + cache.setWithTTL("a", 2, 50); + expect(vi.getTimerCount()).toBe(1); + vi.advanceTimersByTime(20); + expect(cache.get("a")).toBe(2); + cache.delete("a"); + expect(vi.getTimerCount()).toBe(0); + cache.setWithTTL("b", 1); + cache.setWithTTL("c", 2); + cache.clear(); + expect(vi.getTimerCount()).toBe(0); + } finally { + vi.useRealTimers(); + } +}); + +test("a real expiry timer does not keep the process alive", () => { + const schedule = spyOn(globalThis, "setTimeout"); + const cache = createExpiringCache(60_000); + try { + cache.setWithTTL("key", 1); + const timer = schedule.mock.results[0]?.value; + if ( + !timer || + typeof timer !== "object" || + !("hasRef" in timer) || + typeof timer.hasRef !== "function" + ) { + throw new Error("Expected a real Bun timer"); + } + expect(timer.hasRef()).toBe(false); + } finally { + cache.clear(); + schedule.mockRestore(); + } +}); + describe("ExpiringCache", () => { let now: number; let clock: ReturnType; diff --git a/tests/format-amount.test.ts b/tests/format-amount.test.ts index 407f2cce..bb5d4aaa 100644 --- a/tests/format-amount.test.ts +++ b/tests/format-amount.test.ts @@ -110,6 +110,23 @@ test.each<[string, number | bigint | string, number, FormatOptions, string]>([ ["negative decimal string truncates to negative zero", "-0.9", 2, {}, "-0"], ["positive decimal string truncates to zero", "+0.9", 2, {}, "0"], ["no token decimals", 123n, 0, { trim: false }, "123"], + ["a scale below one retains the zero integer placeholder", 25n, 0.5, {}, "0"], + ["a trailing minus is not a sign prefix", "12-", 0, {}, "NaN"], + ["a trailing plus is not a sign prefix", "12+", 0, {}, "NaN"], + [ + "fractional precision truncates display width without rounding", + 199n, + 2, + { maxFractionDigits: 1.5 }, + "1.9", + ], + [ + "an unspecified numeric precision does not erase the whole amount", + -199n, + 2, + { maxFractionDigits: NaN }, + "-1", + ], ["below the whole-unit rounding boundary", 149n, 2, { maxFractionDigits: 0 }, "1"], ["at the whole-unit rounding boundary", 150n, 2, { maxFractionDigits: 0 }, "2"], [ From e3f405b86b714aa3be6772e0edca754342964482 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 11:21:23 -0300 Subject: [PATCH 006/410] fix(config): keep integer limits positive and test fee budgets --- src/utils/constants.ts | 42 +--- src/utils/game-creation-recovery.ts | 5 +- tests/constants.dynamic.test.ts | 114 ++++++++++ tests/fee-budget.behavior.test.ts | 202 ++++++++++++++++++ ...ame-creation-recovery.proof-guards.test.ts | 54 ++++- tests/game-creation-recovery.test.ts | 107 +++++++--- 6 files changed, 459 insertions(+), 65 deletions(-) create mode 100644 tests/fee-budget.behavior.test.ts diff --git a/src/utils/constants.ts b/src/utils/constants.ts index c7ace2aa..dee84473 100644 --- a/src/utils/constants.ts +++ b/src/utils/constants.ts @@ -13,6 +13,9 @@ export let MIN_SOL_BALANCE_FOR_GAMES_LAMPORTS = FeeBudgetManager.getDefaultGameSafetyBufferLamports(); export let JIT_SWAP_FEE_BUFFER_LAMPORTS = FeeBudgetManager.getDefaultJitSwapFeeBufferLamports(); +const isPositiveFeeBudget = (value: number | undefined): value is number => + Number.isFinite(value) && (value ?? 0) > 0; + export const applyDynamicFeeBudgets = (options: { singleTransactionLamports?: number; gameSafetyBufferLamports?: number; @@ -20,27 +23,15 @@ export const applyDynamicFeeBudgets = (options: { }) => { const { singleTransactionLamports, gameSafetyBufferLamports, jitSwapBufferLamports } = options; - if ( - typeof singleTransactionLamports === "number" && - Number.isFinite(singleTransactionLamports) && - singleTransactionLamports > 0 - ) { + if (isPositiveFeeBudget(singleTransactionLamports)) { MIN_SOL_FOR_TX = singleTransactionLamports / LAMPORTS_PER_SOL; } - if ( - typeof gameSafetyBufferLamports === "number" && - Number.isFinite(gameSafetyBufferLamports) && - gameSafetyBufferLamports > 0 - ) { + if (isPositiveFeeBudget(gameSafetyBufferLamports)) { MIN_SOL_BALANCE_FOR_GAMES_LAMPORTS = gameSafetyBufferLamports; } - if ( - typeof jitSwapBufferLamports === "number" && - Number.isFinite(jitSwapBufferLamports) && - jitSwapBufferLamports > 0 - ) { + if (isPositiveFeeBudget(jitSwapBufferLamports)) { JIT_SWAP_FEE_BUFFER_LAMPORTS = jitSwapBufferLamports; } }; @@ -198,14 +189,7 @@ export const TOKENS_LIST = buildTokenList({ defaultToken: DEFAULT_TOKEN }); export const INPUT_TIMEOUT_MS = 15 * 60_000; -const formatInputTimeoutMinutes = (timeoutMs: number): string => { - const minutes = Math.round(timeoutMs / 60_000); - return Math.max(1, minutes).toString(); -}; - -export const INPUT_TIMEOUT_HINT = `⏱️ Reply to this message with your input. This will timeout in ${formatInputTimeoutMinutes( - INPUT_TIMEOUT_MS, -)} minutes`; +export const INPUT_TIMEOUT_HINT = `⏱️ Reply to this message with your input. This will timeout in ${Math.round(INPUT_TIMEOUT_MS / 60_000)} minutes`; // ================================ // GAME BUFFER AND TIMING @@ -228,12 +212,7 @@ export const applyOracleBufferTime = (bufferSeconds: number): number => { ); } - const normalized = Math.max(0, Math.round(bufferSeconds)); - - if (normalized !== GAME_EXPIRATION_BUFFER_TIME) { - GAME_EXPIRATION_BUFFER_TIME = normalized; - } - + GAME_EXPIRATION_BUFFER_TIME = Math.max(0, Math.round(bufferSeconds)); return GAME_EXPIRATION_BUFFER_TIME; }; // ================================ @@ -298,13 +277,14 @@ export function parsePositiveInteger(key: string, fallback: number): number { return fallback; } - if (parsed <= 0) { + const whole = Math.floor(parsed); + if (whole <= 0) { const clamped = Math.max(1, Math.floor(fallback)); console.warn(`[Config] ${key} must be > 0. Received ${parsed}, clamping to ${clamped}.`); return clamped; } - return Math.floor(parsed); + return whole; } export function parseNonNegativeFloat(key: string, fallback: number): number { diff --git a/src/utils/game-creation-recovery.ts b/src/utils/game-creation-recovery.ts index 51be1d32..003f86e5 100644 --- a/src/utils/game-creation-recovery.ts +++ b/src/utils/game-creation-recovery.ts @@ -115,7 +115,8 @@ export async function proveExpiredCreationAbsent( let low = 0; let high = slots.length - 1; let candidate: { slot: number; block: any } | undefined; - while (low <= high) { + const maxProbes = Math.ceil(Math.log2(slots.length + 1)); + for (let probes = 0; low <= high && probes < maxProbes; probes += 1) { const mid = Math.floor((low + high) / 2); const probe = await primary("getBlock", [slots[mid], config]); if (!probe || !Number.isSafeInteger(probe.blockHeight)) return false; @@ -124,7 +125,7 @@ export async function proveExpiredCreationAbsent( high = mid - 1; } else low = mid + 1; } - if (!candidate) return false; + if (low <= high || !candidate) return false; slot = candidate.slot; block = candidate.block; } diff --git a/tests/constants.dynamic.test.ts b/tests/constants.dynamic.test.ts index a06b2818..b66f2a9d 100644 --- a/tests/constants.dynamic.test.ts +++ b/tests/constants.dynamic.test.ts @@ -13,6 +13,7 @@ import { getStartVideoId, getCoinflipVideoId, getGiveawayVideoId, + parseEnableFeeSweeperFlag, } from "../src/utils/constants"; import { refreshDynamicFeeBudgets } from "../src/utils/fee-budget-refresh"; @@ -59,6 +60,25 @@ describe("dynamic constants", () => { expect(JIT_SWAP_FEE_BUFFER_LAMPORTS).toBe(originalJitBuffer); }); + test.each([0, -1, NaN, Infinity, undefined])( + "keeps active fee limits when the provider returns %p", + (invalid) => { + applyDynamicFeeBudgets({ + singleTransactionLamports: 1_000_000, + gameSafetyBufferLamports: 2_000_000, + jitSwapBufferLamports: 3_000_000, + }); + applyDynamicFeeBudgets({ + singleTransactionLamports: invalid, + gameSafetyBufferLamports: invalid, + jitSwapBufferLamports: invalid, + }); + expect(MIN_SOL_FOR_TX).toBe(0.001); + expect(MIN_SOL_BALANCE_FOR_GAMES_LAMPORTS).toBe(2_000_000); + expect(JIT_SWAP_FEE_BUFFER_LAMPORTS).toBe(3_000_000); + }, + ); + test("applyDynamicFeeBudgets updates globals when valid", () => { applyDynamicFeeBudgets({ singleTransactionLamports: 2_500_000, @@ -88,6 +108,23 @@ describe("dynamic constants", () => { expect(GAME_EXPIRATION_BUFFER_TIME).toBe(0); }); + test("rounding to the same buffer is silent, and only a negative value is clamped", () => { + const warn = spyOn(console, "warn").mockImplementation(() => {}); + try { + expect(applyOracleBufferTime(0)).toBe(0); + expect(applyOracleBufferTime(1.5)).toBe(2); + expect(applyOracleBufferTime(2.2)).toBe(2); + expect(GAME_EXPIRATION_BUFFER_TIME).toBe(2); + expect(warn).not.toHaveBeenCalled(); + expect(applyOracleBufferTime(-0.1)).toBe(0); + expect(warn.mock.calls).toEqual([ + ["[Config] Oracle buffer time must be >= 0. Received -0.1, clamping to 0."], + ]); + } finally { + warn.mockRestore(); + } + }); + test("parsePositiveDuration falls back for invalid env values", () => { const key = "TEST_PARSE_POSITIVE_DURATION"; try { @@ -133,6 +170,10 @@ describe("environment number parsers", () => { withEnv("1", () => expect(parsePositiveInteger(key, 6)).toBe(1)); }); + test("a fraction below one cannot turn a positive integer limit off", () => { + withEnv("0.7", () => expect(parsePositiveInteger(key, 6)).toBe(6)); + }); + test("parsePositiveInteger clamps non-positive values to a positive integer fallback", () => { withEnv("0", () => expect(parsePositiveInteger(key, 6)).toBe(6)); withEnv("-3", () => expect(parsePositiveInteger(key, 2.7)).toBe(2)); @@ -163,6 +204,79 @@ describe("environment number parsers", () => { warn.mockRestore(); } }); + + test("does not warn when an environment override was not supplied", () => { + const warn = spyOn(console, "warn").mockImplementation(() => {}); + try { + delete process.env[key]; + expect(parsePositiveDuration(key, 6)).toBe(6); + expect(parsePositiveInteger(key, 7)).toBe(7); + expect(parseNonNegativeFloat(key, 0.5)).toBe(0.5); + expect(warn).not.toHaveBeenCalled(); + } finally { + warn.mockRestore(); + } + }); +}); + +test.each<[string | undefined, boolean]>([ + [undefined, true], + [" TRUE ", true], + ["1", true], + ["1 ", true], + ["FALSE", false], + ["0", false], + ["", false], + ["yes", false], +])("fee sweeper flag %p enables it: %p", (input, expected) => { + expect(parseEnableFeeSweeperFlag(input)).toBe(expected); +}); + +test("reads the supported runtime keys and pins the timing and fee defaults", async () => { + const settings = [ + ["FEE_SWEEP_INTERVAL_MS", 12345, 3_600_000], + ["FEE_SWEEP_SOL_USD_THRESHOLD", 18, 15], + ["FEE_SWEEP_SOL_PRICE_MAX_AGE_MS", 19000, 60_000], + ["FEE_SWEEP_SOL_PRICE_MAX_DRIFT_RATIO", 0.12, 0.2], + ["TELEGRAM_USERNAME_CACHE_TTL_MS", 11000, 300_000], + ["TOKEN_DISCOVERY_COOLDOWN_MS", 12000, 120_000], + ["WALLET_RPC_CACHE_TTL_MS", 13000, 20_000], + ["TOKEN_MINT_NOT_FOUND_LOG_COOLDOWN_MS", 14000, 300_000], + ["USER_WALLET_RPC_WINDOW_MS", 15000, 30_000], + ["USER_WALLET_RPC_MAX_CALLS", 4, 6], + ["MAX_ACTIVE_GAMES_PER_CREATOR", 5, 20], + ["GAME_CREATION_RATE_LIMIT_WINDOW_MS", 16000, 60_000], + ["MAX_GAMES_PER_CREATOR_WINDOW", 8, 10], + ["GAME_MESSAGE_UPDATE_DEBOUNCE_MS", 17000, 5000], + ["JUPITER_MIN_SOL_BALANCE_LAMPORTS", 11111, 10_000_000], + ["JUPITER_GASLESS_MIN_TRADE_USD", 13, 10], + ["USER_SOL_MAX_BUFFER_LAMPORTS", 12222, 500_000], + ["PRICES_CACHE_TTL_MS", 18000, 60_000], + ["PRICES_TIMEOUT_MS", 19000, 3000], + ] as const; + const original = settings.map(([name]) => [name, process.env[name]] as const); + const modulePath = "../src/utils/constants.ts"; + try { + for (const [name] of settings) Reflect.deleteProperty(process.env, name); + const defaults: typeof import("../src/utils/constants") = await import( + `${modulePath}?route-defaults` + ); + for (const [name, , expected] of settings) expect(defaults[name]).toBe(expected); + expect(defaults.BLOCKHASH_CACHE_DURATION).toBe(10_000); + expect(defaults.TOKEN_MANAGER_KNOWN_CACHE_TTL_MS).toBe(60_000); + expect(defaults.INPUT_TIMEOUT_HINT).toContain("15 minutes"); + + for (const [name, override] of settings) process.env[name] = String(override); + const configured: typeof import("../src/utils/constants") = await import( + `${modulePath}?route-overrides` + ); + for (const [name, expected] of settings) expect(configured[name]).toBe(expected); + } finally { + for (const [name, value] of original) { + if (value === undefined) Reflect.deleteProperty(process.env, name); + else process.env[name] = value; + } + } }); test("media ids are Telegram file ids", () => { diff --git a/tests/fee-budget.behavior.test.ts b/tests/fee-budget.behavior.test.ts new file mode 100644 index 00000000..baec6e74 --- /dev/null +++ b/tests/fee-budget.behavior.test.ts @@ -0,0 +1,202 @@ +import { afterEach, beforeEach, expect, spyOn, test } from "bun:test"; +import { address, blockhash, lamports, type MicroLamports } from "@solana/kit"; +import { Connection, SystemProgram } from "#solana"; +import { FeeBudgetManager, loadFeeBudgetConfigFromEnv } from "../src/utils/fee-budget"; + +const env = { + FEE_CACHE_TTL_MS: "12", + FEE_FALLBACK_SINGLE_TX_LAMPORTS: "11", + FEE_SINGLE_TX_MULTIPLIER: "2.5", + FEE_SINGLE_TX_EXTRA_LAMPORTS: "8", + FEE_WRAP_BUFFER_MULTIPLIER: "1.25", + FEE_WRAP_BUFFER_EXTRA_LAMPORTS: "9", + FEE_WRAP_BUFFER_MIN_LAMPORTS: "19", + FEE_JIT_BUFFER_MULTIPLIER: "1.5", + FEE_JIT_BUFFER_EXTRA_LAMPORTS: "13", + FEE_JIT_BUFFER_MIN_LAMPORTS: "23", + FEE_GAME_BUFFER_MULTIPLIER: "2.5", + FEE_GAME_BUFFER_EXTRA_LAMPORTS: "17", + FEE_GAME_BUFFER_MIN_LAMPORTS: "31", + FEE_COMPUTE_UNIT_LIMIT: "7500", +}; + +const hash = blockhash("11111111111111111111111111111111"); +const connectionFor = (price = 1_250n, samples: bigint[] = []) => { + const connection = new Connection("http://localhost:8899"); + const getLatest = spyOn(connection, "getLatestBlockhash").mockResolvedValue({ + blockhash: hash, + lastValidBlockHeight: 90n, + }); + const getFee = spyOn(connection, "getFeeForMessage").mockResolvedValue({ + context: { slot: 71n }, + value: lamports(price), + }); + const getSamples = spyOn(connection, "getRecentPrioritizationFees").mockResolvedValue( + samples.map((prioritizationFee, index) => ({ + slot: BigInt(index + 1), + prioritizationFee: prioritizationFee as MicroLamports, + })), + ); + return { connection, getLatest, getFee, getSamples }; +}; + +let originalEnv: string | undefined; +beforeEach(() => { + originalEnv = process.env.NODE_ENV; + process.env.NODE_ENV = "production"; +}); + +afterEach(() => { + if (originalEnv === undefined) Reflect.deleteProperty(process.env, "NODE_ENV"); + else process.env.NODE_ENV = originalEnv; +}); + +test("reads each fee setting from its own supported environment variable", () => { + expect(loadFeeBudgetConfigFromEnv(env)).toEqual({ + cacheTtlMs: 12, + fallbackSingleTxLamports: 11, + singleTxMultiplier: 2.5, + singleTxExtraLamports: 8, + wrapBufferMultiplier: 1.25, + wrapBufferExtraLamports: 9, + wrapBufferMinLamports: 19, + jitBufferMultiplier: 1.5, + jitBufferExtraLamports: 13, + jitBufferMinLamports: 23, + gameBufferMultiplier: 2.5, + gameBufferExtraLamports: 17, + gameBufferMinLamports: 31, + computeUnitLimit: 7500, + }); +}); + +test("warns exactly when the cache TTL is below its minimum", () => { + const warn = spyOn(console, "warn").mockImplementation(() => {}); + try { + expect(loadFeeBudgetConfigFromEnv({ FEE_CACHE_TTL_MS: "1" }).cacheTtlMs).toBe(1); + expect( + loadFeeBudgetConfigFromEnv({ FEE_SINGLE_TX_EXTRA_LAMPORTS: "0" }).singleTxExtraLamports, + ).toBe(0); + expect( + loadFeeBudgetConfigFromEnv({ FEE_GAME_BUFFER_MULTIPLIER: "oops" }).gameBufferMultiplier, + ).toBe(3); + expect( + loadFeeBudgetConfigFromEnv({ FEE_JIT_BUFFER_EXTRA_LAMPORTS: "-1" }).jitBufferExtraLamports, + ).toBe(120_000); + expect(warn).not.toHaveBeenCalled(); + expect(loadFeeBudgetConfigFromEnv({ FEE_CACHE_TTL_MS: "0" }).cacheTtlMs).toBe(1); + expect(warn.mock.calls).toEqual([ + ["[FeeBudget] FEE_CACHE_TTL_MS must be >= 1. Received 0, clamping to 1."], + ]); + } finally { + warn.mockRestore(); + } +}); + +test("uses the configured default buffer formulas before any RPC calls", async () => { + const keys = Object.keys(env) as Array; + const original = keys.map((key) => [key, process.env[key]] as const); + const { connection, getLatest, getFee, getSamples } = connectionFor(); + try { + for (const key of keys) process.env[key] = env[key]; + process.env.NODE_ENV = "test"; + const modulePath = "../src/utils/fee-budget.ts"; + const { FeeBudgetManager: managerType }: typeof import("../src/utils/fee-budget") = + await import(`${modulePath}?defaults-with-env`); + const manager = managerType.createForTest(connection); + expect(manager.getCachedSingleTransactionLamports()).toBe(36); + expect(manager.getCachedWrapFeeBufferLamports()).toBe(54); + expect(manager.getCachedGameSafetyBufferLamports()).toBe(161); + expect(managerType.getDefaultJitSwapFeeBufferLamports()).toBe(67); + expect(await manager.getSingleTransactionLamports()).toBe(36); + expect(getLatest).not.toHaveBeenCalled(); + expect(getFee).not.toHaveBeenCalled(); + expect(getSamples).not.toHaveBeenCalled(); + } finally { + for (const [key, value] of original) { + if (value === undefined) delete process.env[key]; + else process.env[key] = value; + } + } +}); + +test("keeps each computed buffer distinct and combines the wrap buffer into the game budget", async () => { + const { connection, getLatest, getFee, getSamples } = connectionFor(1_250n, [2_000n]); + const manager = FeeBudgetManager.createForTest(connection, { + fallbackSingleTxLamports: 17, + singleTxMultiplier: 1.75, + singleTxExtraLamports: 7, + wrapBufferMultiplier: 1.125, + wrapBufferExtraLamports: 9, + wrapBufferMinLamports: 19, + jitBufferMultiplier: 1.25, + jitBufferExtraLamports: 13, + jitBufferMinLamports: 23, + gameBufferMultiplier: 2.125, + gameBufferExtraLamports: 17, + gameBufferMinLamports: 31, + computeUnitLimit: 2_000, + }); + expect(await manager.getGameSafetyBufferLamports()).toBe(7_173); + expect(await manager.getJitSwapFeeBufferLamports()).toBe(2_762); + expect(await manager.getWrapFeeBufferLamports()).toBe(2_483); + expect(await manager.getSingleTransactionLamports()).toBe(2_199); + expect(manager.getCachedSingleTransactionLamports()).toBe(2_199); + expect(manager.getCachedWrapFeeBufferLamports()).toBe(2_483); + expect(manager.getCachedGameSafetyBufferLamports()).toBe(7_173); + expect(getLatest.mock.calls).toEqual([["confirmed"]]); + expect(getFee).toHaveBeenCalledTimes(1); + expect(getSamples).toHaveBeenCalledTimes(1); + const message = getFee.mock.calls[0]?.[0]; + expect(message?.recentBlockhash).toBe(hash); + expect(message?.staticAccountKeys.map((key) => key.toBase58())).toEqual([ + address("11111111111111111111111111111112"), + SystemProgram.programId.toBase58(), + ]); + expect(message?.compiledInstructions).toHaveLength(1); +}); + +test("gives each RPC endpoint its own cached manager", () => { + const first = new Connection("http://localhost:8897"); + const same = new Connection("http://localhost:8897"); + const second = new Connection("http://localhost:8898"); + expect(FeeBudgetManager.getInstance(first)).toBe(FeeBudgetManager.getInstance(same)); + expect(FeeBudgetManager.getInstance(first)).not.toBe(FeeBudgetManager.getInstance(second)); +}); + +test.each([ + [ + "sorts unsorted samples and uses the 90th percentile", + Array.from({ length: 25 }, (_, i) => BigInt(25 - i) * 1_000n), + 23, + ], + ["drops zero fees before choosing between two positive samples", [9_000n, 0n, 1_000n], 9], + ["uses no priority fee for an empty sample", [], 0], +] as const)("%s", async (_label, samples, priority) => { + const { connection } = connectionFor(100n, [...samples]); + const manager = FeeBudgetManager.createForTest(connection, { + fallbackSingleTxLamports: 37, + singleTxMultiplier: 1, + singleTxExtraLamports: 0, + computeUnitLimit: 1_000, + }); + expect(await manager.getSingleTransactionLamports()).toBe(100 + priority); +}); + +test("logs a failed estimate and still applies the multiplier to the fallback base fee", async () => { + const { connection, getFee } = connectionFor(); + const outage = new Error("fee RPC down"); + getFee.mockRejectedValue(outage); + const warn = spyOn(console, "warn").mockImplementation(() => {}); + try { + const manager = FeeBudgetManager.createForTest(connection, { + fallbackSingleTxLamports: 107, + singleTxMultiplier: 1.25, + singleTxExtraLamports: 11, + }); + expect(await manager.getSingleTransactionLamports()).toBe(145); + expect(warn.mock.calls).toEqual([["Failed to estimate transaction fee:", outage]]); + } finally { + warn.mockRestore(); + } +}); diff --git a/tests/game-creation-recovery.proof-guards.test.ts b/tests/game-creation-recovery.proof-guards.test.ts index 72bc090d..d58b0cfb 100644 --- a/tests/game-creation-recovery.proof-guards.test.ts +++ b/tests/game-creation-recovery.proof-guards.test.ts @@ -1,6 +1,7 @@ -import { describe, expect, test } from "bun:test"; +import { describe, expect, mock, test } from "bun:test"; import { proveExpiredCreationAbsent, + parseCreationProofCheckpoint, type CreationProofCheckpoint, type RecoveryRpc, } from "../src/utils/game-creation-recovery"; @@ -64,6 +65,29 @@ describe("restart jump to the expiry anchor", () => { const rpc = rpcFor(blocks, 1_014, { getBlocks: slots }); expect(await proveExpiredCreationAbsent(input, rpc, rpc)).toBe(false); }); + + test("requests the intended finalized windows and accepts a one-slot candidate list", async () => { + const shifted = { ...input, blockhash: "hash10000", lastValidBlockHeight: 10013 }; + const shiftedBlocks = chain(10000, 11014); + const rpc = mock(rpcFor(shiftedBlocks, 11014, { getBlocks: [10014] })); + expect(await proveExpiredCreationAbsent(shifted, rpc, rpc)).toBe(true); + expect(rpc).toHaveBeenCalledWith("getBlocks", [8500, 11014, { commitment: "finalized" }]); + }); + + test("does not request a restart jump at the exact distance boundary", async () => { + const rpc = mock(rpcFor(chain(10, 77), 77)); + expect(await proveExpiredCreationAbsent(input, rpc, rpc)).toBe(true); + expect(rpc.mock.calls.some(([method]) => method === "getBlocks")).toBe(false); + }); + + test.each<[string, unknown]>([ + ["no candidate", [13]], + ["missing probe block", [9]], + ["past the tip", [10_000]], + ])("does not prove an absence with %s after a restart", async (_label, slots) => { + const rpc = rpcFor(blocks, 1014, { getBlocks: slots }); + expect(await proveExpiredCreationAbsent(input, rpc, rpc)).toBe(false); + }); }); describe("resuming from a saved checkpoint", () => { @@ -90,6 +114,34 @@ describe("resuming from a saved checkpoint", () => { expect(saved).toEqual([3, 4]); }); + test("can resume a checkpoint at its anchor before any blocks were checked", async () => { + const rpc = mock(rpcFor(chain(10, 14), 14)); + const atStart = { ...checkpoint, cursor: checkpoint.anchor, checkedBlocks: 0 }; + expect( + await proveExpiredCreationAbsent(input, rpc, rpc, { checkpoint: atStart, save: () => {} }), + ).toBe(true); + expect(rpc.mock.calls.some(([method]) => method === "getSlot")).toBe(false); + }); + + test.each<[string, Record]>([ + ["the wrong genesis hash", { genesis: "wrong" }], + ["a negative count", { checkedBlocks: -1 }], + ["a count beyond the scan window", { checkedBlocks: 256 }], + ["a cursor after its anchor", { cursor: { slot: 15, hash: "hash12", height: 12 } }], + ["a missing cursor", { cursor: null }], + ["a missing anchor", { anchor: null }], + ["an anchor at the expiry height", { anchor: { slot: 14, hash: "hash14", height: 13 } }], + ["an invalid slot", { anchor: { slot: "14", hash: "hash14", height: 14 } }], + ["an invalid cursor height", { cursor: { slot: 12, hash: "hash12", height: "12" } }], + ])("restarts rather than trusting a persisted checkpoint with %s", async (_label, patch) => { + const rpc = mock(rpcFor(chain(10, 14), 14)); + const saved = parseCreationProofCheckpoint(JSON.stringify({ ...checkpoint, ...patch })); + expect( + await proveExpiredCreationAbsent(input, rpc, rpc, { checkpoint: saved, save: () => {} }), + ).toBe(true); + expect(rpc).toHaveBeenCalledWith("getSlot", [{ commitment: "finalized" }]); + }); + test("a cursor block that no longer matches the saved hash is not trusted", async () => { const blocks = chain(10, 14); blocks.get(12).blockhash = "reorged-hash12"; diff --git a/tests/game-creation-recovery.test.ts b/tests/game-creation-recovery.test.ts index 73a2aeb9..5a174192 100644 --- a/tests/game-creation-recovery.test.ts +++ b/tests/game-creation-recovery.test.ts @@ -1,4 +1,4 @@ -import { describe, expect, test } from "bun:test"; +import { describe, expect, mock, test, vi } from "bun:test"; import { parseCreationProofCheckpoint, proveExpiredCreationAbsent, @@ -49,6 +49,53 @@ describe("Finalized creation absence proof", () => { const { input, rpc } = fixture(); expect(await proveExpiredCreationAbsent(input, rpc, rpc)).toBe(true); }); + + test("asks both RPCs for finalized proof with the exact anchor as the context floor", async () => { + const { input, rpc } = fixture(); + const primary = mock(rpc); + const witness = mock(rpc); + expect(await proveExpiredCreationAbsent(input, primary, witness)).toBe(true); + expect(primary).toHaveBeenCalledWith("getSlot", [{ commitment: "finalized" }]); + for (const endpoint of [primary, witness]) { + expect(endpoint).toHaveBeenCalledWith("getGenesisHash", []); + expect(endpoint).toHaveBeenCalledWith("getBlock", [ + 14, + { + commitment: "finalized", + transactionDetails: "signatures", + rewards: false, + maxSupportedTransactionVersion: 0, + }, + ]); + expect(endpoint).toHaveBeenCalledWith("isBlockhashValid", [ + input.blockhash, + { + commitment: "finalized", + minContextSlot: 14, + }, + ]); + expect(endpoint).toHaveBeenCalledWith("getSignatureStatuses", [ + [input.signature], + { searchTransactionHistory: true }, + ]); + expect(endpoint).toHaveBeenCalledWith("getAccountInfo", [ + input.gameAddress, + { + commitment: "finalized", + minContextSlot: 14, + encoding: "base64", + }, + ]); + } + }); + + test("height zero is a valid lifetime boundary", async () => { + const { input, rpc, blocks } = fixture(); + for (const [slot, block] of blocks) block.blockHeight = slot - 10; + expect(await proveExpiredCreationAbsent({ ...input, lastValidBlockHeight: 0 }, rpc, rpc)).toBe( + true, + ); + }); test("a completed and closed game cannot be charged again when status indexes miss it", async () => { const { input, rpc, blocks } = fixture(); blocks.get(12).signatures.push(input.signature); @@ -227,40 +274,36 @@ test("restart recovery locates the expiry anchor instead of scanning all later b }); test("confirmation returns while a rebroadcast read is stalled and cancels its later send", async () => { - let confirm!: () => void; - let release!: () => void; - let entered!: () => void; - const confirmation = new Promise((resolve) => { - confirm = resolve; + vi.useFakeTimers({ now: 1_000 }); + const confirmation = Promise.withResolvers(); + const stalled = Promise.withResolvers(); + const send = mock(() => {}); + const rebroadcast = mock(async (signal: AbortSignal) => { + await stalled.promise; + signal.throwIfAborted(); + send(); }); - const stalled = new Promise((resolve) => { - release = resolve; - }); - const started = new Promise((resolve) => { - entered = resolve; - }); - let sends = 0; - const result = withCreationRebroadcast( - () => confirmation, - async (signal) => { - entered(); - await stalled; - signal.throwIfAborted(); - sends++; - }, - 1, - ); - await started; - confirm(); + const result = withCreationRebroadcast(() => confirmation.promise, rebroadcast); try { - expect( - await Promise.race([result.then(() => "confirmed"), Bun.sleep(30).then(() => "blocked")]), - ).toBe("confirmed"); + vi.advanceTimersByTime(2_999); + expect(rebroadcast).not.toHaveBeenCalled(); + vi.advanceTimersByTime(1); + expect(rebroadcast).toHaveBeenCalledTimes(1); + vi.advanceTimersByTime(10_000); + expect(rebroadcast).toHaveBeenCalledTimes(1); + confirmation.resolve("confirmed"); + expect(await result).toBe("confirmed"); + stalled.resolve(); + await Promise.resolve(); + await Promise.resolve(); + expect(send).not.toHaveBeenCalled(); + expect(vi.getTimerCount()).toBe(0); } finally { - release(); + confirmation.resolve("cleanup"); + stalled.resolve(); + await result; + vi.useRealTimers(); } - await Bun.sleep(5); - expect(sends).toBe(0); }); test("retry timing follows the current transaction lifetime and keeps failed notifications prompt", () => { @@ -270,6 +313,8 @@ test("retry timing follows the current transaction lifetime and keeps failed not 3_000, ); expect(getCreationRecoveryDelay({ ...old, state: "failed" }, 1_000_000)).toBe(3_000); + expect(getCreationRecoveryDelay({ ...old, attempts: 1 }, 180_000)).toBe(3_000); + expect(getCreationRecoveryDelay({ ...old, attempts: 1 }, 180_001)).toBe(60_000); }); describe("Checkpointed absence scans", () => { From 135f520081a93c57df58bd5c8d9bc9f1e8b9d201 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 11:31:44 -0300 Subject: [PATCH 007/410] fix(bot): preserve position amounts and reject malformed identity --- src/services/buy-alerts/pool-trades.ts | 4 +- src/services/positions.ts | 5 +- src/utils/context-helpers.ts | 8 +- src/utils/errors/parser.ts | 23 ++-- src/utils/format-amount.ts | 4 +- .../buy-alerts.pool-trades-edge-cases.test.ts | 67 +++++++++-- tests/chat-database.settings-merge.test.ts | 90 +++++++++++++- tests/context-helpers.edge.test.ts | 112 +++++++++++++++++- tests/context-helpers.grace.test.ts | 82 +++++++++---- tests/errors.parser.test.ts | 69 +++++++++-- tests/faucet-database.test.ts | 104 +++++++++++++++- tests/positions.test.ts | 51 ++++++++ 12 files changed, 549 insertions(+), 70 deletions(-) diff --git a/src/services/buy-alerts/pool-trades.ts b/src/services/buy-alerts/pool-trades.ts index fe2fd8d5..21ee3d42 100644 --- a/src/services/buy-alerts/pool-trades.ts +++ b/src/services/buy-alerts/pool-trades.ts @@ -423,9 +423,9 @@ export function createPoolTradePoller(options: PoolTradePollerOptions = {}): Poo pools.map((pair) => ({ mint, pair })), ); const targetByKey = refreshPoolQueue(targets); - const cycleSize = Math.min(poolsPerCycle, poolQueue.length); - for (let index = 0; index < cycleSize; index += 1) { + // Use the initial queue only to bound the cycle. Awaited requests can change the live queue. + for (const _ of poolQueue.slice(0, poolsPerCycle)) { const queuedTarget = poolQueue.shift(); if (!queuedTarget) break; const key = targetKey(queuedTarget.mint, queuedTarget.pairAddress); diff --git a/src/services/positions.ts b/src/services/positions.ts index 4d89a6b7..6500ff70 100644 --- a/src/services/positions.ts +++ b/src/services/positions.ts @@ -5,6 +5,7 @@ import { formatRate, formatSignedPercent, formatUsdValue, + trimFixed, } from "../utils/format-amount"; import { WALLET_RPC_CACHE_TTL_MS, WSOL_MINT } from "../utils/constants"; import { @@ -490,7 +491,7 @@ function formatQuoteSpent(amount: number, ticker: string): string | null { if (!Number.isFinite(amount) || amount <= 0) { return null; } - const text = amount.toFixed(4).replace(/0+$/, "").replace(/\.$/, ""); + const text = trimFixed(amount.toFixed(4)); return `${text} ${ticker}`; } @@ -516,7 +517,7 @@ function formatExactTokenAmount(value: number, decimals: number): string { return "0"; } const places = Math.min(Math.max(0, Math.trunc(decimals)), 18); - return value.toFixed(places).replace(/0+$/, "").replace(/\.$/, "") || "0"; + return trimFixed(value.toFixed(places)); } function formatPositionBag(position: TokenPosition): string { diff --git a/src/utils/context-helpers.ts b/src/utils/context-helpers.ts index d14cc5bb..a7d052e9 100644 --- a/src/utils/context-helpers.ts +++ b/src/utils/context-helpers.ts @@ -43,13 +43,7 @@ export const getTelegramId = ( if (typeof rawId === "string") { const trimmed = rawId.trim(); - if (!trimmed) { - return fallback; - } - - const normalized = trimmed.startsWith("+") ? trimmed.slice(1) : trimmed; - // BigInt accepts a leading sign, so a string that passes this check cannot throw. - return /^-?\d+$/.test(normalized) ? BigInt(trimmed) : fallback; + return /^[+-]?\d+$/.test(trimmed) ? BigInt(trimmed) : fallback; } if (rawId == null) { diff --git a/src/utils/errors/parser.ts b/src/utils/errors/parser.ts index d6ca9c0f..5d1bc4dc 100644 --- a/src/utils/errors/parser.ts +++ b/src/utils/errors/parser.ts @@ -17,11 +17,8 @@ const TRANSACTION_EXPIRED_PATTERNS = [ "last valid block height", ]; -const SIGNATURE_PATTERNS = [ - /signature ([A-Za-z0-9]{44,})/, - /Check signature ([A-Za-z0-9]{44,})/, - /\b([A-Za-z0-9]{80,88})\b/, -]; +// This also matches the "Check signature" form. +const SIGNATURE_PATTERNS = [/signature ([A-Za-z0-9]{44,})/, /\b([A-Za-z0-9]{80,88})\b/]; export const extractLamportsInfo = ( errorMessage: string, @@ -33,14 +30,14 @@ export const extractLamportsInfo = ( export const collectErrorLogs = async ( error: unknown, - visited: Set = new Set(), + visited: Set = new Set(), connection?: Connection, ): Promise => { if (!error || typeof error !== "object") return []; if (visited.has(error)) return []; visited.add(error); - const candidate = error as any; + const candidate = error as Record; const logs: string[] = []; const pushLogs = (maybeLogs: unknown) => { try { @@ -58,7 +55,7 @@ export const collectErrorLogs = async ( const safePush = (key: string) => { try { - pushLogs(candidate?.[key]); + pushLogs(candidate[key]); } catch (logError) { console.debug(`Failed to read ${key} from error`, logError); } @@ -68,9 +65,9 @@ export const collectErrorLogs = async ( safePush("logMessages"); safePush("transactionLogs"); - if (connection && typeof candidate.getLogs === "function") { + if (connection && typeof candidate["getLogs"] === "function") { try { - const extracted = await Promise.resolve(candidate.getLogs(connection)); + const extracted = await Promise.resolve(candidate["getLogs"](connection)); pushLogs(extracted); } catch (logError) { console.debug("Failed to extract logs from error", logError); @@ -79,17 +76,17 @@ export const collectErrorLogs = async ( const nestedCandidates: unknown[] = []; try { - if (candidate?.data) nestedCandidates.push(candidate.data); + if (candidate["data"]) nestedCandidates.push(candidate["data"]); } catch (nestedError) { console.debug("Failed to read data from error", nestedError); } try { - if (candidate?.error) nestedCandidates.push(candidate.error); + if (candidate["error"]) nestedCandidates.push(candidate["error"]); } catch (nestedError) { console.debug("Failed to read nested error", nestedError); } try { - if (candidate?.cause) nestedCandidates.push(candidate.cause); + if (candidate["cause"]) nestedCandidates.push(candidate["cause"]); } catch (nestedError) { console.debug("Failed to read error cause", nestedError); } diff --git a/src/utils/format-amount.ts b/src/utils/format-amount.ts index 40bdde89..30d2c321 100644 --- a/src/utils/format-amount.ts +++ b/src/utils/format-amount.ts @@ -185,8 +185,8 @@ export function formatUsdValue(value: number, options: FormatUsdValueOptions = { } export function trimFixed(value: string): string { - // toFixed uses exponential notation for large numbers. Do not trim its exponent. - return value.includes("e") ? value : value.replace(/0+$/, "").replace(/\.$/, ""); + // Trim only a decimal fraction. Integer and exponent digits are significant. + return value.replace(/(\.\d*?)0+$/, "$1").replace(/\.$/, ""); } export function formatSignedPercent(value: number): string { diff --git a/tests/buy-alerts.pool-trades-edge-cases.test.ts b/tests/buy-alerts.pool-trades-edge-cases.test.ts index cae46d90..f5a2d783 100644 --- a/tests/buy-alerts.pool-trades-edge-cases.test.ts +++ b/tests/buy-alerts.pool-trades-edge-cases.test.ts @@ -1,4 +1,4 @@ -import { afterEach, describe, expect, spyOn, test } from "bun:test"; +import { afterEach, describe, expect, spyOn, test, vi } from "bun:test"; import { createPoolTradePoller, parseGeckoPoolTrade, @@ -178,23 +178,72 @@ describe("pool trade poller", () => { } }); - test("waits with the default timer between pool requests", async () => { + test.each([ + [5, 5], + [undefined, 10_000], + ] as const)( + "waits with the default timer using request interval %p", + async (configured, expectedDelay) => { + vi.useFakeTimers(); + const timer = spyOn(globalThis, "setTimeout"); + const settle = async () => { + for (let step = 0; step < 25; step += 1) await Promise.resolve(); + }; + const fetched: string[] = []; + let clock = 0; + const poller = track( + createPoolTradePoller({ + intervalMs: 60_000, + minRequestIntervalMs: configured, + poolsPerCycle: 2, + now: () => clock, + fetchPoolStats: async () => [pool("pair-a"), pool("pair-b")], + fetchTrades: async (pairAddress) => { + fetched.push(pairAddress); + return { data: [] }; + }, + }), + ); + try { + poller.setMints([mint]); + await settle(); + expect(fetched).toEqual(["pair-a"]); + expect(timer.mock.calls.map((call) => call[1])).toEqual([expectedDelay]); + vi.advanceTimersByTime(expectedDelay - 1); + await settle(); + expect(fetched).toEqual(["pair-a"]); + clock = expectedDelay; + vi.advanceTimersByTime(1); + await settle(); + expect(fetched).toEqual(["pair-a", "pair-b"]); + } finally { + poller.stop(); + timer.mockRestore(); + vi.useRealTimers(); + } + }, + ); + + test("preserves queue order when a mint is removed within a poll", async () => { const fetched: string[] = []; - const poller = track( + const poller: PoolTradePoller = track( createPoolTradePoller({ - intervalMs: 60_000, - minRequestIntervalMs: 5, - poolsPerCycle: 2, - fetchPoolStats: async () => [pool("pair-a"), pool("pair-b")], + ...base, + poolsPerCycle: Infinity, + fetchPoolStats: async (requested) => + requested === mint ? [pool("first"), pool("second")] : [pool("other")], fetchTrades: async (pairAddress) => { fetched.push(pairAddress); + if (pairAddress === "first") poller.setMints([otherMint]); + // Bound the fixture if a mutant stops making progress through the queue. + if (fetched.length >= 4) poller.setMints([]); return { data: [] }; }, }), ); - poller.setMints([mint]); + poller.setMints([mint, otherMint]); await poller.pollNow(); - expect(fetched.slice(0, 2)).toEqual(["pair-a", "pair-b"]); + expect(fetched).toEqual(["first", "other", "other", "other"]); }); test("a mint removed while waiting for a request slot is not fetched", async () => { diff --git a/tests/chat-database.settings-merge.test.ts b/tests/chat-database.settings-merge.test.ts index 211b3474..8613655d 100644 --- a/tests/chat-database.settings-merge.test.ts +++ b/tests/chat-database.settings-merge.test.ts @@ -1,6 +1,7 @@ import { afterEach, beforeEach, describe, expect, test } from "bun:test"; +import { Database } from "bun:sqlite"; import { ChatDatabase } from "../src/utils/chat-database"; -import { resetTestDatabase } from "./helpers/database"; +import { getTestDatabasePath, resetTestDatabase } from "./helpers/database"; beforeEach(() => { resetTestDatabase("chat-settings.sqlite"); @@ -36,4 +37,91 @@ describe("ChatDatabase.upsertChatGameSettings merging", () => { expect(merged.global_public_game_feed).toBeNull(); expect(db.getGlobalPublicGameFeedChatIds()).toEqual([]); }); + + test("preserves zero and omitted fields and clears only explicitly null fields", () => { + const db = ChatDatabase.getInstance(); + db.upsertChatGameSettings(-2004, { + giveaway_default_privacy: "private", + join_notifications_per_minute: 0, + set_by_telegram_id: "9007199254740993", + }); + const expected = { + giveaway_default_privacy: "private", + join_notifications_per_minute: 0, + set_by_telegram_id: "9007199254740993", + }; + expect(db.upsertChatGameSettings(-2004, { timeout_seconds: 30 })).toMatchObject(expected); + expect(db.getChatGameSettings(-2004)).toMatchObject(expected); + db.upsertChatGameSettings(-2004, { giveaway_default_privacy: null, set_by_telegram_id: null }); + expect(db.getChatGameSettings(-2004)).toMatchObject({ + giveaway_default_privacy: null, + join_notifications_per_minute: 0, + set_by_telegram_id: null, + timeout_seconds: 30, + }); + }); +}); + +describe("ChatDatabase buy alert settings", () => { + test.each(["photo", "video", "animation"] as const)( + "keeps existing %s and numeric settings when a patch omits them", + (type) => { + const db = ChatDatabase.getInstance(); + const saved = { + token_mint: "mint", + token_ticker: "TMB", + min_sol_lamports: 0, + media_file_id: "telegram-file", + media_type: type, + set_by_telegram_id: "88", + }; + expect(db.upsertChatBuyAlerts(-3042, saved)).toMatchObject({ ...saved, enabled: false }); + expect(db.getEnabledChatBuyAlerts()).toEqual([]); + expect(db.upsertChatBuyAlerts(-3042, { enabled: true })).toMatchObject({ + ...saved, + enabled: true, + }); + expect(db.getChatBuyAlerts(-3042)).toMatchObject({ ...saved, enabled: true }); + expect(db.getEnabledChatBuyAlerts()).toEqual([ + expect.objectContaining({ ...saved, chat_id: -3042, enabled: true }), + ]); + const cleared = { media_file_id: null, media_type: null, set_by_telegram_id: null }; + db.upsertChatBuyAlerts(-3042, cleared); + expect(db.getChatBuyAlerts(-3042)).toMatchObject({ + ...cleared, + enabled: true, + token_ticker: "TMB", + }); + }, + ); + + test("migrates old alert rows with no media columns", () => { + ChatDatabase.getInstance(); + ChatDatabase.resetForTesting(); + using legacyDb = new Database(getTestDatabasePath("chat-settings.sqlite")); + legacyDb.run("ALTER TABLE chat_buy_alerts DROP COLUMN media_file_id"); + legacyDb.run("ALTER TABLE chat_buy_alerts DROP COLUMN media_type"); + legacyDb.run( + `INSERT INTO chat_buy_alerts (chat_id, enabled, token_mint, token_ticker, updated_at) + VALUES (-7733, 1, 'legacy', 'OLD', 123)`, + ); + + const migrated = ChatDatabase.getInstance(); + expect(migrated.getChatBuyAlerts(-7733)).toMatchObject({ + enabled: true, + token_mint: "legacy", + token_ticker: "OLD", + media_type: null, + media_file_id: null, + }); + migrated.upsertChatBuyAlerts(-7733, { media_type: "video", media_file_id: "new-video" }); + expect(migrated.getChatBuyAlerts(-7733)).toMatchObject({ + enabled: true, + token_mint: "legacy", + media_type: "video", + media_file_id: "new-video", + }); + legacyDb.run("UPDATE chat_buy_alerts SET media_type = 'unknown' WHERE chat_id = -7733"); + expect(migrated.getChatBuyAlerts(-7733)?.media_type).toBeNull(); + }); }); diff --git a/tests/context-helpers.edge.test.ts b/tests/context-helpers.edge.test.ts index 1c7d0b68..231fb34d 100644 --- a/tests/context-helpers.edge.test.ts +++ b/tests/context-helpers.edge.test.ts @@ -1,15 +1,19 @@ import { afterEach, beforeEach, describe, expect, mock, spyOn, test } from "bun:test"; import { + MissingTelegramIdError, MISSING_TELEGRAM_ID_MESSAGE, + categorizeError, containsBalanceInfo, createMessageEditAdapter, getRequiredTelegramIdForContext, getTelegramId, getTelegramIdString, + requireTelegramId, resolveTelegramIdOrRespond, safeAnswerCallbackQuery, } from "../src/utils/context-helpers"; import { __test_resetGlobals } from "../src/utils/telegram-rate-limiter"; +import { makeTestTelegramContext } from "./helpers/grammy"; let warnSpy: ReturnType; let errorSpy: ReturnType; @@ -41,9 +45,64 @@ describe("getTelegramId unusual inputs", () => { expect(getTelegramIdString({ from: { id: 77 } })).toBe("77"); expect(getTelegramIdString({})).toBeUndefined(); }); + + test.each(["+-42", "-+42", "++42", "4x2", "id42", "42id", "0x2a"])( + "falls back for a malformed decimal ID %s", + (id) => { + expect(getTelegramId({ from: { id } }, 73n)).toBe(73n); + }, + ); + + test.each([ + [" +9007199254740993 ", 9_007_199_254_740_993n], + ["-42", -42n], + ["-0", 0n], + ["00042", 42n], + [false, 0n], + [null, 73n], + ] as const)("keeps decimal and coercible ID %p as %p", (id, expected) => { + expect(getTelegramId({ from: { id } }, 73n)).toBe(expected); + }); }); describe("missing identity notifications", () => { + test("names the failed operation when no identity is available", () => { + expect(new MissingTelegramIdError()).toMatchObject({ + name: "MissingTelegramIdError", + message: "Missing Telegram user id", + }); + expect(() => requireTelegramId(null)).toThrow("Missing Telegram user id for operation"); + expect(() => requireTelegramId(null, "withdrawal")).toThrow( + "Missing Telegram user id for withdrawal", + ); + }); + + test("targets the triggering message and sends nothing for absent context", async () => { + const ctx = makeTestTelegramContext({ + update_id: 1, + message: { + chat: { type: "private", id: 71, first_name: "A" }, + from: { id: 0, is_bot: false, first_name: "A" }, + message_id: 25, + date: 1, + }, + }); + const reply = spyOn(ctx.api, "sendMessage").mockResolvedValue({ + chat: { type: "private", id: 71, first_name: "A" }, + message_id: 26, + date: 1, + text: "notice", + }); + expect(await getRequiredTelegramIdForContext(ctx, "withdrawal")).toBeNull(); + expect(reply.mock.calls).toEqual([ + [71, MISSING_TELEGRAM_ID_MESSAGE, { reply_to_message_id: 25 }, undefined], + ]); + expect( + await getRequiredTelegramIdForContext(undefined as unknown as typeof ctx, "retry"), + ).toBeNull(); + expect(reply).toHaveBeenCalledTimes(1); + expect(errorSpy).not.toHaveBeenCalled(); + }); test("falls back to the Bot API when the context cannot reply", async () => { const sendMessage = mock(async () => ({})); const ctx = { chat: { id: -5 }, message: { message_id: 8 }, api: { sendMessage } } as any; @@ -109,10 +168,12 @@ describe("missing identity notifications", () => { test("resolveTelegramIdOrRespond uses a custom log message", async () => { const ctx = { callbackQuery: { id: "cb" }, answerCallbackQuery: async () => true } as any; + const onMissing = mock((_message: string) => {}); - await resolveTelegramIdOrRespond(ctx, "x", { logMessage: "custom", onMissing: () => {} }); + await resolveTelegramIdOrRespond(ctx, "x", { logMessage: "custom", onMissing }); expect(warnSpy).toHaveBeenCalledWith("custom"); + expect(onMissing.mock.calls).toEqual([[MISSING_TELEGRAM_ID_MESSAGE]]); }); test("resolveTelegramIdOrRespond returns the id when present", async () => { @@ -139,6 +200,32 @@ describe("containsBalanceInfo", () => { test("rejects non-string input", () => { expect(containsBalanceInfo(undefined as any)).toBe(false); }); + + test.each([ + ["single digit", "you have 1 sol"], + ["singular lamport", "you have 1 lamport"], + ["singular coin", "you have 1 coin"], + ["singular token", "you have 1 token"], + ["unit separated by several spaces", "you have 12.25 sol"], + ["upper-case ticker with extra spaces", "You have 6 BONK"], + ["need qualifier with extra spaces", "You have 1 but need 2"], + ["not enough prefix with extra spaces", "Not enough: you have 1"], + ])("recognizes %s", (_label, text) => { + expect(containsBalanceInfo(text)).toBe(true); + }); +}); + +test("categorizes a missing error or an error supplied as a string", () => { + expect(categorizeError(undefined)).toEqual({ + message: "Unknown error", + code: undefined, + isAccountNotFound: false, + }); + expect(categorizeError("could not find account")).toEqual({ + message: "could not find account", + code: undefined, + isAccountNotFound: true, + }); }); describe("createMessageEditAdapter", () => { @@ -197,4 +284,27 @@ describe("safeAnswerCallbackQuery error handling", () => { expect(warnSpy).toHaveBeenCalledWith("Unable to answer callback query - invalid context"); }); + + test("an empty answer does not send a blank toast", async () => { + const answerCallbackQuery = mock(async () => true); + await safeAnswerCallbackQuery({ answerCallbackQuery }, ""); + expect(answerCallbackQuery.mock.calls).toEqual([[]]); + expect(warnSpy).not.toHaveBeenCalled(); + }); + + test("logs the distinct missing callback-id case without recording an error", async () => { + await safeAnswerCallbackQuery(undefined); + expect(warnSpy.mock.calls).toEqual([["Unable to answer callback query - missing callback id"]]); + expect(errorSpy).not.toHaveBeenCalled(); + }); + + test.each([ + ["stale callback, no text", "query is too old", undefined, ""], + ["stale callback, exact limit", "query is too old", "x".repeat(50), "x".repeat(50)], + ["stale callback, truncated text", "query is too old", "x".repeat(51), `${"x".repeat(50)}...`], + ["other 400, exact limit", "Bad request", "x".repeat(50), "x".repeat(50)], + ])("logs the expected preview for %s", async (_label, description, input, preview) => { + await safeAnswerCallbackQuery(failing({ error_code: 400, description }), input); + expect(warnSpy.mock.calls).toEqual([[`⚠️ Callback query timeout: ${preview}`]]); + }); }); diff --git a/tests/context-helpers.grace.test.ts b/tests/context-helpers.grace.test.ts index 8fdd0496..6fd31419 100644 --- a/tests/context-helpers.grace.test.ts +++ b/tests/context-helpers.grace.test.ts @@ -1,4 +1,4 @@ -import { describe, expect, spyOn, test } from "bun:test"; +import { afterEach, beforeEach, describe, expect, spyOn, test, vi } from "bun:test"; import { CALLBACK_ANSWER_GRACE_MS, answerCallbackWithGrace, @@ -8,8 +8,6 @@ import { } from "../src/utils/context-helpers"; import { telegramRefusal } from "./helpers/telegram-errors"; -const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)); - const makeCtx = () => { const answers: Array = []; const replies: Array<[string, any]> = []; @@ -27,8 +25,35 @@ const makeCtx = () => { }; describe("answerCallbackWithGrace", () => { + beforeEach(() => vi.useFakeTimers()); + afterEach(() => vi.useRealTimers()); + test("uses a short default grace period", () => { - expect(CALLBACK_ANSWER_GRACE_MS).toBeLessThanOrEqual(500); + expect(CALLBACK_ANSWER_GRACE_MS).toBe(350); + }); + + test("answers at the default deadline and drops missing or empty late text", async () => { + const { ctx, answers } = makeCtx(); + const { promise, resolve } = Promise.withResolvers(); + const late: string[] = []; + const running = answerCallbackWithGrace(ctx, () => promise, { + pendingText: "Waiting", + onLateAnswer: (text) => { + late.push(text); + }, + }); + vi.advanceTimersByTime(349); + expect(answers).toEqual([]); + vi.advanceTimersByTime(1); + expect(answers).toEqual(["Waiting"]); + await safeAnswerCallbackQuery(ctx, ""); + await safeAnswerCallbackQuery(ctx); + expect(late).toEqual([]); + await safeAnswerCallbackQuery(ctx, "Done"); + resolve(); + await running; + expect(answers).toEqual(["Waiting"]); + expect(late).toEqual(["Done"]); }); test("fast work answers the callback itself, once", async () => { @@ -41,7 +66,7 @@ describe("answerCallbackWithGrace", () => { }, { graceMs: 50, pendingText: "⏳ Joining…" }, ); - await sleep(80); + vi.advanceTimersByTime(80); expect(result).toBe(42); expect(answers).toEqual(["✅ Joined! (2/4)"]); }); @@ -49,6 +74,7 @@ describe("answerCallbackWithGrace", () => { test("fast work that never answers gets a silent answer", async () => { const { ctx, answers } = makeCtx(); await answerCallbackWithGrace(ctx, async () => {}, { graceMs: 50 }); + vi.advanceTimersByTime(80); expect(answers).toEqual([undefined]); }); @@ -58,7 +84,7 @@ describe("answerCallbackWithGrace", () => { await answerCallbackWithGrace( ctx, async () => { - await sleep(40); + vi.advanceTimersByTime(40); await safeAnswerCallbackQuery(ctx, "Failed to join game. Please try again."); await safeAnswerCallbackQuery(ctx); }, @@ -79,7 +105,7 @@ describe("answerCallbackWithGrace", () => { await answerCallbackWithGrace( ctx, async () => { - await sleep(30); + vi.advanceTimersByTime(30); await safeAnswerCallbackQuery(ctx, "Refreshed!"); }, { graceMs: 5 }, @@ -89,20 +115,27 @@ describe("answerCallbackWithGrace", () => { test("late answer fallback failures are contained", async () => { const { ctx, answers } = makeCtx(); - await answerCallbackWithGrace( - ctx, - async () => { - await sleep(30); - await safeAnswerCallbackQuery(ctx, "❌ boom"); - }, - { - graceMs: 5, - onLateAnswer: () => { - throw new Error("reply failed"); + const error = new Error("reply failed"); + const warn = spyOn(console, "warn").mockImplementation(() => {}); + try { + await answerCallbackWithGrace( + ctx, + async () => { + vi.advanceTimersByTime(30); + await safeAnswerCallbackQuery(ctx, "❌ boom"); }, - }, - ); - expect(answers).toEqual([undefined]); + { + graceMs: 5, + onLateAnswer: () => { + throw error; + }, + }, + ); + expect(answers).toEqual([undefined]); + expect(warn.mock.calls).toEqual([["Failed to deliver late callback answer:", error]]); + } finally { + warn.mockRestore(); + } }); test("errors propagate and leave the answer to the caller", async () => { @@ -116,8 +149,9 @@ describe("answerCallbackWithGrace", () => { { graceMs: 50 }, ), ).rejects.toThrow("rpc down"); + vi.advanceTimersByTime(80); + expect(answers).toEqual([]); await safeAnswerCallbackQuery(ctx, "❌ Error"); - await sleep(80); expect(answers).toEqual(["❌ Error"]); }); @@ -129,7 +163,7 @@ describe("answerCallbackWithGrace", () => { answerCallbackWithGrace( ctx, async () => { - await sleep(30); + vi.advanceTimersByTime(30); }, { graceMs: 1, pendingText: "inner" }, ), @@ -137,6 +171,10 @@ describe("answerCallbackWithGrace", () => { ); expect(answers).toEqual(["outer"]); }); + + test("runs work even when no callback context exists", async () => { + expect(await answerCallbackWithGrace(undefined, async () => "done")).toBe("done"); + }); }); describe("replyToCallbackMessage", () => { diff --git a/tests/errors.parser.test.ts b/tests/errors.parser.test.ts index d6d0b0e4..e018c838 100644 --- a/tests/errors.parser.test.ts +++ b/tests/errors.parser.test.ts @@ -1,4 +1,5 @@ import { afterEach, beforeEach, describe, expect, spyOn, test } from "bun:test"; +import { Connection } from "#solana"; import { collectErrorLogs, extractLamportsInfo, @@ -8,7 +9,7 @@ import { isTransactionTimeoutError, } from "../src/utils/errors/parser"; -const connection = {} as any; +const connection = new Connection("http://localhost:8899"); const throwingGetter = (key: string, message = `cannot read ${key}`) => Object.defineProperty({}, key, { enumerable: true, @@ -25,27 +26,51 @@ afterEach(() => debugSpy.mockRestore()); describe("collectErrorLogs", () => { test("ignores non-object errors", async () => { - expect(await collectErrorLogs(null)).toEqual([]); + expect(await collectErrorLogs(null, new Set(), connection)).toEqual([]); + expect(await collectErrorLogs(undefined, new Set(), connection)).toEqual([]); expect(await collectErrorLogs("insufficient lamports 1, need 2")).toEqual([]); + const notAnError = Object.assign(() => {}, { logs: ["not an object"] }); + expect(await collectErrorLogs(notAnError)).toEqual([]); }); test("collects string logs from every known field and skips other entries", async () => { const error = { logs: ["a", 1, "b"], logMessages: ["c"], - transactionLogs: "not an array", + transactionLogs: [false, "d"], }; - expect(await collectErrorLogs(error)).toEqual(["a", "b", "c"]); + expect(await collectErrorLogs(error)).toEqual(["a", "b", "c", "d"]); }); test("walks data, error and cause chains without looping on cycles", async () => { - const root: any = { logs: ["root"] }; - root.data = { logs: ["data"] }; - root.error = { logs: ["error"], cause: root }; - root.cause = { logs: ["cause"] }; + let rootReads = 0; + const shared = { logs: ["cause"] }; + const nested = { logs: ["error"], cause: undefined as unknown }; + const root = { + logs: ["root"], + data: { logs: ["data"], cause: shared }, + get error() { + // Bound the test even when a mutant removes the cycle guard. + if (rootReads > 1) throw new Error("would follow the cycle again"); + return nested; + }, + cause: shared, + getLogs: () => { + rootReads += 1; + return []; + }, + }; + nested.cause = root; - expect(await collectErrorLogs(root)).toEqual(["root", "data", "error", "cause"]); + expect(await collectErrorLogs(root, new Set(), connection)).toEqual([ + "root", + "data", + "cause", + "error", + ]); + expect(rootReads).toBe(1); + expect(debugSpy).not.toHaveBeenCalled(); }); test("asks the error for logs only when a connection is supplied", async () => { @@ -100,6 +125,26 @@ describe("collectErrorLogs", () => { expect(debugSpy).toHaveBeenCalledWith("Failed to process extracted logs", expect.any(Error)); }); + test("does not read an empty nested field twice", async () => { + const readFields: string[] = []; + const error = { + get data() { + readFields.push("data"); + return null; + }, + get cause() { + readFields.push("cause"); + return false; + }, + get error() { + readFields.push("error"); + return ""; + }, + }; + expect(await collectErrorLogs(error)).toEqual([]); + expect(readFields).toEqual(["data", "error", "cause"]); + }); + test.each([ ["data", "Failed to read data from error"], ["error", "Failed to read nested error"], @@ -161,6 +206,12 @@ describe("message helpers", () => { const bare = "A".repeat(86); expect(extractSignature(`failed: signature ${sig}`)).toBe(sig); + expect(extractSignature(`failed: Check signature ${sig}, or inspect ${bare}`)).toBe(sig); + expect(extractSignature(`failed: Check signature ${"5".repeat(43)}, or inspect ${bare}`)).toBe( + bare, + ); + expect(extractSignature(`failed: Check signature ${"-".repeat(44)}`)).toBeNull(); + expect(extractSignature(`bare over the limit: ${"A".repeat(89)}`)).toBeNull(); expect(extractSignature(`see ${bare} for details`)).toBe(bare); expect(extractSignature("short 123")).toBeNull(); }); diff --git a/tests/faucet-database.test.ts b/tests/faucet-database.test.ts index a9fc1e03..8a2169e2 100644 --- a/tests/faucet-database.test.ts +++ b/tests/faucet-database.test.ts @@ -1,5 +1,5 @@ import { afterEach, beforeEach, describe, expect, test } from "bun:test"; -import { FaucetDatabase } from "../src/utils/faucet-database"; +import { FAUCET_SUBMITTED_CLAIM_TIMEOUT_MS, FaucetDatabase } from "../src/utils/faucet-database"; import { resetTestDatabase } from "./helpers/database"; let db: FaucetDatabase; @@ -137,7 +137,15 @@ describe("FaucetDatabase", () => { db.reserveClaim(faucet.id, 1n, 1_000); db.recordClaimSignature(faucet.id, 1n, "missing-signature", 2_000); - expect(db.releaseUnknownSubmittedClaims(302_001, 300_000)).toBe(0); + expect(FAUCET_SUBMITTED_CLAIM_TIMEOUT_MS).toBe(300_000); + expect(db.releaseUnknownSubmittedClaims(302_001, FAUCET_SUBMITTED_CLAIM_TIMEOUT_MS)).toBe(0); + expect(db.getSubmittedClaims()).toEqual([ + expect.objectContaining({ + faucet_id: faucet.id, + telegram_id: "1", + transaction_signature: "missing-signature", + }), + ]); expect(db.getClaim(faucet.id, 1n)).toMatchObject({ status: "submitted", transaction_signature: "missing-signature", @@ -148,6 +156,98 @@ describe("FaucetDatabase", () => { expect(db.reserveClaim(faucet.id, 2n, 302_004)).toMatchObject({ ok: true }); }); + test("reports missing and inactive faucets without modifying a claim", () => { + expect(db.getProgress(9999)).toBeNull(); + expect(db.reserveClaim(9999, 1n, 2_000)).toEqual({ ok: false, reason: "not_found" }); + expect(db.cancelFaucet(9999, 10n)).toEqual({ ok: false, reason: "not_found" }); + const faucet = createFaucet(); + db.markFaucetEmpty(faucet.id); + const empty = { ...faucet, status: "empty" as const }; + expect(db.reserveClaim(faucet.id, 1n, 2_000)).toEqual({ + ok: false, + reason: "inactive", + faucet: empty, + }); + expect(db.cancelFaucet(faucet.id, 10n)).toEqual({ + ok: false, + reason: "inactive", + faucet: empty, + }); + expect(db.getClaim(faucet.id, 1n)).toBeNull(); + }); + + test("counts processing and submitted claims without treating either as paid", () => { + const faucet = createFaucet({ maxClaims: 3 }); + expect(db.getProgress(faucet.id)).toEqual({ + faucet, + paidClaims: 0, + processingClaims: 0, + collectors: [], + }); + db.reserveClaim(faucet.id, 2n, 2_000, "2"); + db.reserveClaim(faucet.id, 1n, 2_000, ""); + db.completeClaim(faucet.id, 2n, "paid", 2_001); + db.recordClaimSignature(faucet.id, 1n, "pending", 2_001); + db.reserveClaim(faucet.id, 3n, 2_002); + expect(db.getProgress(faucet.id)).toEqual({ + faucet, + paidClaims: 1, + processingClaims: 2, + collectors: [{ telegramId: "2", displayName: "2" }], + }); + expect(db.getClaim(faucet.id, 1n)?.claimant_display_name).toBe(""); + expect(() => db.recordClaimSignature(faucet.id, 1n, "second", 2_002)).toThrow( + "Faucet claim is no longer processing", + ); + expect(db.getClaim(faucet.id, 1n)?.transaction_signature).toBe("pending"); + expect(db.reserveClaim(faucet.id, 1n, 2_003)).toEqual({ + ok: false, + reason: "processing", + faucet, + }); + }); + + test("retries a notification at its queued deadline and stops after a terminal failure", () => { + const faucet = createFaucet({ maxClaims: 1 }); + db.reserveClaim(faucet.id, 1n, 2_000); + db.completeClaim(faucet.id, 1n, "sig", 2_001); + expect(db.getFaucet(faucet.id)?.status).toBe("completed"); + db.recordNotificationFailure(faucet.id, 1n, "x".repeat(501), 3_000); + expect(db.getPendingNotifications(2_999)).toEqual([]); + expect(db.getPendingNotifications(3_000)).toEqual([ + expect.objectContaining({ + notification_status: "pending", + notification_error: "x".repeat(500), + notification_attempts: 1, + notification_next_attempt_at: 3_000, + }), + ]); + db.recordNotificationFailure(faucet.id, 1n, "permanent", null); + expect(db.getPendingNotifications(10_000)).toEqual([]); + expect(db.getClaim(faucet.id, 1n)).toMatchObject({ + status: "paid", + notification_status: "failed", + notification_error: "permanent", + notification_attempts: 2, + notification_next_attempt_at: null, + }); + db.markNotificationSent(faucet.id, 1n); + expect(db.getClaim(faucet.id, 1n)?.notification_status).toBe("failed"); + }); + + test("records only the first 500 characters of a failed transfer", () => { + const faucet = createFaucet(); + db.reserveClaim(faucet.id, 1n, 2_000); + db.failClaim(faucet.id, 1n, "x".repeat(500) + "!", 2_001); + expect(db.getClaim(faucet.id, 1n)).toMatchObject({ + status: "failed", + last_error: "x".repeat(500), + updated_at: 2_001, + }); + expect(db.getProgress(faucet.id)?.processingClaims).toBe(0); + expect(db.expireDue(9_999)).toEqual([]); + }); + test("does not release a stale processing claim protected by an active operation", () => { const faucet = createFaucet({ maxClaims: 1 }); db.reserveClaim(faucet.id, 1n, 1_000); diff --git a/tests/positions.test.ts b/tests/positions.test.ts index f4224e47..d6ebdcc6 100644 --- a/tests/positions.test.ts +++ b/tests/positions.test.ts @@ -787,6 +787,7 @@ test("format helpers match the wallet PNL style", () => { expect(formatSolSpent(0.42)).toBe("0.42 SOL"); expect(formatPositionSpent({ solSpent: 0.2, usdcSpent: 10 })).toBe("0.2 SOL + 10 USDC"); expect(formatPositionSpent({ usdcSpent: 12 })).toBe("12 USDC"); + expect(formatPositionSpent({ usdcSpent: 1.23e30 })).toBe("1.23e+30 USDC"); expect(formatPositionSpent({})).toBe("-"); }); @@ -1123,6 +1124,56 @@ test("position cards cope with unusual balances and decimals", () => { ).toContain("Balance: 0"); }); +test.each([ + ["whole amount without raw units", { balance: 120, decimals: 0, rawBalance: undefined }, "120"], + [ + "rounded whole amount without raw units", + { balance: 119.9, decimals: 0, rawBalance: undefined }, + "120", + ], + ["zero", { balance: 0, decimals: 0, rawBalance: undefined }, "0"], + ["fractional trailing zeros", { balance: 12.25, decimals: 4, rawBalance: undefined }, "12.25"], + [ + "huge amount without raw units", + { balance: 1.23e30, decimals: 6, rawBalance: undefined }, + "1.23e+30", + ], + ["exact raw units with spaces", { balance: 12, decimals: 0, rawBalance: " 1200 " }, "1200"], + ["negative raw units", { balance: -5, decimals: 2, rawBalance: "-454" }, "-4.54"], + ["partially numeric raw units", { balance: 6.7, decimals: 2, rawBalance: "89units" }, "6.7"], + ["nondecimal prefix in raw units", { balance: 6.7, decimals: 2, rawBalance: "units89" }, "6.7"], + ["negative decimal precision", { balance: 1.25, decimals: -1, rawBalance: "50" }, "1.25"], +] as const)("position card copies the expected value for %s", (_label, amounts, expected) => { + const text = formatPositionMessage(card({ ...amounts, priceUsd: null })); + expect(text.split("\n").find((line) => line.startsWith("Balance:"))).toBe( + `Balance: ${expected}`, + ); +}); + +test("position scope keeps whole tokens in the tracked amount", () => { + expect( + formatUnrealizedScopeLine( + card({ balance: 150, trackedBalance: 120, decimals: 0, priceUsd: null }), + ), + ).toBe("on 120"); +}); + +test("position scope suppresses the USD estimate for zero and only applies below 99 percent tracked", () => { + expect( + formatUnrealizedScopeLine(card({ balance: 100, trackedBalance: 99, priceUsd: 2 })), + ).toBeNull(); + expect(formatUnrealizedScopeLine(card({ balance: 100, trackedBalance: 98.9, priceUsd: 0 }))).toBe( + "on 98.9", + ); +}); + +test("multipage positions have the exact heading and card spacing", () => { + const [a, b] = [card({ ticker: "AAA" }), card({ ticker: "BBB" })]; + expect(formatPositionsPage([a, b], { pageCount: 2 })).toBe( + ["📊 Positions (1/2)", "", formatPositionMessage(a), "", formatPositionMessage(b)].join("\n"), + ); +}); + test("formatUnrealizedScopeLine ignores invalid tracked balances", () => { expect(formatUnrealizedScopeLine(card({ trackedBalance: 0 }))).toBeNull(); expect(formatUnrealizedScopeLine(card({ trackedBalance: Number.NaN }))).toBeNull(); From 2ce0383b8f5e1f7ea5205f927f40cb9c504cfae2 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 11:37:24 -0300 Subject: [PATCH 008/410] fix(finance): keep reports finite when prices are unavailable --- src/services/finance-report.ts | 3 +- tests/finance-ledger.test.ts | 109 ++++++++++++++++- tests/finance-report.test.ts | 163 ++++++++++++++++++++++++- tests/game-creation-recovery.test.ts | 83 +++++++------ tests/game-setup.module.test.ts | 101 +++++++++++++++ tests/wallet-positions.handler.test.ts | 103 +++++++++++++--- 6 files changed, 507 insertions(+), 55 deletions(-) diff --git a/src/services/finance-report.ts b/src/services/finance-report.ts index 71880ad1..239aee9e 100644 --- a/src/services/finance-report.ts +++ b/src/services/finance-report.ts @@ -177,7 +177,7 @@ export async function buildFinanceReport( swapClaimed, gameClaimable, swapClaimable, - solPrice, + rawSolPrice, ] = await Promise.all([ priceBalances(aggregateEvents(events, "game_fee", "earned"), dependencies), priceBalances(aggregateEvents(events, "swap_fee", "earned"), dependencies), @@ -187,6 +187,7 @@ export async function buildFinanceReport( priceBalances(dependencies.swapClaimable, dependencies), dependencies.resolveTokenPriceUsd(WSOL_MINT), ]); + const solPrice = rawSolPrice !== null && Number.isFinite(rawSolPrice) ? rawSolPrice : null; let sponsorCostLamports = 0n; let sponsorReimbursementLamports = 0n; diff --git a/tests/finance-ledger.test.ts b/tests/finance-ledger.test.ts index 5dc7271e..0acf3341 100644 --- a/tests/finance-ledger.test.ts +++ b/tests/finance-ledger.test.ts @@ -1,4 +1,4 @@ -import { describe, expect, test } from "bun:test"; +import { describe, expect, mock, spyOn, test } from "bun:test"; import { PublicKey } from "#solana"; import { FinanceLedgerService, referralDeltaFromTransaction } from "../src/services/finance-ledger"; @@ -33,6 +33,17 @@ describe("Jupiter referral ledger", () => { { mint: MINT, delta: -125n }, ); }); + + test("ignores missing accounts, absent metadata, and zero deltas", () => { + expect(referralDeltaFromTransaction(transaction("100", "125"), "other")).toBeNull(); + expect( + referralDeltaFromTransaction( + { ...transaction("100", "125"), meta: null }, + ACCOUNT.toBase58(), + ), + ).toBeNull(); + expect(referralDeltaFromTransaction(transaction("125", "125"), ACCOUNT.toBase58())).toBeNull(); + }); }); describe("incremental finance backfill", () => { @@ -100,6 +111,102 @@ describe("incremental finance backfill", () => { getReferralTokenAccountsV2: async () => ({ tokenAccounts: [], token2022Accounts: [] }), } as any; + test("requests the default batch limit and transaction commitment, and honors an exact cursor and cutoff", async () => { + const history = createHistory({ + ...source, + beforeSignature: "prior-page", + startTimeMs: 100_000, + }); + const getSignaturesForAddress = mock(async (_address: PublicKey, _options: unknown) => [ + { signature: "at-cutoff", blockTime: 100, slot: 42 }, + { signature: "older", blockTime: 99, slot: 41 }, + ]); + const getTransaction = mock(async (_signature: string, _config: unknown) => ({ + ...transaction("125", "100"), + blockTime: null, + meta: { ...transaction("125", "100").meta, fee: 99 }, + })); + const sleep = spyOn(Bun, "sleep").mockResolvedValue(undefined); + try { + const service = new FinanceLedgerService( + { getSignaturesForAddress, getTransaction } as unknown as ConstructorParameters< + typeof FinanceLedgerService + >[0], + program, + history.store, + OTHER, + referralReader, + ); + expect(await service.backfillNextBatch(100_000)).toMatchObject({ + complete: false, + processedTransactions: 1, + }); + expect(getSignaturesForAddress.mock.calls).toEqual([ + [ACCOUNT, { before: "prior-page", limit: 10 }], + ]); + expect(getTransaction.mock.calls).toEqual([ + ["at-cutoff", { commitment: "confirmed", maxSupportedTransactionVersion: 0 }], + ]); + expect(sleep.mock.calls).toEqual([[250]]); + expect(history.advances).toEqual([ + { signature: "at-cutoff", completed: false, processed: 1 }, + { signature: "at-cutoff", completed: true, processed: 0 }, + ]); + expect(history.events).toEqual([ + { + eventId: `jupiter:at-cutoff:${ACCOUNT.toBase58()}:claimed`, + source: "jupiter", + category: "swap_fee", + kind: "claimed", + signature: "at-cutoff", + account: ACCOUNT.toBase58(), + mint: MINT, + amountRaw: "25", + networkFeeLamports: "99", + timestamp: 100_000, + slot: 42, + }, + ]); + } finally { + sleep.mockRestore(); + } + }); + + test("uses the injected time and delay only when the transaction has no timestamps", async () => { + const sleep = mock(async (_ms: number) => {}); + const history = createHistory(); + const connection = { + getSignaturesForAddress: async () => [ + { signature: "first", blockTime: null, slot: 5 }, + { signature: "zero", blockTime: 99, slot: 6 }, + ], + getTransaction: async (sig: string) => ({ + ...transaction("9", "12"), + blockTime: sig === "zero" ? 0 : null, + }), + } as unknown as ConstructorParameters[0]; + const service = new FinanceLedgerService( + connection, + program, + history.store, + undefined, + referralReader, + { batchSize: 2, requestDelayMs: 12, sleep, now: () => 5_123 }, + ); + await service.backfillNextBatch(0); + expect(sleep.mock.calls).toEqual([[12], [12]]); + expect(history.events).toMatchObject([ + { + kind: "earned", + signature: "first", + amountRaw: "3", + timestamp: 5_000, + networkFeeLamports: null, + }, + { kind: "earned", signature: "zero", amountRaw: "3", timestamp: 0, networkFeeLamports: null }, + ]); + }); + test("persists a cursor after every transaction", async () => { const history = createHistory(); const connection = { diff --git a/tests/finance-report.test.ts b/tests/finance-report.test.ts index f830a0cf..b00813f0 100644 --- a/tests/finance-report.test.ts +++ b/tests/finance-report.test.ts @@ -1,5 +1,9 @@ import { afterEach, beforeEach, describe, expect, spyOn, test } from "bun:test"; -import { buildFinanceReport, resolveFinanceWindow } from "../src/services/finance-report"; +import { + buildFinanceReport, + resolveFinanceWindow, + type FinanceReportDependencies, +} from "../src/services/finance-report"; import { createFinanceHandlers, FINANCE_ADMIN_TELEGRAM_IDS, @@ -59,9 +63,166 @@ describe("finance configuration", () => { monthlyExpenseFactor: 3, }); }); + + test.each([ + ["7d", 7, 7 / 30], + ["30d", 30, 1], + ["90d", 90, 3], + ] as const)("pins the inclusive window and prorating for %s", (period, days, factor) => { + const clock = spyOn(Date, "now").mockReturnValue(NOW); + try { + expect(resolveFinanceWindow(period)).toEqual({ + startTimeMs: NOW - days * 86_400_000, + endTimeMs: NOW + 1, + label: `Last ${days} days`, + monthlyExpenseFactor: factor, + }); + } finally { + clock.mockRestore(); + } + }); }); describe("finance report", () => { + const reportInputs = ( + overrides: Partial, + ): FinanceReportDependencies => ({ + now: NOW, + financeEvents: [], + sponsorRecords: [], + gameClaimable: [], + swapClaimable: [], + coverage: "complete", + backfill: COMPLETE_BACKFILL, + monthlyExpenses: [], + contractRentLamports: 0n, + resolveTokenMetadata: metadata, + resolveTokenPriceUsd: price, + ...overrides, + }); + + test("bills the largest fee for each signature without billing unrelated or outside-window transactions", async () => { + const start = NOW - 7 * 86_400_000; + const expenses = [ + { category: "hosting", description: "VPS", amountUsd: 30 }, + { category: "storage", description: "DB", amountUsd: 60 }, + ]; + const feeEvent = ( + eventId: string, + signature: string, + fee: string, + rest: Partial = {}, + ) => event({ eventId, signature, networkFeeLamports: fee, ...rest }); + const report = await buildFinanceReport( + "7d", + reportInputs({ + financeEvents: [ + feeEvent("early", "early", "99999999999", { timestamp: start - 1 }), + feeEvent("start", "same-game", "100000000", { timestamp: start }), + feeEvent("duplicate-game", "same-game", "300000000", { timestamp: start }), + feeEvent("other-game", "other-game", "200000000", { timestamp: NOW }), + feeEvent("late", "late", "99999999999", { timestamp: NOW + 1 }), + feeEvent("swap", "swap", "77777777777", { category: "swap_fee", mint: USDC }), + feeEvent("swap-repeat", "swap", "88888888888", { category: "swap_fee", mint: USDC }), + feeEvent("claim-game", "claim", "100000000", { kind: "claimed" }), + feeEvent("claim-swap", "claim", "400000000", { + kind: "claimed", + category: "swap_fee", + mint: USDC, + }), + ], + monthlyExpenses: expenses, + contractRentLamports: 2_000_000_000n, + contractRentEstimated: true, + }), + ); + + expect(report).toMatchObject({ + period: "7d", + label: "Last 7 days", + expenseFactor: 7 / 30, + startTimeMs: start, + endTimeMs: NOW + 1, + completedGames: 3, + feeGeneratingSwaps: 1, + gameRevenue: [ + { mint: TIMBA, ticker: "TIMBA", decimals: 6, rawAmount: 3_000_000n, usdValue: 0.03 }, + ], + swapRevenue: [ + { mint: USDC, ticker: "USDC", decimals: 6, rawAmount: 2_000_000n, usdValue: 2 }, + ], + gameClaimed: [{ mint: TIMBA, rawAmount: 1_000_000n }], + swapClaimed: [{ mint: USDC, rawAmount: 1_000_000n }], + completionNetworkExpensesUsd: 50, + sponsorNetworkExpensesUsd: 0, + collectionNetworkExpensesUsd: 40, + networkExpensesUsd: 90, + recurringExpensesUsd: 21, + grossRevenueUsd: 2.03, + totalExpensesUsd: 111, + netProfitUsd: -108.97, + contractRentLamports: 2_000_000_000n, + contractRentUsd: 200, + contractRentEstimated: true, + monthlyExpenses: expenses, + }); + }); + + test("combines claimable raw units and omits zero or negative totals before resolving metadata", async () => { + const unknown = "unpriced-mint"; + const neverLookUp = "unused-mint"; + const lookedUp: string[] = []; + const report = await buildFinanceReport( + "30d", + reportInputs({ + gameClaimable: [ + { mint: unknown, amountRaw: 40n }, + { mint: unknown, amountRaw: -11n }, + { mint: neverLookUp, amountRaw: 5n }, + { mint: neverLookUp, amountRaw: -5n }, + ], + swapClaimable: [ + { mint: USDC, amountRaw: 1_250_000n }, + { mint: TIMBA, amountRaw: -10n }, + ], + coverage: "partial", + resolveTokenMetadata: async (mint) => { + lookedUp.push(mint); + return mint === unknown ? null : metadata(mint); + }, + resolveTokenPriceUsd: async (mint) => (mint === unknown ? Infinity : price(mint)), + }), + ); + expect(lookedUp).toEqual([unknown, USDC]); + expect(report.gameClaimable).toEqual([ + { mint: unknown, ticker: unknown, decimals: 0, rawAmount: 29n, usdValue: null }, + ]); + expect(report.swapClaimable).toEqual([ + { mint: USDC, ticker: "USDC", decimals: 6, rawAmount: 1_250_000n, usdValue: 1.25 }, + ]); + expect(report.hasUnpricedTokens).toBe(true); + expect(report.coverage).toBe("partial"); + expect(report.backfill).toEqual(COMPLETE_BACKFILL); + }); + + test.each([null, NaN, Infinity])( + "keeps unpriced SOL expenses finite when the price is %p", + async (solPrice) => { + const report = await buildFinanceReport( + "90d", + reportInputs({ + financeEvents: [event({})], + contractRentLamports: 2_000_000_000n, + resolveTokenPriceUsd: async (mint) => (mint === SOL ? solPrice : price(mint)), + }), + ); + expect(report.completionNetworkExpensesUsd).toBe(0); + expect(report.networkExpensesUsd).toBe(0); + expect(report.contractRentUsd).toBeNull(); + expect(report.netProfitUsd).toBe(0.01); + }, + ); + test("separates earned, claimed, and currently claimable fees", async () => { const report = await buildFinanceReport("30d", { now: NOW, diff --git a/tests/game-creation-recovery.test.ts b/tests/game-creation-recovery.test.ts index 5a174192..b7cf56f1 100644 --- a/tests/game-creation-recovery.test.ts +++ b/tests/game-creation-recovery.test.ts @@ -211,45 +211,56 @@ describe("Finalized creation absence proof", () => { }); test("rebroadcasts before confirmation timeout and stops after success", async () => { - let sends = 0; - let confirm!: () => void; - const pending = new Promise((resolve) => { - confirm = resolve; - }); - await withCreationRebroadcast( - () => pending, - async () => { - sends++; - if (sends === 2) confirm(); - }, - 1, - ); - expect(sends).toBe(2); - await Bun.sleep(10); - expect(sends).toBe(2); + vi.useFakeTimers(); + const confirmation = Promise.withResolvers(); + const rebroadcast = mock(async () => {}); + const result = withCreationRebroadcast(() => confirmation.promise, rebroadcast, 5); + try { + vi.advanceTimersByTime(4); + expect(rebroadcast).not.toHaveBeenCalled(); + vi.advanceTimersByTime(1); + await Promise.resolve(); + expect(rebroadcast).toHaveBeenCalledTimes(1); + vi.advanceTimersByTime(5); + await Promise.resolve(); + expect(rebroadcast).toHaveBeenCalledTimes(2); + confirmation.resolve("done"); + expect(await result).toBe("done"); + expect(vi.getTimerCount()).toBe(0); + vi.advanceTimersByTime(10); + expect(rebroadcast).toHaveBeenCalledTimes(2); + } finally { + confirmation.resolve("cleanup"); + await result; + vi.useRealTimers(); + } }); test("rebroadcast failures do not cancel confirmation or delay its result", async () => { - let sends = 0; - let finished = false; - let confirm!: () => void; - const pending = new Promise((resolve) => { - confirm = resolve; - }); - await withCreationRebroadcast( - () => pending, - async () => { - if (++sends === 1) throw new Error("RPC down"); - confirm(); - await Bun.sleep(5); - finished = true; - }, - 1, - ); - expect(sends).toBe(2); - expect(finished).toBe(false); - await Bun.sleep(10); - expect(finished).toBe(true); + vi.useFakeTimers(); + const confirmation = Promise.withResolvers(); + const secondSend = Promise.withResolvers(); + const rebroadcast = mock(async () => {}); + rebroadcast.mockRejectedValueOnce(new Error("RPC down")).mockReturnValue(secondSend.promise); + const result = withCreationRebroadcast(() => confirmation.promise, rebroadcast, 5); + try { + vi.advanceTimersByTime(5); + await Promise.resolve(); + expect(rebroadcast).toHaveBeenCalledTimes(1); + vi.advanceTimersByTime(5); + await Promise.resolve(); + expect(rebroadcast).toHaveBeenCalledTimes(2); + confirmation.resolve("done"); + expect(await result).toBe("done"); + secondSend.resolve(); + await Promise.resolve(); + expect(vi.getTimerCount()).toBe(0); + } finally { + confirmation.resolve("cleanup"); + secondSend.resolve(); + await result; + vi.useRealTimers(); + } }); test("restart recovery locates the expiry anchor instead of scanning all later blocks", async () => { diff --git a/tests/game-setup.module.test.ts b/tests/game-setup.module.test.ts index 9cb3889c..b1aa0e1c 100644 --- a/tests/game-setup.module.test.ts +++ b/tests/game-setup.module.test.ts @@ -88,6 +88,22 @@ describe("interactive setup token resolution", () => { }); }); + test("stores the setup under the fallback chat when Telegram omits chat details", async () => { + const { module, sessions } = setup(); + const { ctx, replies } = commandCtx(); + delete ctx.chat; + delete ctx.message; + await module.startInteractiveGameSetup(ctx, 7n, GAME_SETUP_COPY.coinflip); + expect(replies).toHaveLength(1); + expect(sessions.get("0_90")).toMatchObject({ + waitingFor: "setup", + chatId: 0, + messageId: 90, + creatorId: "7", + }); + expect([...sessions.keys()]).toEqual(["0_90"]); + }); + test.each([ ["an unknown configured token", async () => ({ success: false, unknownToken: "GONE" })], ["an unresolved token without a name", async () => ({ success: false })], @@ -237,6 +253,91 @@ describe("creator callbacks", () => { expect(answers).toEqual(["❌ Unable to process action"]); expect(handler).not.toHaveBeenCalled(); + expect(logSpy.mock.calls).toEqual([ + ["🔔 test callback triggered:", "x"], + ["👤 Creator: unknown, Current user: 7"], + ]); + expect(warnSpy.mock.calls).toEqual([["test: unable to resolve creator id from callback"]]); + }); + + test("denies a different or missing creator with the expected notice", async () => { + const { module, answers } = setup(); + const handler = mock(async () => {}); + const handle = module.withCreatorSessionContext( + { name: "edit", resolveCreatorId: () => "7" }, + handler, + ); + await handle(callbackCtx(8)); + const missing = callbackCtx(); + delete missing.callbackQuery; + await handle(missing); + expect(answers).toEqual([ + "🚫 Only the game creator can modify this setup!", + "🚫 Only the game creator can modify this setup!", + ]); + expect(logSpy.mock.calls).toEqual([ + ["🔔 edit callback triggered:", "x"], + ["👤 Creator: 7, Current user: 8"], + ["🔔 edit callback triggered:", undefined], + ["👤 Creator: 7, Current user: unknown"], + ]); + expect(handler).not.toHaveBeenCalled(); + }); + + test.each([ + ["no chat", true, false, "0_90"], + ["no callback", false, true, "-10_0"], + ] as const)( + "preserves the contract minimum with %s", + async (_label, omitChat, omitCallback, key) => { + const { module, sessions } = setup(); + const ctx = callbackCtx(7); + if (omitChat) delete ctx.chat; + if (omitCallback) delete ctx.callbackQuery; + sessions.set(key, { + tokenMint: TOKEN, + tokenTicker: "TKN", + tokenDecimals: 6, + contractMinimum: 4, + }); + const handle = module.withCreatorContext( + { name: "edit", resolveCreatorId: () => "7" }, + (_ctx, setupCtx) => { + expect(setupCtx.updateSession({ waitingFor: "players" })).toMatchObject({ + tokenTicker: "TKN", + contractMinimum: 4, + }); + expect(setupCtx.updateSession({ contractMinimum: 0 })).toMatchObject({ + contractMinimum: 0, + }); + expect(setupCtx.updateSession({ waitingFor: "confirm" })).toMatchObject({ + contractMinimum: 0, + }); + }, + ); + await handle(ctx); + expect([...sessions.keys()]).toEqual([key]); + expect(sessions.get(key)).toMatchObject({ + waitingFor: "confirm", + tokenMint: TOKEN, + contractMinimum: 0, + }); + }, + ); + + test("uses the fallback message ID on an inline callback", async () => { + const { module, sessions } = setup(); + const ctx = callbackCtx(7); + delete ctx.callbackQuery.message; + sessions.set("-10_0", { tokenMint: TOKEN }); + await module.withCreatorContext( + { name: "edit", resolveCreatorId: () => "7" }, + (_ctx, setupCtx) => { + expect(setupCtx.session).toMatchObject({ tokenMint: TOKEN }); + setupCtx.updateSession({ waitingFor: "setup" }); + }, + )(ctx); + expect(sessions.get("-10_0")).toMatchObject({ tokenMint: TOKEN, waitingFor: "setup" }); }); test("refuses callbacks when the sender has no usable id", async () => { diff --git a/tests/wallet-positions.handler.test.ts b/tests/wallet-positions.handler.test.ts index c9981c7c..4197f8e2 100644 --- a/tests/wallet-positions.handler.test.ts +++ b/tests/wallet-positions.handler.test.ts @@ -1,4 +1,4 @@ -import { afterEach, expect, test } from "bun:test"; +import { afterEach, expect, spyOn, test } from "bun:test"; import { InlineKeyboard } from "grammy"; import { WSOL_MINT } from "../src/utils/constants"; import { @@ -29,6 +29,10 @@ const createCtx = (data = "wallet_positions", fromId: number | undefined = 42) = menus.push({ text, options }); return {}; }, + reply: async (text: string, options?: unknown) => { + menus.push({ text, options }); + return { message_id: 8 }; + }, answerCallbackQuery: async (text?: string) => { if (text) answers.push(text); }, @@ -67,10 +71,18 @@ test("onWalletPositions shows an empty state when there are no bot buys", async const { ctx, menus } = createCtx(); await onWalletPositions(ctx, baseDeps()); - expect(menus[0]?.text).toContain("No tracked positions yet"); - expect(menus[0]?.options?.reply_markup?.inline_keyboard?.[0]?.[0]?.callback_data).toBe( - "wallet_pos_r_0", + expect(menus[0]?.text).toBe( + [ + "📊 Positions", + "", + "No tracked positions yet.", + "Buy a token with Swap to start seeing PNL from your average entry.", + ].join("\n"), ); + expect(menus[0]?.options?.reply_markup?.inline_keyboard).toEqual([ + [{ text: "🔁 Refresh", callback_data: "wallet_pos_r_0" }], + [{ text: "← Back to Wallet", callback_data: "main_wallet" }], + ]); }); test("onWalletPositions refresh from empty clears caches", async () => { @@ -231,6 +243,58 @@ test("onWalletPositions refresh clears caches and stays on the same page", async expect(menus[0]?.text).toContain("DDD"); }); +test.each([ + ["wallet_pos_r_10", 10, true], + ["wallet_pos_10", 10, false], + ["wallet_pos_r_10wrong", 0, false], + ["wrongwallet_pos_r_10", 0, false], + ["wallet_pos_10wrong", 0, false], + ["wrongwallet_pos_10", 0, false], + [undefined, 0, false], +] as const)("routes positions callback %p", async (callback, page, refreshing) => { + const { ctx, menus } = createCtx(callback); + if (callback === undefined) ctx.callbackQuery = undefined; + + const holdings = Array.from({ length: 31 }, (_, index) => ({ + mint: `mint-${index}`, + ticker: `TOKEN${index}`, + // Give each position a distinct value to pin order without relying on the ticker sort. + balance: 31 - index, + decimals: 0, + })); + const refreshes: bigint[] = []; + const pages: Array<{ page: number; pageCount: number }> = []; + await onWalletPositions( + ctx, + baseDeps({ + getHoldings: async () => holdings, + getSwapsByWallet: () => + holdings.map(({ mint, ticker, balance }, i) => buy(mint, ticker, String(balance), i + 1)), + fetchPricesUSD: async () => + Object.fromEntries( + [WSOL_MINT, ...holdings.map(({ mint }) => mint)].map((mint) => [mint, 1]), + ), + refreshCaches: (id) => { + refreshes.push(id); + }, + createKeyboard: (view) => { + pages.push(view); + return new InlineKeyboard(); + }, + }), + ); + expect(refreshes).toEqual(refreshing ? [42n] : []); + expect(pages).toEqual([{ page, pageCount: 11 }]); + expect(menus[0]?.text.split("\n")[0]).toBe(`📊 Positions (${page + 1}/11)`); +}); + +test("refreshing still renders the view when no cache invalidator is connected", async () => { + const { ctx, menus, answers } = createCtx("wallet_pos_r_0"); + await onWalletPositions(ctx, baseDeps()); + expect(menus[0]?.text).toContain("📊 Positions"); + expect(answers).toEqual([]); +}); + test("onWalletPositions rejects a missing telegram user", async () => { const { ctx, menus, answers } = createCtx("wallet_positions", 0); await onWalletPositions(ctx, baseDeps()); @@ -260,17 +324,24 @@ test("loadWalletPositions reuses the snapshot so /start and Positions share one test("onWalletPositions reports an error when prices fail", async () => { const { ctx, menus, answers } = createCtx(); - await onWalletPositions( - ctx, - baseDeps({ - getHoldings: async () => [{ mint: TIMBA, ticker: "TIMBA", balance: 10, decimals: 6 }], - getSwapsByWallet: () => [buy(TIMBA, "TIMBA", "10000000", 1)], - fetchPricesUSD: async () => { - throw new Error("prices down"); - }, - }), - ); + const outage = new Error("prices down"); + const report = spyOn(console, "error").mockImplementation(() => {}); + try { + await onWalletPositions( + ctx, + baseDeps({ + getHoldings: async () => [{ mint: TIMBA, ticker: "TIMBA", balance: 10, decimals: 6 }], + getSwapsByWallet: () => [buy(TIMBA, "TIMBA", "10000000", 1)], + fetchPricesUSD: async () => { + throw outage; + }, + }), + ); - expect(menus).toEqual([]); - expect(answers).toContain("❌ Error loading positions"); + expect(menus).toEqual([]); + expect(answers).toContain("❌ Error loading positions"); + expect(report.mock.calls).toEqual([["Error in wallet_positions:", outage]]); + } finally { + report.mockRestore(); + } }); From ef0d37b1b72f780425edc3778fdb92652b24d3e3 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 11:49:40 -0300 Subject: [PATCH 009/410] fix(sweeps): reject invalid prices and preserve game participants --- src/services/fee-sweeper.ts | 22 ++-- src/utils/errors/formatter.ts | 3 +- src/utils/game-database.ts | 2 +- tests/errors.test.ts | 123 +++++++++++++++++++++ tests/fee-sweeper.paths.test.ts | 50 +++++++++ tests/game-database.queries.test.ts | 56 ++++++++++ tests/lightning-handler.test.ts | 159 +++++++++++++++++++++++++++- 7 files changed, 402 insertions(+), 13 deletions(-) diff --git a/src/services/fee-sweeper.ts b/src/services/fee-sweeper.ts index 51650500..2426ad46 100644 --- a/src/services/fee-sweeper.ts +++ b/src/services/fee-sweeper.ts @@ -120,6 +120,11 @@ async function resolveFeeSweepTokens( const MIN_USD_THRESHOLD = 5; const SOL_DECIMALS = 9; +const finiteUsdValue = (amount: number, price?: number): number => { + const value = amount * (price ?? 0); + return Number.isFinite(value) ? value : 0; +}; + const normalizeTimestampMs = (timestamp: number): number => { if (!Number.isFinite(timestamp)) return timestamp; return timestamp < 1_000_000_000_000 ? timestamp * 1000 : timestamp; @@ -145,7 +150,7 @@ const validateSolPriceData = ( ? priceData.timestamp : null; - if (timestamp === null) { + if (timestamp === null || !Number.isFinite(timestamp)) { return { isValid: false, reason: "missing timestamp" }; } @@ -190,7 +195,8 @@ const getSolBalanceUsdValue = async ( priceResolver({ tokenMint: WSOL_MINT }), ]); const solPrice = solPriceData?.price ?? 0; - const usdValue = lamports > 0 && solPrice > 0 ? (lamports / LAMPORTS_PER_SOL) * solPrice : 0; + const usdValue = + lamports > 0 && solPrice > 0 ? finiteUsdValue(lamports / LAMPORTS_PER_SOL, solPrice) : 0; return { lamports, usdValue, solPrice, solPriceData }; }; @@ -245,7 +251,7 @@ const shouldWithdrawToken = async ( const formattedPending = wallet.formatTokenBalance(Number(pendingFees), decimals); const tokenAmount = Number(pendingFees) / 10 ** decimals; const priceData = await priceResolver({ tokenMint: config.mint }); - const tokenUsdValue = tokenAmount * (priceData?.price ?? 0); + const tokenUsdValue = finiteUsdValue(tokenAmount, priceData?.price); if (tokenUsdValue < MIN_USD_THRESHOLD) { console.log( `ℹ️ Skipping ${config.ticker} withdrawal: ${formattedPending} ≈ $${tokenUsdValue.toFixed( @@ -279,7 +285,7 @@ const shouldSwapTokenBalance = async ( const price = await priceResolver({ tokenMint: config.mint, }); - const usdValue = amountDecimal * (price?.price ?? 0); + const usdValue = finiteUsdValue(amountDecimal, price?.price); if (usdValue < MIN_USD_THRESHOLD) { console.log( `ℹ️ ${config.ticker} balance ${amountDecimal.toFixed(6)} ≈ $${usdValue.toFixed( @@ -311,7 +317,7 @@ const unwrapWsolBalance = async ( const metadata = await wallet.getTokenMetadata(WSOL_MINT); const amountDecimal = Number(wsolBalanceLamports) / 10 ** metadata.decimals; const price = await priceResolver({ tokenMint: WSOL_MINT }); - const usdValue = amountDecimal * (price?.price ?? 0); + const usdValue = finiteUsdValue(amountDecimal, price?.price); if (usdValue < MIN_USD_THRESHOLD) { console.log( @@ -483,7 +489,7 @@ async function runReferralSweep( // Try to get price for this token const priceData = await priceResolver({ tokenMint: mint }); - if (!priceData?.price) continue; + if (!priceData?.price || !Number.isFinite(priceData.price)) continue; // Fetch decimals for this token const mintInfo = await connection.getParsedAccountInfo(tokenAccount.account.mint); @@ -495,10 +501,10 @@ async function runReferralSweep( : 9; const tokenAmount = Number(amount) / 10 ** decimals; - totalUsdValue += tokenAmount * priceData.price; + totalUsdValue += finiteUsdValue(tokenAmount, priceData.price); } - if (totalUsdValue < MIN_USD_THRESHOLD) { + if (!Number.isFinite(totalUsdValue) || totalUsdValue < MIN_USD_THRESHOLD) { console.log( `ℹ️ Skipping referral claim: total value ≈ $${totalUsdValue.toFixed(2)} (< $${MIN_USD_THRESHOLD}).`, ); diff --git a/src/utils/errors/formatter.ts b/src/utils/errors/formatter.ts index b5f6cc47..69d784be 100644 --- a/src/utils/errors/formatter.ts +++ b/src/utils/errors/formatter.ts @@ -6,6 +6,7 @@ import type { Connection } from "#solana"; import type { WalletManager } from "../wallet"; import { LAMPORTS_PER_SOL, CALLBACK_MESSAGE_MAX_LENGTH } from "../constants"; import { FeeBudgetManager } from "../fee-budget"; +import { trimFixed } from "../format-amount"; import { extractLamportsInfo, extractLamportsInfoFromError, @@ -21,7 +22,7 @@ const formatSolAmount = (lamports: number, walletManager?: WalletManager): strin // Six decimals keeps the message readable while preserving sub-cent fee precision. const roundedUpLamports = Math.ceil(Math.max(lamports, 0) / 1_000) * 1_000; const formatted = (roundedUpLamports / LAMPORTS_PER_SOL).toFixed(6); - const concise = formatted.replace(/\.?0+$/u, ""); + const concise = trimFixed(formatted); if (concise !== "0" || !walletManager) { return concise; diff --git a/src/utils/game-database.ts b/src/utils/game-database.ts index 10ee0caa..bb4f9892 100644 --- a/src/utils/game-database.ts +++ b/src/utils/game-database.ts @@ -483,7 +483,7 @@ export class GameDatabase extends BaseDatabase { const addresses = this.getGameParticipantAddresses(gameAddress); const index = Number.isInteger(ticketIndex) && ticketIndex >= 0 ? ticketIndex : -1; - if (movedParticipant && index < addresses.length) { + if (movedParticipant && index >= 0 && index < addresses.length) { addresses[index] = movedParticipant; } else { const playerIndex = addresses.indexOf(playerAddress); diff --git a/tests/errors.test.ts b/tests/errors.test.ts index 2f6970a4..69379806 100644 --- a/tests/errors.test.ts +++ b/tests/errors.test.ts @@ -15,6 +15,112 @@ test("truncateMessage truncates long message and appends ellipsis", () => { expect(truncateMessage(longMessage, { maxLength: 10 })).toBe("a".repeat(7) + "..."); }); +test.each(["❌", "⚠️", "Error:", "Failed:", "Invalid:"])( + "keeps the complete first sentence for the %s prefix", + (prefix) => { + const sentence = `${prefix} Stop.`; + expect( + truncateMessage(`${sentence} Use another token in this wallet.`, { + maxLength: 21, + preserveSentences: true, + }), + ).toBe(sentence); + }, +); + +test("only prefers sentence and word breaks when enabled and before their cutoffs", () => { + expect(truncateMessage("12345678901234567890", { maxLength: 20 })).toBe("12345678901234567890"); + expect(truncateMessage("Error: Stop. More troublesome detail", { maxLength: 20 })).toBe( + "Error: Stop. More...", + ); + expect( + truncateMessage("Error: 1234567890. More detail", { maxLength: 20, preserveSentences: true }), + ).toBe("Error: 1234567890..."); + expect( + truncateMessage("Start. Text has no recognized prefix", { + maxLength: 20, + preserveSentences: true, + }), + ).toBe("Start. Text has n..."); + expect( + truncateMessage("12345678901234 xyz additional details", { maxLength: 20, wordBoundary: true }), + ).toBe("12345678901234 xy..."); + expect( + truncateMessage("123456789012345 xyz additional details", { + maxLength: 20, + wordBoundary: true, + }), + ).toBe("123456789012345..."); + expect(truncateMessage("123456789012345 xyz additional details", { maxLength: 20 })).toBe( + "123456789012345 x...", + ); +}); + +test.each([ + [ + "insufficient lamports 42, need 3043", + "💰 Not enough SOL\nThis needs about 0.000004 SOL more. Top up with /deposit and try again.", + ], + [ + "insufficient funds for rent", + "💰 Not enough SOL\nOpening a token account needs a small deposit. Keep at least 0.000405 SOL in your wallet and try again.", + ], + [ + "insufficient for fees", + "💰 Not enough SOL for fees\nKeep at least 0.00004 SOL in your wallet, or top up with /deposit.", + ], + [ + "account does not exist", + "🏗️ Account setup needed\nKeep at least 0.00004 SOL in your wallet to cover the setup fee.", + ], + [ + "failed to wrap sol automatically", + "🪙 Couldn't convert SOL\nTry again in a moment, or add more SOL if it keeps happening.", + ], + [ + "custom program error", + "❌ Transaction failed\nThe network rejected it. Try again shortly, or ask an admin if it keeps happening.", + ], + [ + "simulation failed", + "❌ Transaction failed\nThe network rejected it. Try again shortly, or ask an admin if it keeps happening.", + ], + [ + "no route found", + "🛣️ No swap route\nThere's no way to trade this pair right now. Try a smaller amount, another pair, or later.\nKeep some SOL in your wallet for fees.", + ], + [ + "slippage", + "📊 Price moved\nThe price changed too much while swapping. Try a smaller amount or a slightly higher tolerance.", + ], + [ + "price impact", + "💹 Price impact too high\nThis swap would move the price too much. Try a smaller amount or split it into several trades.", + ], + [ + "quote failed", + "📋 No price available\nWe couldn't price this swap. Try again shortly or pick another pair.", + ], + [ + "circular_arbitrage_is_disabled", + "🔄 Same token\nYou can't swap a token for itself. Pick a different token to receive.", + ], + ...["address table account", "lookup table", "addresstablelookup"].map((input) => [ + input, + "🔗 No swap route\nThis trade needs a route we can't use here. Try a smaller amount or another pair.", + ]), + [ + "transaction confirmation timeout", + "⏳ Still confirming\nThe network is slow, so this may still go through.\nCheck it on Solscan before you retry.", + ], + [ + "transaction expired before confirmation", + "⛔ Transaction dropped\nThe network dropped it before it was confirmed.\nTry again to send a fresh transaction.", + ], +])("gives actionable wording for %s", async (input, expected) => { + expect(await parseTransactionError(input)).toBe(expected); +}); + test("parseTransactionError formats insufficient lamports message", async () => { const error = new Error("insufficient lamports 100, need 200"); const message = await parseTransactionError(error); @@ -251,6 +357,12 @@ test("parseTransactionError still formats errors when the fee budget cannot be r }); describe("buildFriendlyShortfallMessage", () => { + test("does not trim trailing digits from scientific notation", () => { + expect(buildFriendlyShortfallMessage({ missingLamports: 1.23e39 })).toBe( + "💰 Not enough SOL\nYou need about 1.23e+30 SOL more.\nAdd SOL or reduce the amount and try again.", + ); + }); + test("uses the wallet formatter for a zero shortfall and the default action", () => { const msg = buildFriendlyShortfallMessage({ missingLamports: -5, @@ -274,4 +386,15 @@ describe("buildFriendlyShortfallMessage", () => { "💰 Not enough SOL\nGame entry needs a fee buffer. You need about 0.001 SOL more.\nDeposit SOL first.", ); }); + + test("keeps sentence punctuation inside a reason", () => { + expect( + buildFriendlyShortfallMessage({ + missingLamports: 1_000, + reason: "Wallet not found. Retry after setup?!", + }), + ).toBe( + "💰 Not enough SOL\nWallet not found. Retry after setup. You need about 0.000001 SOL more.\nAdd SOL or reduce the amount and try again.", + ); + }); }); diff --git a/tests/fee-sweeper.paths.test.ts b/tests/fee-sweeper.paths.test.ts index 40d68235..65010948 100644 --- a/tests/fee-sweeper.paths.test.ts +++ b/tests/fee-sweeper.paths.test.ts @@ -5,6 +5,7 @@ import { __test_processTokenFee, __test_resolveFeeSweepTokens, __test_runReferralSweep, + __test_shouldSwapTokenBalance, __test_shouldWithdrawToken, __test_sweepTokensToSol, __test_unwrapWsolBalance, @@ -97,6 +98,21 @@ describe("withdrawal threshold", () => { expect(small.shouldWithdraw).toBe(false); expect(unpriced).toMatchObject({ shouldWithdraw: false, tokenUsdValue: 0 }); }); + + test.each([NaN, Infinity, -Infinity])( + "does not withdraw or swap a token when the returned price is %p", + async (invalidPrice) => { + const token = { mint: "M", ticker: "TKN" }; + const resolver = price(invalidPrice); + expect( + await __test_shouldWithdrawToken(wallet, token, 6_000_000n, 6, resolver), + ).toMatchObject({ shouldWithdraw: false, tokenUsdValue: 0 }); + expect(await __test_shouldSwapTokenBalance(token, 6_000_000n, 6, resolver)).toMatchObject({ + shouldSwap: false, + usdValue: 0, + }); + }, + ); }); describe("SOL price validation before swaps", () => { @@ -138,6 +154,11 @@ describe("SOL price validation before swaps", () => { expect(await run({ price: 100, timestamp: Math.floor(Date.now() / 1000) })).toBe(1); }); + test.each([NaN, Infinity])("rejects a non-finite SOL price timestamp %p", async (timestamp) => { + expect(await run({ price: 100, resolvedAt: timestamp, timestamp })).toBe(0); + expect(logged(warnSpy, "missing timestamp")).toBe(true); + }); + test.each([ ["a missing timestamp", { price: 100 }, "missing timestamp"], ["a stale price", { price: 100, resolvedAt: Date.now() - 24 * 60 * 60_000 }, "stale timestamp"], @@ -222,6 +243,20 @@ describe("token-to-SOL sweep details", () => { }); describe("WSOL unwrap with the default balance reader", () => { + test("does not unwrap using an infinite SOL price", async () => { + const payer = await Keypair.generate(); + const unwrapSolWithKeypair = mock(async () => ({ signature: "sig", remainingLamports: 0 })); + await __test_unwrapWsolBalance( + { getTokenMetadata: async () => ({ decimals: 9 }), unwrapSolWithKeypair } as any, + {} as any, + payer.publicKey, + payer, + price(Infinity), + async () => 100_000n, + ); + expect(unwrapSolWithKeypair).not.toHaveBeenCalled(); + }); + test("adds up every WSOL token account before unwrapping", async () => { const owner = (await Keypair.generate()).publicKey; const payer = await Keypair.generate(); @@ -321,6 +356,21 @@ describe("referral claims", () => { expect(logged(logSpy, "No referral fee transactions to claim")).toBe(true); }); + test("does not claim a referral account priced at infinity", async () => { + const s = await claimSetup({ transactions: [] }); + const claim = spyOn(s.provider, "claimAllV2"); + expect( + await __test_runReferralSweep( + s.connection as any, + s.payer, + referral, + price(Infinity), + () => s.provider as any, + ), + ).toBe(0); + expect(claim).not.toHaveBeenCalled(); + }); + test("signs each claim with a fresh blockhash and records claimed deltas", async () => { const tx = fakeTx(); const s = await claimSetup({ transactions: [undefined, tx] }); diff --git a/tests/game-database.queries.test.ts b/tests/game-database.queries.test.ts index 279889ef..b2033877 100644 --- a/tests/game-database.queries.test.ts +++ b/tests/game-database.queries.test.ts @@ -46,7 +46,43 @@ describe("GameDatabase query edge cases", () => { expect(db.getGame("G_TIME")?.created_at).toBe(123_456); }); + test("normalizes invalid times without treating a zero timestamp as missing", () => { + const clock = spyOn(Date, "now").mockReturnValue(7_000); + try { + db.saveGame("INVALID", "1", 5, "coinflip", "", "", 0, 0, 0, NaN, Infinity, NaN); + expect(db.getGame("INVALID")).toMatchObject({ + created_at: 7_000, + timeout_seconds: null, + expires_at: null, + token_mint: null, + token_ticker: null, + max_players: null, + min_players: null, + chat_id: null, + }); + db.saveGame("ZERO", "1", 5, "coinflip", "mint", "TKN", 8, 2, -10, 0, 0, 0); + expect(db.getGame("ZERO")).toMatchObject({ + created_at: 0, + timeout_seconds: 0, + expires_at: 0, + token_mint: "mint", + token_ticker: "TKN", + max_players: 8, + min_players: 2, + chat_id: -10, + }); + } finally { + clock.mockRestore(); + } + }); + describe("participant address bookkeeping", () => { + test("an unknown game or a new game has no participant addresses", () => { + expect(db.getGameParticipantAddresses("UNKNOWN")).toEqual([]); + db.saveGame("NEW", "1", 5, "coinflip"); + expect(db.getGameParticipantAddresses("NEW")).toEqual([]); + }); + test("ignores stored participant data that is not a list of addresses", () => { db.saveGame("G_P", "1", 5, "coinflip"); @@ -86,6 +122,26 @@ describe("GameDatabase query edge cases", () => { }); }); + test("moves an existing joiner to the new slot and preserves order at both ends", () => { + db.saveGame("JOIN", "1", 5, "coinflip"); + db.saveGameParticipantAddresses("JOIN", ["A", "B", "", " ", "A", "C"]); + expect(db.getGameParticipantAddresses("JOIN")).toEqual(["A", "B", "C"]); + db.recordGameParticipantJoined("JOIN", "B", -1, 3); + expect(db.getGameParticipantAddresses("JOIN")).toEqual(["B", "A", "C"]); + db.recordGameParticipantJoined("JOIN", "B", 99, 3); + expect(db.getGameParticipantAddresses("JOIN")).toEqual(["A", "C", "B"]); + }); + + test.each([-1, NaN, 1.5, 3])( + "uses the leaver address when the replacement index %p is invalid", + (invalid) => { + db.saveGame("UNJOIN", "1", 5, "coinflip"); + db.saveGameParticipantAddresses("UNJOIN", ["A", "B", "C"]); + db.recordGameParticipantUnjoined("UNJOIN", "A", invalid, 2, "C"); + expect(db.getGameParticipantAddresses("UNJOIN")).toEqual(["B", "C"]); + }, + ); + describe("getCreatorInfo", () => { test("returns null for an unknown game", () => { expect(db.getCreatorInfo("NOPE")).toBeNull(); diff --git a/tests/lightning-handler.test.ts b/tests/lightning-handler.test.ts index 36db1c0f..35c319da 100644 --- a/tests/lightning-handler.test.ts +++ b/tests/lightning-handler.test.ts @@ -5,9 +5,14 @@ import { join } from "node:path"; import { Bot } from "grammy"; import { patchReplyBehavior } from "../src/utils/reply-patch"; import type { Update } from "grammy/types"; -import { depositMessage, registerLightningDeposits } from "../src/handlers/lightning"; -import { FixedFloatClient } from "../src/services/lightning/fixedfloat"; -import { DepositStore } from "../src/services/lightning/store"; +import { + depositAmountMessage, + depositMessage, + depositMethodsMessage, + registerLightningDeposits, +} from "../src/handlers/lightning"; +import { FixedFloatClient, type FixedFloatOrder } from "../src/services/lightning/fixedfloat"; +import { DepositStore, type Deposit } from "../src/services/lightning/store"; import { clearAllInputSessions } from "../src/utils/user-state"; import type { WalletManager } from "../src/utils/wallet"; @@ -335,6 +340,154 @@ describe("quote failures", () => { }); describe("deposit cards", () => { + const expiration = Date.UTC(2026, 10, 28, 12, 34); + const providerOrder: FixedFloatOrder = { + id: "TEST01", + type: "float", + status: "NEW", + time: { expiration: expiration / 1_000 }, + from: { code: "BTCLN", amount: "0.00025", address: "lnbc<&invoice", usd: "26" }, + to: { code: "SOL", amount: "0.36", address, usd: "30" }, + }; + const card = (state: Deposit["state"], order: FixedFloatOrder | null): Deposit => ({ + id: "private-card", + owner: "1", + destination: address, + sats: "25000", + quotedSol: "0.24", + payUsd: "25", + receiveUsd: "24", + state, + created: 0, + order, + nextPoll: 0, + attempts: 0, + notified: "", + messageId: null, + }); + const exchangeDisclosure = + 'Exchange provided by FixedFloat service rules.'; + + test("quotes the stored price and offers exactly one way to create the invoice", () => { + const { text, keyboard } = depositMessage(card("quoted", null)); + expect(text).toBe( + [ + "⚡ Deposit via Lightning", + "", + "You pay: 25,000 sats (≈ $25.00)", + "You receive: ≈ 0.24 SOL (≈ $24.00)", + "Fee: 1%", + "", + "Quote valid for one minute.", + "", + exchangeDisclosure, + ].join("\n"), + ); + expect(keyboard.inline_keyboard).toEqual([ + [{ text: "Create invoice", callback_data: "ln_create:private-card" }], + [ + { text: "Change amount", callback_data: "ln_cancel:private-card" }, + { text: "← Deposit", callback_data: "wallet_deposit" }, + ], + ]); + }); + + test("prints the escaped invoice before expiry, and no invoice at the exact expiry", () => { + const clock = spyOn(Date, "now").mockReturnValue(expiration - 1); + try { + const active = depositMessage(card("active", providerOrder)); + expect(active.text).toBe( + [ + "⚡ Pay with Lightning", + "", + "You pay: 25,000 sats (≈ $26.00)", + "You receive: ≈ 0.36 SOL (≈ $30.00)", + "Fee: 1%", + "", + "lnbc<&invoice", + "", + "Tap the invoice to copy. Pay once before 12:34 UTC.", + "", + exchangeDisclosure, + ].join("\n"), + ); + expect(active.keyboard.inline_keyboard.flat()).toEqual([ + { text: "Open FixedFloat order", url: "https://ff.io/order/TEST01" }, + { text: "🔁 Refresh", callback_data: "ln_status:private-card" }, + { text: "← Deposit", callback_data: "wallet_deposit" }, + { text: "← Wallet", callback_data: "main_wallet" }, + ]); + + clock.mockReturnValue(expiration); + const expired = depositMessage(card("active", providerOrder)).text; + expect(expired).toBe( + `This invoice has expired. Do not pay it. Checking the final order status…\n\n${exchangeDisclosure}`, + ); + expect(expired).not.toContain(providerOrder.from.address); + } finally { + clock.mockRestore(); + } + }); + + test("uses the settlement amount and proportionate USD value in a completed card", () => { + const completed = depositMessage( + card("completed", { + ...providerOrder, + status: "DONE", + to: { ...providerOrder.to, tx: { id: "settled/1", amount: "0.18" } }, + }), + ); + expect(completed.text).toBe( + "✅ Deposit received\n\n0.18 SOL (≈ $15.00) arrived in your wallet.", + ); + expect(completed.keyboard.inline_keyboard.flat()).toEqual([ + { text: "View transaction", url: "https://solscan.io/tx/settled%2F1" }, + { text: "← Deposit", callback_data: "wallet_deposit" }, + { text: "← Wallet", callback_data: "main_wallet" }, + ]); + }); + + test.each(["unknown", "creating", "failed", "expired"] as const)( + "never displays payment instructions in the %s state", + (state) => { + const { text, keyboard } = depositMessage(card(state, providerOrder)); + expect(text).not.toContain("Pay with Lightning"); + expect(text).not.toContain("lnbc"); + const callbacks = keyboard.inline_keyboard + .flat() + .flatMap((button) => ("callback_data" in button ? [button.callback_data] : [])); + expect(callbacks).toEqual([ + state === "unknown" || state === "creating" ? "ln_status:private-card" : "wallet_deposit", + "wallet_deposit", + "main_wallet", + ]); + }, + ); + + test("lists only available deposit methods and escapes a provider error on the amount menu", () => { + const disabled = depositMethodsMessage(false); + expect(disabled.text).toBe("💰 Deposit\n\nChoose a deposit method."); + expect(disabled.keyboard.inline_keyboard).toEqual([ + [{ text: "◎ Solana", callback_data: "deposit_solana" }], + [{ text: "← Wallet", callback_data: "main_wallet" }], + ]); + expect(depositMethodsMessage(true).keyboard.inline_keyboard[0]).toEqual([ + { text: "◎ Solana", callback_data: "deposit_solana" }, + { text: "⚡ Lightning", callback_data: "wallet_lightning" }, + ]); + const limited = depositAmountMessage( + { btcUsd: 100_000, minSats: 25_001, maxSats: 25_999 }, + "Quote moved ", + ); + expect(limited.text).toBe( + "⚡ Deposit via Lightning\n\nQuote moved <again>\n\nChoose an amount in USD.\nLimits: $25.01 to $25.99", + ); + expect(limited.keyboard.inline_keyboard).toEqual([ + [{ text: "✏️ Custom Amount", callback_data: "ln_custom" }], + [{ text: "← Deposit", callback_data: "wallet_deposit" }], + ]); + }); + test("a card that cannot be shown offers to go back", async () => { await withHarness({}, async (h) => { await h.click("ln_usd:25"); From f035cc52aa56ded4cfd0acef4102c71747e2ba2b Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 11:53:43 -0300 Subject: [PATCH 010/410] fix(wallet): preserve pending fetches and validate wrap amounts --- src/handlers/wallet-menu.ts | 4 +++- src/handlers/wallet-transactions.ts | 7 +++---- tests/wallet-menu.cache.test.ts | 23 ++++++++++++++++++++++- tests/wallet-menu.page-snapshot.test.ts | 11 +++++++++-- tests/wallet-transactions.flows.test.ts | 18 ++++++++++++++++++ tests/wallet-ui.swr.test.ts | 22 +++++++++++++++++++--- 6 files changed, 74 insertions(+), 11 deletions(-) diff --git a/src/handlers/wallet-menu.ts b/src/handlers/wallet-menu.ts index d67df5d2..1f2e8054 100644 --- a/src/handlers/wallet-menu.ts +++ b/src/handlers/wallet-menu.ts @@ -371,7 +371,9 @@ export const createWalletMenuModule = (options: WalletMenuModuleOptions): Wallet try { return await fetchPromise; } finally { - pendingWalletFetches.delete(cacheKey); + if (pendingWalletFetches.get(cacheKey) === fetchPromise) { + pendingWalletFetches.delete(cacheKey); + } } }; diff --git a/src/handlers/wallet-transactions.ts b/src/handlers/wallet-transactions.ts index 729e25b9..8223cbf4 100644 --- a/src/handlers/wallet-transactions.ts +++ b/src/handlers/wallet-transactions.ts @@ -906,11 +906,10 @@ export const createWalletTransactionsModule = ( bot.callbackQuery(/^confirm_wrap_/, async (ctx) => { try { - const callbackData = ctx.callbackQuery?.data || ""; - const lamportsRaw = callbackData.replace("confirm_wrap_", ""); - const lamportsToWrap = Number.parseInt(lamportsRaw, 10); + const match = /^confirm_wrap_(\d+)$/.exec(ctx.callbackQuery?.data ?? ""); + const lamportsToWrap = Number(match?.[1]); - if (!Number.isFinite(lamportsToWrap) || lamportsToWrap <= 0) { + if (!Number.isSafeInteger(lamportsToWrap) || lamportsToWrap <= 0) { throw new Error("Invalid wrap amount"); } diff --git a/tests/wallet-menu.cache.test.ts b/tests/wallet-menu.cache.test.ts index b71a8245..d0ee6399 100644 --- a/tests/wallet-menu.cache.test.ts +++ b/tests/wallet-menu.cache.test.ts @@ -1,4 +1,4 @@ -import { describe, expect, test } from "bun:test"; +import { describe, expect, mock, test } from "bun:test"; import { createWalletMenuModule } from "../src/handlers/wallet-menu"; import { applyHoldMarks, createMemoryHoldMarkStore } from "../src/services/hold-marks"; import type { WalletTokenCensus } from "../src/utils/wallet"; @@ -95,6 +95,27 @@ const ensureBalanceCalled = (state: WalletState, expected: number) => expect(state.balanceCalls).toBe(expected); describe("wallet menu cache guards", () => { + test("a superseded fetch cannot drop the newer fetch from the pending cache", async () => { + const { wallet } = createStubWallet(); + const module = createModule(wallet); + const firstResult = Promise.withResolvers(); + const freshResult = Promise.withResolvers(); + const getBalance = mock(async () => 333); + getBalance.mockReturnValueOnce(firstResult.promise).mockReturnValueOnce(freshResult.promise); + wallet.getBalance = getBalance; + const first = module.getCachedWalletData(1n); + wallet.clearCachedWalletData("1"); + const fresh = module.getCachedWalletData(1n); + firstResult.resolve(100); + expect((await first).nativeSolBalance).toBe(100); + + const concurrent = module.getCachedWalletData(1n); + freshResult.resolve(222); + expect((await fresh).nativeSolBalance).toBe(222); + expect((await concurrent).nativeSolBalance).toBe(222); + expect(getBalance).toHaveBeenCalledTimes(2); + }); + test("zero TTL forces repeated RPC calls", async () => { const { wallet, state } = createStubWallet(); const module = createModule(wallet); diff --git a/tests/wallet-menu.page-snapshot.test.ts b/tests/wallet-menu.page-snapshot.test.ts index e58c548c..d25a4378 100644 --- a/tests/wallet-menu.page-snapshot.test.ts +++ b/tests/wallet-menu.page-snapshot.test.ts @@ -115,7 +115,12 @@ describe("wallet page snapshots (stale-while-revalidate)", () => { const module = createModule(wallet); Date.now = () => 3_000_000; await module.getWalletPageData(1n, 0, 8); - Date.now = () => 3_000_000 + WALLET_PAGE_SNAPSHOT_MAX_AGE_MS + 1; + expect(WALLET_PAGE_SNAPSHOT_MAX_AGE_MS).toBe(600_000); + Date.now = () => 3_600_000; + expect(module.peekWalletPageData(1n, 0, 8)).toBeDefined(); + Date.now = () => 3_600_001; + expect(module.peekWalletPageData(1n, 0, 8)).toBeUndefined(); + Date.now = () => 3_600_000; expect(module.peekWalletPageData(1n, 0, 8)).toBeUndefined(); }); @@ -262,9 +267,11 @@ describe("wallet menu caches and limits", () => { const { wallet } = createStubWallet(); const module = createModule(wallet); - for (let user = 1; user <= 5_001; user += 1) { + for (let user = 1; user <= 5_000; user += 1) { await module.getWalletPageData(BigInt(user), 0, 8); } + expect(module.peekWalletPageData(1n, 0, 8)).toBeDefined(); + await module.getWalletPageData(5_001n, 0, 8); expect(module.peekWalletPageData(1n, 0, 8)).toBeUndefined(); expect(module.peekWalletPageData(2n, 0, 8)).toBeDefined(); diff --git a/tests/wallet-transactions.flows.test.ts b/tests/wallet-transactions.flows.test.ts index 4245351d..5de7a2fd 100644 --- a/tests/wallet-transactions.flows.test.ts +++ b/tests/wallet-transactions.flows.test.ts @@ -310,6 +310,24 @@ describe("wrap and unwrap flows", () => { expect(lastText()).toContain("Wrap Failed"); }); + test.each([ + ["a trailing unit", "100lamports"], + ["a fractional value", "100.1"], + ["an exponent", "1e4"], + ["an unsafe integer", "9007199254740993"], + ["a negative value", "-1"], + ["zero", "0"], + ])("rejects a wrap confirmation with %s before moving funds", async (_label, amount) => { + const wraps: unknown[][] = []; + stub(wallet, "wrapSol", async (...args: unknown[]) => { + wraps.push(args); + return "fake-wrap"; + }); + await press(`confirm_wrap_${amount}`, { userId: USER }); + expect(wraps).toEqual([]); + expect(answers().at(-1)).toBe("❌ Wrap failed"); + }); + test("wrap failures and invalid amounts show an error", async () => { stub(wallet, "wrapSol", async () => { throw new Error("rpc down"); diff --git a/tests/wallet-ui.swr.test.ts b/tests/wallet-ui.swr.test.ts index 468f02a9..5d87a4ab 100644 --- a/tests/wallet-ui.swr.test.ts +++ b/tests/wallet-ui.swr.test.ts @@ -30,6 +30,7 @@ const page = (solBalance: number, fetchedAt?: number) => ({ type Setup = { cached?: { data: ReturnType; fetchedAt: number }; fresh?: () => Promise>; + callbackData?: string; callbackMessage?: Record | null; editText?: (...args: any[]) => Promise; editCaption?: (...args: any[]) => Promise; @@ -38,6 +39,7 @@ type Setup = { const run = async (setup: Setup) => { const calls: any[] = []; + const requested: Array<[bigint, number, number]> = []; let fetches = 0; const callbackMessage = setup.callbackMessage === null @@ -52,7 +54,9 @@ const run = async (setup: Setup) => { from: { id: 1 }, me: { id: 42 }, chat: { id: 99, type: "private" }, - callbackQuery: callbackMessage ? { id: "cb", message: callbackMessage } : undefined, + callbackQuery: callbackMessage + ? { id: "cb", data: setup.callbackData, message: callbackMessage } + : undefined, editMessageText: async (...args: any[]) => { calls.push(["ctxEditText", ...args]); return true; @@ -81,8 +85,9 @@ const run = async (setup: Setup) => { getCachedWalletData: async () => { throw new Error("not used"); }, - getWalletPageData: async () => { + getWalletPageData: async (id, pageNumber, pageSize) => { fetches += 1; + requested.push([id, pageNumber, pageSize]); return setup.fresh ? setup.fresh() : page(2e9, NOW); }, peekWalletPageData: () => setup.cached, @@ -98,9 +103,20 @@ const run = async (setup: Setup) => { now: () => NOW, }); await ctx.__walletBackgroundRefresh; - return { calls, captured, fetches: () => fetches }; + return { calls, captured, requested, fetches: () => fetches }; }; +test.each([ + ["wallet_page_12", 12], + ["prefix_wallet_page_12", 0], + ["wallet_page_12_extra", 0], + ["wallet_page_-1", 0], + [undefined, 0], +] as const)("fetches the intended wallet page for %p", async (callbackData, expectedPage) => { + const result = await run({ callbackData }); + expect(result.requested).toEqual([[1n, expectedPage, 8]]); +}); + describe("wallet updated label", () => { test("formats ages", () => { expect(formatWalletUpdatedLabel(NOW, NOW)).toBeNull(); From 6b4541d2dcee1733f3e2b71f2f8992008caf9264 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 11:59:27 -0300 Subject: [PATCH 011/410] test(rpc): cover time limits and failover boundaries --- tests/program-context.test.ts | 16 ++- tests/recent-update.guard.test.ts | 78 ++++++++++- tests/rpc-endpoints.error-paths.test.ts | 39 ++++++ tests/rpc-endpoints.test.ts | 8 +- tests/rpc-request-budget.happy-path.test.ts | 141 +++++++++++++++++++- tests/service-health.test.ts | 30 ++++- tests/swap-provider-retry.test.ts | 49 +++++-- tests/telegram-errors.test.ts | 30 +++++ tests/transaction-fee.test.ts | 2 + 9 files changed, 367 insertions(+), 26 deletions(-) diff --git a/tests/program-context.test.ts b/tests/program-context.test.ts index b79e9591..8314935a 100644 --- a/tests/program-context.test.ts +++ b/tests/program-context.test.ts @@ -118,13 +118,17 @@ describe("loadProgramContext", () => { test("derives the wallet from the trimmed mnemonic option", async () => { const mnemonic = process.env.MNEMONIC!; - - const loaded = await loadProgramContext({ mnemonic: ` ${mnemonic} ` }); - const expected = WalletManager.getInstance(mnemonic); - expect(loaded.wallet).toBe(expected); - expect(loaded.operatorKeypair).toBe(operatorKeypair); - expect(loaded.connection).toBe(expected.getConnection()); + const getWallet = spyOn(WalletManager, "getInstance"); + try { + const loaded = await loadProgramContext({ mnemonic: ` ${mnemonic} ` }); + expect(getWallet.mock.calls).toEqual([[mnemonic]]); + expect(loaded.wallet).toBe(expected); + expect(loaded.operatorKeypair).toBe(operatorKeypair); + expect(loaded.connection).toBe(expected.getConnection()); + } finally { + getWallet.mockRestore(); + } }); test("falls back to the environment mnemonic when the option is blank", async () => { diff --git a/tests/recent-update.guard.test.ts b/tests/recent-update.guard.test.ts index 81c8a261..66d7441c 100644 --- a/tests/recent-update.guard.test.ts +++ b/tests/recent-update.guard.test.ts @@ -1,5 +1,6 @@ -import { afterEach, beforeEach, expect, test } from "bun:test"; -import { recentUpdateGuard } from "../src/utils/recent-update"; +import { afterEach, beforeEach, expect, mock, spyOn, test } from "bun:test"; +import type { Context } from "grammy"; +import { recentUpdateGuard, shouldDropUpdate } from "../src/utils/recent-update"; const ENV_KEYS = ["MAX_CALLBACK_AGE_SEC", "MAX_MESSAGE_AGE_SEC", "MAX_UPDATE_AGE_SEC"] as const; const saved: Record = {}; @@ -50,3 +51,76 @@ test("a failure while answering an expired callback is swallowed and the update expect(nextCalls).toBe(0); }); + +test("the default allows exactly 24 hours for callbacks and 60 seconds for a new message", async () => { + const now = 1_700_000_000; + expect(shouldDropUpdate(now - 86_400, now)).toBe(false); + expect(shouldDropUpdate(now - 86_401, now)).toBe(true); + const clock = spyOn(Date, "now").mockReturnValue(now * 1_000); + try { + const answer = mock(async (_text?: string) => true); + const next = mock(async () => {}); + await recentUpdateGuard( + { + callbackQuery: { id: "old", message: { date: now - 86_400 } }, + answerCallbackQuery: answer, + } as unknown as Context, + next, + ); + await recentUpdateGuard({ message: { date: now - 60 } } as unknown as Context, next); + await recentUpdateGuard({ message: { date: now - 61 } } as unknown as Context, next); + expect(next).toHaveBeenCalledTimes(2); + expect(answer).not.toHaveBeenCalled(); + } finally { + clock.mockRestore(); + } +}); + +test.each([ + ["join_game-id", true], + ["refresh_game-id", true], + ["faucet:claim", true], + ["notjoin_", false], + ["notrefresh_", false], + ["notfaucet:", false], + [undefined, false], +] as const)("only exempts old callbacks with a lifetime-aware prefix %p", async (data, allowed) => { + const now = 1_700_000_000; + const clock = spyOn(Date, "now").mockReturnValue(now * 1_000); + try { + const answer = mock(async (_text?: string) => true); + const next = mock(async () => {}); + await recentUpdateGuard( + { + callbackQuery: { id: "fixture", data, message: { date: now - 86_401 } }, + answerCallbackQuery: answer, + } as unknown as Context, + next, + ); + expect(next).toHaveBeenCalledTimes(allowed ? 1 : 0); + expect(answer.mock.calls).toEqual( + allowed ? [] : [["⏱️ This action expired. Please open a new menu."]], + ); + } finally { + clock.mockRestore(); + } +}); + +test.each([ + ["editedMessage", "edit_date"], + ["channelPost", "date"], + ["editedChannelPost", "edit_date"], +] as const)("uses the timestamp from %s", async (update, dateField) => { + const now = 1_700_000_000; + const clock = spyOn(Date, "now").mockReturnValue(now * 1_000); + try { + const next = mock(async () => {}); + process.env["MAX_UPDATE_AGE_SEC"] = "not numeric"; + process.env["MAX_MESSAGE_AGE_SEC"] = "0"; + await recentUpdateGuard({ [update]: { [dateField]: now - 60 } } as unknown as Context, next); + await recentUpdateGuard({ [update]: { [dateField]: now - 61 } } as unknown as Context, next); + expect(next).toHaveBeenCalledTimes(1); + } finally { + clock.mockRestore(); + } +}); diff --git a/tests/rpc-endpoints.error-paths.test.ts b/tests/rpc-endpoints.error-paths.test.ts index af75bbaf..f0cf945f 100644 --- a/tests/rpc-endpoints.error-paths.test.ts +++ b/tests/rpc-endpoints.error-paths.test.ts @@ -21,6 +21,21 @@ describe("isRetryableRpcError status codes", () => { expect(isRetryableRpcError({ code: 599, message: "weird" })).toBe(true); expect(isRetryableRpcError({ code: 404, message: "missing" })).toBe(false); }); + + test("follows nested causes and stops at a cycle", () => { + expect(isRetryableRpcError(null)).toBe(false); + expect(isRetryableRpcError({ cause: { code: "ETIMEDOUT" } })).toBe(true); + const nested: { cause?: unknown } = { cause: { message: "invalid input" } }; + let reads = 0; + Object.defineProperty(nested, "cause", { + get() { + // Even an instrumented cycle guard must finish this fixture. + return ++reads === 1 ? nested : null; + }, + }); + expect(isRetryableRpcError(nested)).toBe(false); + expect(reads).toBe(1); + }); }); describe("RpcEndpointManager construction", () => { @@ -47,6 +62,30 @@ describe("RpcEndpointManager construction", () => { expect(connection.commitment).toBe("finalized"); expect(Object.prototype.toString.call(connection)).toBe("[object Connection]"); }); + + test("de-duplicates endpoints after whitespace normalization and defaults to confirmed", () => { + const calls: unknown[] = []; + const manager = new RpcEndpointManager( + [ + " https://rpc-first.example ", + "", + "https://rpc-first.example", + "https://rpc-second.example", + ], + { + connectionFactory: (endpoint, commitment) => { + calls.push([endpoint, commitment]); + return asConnection({}); + }, + }, + ); + expect(manager.getAllEndpoints()).toEqual([ + "https://rpc-first.example", + "https://rpc-second.example", + ]); + expect(manager.getConnection().commitment).toBe("confirmed"); + expect(calls).toEqual([["https://rpc-first.example", "confirmed"]]); + }); }); describe("RpcEndpointManager listeners", () => { diff --git a/tests/rpc-endpoints.test.ts b/tests/rpc-endpoints.test.ts index fcb84aba..28658da9 100644 --- a/tests/rpc-endpoints.test.ts +++ b/tests/rpc-endpoints.test.ts @@ -327,17 +327,19 @@ test("subscription removals retain their owner while new listeners follow HTTP f }); const connection = manager.getConnection(); const id = connection.onLogs("all", () => {}); - expect(typeof id).toBe("number"); + expect(id).toBe(1); await connection.getSlot(); expect(manager.getActiveEndpoint()).toBe(endpoints[1]); const replacementId = connection.onLogs("all", () => {}); - expect(typeof replacementId).toBe("number"); - expect(replacementId).not.toBe(id); + expect(replacementId).toBe(2); await connection.removeOnLogsListener(id); await connection.removeOnLogsListener(replacementId); + // Removal of a retired local ID falls back to the active connection. + await connection.removeOnLogsListener(id); expect(registrations).toEqual([endpoints[0], endpoints[1]]); expect(removals).toEqual([ [endpoints[0], 7], [endpoints[1], 7], + [endpoints[1], id], ]); }); diff --git a/tests/rpc-request-budget.happy-path.test.ts b/tests/rpc-request-budget.happy-path.test.ts index 8682506b..3147e0b0 100644 --- a/tests/rpc-request-budget.happy-path.test.ts +++ b/tests/rpc-request-budget.happy-path.test.ts @@ -1,7 +1,9 @@ -import { describe, expect, test } from "bun:test"; +import { describe, expect, spyOn, test, vi } from "bun:test"; import { RpcRetryLaterError, backgroundRpc, + boundedRpc, + foregroundRpc, noteRpcRateLimit, } from "../src/utils/rpc-request-budget"; @@ -35,4 +37,141 @@ describe("backgroundRpc", () => { expect((failure as Error).message).toContain("cooling down"); expect(called).toBe(false); }); + + test("a shorter retry reading cannot shorten the cooldown, and the exact end is permitted", async () => { + const clock = spyOn(Date, "now").mockReturnValue(1_000); + const endpoint = "https://test-exact-cooldown.test/key-a"; + const anotherKey = "https://test-exact-cooldown.test/key-b"; + const signal = new AbortController().signal; + try { + expect(noteRpcRateLimit(endpoint, "7")).toBe(8_000); + expect(noteRpcRateLimit(anotherKey, "1")).toBe(8_000); + clock.mockReturnValue(7_999); + const error = await backgroundRpc(anotherKey, signal, async () => "unexpected").catch( + (failure: unknown) => failure, + ); + expect(error).toMatchObject({ + name: "RpcRetryLaterError", + message: "Recovery RPC is cooling down", + retryAt: 8_000, + }); + clock.mockReturnValue(8_000); + expect(await backgroundRpc(anotherKey, signal, async () => "done")).toBe("done"); + } finally { + clock.mockRestore(); + } + }); + + test("paces two API keys on the same host at 500ms after a failed request", async () => { + vi.useFakeTimers(); + let now = 0; + const clock = spyOn(Date, "now").mockImplementation(() => now); + const controller = new AbortController(); + const hits: Array = []; + const waitForTick = async () => { + for (let step = 0; step < 12; step += 1) await Promise.resolve(); + }; + let second: Promise | undefined; + try { + const scope = "https://test-shared-key-budget.test"; + await expect( + backgroundRpc(`${scope}/one`, controller.signal, async () => { + throw new Error("first request failed"); + }), + ).rejects.toThrow("first request failed"); + second = backgroundRpc(`${scope}/two`, controller.signal, async () => { + hits.push(["same host", now]); + }).catch((error: unknown) => error); + await waitForTick(); + await backgroundRpc( + "https://test-separate-key-budget.test/other", + controller.signal, + async () => { + hits.push(["other host", now]); + }, + ); + for (let tick = 0; tick < 9; tick += 1) { + now += 50; + vi.advanceTimersByTime(50); + await waitForTick(); + } + now += 49; + vi.advanceTimersByTime(49); + await waitForTick(); + expect(hits).toEqual([["other host", 0]]); + now += 1; + vi.advanceTimersByTime(1); + await waitForTick(); + expect(hits).toEqual([ + ["other host", 0], + ["same host", 500], + ]); + } finally { + controller.abort(); + await second; + clock.mockRestore(); + vi.useRealTimers(); + } + }); +}); + +test.each([ + ["missing", null, 6_000], + ["malformed", "later", 6_000], + ["zero", "0", 2_000], + ["a past date", "Thu, 01 Jan 1970 00:00:00 GMT", 2_000], +] as const)("a %s Retry-After uses the documented safe delay", (name, input, expected) => { + expect( + noteRpcRateLimit(`https://retry-${name.replaceAll(" ", "-")}.test/fixture`, input, 1_000), + ).toBe(expected); +}); + +test("bounded RPC stops hanging reads and clears a completed read's timer", async () => { + vi.useFakeTimers(); + const never = Promise.withResolvers(); + try { + expect(await boundedRpc(async () => "done", 9)).toBe("done"); + expect(vi.getTimerCount()).toBe(0); + const outcomes: unknown[] = []; + void boundedRpc(() => never.promise, 7).catch((error: unknown) => { + outcomes.push(error); + }); + vi.advanceTimersByTime(6); + expect(outcomes).toEqual([]); + vi.advanceTimersByTime(1); + for (let step = 0; step < 8; step += 1) await Promise.resolve(); + expect(outcomes).toEqual([expect.objectContaining({ message: "RPC request timed out" })]); + expect(vi.getTimerCount()).toBe(0); + } finally { + never.resolve("cleanup"); + vi.useRealTimers(); + } +}); + +test("a failed foreground request releases the background lane", async () => { + const controller = new AbortController(); + vi.useFakeTimers(); + try { + const error = new Error("request failed"); + await expect( + foregroundRpc(async () => { + throw error; + }), + ).rejects.toBe(error); + const calls: string[] = []; + const task = backgroundRpc( + "https://after-foreground-error.test", + controller.signal, + async () => { + calls.push("started"); + }, + ).catch((failure: unknown) => failure); + for (let step = 0; step < 8; step += 1) await Promise.resolve(); + controller.abort(); + await task; + expect(calls).toEqual(["started"]); + } finally { + controller.abort(); + vi.useRealTimers(); + } }); diff --git a/tests/service-health.test.ts b/tests/service-health.test.ts index a780f6c7..559df1a5 100644 --- a/tests/service-health.test.ts +++ b/tests/service-health.test.ts @@ -1,4 +1,4 @@ -import { expect, test } from "bun:test"; +import { expect, mock, test, vi } from "bun:test"; import { checkServiceHealth } from "../src/utils/service-health"; test("checkServiceHealth returns true on ok: true", async () => { @@ -21,6 +21,34 @@ test("checkServiceHealth handles errors and returns false", async () => { expect(res).toBe(false); }); +test("uses HEAD and aborts an unanswered health request at the default deadline", async () => { + vi.useFakeTimers(); + const handleResult = Promise.withResolvers(); + const probe = mock(async (_input: RequestInfo | URL, init?: RequestInit) => { + const signal = init?.signal; + if (signal) { + signal.addEventListener("abort", () => handleResult.reject(signal.reason), { once: true }); + } + return handleResult.promise; + }); + const url = "https://example.test/health"; + const health = checkServiceHealth(url, undefined, probe); + try { + const signal = probe.mock.calls[0]?.[1]?.signal ?? undefined; + expect(probe.mock.calls).toEqual([[url, { method: "HEAD", signal }]]); + expect(signal).toBeInstanceOf(AbortSignal); + vi.advanceTimersByTime(4_999); + expect(signal?.aborted).toBe(false); + vi.advanceTimersByTime(1); + expect(signal?.aborted).toBe(true); + expect(await health).toBe(false); + } finally { + handleResult.resolve(new Response(null, { status: 200 })); + await health; + vi.useRealTimers(); + } +}); + test("checkServiceHealth clears timeout when fetch rejects", async () => { const originalSetTimeout = globalThis.setTimeout; const originalClearTimeout = globalThis.clearTimeout; diff --git a/tests/swap-provider-retry.test.ts b/tests/swap-provider-retry.test.ts index 33d319c4..7240a4b9 100644 --- a/tests/swap-provider-retry.test.ts +++ b/tests/swap-provider-retry.test.ts @@ -1,4 +1,4 @@ -import { describe, expect, test } from "bun:test"; +import { describe, expect, spyOn, test, vi } from "bun:test"; import { SWAP_QUOTE_RETRY_LABEL, SWAP_QUOTE_RETRY_PREFIX, @@ -19,6 +19,7 @@ describe("isSwapProviderUnavailableError", () => { ["error code", Object.assign(new Error("connect"), { code: "ECONNRESET" })], ["undici code", Object.assign(new Error("x"), { code: "UND_ERR_CONNECT_TIMEOUT" })], ["http 503", new Error("Jupiter order failed: 503 Service Unavailable - upstream")], + ["http 502 without a reason phrase", new Error("Jupiter build failed: 502")], ["http 429", new Error("Jupiter build failed: 429 Too Many Requests - slow down")], ["network", new Error("fetch failed")], [ @@ -36,6 +37,13 @@ describe("isSwapProviderUnavailableError", () => { ["no route", new Error("Jupiter order error (code 1): No routes found")], ["http 400", new Error("Jupiter order failed: 400 Bad Request - invalid mint")], ["balance", new Error("Insufficient balance to attempt this swap.")], + ["malformed http status", new Error("Jupiter build failed: 5xx")], + ["embedded code text", Object.assign(new Error("rejected"), { code: "NON_ECONNRESET" })], + ["unrelated code", Object.assign(new Error("rejected"), { code: "INVALID_INPUT" })], + [ + "non-string code", + Object.assign(new Error("rejected"), { code: { toString: () => "ECONNRESET" } }), + ], ["null", null], ["undefined", undefined], ])("ignores %s", (_label, error) => { @@ -43,9 +51,11 @@ describe("isSwapProviderUnavailableError", () => { }); test("survives cyclic causes", () => { - const error: any = new Error("Jupiter order error: route"); - error.cause = error; + const error = new Error("Jupiter order error: route"); + let reads = 0; + Object.defineProperty(error, "cause", { get: () => (++reads === 1 ? error : undefined) }); expect(isSwapProviderUnavailableError(error)).toBe(false); + expect(reads).toBe(1); }); }); @@ -68,16 +78,29 @@ describe("swap quote retry store", () => { expect(store.get(callback.slice(SWAP_QUOTE_RETRY_PREFIX.length))).toBeUndefined(); }); - test("entries expire", async () => { - const store = createSwapQuoteRetryStore(5); - const callback = store.save({ - userId: "1", - fromTokenIdentifier: "A", - toToken: "B", - amount: "1", - }); - await new Promise((resolve) => setTimeout(resolve, 20)); - expect(store.get(callback.slice(SWAP_QUOTE_RETRY_PREFIX.length))).toBeUndefined(); + test.each([ + ["default five-minute", undefined, 300_000], + ["custom", 5, 5], + ] as const)("a retry stays available until the exact %s limit", (_label, ttl, expectedMs) => { + vi.useFakeTimers(); + let now = 10_000; + const clock = spyOn(Date, "now").mockImplementation(() => now); + const store = createSwapQuoteRetryStore(ttl); + try { + const request = { userId: "1", fromTokenIdentifier: "A", toToken: "B", amount: "1" }; + const callback = store.save(request); + const id = callback.slice(SWAP_QUOTE_RETRY_PREFIX.length); + now += expectedMs - 1; + vi.advanceTimersByTime(expectedMs - 1); + expect(store.get(id)).toEqual(request); + now += 1; + vi.advanceTimersByTime(1); + expect(store.get(id)).toBeUndefined(); + } finally { + store.clear(); + clock.mockRestore(); + vi.useRealTimers(); + } }); }); diff --git a/tests/telegram-errors.test.ts b/tests/telegram-errors.test.ts index ae765fdf..5ddfdb32 100644 --- a/tests/telegram-errors.test.ts +++ b/tests/telegram-errors.test.ts @@ -96,6 +96,14 @@ describe("telegram error helpers", () => { ).toBe(true); }); + test("requires a Telegram 403 rather than similar text or a non-Telegram error code", () => { + const description = "Forbidden: bot can't initiate conversation with a user"; + expect(isBotInitiationForbidden(description)).toBe(false); + expect(isBotInitiationForbidden(null)).toBe(false); + expect(isBotInitiationForbidden({ error_code: 400, description })).toBe(false); + expect(isBotInitiationForbidden({ error_code: 403, description: "other reason" })).toBe(false); + }); + test("isRateLimited detects 429 and retry-after messages", () => { expect(isRateLimited({ error_code: 429, description: "Too Many Requests" })).toBe(true); expect(isRateLimited({ description: "Too Many Requests: retry after 3" })).toBe(true); @@ -103,6 +111,13 @@ describe("telegram error helpers", () => { expect(isRateLimited("not a rate limit")).toBe(false); }); + test("recognizes a bare numeric 429 and otherwise uses the response text", () => { + expect(isRateLimited({ error_code: 429 })).toBe(true); + expect(isRateLimited({ error_code: 400 })).toBe(false); + expect(isRateLimited(null)).toBe(false); + expect(isRateLimited({ message: "Retry After 123" })).toBe(true); + }); + test("getRetryAfterSeconds reads retry_after from Telegram error objects and descriptions", () => { expect(getRetryAfterSeconds({ error_code: 429, parameters: { retry_after: 7 } })).toBe(7); expect(getRetryAfterSeconds({ retry_after: 2 })).toBe(2); @@ -111,4 +126,19 @@ describe("telegram error helpers", () => { expect(getRetryAfterSeconds({ description: "Too Many Requests" })).toBeNull(); expect(getRetryAfterSeconds("retry after 9")).toBeNull(); }); + + test("prefers the structured delay, keeps zero, and reads the whole fallback delay", () => { + const description = "Too Many Requests: retry after 123"; + expect( + getRetryAfterSeconds({ parameters: { retry_after: 0 }, retry_after: 7, description }), + ).toBe(0); + expect(getRetryAfterSeconds({ parameters: { retry_after: -2 }, description })).toBe(0); + expect( + getRetryAfterSeconds({ parameters: { retry_after: "4" }, retry_after: 7, description }), + ).toBe(7); + expect(getRetryAfterSeconds({ parameters: { retry_after: NaN }, description })).toBe(123); + expect(getRetryAfterSeconds({ retry_after: Infinity, description })).toBe(123); + expect(getRetryAfterSeconds({ description })).toBe(123); + expect(getRetryAfterSeconds(null)).toBeNull(); + }); }); diff --git a/tests/transaction-fee.test.ts b/tests/transaction-fee.test.ts index 7142a68c..43a9601d 100644 --- a/tests/transaction-fee.test.ts +++ b/tests/transaction-fee.test.ts @@ -46,6 +46,7 @@ describe("getConfirmedTransactionFeeLamports", () => { test.each([ ["missing transaction", null], ["missing meta", {}], + ["null meta", { meta: null }], ["non-numeric fee", { meta: { fee: "5000" } }], ["negative fee", { meta: { fee: -1 } }], ["fractional fee", { meta: { fee: 1.5 } }], @@ -54,6 +55,7 @@ describe("getConfirmedTransactionFeeLamports", () => { expect( await getConfirmedTransactionFeeLamports(connectionReturning(value) as any, "sig"), ).toBeNull(); + expect(warnSpy).not.toHaveBeenCalled(); }); test("returns null and warns when the RPC call fails", async () => { From 1d4095fb8f2b3f1e5d43e304be3790741c4799db Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 12:06:55 -0300 Subject: [PATCH 012/410] fix(swaps): isolate quotes and reject invalid surcharge values --- src/utils/admin-payer-surcharge.ts | 5 +- src/utils/integrator-fees.ts | 3 +- src/utils/swap/quote-cache.ts | 6 ++- tests/admin-payer-surcharge.test.ts | 6 ++- tests/integrator-fees.test.ts | 26 ++++++++++ tests/route-cost.test.ts | 33 +++++++++++++ tests/swap-quote-cache.test.ts | 50 ++++++++++++++++++- tests/token-display.test.ts | 44 +++++++++++++++++ tests/token-programs.test.ts | 29 ++++++++++- tests/verified-token-registry.test.ts | 70 ++++++++++++++++++++++++++- 10 files changed, 264 insertions(+), 8 deletions(-) create mode 100644 tests/token-display.test.ts diff --git a/src/utils/admin-payer-surcharge.ts b/src/utils/admin-payer-surcharge.ts index 20cd2c0c..bcfcb78b 100644 --- a/src/utils/admin-payer-surcharge.ts +++ b/src/utils/admin-payer-surcharge.ts @@ -34,6 +34,9 @@ export interface ReferralFeeCalculationOptions { maxFeeBps?: number; } +export const hasUsableReferralFeeValues = (tradeUsd: number, deficitUsd: number): boolean => + Number.isFinite(tradeUsd) && tradeUsd > 0 && Number.isFinite(deficitUsd) && deficitUsd > 0; + export const calculateReferralFeeBps = (options: ReferralFeeCalculationOptions): number => { const { baseFeeBps, @@ -44,7 +47,7 @@ export const calculateReferralFeeBps = (options: ReferralFeeCalculationOptions): maxFeeBps = MAX_REFERRAL_FEE_BPS, } = options; - if (tradeUsd <= 0 || deficitUsd <= 0) { + if (!hasUsableReferralFeeValues(tradeUsd, deficitUsd)) { throw new Error( "Cannot estimate referral surcharge for gas payer. Please top up SOL or try a larger trade.", ); diff --git a/src/utils/integrator-fees.ts b/src/utils/integrator-fees.ts index 3a81daf3..bc1fb6c5 100644 --- a/src/utils/integrator-fees.ts +++ b/src/utils/integrator-fees.ts @@ -4,6 +4,7 @@ import { getUsdPrice } from "./price-service"; import { clampReferralFeeBps, calculateReferralFeeBps, + hasUsableReferralFeeValues, DEFAULT_REFERRAL_BASE_FEE_BPS, DEFAULT_MAX_EXTRA_FEE_BPS, MAX_REFERRAL_FEE_BPS, @@ -126,7 +127,7 @@ export async function calculateDynamicReferralFee(context: DynamicFeeContext): P ); const deficitUsd = await estimateSolUsdValue(shortfallLamports); - if (tradeUsd <= 0 || deficitUsd <= 0) { + if (!hasUsableReferralFeeValues(tradeUsd, deficitUsd)) { if (throwOnPriceFailure) { throw new Error( "Cannot estimate referral surcharge for gas payer. Please top up SOL or try a larger trade.", diff --git a/src/utils/swap/quote-cache.ts b/src/utils/swap/quote-cache.ts index 7be7b984..9f308d00 100644 --- a/src/utils/swap/quote-cache.ts +++ b/src/utils/swap/quote-cache.ts @@ -55,6 +55,7 @@ export class SwapQuoteCache { amount, taker, platformFeeBps = 0, + feeAccount, maxAccounts = 0, onlyDirectRoutes = false, swapMode = "ExactIn", @@ -62,6 +63,7 @@ export class SwapQuoteCache { referralFee, payer, closeAuthority, + slippageBps, } = params; return JSON.stringify({ @@ -70,6 +72,7 @@ export class SwapQuoteCache { amount, taker, platformFeeBps, + feeAccount, maxAccounts, onlyDirectRoutes, swapMode, @@ -77,6 +80,7 @@ export class SwapQuoteCache { referralFee, payer, closeAuthority, - }); + slippageBps, + } satisfies Record); } } diff --git a/tests/admin-payer-surcharge.test.ts b/tests/admin-payer-surcharge.test.ts index ecafba5f..572afd92 100644 --- a/tests/admin-payer-surcharge.test.ts +++ b/tests/admin-payer-surcharge.test.ts @@ -173,7 +173,11 @@ describe("calculateReferralFeeBps", () => { ["negative trade value", -5, 1], ["zero deficit", 100, 0], ["negative deficit", 100, -1], - ])("refuses to estimate with a %s", (_label, tradeUsd, deficitUsd) => { + ["infinite trade value", Infinity, 1], + ["infinite deficit", 100, Infinity], + ["NaN trade value", NaN, 1], + ["NaN deficit", 100, NaN], + ])("refuses to estimate with %s", (_label, tradeUsd, deficitUsd) => { expect(() => calculateReferralFeeBps({ baseFeeBps: 100, tradeUsd, deficitUsd })).toThrow( "Cannot estimate referral surcharge", ); diff --git a/tests/integrator-fees.test.ts b/tests/integrator-fees.test.ts index d94f577c..152cad34 100644 --- a/tests/integrator-fees.test.ts +++ b/tests/integrator-fees.test.ts @@ -502,6 +502,32 @@ describe("calculateDynamicReferralFee", () => { ).rejects.toThrow("Cannot estimate referral surcharge for gas payer."); }); + test.each([ + ["infinite token quote", Infinity, 40], + ["NaN token quote", NaN, 40], + ["infinite SOL quote", 1, Infinity], + ["NaN SOL quote", 1, NaN], + ] as const)( + "does not calculate a surcharge from a non-finite %s", + async (_label, tokenPrice, solPrice) => { + vi.spyOn(priceService, "getUsdPrice").mockImplementation(async ({ tokenMint }) => + priceLookup(tokenMint === WSOL_MINT ? solPrice : tokenPrice, "fixture"), + ); + const input = { + inputMint: ADMIN_REF_MINT1, + inputTicker: "TKN", + inputDecimals: 6, + inputAmountRaw: 10_000_000, + shortfallLamports: 5_000_000, + baseFeeBps: 85, + }; + await expect( + calculateDynamicReferralFee({ ...input, throwOnPriceFailure: true }), + ).rejects.toThrow("Cannot estimate referral surcharge for gas payer"); + expect(await calculateDynamicReferralFee(input)).toBe(85); + }, + ); + describe("when the input token has no price but SOL does", () => { beforeEach(() => { vi.spyOn(priceService, "getUsdPrice").mockImplementation(async (opts: any) => diff --git a/tests/route-cost.test.ts b/tests/route-cost.test.ts index 9f2868a5..5eac3e4d 100644 --- a/tests/route-cost.test.ts +++ b/tests/route-cost.test.ts @@ -10,6 +10,39 @@ const buildCosts = (routeLamports: number) => ({ }); describe("calculateRouteCosts", () => { + test("uses the default ceil rounding and max strategy without a config", () => { + expect(calculateRouteCosts({ rentFeeLamports: 3, prioritizationFeeLamports: 2 })).toEqual({ + routeLamports: 5, + paddingLamports: 2, + requiredLamports: 5, + }); + expect(calculateRouteCosts(null)).toEqual({ + routeLamports: 0, + paddingLamports: 0, + requiredLamports: 0, + }); + }); + + test("supports nearest rounding and applies the minimum only for a nonzero route", () => { + expect( + calculateRouteCosts(buildCosts(5), { + paddingRounding: "round", + requiredStrategy: "sum", + baseRequiredLamports: 10, + }), + ).toEqual({ routeLamports: 5, paddingLamports: 1, requiredLamports: 16 }); + expect(calculateRouteCosts(buildCosts(5), { minPaddingLamports: 9 })).toEqual({ + routeLamports: 5, + paddingLamports: 9, + requiredLamports: 9, + }); + expect(calculateRouteCosts(buildCosts(0), { minPaddingLamports: 9 })).toEqual({ + routeLamports: 0, + paddingLamports: 0, + requiredLamports: 0, + }); + }); + test("handles rent-heavy routes for user payer", () => { const costs = calculateRouteCosts(buildCosts(2_310_000), { paddingRatio: 0.25, diff --git a/tests/swap-quote-cache.test.ts b/tests/swap-quote-cache.test.ts index 732e9c73..675df4b2 100644 --- a/tests/swap-quote-cache.test.ts +++ b/tests/swap-quote-cache.test.ts @@ -1,8 +1,56 @@ -import { describe, test, expect } from "bun:test"; +import { describe, test, expect, mock, spyOn, vi } from "bun:test"; import { SwapQuoteCache } from "../src/utils/swap/quote-cache"; import { makeJupiterParams, makeJupiterQuote } from "./helpers/jupiter-factories"; describe("SwapQuoteCache", () => { + test.each([ + ["a different slippage limit", { slippageBps: 100 }, { slippageBps: 200 }], + [ + "a different fee account", + { feeAccount: "payer-fixture-a" }, + { feeAccount: "payer-fixture-b" }, + ], + ["direct versus indirect routes", { onlyDirectRoutes: true }, { onlyDirectRoutes: false }], + ["exact in versus exact out", { swapMode: "ExactIn" }, { swapMode: "ExactOut" }], + ] as const)("keeps quotes separate for %s", async (_label, first, second) => { + const cache = new SwapQuoteCache(); + const a = makeJupiterParams(first); + const b = makeJupiterParams(second); + const loadA = mock(async () => makeJupiterQuote(a, { outAmount: "111" })); + const loadB = mock(async () => makeJupiterQuote(b, { outAmount: "222" })); + expect((await cache.getJupiterQuote(a, loadA)).outAmount).toBe("111"); + expect((await cache.getJupiterQuote(b, loadB)).outAmount).toBe("222"); + expect(loadB).toHaveBeenCalledTimes(1); + }); + + test.each([ + ["default", undefined, 5_000], + ["zero", 0, 5_000], + ["infinity", Infinity, 5_000], + ["custom", 10, 10], + ] as const)("honors the expected expiry for %s TTL", async (_label, ttlMs, delay) => { + vi.useFakeTimers(); + let now = 10_000; + const time = spyOn(Date, "now").mockImplementation(() => now); + const cache = new SwapQuoteCache({ ttlMs }); + const params = makeJupiterParams(); + const loader = mock(async () => makeJupiterQuote(params)); + try { + await cache.getJupiterQuote(params, loader); + now += delay - 1; + vi.advanceTimersByTime(delay - 1); + await cache.getJupiterQuote(params, loader); + expect(loader).toHaveBeenCalledTimes(1); + now += 1; + vi.advanceTimersByTime(1); + await cache.getJupiterQuote(params, loader); + expect(loader).toHaveBeenCalledTimes(2); + } finally { + time.mockRestore(); + vi.useRealTimers(); + } + }); + test("coalesces concurrent Jupiter quote requests", async () => { const cache = new SwapQuoteCache({ ttlMs: 5_000 }); const params = makeJupiterParams(); diff --git a/tests/token-display.test.ts b/tests/token-display.test.ts new file mode 100644 index 00000000..15cece24 --- /dev/null +++ b/tests/token-display.test.ts @@ -0,0 +1,44 @@ +import { expect, test } from "bun:test"; +import { + abbreviateMint, + resolveTokenDisplaySymbols, + sanitizeTokenSymbol, + truncateTokenDisplay, +} from "../src/utils/token-display"; + +test.each([ + [undefined, "TOKEN"], + [" ", "TOKEN"], + [" 1234567890 ", "1234567890"], + [" 12345678901 ", "1234…8901"], +] as const)("shows a stable mint fallback for %p", (mint, expected) => { + expect(abbreviateMint(mint)).toBe(expected); +}); + +test("normalizes token metadata and cuts after nine whole graphemes only when needed", () => { + expect(sanitizeTokenSymbol(" ABC D\u200B ")).toBe("ABC D"); + expect(sanitizeTokenSymbol(undefined)).toBe("TOKEN"); + expect(sanitizeTokenSymbol("1234567890")).toBe("1234567890"); + const grapheme = "x\u0301"; + expect(sanitizeTokenSymbol(grapheme.repeat(11))).toBe(grapheme.repeat(9) + "…"); +}); + +test("truncates general display text by grapheme instead of UTF-16 code units", () => { + const grapheme = "e\u0301"; + expect(truncateTokenDisplay(` \u200B${grapheme.repeat(2)} `, 2)).toBe(grapheme.repeat(2)); + expect(truncateTokenDisplay(grapheme.repeat(3), 2)).toBe(grapheme + "…"); + expect(truncateTokenDisplay(grapheme, 0)).toBe("…"); + expect(truncateTokenDisplay(null)).toBe(""); + expect(truncateTokenDisplay("x".repeat(64))).toBe("x".repeat(64)); + expect(truncateTokenDisplay("x".repeat(65))).toBe("x".repeat(63) + "…"); +}); + +test("adds the mint only to tickers that collide after normalization", () => { + expect( + resolveTokenDisplaySymbols([ + { ticker: "ABC", mint: "12345678901" }, + { ticker: " ABC ", mint: "mnopqrstuvw" }, + { ticker: "XYZ", mint: "98765432101" }, + ]), + ).toEqual(["ABC (1234…8901)", "ABC (mnop…tuvw)", "XYZ"]); +}); diff --git a/tests/token-programs.test.ts b/tests/token-programs.test.ts index ec70b2b7..f5793c46 100644 --- a/tests/token-programs.test.ts +++ b/tests/token-programs.test.ts @@ -1,6 +1,6 @@ import { describe, test, expect, spyOn } from "bun:test"; -import { PublicKey } from "#solana"; -import { TOKEN_2022_PROGRAM_ID } from "#token"; +import { Connection, PublicKey } from "#solana"; +import { TOKEN_2022_PROGRAM_ID, TOKEN_PROGRAM_ID } from "#token"; import { detectTokenProgram } from "../src/utils/token-programs"; class StubConnection { @@ -53,6 +53,31 @@ describe("detectTokenProgram", () => { expect(result!.programId.equals(TOKEN_2022_PROGRAM_ID)).toBe(true); }); + test("recognizes a preloaded legacy owner and does not guess a malformed owner", async () => { + const mint = "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"; + const connection = new Connection("http://localhost:8899"); + const getAccount = spyOn(connection, "getAccountInfo").mockRejectedValue( + new Error("unexpected lookup"), + ); + const report = spyOn(console, "log").mockImplementation(() => {}); + try { + expect(await detectTokenProgram(connection, mint, { owner: TOKEN_PROGRAM_ID })).toEqual({ + programId: TOKEN_PROGRAM_ID, + isToken2022: false, + }); + await expect( + detectTokenProgram(connection, mint, { + owner: "provider-owner-string" as unknown as PublicKey, + }), + ).rejects.toThrow( + `Token mint ${mint} is owned by an unknown program (provider-owner-string)`, + ); + expect(getAccount).not.toHaveBeenCalled(); + } finally { + report.mockRestore(); + } + }); + test("returns null when mint account is missing", async () => { const mint = new PublicKey("2zsB6q5fkvMS4L7HhQTF19EaiqRkJWhGXZ6Q3A1tqhzd"); const conn = new StubConnection({ [mint.toBase58()]: null }); diff --git a/tests/verified-token-registry.test.ts b/tests/verified-token-registry.test.ts index ac4aeb61..ed8ff569 100644 --- a/tests/verified-token-registry.test.ts +++ b/tests/verified-token-registry.test.ts @@ -1,5 +1,6 @@ -import { afterEach, beforeEach, describe, expect, test } from "bun:test"; +import { afterEach, beforeEach, describe, expect, spyOn, test, vi } from "bun:test"; import { existsSync, mkdirSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs"; +import { dirname } from "node:path"; import { __test_reloadVerifiedTokenSnapshot, __test_setVerifiedTokenMints, @@ -76,6 +77,73 @@ describe("verified token registry refresh", () => { expect(requests).toHaveLength(1); }); + test("refreshes at six hours, makes one in-flight request, and trims the API key", async () => { + const start = 45_000; + const clock = spyOn(Date, "now").mockReturnValue(start); + const response = Promise.withResolvers(); + const first = Response.json([{ id: BONK }]); + try { + process.env["JUPITER_API_KEY"] = " test-key "; + respondWith(() => (requests.length === 1 ? response.promise : Response.json([{ id: USDC }]))); + getVerifiedTokenMints(); + getVerifiedTokenMints(); + expect(requests).toHaveLength(1); + expect((requests[0]?.init?.headers as Record)["x-api-key"]).toBe("test-key"); + response.resolve(first); + await __test_waitForVerifiedTokenRefresh(); + clock.mockReturnValue(start + 21_600_000 - 1); + expect(getVerifiedTokenMints().has(BONK)).toBe(true); + expect(requests).toHaveLength(1); + clock.mockReturnValue(start + 21_600_000); + await refresh(); + expect(requests).toHaveLength(2); + } finally { + response.resolve(first); + await __test_waitForVerifiedTokenRefresh(); + clock.mockRestore(); + } + }); + + test("aborts the provider request at the deadline and keeps local mints", async () => { + vi.useFakeTimers(); + const answer = Promise.withResolvers(); + try { + respondWith(() => { + const signal = requests[0]?.init?.signal; + signal?.addEventListener("abort", () => answer.reject(signal.reason), { once: true }); + return answer.promise; + }); + getVerifiedTokenMints(); + const signal = requests[0]?.init?.signal; + expect(signal).toBeInstanceOf(AbortSignal); + vi.advanceTimersByTime(2_999); + expect(signal?.aborted).toBe(false); + vi.advanceTimersByTime(1); + expect(signal?.aborted).toBe(true); + await __test_waitForVerifiedTokenRefresh(); + for (const mint of localMints()) expect(getVerifiedTokenMints().has(mint)).toBe(true); + } finally { + answer.resolve(Response.json([])); + await __test_waitForVerifiedTokenRefresh(); + vi.useRealTimers(); + } + }); + + test("stores snapshots under the configured database directory after trimming it", async () => { + const original = process.env["BOT_DB_DIR"]; + const modulePath = "../src/utils/verified-token-registry.ts"; + try { + process.env["BOT_DB_DIR"] = ` ${dirname(__test_snapshotPath)} `; + const registry: typeof import("../src/utils/verified-token-registry") = await import( + `${modulePath}?custom-database-directory` + ); + expect(registry.__test_snapshotPath).toBe(__test_snapshotPath); + } finally { + if (original === undefined) delete process.env["BOT_DB_DIR"]; + else process.env["BOT_DB_DIR"] = original; + } + }); + test("a persisted snapshot is loaded on the next start", async () => { respondWith(() => Response.json([{ id: BONK }])); await refresh(); From e831a4738564103910bba987991749518fb3253d Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 12:12:52 -0300 Subject: [PATCH 013/410] fix(games): preserve games omitted from a batch result --- src/bot/expired-game-scan.ts | 4 +- src/utils/price-service.ts | 42 +++----------- tests/expired-game-scan.test.ts | 76 ++++++++++++++++++++---- tests/game-settings.privacy.test.ts | 34 ++++++++++- tests/keypairs.test.ts | 25 +++++++- tests/token-price-cache.test.ts | 31 ++++++++++ tests/transaction-runner.test.ts | 89 ++++++++++++++++++++++++++++- 7 files changed, 250 insertions(+), 51 deletions(-) diff --git a/src/bot/expired-game-scan.ts b/src/bot/expired-game-scan.ts index 6f72bf00..6df1bb9b 100644 --- a/src/bot/expired-game-scan.ts +++ b/src/bot/expired-game-scan.ts @@ -72,7 +72,9 @@ export const createExpiredGameScanner = (deps: ExpiredGameScanDeps) => { try { const accounts = await api.fetchMultiple(candidates.map((candidate) => candidate.gamePda)); candidates.forEach((candidate, index) => { - loaded.set(candidate.game.game_address, accounts[index] ?? null); + const account = accounts[index]; + // Only an explicit null reports absence. Retry omitted entries individually. + if (account !== undefined) loaded.set(candidate.game.game_address, account); }); } catch (error) { console.warn("Batch expired-game lookup failed; checking games individually:", error); diff --git a/src/utils/price-service.ts b/src/utils/price-service.ts index 584d5c1b..82482526 100644 --- a/src/utils/price-service.ts +++ b/src/utils/price-service.ts @@ -18,35 +18,15 @@ const normalize = (value?: string | null): string | null => { return trimmed; }; -const buildCacheKeys = (request: PriceLookupRequest): string[] => { - const keys = new Set(); - const normalizedMint = normalize(request.tokenMint); - - if (normalizedMint) { - keys.add(normalizedMint); - } - - return Array.from(keys.values()); -}; - const isHintFresh = (hint: CachedPriceLookup): boolean => { const now = Date.now(); return now - hint.resolvedAt <= TOKEN_PRICE_CACHE_TTL_MS; }; const matchesRequest = (hint: CachedPriceLookup, request: PriceLookupRequest): boolean => { - const keys = buildCacheKeys(request); - const hintKeys = new Set( - buildCacheKeys({ - tokenMint: hint.tokenMint, - }), - ); - - if (keys.length === 0) { - return hintKeys.size > 0; - } - - return keys.some((key) => hintKeys.has(key)); + const requestMint = normalize(request.tokenMint); + const hintMint = normalize(hint.tokenMint); + return hintMint !== null && (requestMint === null || requestMint === hintMint); }; export function rememberPriceLookup( @@ -59,23 +39,15 @@ export function rememberPriceLookup( resolvedAt: (lookup as CachedPriceLookup).resolvedAt ?? Date.now(), }; - const keys = buildCacheKeys(request); - for (const key of keys) { - priceCache.setWithTTL(key, entry); - } + const key = normalize(request.tokenMint); + if (key !== null) priceCache.setWithTTL(key, entry); return entry; } export function getCachedPriceLookup(request: PriceLookupRequest): CachedPriceLookup | null { - const keys = buildCacheKeys(request); - for (const key of keys) { - const cached = priceCache.get(key); - if (cached) { - return cached; - } - } - return null; + const key = normalize(request.tokenMint); + return key === null ? null : (priceCache.get(key) ?? null); } const maybeUseHint = ( diff --git a/tests/expired-game-scan.test.ts b/tests/expired-game-scan.test.ts index 2e75b165..fbee19f6 100644 --- a/tests/expired-game-scan.test.ts +++ b/tests/expired-game-scan.test.ts @@ -1,4 +1,4 @@ -import { describe, expect, test, vi } from "bun:test"; +import { describe, expect, spyOn, test, vi } from "bun:test"; import { Keypair, PublicKey } from "#solana"; import { createExpiredGameScanner, type ExpiredGameScanDeps } from "../src/bot/expired-game-scan"; import { DEFAULT_NULL_ADDRESS } from "../src/utils/constants"; @@ -150,6 +150,44 @@ describe("createExpiredGameScanner", () => { expect(deps.handleExpiredGame).toHaveBeenCalledTimes(1); }); + test("falls back for an omitted batch entry without deleting the stored game", async () => { + const [present, omitted] = await Promise.all([address(), address()]); + const api = { + fetchMultiple: vi.fn(async (_keys: PublicKey[]) => [{ expired: true }]), + fetch: vi.fn(async (_key: PublicKey) => ({ expired: true })), + }; + const deps = createDeps({ + getGamesExpiringBefore: vi.fn(() => [game(present), game(omitted)]), + gameAccounts: () => api, + }); + + await createExpiredGameScanner(deps).scan(); + + expect(api.fetchMultiple).toHaveBeenCalledWith([ + new PublicKey(present), + new PublicKey(omitted), + ]); + expect(api.fetch.mock.calls.map(([key]) => key.toBase58())).toEqual([omitted]); + expect(deps.cleanupOrphanedGame).not.toHaveBeenCalled(); + expect(deps.handleExpiredGame).toHaveBeenCalledTimes(2); + }); + + test("passes the exact exclusion list and stops after the default ten batches", async () => { + const addresses = await Promise.all(Array.from({ length: 11 }, address)); + const snapshots: string[][] = []; + const deps = createDeps({ + batchSize: 1, + getGamesExpiringBefore: (_cutoff, _limit, exclude) => { + const key = addresses[snapshots.length]; + snapshots.push([...exclude]); + return key ? [game(key)] : []; + }, + }); + await createExpiredGameScanner(deps).scan(); + expect(snapshots).toEqual(Array.from({ length: 10 }, (_, index) => addresses.slice(0, index))); + expect(deps.handleExpiredGame).toHaveBeenCalledTimes(10); + }); + test("skips a tick while the previous scan is still running", async () => { let release: () => void = () => {}; const gate = new Promise((resolve) => { @@ -163,25 +201,43 @@ describe("createExpiredGameScanner", () => { }); const scanner = createExpiredGameScanner(deps); + const announce = spyOn(console, "log").mockImplementation(() => {}); const first = scanner.scan(); - await scanner.scan(); - expect(deps.getBlockchainTime).toHaveBeenCalledTimes(1); - - release(); - await first; + const overlapping = scanner.scan(); + try { + await Promise.resolve(); + expect(deps.getBlockchainTime).toHaveBeenCalledTimes(1); + expect(announce.mock.calls).toEqual([ + ["⏭️ Expired-game scan still running; skipping this tick"], + ]); + } finally { + release(); + await Promise.all([first, overlapping]); + announce.mockRestore(); + } await scanner.scan(); expect(deps.getBlockchainTime).toHaveBeenCalledTimes(2); }); test("logs and recovers from an unexpected scan failure", async () => { + const failure = new Error("db locked"); const deps = createDeps({ getGamesExpiringBefore: vi.fn(() => { - throw new Error("db locked"); + throw failure; }), }); const scanner = createExpiredGameScanner(deps); - await scanner.scan(); - await scanner.scan(); - expect(deps.getGamesExpiringBefore).toHaveBeenCalledTimes(2); + const report = spyOn(console, "error").mockImplementation(() => {}); + try { + await scanner.scan(); + await scanner.scan(); + expect(deps.getGamesExpiringBefore).toHaveBeenCalledTimes(2); + expect(report.mock.calls).toEqual([ + ["Error in periodic game check:", failure], + ["Error in periodic game check:", failure], + ]); + } finally { + report.mockRestore(); + } }); }); diff --git a/tests/game-settings.privacy.test.ts b/tests/game-settings.privacy.test.ts index f4ee0936..02a5061e 100644 --- a/tests/game-settings.privacy.test.ts +++ b/tests/game-settings.privacy.test.ts @@ -1,6 +1,11 @@ import { describe, expect, test } from "bun:test"; -import { resolveAdvancedOptions, resolveGamePrivacy } from "../src/utils/game-settings"; +import { + clampMinPlayers, + clampTimeoutSeconds, + resolveAdvancedOptions, + resolveGamePrivacy, +} from "../src/utils/game-settings"; import type { ChatGameSettings } from "../src/types"; const chat = (privacy: Partial): ChatGameSettings => ({ @@ -100,3 +105,30 @@ describe("resolveAdvancedOptions privacy", () => { ); }); }); + +describe("game limits", () => { + test.each([ + ["coinflip", 9, 8, 4, 4], + ["coinflip", 9, 4, 8, 4], + ["coinflip", 9, 8, 0, 2], + ["coinflip", 2.5, 8, 4, 3], + ["giveaway", 0, 8, 4, 1], + ["giveaway", NaN, 8, undefined, 1], + ] as const)( + "keeps a %s player minimum of %p within %p/%p", + (kind, requested, max, limit, expected) => { + expect(clampMinPlayers(kind, requested, max, limit)).toBe(expected); + }, + ); + + test.each([ + [undefined, 3_600], + [NaN, 3_600], + [0, 300], + [299.9, 300], + [360.5, 361], + [86_401, 86_400], + ])("clamps a timeout of %p seconds to %p", (requested, expected) => { + expect(clampTimeoutSeconds(requested)).toBe(expected); + }); +}); diff --git a/tests/keypairs.test.ts b/tests/keypairs.test.ts index e8207b62..9d9b2661 100644 --- a/tests/keypairs.test.ts +++ b/tests/keypairs.test.ts @@ -1,5 +1,5 @@ -import { afterEach, beforeEach, describe, expect, spyOn, test } from "bun:test"; -import { mkdtempSync, writeFileSync } from "node:fs"; +import { afterAll, afterEach, beforeEach, describe, expect, spyOn, test } from "bun:test"; +import { mkdtempSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join, relative } from "node:path"; import { Keypair } from "../src/utils/solana"; @@ -12,11 +12,12 @@ import { } from "../src/utils/keypairs"; const dir = mkdtempSync(join(tmpdir(), "keypairs-test-")); +afterAll(() => rmSync(dir, { recursive: true, force: true })); const writeKeypair = async (name: string) => { const keypair = await Keypair.generate(); const file = join(dir, name); - writeFileSync(file, JSON.stringify(Array.from(keypair.secretKey))); + writeFileSync(file, JSON.stringify(Array.from(keypair.secretKey)), { mode: 0o600 }); return { keypair, file }; }; @@ -110,6 +111,24 @@ describe("resolveKeypairFromEnv", () => { `Role: failed to load keypair from ${join(dir, "nope.json")}`, ); }); + + test("keeps the JSON parsing error as a cause when adding the operator role and path", async () => { + const file = join(dir, "broken-config.json"); + writeFileSync(file, "not JSON"); + process.env["TEST_KEYPAIR_PATH"] = file; + const fallback = await Keypair.generate(); + const result = await resolveKeypairFromEnv( + "TEST_KEYPAIR_PATH", + fallback, + "Fixture payer", + ).catch((error: unknown) => error); + expect(result).toBeInstanceOf(Error); + const failure = result as Error; + expect(failure.message).toContain(`Fixture payer: failed to load keypair from ${file}`); + expect(failure.cause).toBeInstanceOf(Error); + expect((failure.cause as Error).cause).toBeInstanceOf(SyntaxError); + expect(logSpy).not.toHaveBeenCalled(); + }); }); describe("resolveOracleOperatorKeypair", () => { diff --git a/tests/token-price-cache.test.ts b/tests/token-price-cache.test.ts index 73981a78..fb7b87d1 100644 --- a/tests/token-price-cache.test.ts +++ b/tests/token-price-cache.test.ts @@ -3,6 +3,7 @@ import { __test_clearPriceServiceCache, rememberPriceLookup, getUsdPrice, + getCachedPriceLookup, } from "../src/utils/price-service"; import * as priceModule from "../src/utils/prices"; import { WSOL_MINT } from "../src/utils/token-registry"; @@ -96,6 +97,36 @@ describe("token price cache", () => { expect(live).toHaveBeenCalledTimes(1); }); + test("uses a hint at the exact age boundary and refreshes it one millisecond later", async () => { + const clock = vi.spyOn(Date, "now").mockReturnValue(100_000); + const live = vi.spyOn(priceModule, "resolveTokenPriceUSD").mockResolvedValue({ + price: 0.93, + identifier: USDC, + }); + const atBoundary = await getUsdPrice({ tokenMint: USDC, hint: hint({ resolvedAt: 40_000 }) }); + expect(atBoundary).toMatchObject({ price: 1.25, resolvedAt: 40_000 }); + expect(live).not.toHaveBeenCalled(); + __test_clearPriceServiceCache(); + clock.mockReturnValue(100_001); + expect( + await getUsdPrice({ tokenMint: USDC, hint: hint({ resolvedAt: 40_000 }) }), + ).toMatchObject({ price: 0.93, resolvedAt: 100_001 }); + expect(live).toHaveBeenCalledTimes(1); + }); + + test("does not cache a hint under a blank mint or invent a fresh timestamp", async () => { + vi.spyOn(Date, "now").mockReturnValue(1_000); + const lookup = hint({ resolvedAt: 0 }); + expect(rememberPriceLookup(lookup, { tokenMint: " " })).toMatchObject({ + resolvedAt: 0, + tokenMint: USDC, + }); + expect(getCachedPriceLookup({ tokenMint: " " })).toBeNull(); + expect(getCachedPriceLookup({ tokenMint: USDC })).toBeNull(); + expect(await getUsdPrice({ tokenMint: " ", hint: lookup })).toMatchObject({ resolvedAt: 0 }); + expect(getCachedPriceLookup({ tokenMint: USDC })).toBeNull(); + }); + test("a hint with a mint answers a request without one", async () => { const live = vi.spyOn(priceModule, "resolveTokenPriceUSD"); diff --git a/tests/transaction-runner.test.ts b/tests/transaction-runner.test.ts index 4226c28e..29d64339 100644 --- a/tests/transaction-runner.test.ts +++ b/tests/transaction-runner.test.ts @@ -1,4 +1,4 @@ -import { afterEach, beforeEach, describe, expect, mock, spyOn, test } from "bun:test"; +import { afterEach, beforeEach, describe, expect, mock, spyOn, test, vi } from "bun:test"; import { confirmTransactionWithRecovery, getConfirmationRetryDelays, @@ -57,6 +57,93 @@ describe("getConfirmationRetryDelays", () => { }); describe("confirmTransactionWithRecovery", () => { + test.each([ + ["absent RPC result", undefined], + ["null RPC result", null], + ["missing value field", {}], + ["empty status list", { value: [] }], + ] as const)( + "treats %s as pending without claiming success or throwing a type error", + async (_label, response) => { + const failure = timeout(); + const history = mock(async (_signatures: string[], _config: unknown) => response); + const wallet = { + confirmTransaction: async () => { + throw failure; + }, + getConnection: () => ({ getSignatureStatuses: history }), + } as unknown as Parameters[0]["wallet"]; + await expect( + confirmTransactionWithRecovery({ + wallet, + initialSignature: "pending-signature", + operationLabel: "Cancel", + retryDelays: [0], + }), + ).rejects.toBe(failure); + expect(history.mock.calls).toEqual([ + [["pending-signature"], { searchTransactionHistory: true }], + ]); + expect(failure.cause).toMatchObject({ + message: "Transaction pending-signature still pending after retry 1", + }); + }, + ); + + test("does not wait or attach recovery errors when explicitly asked not to retry", async () => { + const failure = timeout(); + const { wallet, statusCalls } = makeWallet({ + confirm: async () => { + throw failure; + }, + }); + const probe = mock(async () => true); + await expect( + confirmTransactionWithRecovery({ + wallet, + initialSignature: "unconfirmed", + operationLabel: "Join", + retryDelays: [], + probes: [{ check: probe, label: "skip this" }], + }), + ).rejects.toBe(failure); + expect(probe).not.toHaveBeenCalled(); + expect(statusCalls).toEqual([]); + expect(Object.hasOwn(failure, "recoveryErrors")).toBe(false); + }); + + test("waits for the configured delay before checking transaction history", async () => { + vi.useFakeTimers(); + try { + const { wallet, statusCalls } = makeWallet({ + confirm: async () => { + throw timeout(); + }, + statuses: () => ({ confirmationStatus: "confirmed" }), + }); + const outcomes: unknown[] = []; + void confirmTransactionWithRecovery({ + wallet, + initialSignature: "waiting", + operationLabel: "Join", + retryDelays: [12], + }).then( + (signature) => outcomes.push(signature), + (error: unknown) => outcomes.push(error), + ); + await Promise.resolve(); + vi.advanceTimersByTime(11); + for (let step = 0; step < 6; step += 1) await Promise.resolve(); + expect(statusCalls).toEqual([]); + vi.advanceTimersByTime(1); + for (let step = 0; step < 9; step += 1) await Promise.resolve(); + expect(statusCalls).toEqual(["waiting"]); + expect(outcomes).toEqual(["waiting"]); + } finally { + vi.useRealTimers(); + } + }); + test("returns the original signature when it confirms", async () => { const { wallet } = makeWallet({}); const logger = mock(() => {}); From 48310aefee8c9bd86afb8f0096a3b391250afda1 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 12:20:17 -0300 Subject: [PATCH 014/410] test(bot): cover faucet schedules and transaction retry bounds --- tests/faucet-handler.test.ts | 66 ++++++++++++++++++++++++++++-- tests/game-command-input.test.ts | 21 ++++++++++ tests/outbound-error-guard.test.ts | 15 +++++++ tests/pda.test.ts | 23 +++++++++++ tests/program-event-parser.test.ts | 31 +++++++++++++- tests/transaction-runner.test.ts | 17 ++++++-- 6 files changed, 165 insertions(+), 8 deletions(-) create mode 100644 tests/game-command-input.test.ts diff --git a/tests/faucet-handler.test.ts b/tests/faucet-handler.test.ts index 13639355..13f3a7f4 100644 --- a/tests/faucet-handler.test.ts +++ b/tests/faucet-handler.test.ts @@ -160,13 +160,18 @@ describe("faucet handler", () => { test.each([ ["/faucet $1 4", "$1 worth of TOK", 4], ["/faucet 1 USD 4", "$1 worth of TOK", 4], + ["/faucet\t2$ 4", "$2 worth of TOK", 4], + ["/faucet 3 us$ 4", "$3 worth of TOK", 4], ["/faucet 1 4", "1 TOK", 4], ["/faucet $1 WBTC 4", "$1 worth of TOK", 4], ["/faucet 1 WBTC 4", "1 TOK", 4], ])("accepts shared amount syntax: %s", async (command, display, claims) => { const explicitToken = command.includes("WBTC"); const harness = createHarness({ - parse: () => ({ ...parsed, tokenWasSpecified: explicitToken || command.includes(" USD ") }), + parse: () => ({ + ...parsed, + tokenWasSpecified: explicitToken || / (?:usd|us\$) /i.test(command), + }), }); await harness.module.handleCommand(harness.commandContext(command)); const faucet = db.getFaucet(1); @@ -175,6 +180,41 @@ describe("faucet handler", () => { expect(harness.replies.at(-1)?.text).toContain("Collected by: 0/4 users"); }); + test("expires 24 hours after creation, not a millisecond sooner", async () => { + let currentTime = 10_000; + const harness = createHarness({ now: () => currentTime }); + await harness.module.handleCommand(harness.commandContext("/faucet 1 4")); + + expect(db.getFaucet(1)?.expires_at).toBe(86_410_000); + currentTime = 86_409_999; + expect(await harness.module.expireDue()).toBe(0); + expect(db.getFaucet(1)?.status).toBe("active"); + currentTime = 86_410_000; + expect(await harness.module.expireDue()).toBe(1); + expect(db.getFaucet(1)?.status).toBe("expired"); + }); + + test("releases an unsubmitted claim at five minutes but keeps a submitted claim", async () => { + let currentTime = 10_000; + const harness = createHarness({ now: () => currentTime }); + await harness.module.handleCommand(harness.commandContext("/faucet 1 4")); + expect(db.reserveClaim(1, 20n, currentTime).ok).toBe(true); + expect(db.reserveClaim(1, 21n, currentTime).ok).toBe(true); + db.recordClaimSignature(1, 21n, "submitted-signature", currentTime); + + currentTime = 309_999; + expect(await harness.module.reconcile()).toBe(0); + expect(db.getClaim(1, 20n)?.status).toBe("processing"); + currentTime = 310_000; + expect(await harness.module.reconcile()).toBe(1); + expect(db.getClaim(1, 20n)?.status).toBe("failed"); + expect(db.getClaim(1, 21n)).toMatchObject({ + status: "submitted", + transaction_signature: "submitted-signature", + }); + expect(harness.transferSenders).toEqual([]); + }); + test("rejects creation when existing faucets reserve the available balance", async () => { const harness = createHarness({ balance: 500 }); await harness.module.handleCommand(harness.commandContext("/faucet 1 4")); @@ -632,8 +672,12 @@ describe("faucet handler", () => { await harness.module.handleCommand(harness.commandContext("/faucet 1 1")); await harness.module.handleClaim(harness.callbackContext(20), 1); - for (let attempt = 1; attempt < 5; attempt += 1) { - currentTime = db.getClaim(1, 20n)?.notification_next_attempt_at ?? currentTime; + for (const [index, nextAttempt] of [61_000, 361_000, 1_261_000, 4_861_000].entries()) { + expect(db.getClaim(1, 20n)?.notification_next_attempt_at).toBe(nextAttempt); + currentTime = nextAttempt - 1; + await harness.module.reconcile(); + expect(db.getClaim(1, 20n)?.notification_attempts).toBe(index + 1); + currentTime = nextAttempt; await harness.module.reconcile(); } @@ -883,6 +927,22 @@ describe("buildFaucetMessage", () => { expires_at: 1, } as const; + test.each([ + [1, 0, "⬜⬜⬜⬜"], + [3, 1, "🟩⬜⬜⬜"], + [5, 2, "🟩🟩⬜⬜⬜"], + [30, 15, "🟩🟩🟩🟩🟩🟩🟩🟩⬜⬜⬜⬜⬜⬜⬜⬜"], + [30, 30, "🟩🟩🟩🟩🟩🟩🟩🟩🟩🟩🟩🟩🟩🟩🟩🟩"], + ] as const)("renders progress for %i slots with %i paid", (maxClaims, paidClaims, bar) => { + const text = buildFaucetMessage({ + faucet: { ...faucet, max_claims: maxClaims }, + paidClaims, + processingClaims: 0, + collectors: [], + }); + expect(text.split("\n").at(-1)).toBe(bar); + }); + test("lists at most twenty collectors and counts the rest", () => { const collectors = Array.from({ length: 22 }, (_, index) => ({ telegramId: String(index + 1), diff --git a/tests/game-command-input.test.ts b/tests/game-command-input.test.ts new file mode 100644 index 00000000..127cae52 --- /dev/null +++ b/tests/game-command-input.test.ts @@ -0,0 +1,21 @@ +import { expect, test } from "bun:test"; +import { parseGameCommandInput } from "../src/handlers/game-command-input"; + +test.each([ + [[], "menu", undefined, undefined], + [["", "", "USDC"], "menu", "USDC", undefined], + [["2."], "direct", undefined, "2."], + [["$2.125"], "direct", undefined, "$2.125"], + [[".125"], "direct", undefined, ".125"], + [[".abc"], "menu", ".abc", undefined], + [["1.abc"], "menu", "1.abc", undefined], + [["2.2", "bOnK"], "direct", "bOnK", "2.2"], + [["2.2", "", "BONK"], "direct", "BONK", "2.2"], + [["1", ".123"], "direct", undefined, "1"], + [["1", "uSd"], "direct", undefined, "1"], + [["1", "pRiVaTe"], "direct", undefined, "1"], + [["1", "pUbLiC"], "direct", undefined, "1"], +] as const)("parses %p as %s", (args, mode, token, amount) => { + const input = parseGameCommandInput(args); + expect([input.mode, input.token, input.amount]).toEqual([mode, token, amount]); +}); diff --git a/tests/outbound-error-guard.test.ts b/tests/outbound-error-guard.test.ts index ffc4e379..fb62d562 100644 --- a/tests/outbound-error-guard.test.ts +++ b/tests/outbound-error-guard.test.ts @@ -6,6 +6,21 @@ import { } from "../src/utils/outbound-error-guard"; describe("outbound Telegram error guard", () => { + test.each([ + ["stack location", "at async checkout (/workspace/checkout.js:38:2)"], + ["bare source location", "file:///workspace/context.ts:24:15"], + ["cause header", "Caused by: invalid response shape"], + ["bare validator token", "unrecognized_keys"], + ["network error code", "EHOSTUNREACH"], + ["HTTP status message", "status was 403"], + ["failing fetch", "fetch unexpected result"], + ["contract diagnostics", "custom program error"], + ["structured nested diagnostic", '{"nested":[{"cOdE":"REJECTED"}]}'], + ["structured validator", '[{"metadata":{"issues":[{"unexpected":"shape"}]}}]'], + ] as const)("filters a %s without the other diagnostic markers", (_case, text) => { + expect(guardOutboundText(text)).toBe(GENERIC_USER_ERROR_MESSAGE); + }); + test.each([ `Failed to request Jupiter order: [ { "expected": "string", "code": "invalid_type", "path": ["routePlan"] } diff --git a/tests/pda.test.ts b/tests/pda.test.ts index df33a980..04f546a7 100644 --- a/tests/pda.test.ts +++ b/tests/pda.test.ts @@ -18,3 +18,26 @@ test("getGamePDA derives expected address", async () => { const pda = await PDAManager.getGamePDA(randomHash, programId); expect(pda.toBase58()).toBe(expected.toBase58()); }); + +test.each([0, 31, 33])("rejects a game hash with %i bytes", async (size) => { + const program = new PublicKey("11111111111111111111111111111112"); + await expect(PDAManager.getGamePDA(Buffer.alloc(size), program)).rejects.toThrow( + "Game random hash must be 32 bytes", + ); +}); + +test("uses the requested program and mint for both vault and legacy token addresses", async () => { + const program = new PublicKey("11111111111111111111111111111112"); + const mint = new PublicKey("EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"); + const [vault] = await PublicKey.findProgramAddress( + [Buffer.from("game_vault"), mint.toBuffer()], + program, + ); + const [token] = await PublicKey.findProgramAddress( + [Buffer.from("game_token"), mint.toBuffer()], + program, + ); + expect(await PDAManager.getGameVaultPDA(mint, program)).toEqual(vault); + expect(await PDAManager.getGameTokenPDA(mint, program)).toEqual(token); + expect(vault.equals(token)).toBe(false); +}); diff --git a/tests/program-event-parser.test.ts b/tests/program-event-parser.test.ts index 4a499c99..9df6290f 100644 --- a/tests/program-event-parser.test.ts +++ b/tests/program-event-parser.test.ts @@ -1,15 +1,43 @@ -import { describe, expect, test } from "bun:test"; +import { describe, expect, mock, test } from "bun:test"; import { PublicKey } from "#solana"; +import { EVENT_DISCRIMINATORS } from "@timbagame/protocol/contracts/events"; import { LEGACY_PLAYER_REFUNDED_DISCRIMINATOR, decodeLegacyPlayerRefunded, decodeProgramEventLog, parseProgramEventLogs, + parseProgramEventsFromTransaction, } from "../src/utils/program-event-parser"; const GAME = new PublicKey("11111111111111111111111111111112"); const PLAYER = new PublicKey("So11111111111111111111111111111111111111112"); +test.each([ + [0, "coinflip"], + [1, "giveaway"], +] as const)("adapts a published %s game type to the bot's %s data", (tag, name) => { + const mint = new PublicKey("EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"); + const payload = Buffer.alloc(146); + Buffer.from(EVENT_DISCRIMINATORS.GameCreated).copy(payload, 0); + GAME.toBuffer().copy(payload, 8); + PLAYER.toBuffer().copy(payload, 40); + payload.writeUInt8(tag, 72); + mint.toBuffer().copy(payload, 97); + const fallback = mock(() => null); + const event = decodeProgramEventLog(payload.toString("base64"), fallback); + expect(event).toMatchObject({ + name: "GameCreated", + data: { gameKey: GAME, creator: PLAYER, tokenMint: mint, gameType: { [name]: {} } }, + }); + expect(fallback).not.toHaveBeenCalled(); +}); + +test("does not invent events from a missing transaction log", () => { + const program = { programId: GAME }; + expect(parseProgramEventsFromTransaction(program, null)).toEqual([]); + expect(parseProgramEventsFromTransaction(program, undefined)).toEqual([]); +}); + /** Encode a pre-moved_participant v0.2 PlayerUnjoined program-data payload. */ function encodeLegacyPlayerRefunded(fields: { gameKey: PublicKey; @@ -155,6 +183,7 @@ describe("parseProgramEventLogs", () => { expect(events).toHaveLength(1); expect(events[0]?.name).toBe("TokenFeeWithdrawn"); expect((events[0]?.data["tokenMint"] as PublicKey).equals(mint)).toBe(true); + expect(events[0]?.data["operator"]).toEqual(operator); expect(events[0]?.data["amount"]?.toString()).toBe("123"); }); diff --git a/tests/transaction-runner.test.ts b/tests/transaction-runner.test.ts index 29d64339..a635ef27 100644 --- a/tests/transaction-runner.test.ts +++ b/tests/transaction-runner.test.ts @@ -3,7 +3,6 @@ import { confirmTransactionWithRecovery, getConfirmationRetryDelays, } from "../src/utils/transaction-runner"; -import { TRANSACTION_RESUBMIT_ATTEMPTS } from "../src/utils/constants"; type Status = { err?: unknown; confirmationStatus?: string; confirmations?: number | null } | null; @@ -18,6 +17,7 @@ const makeWallet = (options: { : { getSignatureStatuses: async (signatures: string[], config: unknown) => { expect(config).toEqual({ searchTransactionHistory: true }); + if (statusCalls.length >= 6) throw new Error("Unexpected seventh status lookup"); statusCalls.push(signatures[0]!); return { value: [options.statuses?.(signatures[0]!) ?? null] }; }, @@ -35,7 +35,12 @@ let warnSpy: ReturnType; let errorSpy: ReturnType; beforeEach(() => { warnSpy = spyOn(console, "warn").mockImplementation(() => {}); - errorSpy = spyOn(console, "error").mockImplementation(() => {}); + let errors = 0; + errorSpy = spyOn(console, "error").mockImplementation(() => { + // A mutant can decrement the resubmission index in a loop of caught errors. + // Stop it synchronously so it cannot starve the runner's timeout timer. + if (++errors > 6) throw new Error("Unexpected seventh recovery error"); + }); }); afterEach(() => { warnSpy.mockRestore(); @@ -66,7 +71,11 @@ describe("confirmTransactionWithRecovery", () => { "treats %s as pending without claiming success or throwing a type error", async (_label, response) => { const failure = timeout(); - const history = mock(async (_signatures: string[], _config: unknown) => response); + let calls = 0; + const history = mock(async (_signatures: string[], _config: unknown) => { + if (++calls > 1) throw new Error("Unexpected second status lookup"); + return response; + }); const wallet = { confirmTransaction: async () => { throw failure; @@ -278,7 +287,7 @@ describe("confirmTransactionWithRecovery", () => { }).catch((caught) => caught); expect(error).toBe(original); - expect(attempts).toBe(TRANSACTION_RESUBMIT_ATTEMPTS); + expect(attempts).toBe(2); expect(error.cause).toBeInstanceOf(Error); expect(error.recoveryErrors).toHaveLength(1); expect(errorSpy.mock.calls[0]?.[1]?.message).toBe( From 107da46983202491dfd4004e1a4d8279a434c493 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 12:26:23 -0300 Subject: [PATCH 015/410] fix(wallet): reject invalid times and refresh after clock rollback --- src/bot/expired-game-scan.ts | 5 +-- src/utils/wallet.ts | 20 ++++----- tests/expired-game-scan.test.ts | 47 +++++++++++++++++++++ tests/game.funding-and-tokens.test.ts | 31 ++++++++------ tests/wallet.blockhash-cache.test.ts | 59 ++++++++++++++++----------- tests/wallet.throttle.test.ts | 22 ++++++++++ tests/wallet.time.test.ts | 34 ++++++++++++++- 7 files changed, 165 insertions(+), 53 deletions(-) diff --git a/src/bot/expired-game-scan.ts b/src/bot/expired-game-scan.ts index 6df1bb9b..36d7aa24 100644 --- a/src/bot/expired-game-scan.ts +++ b/src/bot/expired-game-scan.ts @@ -93,10 +93,9 @@ export const createExpiredGameScanner = (deps: ExpiredGameScanDeps) => { const cutoffMs = nowMs + deps.lookaheadMs; const processedAddresses: string[] = []; const blockTime = await deps.getBlockchainTime(); - const currentTime = - typeof blockTime === "number" && Number.isFinite(blockTime) ? blockTime : undefined; + const currentTime = Number.isFinite(blockTime) ? blockTime : undefined; let batchCount = 0; - let expiringGames: GameData[] = []; + let expiringGames: GameData[]; do { expiringGames = deps.getGamesExpiringBefore(cutoffMs, batchSize, processedAddresses); diff --git a/src/utils/wallet.ts b/src/utils/wallet.ts index d0c1cf0c..868496be 100644 --- a/src/utils/wallet.ts +++ b/src/utils/wallet.ts @@ -3207,11 +3207,10 @@ export class WalletManager { private async fetchBlockchainTime(): Promise { try { const slot = await this.connection.getSlot(); - const blockTime = await this.connection.getBlockTime(slot); - if (!blockTime) { + const normalized = Number(await this.connection.getBlockTime(slot)); + if (!Number.isSafeInteger(normalized) || normalized <= 0) { throw new Error("Could not get blockchain time"); } - const normalized = Number(blockTime); this.blockchainTimeCache = { blockTime: normalized, fetchedAtMs: this.currentTimeMs() }; return normalized; } catch (error) { @@ -3225,15 +3224,12 @@ export class WalletManager { lastValidBlockHeight: number; }> { const now = Date.now(); - if ( - !forceFresh && - this.blockhashCache && - now - this.blockhashCache.timestamp < BLOCKHASH_CACHE_DURATION - ) { - return { - blockhash: this.blockhashCache.blockhash, - lastValidBlockHeight: this.blockhashCache.lastValidBlockHeight, - }; + const cached = this.blockhashCache; + if (!forceFresh && cached) { + const age = now - cached.timestamp; + if (age >= 0 && age < BLOCKHASH_CACHE_DURATION) { + return { blockhash: cached.blockhash, lastValidBlockHeight: cached.lastValidBlockHeight }; + } } await this.throttle("blockhash"); diff --git a/tests/expired-game-scan.test.ts b/tests/expired-game-scan.test.ts index fbee19f6..6440c8dc 100644 --- a/tests/expired-game-scan.test.ts +++ b/tests/expired-game-scan.test.ts @@ -150,6 +150,53 @@ describe("createExpiredGameScanner", () => { expect(deps.handleExpiredGame).toHaveBeenCalledTimes(1); }); + test("does not query the chain or clean up when all stored addresses are unusable", async () => { + const fetch = vi.fn(async () => ({ expired: true })); + const fetchMultiple = vi.fn(async () => [{ expired: true }]); + const deps = createDeps({ + getGamesExpiringBefore: () => [game(""), game("not-a-public-key")], + gameAccounts: () => ({ fetch, fetchMultiple }), + }); + await createExpiredGameScanner(deps).scan(); + expect(fetch).not.toHaveBeenCalled(); + expect(fetchMultiple).not.toHaveBeenCalled(); + expect(deps.cleanupOrphanedGame).not.toHaveBeenCalled(); + expect(deps.updateGameMessage).not.toHaveBeenCalled(); + }); + + test("stops on an empty database page without reading game accounts again", async () => { + const key = await address(); + const getGamesExpiringBefore = vi + .fn(() => [] as ReturnType) + .mockImplementationOnce(() => [game(key)]); + const deps = createDeps({ batchSize: 1, getGamesExpiringBefore }); + await createExpiredGameScanner(deps).scan(); + expect(getGamesExpiringBefore).toHaveBeenCalledTimes(2); + expect(deps.gameAccounts).toHaveBeenCalledTimes(1); + expect(deps.completeGame).toHaveBeenCalledWith(key); + }); + + test.each([ + ["epoch zero", 0, 0], + ["finite negative", -5, -5], + ["infinite", Infinity, undefined], + ["nonnumeric", "123", undefined], + ] as const)("passes the expected time on a %s response", async (_label, blockTime, expected) => { + const key = await address(); + const account = { expired: true }; + const isExpired = vi.fn(() => false); + const deps = createDeps({ + getGamesExpiringBefore: () => [game(key)], + gameAccounts: () => ({ fetch: async () => account }), + // Model a malformed RPC value as well as valid numeric responses. + getBlockchainTime: async () => blockTime as number, + isExpired, + }); + await createExpiredGameScanner(deps).scan(); + expect(isExpired).toHaveBeenCalledWith(account, expected); + expect(deps.handleExpiredGame).not.toHaveBeenCalled(); + }); + test("falls back for an omitted batch entry without deleting the stored game", async () => { const [present, omitted] = await Promise.all([address(), address()]); const api = { diff --git a/tests/game.funding-and-tokens.test.ts b/tests/game.funding-and-tokens.test.ts index 08d21d86..8e6c5985 100644 --- a/tests/game.funding-and-tokens.test.ts +++ b/tests/game.funding-and-tokens.test.ts @@ -52,16 +52,19 @@ describe("GameManager ensureWrappedSolBalance", () => { return gm; }; - test("returns the current balances untouched when the WSOL balance already covers the stake", async () => { - const wrapSol = async () => { - throw new Error("should not wrap"); - }; - const gm = setup({ wrapSol }); + test.each([1_000, 1_500])( + "does not wrap when %i WSOL already covers the stake", + async (balance) => { + const wrapSol = async () => { + throw new Error("should not wrap"); + }; + const gm = setup({ wrapSol }); - const result = await gm.ensureWrappedSolBalance(1n, REQUIRED, 1_500, 777, "create"); + const result = await gm.ensureWrappedSolBalance(1n, REQUIRED, balance, 777, "create"); - expect(result).toEqual({ success: true, tokenBalance: 1_500, solBalance: 777 }); - }); + expect(result).toEqual({ success: true, tokenBalance: balance, solBalance: 777 }); + }, + ); describe("when the WSOL balance covers only part of the stake", () => { const CURRENT = 400; @@ -167,6 +170,7 @@ describe("GameManager ensureWrappedSolBalance", () => { wrapSol: async () => "wrap-sig", getTokenBalance: async () => { tokenReads += 1; + if (tokenReads > 7) throw new Error("Unexpected eighth WSOL lookup"); return 10; }, getBalance: async () => 50_000, @@ -201,7 +205,7 @@ describe("GameManager ensureWrappedSolBalance", () => { ).toBe(true); }); - test("polls with the production backoff schedule outside the test environment", async () => { + test("uses the complete production backoff and accepts the exact stake and SOL reserve", async () => { const previousEnv = process.env.NODE_ENV; const timers = stubInstantTimers(); let reads = 0; @@ -209,17 +213,18 @@ describe("GameManager ensureWrappedSolBalance", () => { wrapSol: async () => "wrap-sig", getTokenBalance: async () => { reads += 1; - return reads >= 3 ? REQUIRED : 0; + if (reads > 7) throw new Error("Unexpected eighth WSOL lookup"); + return reads === 7 ? REQUIRED : 0; }, - getBalance: async () => 90_000, + getBalance: async () => 100, }); try { process.env.NODE_ENV = "production"; const result = await gm.ensureWrappedSolBalance(1n, REQUIRED, 0, 90_000, "create"); - expect(result).toEqual({ success: true, tokenBalance: REQUIRED, solBalance: 90_000 }); - expect(timers.delays).toEqual([250, 500]); + expect(result).toEqual({ success: true, tokenBalance: REQUIRED, solBalance: 100 }); + expect(timers.delays).toEqual([250, 500, 1_000, 2_000, 4_000, 8_000]); } finally { process.env.NODE_ENV = previousEnv; timers.restore(); diff --git a/tests/wallet.blockhash-cache.test.ts b/tests/wallet.blockhash-cache.test.ts index 30092ab0..9c417292 100644 --- a/tests/wallet.blockhash-cache.test.ts +++ b/tests/wallet.blockhash-cache.test.ts @@ -1,4 +1,4 @@ -import { expect, test } from "bun:test"; +import { expect, mock, spyOn, test } from "bun:test"; import type { Connection } from "#solana"; import { WalletManager } from "../src/utils/wallet"; import { WSOL_MINT } from "../src/utils/constants"; @@ -14,30 +14,41 @@ class FakeConnection implements Partial { } } -test("getLatestBlockhash caches within TTL", async () => { - // Inject fake connection/time - let now = Date.now(); - const realNow = Date.now; - // Monkey-patch Date.now so internal cache uses our clock - // @ts-ignore - Date.now = () => now; - const conn = new FakeConnection() as any as Connection; - const wm = WalletManager.createForTest(mnemonic, { - connection: conn, - fetch: globalThis.fetch as any, - timeNow: () => now, - }); - - const a = await wm.getLatestBlockhash(); - const b = await wm.getLatestBlockhash(); - expect(a.blockhash).toBe(b.blockhash); // cached +test.each([ + ["before expiry", 9_999, false, 1], + ["at expiry", 10_000, false, 2], + ["after a clock rollback", -1, false, 2], + ["with a forced refresh", 9_999, true, 2], +] as const)("gets the expected confirmed blockhash %s", async (_case, age, forceFresh, count) => { + let now = 1_000_000; + const clock = spyOn(Date, "now").mockImplementation(() => now); + try { + let read = 0; + const getLatestBlockhash = mock(async (_commitment: string) => { + read += 1; + return { blockhash: `hash-${read}`, lastValidBlockHeight: 1000n + BigInt(read) }; + }); + const wallet = WalletManager.createForTest(mnemonic, { + connection: { getLatestBlockhash } as unknown as Connection, + // Skip the ordinary RPC spacing. The cache still uses the fake wall clock. + timeNow: () => 2_000_000 + 20_000 * read, + }); + expect(await wallet.getLatestBlockhash()).toEqual({ + blockhash: "hash-1", + lastValidBlockHeight: 1001, + }); - // Advance time beyond cache TTL (10s) - now += 11_000; - const c = await wm.getLatestBlockhash(); - expect(c.blockhash).not.toBe(a.blockhash); - // restore Date.now - Date.now = realNow; + now += age; + expect(await wallet.getLatestBlockhash(forceFresh)).toEqual({ + blockhash: `hash-${count}`, + lastValidBlockHeight: 1000 + count, + }); + expect(getLatestBlockhash.mock.calls).toEqual( + Array.from({ length: count }, () => ["confirmed"]), + ); + } finally { + clock.mockRestore(); + } }); test("getTokenMetadata uses known token shortcuts", async () => { diff --git a/tests/wallet.throttle.test.ts b/tests/wallet.throttle.test.ts index 24411bf0..79cf834e 100644 --- a/tests/wallet.throttle.test.ts +++ b/tests/wallet.throttle.test.ts @@ -113,6 +113,28 @@ describe("WalletManager.getBlockchainTime cache", () => { await manager.getBlockchainTime(); expect(slotCalls).toBe(2); }); + + test("refreshes exactly at five seconds and when the local clock goes back", async () => { + const clock = { now: 5_000_000 }; + let reads = 0n; + const { manager } = createManager( + { + getSlot: async () => 42n, + getBlockTime: async () => 1_700_000_000n + 10n * ++reads, + }, + clock, + ); + + expect(await manager.getBlockchainTime()).toBe(1_700_000_010); + expect(await manager.getBlockchainTime()).toBe(1_700_000_010); + clock.now = 5_004_999; + expect(await manager.getBlockchainTime()).toBe(1_700_000_014); + clock.now = 5_005_000; + expect(await manager.getBlockchainTime()).toBe(1_700_000_020); + clock.now = 5_004_999; + expect(await manager.getBlockchainTime()).toBe(1_700_000_030); + expect(reads).toBe(3n); + }); }); describe("WalletManager.getKeyPair async derivation", () => { diff --git a/tests/wallet.time.test.ts b/tests/wallet.time.test.ts index 7962ffc4..ce3eaed6 100644 --- a/tests/wallet.time.test.ts +++ b/tests/wallet.time.test.ts @@ -1,7 +1,39 @@ -import { describe, expect, test } from "bun:test"; +import { describe, expect, mock, spyOn, test } from "bun:test"; +import type { Connection } from "#solana"; import { WalletManager } from "../src/utils/wallet"; describe("WalletManager time-related helpers", () => { + test.each([ + ["absent", null], + ["zero", 0], + ["negative", -1n], + ["NaN", NaN], + ["infinite", Infinity], + ["fractional", 1000.5], + ["out of range", 9_007_199_254_740_992n], + ] as const)("does not cache a %s block time", async (_label, invalid) => { + const now = spyOn(Date, "now").mockReturnValue(1_700_000_002_123); + const logger = spyOn(console, "warn").mockImplementation(() => {}); + try { + const getBlockTime = mock(async (_slot: bigint): Promise => 1_700_000_010n); + // Deliberately violate the RPC type to model a malformed provider response. + getBlockTime.mockImplementationOnce(async () => invalid as bigint | null); + const connection = { getSlot: async () => 42n, getBlockTime } as unknown as Connection; + const wallet = WalletManager.createForTest( + "test walk nut penalty hip pave soap entry language right filter choice", + { connection }, + ); + + expect(await wallet.getBlockchainTime()).toBe(1_700_000_002); + expect(await wallet.getBlockchainTime()).toBe(1_700_000_010); + expect(await wallet.getBlockchainTime()).toBe(1_700_000_010); + expect(getBlockTime.mock.calls).toEqual([[42n], [42n]]); + } finally { + now.mockRestore(); + logger.mockRestore(); + } + }); + test("getBlockchainTime falls back to system time on error", async () => { const calls: any = { getSlot: 0, getBlockTime: 0 }; const connection: any = { From 262321e754990b0ec39050bb6b7addcec6652e3b Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 12:28:41 -0300 Subject: [PATCH 016/410] fix(games): distinguish incomplete RPC batches from absent accounts --- src/utils/game.ts | 9 ++++----- src/utils/timba-program.ts | 9 +++++++-- tests/game-manager.public-page.test.ts | 25 +++++++++++++++++++++++++ tests/timba-program.test.ts | 21 ++++++++++++++++++++- 4 files changed, 56 insertions(+), 8 deletions(-) diff --git a/src/utils/game.ts b/src/utils/game.ts index 640091f6..9ab8aa0d 100644 --- a/src/utils/game.ts +++ b/src/utils/game.ts @@ -6827,7 +6827,7 @@ export class GameManager { */ private async fetchGameAccountsBatch(addresses: string[]): Promise> { const accounts = new Map(); - const accountApi = this.program.account.game as any; + const accountApi = this.program.account.game; if (addresses.length === 0 || typeof accountApi?.fetchMultiple !== "function") { return accounts; } @@ -6845,11 +6845,10 @@ export class GameManager { } try { - const fetched: Array = await accountApi.fetchMultiple( - valid.map((entry) => entry.pda), - ); + const fetched = await accountApi.fetchMultiple(valid.map((entry) => entry.pda)); valid.forEach((entry, index) => { - accounts.set(entry.address, fetched[index] ?? null); + const account = fetched[index]; + if (account !== undefined) accounts.set(entry.address, account); }); } catch (error) { console.warn("Batch game account lookup failed; falling back to single lookups:", error); diff --git a/src/utils/timba-program.ts b/src/utils/timba-program.ts index 3948f551..529ce8bb 100644 --- a/src/utils/timba-program.ts +++ b/src/utils/timba-program.ts @@ -39,7 +39,7 @@ export class TimbaAccountNotFoundError extends Error { export interface TimbaAccountClient { fetch(address: PublicKey): Promise; fetchNullable(address: PublicKey): Promise; - /** Batch lookup: one RPC call per 100 addresses; missing accounts resolve to null. */ + /** Batch lookup: one RPC call per 100 addresses. Absent accounts are null; incomplete batches reject. */ fetchMultiple(addresses: PublicKey[]): Promise>; all(): Promise>; } @@ -151,8 +151,13 @@ function accountClient(options: { for (let offset = 0; offset < addresses.length; offset += MULTIPLE_ACCOUNTS_CHUNK_SIZE) { const chunk = addresses.slice(offset, offset + MULTIPLE_ACCOUNTS_CHUNK_SIZE); const infos = await options.connection.getMultipleAccountsInfo(chunk, "confirmed"); + if (infos.length !== chunk.length) { + throw new Error("Incomplete Timba account batch"); + } chunk.forEach((address, index) => { - results.push(decodeInfo(address, infos[index] as any)); + const info = infos[index]; + if (info === undefined) throw new Error("Incomplete Timba account batch"); + results.push(decodeInfo(address, info)); }); } return results; diff --git a/tests/game-manager.public-page.test.ts b/tests/game-manager.public-page.test.ts index 848b75d6..a007c89d 100644 --- a/tests/game-manager.public-page.test.ts +++ b/tests/game-manager.public-page.test.ts @@ -237,4 +237,29 @@ describe("GameManager active list batching", () => { expect(fetchNullable).toHaveBeenCalledTimes(1); expect(games).toHaveLength(1); }); + + test("keeps a game returned by the single lookup when the batch omits it", async () => { + const [missing, omitted] = await Promise.all([Keypair.generate(), Keypair.generate()]); + const missingAddress = missing.publicKey.toBase58(); + const omittedAddress = omitted.publicKey.toBase58(); + const fetchNullable = vi.fn(async (_address: PublicKey) => ({ + ticketsCount: 1, + maxTickets: 2, + })); + const manager = createManager( + { account: { game: { fetchMultiple: async () => [null], fetchNullable } } }, + {}, + { + getActiveGames: () => [ + { game_address: missingAddress, game_type: "coinflip" }, + { game_address: omittedAddress, game_type: "coinflip" }, + ], + }, + ); + stubFormatting(manager); + + const games = await manager.getUserActiveGames({} as any, 7n); + expect(fetchNullable.mock.calls.map(([key]) => key.toBase58())).toEqual([omittedAddress]); + expect(games.map((row) => row.gameAddress)).toEqual([omittedAddress]); + }); }); diff --git a/tests/timba-program.test.ts b/tests/timba-program.test.ts index 0b39c4c1..6a25c22f 100644 --- a/tests/timba-program.test.ts +++ b/tests/timba-program.test.ts @@ -158,7 +158,11 @@ describe(`Timba ${contractVersion} generated client adapter`, () => { const addresses = await Promise.all(Array.from({ length: 101 }, () => publicKey())); const chunkSizes: number[] = []; const connection = { - getMultipleAccountsInfo: async (keys: PublicKey[]) => { + getMultipleAccountsInfo: async (keys: PublicKey[], commitment: string) => { + expect(commitment).toBe("confirmed"); + if (chunkSizes.length === 2 || keys.length === 0) { + throw new Error("Unexpected RPC chunk"); + } chunkSizes.push(keys.length); return keys.map((key) => key.equals(addresses[1]!) @@ -189,4 +193,19 @@ describe(`Timba ${contractVersion} generated client adapter`, () => { "is not owned", ); }); + + test.each([ + ["short", []], + ["long", [null, null]], + ["sparse", Array(1)], + ] as const)( + "rejects a %s batch response instead of inventing missing accounts", + async (_label, infos) => { + const connection = { getMultipleAccountsInfo: async () => infos } as unknown as Connection; + const program = createTimbaProgram(connection); + await expect(program.account.game.fetchMultiple([await publicKey()])).rejects.toThrow( + "Incomplete Timba account batch", + ); + }, + ); }); From 8bf1ac47397ee9aa10605da151e6de30744910f9 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 12:30:21 -0300 Subject: [PATCH 017/410] fix(games): reject invalid visibility in setup buttons --- src/utils/callback-data.ts | 17 ++++++++---- tests/callback-data.test.ts | 53 +++++++++++++++++++++++++++++++++++++ 2 files changed, 65 insertions(+), 5 deletions(-) diff --git a/src/utils/callback-data.ts b/src/utils/callback-data.ts index 9df42772..4be69cba 100644 --- a/src/utils/callback-data.ts +++ b/src/utils/callback-data.ts @@ -183,7 +183,7 @@ export const decodeGameConfirmPayload = ( const players = decodeUnsigned(parts[3]); const timeoutSeconds = decodeUnsigned(parts[4]); const minPlayers = decodeUnsigned(parts[5]); - const isPrivate = parts[6] === "1"; + const visibility = parts[6]; const creatorId = decodeCreatorId(parts[7]); if ( @@ -192,6 +192,7 @@ export const decodeGameConfirmPayload = ( players === null || timeoutSeconds === null || minPlayers === null || + (visibility !== "0" && visibility !== "1") || !creatorId ) { return null; @@ -203,7 +204,7 @@ export const decodeGameConfirmPayload = ( players, timeoutSeconds, minPlayers, - isPrivate, + isPrivate: visibility === "1", creatorId, }; }; @@ -296,10 +297,16 @@ export const decodeVisibilityPayload = ( const gameType = fromGameTypeCode(parts[1]); const amount = decodeAmount(parts[2]); const players = decodeUnsigned(parts[3]); - const isPrivate = parts[4] === "1"; + const visibility = parts[4]; const creatorId = decodeCreatorId(parts[5]); - if (!gameType || amount === null || players === null || !creatorId) { + if ( + !gameType || + amount === null || + players === null || + (visibility !== "0" && visibility !== "1") || + !creatorId + ) { return null; } @@ -307,7 +314,7 @@ export const decodeVisibilityPayload = ( gameType, amount, players, - isPrivate, + isPrivate: visibility === "1", creatorId, }; }; diff --git a/tests/callback-data.test.ts b/tests/callback-data.test.ts index 0726c440..aa722cea 100644 --- a/tests/callback-data.test.ts +++ b/tests/callback-data.test.ts @@ -95,6 +95,59 @@ test("includes the exact 64-byte Telegram boundary", () => { expect(callback.isCallbackSafeLength("")).toBe(false); }); +test("keeps already-sent game buttons compatible with the current bot", () => { + const input = { gameType: "giveaway" as const, amount: "1.25", creatorId: "42", players: 35 }; + const confirm = { ...input, timeoutSeconds: 600, minPlayers: 1, isPrivate: true }; + const timeout = { ...input, deltaMinutes: -1 }; + const minimum = { ...input, deltaPlayers: 1 }; + const visibility = { ...input, isPrivate: false }; + const amount = { gameType: input.gameType, amount: input.amount, creatorId: input.creatorId }; + + expect(callback.encodeGameConfirmPayload(confirm)).toBe("cg|g|2:3h|z|go|1|1|n16"); + expect(callback.decodeGameConfirmPayload("cg|g|2:3h|z|go|1|1|n16")).toEqual(confirm); + expect(callback.encodeTimeoutChangePayload(timeout)).toBe("ct|g|2:3h|z|-1|n16"); + expect(callback.decodeTimeoutChangePayload("ct|g|2:3h|z|-1|n16")).toEqual(timeout); + expect(callback.encodeMinPlayersChangePayload(minimum)).toBe("cm|g|2:3h|z|1|n16"); + expect(callback.decodeMinPlayersChangePayload("cm|g|2:3h|z|1|n16")).toEqual(minimum); + expect(callback.encodeVisibilityPayload(visibility)).toBe("cv|g|2:3h|z|0|n16"); + expect(callback.decodeVisibilityPayload("cv|g|2:3h|z|0|n16")).toEqual(visibility); + expect(callback.encodePlayersSelectionPayload(input)).toBe("gp|g|2:3h|z|n16"); + expect(callback.decodePlayersSelectionPayload("gp|g|2:3h|z|n16")).toEqual(input); + expect(callback.encodeAmountSelectionPayload(amount)).toBe("ga|g|2:3h|n16"); + expect(callback.decodeAmountSelectionPayload("ga|g|2:3h|n16")).toEqual(amount); + expect(callback.encodeCustomPlayersPayload(amount)).toBe("gcp|g|2:3h|n16"); + expect(callback.decodeCustomPlayersPayload("gcp|g|2:3h|n16")).toEqual(amount); +}); + +test.each([ + ["zero", 0, "0", 0], + ["negative zero", -0, "0", 0], + ["round up", 1.5, "2", 2], + ["upper safe integer", 9_007_199_254_740_991, "2gosa7pa2gv", 9_007_199_254_740_991], +] as const)("encodes the expected player count for %s", (_label, count, encoded, rounded) => { + const input = { gameType: "coinflip" as const, amount: "0", creatorId: "0", players: count }; + expect(callback.encodePlayersSelectionPayload(input)).toBe(`gp|c|0:0|${encoded}|n0`); + const decoded = callback.decodePlayersSelectionPayload(`gp|c|0:0|${encoded}|n0`); + expect(decoded?.players).toBe(rounded); + expect(decoded?.amount).toBe("0"); + expect(decoded?.creatorId).toBe("0"); +}); + +test.each([ + ["negative", -1], + ["negative fraction", -0.1], + ["not a number", NaN], + ["infinite", Infinity], + ["outside the safe integer range", Number.MAX_SAFE_INTEGER + 1], +] as const)("rejects a %s unsigned player count", (_label, count) => { + expect(callback.encodePlayersSelectionPayload({ ...base, players: count })).toBeNull(); +}); + +test.each(["", "2"])("rejects an unknown visibility field '%s'", (value) => { + expect(callback.decodeGameConfirmPayload(`cg|g|2:3h|z|go|1|${value}|n16`)).toBeNull(); + expect(callback.decodeVisibilityPayload(`cv|g|2:3h|z|${value}|n16`)).toBeNull(); +}); + test("round-trips Unicode creator IDs as text", () => { const payload = { ...base, gameType: "giveaway" as const, amount: "7", creatorId: "club-é-🟢" }; expect( From c6db2825df22c04108aae0b9b9ecabf4c7ad684f Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 12:35:43 -0300 Subject: [PATCH 018/410] test(bot): cover database expiry and swap fee defaults --- src/utils/swap/route-cost.ts | 11 ++-- tests/game-database.test.ts | 98 +++++++++++++++++++++++++++++++--- tests/route-cost.test.ts | 29 ++++++++++ tests/swap-quote-cache.test.ts | 19 +++++++ 4 files changed, 144 insertions(+), 13 deletions(-) diff --git a/src/utils/swap/route-cost.ts b/src/utils/swap/route-cost.ts index 24acef82..564f5893 100644 --- a/src/utils/swap/route-cost.ts +++ b/src/utils/swap/route-cost.ts @@ -30,10 +30,6 @@ const clampNumber = (value: number): number => { return Math.max(0, Math.trunc(value)); }; -const roundPadding = (value: number, rounding: "ceil" | "round"): number => { - return rounding === "round" ? Math.round(value) : Math.ceil(value); -}; - export const calculateRouteCosts = ( costs: RouteLikeCosts | null | undefined, config?: RouteCostConfig, @@ -48,9 +44,10 @@ export const calculateRouteCosts = ( const paddingRatio = config?.paddingRatio ?? 0.25; const paddingExtraLamports = config?.paddingExtraLamports ?? 0; const minPaddingLamports = config?.minPaddingLamports ?? 0; - const paddingRounding = config?.paddingRounding ?? "ceil"; + const paddingRounding = config?.paddingRounding; - const ratioPadding = roundPadding(routeLamports * paddingRatio, paddingRounding); + const rawPadding = routeLamports * paddingRatio; + const ratioPadding = paddingRounding === "round" ? Math.round(rawPadding) : Math.ceil(rawPadding); let paddingLamports = clampNumber(ratioPadding + paddingExtraLamports); if (routeLamports > 0) { @@ -58,7 +55,7 @@ export const calculateRouteCosts = ( } const baseRequiredLamports = Math.max(0, config?.baseRequiredLamports ?? 0); - const requiredStrategy = config?.requiredStrategy ?? "max"; + const requiredStrategy = config?.requiredStrategy; const requiredLamports = requiredStrategy === "sum" diff --git a/tests/game-database.test.ts b/tests/game-database.test.ts index 8717ac2e..f7639a2c 100644 --- a/tests/game-database.test.ts +++ b/tests/game-database.test.ts @@ -1,6 +1,5 @@ import { expect, test, beforeEach, spyOn } from "bun:test"; import fc from "fast-check"; -import type { GameData } from "../src/types"; import { GameDatabase } from "../src/utils/game-database"; import { GAME_CREATION_RATE_LIMIT_WINDOW_MS } from "../src/utils/constants"; import { resetTestDatabase } from "./helpers/database"; @@ -26,6 +25,43 @@ test("saveGame is idempotent and preserves terminal state during hydration races expect(game.completed_at).toBe(1234); }); +test.each([ + ["zero", [0, 0, 0], [0, 0, 0]], + ["negative", [-1, -1, -1], [-1, -1, -1]], + ["finite", [60, 70_000, 10_000], [60, 70_000, 10_000]], + ["missing", [undefined, undefined, undefined], [null, null, 12_345]], + ["infinite", [Infinity, Infinity, Infinity], [null, null, 12_345]], + ["NaN", [NaN, NaN, NaN], [null, null, 12_345]], +] as const)("stores game timing for the %s input", (_label, input, expected) => { + const db = GameDatabase.getInstance(); + const clock = spyOn(Date, "now").mockReturnValue(12_345); + try { + db.saveGame( + "timed-game", + "11", + 100, + "coinflip", + "mint", + "TOK", + 5, + 2, + -100, + input[0], + input[1], + input[2], + ); + expect(db.getGame("timed-game")).toMatchObject({ + timeout_seconds: expected[0], + expires_at: expected[1], + created_at: expected[2], + min_players: 2, + max_players: 5, + }); + } finally { + clock.mockRestore(); + } +}); + test("GameDatabase: CRUD for games, mappings, participants, and slot updates", () => { const db = GameDatabase.getInstance(); @@ -683,17 +719,19 @@ test("getGamesExpiringBefore can paginate large batches by excluding processed e const seen = new Set(); const limit = 15; - let batch: GameData[]; const excludes: string[] = []; - do { - batch = db.getGamesExpiringBefore(base + 1000, limit, excludes); + for (let page = 0; page < 4; page += 1) { + const batch = db.getGamesExpiringBefore(base + 1000, limit, excludes); + expect(batch).toHaveLength(15); for (const game of batch) { + expect(seen.has(game.game_address)).toBe(false); seen.add(game.game_address); excludes.push(game.game_address); } - } while (batch.length === limit); + } - expect(seen.size).toBe(total); + expect(db.getGamesExpiringBefore(base + 1000, limit, excludes)).toEqual([]); + expect(seen).toEqual(new Set(addresses)); }); test("getGamesExpiringBefore honors excludes and fills with oldest non-expiring", () => { @@ -734,6 +772,54 @@ test("getGamesExpiringBefore honors excludes and fills with oldest non-expiring" expect(results.map((g) => g.game_address)).toEqual(["exp-2", "no-exp-1", "no-exp-2"]); }); +test("keeps positive and negative membership results until the exact 30-minute boundary", () => { + const db = GameDatabase.getInstance(); + let now = 100_000_000; + const clock = spyOn(Date, "now").mockImplementation(() => now); + try { + db.saveMembershipCache(-100, "1001", true); + db.saveMembershipCacheBatch(-100, [{ telegramId: "1002", isMember: false }]); + db.saveMembershipCache(-200, "1002", true); + + now += 1_800_000; + expect(db.getCachedMembership(-100, "1001")).toBe(true); + expect(db.getCachedMembership(-100, "1002")).toBe(false); + expect(db.getCachedMemberships(-100, ["1001", "1002", "9000"])).toEqual( + new Map([ + ["1001", true], + ["1002", false], + ]), + ); + expect(db.getCachedMemberships(-200, ["1001", "1002"])).toEqual(new Map([["1002", true]])); + + now += 1; + expect(db.getCachedMembership(-100, "1001")).toBeNull(); + expect(db.getCachedMembership(-100, "1002")).toBeNull(); + expect(db.getCachedMemberships(-100, ["1001", "1002"])).toEqual(new Map()); + } finally { + clock.mockRestore(); + } +}); + +test("cleans membership entries one millisecond after the 24-hour retention window", () => { + const db = GameDatabase.getInstance(); + let now = 100_000_000; + const clock = spyOn(Date, "now").mockImplementation(() => now); + try { + db.saveMembershipCache(-100, "1001", true); + now += 86_400_000; + db.saveMembershipCache(-100, "1002", false); + expect(db.cleanupMembershipCache()).toBe(0); + + now += 1; + expect(db.cleanupMembershipCache()).toBe(1); + expect(db.getCachedMembership(-100, "1001", 90_000_000)).toBeNull(); + expect(db.getCachedMembership(-100, "1002")).toBe(false); + } finally { + clock.mockRestore(); + } +}); + test("findTelegramIdByUsername normalizes usernames", () => { const db = GameDatabase.getInstance(); diff --git a/tests/route-cost.test.ts b/tests/route-cost.test.ts index 5eac3e4d..a2f3197a 100644 --- a/tests/route-cost.test.ts +++ b/tests/route-cost.test.ts @@ -43,6 +43,35 @@ describe("calculateRouteCosts", () => { }); }); + test("keeps omitted and explicit defaults at the same fee boundary", () => { + for (const options of [ + undefined, + {}, + { paddingRounding: "ceil", requiredStrategy: "max" }, + ] as const) { + expect(calculateRouteCosts(buildCosts(1), options)).toEqual({ + routeLamports: 1, + paddingLamports: 1, + requiredLamports: 1, + }); + expect(calculateRouteCosts(buildCosts(-10), options)).toEqual({ + routeLamports: 0, + paddingLamports: 0, + requiredLamports: 0, + }); + } + expect( + calculateRouteCosts( + { signatureFeeLamports: null }, + { requiredStrategy: "sum", baseRequiredLamports: 10 }, + ), + ).toEqual({ + routeLamports: 0, + paddingLamports: 0, + requiredLamports: 10, + }); + }); + test("handles rent-heavy routes for user payer", () => { const costs = calculateRouteCosts(buildCosts(2_310_000), { paddingRatio: 0.25, diff --git a/tests/swap-quote-cache.test.ts b/tests/swap-quote-cache.test.ts index 675df4b2..64b1ab87 100644 --- a/tests/swap-quote-cache.test.ts +++ b/tests/swap-quote-cache.test.ts @@ -23,9 +23,28 @@ describe("SwapQuoteCache", () => { expect(loadB).toHaveBeenCalledTimes(1); }); + test("shares quotes when a caller explicitly sends the default route options", async () => { + const cache = new SwapQuoteCache(); + const unqualified = makeJupiterParams(); + const standard = makeJupiterParams({ + onlyDirectRoutes: false, + swapMode: "ExactIn", + maxAccounts: 0, + platformFeeBps: 0, + }); + const quote = makeJupiterQuote(unqualified, { outAmount: "222" }); + const load = mock(async () => quote); + + await expect(cache.getJupiterQuote(unqualified, load)).resolves.toBe(quote); + await expect(cache.getJupiterQuote(standard, load)).resolves.toBe(quote); + expect(load).toHaveBeenCalledTimes(1); + }); + test.each([ ["default", undefined, 5_000], ["zero", 0, 5_000], + ["negative", -7, 5_000], + ["NaN", NaN, 5_000], ["infinity", Infinity, 5_000], ["custom", 10, 10], ] as const)("honors the expected expiry for %s TTL", async (_label, ttlMs, delay) => { From 16f994f081d093d40d8c700ce7f44294ee4a1005 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 12:39:19 -0300 Subject: [PATCH 019/410] fix(tokens): reject invalid mint decimals before caching metadata --- src/bot.ts | 3 +- src/utils/callback-data.ts | 7 ++--- src/utils/token-decimals.ts | 5 +++ src/utils/token-metadata.ts | 5 +-- src/utils/wallet.ts | 5 +-- tests/bot-privatekey.flows.test.ts | 22 +++++++++++++- tests/bot.token-metadata-cache.test.ts | 42 +++++++++++++++++++++++++- tests/token-metadata.test.ts | 20 ++++++++++++ tests/wallet.injection.test.ts | 14 +++++++++ 9 files changed, 112 insertions(+), 11 deletions(-) create mode 100644 src/utils/token-decimals.ts diff --git a/src/bot.ts b/src/bot.ts index 13042658..1bf5f351 100644 --- a/src/bot.ts +++ b/src/bot.ts @@ -197,6 +197,7 @@ import { getRetryAfterSeconds, isMessageNotModified, isRateLimited } from "./uti import { FaucetDatabase } from "./utils/faucet-database"; import { outboundErrorGuard } from "./utils/outbound-error-guard"; import { sendMediaWithFallback } from "./utils/media"; +import { isMintDecimals } from "./utils/token-decimals"; export type { CreateGameViaCommandOptions } from "./handlers/game-commands"; // ================================ @@ -428,7 +429,7 @@ const getCachedTokenMetadata = async (mint: string) => { const fetchPromise = (async () => { try { const metadata = await wallet.getTokenMetadata(normalizedMint); - if (!metadata || typeof metadata.decimals !== "number") { + if (!isMintDecimals(metadata?.decimals)) { throw new Error("Token metadata missing decimals"); } const entry: CachedTokenMetadata = { diff --git a/src/utils/callback-data.ts b/src/utils/callback-data.ts index 4be69cba..97c7909d 100644 --- a/src/utils/callback-data.ts +++ b/src/utils/callback-data.ts @@ -1,13 +1,12 @@ import type { GameType } from "../types"; import { formatAmount } from "./format-amount"; +import { MAX_MINT_DECIMALS } from "./token-decimals"; export const CALLBACK_DATA_LIMIT = 64; const CALLBACK_SEPARATOR = "|"; const AMOUNT_SEPARATOR = ":"; const ALPHABET = "0123456789abcdefghijklmnopqrstuvwxyz"; -// A Solana token stores the decimal count in one unsigned byte. -const MAX_AMOUNT_SCALE = 255; const CALLBACK_PREFIX = { confirmGame: "cg", @@ -71,7 +70,7 @@ const normalizeAmount = (amount: string): { digits: bigint; scale: number } | nu const decimalPoint = trimmed.indexOf("."); if (decimalPoint === -1) return { digits: BigInt(trimmed), scale: 0 }; const fraction = trimmed.slice(decimalPoint + 1).replace(/0+$/, ""); - if (fraction.length > MAX_AMOUNT_SCALE) return null; + if (fraction.length > MAX_MINT_DECIMALS) return null; return { digits: BigInt(trimmed.slice(0, decimalPoint) + fraction), scale: fraction.length }; }; @@ -88,7 +87,7 @@ const decodeAmount = (encoded: string | undefined): string | null => { const separator = raw.indexOf(AMOUNT_SEPARATOR); if (separator < 1) return null; const scale = decodeUnsigned(raw.slice(0, separator)); - if (scale === null || scale > MAX_AMOUNT_SCALE) return null; + if (scale === null || scale > MAX_MINT_DECIMALS) return null; const digits = decodeBase36ToBigInt(raw.slice(separator + 1)); if (digits === null) return null; diff --git a/src/utils/token-decimals.ts b/src/utils/token-decimals.ts new file mode 100644 index 00000000..8430a03c --- /dev/null +++ b/src/utils/token-decimals.ts @@ -0,0 +1,5 @@ +/** SPL mints store decimal precision in a single unsigned byte. */ +export const MAX_MINT_DECIMALS = 255; + +export const isMintDecimals = (value: unknown): value is number => + typeof value === "number" && Number.isInteger(value) && value >= 0 && value <= MAX_MINT_DECIMALS; diff --git a/src/utils/token-metadata.ts b/src/utils/token-metadata.ts index edfcd106..86c25667 100644 --- a/src/utils/token-metadata.ts +++ b/src/utils/token-metadata.ts @@ -2,6 +2,7 @@ import { Connection, PublicKey } from "#solana"; import { fetchJupiterTokenMetadata } from "./jupiter"; import type { FetchLike } from "../types"; import { deserializeMetadata } from "@metaplex-foundation/mpl-token-metadata"; +import { isMintDecimals } from "./token-decimals"; export interface TokenMetadataResult { decimals: number; @@ -79,7 +80,7 @@ export async function resolveTokenMetadata({ }: ResolveTokenMetadataParams): Promise { let cachedDecimals: number | null = null; const ensureDecimals = async (value?: number | null): Promise => { - if (typeof value === "number" && Number.isFinite(value)) { + if (isMintDecimals(value)) { cachedDecimals = value; return value; } @@ -91,7 +92,7 @@ export async function resolveTokenMetadata({ if (getDecimals) { try { const resolved = await getDecimals(); - if (typeof resolved === "number" && Number.isFinite(resolved)) { + if (isMintDecimals(resolved)) { cachedDecimals = resolved; return resolved; } diff --git a/src/utils/wallet.ts b/src/utils/wallet.ts index 868496be..adb78ce8 100644 --- a/src/utils/wallet.ts +++ b/src/utils/wallet.ts @@ -89,6 +89,7 @@ import { formatAmount } from "./format-amount"; import { isMissingAccountError } from "./account-errors"; import { WSOL_MINT } from "./token-registry"; import { resolveTokenMetadata } from "./token-metadata"; +import { isMintDecimals } from "./token-decimals"; import { detectTokenProgram, type TokenProgramDetection } from "./token-programs"; import { createExpiringCache, type ExpiringCache } from "./expiring-cache"; import { TokenDatabase } from "./token-database"; @@ -1725,7 +1726,7 @@ export class WalletManager { } try { const result = await this.tokenMetadataResolver(tokenMint); - if (result && typeof result.decimals === "number") { + if (result && isMintDecimals(result.decimals)) { this.tokenMetadataCache.setWithTTL(tokenMint, result); return result; } @@ -1774,7 +1775,7 @@ export class WalletManager { try { const parsedInfo = await getParsedAccountInfo(mintPublicKey); const parsedDecimals = parsedInfo?.value?.data?.parsed?.info?.decimals ?? null; - if (typeof parsedDecimals === "number") { + if (isMintDecimals(parsedDecimals)) { decimals = parsedDecimals; } } catch (parsedError) { diff --git a/tests/bot-privatekey.flows.test.ts b/tests/bot-privatekey.flows.test.ts index 435e3f6d..8805c299 100644 --- a/tests/bot-privatekey.flows.test.ts +++ b/tests/bot-privatekey.flows.test.ts @@ -1,4 +1,4 @@ -import { afterEach, beforeEach, describe, expect, spyOn, test } from "bun:test"; +import { afterEach, beforeEach, describe, expect, spyOn, test, vi } from "bun:test"; import { Keypair } from "#solana"; import { answers, @@ -126,6 +126,26 @@ describe("private key export", () => { expect(callsTo("sendMessage")).toHaveLength(0); }); + test.each([ + [60_000, 1], + [60_001, 0], + ] as const)( + "sends the private reply the expected number of times at %i ms", + async (age, sends) => { + vi.useFakeTimers(); + const clock = spyOn(Date, "now").mockReturnValue(1_700_000_000_000); + try { + await at("cmd_privatekey"); + clock.mockReturnValue(1_700_000_000_000 + age); + await at("confirm_privatekey"); + expect(callsTo("sendMessage")).toHaveLength(sends); + } finally { + clock.mockRestore(); + vi.useRealTimers(); + } + }, + ); + test("at most three exports are allowed per hour", async () => { const timeoutSpy = spyOn(globalThis, "setTimeout").mockImplementation( (() => ({}) as any) as any, diff --git a/tests/bot.token-metadata-cache.test.ts b/tests/bot.token-metadata-cache.test.ts index 1c5d42af..44c17908 100644 --- a/tests/bot.token-metadata-cache.test.ts +++ b/tests/bot.token-metadata-cache.test.ts @@ -1,4 +1,4 @@ -import { describe, test, expect, beforeEach } from "bun:test"; +import { describe, test, expect, beforeEach, spyOn } from "bun:test"; import { wallet, __test_getCachedTokenMetadata, @@ -43,6 +43,46 @@ describe("token metadata cache", () => { wallet.getTokenMetadata = originalGetTokenMetadata; }); + test("uses the production five-minute expiry for the normalized mint", async () => { + let now = 1_000_000; + const clock = spyOn(Date, "now").mockImplementation(() => now); + const fetch = spyOn(wallet, "getTokenMetadata").mockResolvedValue({ decimals: 2 }); + const mint = "TestMint11111111111111111111111111111111"; + try { + fetch.mockResolvedValueOnce({ decimals: 0 }); + expect((await __test_getCachedTokenMetadata(` ${mint} `)).decimals).toBe(0); + now += 299_999; + expect((await __test_getCachedTokenMetadata(mint)).decimals).toBe(0); + now += 1; + expect((await __test_getCachedTokenMetadata(mint)).decimals).toBe(2); + expect(fetch.mock.calls).toEqual([[mint], [mint]]); + } finally { + fetch.mockRestore(); + clock.mockRestore(); + } + }); + + test.each([ + ["negative", -1], + ["non-finite", Infinity], + ["fractional", 8.5], + ["outside the mint byte range", 256], + ] as const)("does not cache %s token decimals", async (_label, decimals) => { + const mint = "TestMint11111111111111111111111111111111"; + const fetch = spyOn(wallet, "getTokenMetadata") + .mockResolvedValueOnce({ decimals }) + .mockResolvedValue({ decimals: 255 }); + try { + await expect(__test_getCachedTokenMetadata(mint)).rejects.toThrow( + "Token metadata unavailable", + ); + expect((await __test_getCachedTokenMetadata(mint)).decimals).toBe(255); + expect(fetch).toHaveBeenCalledTimes(2); + } finally { + fetch.mockRestore(); + } + }); + test("coalesces concurrent fetches for the same mint", async () => { const mint = "ConcurrentMint111111111111111111111111111111"; const originalGetTokenMetadata = wallet.getTokenMetadata; diff --git a/tests/token-metadata.test.ts b/tests/token-metadata.test.ts index 009b9913..35aad5e7 100644 --- a/tests/token-metadata.test.ts +++ b/tests/token-metadata.test.ts @@ -1,5 +1,6 @@ import { afterEach, beforeEach, describe, expect, mock, spyOn, test } from "bun:test"; import { getMetadataAccountDataSerializer } from "@metaplex-foundation/mpl-token-metadata"; +import type { Connection } from "#solana"; import { resolveTokenMetadata } from "../src/utils/token-metadata"; const MINT = "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"; @@ -187,10 +188,29 @@ describe("resolveTokenMetadata", () => { expect(result).toEqual({ decimals: 2 }); }); + test.each([ + ["a negative value", -1], + ["a fractional value", 9.5], + ["a value outside the mint byte range", 256], + ] as const)("uses a valid RPC scale when metadata gives %s", async (_label, invalid) => { + const getDecimals = mock(async () => 9); + const result = await resolveTokenMetadata({ + connection: connectionWith(null) as unknown as Connection, + mintAddress: MINT, + fetch: jupiterFetch([{ id: MINT, symbol: "USDC", name: "USD Coin", decimals: invalid }]), + getDecimals, + }); + expect(result).toEqual({ symbol: "USDC", name: "USD Coin", decimals: 9 }); + expect(getDecimals).toHaveBeenCalledTimes(1); + }); + test("uses the default decimals when the resolver fails or returns nothing useful", async () => { for (const getDecimals of [ async () => null, async () => Number.NaN, + async () => -1, + async () => 256, + async () => 9.5, async () => { throw new Error("mint missing"); }, diff --git a/tests/wallet.injection.test.ts b/tests/wallet.injection.test.ts index 19147489..69a4a612 100644 --- a/tests/wallet.injection.test.ts +++ b/tests/wallet.injection.test.ts @@ -187,6 +187,20 @@ describe("WalletManager dependency injection", () => { expect((conn as any).calls.getLatestBlockhash).toBe(1); }); + test("uses RPC mint decimals instead of caching an invalid local scale", async () => { + const conn = makeMockConnection(); + const mint = "11111111111111111111111111111111"; + conn.setDecimals(mint, 9); + const wallet = WalletManager.createForTest("test mnemonic", { + connection: conn, + fetch: async () => Response.json([]), + tokenMetadataResolver: async () => ({ decimals: -1, symbol: "UNUSABLE" }), + }); + + expect(await wallet.getTokenMetadata(mint)).toEqual({ decimals: 9 }); + expect(await wallet.getTokenMetadata(mint)).toEqual({ decimals: 9 }); + }); + test("getFullTokenMetadata falls back to Jupiter and reads decimals via RPC", async () => { const conn = makeMockConnection(); const mint = "11111111111111111111111111111111"; // valid base58, not in knownTokens From 5c8c09027e4559544619a0d4a1c6de9a19b75949 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 12:42:47 -0300 Subject: [PATCH 020/410] fix(bot): scope prompt cleanup to the reply that acquired it --- src/bot.ts | 22 +++----- src/handlers/lightning.ts | 7 +-- src/utils/user-state.ts | 30 +++-------- tests/game-callbacks.module.test.ts | 10 ++-- tests/input-session.locks.test.ts | 2 +- tests/user-state.util.test.ts | 78 ++++++++++++++++++++++++++++- 6 files changed, 102 insertions(+), 47 deletions(-) diff --git a/src/bot.ts b/src/bot.ts index 1bf5f351..53493d29 100644 --- a/src/bot.ts +++ b/src/bot.ts @@ -6070,8 +6070,6 @@ bot.on("message:text", async (ctx, next) => { const userMessage = ctx.message.text.trim(); - const previousSessionType = inputSession.type; - try { if (inputSession.type === "send_custom_amount") { await handleCustomAmountInput(ctx, inputSession, userMessage); @@ -6087,16 +6085,10 @@ bot.on("message:text", async (ctx, next) => { await chatDefaultsModule.handleSettingsInput(ctx, inputSession, userMessage); } - const updatedSession = getInputSession(sessionKey); - const sessionTransitioned = updatedSession && updatedSession.type !== previousSessionType; - - // Clear session after successful processing unless a new session replaced it - if (!sessionTransitioned) { - clearInputSession(sessionKey); - } + clearInputSession(sessionKey, lockerId); } catch (error) { // Clear session even on error to prevent stuck states - clearInputSession(sessionKey); + clearInputSession(sessionKey, lockerId); console.error("Error handling user input:", error); // Try to update the original message with error @@ -6112,7 +6104,7 @@ bot.on("message:text", async (ctx, next) => { }); } } finally { - clearInputSessionProcessing(sessionKey); + clearInputSessionProcessing(sessionKey, lockerId); } }); @@ -6185,7 +6177,7 @@ const handleMediaForChatDefaults = async ( "Files sent as documents are not supported.", { parse_mode: "HTML" }, ); - clearInputSession(sessionKey); + clearInputSession(sessionKey, lockerId); return; } @@ -6193,15 +6185,15 @@ const handleMediaForChatDefaults = async ( (ctx as any).__mediaType = mediaType; await chatDefaultsModule.handleSettingsInput(ctx, inputSession, ""); - clearInputSession(sessionKey); + clearInputSession(sessionKey, lockerId); } catch (error) { - clearInputSession(sessionKey); + clearInputSession(sessionKey, lockerId); console.error("Error handling media input for chat defaults:", error); await replyEphemeralToSender(ctx, "❌ Error processing media\n\nPlease try again.", { parse_mode: "HTML", }); } finally { - clearInputSessionProcessing(sessionKey); + clearInputSessionProcessing(sessionKey, lockerId); } }; diff --git a/src/handlers/lightning.ts b/src/handlers/lightning.ts index 4d914b2e..ef5e22d2 100644 --- a/src/handlers/lightning.ts +++ b/src/handlers/lightning.ts @@ -335,12 +335,13 @@ export function registerLightningDeposits( pending.session.initiatorId !== String(ctx.from.id) ) return await next(); - if (!markInputSessionProcessing(pending.key, String(ctx.message.message_id))) return; + const lockerId = String(ctx.message.message_id); + if (!markInputSessionProcessing(pending.key, lockerId)) return; try { const accepted = await amount(ctx, ctx.message.text, pending.session.messageId); - if (accepted !== false) clearInputSession(pending.key); + if (accepted !== false) clearInputSession(pending.key, lockerId); } finally { - clearInputSessionProcessing(pending.key); + clearInputSessionProcessing(pending.key, lockerId); } }); bot.callbackQuery(/^ln_(create|status|cancel):([0-9a-f-]{36})$/, async (ctx) => { diff --git a/src/utils/user-state.ts b/src/utils/user-state.ts index 70718a79..175b2d1b 100644 --- a/src/utils/user-state.ts +++ b/src/utils/user-state.ts @@ -213,7 +213,9 @@ export const findInputSession = ( return latest ? { key: latest.key, session: latest.session } : undefined; }; -export const clearInputSession = (key: string): void => { +export const clearInputSession = (key: string, lockerId?: string): void => { + // An async handler may finish after another prompt has replaced this key. + if (lockerId !== undefined && getInputSession(key)?.processingBy !== lockerId) return; clearNamespacedState(INPUT_SESSION_NAMESPACE, key); }; @@ -226,18 +228,8 @@ const getInputSessionNamespacedKey = (key: string): string => export const markInputSessionProcessing = (key: string, lockerId: string): boolean => { const namespacedKey = getInputSessionNamespacedKey(key); - const existing = userStates.get(namespacedKey); - if (!existing) { - return false; - } - - if ( - existing["processing"] === true && - typeof existing["processingBy"] === "string" && - existing["processingBy"] !== lockerId - ) { - return false; - } + const existing = getUserState(namespacedKey); + if (!existing || existing.processing === true) return false; userStates.set(namespacedKey, { ...existing, @@ -248,16 +240,10 @@ export const markInputSessionProcessing = (key: string, lockerId: string): boole return true; }; -export const clearInputSessionProcessing = (key: string): void => { +export const clearInputSessionProcessing = (key: string, lockerId: string): void => { const namespacedKey = getInputSessionNamespacedKey(key); - const existing = userStates.get(namespacedKey); - if (!existing) { - return; - } - - if (!existing["processing"] && !existing["processingBy"]) { - return; - } + const existing = getUserState(namespacedKey); + if (!existing || existing.processingBy !== lockerId) return; const sanitized = { ...existing }; Reflect.deleteProperty(sanitized, "processing"); diff --git a/tests/game-callbacks.module.test.ts b/tests/game-callbacks.module.test.ts index 0cbca7e6..d50bf95b 100644 --- a/tests/game-callbacks.module.test.ts +++ b/tests/game-callbacks.module.test.ts @@ -280,11 +280,11 @@ describe("joining a game", () => { }); test.each([ - [{ id: 7, username: "@@bob" }, "@bob"], - [{ id: 7, first_name: "Ann", last_name: "Lee" }, "Ann Lee"], - [{ id: 7, username: "@", first_name: "Ann" }, null], - [{ id: 7, first_name: " ", last_name: "" }, null], - ])("derives the display name from %p", async (from, expected) => { + ["a repeated at sign", { id: 7, username: "@@bob" }, "@bob"], + ["a first and last name", { id: 7, first_name: "Ann", last_name: "Lee" }, "Ann Lee"], + ["an empty handle", { id: 7, username: "@", first_name: "Ann" }, null], + ["an empty name", { id: 7, first_name: " ", last_name: "" }, null], + ])("derives the display name from %s", async (_label, from, expected) => { const h = setup(); await run(h, `join_${GAME}`, from); diff --git a/tests/input-session.locks.test.ts b/tests/input-session.locks.test.ts index 24721a23..669f5df0 100644 --- a/tests/input-session.locks.test.ts +++ b/tests/input-session.locks.test.ts @@ -156,6 +156,6 @@ test("ignores duplicate replies while another handler is processing", async () = expect(sessionEntry.processing).toBe(true); expect(sessionEntry.processingBy).toBe(lockerId); - clearInputSessionProcessing(sessionKey); + clearInputSessionProcessing(sessionKey, lockerId); __test_clearRawState(`${INPUT_NAMESPACE_PREFIX}${sessionKey}`); }); diff --git a/tests/user-state.util.test.ts b/tests/user-state.util.test.ts index 24c176c8..ac25f609 100644 --- a/tests/user-state.util.test.ts +++ b/tests/user-state.util.test.ts @@ -1,4 +1,4 @@ -import { test, expect } from "bun:test"; +import { test, expect, spyOn } from "bun:test"; import { setUserState, getUserState, @@ -8,6 +8,10 @@ import { __test_clearUserState, __test_getRawPending, markInputSessionProcessing, + clearInputSessionProcessing, + setInputSession, + getInputSession, + clearInputSession, } from "../src/utils/user-state"; import { INPUT_TIMEOUT_MS } from "../src/utils/constants"; @@ -104,3 +108,75 @@ test("markInputSessionProcessing refuses to lock a missing input session", () => expect(markInputSessionProcessing(key, "locker")).toBe(false); expect(__test_getRawUserState(`input_session:${key}`)).toBeUndefined(); }); + +test("keeps state and a pending transaction at the 15-minute boundary", () => { + const clock = spyOn(Date, "now").mockReturnValue(1_000_000); + try { + setUserState("expiry-user", { type: "send" }); + storePendingTransaction("expiry-tx", { type: "swap" }); + clock.mockReturnValue(1_900_000); + setUserState("expiry-user-other", { type: "other" }); + storePendingTransaction("expiry-tx-other", { type: "other" }); + expect(getUserState("expiry-user")).toMatchObject({ type: "send" }); + expect(getPendingTransaction("expiry-tx", false)).toMatchObject({ type: "swap" }); + + clock.mockReturnValue(1_900_001); + expect(getUserState("expiry-user")).toBeUndefined(); + expect(getPendingTransaction("expiry-tx", false)).toBeUndefined(); + } finally { + clock.mockRestore(); + for (const id of ["expiry-user", "expiry-user-other"]) __test_clearUserState(id); + for (const id of ["expiry-tx", "expiry-tx-other"]) getPendingTransaction(id); + } +}); + +test("refuses a duplicate delivery of the reply while the first copy is processing", () => { + const key = "duplicate-prompt"; + try { + setInputSession(key, { type: "send" }); + expect(markInputSessionProcessing(key, "same-message")).toBe(true); + expect(markInputSessionProcessing(key, "same-message")).toBe(false); + expect(markInputSessionProcessing(key, "later-message")).toBe(false); + clearInputSessionProcessing(key, "same-message"); + expect(markInputSessionProcessing(key, "later-message")).toBe(true); + } finally { + clearInputSession(key); + } +}); + +test("does not give an expired prompt a processing lock", () => { + const key = "expired-prompt"; + const clock = spyOn(Date, "now").mockReturnValue(1_000_000); + try { + setInputSession(key, { type: "send" }); + clock.mockReturnValue(1_900_001); + expect(markInputSessionProcessing(key, "late-message")).toBe(false); + expect(getInputSession(key)).toBeUndefined(); + } finally { + clock.mockRestore(); + clearInputSession(key); + } +}); + +test("an old reply cannot release the lock on a replacement prompt", () => { + const key = "replacement-prompt"; + try { + setInputSession(key, { type: "send" }); + expect(markInputSessionProcessing(key, "old-reply")).toBe(true); + setInputSession(key, { type: "swap" }); + expect(markInputSessionProcessing(key, "new-reply")).toBe(true); + clearInputSession(key, "old-reply"); + expect(getInputSession(key)?.type).toBe("swap"); + clearInputSessionProcessing(key, "old-reply"); + expect(getInputSession(key)).toEqual({ + type: "swap", + processing: true, + processingBy: "new-reply", + }); + expect(markInputSessionProcessing(key, "another-reply")).toBe(false); + clearInputSessionProcessing(key, "new-reply"); + expect(getInputSession(key)).toEqual({ type: "swap" }); + } finally { + clearInputSession(key); + } +}); From 71d08270da52ba1c2c719cd96672816433d0f185 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 12:46:39 -0300 Subject: [PATCH 021/410] test(rpc): bound cancellation and referral retry checks --- src/services/fee-sweeper.ts | 3 +- src/utils/rpc-endpoints.ts | 2 +- tests/fee-sweeper.paths.test.ts | 19 +++++ tests/rpc-request-budget.happy-path.test.ts | 25 +++--- tests/rpc-request-budget.test.ts | 93 ++++++++++++--------- 5 files changed, 85 insertions(+), 57 deletions(-) diff --git a/src/services/fee-sweeper.ts b/src/services/fee-sweeper.ts index 2426ad46..2ef5a7ef 100644 --- a/src/services/fee-sweeper.ts +++ b/src/services/fee-sweeper.ts @@ -526,8 +526,7 @@ async function runReferralSweep( console.log(`🧾 Found ${transactions.length} referral transaction(s). Processing...`); let processedClaims = 0; - for (let i = 0; i < transactions.length; i++) { - const tx = transactions[i]; + for (const [i, tx] of transactions.entries()) { if (!tx) continue; const latestBlockhash = await connection.getLatestBlockhash("confirmed"); tx.message.recentBlockhash = asBlockhash(String(latestBlockhash.blockhash)); diff --git a/src/utils/rpc-endpoints.ts b/src/utils/rpc-endpoints.ts index d91fb3eb..3d178c01 100644 --- a/src/utils/rpc-endpoints.ts +++ b/src/utils/rpc-endpoints.ts @@ -262,7 +262,7 @@ export class RpcEndpointManager { const total = this.endpoints.length; const startIndex = this.activeIndex; - for (let offset = 0; offset < total; offset++) { + for (const offset of this.endpoints.keys()) { if (isRead && Date.now() >= deadline) break; const index = (startIndex + offset) % total; const connection = this.ensureConnection(index); diff --git a/tests/fee-sweeper.paths.test.ts b/tests/fee-sweeper.paths.test.ts index 65010948..3f53076f 100644 --- a/tests/fee-sweeper.paths.test.ts +++ b/tests/fee-sweeper.paths.test.ts @@ -371,6 +371,25 @@ describe("referral claims", () => { expect(claim).not.toHaveBeenCalled(); }); + test("skips empty entries and sends each referral claim once in provider order", async () => { + type SweepInputs = Parameters; + const first = { ...fakeTx(), serialize: () => new Uint8Array([8]) }; + const second = { ...fakeTx(), serialize: () => new Uint8Array([9]) }; + const s = await claimSetup({ transactions: [undefined, first, undefined, second] }); + expect( + await __test_runReferralSweep( + s.connection as unknown as SweepInputs[0], + s.payer, + referral, + price(1), + () => s.provider as unknown as ReturnType>, + ), + ).toBe(2); + expect(s.sent.map((raw) => Array.from(raw))).toEqual([[8], [9]]); + expect(first.sign).toHaveBeenCalledTimes(1); + expect(second.sign).toHaveBeenCalledTimes(1); + }); + test("signs each claim with a fresh blockhash and records claimed deltas", async () => { const tx = fakeTx(); const s = await claimSetup({ transactions: [undefined, tx] }); diff --git a/tests/rpc-request-budget.happy-path.test.ts b/tests/rpc-request-budget.happy-path.test.ts index 3147e0b0..a7a64eef 100644 --- a/tests/rpc-request-budget.happy-path.test.ts +++ b/tests/rpc-request-budget.happy-path.test.ts @@ -71,7 +71,6 @@ describe("backgroundRpc", () => { const waitForTick = async () => { for (let step = 0; step < 12; step += 1) await Promise.resolve(); }; - let second: Promise | undefined; try { const scope = "https://test-shared-key-budget.test"; await expect( @@ -79,7 +78,7 @@ describe("backgroundRpc", () => { throw new Error("first request failed"); }), ).rejects.toThrow("first request failed"); - second = backgroundRpc(`${scope}/two`, controller.signal, async () => { + void backgroundRpc(`${scope}/two`, controller.signal, async () => { hits.push(["same host", now]); }).catch((error: unknown) => error); await waitForTick(); @@ -108,7 +107,7 @@ describe("backgroundRpc", () => { ]); } finally { controller.abort(); - await second; + await waitForTick(); clock.mockRestore(); vi.useRealTimers(); } @@ -130,7 +129,13 @@ test("bounded RPC stops hanging reads and clears a completed read's timer", asyn vi.useFakeTimers(); const never = Promise.withResolvers(); try { - expect(await boundedRpc(async () => "done", 9)).toBe("done"); + const completed: unknown[] = []; + void boundedRpc(async () => "done", 9).then( + (result) => completed.push(result), + (error: unknown) => completed.push(error), + ); + for (let step = 0; step < 8; step += 1) await Promise.resolve(); + expect(completed).toEqual(["done"]); expect(vi.getTimerCount()).toBe(0); const outcomes: unknown[] = []; void boundedRpc(() => never.promise, 7).catch((error: unknown) => { @@ -159,16 +164,10 @@ test("a failed foreground request releases the background lane", async () => { }), ).rejects.toBe(error); const calls: string[] = []; - const task = backgroundRpc( - "https://after-foreground-error.test", - controller.signal, - async () => { - calls.push("started"); - }, - ).catch((failure: unknown) => failure); + void backgroundRpc("https://after-foreground-error.test", controller.signal, async () => { + calls.push("started"); + }).catch((failure: unknown) => failure); for (let step = 0; step < 8; step += 1) await Promise.resolve(); - controller.abort(); - await task; expect(calls).toEqual(["started"]); } finally { controller.abort(); diff --git a/tests/rpc-request-budget.test.ts b/tests/rpc-request-budget.test.ts index d34d69d6..9f07f99d 100644 --- a/tests/rpc-request-budget.test.ts +++ b/tests/rpc-request-budget.test.ts @@ -1,29 +1,36 @@ -import { expect, test } from "bun:test"; +import { expect, spyOn, test, vi } from "bun:test"; import { backgroundRpc, foregroundRpc, noteRpcRateLimit } from "../src/utils/rpc-request-budget"; +const flushTasks = async () => { + for (let step = 0; step < 12; step += 1) await Promise.resolve(); +}; + test("background waits for foreground and rechecks shared-host cooldown", async () => { - let release!: () => void; - const foreground = foregroundRpc( - () => - new Promise((resolve) => { - release = resolve; - }), - ); - let called = false; - const background = backgroundRpc( - "https://budget.test/key-a", - AbortSignal.timeout(2000), - async () => { - called = true; - }, - ); - await new Promise((resolve) => setTimeout(resolve, 20)); - expect(called).toBe(false); - noteRpcRateLimit("https://budget.test/key-b", "10"); - release(); - await foreground; - await expect(background).rejects.toThrow("cooling down"); - expect(called).toBe(false); + vi.useFakeTimers(); + const now = spyOn(Date, "now").mockReturnValue(1_000); + const gate = Promise.withResolvers(); + const controller = new AbortController(); + const outcomes: unknown[] = []; + try { + const foreground = foregroundRpc(() => gate.promise); + void backgroundRpc("https://budget.test/key-a", controller.signal, async () => "called").then( + (result) => outcomes.push(result), + (error: unknown) => outcomes.push(error), + ); + await flushTasks(); + expect(outcomes).toEqual([]); + expect(noteRpcRateLimit("https://budget.test/key-b", "10")).toBe(11_000); + gate.resolve(); + await foreground; + vi.advanceTimersByTime(10); + await flushTasks(); + expect(outcomes).toEqual([expect.objectContaining({ retryAt: 11_000 })]); + } finally { + controller.abort(); + gate.resolve(); + now.mockRestore(); + vi.useRealTimers(); + } }); test("Retry-After supports seconds and dates", () => { expect(noteRpcRateLimit("https://seconds.test", "7", 1000)).toBe(8000); @@ -39,24 +46,28 @@ test("aborted background work never calls the provider", async () => { ).rejects.toThrow("cancelled"); }); test("aborting while background work waits for foreground traffic rejects without calling", async () => { - let release!: () => void; - const foreground = foregroundRpc( - () => - new Promise((resolve) => { - release = resolve; - }), - ); + vi.useFakeTimers(); + const gate = Promise.withResolvers(); const controller = new AbortController(); - let called = false; - const background = backgroundRpc("https://abort-wait.test", controller.signal, async () => { - called = true; - }); - await new Promise((resolve) => setTimeout(resolve, 20)); const reason = new Error("scan cancelled"); - controller.abort(reason); - - await expect(background).rejects.toBe(reason); - expect(called).toBe(false); - release(); - await foreground; + const outcomes: unknown[] = []; + const foreground = foregroundRpc(() => gate.promise); + try { + void backgroundRpc("https://abort-wait.test", controller.signal, async () => "called").then( + (result) => outcomes.push(result), + (error: unknown) => outcomes.push(error), + ); + await flushTasks(); + expect(outcomes).toEqual([]); + expect(vi.getTimerCount()).toBe(1); + controller.abort(reason); + await flushTasks(); + expect(outcomes).toEqual([reason]); + expect(vi.getTimerCount()).toBe(0); + } finally { + controller.abort(); + gate.resolve(); + await foreground; + vi.useRealTimers(); + } }); From dda457b307d90cfe6b653810772d1bbcae9870ab Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 12:50:25 -0300 Subject: [PATCH 022/410] fix(settings): reject partial numeric chat settings --- src/handlers/chat-defaults.ts | 21 ++++++++++----- tests/bot-middleware.test.ts | 10 +++---- tests/chat-defaults.handler.test.ts | 42 +++++++++++++++++++++++++++++ 3 files changed, 61 insertions(+), 12 deletions(-) diff --git a/src/handlers/chat-defaults.ts b/src/handlers/chat-defaults.ts index b1e2c7df..ed2780ef 100644 --- a/src/handlers/chat-defaults.ts +++ b/src/handlers/chat-defaults.ts @@ -65,6 +65,13 @@ const formatBuyAlertMediaSummary = (mediaId: string | null | undefined): string return "Custom"; }; +const parseSettingsInteger = (input: string): number | null => { + const trimmed = input.trim(); + if (!/^[+-]?\d+$/.test(trimmed)) return null; + const value = Number(trimmed); + return Number.isSafeInteger(value) ? value : null; +}; + export const isChatDefaultsMediaSetting = ( setting: string | undefined, ): setting is "video_coinflip" | "video_giveaway" | "video_buy_alerts" => @@ -519,9 +526,9 @@ const handlePlayersUpdate = async ( return; } - const parsed = Number.parseInt(input.trim(), 10); - const clamped = clampChatPlayers(parsed, target, maxLimit); - if (clamped === null || Number.isNaN(parsed)) { + const parsed = parseSettingsInteger(input); + const clamped = parsed === null ? null : clampChatPlayers(parsed, target, maxLimit); + if (clamped === null) { await deps.replyErrorToMessage( ctx, `❌ Invalid number. Please enter a value between ${minValue}-${maxLimit}.`, @@ -566,8 +573,8 @@ const handleTimeoutUpdate = async ( return; } - const parsed = Number.parseInt(input.trim(), 10); - if (!Number.isFinite(parsed)) { + const parsed = parseSettingsInteger(input); + if (parsed === null) { await deps.replyErrorToMessage(ctx, "❌ Please enter a valid number of seconds."); return; } @@ -1270,8 +1277,8 @@ export const createChatDefaultsModule = (deps: ChatDefaultsModuleDeps): ChatDefa return true; } - const rate = parseInt(userMessage.trim(), 10); - if (isNaN(rate) || rate < 0 || rate > MAX_JOIN_NOTIFICATIONS_PER_MINUTE) { + const rate = parseSettingsInteger(userMessage); + if (rate === null || rate < 0 || rate > MAX_JOIN_NOTIFICATIONS_PER_MINUTE) { await deps.replyErrorToMessage( ctx, `❌ Invalid rate. Please enter a number between 0 and ${MAX_JOIN_NOTIFICATIONS_PER_MINUTE}.`, diff --git a/tests/bot-middleware.test.ts b/tests/bot-middleware.test.ts index e421c118..dd579f8d 100644 --- a/tests/bot-middleware.test.ts +++ b/tests/bot-middleware.test.ts @@ -36,11 +36,11 @@ describe("global error boundary", () => { bot.errorHandler(new BotError(new Error("handler exploded"), { update } as any)); test.each([ - [{ callback_query: {} }, "callback_query"], - [{ message: {} }, "message"], - [{ edited_message: {} }, "update"], - [undefined, "update"], - ])("names the kind of update that failed: %p", async (update, path) => { + ["callback query", { callback_query: {} }, "callback_query"], + ["message", { message: {} }, "message"], + ["edited message", { edited_message: {} }, "update"], + ["missing update", undefined, "update"], + ])("names the kind of update that failed: %s", async (_label, update, path) => { await report(update); expect(errorSpy).toHaveBeenCalledWith(`Bot error while handling ${path}:`, expect.any(Error)); }); diff --git a/tests/chat-defaults.handler.test.ts b/tests/chat-defaults.handler.test.ts index eaed4fea..dcc67db1 100644 --- a/tests/chat-defaults.handler.test.ts +++ b/tests/chat-defaults.handler.test.ts @@ -239,6 +239,48 @@ describe("chat defaults module", () => { expect(replies.some((text) => text.includes("Default game timeout"))).toBe(true); }); + test.each([ + ["coinflip count", { setting: "coinflip" }, "coinflip_max_players", " +08 ", 8], + ["giveaway count", { setting: "giveaway" }, "giveaway_max_players", " 07 ", 7], + ["timeout", { setting: "timeout" }, "timeout_seconds", " +7200 ", 7200], + ["join rate", { target: "join_rate_custom" }, "join_notifications_per_minute", " +05 ", 5], + ] as const)( + "changes %s only for a complete decimal integer", + async (_label, setting, key, valid, expected) => { + type ModuleInputs = Parameters[0]; + const { ctx } = buildMockContext(); + const errors: string[] = []; + const module = createChatDefaultsModule({ + bot: new Bot("test-token"), + chatDb, + gameDb, + getTokenManager: baseTokenManager, + getGameManager: () => ({}) as ReturnType, + wrapCallbackHandler: (handler) => async (context, next) => await handler(context, next), + getOracleMaxPlayers: () => 25, + isUserGroupAdmin: async () => true, + replyToMessage: async () => {}, + replyErrorToMessage: async (_context, text) => { + errors.push(text); + }, + }); + const session: InputSessionState = { + type: "chat_defaults", + chatId: 99, + initiatorId: "123", + ...setting, + }; + + await module.handleSettingsInput(ctx, session, valid); + expect(chatDb.getChatGameSettings(99)?.[key]).toBe(expected); + for (const invalid of ["2.5", "2e3", "0x10", "12players", "9007199254740992"]) { + await module.handleSettingsInput(ctx, session, invalid); + expect(chatDb.getChatGameSettings(99)?.[key]).toBe(expected); + } + expect(errors).toHaveLength(5); + }, + ); + test("displays username from gameDb when available", async () => { const tokenManager = baseTokenManager(); tokenManager.setChatDefaultToken(99, "mint", "AAA", "12345"); From e62395b7b37fbd2ac8d57398338d58104df1f013 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 12:53:17 -0300 Subject: [PATCH 023/410] refactor(evm): simplify canonical game-button validation --- src/evm/bot.ts | 6 ++--- tests/evm.bot-store-setup.test.ts | 37 +++++++++++++++++++++++++++++++ 2 files changed, 40 insertions(+), 3 deletions(-) diff --git a/src/evm/bot.ts b/src/evm/bot.ts index 25ac5a5b..b84deb21 100644 --- a/src/evm/bot.ts +++ b/src/evm/bot.ts @@ -33,10 +33,10 @@ export function gameCallback(action: string, game: Hex) { return `evm:${action}:${Buffer.from(game.slice(2), "hex").toString("base64url")}`; } export function callbackGame(value: string): Hex { - if (!/^[A-Za-z0-9_-]{43}$/.test(value)) throw new Error("Invalid game callback"); + // A 32-byte id has 43 unpadded base64url characters. Bound the input before decoding. + if (value.length !== 43) throw new Error("Invalid game callback"); const bytes = Buffer.from(value, "base64url"); - if (bytes.length !== 32 || bytes.toString("base64url") !== value) - throw new Error("Invalid game callback"); + if (bytes.toString("base64url") !== value) throw new Error("Invalid game callback"); return `0x${bytes.toString("hex")}`; } export function registerEvmBot( diff --git a/tests/evm.bot-store-setup.test.ts b/tests/evm.bot-store-setup.test.ts index 2baec463..676bdfbd 100644 --- a/tests/evm.bot-store-setup.test.ts +++ b/tests/evm.bot-store-setup.test.ts @@ -3,6 +3,7 @@ import { Bot, type Context } from "grammy"; import { mkdtempSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; +import fc from "fast-check"; import type { Address, Hex } from "viem"; import { callbackGame, gameCallback, registerEvmBot } from "../src/evm/bot"; import { registerEvmSetup } from "../src/evm/setup"; @@ -37,6 +38,42 @@ describe("evm callbackGame validation", () => { const forged = `${"A".repeat(42)}B`; expect(() => callbackGame(forged)).toThrow("Invalid game callback"); }); + + test("encodes a zero game id as the fixed-length Telegram button", () => { + const zero = `0x${"00".repeat(32)}` as Hex; + const encoded = "A".repeat(43); + expect(gameCallback("j", zero)).toBe(`evm:j:${encoded}`); + expect(callbackGame(encoded)).toBe(zero); + }); + + test("rejects non-canonical and oversized button data", () => { + const encoded = "A".repeat(43); + for (const invalid of [ + "", + "A".repeat(42), + "A".repeat(44), + `${encoded}=`, + ` ${encoded}`, + `${encoded}\n`, + `${"A".repeat(42)}+`, + "é".repeat(43), + "A".repeat(10_000), + ]) { + expect(() => callbackGame(invalid)).toThrow("Invalid game callback"); + } + }); + + test("keeps every byte of an ABI game id through the button encoding", () => { + fc.assert( + fc.property(fc.uint8Array({ minLength: 32, maxLength: 32 }), (bytes) => { + const id = `0x${Buffer.from(bytes).toString("hex")}` as Hex; + const callback = gameCallback("j", id); + expect(Buffer.byteLength(callback)).toBe(49); + expect(callbackGame(callback.slice("evm:j:".length))).toBe(id); + }), + { seed: 451, numRuns: 192 }, + ); + }); }); describe("EvmBotStore identity", () => { From 9fcb755e58f73d79252fe39c64b05b59876ed7dd Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 12:55:22 -0300 Subject: [PATCH 024/410] fix(swaps): enforce the token-account visibility deadline --- src/utils/swap-manager.ts | 11 +++- tests/swap-manager.token-account-wait.test.ts | 64 ++++++++++++++++++- 2 files changed, 72 insertions(+), 3 deletions(-) diff --git a/src/utils/swap-manager.ts b/src/utils/swap-manager.ts index 62354aef..147a78b6 100644 --- a/src/utils/swap-manager.ts +++ b/src/utils/swap-manager.ts @@ -41,6 +41,7 @@ import { SwapQuoteCache } from "./swap/quote-cache"; import { getReferralConfig } from "./token-registry"; import { SwapService } from "./swap/service"; import { calculateRouteCosts, DEFAULT_ROUTE_LAMPORTS_PADDING } from "./swap/route-cost"; +import { boundedRpc } from "./rpc-request-budget"; import { DEFAULT_REFERRAL_BASE_FEE_BPS, DEFAULT_MAX_EXTRA_FEE_BPS, @@ -1278,8 +1279,14 @@ export class SwapManager { const connection = this.wallet.getConnection?.() ?? this.connection; while (Date.now() < deadline) { try { - const infos = await connection.getMultipleAccountsInfo(addresses, "confirmed"); - if (infos.every((info) => info !== null)) { + const infos = await boundedRpc( + () => connection.getMultipleAccountsInfo(addresses, "confirmed"), + deadline - Date.now(), + ); + if ( + infos.length === addresses.length && + addresses.every((_key, index) => infos[index] != null) + ) { return; } } catch (error) { diff --git a/tests/swap-manager.token-account-wait.test.ts b/tests/swap-manager.token-account-wait.test.ts index 3e74e13d..b0302b62 100644 --- a/tests/swap-manager.token-account-wait.test.ts +++ b/tests/swap-manager.token-account-wait.test.ts @@ -1,4 +1,4 @@ -import { describe, expect, test, vi } from "bun:test"; +import { describe, expect, spyOn, test, vi } from "bun:test"; import { Keypair, PublicKey } from "#solana"; import { SwapManager } from "../src/utils/swap-manager"; @@ -15,6 +15,68 @@ const createSwapManager = (connection: any, walletOverrides: Record }; describe("SwapManager token-account setup wait", () => { + const account = { data: new Uint8Array() }; + const keys = [new PublicKey("11111111111111111111111111111111"), new PublicKey(WSOL)]; + + test.each([ + ["empty", []], + ["short", [account]], + ["sparse", Array(2)], + ["missing entry", [account, undefined]], + ["null entry", [account, null]], + ["extra entry", [account, account, account]], + ] as const)("keeps polling after the %s account response", async (_case, incomplete) => { + const getMultipleAccountsInfo = vi.fn( + async ( + _keys: PublicKey[], + _commitment: string, + ): Promise => [account, account], + ); + getMultipleAccountsInfo.mockResolvedValueOnce(incomplete); + const { sm, sleeps } = createSwapManager({ getMultipleAccountsInfo }); + + await sm["waitForTokenAccounts"](keys); + + expect(getMultipleAccountsInfo.mock.calls).toEqual([ + [keys, "confirmed"], + [keys, "confirmed"], + ]); + expect(sleeps).toEqual([250]); + }); + + test("stops a hung lookup at the 2-second visibility deadline", async () => { + vi.useFakeTimers(); + const now = spyOn(Date, "now").mockReturnValue(1_000_000); + const pending = Promise.withResolvers<(typeof account)[]>(); + const getMultipleAccountsInfo = vi.fn(() => pending.promise); + const { sm, sleeps } = createSwapManager({ getMultipleAccountsInfo }); + const outcomes: unknown[] = []; + const flush = async () => { + for (let tick = 0; tick < 12; tick += 1) await Promise.resolve(); + }; + try { + void sm["waitForTokenAccounts"](keys).then( + () => outcomes.push("done"), + (error: unknown) => outcomes.push(error), + ); + now.mockReturnValue(1_001_999); + vi.advanceTimersByTime(1_999); + await flush(); + expect(outcomes).toEqual([]); + now.mockReturnValue(1_002_000); + vi.advanceTimersByTime(1); + await flush(); + expect(outcomes).toEqual(["done"]); + expect(getMultipleAccountsInfo).toHaveBeenCalledTimes(1); + expect(sleeps).toEqual([]); + } finally { + pending.resolve([account, account]); + await flush(); + now.mockRestore(); + vi.useRealTimers(); + } + }); + test("stops polling as soon as the created accounts are visible", async () => { const created = (await Keypair.generate()).publicKey; let polls = 0; From b75386727111ce394917201e4e85c2468cc6e5f5 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 13:01:47 -0300 Subject: [PATCH 025/410] fix(games): keep obsolete scans out of the public game cache --- src/utils/game.ts | 17 +++--- tests/game-manager.public-page.test.ts | 71 +++++++++++++++++++++++++- 2 files changed, 81 insertions(+), 7 deletions(-) diff --git a/src/utils/game.ts b/src/utils/game.ts index 9ab8aa0d..f11cc490 100644 --- a/src/utils/game.ts +++ b/src/utils/game.ts @@ -6967,17 +6967,20 @@ export class GameManager { entries = cached.entries; } else { if (!this.publicGamesInFlight) { - this.publicGamesInFlight = this.fetchActivePublicGameEntries() + const scan = this.fetchActivePublicGameEntries() .then((fetched) => { - this.publicGamesCache = { - entries: fetched, - expiresAt: Date.now() + PUBLIC_GAMES_CACHE_TTL_MS, - }; + if (this.publicGamesInFlight === scan) { + this.publicGamesCache = { + entries: fetched, + expiresAt: Date.now() + PUBLIC_GAMES_CACHE_TTL_MS, + }; + } return fetched; }) .finally(() => { - this.publicGamesInFlight = null; + if (this.publicGamesInFlight === scan) this.publicGamesInFlight = null; }); + this.publicGamesInFlight = scan; } entries = await this.publicGamesInFlight; } @@ -6989,6 +6992,8 @@ export class GameManager { /** Drop the cached /public list, e.g. after a game is created, joined or closed. */ public invalidatePublicGamesCache(): void { this.publicGamesCache = null; + // A read started before the update must not populate the replacement cache. + this.publicGamesInFlight = null; } private static isPublicEntryExpired(account: any): boolean { diff --git a/tests/game-manager.public-page.test.ts b/tests/game-manager.public-page.test.ts index a007c89d..96d4b592 100644 --- a/tests/game-manager.public-page.test.ts +++ b/tests/game-manager.public-page.test.ts @@ -1,5 +1,6 @@ -import { afterEach, describe, expect, test, vi } from "bun:test"; +import { afterEach, describe, expect, spyOn, test, vi } from "bun:test"; import { Keypair, PublicKey } from "#solana"; +import type { Context } from "grammy"; import { GameManager } from "../src/utils/game"; const now = () => Math.floor(Date.now() / 1000); @@ -108,6 +109,74 @@ describe("GameManager.getActivePublicGamesPage", () => { expect(all).toHaveBeenCalledTimes(3); }); + test("refreshes a complete public scan at the exact eight-second deadline", async () => { + const start = 1_700_000_000_000; + const clock = spyOn(Date, "now").mockReturnValue(start); + const games = [await makeGame()]; + const all = vi.fn(async () => games); + const manager = createManager( + { account: { game: { all } } }, + { getTokenMetadata: async () => ({ symbol: "TIMBA" }) }, + ); + stubFormatting(manager); + const read = () => manager.getActivePublicGamesPage({} as Context, { page: 0, pageSize: 5 }); + await read(); + clock.mockReturnValue(start + 7_999); + await read(); + expect(all).toHaveBeenCalledTimes(1); + clock.mockReturnValue(start + 8_000); + await read(); + expect(all).toHaveBeenCalledTimes(2); + }); + + test.each(["old scan finishes first", "new scan finishes first"] as const)( + "keeps a new public scan after invalidation when the %s", + async (order) => { + const removed = [await makeGame()]; + const current = [await makeGame()]; + const oldRead = Promise.withResolvers(); + const newRead = Promise.withResolvers(); + const all = vi.fn(() => newRead.promise).mockImplementationOnce(() => oldRead.promise); + const manager = createManager( + { account: { game: { all } } }, + { getTokenMetadata: async () => ({ symbol: "TIMBA" }) }, + ); + stubFormatting(manager); + const read = async () => { + const page = await manager.getActivePublicGamesPage({} as Context, { + page: 0, + pageSize: 5, + }); + return page.games.map((game) => game.gameAddress); + }; + const initial = read(); + manager.invalidatePublicGamesCache(); + const updated = read(); + let concurrent: ReturnType | undefined; + try { + expect(all).toHaveBeenCalledTimes(2); + if (order === "old scan finishes first") { + oldRead.resolve(removed); + await initial; + concurrent = read(); + expect(all).toHaveBeenCalledTimes(2); + } + newRead.resolve(current); + const expected = current.map((game) => game.publicKey.toBase58()); + await expect(updated).resolves.toEqual(expected); + if (concurrent) await expect(concurrent).resolves.toEqual(expected); + oldRead.resolve(removed); + await initial; + await expect(read()).resolves.toEqual(expected); + expect(all).toHaveBeenCalledTimes(2); + } finally { + oldRead.resolve(removed); + newRead.resolve(current); + await Promise.allSettled([initial, updated, concurrent]); + } + }, + ); + test("drops games that expire while the list is cached", async () => { const soon = await makeGame({ createdAt: now() - 100, timeout: 102 }); const later = await makeGame(); From f51cfb660c438189be8c9a8653b5d9c390405189 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 13:01:48 -0300 Subject: [PATCH 026/410] test(swaps): cover partial sponsor setup and fee fallbacks --- tests/integrator-fees.test.ts | 76 +++++++++++++++++++++++++++++++++++ 1 file changed, 76 insertions(+) diff --git a/tests/integrator-fees.test.ts b/tests/integrator-fees.test.ts index 152cad34..cd009df3 100644 --- a/tests/integrator-fees.test.ts +++ b/tests/integrator-fees.test.ts @@ -120,6 +120,61 @@ describe("Integrator fee calculations", () => { expect(spy).not.toHaveBeenCalled(); }); + test.each([ + ["only the payer", { adminPayer: "sponsor-payer" }], + ["only the close authority", { adminCloseAuthority: "sponsor-authority" }], + ["neither key", {}], + ] as const)("uses the sender when %s is configured", async (_case, config) => { + __test_setReferralConfig({ referralAccount: REFERRAL_ACCOUNT, ...config }); + const price = vi.spyOn(priceService, "getUsdPrice").mockResolvedValue(null); + + await expect( + resolveIntegratorSwapParams({ + inputMint: ADMIN_REF_MINT1, + outputMint: WSOL_MINT, + inputTicker: "USDC", + inputDecimals: 6, + inputAmountRaw: 5_000_000, + userPublicKey: "sender-public-key", + availableSolLamports: 0, + solFeeBufferLamports: 10_000_000, + }), + ).resolves.toEqual({ + referralAccount: REFERRAL_ACCOUNT, + referralFee: 100, + payer: "sender-public-key", + closeAuthority: "sender-public-key", + payerKind: "user", + }); + expect(price).not.toHaveBeenCalled(); + }); + + test("keeps a sponsored unwrap on the base fee when the price service is unavailable", async () => { + __test_setReferralConfig({ + referralAccount: REFERRAL_ACCOUNT, + adminPayer: "sponsor-payer", + adminCloseAuthority: "sponsor-authority", + }); + const price = vi.spyOn(priceService, "getUsdPrice").mockResolvedValue(null); + await expect( + resolveIntegratorSwapParams({ + inputMint: WSOL_MINT, + outputMint: "SOL", + inputTicker: "SOL", + inputDecimals: 9, + inputAmountRaw: 100_000_000, + userPublicKey: "sender-public-key", + availableSolLamports: 0, + }), + ).resolves.toMatchObject({ + payerKind: "admin", + payer: "sponsor-payer", + closeAuthority: "sponsor-authority", + referralFee: 100, + }); + expect(price.mock.calls).toEqual([[{ tokenMint: WSOL_MINT }], [{ tokenMint: WSOL_MINT }]]); + }); + test("applies extra referral fee to reimburse admin gas payer shortfall", async () => { __test_setReferralConfig({ referralAccount: REFERRAL_ACCOUNT, @@ -377,6 +432,7 @@ describe("calculateDynamicReferralFee", () => { }); test("returns base fee when shortfallLamports is zero", async () => { + const price = vi.spyOn(priceService, "getUsdPrice").mockResolvedValue(null); const result = await calculateDynamicReferralFee({ inputMint: "SomeMint111111111111111111111111111111111", inputTicker: "TKN", @@ -387,9 +443,11 @@ describe("calculateDynamicReferralFee", () => { }); expect(result).toBe(85); + expect(price).not.toHaveBeenCalled(); }); test("returns base fee when shortfallLamports is negative", async () => { + const price = vi.spyOn(priceService, "getUsdPrice").mockResolvedValue(null); const result = await calculateDynamicReferralFee({ inputMint: "SomeMint111111111111111111111111111111111", inputTicker: "TKN", @@ -400,8 +458,26 @@ describe("calculateDynamicReferralFee", () => { }); expect(result).toBe(85); + expect(price).not.toHaveBeenCalled(); }); + test.each([0, -5, NaN, Infinity])( + "does not request a trade price for %p raw units", + async (amount) => { + const price = vi.spyOn(priceService, "getUsdPrice").mockResolvedValue(null); + await expect( + calculateDynamicReferralFee({ + inputMint: ADMIN_REF_MINT1, + inputTicker: "USDC", + inputDecimals: 6, + inputAmountRaw: amount, + shortfallLamports: 100_000, + }), + ).resolves.toBe(100); + expect(price.mock.calls).toEqual([[{ tokenMint: WSOL_MINT }]]); + }, + ); + test("calculates dynamic fee based on deficit/trade ratio", async () => { vi.spyOn(priceService, "getUsdPrice").mockImplementation(async (opts: any) => { const resolvedAt = Date.now(); From fce3d4050f388431dbddc0b075fab7f7f79f610e Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 13:03:15 -0300 Subject: [PATCH 027/410] fix(positions): reject invalid scales and non-finite amounts --- src/services/positions.ts | 10 ++++++---- tests/positions.test.ts | 33 +++++++++++++++++++++++++++++++++ 2 files changed, 39 insertions(+), 4 deletions(-) diff --git a/src/services/positions.ts b/src/services/positions.ts index 6500ff70..da25beeb 100644 --- a/src/services/positions.ts +++ b/src/services/positions.ts @@ -13,6 +13,7 @@ import { getBuiltinTokenMetadataByTicker, } from "../utils/token-registry"; import type { SwapStatRecord } from "../utils/transaction-history"; +import { isMintDecimals } from "../utils/token-decimals"; export const USDC_MINT = "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"; export const USDT_MINT = "Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB"; @@ -120,7 +121,7 @@ export function createDecimalResolver( const byMint = new Map(); for (const token of known) { const mint = token.mint ?? token.token_mint; - if (mint && Number.isFinite(token.decimals) && token.decimals >= 0 && token.decimals <= 18) { + if (mint && Number.isInteger(token.decimals) && token.decimals >= 0 && token.decimals <= 18) { byMint.set(mint, token.decimals); } } @@ -128,7 +129,7 @@ export function createDecimalResolver( } export function rawAmountToNumber(raw: string | undefined, decimals: number): number { - if (!raw || decimals < 0) { + if (!raw || !isMintDecimals(decimals)) { return 0; } @@ -137,7 +138,8 @@ export function rawAmountToNumber(raw: string | undefined, decimals: number): nu const base = 10n ** BigInt(decimals); const whole = value / base; const frac = value % base; - return Number(whole) + Number(frac) / Number(base); + const amount = Number(whole) + Number(frac) / Number(base); + return Number.isFinite(amount) ? amount : 0; } catch { const parsed = Number(raw); if (!Number.isFinite(parsed)) { @@ -148,7 +150,7 @@ export function rawAmountToNumber(raw: string | undefined, decimals: number): nu } export function quoteAmountToSol(quoteMint: string, quoteAmount: number): number { - if (quoteAmount <= 0 || quoteMint !== WSOL_MINT) { + if (!Number.isFinite(quoteAmount) || quoteAmount <= 0 || quoteMint !== WSOL_MINT) { return 0; } return quoteAmount; diff --git a/tests/positions.test.ts b/tests/positions.test.ts index d6ebdcc6..6e32c256 100644 --- a/tests/positions.test.ts +++ b/tests/positions.test.ts @@ -142,6 +142,22 @@ test("resolveTokenDecimals does not invent 6 decimals for an unknown mint", () = expect(fillsFromSwaps([swap({ output_mint: UNKNOWN_MINT, output_ticker: "NOPE" })])).toEqual([]); }); +test("position metadata accepts the whole-number endpoints and skips invalid scales", () => { + const resolve = createDecimalResolver([ + { mint: "zero", decimals: 0 }, + { token_mint: "maximum", decimals: 18 }, + { mint: "negative", decimals: -1 }, + { mint: "fractional", decimals: 5.5 }, + { mint: "too-large", decimals: 19 }, + { mint: "infinite", decimals: Infinity }, + ]); + expect(resolve("zero", "NOPE")).toBe(0); + expect(resolve("maximum", "NOPE")).toBe(18); + for (const invalid of ["negative", "fractional", "too-large", "infinite"]) { + expect(resolve(invalid, "NOPE")).toBeNull(); + } +}); + test("buildTokenPositions does not treat a small bot buy as the cost of a larger bag", () => { const magaiba = "A6rSPi9JmJgVkW6BatsA6MjFYLseizPM2Fnt92coFjf4"; const fills = fillsFromSwaps( @@ -780,6 +796,10 @@ test("quoteAmountToSol only counts native SOL", () => { expect(quoteAmountToSol(WSOL_MINT, 0.42)).toBeCloseTo(0.42, 8); }); +test.each([0, -1, Infinity, NaN])("ignores invalid or empty SOL cost %p", (amount) => { + expect(quoteAmountToSol(WSOL_MINT, amount)).toBe(0); +}); + test("format helpers match the wallet PNL style", () => { expect(formatSignedPercent(0.184)).toBe("+18.4%"); expect(formatSignedPercent(-0.0646)).toBe("-6.46%"); @@ -1041,6 +1061,19 @@ test("rawAmountToNumber handles missing, invalid and non-integer raw values", () expect(rawAmountToNumber("not-a-number", 3)).toBe(0); }); +test("rawAmountToNumber preserves zero-decimal balances and signed amounts", () => { + expect(rawAmountToNumber("9007199254740991", 0)).toBe(9_007_199_254_740_991); + expect(rawAmountToNumber("-100", 2)).toBe(-1); +}); + +test.each([NaN, Infinity, 8.5, 256])("rawAmountToNumber rejects unusable scale %p", (decimals) => { + expect(rawAmountToNumber("100", decimals)).toBe(0); +}); + +test("rawAmountToNumber does not return infinity for a malformed provider amount", () => { + expect(rawAmountToNumber("9".repeat(400), 0)).toBe(0); +}); + test("same-timestamp rotations apply the sell before the buy", () => { const buy = { mint: TIMBA, From db19db3ee646fcbb9fa4bd3f2c40eaf0b5a65aa0 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 13:07:32 -0300 Subject: [PATCH 028/410] fix(positions): keep refreshed prices when old requests finish --- src/services/positions.ts | 10 +++++--- tests/positions.test.ts | 52 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 58 insertions(+), 4 deletions(-) diff --git a/src/services/positions.ts b/src/services/positions.ts index da25beeb..f897f885 100644 --- a/src/services/positions.ts +++ b/src/services/positions.ts @@ -712,7 +712,7 @@ async function resolvePositionWork( ); } - const next: PositionWorkCache = { + return { expiresAt: now + POSITION_SNAPSHOT_TTL_MS, fills, swapFingerprint, @@ -723,8 +723,6 @@ async function resolvePositionWork( pricesUsd, pricedMints, }; - positionWorkCache.set(args.walletAddress, next); - return next; } export function clearPositionSnapshot(walletAddress?: string): void { @@ -763,8 +761,12 @@ export async function loadTokenPositionsForWallet( pendingPositionWork.set(cacheKey, workPromise); try { const work = await workPromise; + // Refresh can replace this request while prices are loading. + if (pendingPositionWork.get(cacheKey) === workPromise) { + positionWorkCache.set(cacheKey, work); + } return buildTokenPositions({ fills: work.fills, holdings, pricesUsd: work.pricesUsd }); } finally { - pendingPositionWork.delete(cacheKey); + if (pendingPositionWork.get(cacheKey) === workPromise) pendingPositionWork.delete(cacheKey); } } diff --git a/tests/positions.test.ts b/tests/positions.test.ts index 6e32c256..a92de548 100644 --- a/tests/positions.test.ts +++ b/tests/positions.test.ts @@ -1286,6 +1286,58 @@ test("a concurrent load with nothing new to price reuses the shared prices", asy clearPositionSnapshot(); }); +test.each(["old quote finishes first", "new quote finishes first"] as const)( + "keeps the refreshed wallet snapshot when the %s", + async (order) => { + const address = `refresh-${order}`; + const oldQuote = Promise.withResolvers>(); + const newQuote = Promise.withResolvers>(); + const older = { [WSOL_MINT]: 100, [TIMBA]: 1 }; + const newer = { [WSOL_MINT]: 100, [TIMBA]: 2 }; + let priceCalls = 0; + const loader = { + walletAddress: address, + getHoldings: async () => [{ mint: TIMBA, ticker: "TIMBA", balance: 100, decimals: 6 }], + getSwaps: () => [swap({ amount_in: "1000000000", amount_out: "100000000" })], + fetchPricesUSD: () => (++priceCalls === 1 ? oldQuote.promise : newQuote.promise), + }; + const flush = async () => { + for (let tick = 0; tick < 8; tick += 1) await Promise.resolve(); + }; + const read = async () => (await loadTokenPositionsForWallet(loader))[0]?.priceUsd; + const initial = read(); + let updated: ReturnType | undefined; + let concurrent: ReturnType | undefined; + try { + await flush(); + expect(priceCalls).toBe(1); + clearPositionSnapshot(address); + updated = read(); + await flush(); + expect(priceCalls).toBe(2); + if (order === "old quote finishes first") { + oldQuote.resolve(older); + await initial; + concurrent = read(); + await flush(); + expect(priceCalls).toBe(2); + } + newQuote.resolve(newer); + expect(await updated).toBe(2); + if (concurrent) expect(await concurrent).toBe(2); + oldQuote.resolve(older); + await initial; + expect(await read()).toBe(2); + expect(priceCalls).toBe(2); + } finally { + oldQuote.resolve(older); + newQuote.resolve(newer); + await Promise.allSettled([initial, updated, concurrent]); + clearPositionSnapshot(address); + } + }, +); + test("newly known token metadata rebuilds cached fills", async () => { clearPositionSnapshot(); const swaps = [ From f5adc016d5b7b881c44abb8820e7ff37b5590adc Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 13:10:31 -0300 Subject: [PATCH 029/410] fix(alerts): discard results from superseded mint watches --- src/services/buy-alerts/pool-trades.ts | 52 ++++---- .../buy-alerts.pool-trades-edge-cases.test.ts | 111 ++++++++++++++++++ 2 files changed, 141 insertions(+), 22 deletions(-) diff --git a/src/services/buy-alerts/pool-trades.ts b/src/services/buy-alerts/pool-trades.ts index 21ee3d42..8edba583 100644 --- a/src/services/buy-alerts/pool-trades.ts +++ b/src/services/buy-alerts/pool-trades.ts @@ -91,6 +91,7 @@ const geckoTradesResponseSchema = z .passthrough(); function parseFiniteNumber(value: number | string | undefined): number | null { + if (typeof value === "string" && value.trim() === "") return null; const numeric = Number(value ?? NaN); if (!Number.isFinite(numeric) || numeric < 0) { return null; @@ -180,6 +181,9 @@ export type PoolTradePoller = BuyFeed & { pollNow: () => Promise; }; +type MintWatch = { since: number }; +type PollTarget = { mint: string; pair: PairStats; watch: MintWatch }; + export function createPoolTradePoller(options: PoolTradePollerOptions = {}): PoolTradePoller { const fetchPoolStats = options.fetchPoolStats ?? @@ -227,7 +231,8 @@ export function createPoolTradePoller(options: PoolTradePollerOptions = {}): Poo const primed = new Map>(); const discoveredPools = new Map>(); const baselinePools = new Map>(); - const watchedAtByMint = new Map(); + const watches = new Map(); + const stillWatching = (mint: string, watch: MintWatch) => watches.get(mint) === watch; let poolQueue: Array<{ mint: string; pairAddress: string }> = []; let nextTradeFetchAt = 0; let consecutiveTradeFailures = 0; @@ -288,6 +293,7 @@ export function createPoolTradePoller(options: PoolTradePollerOptions = {}): Poo const pollPool = async ( mint: string, pair: PairStats, + watch: MintWatch, firstPassCutoffMs: number | null, ): Promise => { // Only targets with a non-empty pair address are queued (see the target filter). @@ -296,7 +302,7 @@ export function createPoolTradePoller(options: PoolTradePollerOptions = {}): Poo let payload: unknown; try { await waitForTradeSlot(); - if (!mints.includes(mint)) { + if (!stillWatching(mint, watch)) { return false; } payload = await fetchTrades(pairAddress); @@ -305,6 +311,7 @@ export function createPoolTradePoller(options: PoolTradePollerOptions = {}): Poo reportError(error); return false; } + if (!stillWatching(mint, watch)) return false; const parsed = geckoTradesResponseSchema.safeParse(payload); if (!parsed.success) { @@ -336,6 +343,7 @@ export function createPoolTradePoller(options: PoolTradePollerOptions = {}): Poo tradeTimestamp >= firstPassCutoffMs; if (!isFirstPass || firstPassCutoffMs == null || occurredAfterWatchStarted) { emit(event); + if (!stillWatching(mint, watch)) return false; } } @@ -346,7 +354,7 @@ export function createPoolTradePoller(options: PoolTradePollerOptions = {}): Poo return true; }; - const discoverMintPools = async (mint: string): Promise => { + const discoverMintPools = async (mint: string, watch: MintWatch): Promise => { let pools: PairStats[]; try { pools = await fetchPoolStats(mint); @@ -354,6 +362,7 @@ export function createPoolTradePoller(options: PoolTradePollerOptions = {}): Poo reportError(error); return []; } + if (!stillWatching(mint, watch)) return []; const uniquePools = new Map(); for (const pool of pools) { const pairAddress = pool.pairAddress?.trim(); @@ -387,11 +396,10 @@ export function createPoolTradePoller(options: PoolTradePollerOptions = {}): Poo const targetKey = (mint: string, pairAddress: string): string => `${mint}:${pairAddress}`; - const refreshPoolQueue = ( - targets: Array<{ mint: string; pair: PairStats }>, - ): Map => { - const targetByKey = new Map(); + const refreshPoolQueue = (targets: PollTarget[]): Map => { + const targetByKey = new Map(); for (const target of targets) { + if (!stillWatching(target.mint, target.watch)) continue; const pairAddress = target.pair.pairAddress?.trim(); if (!pairAddress) continue; targetByKey.set(targetKey(target.mint, pairAddress), target); @@ -416,13 +424,15 @@ export function createPoolTradePoller(options: PoolTradePollerOptions = {}): Poo queuedPolls += 1; const run = async () => { if (mints.length === 0) return; - const poolsByMint = await Promise.all( - mints.map(async (mint) => ({ mint, pools: await discoverMintPools(mint) })), - ); - const targets = poolsByMint.flatMap(({ mint, pools }) => - pools.map((pair) => ({ mint, pair })), + const targetsByMint = await Promise.all( + mints.map(async (mint) => { + const watch = watches.get(mint); + if (!watch) return []; + const pools = await discoverMintPools(mint, watch); + return pools.map((pair) => ({ mint, pair, watch })); + }), ); - const targetByKey = refreshPoolQueue(targets); + const targetByKey = refreshPoolQueue(targetsByMint.flat()); // Use the initial queue only to bound the cycle. Awaited requests can change the live queue. for (const _ of poolQueue.slice(0, poolsPerCycle)) { @@ -430,16 +440,14 @@ export function createPoolTradePoller(options: PoolTradePollerOptions = {}): Poo if (!queuedTarget) break; const key = targetKey(queuedTarget.mint, queuedTarget.pairAddress); const target = targetByKey.get(key); - if (!target) continue; + if (!target || !stillWatching(target.mint, target.watch)) continue; poolQueue.push(queuedTarget); - const { mint, pair } = target; + const { mint, pair, watch } = target; const pairAddress = queuedTarget.pairAddress; const isBaselinePool = baselinePools.get(mint)?.has(pairAddress) ?? false; - const firstPassCutoffMs = isBaselinePool - ? (watchedAtByMint.get(mint) ?? Number.POSITIVE_INFINITY) - : null; - const succeeded = await pollPool(mint, pair, firstPassCutoffMs); + const firstPassCutoffMs = isBaselinePool ? watch.since : null; + const succeeded = await pollPool(mint, pair, watch, firstPassCutoffMs); if (succeeded) { baselinePools.get(mint)?.delete(pairAddress); } @@ -489,12 +497,12 @@ export function createPoolTradePoller(options: PoolTradePollerOptions = {}): Poo primed.delete(mint); discoveredPools.delete(mint); baselinePools.delete(mint); - watchedAtByMint.delete(mint); + watches.delete(mint); } } for (const mint of nextSet) { if (!previousSet.has(mint)) { - watchedAtByMint.set(mint, now()); + watches.set(mint, { since: now() }); } } mints = Array.from(nextSet); @@ -515,7 +523,7 @@ export function createPoolTradePoller(options: PoolTradePollerOptions = {}): Poo primed.clear(); discoveredPools.clear(); baselinePools.clear(); - watchedAtByMint.clear(); + watches.clear(); poolQueue = []; nextTradeFetchAt = 0; consecutiveTradeFailures = 0; diff --git a/tests/buy-alerts.pool-trades-edge-cases.test.ts b/tests/buy-alerts.pool-trades-edge-cases.test.ts index f5a2d783..75b6aedb 100644 --- a/tests/buy-alerts.pool-trades-edge-cases.test.ts +++ b/tests/buy-alerts.pool-trades-edge-cases.test.ts @@ -1,5 +1,6 @@ import { afterEach, describe, expect, spyOn, test, vi } from "bun:test"; import { + GeckoRateLimitError, createPoolTradePoller, parseGeckoPoolTrade, rememberSignature, @@ -91,6 +92,13 @@ describe("parseGeckoPoolTrade rejects unusable payloads", () => { expect(event).toMatchObject({ signature: "sig", solAmount: null, inputAmount: null }); }); + test("keeps explicit zero amounts but treats a blank provider amount as unavailable", () => { + const blank = parseGeckoPoolTrade(mint, trade("blank", undefined, { from_token_amount: " " })); + const zero = parseGeckoPoolTrade(mint, trade("zero", undefined, { from_token_amount: "0" })); + expect(blank).toMatchObject({ signature: "blank", inputAmount: null, solAmount: null }); + expect(zero).toMatchObject({ signature: "zero", inputAmount: 0, solAmount: null }); + }); + test("requires a real signature and normalizes the wallet, mint, ticker, and venue", () => { expect(parseGeckoPoolTrade(mint, trade(" "))).toBeNull(); expect( @@ -128,6 +136,109 @@ describe("pool trade poller", () => { now: () => 0, }; + test.each([ + ["removed", false], + ["re-added", true], + ] as const)("drops stale trades when the watched mint is %s", async (_label, readd) => { + const pending = Promise.withResolvers(); + const signatures: string[] = []; + let requests = 0; + const poller = track( + createPoolTradePoller({ + ...base, + fetchPoolStats: async () => [pool("test-pool")], + fetchTrades: async () => { + requests += 1; + return requests === 1 ? pending.promise : { data: [trade("current", 1)] }; + }, + }), + ); + poller.onTrade((event) => signatures.push(event.signature)); + try { + poller.setMints([mint]); + for (let tick = 0; tick < 16; tick += 1) await Promise.resolve(); + expect(requests).toBe(1); + poller.setMints([]); + if (readd) poller.setMints([mint]); + const finished = poller.pollNow(); + pending.resolve({ data: [trade("removed", 1)] }); + await finished; + expect(signatures).toEqual(readd ? ["current"] : []); + } finally { + pending.resolve({ data: [] }); + poller.stop(); + } + }); + + test("does not poll an obsolete pool discovered after restarting a mint watch", async () => { + const firstDiscovery = Promise.withResolvers(); + const requestedPools: string[] = []; + let discoveries = 0; + const poller = track( + createPoolTradePoller({ + ...base, + fetchPoolStats: async () => + ++discoveries === 1 ? firstDiscovery.promise : [pool("current")], + fetchTrades: async (pair) => { + requestedPools.push(pair); + return { data: [] }; + }, + }), + ); + try { + poller.setMints([mint]); + for (let tick = 0; tick < 8; tick += 1) await Promise.resolve(); + expect(discoveries).toBe(1); + poller.setMints([]); + poller.setMints([mint]); + const finished = poller.pollNow(); + firstDiscovery.resolve([pool("obsolete")]); + await finished; + expect(requestedPools).toEqual(["current"]); + } finally { + firstDiscovery.resolve([]); + poller.stop(); + } + }); + + test.each([ + [299_999, 120_000], + [300_000, 60_000], + ] as const)( + "restarts rate-limit backoff only after the required healthy time (%i ms)", + async (healthyMs, lastDelay) => { + let now = 0; + let calls = 0; + const delays: number[] = []; + const poller = track( + createPoolTradePoller({ + ...base, + minRequestIntervalMs: 1_000, + now: () => now, + fetchPoolStats: async () => [pool("test-pool")], + fetchTrades: async () => { + calls += 1; + if (calls === 1 || calls === 4) throw new GeckoRateLimitError(null); + return { data: [] }; + }, + onError: () => {}, + wait: async (delay) => { + delays.push(delay); + now += delay; + }, + }), + ); + poller.setMints([mint]); + await poller.pollNow(); // The next successful response starts the healthy window. + now += healthyMs; + await poller.pollNow(); + await poller.pollNow(); + await poller.pollNow(); + expect(calls).toBe(5); + expect(delays).toEqual([60_000, 1_000, lastDelay]); + }, + ); + test("includes the exact watch start boundary but skips earlier and undated buys", async () => { const start = Date.parse("2026-09-03T20:00:00Z"); const observed: string[] = []; From 713eca7d551e60d5c9585441147413dc5646b103 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 13:14:10 -0300 Subject: [PATCH 030/410] fix(telegram): prevent invalid callback queues from hanging --- src/utils/telegram-rate-limiter.ts | 10 ++-- tests/telegram-rate-limiter.queue.test.ts | 67 +++++++++++++++++++---- 2 files changed, 62 insertions(+), 15 deletions(-) diff --git a/src/utils/telegram-rate-limiter.ts b/src/utils/telegram-rate-limiter.ts index c046e7de..24832a13 100644 --- a/src/utils/telegram-rate-limiter.ts +++ b/src/utils/telegram-rate-limiter.ts @@ -58,6 +58,9 @@ export class CallbackAnswerQueue { this.answerFn = options.answerFn; this.throttleMs = options.throttleMs ?? CALLBACK_ANSWER_THROTTLE_MS; this.maxSize = options.maxSize ?? CALLBACK_ANSWER_QUEUE_MAX_SIZE; + if (!Number.isSafeInteger(this.maxSize) || this.maxSize <= 0) { + throw new Error("Callback queue capacity must be a positive integer"); + } } /** @@ -65,9 +68,8 @@ export class CallbackAnswerQueue { */ enqueue(callbackQueryId: string, text?: string, showAlert?: boolean): void { // Drop oldest if queue is full - while (this.queue.length >= this.maxSize) { - this.queue.shift(); - } + const overflow = this.queue.length + 1 - this.maxSize; + if (overflow > 0) this.queue.splice(0, overflow); this.queue.push({ callbackQueryId, @@ -120,7 +122,7 @@ export class CallbackAnswerQueue { const entry = this.queue.shift(); if (!entry) { - continue; + break; } try { diff --git a/tests/telegram-rate-limiter.queue.test.ts b/tests/telegram-rate-limiter.queue.test.ts index 58aace7f..4fecfdef 100644 --- a/tests/telegram-rate-limiter.queue.test.ts +++ b/tests/telegram-rate-limiter.queue.test.ts @@ -1,4 +1,4 @@ -import { expect, test } from "bun:test"; +import { expect, spyOn, test, vi } from "bun:test"; import { CallbackAnswerQueue, TelegramRateLimiter } from "../src/utils/telegram-rate-limiter"; test("a global rate limit reports its remaining wait for every chat", () => { @@ -16,6 +16,8 @@ test("a global rate limit reports its remaining wait for every chat", () => { }); test("clearing the queue while a throttled answer is waiting drops it without answering", async () => { + vi.useFakeTimers(); + const clock = spyOn(Date, "now").mockReturnValue(10_000); const answered: string[] = []; const queue = new CallbackAnswerQueue({ answerFn: async (id) => { @@ -25,16 +27,59 @@ test("clearing the queue while a throttled answer is waiting drops it without an throttleMs: 150, }); - queue.enqueue("first"); - queue.enqueue("second"); - // "first" is answered right away. "second" is now sleeping out the throttle. - await Bun.sleep(20); - expect(answered).toEqual(["first"]); - expect(queue.length).toBe(1); + const flush = async () => { + for (let tick = 0; tick < 8; tick += 1) await Promise.resolve(); + }; + try { + queue.enqueue("first"); + queue.enqueue("second"); + await flush(); + expect(answered).toEqual(["first"]); + expect(queue.length).toBe(1); - queue.clear(); - await Bun.sleep(250); + queue.clear(); + clock.mockReturnValue(10_150); + vi.advanceTimersByTime(150); + await flush(); + expect(answered).toEqual(["first"]); + expect(queue.isProcessing).toBe(false); + expect(vi.getTimerCount()).toBe(0); + } finally { + clock.mockRestore(); + vi.useRealTimers(); + } +}); + +test.each([0, -1, Infinity, NaN, 1.5])("rejects invalid callback queue capacity %p", (maxSize) => { + expect(() => new CallbackAnswerQueue({ maxSize, answerFn: async () => true })).toThrow( + "Callback queue capacity must be a positive integer", + ); +}); - expect(answered).toEqual(["first"]); - expect(queue.isProcessing).toBe(false); +test("keeps the newest waiting entries and sends them in order", async () => { + const first = Promise.withResolvers(); + const answered: string[] = []; + const queue = new CallbackAnswerQueue({ + maxSize: 2, + throttleMs: 0, + answerFn: async (id) => { + answered.push(id); + return id === "running" ? first.promise : true; + }, + }); + try { + queue.enqueue("running"); + queue.enqueue("oldest"); + queue.enqueue("recent"); + queue.enqueue("latest"); + expect(queue.length).toBe(2); + expect(answered).toEqual(["running"]); + first.resolve(true); + for (let tick = 0; tick < 12; tick += 1) await Promise.resolve(); + expect(answered).toEqual(["running", "recent", "latest"]); + expect(queue.length).toBe(0); + expect(queue.isProcessing).toBe(false); + } finally { + first.resolve(true); + } }); From b4d895816927e9c0903b9d0db3e3eff88f30b50a Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 13:16:23 -0300 Subject: [PATCH 031/410] fix(alerts): omit an unrepresentable dollar valuation --- src/services/buy-alerts/formatter.ts | 5 ++++- tests/buy-alerts.formatter.test.ts | 14 ++++++++++++++ 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/src/services/buy-alerts/formatter.ts b/src/services/buy-alerts/formatter.ts index 14ef6bdf..b76d5f7b 100644 --- a/src/services/buy-alerts/formatter.ts +++ b/src/services/buy-alerts/formatter.ts @@ -102,7 +102,10 @@ export function formatBuyAlertMessage({ const spentSol = trimFixed(event.solAmount.toFixed(4)); spentLine = `Spent: ${copyableHtml(spentSol)} SOL`; if (positiveFinite(solPriceUsd)) { - spentLine += ` ($${escapeHtml(formatUsdValue(event.solAmount * solPriceUsd))})`; + const spentUsd = event.solAmount * solPriceUsd; + if (Number.isFinite(spentUsd)) { + spentLine += ` ($${escapeHtml(formatUsdValue(spentUsd))})`; + } } } else if (positiveFinite(event.inputAmount)) { const inputAmount = formatBuyTokenAmount(event.inputAmount); diff --git a/tests/buy-alerts.formatter.test.ts b/tests/buy-alerts.formatter.test.ts index 2f140bb7..ec5ef069 100644 --- a/tests/buy-alerts.formatter.test.ts +++ b/tests/buy-alerts.formatter.test.ts @@ -264,3 +264,17 @@ test.each<[number | null, number | null, string]>([ }); expect(text.split("\n").find((line) => line.startsWith("Spent:"))).toBe(expected); }); + +test.each([ + ["a normal price", 0.0625, 100, "Spent: 0.0625 SOL ($6.25)"], + ["a missing price", 0.0625, null, "Spent: 0.0625 SOL"], + ["an overflowing valuation", 1e308, 2, "Spent: 1e+308 SOL"], +] as const)("renders the expected SOL cost with %s", (_label, solAmount, solPriceUsd, expected) => { + const text = formatBuyAlertMessage({ + event: { ...event, solAmount }, + ticker: "TOK", + pair: null, + solPriceUsd, + }); + expect(text.split("\n").find((line) => line.startsWith("Spent:"))).toBe(expected); +}); From c6c69d871324cbac5eb090e0d4f9fdd4246a4867 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 13:20:01 -0300 Subject: [PATCH 032/410] fix(games): require decimal player counts in both setup flows --- src/evm/setup.ts | 5 +++-- src/handlers/chat-defaults.ts | 14 ++++--------- src/handlers/game-callbacks.ts | 5 +++-- src/utils/arg-parsing.ts | 8 ++++++++ tests/evm.bot-store-setup.test.ts | 34 +++++++++++++++++++++++++++++++ tests/game-setup.flows.test.ts | 9 +++++--- 6 files changed, 58 insertions(+), 17 deletions(-) diff --git a/src/evm/setup.ts b/src/evm/setup.ts index 58be1117..4764f7a1 100644 --- a/src/evm/setup.ts +++ b/src/evm/setup.ts @@ -1,5 +1,6 @@ import { Bot, GrammyError, type InlineKeyboard, type Context } from "grammy"; import { formatTokenAmount, parseTokenAmount } from "@timbagame/protocol/amounts"; +import { parseDecimalInteger } from "../utils/arg-parsing"; import { createAmountMenuKeyboard, createPlayerSelectionKeyboard, @@ -228,8 +229,8 @@ export function registerEvmSetup( s.amount = formatTokenAmount(raw, s.token.decimals); s.screen = "players"; } else { - const value = Number(ctx.message.text); - if (!Number.isInteger(value) || value < (s.type === "coinflip" ? 2 : 1) || value > 100) + const value = parseDecimalInteger(ctx.message.text); + if (value === null || value < (s.type === "coinflip" ? 2 : 1) || value > 100) throw new Error("players"); s.players = value; s.minPlayers = Math.min(s.minPlayers, value); diff --git a/src/handlers/chat-defaults.ts b/src/handlers/chat-defaults.ts index ed2780ef..da1f15e6 100644 --- a/src/handlers/chat-defaults.ts +++ b/src/handlers/chat-defaults.ts @@ -1,6 +1,7 @@ import { InlineKeyboard, type Bot, type Context } from "grammy"; import { GameDatabase } from "../utils/game-database"; import { formatDuration } from "../utils/format-time"; +import { parseDecimalInteger } from "../utils/arg-parsing"; import { DEFAULT_COINFLIP_MAX_PLAYERS, @@ -65,13 +66,6 @@ const formatBuyAlertMediaSummary = (mediaId: string | null | undefined): string return "Custom"; }; -const parseSettingsInteger = (input: string): number | null => { - const trimmed = input.trim(); - if (!/^[+-]?\d+$/.test(trimmed)) return null; - const value = Number(trimmed); - return Number.isSafeInteger(value) ? value : null; -}; - export const isChatDefaultsMediaSetting = ( setting: string | undefined, ): setting is "video_coinflip" | "video_giveaway" | "video_buy_alerts" => @@ -526,7 +520,7 @@ const handlePlayersUpdate = async ( return; } - const parsed = parseSettingsInteger(input); + const parsed = parseDecimalInteger(input); const clamped = parsed === null ? null : clampChatPlayers(parsed, target, maxLimit); if (clamped === null) { await deps.replyErrorToMessage( @@ -573,7 +567,7 @@ const handleTimeoutUpdate = async ( return; } - const parsed = parseSettingsInteger(input); + const parsed = parseDecimalInteger(input); if (parsed === null) { await deps.replyErrorToMessage(ctx, "❌ Please enter a valid number of seconds."); return; @@ -1277,7 +1271,7 @@ export const createChatDefaultsModule = (deps: ChatDefaultsModuleDeps): ChatDefa return true; } - const rate = parseSettingsInteger(userMessage); + const rate = parseDecimalInteger(userMessage); if (rate === null || rate < 0 || rate > MAX_JOIN_NOTIFICATIONS_PER_MINUTE) { await deps.replyErrorToMessage( ctx, diff --git a/src/handlers/game-callbacks.ts b/src/handlers/game-callbacks.ts index ae0c8c33..893073d8 100644 --- a/src/handlers/game-callbacks.ts +++ b/src/handlers/game-callbacks.ts @@ -2,6 +2,7 @@ import { InlineKeyboard, type Bot, type Context, type MiddlewareFn } from "gramm import type { NextFunction } from "grammy"; import { PublicKey } from "#solana"; import { isMissingAccountError } from "../utils/account-errors"; +import { parseDecimalInteger } from "../utils/arg-parsing"; import { DEFAULT_GAME_TIMEOUT, @@ -640,7 +641,7 @@ export const createGameCallbacksModule = (deps: GameCallbacksModuleDeps): GameCa const inputText = ctx.message.text.trim(); if (userSession.waitingFor === "players_input") { - const players = Number.parseInt(inputText, 10); + const players = parseDecimalInteger(inputText); const minPlayers = getMinPlayersFloor(userSession.gameType as "coinflip" | "giveaway"); const maxPlayers = Math.max( minPlayers, @@ -651,7 +652,7 @@ export const createGameCallbacksModule = (deps: GameCallbacksModuleDeps): GameCa `🔍 Custom players input: "${inputText}" -> ${players} (gameType: ${userSession.gameType}, min: ${minPlayers}, max: ${maxPlayers})`, ); - if (Number.isNaN(players) || players < minPlayers || players > maxPlayers) { + if (players === null || players < minPlayers || players > maxPlayers) { const errorMessage = `❌ Invalid number of players. Please enter a number between ${minPlayers} and ${maxPlayers}.`; try { await ctx.api.editMessageText( diff --git a/src/utils/arg-parsing.ts b/src/utils/arg-parsing.ts index 82fee1d9..ad8e6f3c 100644 --- a/src/utils/arg-parsing.ts +++ b/src/utils/arg-parsing.ts @@ -1,6 +1,14 @@ export type InferPlayersResult = { ok: true; value: number; source: "default" | "arg" } | { ok: false; error: string }; +/** Parses a complete decimal integer from a reply without accepting prefixes or rounding. */ +export function parseDecimalInteger(input: string): number | null { + const trimmed = input.trim(); + if (!/^[+-]?\d+$/.test(trimmed)) return null; + const value = Number(trimmed); + return Number.isSafeInteger(value) ? value : null; +} + /** * Infer max players from command args in a robust, index-based way. * diff --git a/tests/evm.bot-store-setup.test.ts b/tests/evm.bot-store-setup.test.ts index 676bdfbd..c030b960 100644 --- a/tests/evm.bot-store-setup.test.ts +++ b/tests/evm.bot-store-setup.test.ts @@ -246,6 +246,40 @@ describe("EVM setup custom players prompt", () => { ); expect(after.input).toBe("players"); expect(after.prompt).toBe(100 + sent.length); + + const readSetup = () => { + const current = store.db + .query<{ body: string }, [string]>("SELECT body FROM setups WHERE id=?") + .get(row.id); + if (!current) throw new Error("The saved game setup is missing"); + return JSON.parse(current.body); + }; + let updateId = 3; + const replyWith = (text: string) => + bot.handleUpdate({ + update_id: updateId, + message: { + message_id: updateId++, + date: 1, + chat, + from, + text, + reply_to_message: { + message_id: after.prompt, + date: 1, + chat, + text: "player prompt", + reply_to_message: undefined, + }, + }, + }); + for (const invalid of ["2.5", "2e1", "0x10", "7players"]) { + await replyWith(invalid); + expect(readSetup()).toMatchObject({ input: "players", prompt: after.prompt, players: 2 }); + } + await replyWith(" +07 "); + expect(readSetup()).toMatchObject({ screen: "confirm", players: 7 }); + expect(readSetup().input).toBeUndefined(); } finally { store.db.close(); } diff --git a/tests/game-setup.flows.test.ts b/tests/game-setup.flows.test.ts index b35f2e21..16816000 100644 --- a/tests/game-setup.flows.test.ts +++ b/tests/game-setup.flows.test.ts @@ -241,9 +241,12 @@ describe("interactive game setup", () => { await clickLabel("📊 Custom Players", setupId); expect(getGameSetupSession(`${CHAT}_${setupId}`)?.waitingFor).toBe("players_input"); - await replyTo(setupId, "1"); - expect(messageText(lastMessage())).toContain("Invalid number of players"); - await replyTo(setupId, "7"); + for (const invalid of ["1", "2.5", "2e1", "0x10", "7players"]) { + await replyTo(setupId, invalid); + expect(messageText(lastMessage())).toContain("Invalid number of players"); + expect(getGameSetupSession(`${CHAT}_${setupId}`)?.waitingFor).toBe("players_input"); + } + await replyTo(setupId, " +07 "); expect(messageText(lastMessage())).toContain("Players: 7"); }); From c3e526e3a0416f671345b2c770ad9b1a34fd03b5 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 13:26:01 -0300 Subject: [PATCH 033/410] test(bot): bound cache eviction and pending setup recovery --- src/bot.ts | 8 +++---- tests/bot-token-policy.test.ts | 32 ++++++++++++++++++++++++++ tests/bot.token-metadata-cache.test.ts | 24 +++++++++++++++++++ tests/outbound-error-guard.test.ts | 18 +++++++++++++++ 4 files changed, 78 insertions(+), 4 deletions(-) diff --git a/src/bot.ts b/src/bot.ts index 53493d29..7cdcdb48 100644 --- a/src/bot.ts +++ b/src/bot.ts @@ -396,9 +396,8 @@ const setTokenMetadataCacheEntry = (mint: string, entry: CachedTokenMetadata): v cachedTokenMetadata.delete(mint); cachedTokenMetadata.set(mint, entry); - while (cachedTokenMetadata.size > TOKEN_METADATA_CACHE_MAX_ENTRIES) { - const oldestKey = cachedTokenMetadata.keys().next().value; - if (!oldestKey) { + for (const oldestKey of cachedTokenMetadata.keys()) { + if (!(cachedTokenMetadata.size > TOKEN_METADATA_CACHE_MAX_ENTRIES) || !oldestKey) { break; } cachedTokenMetadata.delete(oldestKey); @@ -3410,7 +3409,8 @@ const recoverPendingGameCreations = async (): Promise => { recoveringGameCreations = true; try { const pending = gameDb.getPendingGameCreations(Date.now(), 25); - for (let offset = 0; offset < pending.length; offset += 4) { + for (const offset of pending.keys()) { + if (offset % 4 !== 0) continue; await Promise.all( pending.slice(offset, offset + 4).map(async (record) => { try { diff --git a/tests/bot-token-policy.test.ts b/tests/bot-token-policy.test.ts index b17b6b5f..a4279c64 100644 --- a/tests/bot-token-policy.test.ts +++ b/tests/bot-token-policy.test.ts @@ -185,6 +185,38 @@ describe("recoverPendingGameCreations", () => { expect(recover).toHaveBeenCalledTimes(1); }); + test("reads at most 25 pending records and starts four recoveries at a time", async () => { + const clock = spyOn(Date, "now").mockReturnValue(1_000_000); + const getPendingGameCreations = spyOn( + botModule.__test_getGameDatabase(), + "getPendingGameCreations", + ); + + const started: string[] = []; + let releaseFirstRecord: (() => void) | undefined; + recover.mockImplementation((_context: unknown, record: { game_address: string }) => { + if (started.includes(record.game_address)) throw new Error("record already attempted"); + started.push(record.game_address); + if (record.game_address !== "Game0") return Promise.resolve(false); + return new Promise((resolve) => { + releaseFirstRecord = () => resolve(false); + }); + }); + + const sweep = botModule.__test_recoverPendingGameCreations(); + const firstBatch = [...started]; + releaseFirstRecord?.(); + try { + await sweep; + expect(getPendingGameCreations).toHaveBeenCalledWith(1_000_000, 25); + expect(firstBatch).toEqual(["Game0", "Game1", "Game2", "Game3"]); + expect(started).toEqual(pending.map(({ game_address }) => game_address)); + } finally { + clock.mockRestore(); + getPendingGameCreations.mockRestore(); + } + }); + test("a failing sweep is logged and can run again", async () => { botModule.__test_setGameDatabase({ getPendingGameCreations: () => { diff --git a/tests/bot.token-metadata-cache.test.ts b/tests/bot.token-metadata-cache.test.ts index 44c17908..6fdc231f 100644 --- a/tests/bot.token-metadata-cache.test.ts +++ b/tests/bot.token-metadata-cache.test.ts @@ -142,6 +142,30 @@ describe("token metadata cache", () => { wallet.getTokenMetadata = originalGetTokenMetadata; }); + test("keeps exactly 200 recent mints at the production capacity", async () => { + const clock = spyOn(Date, "now").mockReturnValue(1_000_000); + const fetch = spyOn(wallet, "getTokenMetadata").mockResolvedValue({ decimals: 6 }); + try { + for (let index = 0; index < 200; index++) { + expect((await __test_getCachedTokenMetadata(`Mint-${index}`)).decimals).toBe(6); + } + await __test_getCachedTokenMetadata("Mint-0"); + expect(fetch).toHaveBeenCalledTimes(200); + + await __test_getCachedTokenMetadata("Mint-200"); + await __test_getCachedTokenMetadata("Mint-0"); + await __test_getCachedTokenMetadata("Mint-2"); + expect(fetch).toHaveBeenCalledTimes(201); + + await __test_getCachedTokenMetadata("Mint-1"); + expect(fetch).toHaveBeenCalledTimes(202); + expect(fetch).toHaveBeenLastCalledWith("Mint-1"); + } finally { + fetch.mockRestore(); + clock.mockRestore(); + } + }); + test("wraps metadata errors with context", async () => { const mint = "ErrorMint99999999999999999999999999999999"; const originalGetTokenMetadata = wallet.getTokenMetadata; diff --git a/tests/outbound-error-guard.test.ts b/tests/outbound-error-guard.test.ts index fb62d562..eccbf4f9 100644 --- a/tests/outbound-error-guard.test.ts +++ b/tests/outbound-error-guard.test.ts @@ -21,6 +21,24 @@ describe("outbound Telegram error guard", () => { expect(guardOutboundText(text)).toBe(GENERIC_USER_ERROR_MESSAGE); }); + test("continues searching for a diagnostic after null and primitive values", () => { + const text = JSON.stringify([null, false, 2, "plain", { outer: { statusText: "Busy" } }]); + expect(guardOutboundText(text)).toBe(GENERIC_USER_ERROR_MESSAGE); + }); + + test.each([ + [5, true], + [6, false], + ] as const)( + "inspects structured messages through object depth 5 (depth %i)", + (depth, blocked) => { + let value: object = { statusText: "Busy" }; + for (let index = 0; index < depth; index++) value = { child: value }; + const text = JSON.stringify(value); + expect(guardOutboundText(text)).toBe(blocked ? GENERIC_USER_ERROR_MESSAGE : text); + }, + ); + test.each([ `Failed to request Jupiter order: [ { "expected": "string", "code": "invalid_type", "path": ["routePlan"] } From 368b18bea12d48af2716f5034b80bc946ba75fa6 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 13:28:34 -0300 Subject: [PATCH 034/410] test(db): check pending game replacement and lease boundaries --- tests/game-database.pending-creation.test.ts | 109 +++++++++++++++++++ 1 file changed, 109 insertions(+) diff --git a/tests/game-database.pending-creation.test.ts b/tests/game-database.pending-creation.test.ts index abe73de8..4364d38f 100644 --- a/tests/game-database.pending-creation.test.ts +++ b/tests/game-database.pending-creation.test.ts @@ -283,6 +283,115 @@ describe("GameDatabase pending game creation lifecycle", () => { }); }); + describe("replacing a proven-absent game transaction", () => { + const game = "PENDING_1"; + const replacement = { + signature: "SIG_TWO", + blockhash: "new-blockhash", + lastValidBlockHeight: 250, + wire: "bmV3LXRyYW5zYWN0aW9u", + }; + + beforeEach(() => { + db.savePendingGameCreation({ + ...pendingInput(), + state: "unknown", + transactionBlockhash: "old-blockhash", + lastValidBlockHeight: 100, + }); + }); + + test.each([ + ["missing record", "OTHER_GAME", "SIG_ONE", "SIG_TWO"], + ["stale signature", game, "SIG_STALE", "SIG_TWO"], + ["unchanged signature", game, "SIG_ONE", "SIG_ONE"], + ] as const)("leaves the transaction intact for a %s", (_label, address, previous, next) => { + const original = db.getPendingGameCreation(game); + expect( + db.replaceExpiredGameCreation( + address, + previous, + { ...replacement, signature: next }, + NOW + 1, + ), + ).toBe(false); + expect(db.getPendingGameCreation(game)).toEqual(original); + expect(db.getPendingGameCreationAuditRecords()).toHaveLength(1); + }); + + test("fences replacement at the exact end of the game deadline", () => { + expect(db.replaceExpiredGameCreation(game, "SIG_ONE", replacement, NOW + 60_000)).toBe(false); + expect(db.getPendingGameCreation(game)?.transaction_signature).toBe("SIG_ONE"); + }); + + test("releases an expired lease and preserves the full proof of the previous attempt", () => { + const leaseEnds = NOW + 20_000; + expect(db.claimPendingGameCreationSubmission(game, "sender", leaseEnds, NOW)).toEqual({ + acquired: true, + }); + expect(db.replaceExpiredGameCreation(game, "SIG_ONE", replacement, leaseEnds - 1)).toBe( + false, + ); + expect(db.replaceExpiredGameCreation(game, "SIG_ONE", replacement, leaseEnds)).toBe(true); + + const record = db.getPendingGameCreation(game); + expect(record).toMatchObject({ + state: "prepared", + transaction_signature: replacement.signature, + transaction_blockhash: replacement.blockhash, + last_valid_block_height: replacement.lastValidBlockHeight, + signed_transaction_base64: replacement.wire, + replacement_count: 1, + submission_lease_id: null, + submission_lease_expires_at: null, + next_attempt_at: leaseEnds, + updated_at: leaseEnds, + transaction_prepared_at: leaseEnds, + }); + expect(JSON.parse(record?.replacement_history ?? "null")).toEqual([ + { + signature: "SIG_ONE", + blockhash: "old-blockhash", + lastValidBlockHeight: 100, + resolvedAt: leaseEnds, + reason: + "Absent from complete finalized blockhash lifetime; independent anchor corroborated", + }, + ]); + }); + }); + + describe("finishing a pending game submission", () => { + test("truncates only the stored error and uses the supplied zero epoch and retry time", () => { + const game = "PENDING_1"; + db.savePendingGameCreation({ ...pendingInput(), state: "prepared" }); + expect(db.claimPendingGameCreationSubmission(game, "worker", NOW + 1, NOW)).toEqual({ + acquired: true, + }); + + const diagnostic = "x".repeat(500); + expect( + db.finishPendingGameCreationSubmission(game, "another-worker", "failed", { now: 0 }), + ).toBe(false); + expect(db.getPendingGameCreation(game)?.submission_lease_id).toBe("worker"); + expect( + db.finishPendingGameCreationSubmission(game, "worker", "unknown", { + error: `${diagnostic}omitted`, + nextAttemptAt: 123, + now: 0, + }), + ).toBe(true); + expect(db.getPendingGameCreation(game)).toMatchObject({ + state: "unknown", + submission_lease_id: null, + submission_lease_expires_at: null, + last_error: diagnostic, + updated_at: 0, + next_attempt_at: 123, + }); + }); + }); + describe("resolvePendingGameCreation", () => { test("keeps a confirmed record that has recovery evidence on the automatic path", () => { db.savePendingGameCreation( From 0b295f49e3bee54c45a435faa2395aa0f2108234 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 13:30:55 -0300 Subject: [PATCH 035/410] test(bot): check legacy prompt ownership without network fallback --- tests/bot-chat-media.flows.test.ts | 43 ++++++++++++++++++++++++++++++ tests/input-session.locks.test.ts | 32 +++++++++++----------- 2 files changed, 58 insertions(+), 17 deletions(-) diff --git a/tests/bot-chat-media.flows.test.ts b/tests/bot-chat-media.flows.test.ts index 77271cbe..5441a578 100644 --- a/tests/bot-chat-media.flows.test.ts +++ b/tests/bot-chat-media.flows.test.ts @@ -188,8 +188,34 @@ describe("media replies for chat defaults", () => { "❌ This prompt is no longer active for you.\n\nOpen the defaults menu again to continue.", ); expect(botModule.__test_getChatDatabase().getChatGameSettings(CHAT)).toBeNull(); + expect(getInputSession(`${CHAT}_${PROMPT}`)?.initiatorId).toBe("9999"); }); + test.each([ + ["empty", ""], + ["missing", undefined], + ] as const)( + "allows a direct media reply to a legacy prompt with owner %s", + async (_label, owner) => { + const key = `${CHAT}_${PROMPT}`; + setInputSession(key, { + type: "chat_defaults", + setting: "video_coinflip", + chatId: CHAT, + messageId: PROMPT, + initiatorId: owner, + }); + + await sendMedia(video, { replyTo: PROMPT }); + + expect(botModule.__test_getChatDatabase().getChatGameSettings(CHAT)).toMatchObject({ + coinflip_video_id: "video-file", + coinflip_media_type: "video", + }); + expect(getInputSession(key)).toBeUndefined(); + }, + ); + test("media is ignored without a matching media prompt", async () => { prompt("timeout"); @@ -263,6 +289,23 @@ describe("typed replies to chat default prompts", () => { expect(rest.filter((payload) => "ephemeral_message_parameters" in payload)).toEqual([]); }; + test.each([ + ["empty", ""], + ["missing", undefined], + ] as const)( + "allows an admin reply to a legacy text prompt with owner %s", + async (_label, owner) => { + promptFor({ setting: "timeout", initiatorId: owner }); + + await sendReply("900"); + + expect(botModule.__test_getChatDatabase().getChatGameSettings(CHAT)?.timeout_seconds).toBe( + 900, + ); + expect(getInputSession(`${CHAT}_${PROMPT}`)).toBeUndefined(); + }, + ); + test.each([ [ "an invalid player count", diff --git a/tests/input-session.locks.test.ts b/tests/input-session.locks.test.ts index 669f5df0..823d0ed2 100644 --- a/tests/input-session.locks.test.ts +++ b/tests/input-session.locks.test.ts @@ -49,23 +49,21 @@ beforeAll(async () => { api.editMessageText = async () => ({ ok: true, result: true }); api.deleteMessage = async () => ({ ok: true, result: true }); api.answerCallbackQuery = async () => ({ ok: true, result: true }); - api.config.use( - async (prev: any, method: string, payload: any, signal: AbortSignal | undefined) => { - if (method === "sendMessage") { - sendMessagePayloads.push(payload); - return { - ok: true, - result: { - message_id: Math.trunc(Math.random() * 10_000) + 1, - chat: { id: payload.chat_id }, - date: Math.floor(Date.now() / 1000), - }, - }; - } - - return prev(method, payload, signal); - }, - ); + api.config.use(async (_prev: unknown, method: string, payload: any) => { + if (method === "sendMessage") { + sendMessagePayloads.push(payload); + return { + ok: true, + result: { + message_id: Math.trunc(Math.random() * 10_000) + 1, + chat: { id: payload.chat_id }, + date: Math.floor(Date.now() / 1000), + }, + }; + } + + throw new Error(`Unexpected Telegram API call in the input-lock test: ${method}`); + }); }); const clearInputSessions = () => { From c0fe4b7ddda2376c0264e9bf42ec63acb0596eac Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 13:32:53 -0300 Subject: [PATCH 036/410] fix(format): preserve finite percentages above the number range --- src/utils/format-amount.ts | 11 +++++++++-- tests/format-amount.test.ts | 3 +++ 2 files changed, 12 insertions(+), 2 deletions(-) diff --git a/src/utils/format-amount.ts b/src/utils/format-amount.ts index 30d2c321..208630a4 100644 --- a/src/utils/format-amount.ts +++ b/src/utils/format-amount.ts @@ -194,10 +194,17 @@ export function formatSignedPercent(value: number): string { return "0%"; } - const abs = Math.abs(value) * 100; + const magnitude = Math.abs(value); + const sign = Math.sign(value) === 1 ? "+" : "-"; + const abs = magnitude * 100; + if (!Number.isFinite(abs)) { + // A finite ratio can overflow when converted to a percentage. Scale its exponent instead. + const [coefficient, exponent] = magnitude.toExponential().split("e+"); + return `${sign}${coefficient}e+${Number(exponent) + 2}%`; + } const wholePercent = Math.trunc(abs); const digits = abs.toFixed(wholePercent >= 10 ? 1 : 2); - return `${Math.sign(value) === 1 ? "+" : "-"}${trimFixed(digits)}%`; + return `${sign}${trimFixed(digits)}%`; } const RATE_PRECISION = [ diff --git a/tests/format-amount.test.ts b/tests/format-amount.test.ts index bb5d4aaa..70dbe413 100644 --- a/tests/format-amount.test.ts +++ b/tests/format-amount.test.ts @@ -27,6 +27,9 @@ test.each<[number, string]>([ [0.10051, "+10.1%"], [-0.10051, "-10.1%"], [1e28, "+1e+30%"], + [1e307, "+1e+309%"], + [-1e307, "-1e+309%"], + [Number.MAX_VALUE, "+1.7976931348623157e+310%"], ])("formatSignedPercent(%p) is %s", (value, expected) => { expect(formatSignedPercent(value)).toBe(expected); }); From dc78255835c4c7c7fd39d4b849be0794a2a14c01 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 13:34:56 -0300 Subject: [PATCH 037/410] test(finance): check sponsor evidence after database reopen --- tests/transaction-history.paths.test.ts | 84 ++++++++++++++++++++++++- 1 file changed, 83 insertions(+), 1 deletion(-) diff --git a/tests/transaction-history.paths.test.ts b/tests/transaction-history.paths.test.ts index 8c7ad92f..0955dee4 100644 --- a/tests/transaction-history.paths.test.ts +++ b/tests/transaction-history.paths.test.ts @@ -4,6 +4,7 @@ import { TransactionHistory, createTransactionRecord, formatTransactionForDisplay, + type SwapStatRecord, type TransactionRecord, } from "../src/utils/transaction-history"; import { getTestDatabasePath, resetTestDatabase } from "./helpers/database"; @@ -100,7 +101,13 @@ describe("swap_stats finance schema migration", () => { ]), ); expect(db.getSwapsByWallet("wallet-f")).toEqual([ - expect.objectContaining({ signature: "legacy-sig", amount_in: "5" }), + expect.objectContaining({ + signature: "legacy-sig", + amount_in: "5", + sponsor_cost_lamports: null, + sponsor_reimbursement_lamports: null, + sponsor_cost_estimated: undefined, + }), ]); // The upgraded table accepts rows that use the new columns. db.recordSwap({ @@ -124,6 +131,81 @@ describe("swap_stats finance schema migration", () => { }); }); +describe("swap finance evidence", () => { + const openHistory = () => Reflect.construct(TransactionHistory, []) as TransactionHistory; + + test("keeps an exact zero cost distinct from estimates and unknown costs after reopening the database", () => { + const wallet = "wallet-f"; + const swap: SwapStatRecord = { + signature: "measure", + wallet, + input_mint: "in", + output_mint: "out", + input_ticker: "IN", + output_ticker: "OUT", + amount_in: "7", + referral_applied: false, + timestamp: 2000, + }; + const db = openHistory(); + db.recordSwap({ + ...swap, + fee_bps: 0, + sponsor_cost_lamports: "0", + sponsor_reimbursement_lamports: "0", + sponsor_cost_estimated: false, + }); + db.recordSwap({ + ...swap, + signature: "estimate", + sponsor_cost_lamports: "314", + sponsor_reimbursement_lamports: "92", + sponsor_cost_estimated: true, + referral_applied: true, + timestamp: 1000, + network: "devnet", + }); + db.recordSwap({ ...swap, signature: "unknown", timestamp: 3000 }); + db.recordSwap({ ...swap, signature: "other-wallet", wallet: "different" }); + db.recordSwap({ ...swap, sponsor_cost_estimated: true, sponsor_cost_lamports: "999" }); + db.close(); + + const reopened = openHistory(); + const readSwaps = () => { + try { + return reopened.getSwapsByWallet(wallet); + } finally { + reopened.close(); + } + }; + expect(readSwaps()).toEqual([ + expect.objectContaining({ + signature: "estimate", + sponsor_cost_lamports: "314", + sponsor_reimbursement_lamports: "92", + sponsor_cost_estimated: true, + referral_applied: true, + network: "devnet", + }), + expect.objectContaining({ + signature: "measure", + sponsor_cost_lamports: "0", + sponsor_reimbursement_lamports: "0", + sponsor_cost_estimated: false, + referral_applied: false, + fee_bps: 0, + network: "mainnet", + }), + expect.objectContaining({ + signature: "unknown", + sponsor_cost_lamports: null, + sponsor_reimbursement_lamports: null, + sponsor_cost_estimated: undefined, + }), + ]); + }); +}); + describe("TransactionHistory error handling", () => { test("addTransaction logs and rethrows on a duplicate signature", () => { const db = TransactionHistory.getInstance(); From 99cb369c7178e083d5b34f4004a74c6be1ee38b2 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 13:36:54 -0300 Subject: [PATCH 038/410] test(games): check confirmation of a settled last-seat join --- tests/game-callbacks.module.test.ts | 40 +++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) diff --git a/tests/game-callbacks.module.test.ts b/tests/game-callbacks.module.test.ts index d50bf95b..a6cc2d51 100644 --- a/tests/game-callbacks.module.test.ts +++ b/tests/game-callbacks.module.test.ts @@ -245,6 +245,46 @@ describe("joining a game", () => { expect(h.program.account.game.fetch).toHaveBeenCalledTimes(1); }); + test("uses the reported ticket count and the capacity from the post-join account", async () => { + const h = setup(); + const gameAccount = { ticketsCount: 9n, maxTickets: 12n }; + h.gameManager.joinGame.mockResolvedValue({ success: true, ticketsCount: 2, gameAccount }); + + expect((await run(h, `join_${GAME}`)).answers).toEqual(["✅ Joined! (2/12)"]); + expect(h.program.account.game.fetch).not.toHaveBeenCalled(); + expect(h.gameManager.updateGameMessageFromData.mock.calls[0]?.[6]).toEqual({ gameAccount }); + }); + + test("confirms a successful last-seat join when settlement has already closed the account", async () => { + const h = setup(); + h.gameManager.joinGame.mockResolvedValue({ success: true }); + h.program.account.game.fetch.mockRejectedValue( + Object.assign(new Error("game is settled"), { code: "ACCOUNT_NOT_FOUND" }), + ); + + expect((await run(h, `join_${GAME}`, { id: 71 })).answers).toEqual(["✅ Joined!"]); + expect(h.gameManager.updateGameMessageFromData).not.toHaveBeenCalled(); + }); + + test("answers before redrawing the game card after a successful join", async () => { + const h = setup(); + const call = callbackCtx(`join_${GAME}`, { id: 72 }); + const order: string[] = []; + call.ctx.answerCallbackQuery = async () => { + order.push("answer"); + }; + h.gameManager.updateGameMessageFromData.mockImplementation(async () => { + order.push("redraw"); + }); + + await h.module.__test_handleGenericGameCallback( + call.ctx, + mock(async () => {}), + ); + + expect(order).toEqual(["answer", "redraw"]); + }); + test("recreates the game card when joining from another chat", async () => { const h = setup(); h.gameManager.getActiveGameMessages.mockImplementation(() => new Map([[-999, 1]])); From 9e970939e5c49a445a3b4238e36157420318440c Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 13:39:51 -0300 Subject: [PATCH 039/410] refactor(tokens): share the USD amount parsing path --- src/utils/token-manager.ts | 45 +---------------------------- tests/token-manager.amounts.test.ts | 41 ++++++++++++++++++++++++++ 2 files changed, 42 insertions(+), 44 deletions(-) diff --git a/src/utils/token-manager.ts b/src/utils/token-manager.ts index 2956da11..3eb6988c 100644 --- a/src/utils/token-manager.ts +++ b/src/utils/token-manager.ts @@ -445,12 +445,6 @@ export class TokenManager { error: "unsupported_token", unknownToken: candidateUpper, }; - } else if (candidateLooksLikeTicker) { - return { - success: false, - error: "unknown_token", - unknownToken: candidateUpper, - }; } else { return { success: false, @@ -622,44 +616,7 @@ export class TokenManager { return { ok: true, amount: Number(rawAmountBigInt), priceLookup }; }; - if (isFiatHint) { - const usdResult = await toRawAmountFromUsd(); - if (!usdResult.ok) { - if (usdResult.reason === "unsupported_token") { - return { - success: false, - error: "unsupported_token", - unknownToken: "USD", - reason: "fiat_pricing_unavailable", - }; - } - return { - success: false, - error: usdResult.reason, - reason: usdResult.detail, - }; - } - - const formattedAmount = - this.wallet.formatTokenBalance(usdResult.amount, targetDecimals) + " " + tokenTicker; - - return { - success: true, - data: { - amount: usdResult.amount, - isSol, - formattedAmount, - tokenMint, - tokenTicker, - decimals: targetDecimals, - tokenWasSpecified, - requestedNativeSol, - priceLookup: usdResult.priceLookup, - }, - }; - } - - if (amountHasFiatMarker) { + if (isFiatHint || amountHasFiatMarker) { const usdResult = await toRawAmountFromUsd(); if (!usdResult.ok) { if (usdResult.reason === "unsupported_token") { diff --git a/tests/token-manager.amounts.test.ts b/tests/token-manager.amounts.test.ts index 24fbf3b4..9a30d7b8 100644 --- a/tests/token-manager.amounts.test.ts +++ b/tests/token-manager.amounts.test.ts @@ -75,6 +75,47 @@ describe("parseAmount argument validation", () => { unknownToken: "AB1C", }); }); + + test("rejects a numeric following argument only when it has more than 18 digits", async () => { + const tm = makeManager(); + expect(await tm.parseAmount(["/cf", "1", " 123456789.123456789 "], 1, 1, "game")).toMatchObject( + { success: true, data: { amount: 1_000_000, tokenWasSpecified: false } }, + ); + expect(await tm.parseAmount(["/cf", "1", "123456789.1234567890"], 1, 1, "game")).toEqual({ + success: false, + error: "invalid_amount", + }); + }); +}); + +describe("parseAmount USD conversion", () => { + test.each([ + ["leading marker", ["$ 7.000003"], false], + ["trailing marker", ["7.000003 $"], false], + ["currency code", ["7.000003", " usd "], true], + ["dollar token", ["7.000003", "$"], true], + ["US dollar token", ["7.000003", "US$"], true], + ["both marker and code", ["$7.000003", "USD"], true], + ] as const)("floors to whole token units once for a %s", async (_label, args, explicit) => { + const quote = priceLookup(2.5); + const lookup = spyOn(priceService, "getUsdPrice").mockResolvedValue(quote); + + expect(await makeManager().parseAmount(["/cf", ...args], 1, 1, "game")).toEqual({ + success: true, + data: { + amount: 2_800_001, + isSol: false, + formattedAmount: "2.800001 DISC", + tokenMint: "MINT", + tokenTicker: "DISC", + decimals: 6, + tokenWasSpecified: explicit, + requestedNativeSol: false, + priceLookup: quote, + }, + }); + expect(lookup.mock.calls).toEqual([[{ tokenMint: "MINT" }]]); + }); }); describe("parseAmount USD conversion failures", () => { From 0cd67f5c5a34902156b5fdfd9c982a1d250272f8 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 13:42:54 -0300 Subject: [PATCH 040/410] fix(prices): enforce the deadline through the Jupiter response body --- src/utils/prices.ts | 150 +++++++++-------------------- tests/prices.http-deadline.test.ts | 78 +++++++++++++++ tests/prices.resilience.test.ts | 19 ++-- 3 files changed, 132 insertions(+), 115 deletions(-) create mode 100644 tests/prices.http-deadline.test.ts diff --git a/src/utils/prices.ts b/src/utils/prices.ts index 9bef1021..82f6ae39 100644 --- a/src/utils/prices.ts +++ b/src/utils/prices.ts @@ -24,12 +24,6 @@ const priceEntrySchema = z const priceEntriesSchema = z.record(z.string(), priceEntrySchema); const wrappedJupiterPriceResponseSchema = z.object({ data: priceEntriesSchema }).passthrough(); -function isAbortError(error: unknown): boolean { - if (!error || typeof error !== "object") return false; - const candidate = error as { name?: unknown; code?: unknown }; - return candidate.name === "AbortError" || candidate.code === "ABORT_ERR"; -} - function getPriceEntries(payload: unknown): Record> { const wrapped = wrappedJupiterPriceResponseSchema.safeParse(payload); return wrapped.success ? wrapped.data.data : priceEntriesSchema.parse(payload); @@ -59,25 +53,6 @@ function isValidMintAddress(value: string): boolean { } } -async function withTimeout( - factory: (signal: AbortSignal) => Promise, - timeoutMs: number, -): Promise { - const ac = new AbortController(); - const timer = setTimeout(() => ac.abort(), timeoutMs); - - try { - return await factory(ac.signal); - } catch (error) { - if (isAbortError(error)) { - throw new Error("timeout", { cause: error }); - } - throw error; - } finally { - clearTimeout(timer); - } -} - function pickValidPrice(candidates: Array): number | null { for (const candidate of candidates) { const price = typeof candidate === "number" ? candidate : Number(candidate); @@ -106,31 +81,38 @@ function pickUsdPrice(entry: z.infer, mint?: string): n return price; } -async function fetchFromJupiter( - id: string, +async function fetchJupiterEntries( + ids: string, fetchImpl: FetchLike, timeoutMs: number, -): Promise { +): Promise | null> { + const controller = new AbortController(); + let timer: ReturnType | undefined; try { const url = new URL(JUPITER_PRICE_URL); - url.searchParams.set("ids", id); + url.searchParams.set("ids", ids); const apiKey = process.env.JUPITER_API_KEY; - const res = await withTimeout( - (signal) => - fetchImpl(url.toString(), { - method: "GET", - headers: apiKey ? { "x-api-key": apiKey } : undefined, - signal, - }), - timeoutMs, - ); - if (!res.ok) return null; - const entry = getPriceEntries(await res.json())[id]; - if (!entry) return null; - return pickUsdPrice(entry, id); + const deadline = new Promise((resolve) => { + timer = setTimeout(() => { + controller.abort(); + resolve(null); + }, timeoutMs); + }); + const request = async () => { + const response = await fetchImpl(url.toString(), { + method: "GET", + headers: apiKey ? { "x-api-key": apiKey } : undefined, + signal: controller.signal, + }); + return response.ok ? getPriceEntries(await response.json()) : null; + }; + // Use one deadline for both headers and body, even when a transport ignores abort. + return await Promise.race([deadline, request()]); } catch { return null; + } finally { + clearTimeout(timer); } } @@ -139,33 +121,13 @@ async function fetchBatchFromJupiter( fetchImpl: FetchLike, timeoutMs: number, ): Promise> { - try { - const url = new URL(JUPITER_PRICE_URL); - url.searchParams.set("ids", ids.join(",")); - const apiKey = process.env.JUPITER_API_KEY; - - const res = await withTimeout( - (signal) => - fetchImpl(url.toString(), { - method: "GET", - headers: apiKey ? { "x-api-key": apiKey } : undefined, - signal, - }), - timeoutMs, - ); - if (!res.ok) { - return {}; - } - - const container = getPriceEntries(await res.json()); - return ids.reduce>((acc, requestId) => { - const entry = container?.[requestId]; - acc[requestId] = entry ? pickUsdPrice(entry, requestId) : null; - return acc; - }, {}); - } catch { - return {}; - } + const entries = await fetchJupiterEntries(ids.join(","), fetchImpl, timeoutMs); + if (!entries) return {}; + return ids.reduce>((acc, id) => { + const entry = entries[id]; + acc[id] = entry ? pickUsdPrice(entry, id) : null; + return acc; + }, {}); } export async function getPriceUSD( @@ -193,7 +155,9 @@ export async function getPriceUSD( const pendingPromise = (async () => { try { // 1) Jupiter price endpoint - const fromJup = await fetchFromJupiter(key, fetchImpl, PRICES_TIMEOUT_MS); + const entries = await fetchJupiterEntries(key, fetchImpl, PRICES_TIMEOUT_MS); + const entry = entries?.[key]; + const fromJup = entry ? pickUsdPrice(entry, key) : null; if (fromJup && fromJup > 0) { priceCache.setWithTTL(key, { value: fromJup }); return fromJup; @@ -228,44 +192,24 @@ export async function getPricesUSD( return Object.fromEntries(ids.map((id) => [id, 0])); } - const batchTargets = new Map }>(); - + const batchTargets = new Set(); for (const id of ids) { const normalizedKey = normalizeKey(id); - if (!normalizedKey || !isValidMintAddress(normalizedKey)) { - continue; - } - - const target = batchTargets.get(normalizedKey); - if (target) { - target.normalizedKeys.add(normalizedKey); - } else { - batchTargets.set(normalizedKey, { - requestId: normalizedKey, - normalizedKeys: new Set([normalizedKey]), - }); + if (normalizedKey && isValidMintAddress(normalizedKey)) { + batchTargets.add(normalizedKey); } } - if (batchTargets.size > 0) { - const requests = Array.from(batchTargets.values()); - for (let offset = 0; offset < requests.length; offset += JUPITER_PRICE_BATCH_SIZE) { - const batch = requests.slice(offset, offset + JUPITER_PRICE_BATCH_SIZE); - const fetched = await fetchBatchFromJupiter( - batch.map((item) => item.requestId), - fetchImpl, - PRICES_TIMEOUT_MS, - ); - - for (const target of batch) { - const price = fetched[target.requestId]; - if (!price || !Number.isFinite(price) || price <= 0) { - continue; - } - for (const normalizedKey of target.normalizedKeys) { - priceCache.setWithTTL(normalizedKey, { value: price }); - } - } + const requests = Array.from(batchTargets); + for (const offset of requests.keys()) { + if (offset % JUPITER_PRICE_BATCH_SIZE !== 0) continue; + const batch = requests.slice(offset, offset + JUPITER_PRICE_BATCH_SIZE); + const fetched = await fetchBatchFromJupiter(batch, fetchImpl, PRICES_TIMEOUT_MS); + + for (const mint of batch) { + const price = fetched[mint]; + if (!price || !Number.isFinite(price) || price <= 0) continue; + priceCache.setWithTTL(mint, { value: price }); } } diff --git a/tests/prices.http-deadline.test.ts b/tests/prices.http-deadline.test.ts new file mode 100644 index 00000000..505226fe --- /dev/null +++ b/tests/prices.http-deadline.test.ts @@ -0,0 +1,78 @@ +import { expect, test, vi } from "bun:test"; +import type { FetchLike } from "../src/types"; +import { __test_resetPriceCache, getPriceUSD, getPricesUSD } from "../src/utils/prices"; + +const MINT = "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"; +const OTHER_MINT = "7vfCXTUXx5WJV5JADk17DUJ4ksgau7utNKj4b963voxs"; + +async function flushRequests(): Promise { + for (let tick = 0; tick < 30; tick++) await Promise.resolve(); +} + +test.each([ + ["single response", false, false], + ["single body", false, true], + ["batch body", true, true], +] as const)( + "enforces the production three-second price deadline for a hung %s", + async (_label, batch, body) => { + const previous = process.env["PRICES_ENABLED"]; + process.env["PRICES_ENABLED"] = "true"; + __test_resetPriceCache(); + vi.useFakeTimers(); + const responsePending = Promise.withResolvers(); + const bodyPending = Promise.withResolvers(); + const requests: string[] = []; + const outcomes: unknown[] = []; + let firstSignal: AbortSignal | null | undefined; + let bodyReads = 0; + const empty = () => Response.json({}); + const fetchImpl: FetchLike = async (input, init) => { + const ids = new URL(String(input)).searchParams.get("ids") ?? ""; + requests.push(ids); + if (requests.length === 1) { + firstSignal = init?.signal; + if (!body) return responsePending.promise; + const response = empty(); + response.json = () => { + bodyReads++; + return bodyPending.promise; + }; + return response; + } + return Response.json({ [ids]: { usdPrice: ids === MINT ? 5 : 7 } }); + }; + + try { + const lookup = batch + ? getPricesUSD([MINT, OTHER_MINT], fetchImpl) + : getPriceUSD(MINT, fetchImpl); + void lookup.then( + (value) => outcomes.push(value), + (error: unknown) => outcomes.push(error), + ); + await flushRequests(); + expect(bodyReads).toBe(body ? 1 : 0); + expect(firstSignal?.aborted).toBe(false); + + vi.advanceTimersByTime(2_999); + await flushRequests(); + expect(outcomes).toEqual([]); + expect(firstSignal?.aborted).toBe(false); + + vi.advanceTimersByTime(1); + await flushRequests(); + expect(firstSignal?.aborted).toBe(true); + expect(outcomes).toEqual(batch ? [{ [MINT]: 5, [OTHER_MINT]: 7 }] : [0]); + expect(requests).toEqual(batch ? [`${MINT},${OTHER_MINT}`, MINT, OTHER_MINT] : [MINT]); + } finally { + responsePending.resolve(empty()); + bodyPending.resolve({}); + await flushRequests(); + vi.useRealTimers(); + __test_resetPriceCache(); + if (previous === undefined) delete process.env["PRICES_ENABLED"]; + else process.env["PRICES_ENABLED"] = previous; + } + }, +); diff --git a/tests/prices.resilience.test.ts b/tests/prices.resilience.test.ts index 9938ada5..90a50d82 100644 --- a/tests/prices.resilience.test.ts +++ b/tests/prices.resilience.test.ts @@ -236,21 +236,16 @@ describe("price utilities resilience", () => { const mints = await Promise.all( Array.from({ length: 55 }, async () => (await Keypair.generate()).publicKey.toBase58()), ); - const requestSizes: number[] = []; - const fetchImpl = (async (url: string) => { - const ids = (new URL(url).searchParams.get("ids") ?? "").split(",").filter(Boolean); - requestSizes.push(ids.length); - return { - ok: true, - async json() { - return Object.fromEntries(ids.map((id) => [id, { usdPrice: 1 }])); - }, - } as any; - }) as any; + const requests: string[][] = []; + const fetchImpl = async (input: RequestInfo | URL) => { + const ids = (new URL(String(input)).searchParams.get("ids") ?? "").split(",").filter(Boolean); + requests.push(ids); + return Response.json(Object.fromEntries(ids.map((id) => [id, { usdPrice: 1 }]))); + }; const prices = await getPricesUSD(mints, fetchImpl); - expect(requestSizes).toEqual([50, 5]); + expect(requests).toEqual([mints.slice(0, 50), mints.slice(50)]); expect(Object.keys(prices)).toHaveLength(55); expect(Object.values(prices).every((price) => price === 1)).toBe(true); }); From be06b55e1bef3620120e64096fe572f14feace97 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 13:45:27 -0300 Subject: [PATCH 041/410] test(leaderboard): check tied highlights and currency thresholds --- tests/leaderboard-ui.test.ts | 67 ++++++++++++++++++++++++++++++++++++ 1 file changed, 67 insertions(+) diff --git a/tests/leaderboard-ui.test.ts b/tests/leaderboard-ui.test.ts index 73b39b62..97c0d56e 100644 --- a/tests/leaderboard-ui.test.ts +++ b/tests/leaderboard-ui.test.ts @@ -21,6 +21,24 @@ type LeaderboardPlayerSeed = { gamesJoined: number; }; +const contender = ( + id: string, + name: string, + wins: number, + losses: number, +): LeaderboardPlayerDisplay => ({ + telegramId: id, + displayName: name, + totalGames: wins + losses, + wins, + losses, + winRate: (wins / (wins + losses)) * 100, + gamesCreated: 0, + gamesJoined: wins + losses, + totalVolume: 0, + netWonUsd: 0, +}); + describe("leaderboard UI rendering", () => { test("empty leaderboard message mirrors leaderboard layout", () => { const message = buildEmptyLeaderboardMessage(); @@ -81,6 +99,43 @@ describe("leaderboard UI rendering", () => { expect(output).toContain("Most games played"); }); + test.each([ + ["chat", buildLeaderboardMessage], + ["global", buildGlobalLeaderboardMessage], + ] as const)( + "%s highlights keep the displayed champion when another player ties", + (_label, build) => { + const champion = contender("1", "Champion", 3, 1); + const tied = contender("2", "Tied player", 3, 1); + + const output = build({ players: [champion], allPlayers: [tied, champion] }); + + expect(output).toContain("🥇 Champion"); + expect(output).not.toContain("Highlights"); + expect(output).not.toContain("Tied player"); + }, + ); + + test.each([ + ["chat", buildLeaderboardMessage], + ["global", buildGlobalLeaderboardMessage], + ] as const)( + "%s highlights consider hidden players independently for both measures", + (_label, build) => { + const champion = contender("1", "Champion", 3, 1); + const mostWins = contender("2", "Rate & Leader", 3, 0); + const mostGames = contender("3", "Count ", 4, 5); + + const output = build({ players: [champion], allPlayers: [mostGames, champion, mostWins] }); + + expect(output.split("\n").slice(-3)).toEqual([ + "Highlights", + "• Best win rate: Rate & Leader (100%)", + "• Most games played: Count <Leader> (9)", + ]); + }, + ); + test("win rate formatting clamps invalid inputs", () => { const players: LeaderboardPlayerDisplay[] = [ { @@ -203,6 +258,18 @@ describe("formatNetUsd", () => { expect(formatNetUsd(0)).toBe("$0"); }); + test.each([ + [-0, "$0"], + [0.9999, "+$0.9999"], + [1, "+$1.00"], + [-1, "-$1.00"], + [999.99, "+$999.99"], + [1000, "+$1.0k"], + [-1000, "-$1.0k"], + ] as const)("keeps exact net USD precision at %p", (value, expected) => { + expect(formatNetUsd(value)).toBe(expected); + }); + test("handles non-finite values as $0", () => { expect(formatNetUsd(NaN)).toBe("$0"); expect(formatNetUsd(Infinity)).toBe("$0"); From 58aec5fd366c6b04343e1fc8c4d430a5f885ab13 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 13:49:44 -0300 Subject: [PATCH 042/410] fix(oracle): keep superseded policy responses out of the cache --- src/utils/oracle.ts | 9 ++- tests/oracle-client.policy.test.ts | 104 ++++++++++++++++++++++++++++- 2 files changed, 109 insertions(+), 4 deletions(-) diff --git a/src/utils/oracle.ts b/src/utils/oracle.ts index fb7b9ff4..39ad2c5b 100644 --- a/src/utils/oracle.ts +++ b/src/utils/oracle.ts @@ -98,6 +98,7 @@ export class OracleClient { }; private tokenPolicyRequest?: { oracleApiUrl: string; + id: symbol; promise: Promise; }; @@ -179,10 +180,11 @@ export class OracleClient { return this.tokenPolicyRequest.promise; } + const id = Symbol(); const promise = (async () => { try { const policies = expectStatus(await this.apiClient().tokenPolicies(), 200).data.policies; - if (this.oracleApiUrl === oracleApiUrl) { + if (this.tokenPolicyRequest?.id === id) { this.tokenPolicyCache = { oracleApiUrl, policies, @@ -203,11 +205,11 @@ export class OracleClient { } })(); - this.tokenPolicyRequest = { oracleApiUrl, promise }; + this.tokenPolicyRequest = { oracleApiUrl, id, promise }; try { return await promise; } finally { - if (this.tokenPolicyRequest?.promise === promise) { + if (this.tokenPolicyRequest?.id === id) { this.tokenPolicyRequest = undefined; } } @@ -366,5 +368,6 @@ export class OracleClient { public setOracleUrl(url: string): void { this.oracleApiUrl = url; this.tokenPolicyCache = undefined; + this.tokenPolicyRequest = undefined; } } diff --git a/tests/oracle-client.policy.test.ts b/tests/oracle-client.policy.test.ts index 75b1553b..d16d56b5 100644 --- a/tests/oracle-client.policy.test.ts +++ b/tests/oracle-client.policy.test.ts @@ -1,4 +1,4 @@ -import { afterEach, beforeEach, describe, expect, test } from "bun:test"; +import { afterEach, beforeEach, describe, expect, spyOn, test } from "bun:test"; import { Keypair, PublicKey, SystemProgram, Transaction } from "#solana"; import { OracleClient, OraclePolicyError, formatOraclePolicyError } from "../src/utils/oracle"; @@ -119,6 +119,108 @@ describe("Oracle token policy", () => { expect(cached).toEqual(first); }); + const replyWithRevision = (revision: number) => + Response.json(oracleResponse({ policies: [tokenPolicy({ revision })] })); + const waitForReply = (reply: Promise): typeof globalThis.fetch => + Object.assign(() => reply, { preconnect: realFetch.preconnect }); + + test("reloads policies exactly five seconds after a successful response", async () => { + let now = 1_000_000; + const clock = spyOn(Date, "now").mockImplementation(() => now); + const fetch = spyOn(globalThis, "fetch") + .mockRejectedValue(new Error("Unexpected Oracle policy request")) + .mockResolvedValueOnce(replyWithRevision(3)) + .mockResolvedValueOnce(replyWithRevision(4)); + const client = newOracleClient(); + client.setOracleUrl("http://oracle.test"); + try { + expect((await client.getTokenPolicies())[0]?.revision).toBe(3); + now += 4_999; + expect((await client.getTokenPolicies())[0]?.revision).toBe(3); + expect(fetch).toHaveBeenCalledTimes(1); + now++; + expect((await client.getTokenPolicies())[0]?.revision).toBe(4); + expect(fetch).toHaveBeenCalledTimes(2); + } finally { + clock.mockRestore(); + fetch.mockRestore(); + } + }); + + test.each(["before", "after"] as const)( + "discards a superseded response that arrives %s the new policy", + async (order) => { + const firstReply = Promise.withResolvers(); + const otherReply = Promise.withResolvers(); + const newReply = Promise.withResolvers(); + const fetch = spyOn(globalThis, "fetch") + .mockRejectedValue(new Error("Unexpected Oracle policy request")) + .mockImplementationOnce(waitForReply(firstReply.promise)) + .mockImplementationOnce(waitForReply(otherReply.promise)) + .mockImplementationOnce(waitForReply(newReply.promise)); + const client = newOracleClient(); + client.setOracleUrl("http://first.test"); + const older = client.getTokenPolicies(); + client.setOracleUrl("http://other.test"); + const other = client.getTokenPolicies(); + client.setOracleUrl("http://first.test"); + const newest = client.getTokenPolicies(); + try { + for (let tick = 0; tick < 12; tick++) await Promise.resolve(); + expect(fetch.mock.calls.map(([url]) => String(url))).toEqual([ + "http://first.test/token-policies", + "http://other.test/token-policies", + "http://first.test/token-policies", + ]); + otherReply.resolve(replyWithRevision(4)); + await other; + + if (order === "before") { + firstReply.resolve(replyWithRevision(3)); + await older; + const follower = client.getTokenPolicies(); + newReply.resolve(replyWithRevision(5)); + expect((await follower)[0]?.revision).toBe(5); + } else { + newReply.resolve(replyWithRevision(5)); + await newest; + firstReply.resolve(replyWithRevision(3)); + await older; + } + expect((await client.getTokenPolicies())[0]?.revision).toBe(5); + expect(fetch).toHaveBeenCalledTimes(3); + } finally { + firstReply.resolve(replyWithRevision(3)); + otherReply.resolve(replyWithRevision(4)); + newReply.resolve(replyWithRevision(5)); + await Promise.allSettled([older, other, newest]); + fetch.mockRestore(); + } + }, + ); + + test("refreshes pending policies when setting the same Oracle URL again", async () => { + const olderReply = Promise.withResolvers(); + const fetch = spyOn(globalThis, "fetch") + .mockRejectedValue(new Error("Unexpected Oracle policy request")) + .mockImplementationOnce(waitForReply(olderReply.promise)) + .mockResolvedValueOnce(replyWithRevision(5)); + const client = newOracleClient(); + client.setOracleUrl("http://oracle.test"); + const older = client.getTokenPolicies(); + client.setOracleUrl("http://oracle.test"); + const newer = client.getTokenPolicies(); + try { + olderReply.resolve(replyWithRevision(3)); + expect((await newer)[0]?.revision).toBe(5); + expect((await client.getTokenPolicies())[0]?.revision).toBe(5); + expect(fetch).toHaveBeenCalledTimes(2); + } finally { + await Promise.allSettled([older, newer]); + fetch.mockRestore(); + } + }); + test("preserves a typed signing rejection without exposing server text", async () => { globalThis.fetch = (async () => new Response( From 5d4ffde0c7bfe78dbb19f88fa3b2dc69d1841cbb Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 13:52:13 -0300 Subject: [PATCH 043/410] test(wallet): bound cache eviction and token batch iteration --- src/utils/wallet.ts | 18 ++++--- tests/wallet.balances-edge-cases.test.ts | 67 +++++++++++++++++++++++- 2 files changed, 77 insertions(+), 8 deletions(-) diff --git a/src/utils/wallet.ts b/src/utils/wallet.ts index adb78ce8..9e23a564 100644 --- a/src/utils/wallet.ts +++ b/src/utils/wallet.ts @@ -184,9 +184,8 @@ class KeypairCache { } private trim(): void { - while (this.cache.size > this.capacity) { - const oldestKey = this.cache.keys().next().value; - if (oldestKey === undefined) { + for (const oldestKey of this.cache.keys()) { + if (!(this.cache.size > this.capacity) || oldestKey === undefined) { break; } this.cache.delete(oldestKey); @@ -227,6 +226,12 @@ const hasRealTicker = (token: KnownTokenDefinition | undefined, mint: string): b }; const TOKEN_METADATA_LOOKUP_TIMEOUT_MS = 5_000; +function* walletBatches(items: T[], size: number): Generator { + for (const offset of items.keys()) { + if (offset % size === 0) yield items.slice(offset, offset + size); + } +} + async function withTimeout(promise: Promise, timeoutMs: number): Promise { let timer: ReturnType | undefined; try { @@ -1256,8 +1261,7 @@ export class WalletManager { } const CHUNK_SIZE = 100; - for (let i = 0; i < ataEntries.length; i += CHUNK_SIZE) { - const chunk = ataEntries.slice(i, i + CHUNK_SIZE); + for (const chunk of walletBatches(ataEntries, CHUNK_SIZE)) { const infos = await this.connection.getMultipleAccountsInfo( chunk.map((item) => item.address), ); @@ -1431,8 +1435,8 @@ export class WalletManager { const prefetch = async (mints: Iterable) => { const uniqueMints = Array.from(new Set(mints)).slice(0, 64); - for (let index = 0; index < uniqueMints.length; index += 8) { - await Promise.all(uniqueMints.slice(index, index + 8).map((mint) => load(mint))); + for (const batch of walletBatches(uniqueMints, 8)) { + await Promise.all(batch.map((mint) => load(mint))); } }; diff --git a/tests/wallet.balances-edge-cases.test.ts b/tests/wallet.balances-edge-cases.test.ts index 1d16ea9e..05d3ae1b 100644 --- a/tests/wallet.balances-edge-cases.test.ts +++ b/tests/wallet.balances-edge-cases.test.ts @@ -1,6 +1,11 @@ import { afterEach, beforeEach, describe, expect, spyOn, test } from "bun:test"; import { Keypair, PublicKey, SolanaJSONRPCError } from "#solana"; -import { AccountLayout, TOKEN_2022_PROGRAM_ID, TOKEN_PROGRAM_ID } from "#token"; +import { + AccountLayout, + getAssociatedTokenAddress, + TOKEN_2022_PROGRAM_ID, + TOKEN_PROGRAM_ID, +} from "#token"; import { WalletManager, type WalletTokenBalance, @@ -35,6 +40,12 @@ const walletWith = (connection: Record, deps: Record (await Keypair.generate()).publicKey.toBase58(); +const fixtureMints = (count: number) => + Array.from({ length: count }, (_, index) => { + const bytes = new Uint8Array(32); + bytes[0] = index + 1; + return new PublicKey(bytes); + }); const knownToken = (mint: string, ticker: string, decimals = 6) => ({ token_mint: mint, @@ -247,6 +258,60 @@ describe("getAllWalletTokenBalances edge cases", () => { return { censuses, onCensus: (census: WalletTokenCensus) => censuses.push(census) }; }; + test("requests at most 100 associated token accounts per RPC call without reordering them", async () => { + const mints = fixtureMints(101); + const requests: string[][] = []; + const wallet = walletWith( + baseConnection({ + getMultipleAccountsInfo: async (keys: PublicKey[]) => { + requests.push(keys.map((key) => key.toBase58())); + return keys.map(() => null); + }, + }), + ); + const owner = await wallet.getPublicKey(TELEGRAM_ID); + const addresses = await Promise.all( + mints.map(async (mint) => (await getAssociatedTokenAddress(mint, owner)).toBase58()), + ); + + const balances = await wallet.getAllWalletTokenBalances( + TELEGRAM_ID, + mints.map((mint, index) => knownToken(mint.toBase58(), `TOKEN${index}`)), + ); + + expect(balances).toEqual([]); + expect(requests).toEqual([addresses.slice(0, 100), addresses.slice(100)]); + }); + + test("prefetch starts eight unique mints at a time and stops at the 64-mint limit", async () => { + const mints = fixtureMints(65).map((mint) => mint.toBase58()); + const wallet = walletWith(baseConnection()); + const releaseFirstMint = Promise.withResolvers(); + const requested: string[] = []; + const fetch = spyOn(wallet, "getFullTokenMetadata").mockImplementation(async (mint) => { + requested.push(mint); + if (mint === mints[0]) await releaseFirstMint.promise; + return { decimals: 6 }; + }); + const { prefetch } = ( + wallet as unknown as { + createMetadataLoader(): { prefetch(mints: Iterable): Promise }; + } + ).createMetadataLoader(); + + try { + const run = prefetch([...mints.slice(0, 8), ...mints]); + const firstBatch = [...requested]; + releaseFirstMint.resolve(); + await run; + expect(firstBatch).toEqual(mints.slice(0, 8)); + expect(requested).toEqual(mints.slice(0, 64)); + } finally { + releaseFirstMint.resolve(); + fetch.mockRestore(); + } + }); + test("a failing token-program persist is logged and the lookup carries on", async () => { const tokenDb = { setTokenProgramId: () => { From 3952edd125cd8e450902eacba424fc9bbb0d1c60 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 13:54:19 -0300 Subject: [PATCH 044/410] fix(telegram): bound invalid media retry limits --- src/utils/media.ts | 7 +++---- tests/media.retry.test.ts | 43 ++++++++++++++++++++++++++++++++++++++- 2 files changed, 45 insertions(+), 5 deletions(-) diff --git a/src/utils/media.ts b/src/utils/media.ts index a77f8558..629907ab 100644 --- a/src/utils/media.ts +++ b/src/utils/media.ts @@ -52,7 +52,6 @@ type QueuedEditTask = { }; type QueuedEditState = { - inFlight: boolean; pending?: QueuedEditTask; }; @@ -75,7 +74,6 @@ const runQueuedMediaEdit = async (key: string, task: QueuedEditTask): Prom return; } - state.inFlight = false; messageMediaEditQueue.delete(key); }; @@ -85,7 +83,7 @@ export const enqueueMessageMediaEdit = ( ): Promise> => { const state = messageMediaEditQueue.get(key); if (!state) { - const nextState: QueuedEditState = { inFlight: true }; + const nextState: QueuedEditState = {}; messageMediaEditQueue.set(key, nextState); return new Promise>((resolve, reject) => { @@ -107,7 +105,8 @@ export const awaitTelegramRetry = async ( operation: () => Promise, options: { maxAttempts?: number } = {}, ): Promise => { - const maxAttempts = Math.max(1, options.maxAttempts ?? 3); + const requestedAttempts = Math.ceil(Math.max(1, options.maxAttempts ?? 3)); + const maxAttempts = Number.isSafeInteger(requestedAttempts) ? requestedAttempts : 3; for (let attempt = 1; ; attempt += 1) { try { diff --git a/tests/media.retry.test.ts b/tests/media.retry.test.ts index ab4230f4..d340cf05 100644 --- a/tests/media.retry.test.ts +++ b/tests/media.retry.test.ts @@ -1,4 +1,4 @@ -import { describe, expect, spyOn, test } from "bun:test"; +import { describe, expect, spyOn, test, vi } from "bun:test"; import fc from "fast-check"; import { awaitTelegramRetry, @@ -49,6 +49,7 @@ describe("media retry helpers", () => { awaitTelegramRetry( async () => { attempts += 1; + if (attempts > maxAttempts) throw new Error("retry fixture exhausted"); throw err; }, { maxAttempts }, @@ -151,6 +152,7 @@ describe("media retry helpers", () => { awaitTelegramRetry( async () => { attempts += 1; + if (attempts > 2) throw new Error("retry fixture exhausted"); throw error; }, { maxAttempts: 2 }, @@ -159,6 +161,45 @@ describe("media retry helpers", () => { expect(attempts).toBe(2); }); + test.each([ + ["default", undefined, 3], + ["non-finite", Infinity, 3], + ["NaN", NaN, 3], + ["unsafe integer", Number.MAX_VALUE, 3], + ["zero", 0, 1], + ["negative infinity", -Infinity, 1], + ["fractional", 1.5, 2], + ] as const)("bounds %s Telegram retry counts", async (_label, maxAttempts, expected) => { + vi.useFakeTimers(); + const failure = Object.assign(new Error("Too Many Requests"), { + error_code: 429, + parameters: { retry_after: 0 }, + }); + const outcomes: unknown[] = []; + let attempts = 0; + try { + const run = awaitTelegramRetry( + async () => { + if (++attempts > expected) throw new Error("retry fixture exhausted"); + throw failure; + }, + { maxAttempts }, + ); + void run.then( + (result) => outcomes.push(result), + (error: unknown) => outcomes.push(error), + ); + for (let tick = 0; tick < 32; tick++) { + vi.advanceTimersByTime(1); + await Promise.resolve(); + } + expect(attempts).toBe(expected); + expect(outcomes).toEqual([failure]); + } finally { + vi.useRealTimers(); + } + }); + test("awaitTelegramRetry waits one second when a 429 carries no retry-after hint", async () => { const delays: number[] = []; globalThis.setTimeout = ((callback: () => void, ms?: number) => { From c336a3243f3f65b244fc3d451670d2fb882f0235 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 13:55:50 -0300 Subject: [PATCH 045/410] fix(status): validate RPC slots and redact endpoint URLs --- src/handlers/admin-status.ts | 16 +++++++++----- tests/admin-status.test.ts | 41 ++++++++++++++++++++++++++++++++++++ 2 files changed, 52 insertions(+), 5 deletions(-) diff --git a/src/handlers/admin-status.ts b/src/handlers/admin-status.ts index 0e40349b..fb1db720 100644 --- a/src/handlers/admin-status.ts +++ b/src/handlers/admin-status.ts @@ -48,7 +48,7 @@ const describeProbeError = (error: unknown): string => { if (name === "TimeoutError" || name === "AbortError") return "timed out"; const message = error instanceof Error ? error.message : String(error); // Keep it short and free of URLs, which may include credentials. - return message.replace(/https?:\/\/\S+/g, "[url]").slice(0, 80) || "error"; + return message.replace(/https?:\/\/\S+/gi, "[url]").slice(0, 80) || "error"; }; /** Times one getSlot JSON-RPC call against `endpoint`. Never throws. */ @@ -70,12 +70,18 @@ export const probeRpcEndpoint = async ( body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "getSlot" }), signal: AbortSignal.timeout(options.timeoutMs ?? RPC_PROBE_TIMEOUT_MS), }); - const latencyMs = Math.round(now() - startedAt); if (!response.ok) { - return { endpoint, ok: false, latencyMs, error: `HTTP ${response.status}` }; + return { + endpoint, + ok: false, + latencyMs: Math.round(now() - startedAt), + error: `HTTP ${response.status}`, + }; } const payload = (await response.json()) as { result?: unknown; error?: { message?: string } }; - if (typeof payload?.result !== "number") { + const latencyMs = Math.round(now() - startedAt); + const slot = payload?.result; + if (typeof slot !== "number" || !Number.isSafeInteger(slot) || slot < 0) { return { endpoint, ok: false, @@ -83,7 +89,7 @@ export const probeRpcEndpoint = async ( error: describeProbeError(payload?.error?.message ?? "unexpected response"), }; } - return { endpoint, ok: true, latencyMs, slot: payload.result }; + return { endpoint, ok: true, latencyMs, slot }; } catch (error) { return { endpoint, diff --git a/tests/admin-status.test.ts b/tests/admin-status.test.ts index e715cfa8..7c79c265 100644 --- a/tests/admin-status.test.ts +++ b/tests/admin-status.test.ts @@ -51,6 +51,9 @@ describe("admin ids", () => { }); describe("rpc probe", () => { + const mockProbeFetch = (run: () => Promise): typeof fetch => + Object.assign(run, { preconnect: globalThis.fetch.preconnect }); + test("reports slot and latency", async () => { let clock = 100; let body: any; @@ -97,6 +100,44 @@ describe("rpc probe", () => { expect(network).toMatchObject({ ok: false, error: "Unable to connect to [url]" }); }); + test("redacts an uppercase HTTPS endpoint from remote errors", async () => { + const result = await probeRpcEndpoint("https://rpc.example", { + fetchFn: mockProbeFetch(async () => { + throw new Error("Unable to connect to HTTPS://rpc.example/?token=fixture-only"); + }), + }); + expect(result).toMatchObject({ ok: false, error: "Unable to connect to [url]" }); + }); + + test.each([ + ["negative", "-1"], + ["fractional", "0.5"], + ["unsafe", "9007199254740992"], + ["unrepresentable", "1e309"], + ] as const)("does not report %s slots as healthy", async (_label, slot) => { + const result = await probeRpcEndpoint("https://rpc.example", { + fetchFn: mockProbeFetch(async () => new Response(`{"result":${slot}}`)), + }); + expect(result).toMatchObject({ ok: false, error: "unexpected response" }); + }); + + test("accepts slot zero and measures through the RPC response body", async () => { + let clock = 100; + const result = await probeRpcEndpoint("https://rpc.example", { + now: () => clock, + fetchFn: mockProbeFetch(async () => { + clock += 10; + const response = new Response(null); + response.json = async () => { + clock += 800; + return { jsonrpc: "2.0", id: 1, result: 0 }; + }; + return response; + }), + }); + expect(result).toMatchObject({ ok: true, slot: 0, latencyMs: 810 }); + }); + test("endpoint labels only show the host", () => { expect(describeRpcEndpoint("https://mainnet.helius-rpc.com/?api-key=secret")).toBe( "mainnet.helius-rpc.com", From 63a6a0c12256764637ec939bc3772f2c8dd9a02d Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 13:57:33 -0300 Subject: [PATCH 046/410] test(tokens): verify built-in mint and precision mappings --- tests/token-registry.test.ts | 65 ++++++++++++++++++++++++++++++++++++ 1 file changed, 65 insertions(+) diff --git a/tests/token-registry.test.ts b/tests/token-registry.test.ts index 17c94887..893be7ef 100644 --- a/tests/token-registry.test.ts +++ b/tests/token-registry.test.ts @@ -1,8 +1,11 @@ import { afterEach, beforeEach, describe, expect, spyOn, test } from "bun:test"; import { buildTokenList, + getBuiltinTokenMetadataByMint, + getBuiltinTokenMetadataByTicker, getTokenByMint, getTokenByTicker, + getTokenMintAlias, getSupportedTokens, requireTokenByMint, requireTokenByTicker, @@ -57,6 +60,27 @@ describe("token-registry", () => { expect(token.ticker).toBe("TIMBA"); }); + test("an explicit network and mint do not depend on automatic network detection", () => { + process.env.DEFAULT_TOKEN_MINT = " "; + process.env.DEFAULT_TOKEN_TICKER = " "; + networkSpy = spyOn(NetworkDetector, "getCurrentNetwork").mockImplementation(() => { + throw new Error("automatic network selection must not run"); + }); + + expect(resolveDefaultToken({ network: "mainnet" })).toEqual({ + mint: "F3A1baCgv4TF79TSjdMTvpMDtNv8DJvHZwNc9DG8pump", + ticker: "TIMBA", + }); + expect(resolveDefaultToken({ mint: "FixtureMint" })).toEqual({ + mint: "FixtureMint", + ticker: "TOKEN", + }); + expect( + buildTokenList({ network: "devnet", defaultToken: { mint: "FixtureMint", ticker: "FIX" } }), + ).toContainEqual({ mint: "FixtureMint", ticker: "FIX" }); + expect(networkSpy).not.toHaveBeenCalled(); + }); + test("buildTokenList dedupes default token and respects includeDefault", () => { networkSpy = spyOn(NetworkDetector, "getCurrentNetwork").mockReturnValue("mainnet"); @@ -75,6 +99,47 @@ describe("token-registry", () => { const tokens = getSupportedTokens({ defaultToken: customDefault }); expect(tokens).toContainEqual(customDefault); + expect( + getSupportedTokens({ defaultToken: customDefault, includeDefault: false }), + ).not.toContainEqual(customDefault); + }); + + test("lookup aliases do not change the game mint allowlist", () => { + const bonk = "DezXAZ8z7PnrnRJjz3wXBoRgixCa6xjnB7YaB1pPB263"; + expect(getTokenMintAlias(" bOnK ")).toBe(bonk); + expect(getTokenByTicker("BONK", { network: "mainnet", includeDefault: false })).toBeUndefined(); + expect(getTokenByMint(bonk, { network: "mainnet", includeDefault: false })).toBeUndefined(); + }); + + test.each([ + ["USDC", "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v", 6], + ["USDT", "Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB", 6], + ["WBTC", "3NZ9JMVBmGAqocybic2c7LQCJScmgsAZ6vQqTDzcqmJh", 8], + ["ETH", "7vfCXTUXx5WJV5JADk17DUJ4ksgau7utNKj4b963voxs", 8], + ["MAGAIBA", "A6rSPi9JmJgVkW6BatsA6MjFYLseizPM2Fnt92coFjf4", 8], + ] as const)( + "binds the built-in %s ticker and mint to the same precision", + (ticker, mint, decimals) => { + expect(getBuiltinTokenMetadataByTicker(` ${ticker.toLowerCase()} `)).toEqual({ + ticker, + mint, + decimals, + }); + expect(getBuiltinTokenMetadataByMint(` ${mint} `)).toEqual({ ticker, mint, decimals }); + }, + ); + + test("keeps native SOL and its wrapped token distinct on ticker lookups", () => { + const native = { mint: WSOL_MINT, ticker: "SOL", decimals: 9, isNativeSol: true }; + expect(getBuiltinTokenMetadataByTicker(" sol ")).toEqual(native); + expect(getBuiltinTokenMetadataByTicker(" wSoL ")).toEqual({ + mint: WSOL_MINT, + ticker: "WSOL", + decimals: 9, + }); + expect(getBuiltinTokenMetadataByMint(` ${WSOL_MINT} `)).toEqual(native); + expect(getBuiltinTokenMetadataByTicker("")).toBeUndefined(); + expect(getBuiltinTokenMetadataByMint("")).toBeUndefined(); }); test("getToken lookups normalize ticker and mint values", () => { From c63167dcf9656adb7830a8bcc1e76897673b600f Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 14:00:45 -0300 Subject: [PATCH 047/410] test(games): bound username eviction and participant preview loops --- src/utils/game.ts | 24 ++++++------- tests/game-manager.participants.test.ts | 11 +++++- tests/game-manager.username.test.ts | 45 +++++++++++++++++++++++++ 3 files changed, 66 insertions(+), 14 deletions(-) diff --git a/src/utils/game.ts b/src/utils/game.ts index f11cc490..5f231c82 100644 --- a/src/utils/game.ts +++ b/src/utils/game.ts @@ -1070,16 +1070,18 @@ export class GameManager { } } + private trimUsernameCacheKeys(keys: string[], cache: { delete(key: string): boolean }): void { + const overflow = Math.max(0, keys.length - this.usernameCacheMaxEntries); + for (const oldestKey of keys.splice(0, overflow)) { + if (oldestKey) cache.delete(oldestKey); + } + } + private trackUsernameCacheKey(key: string): void { this.removeUsernameCacheKey(key); this.usernameCacheKeys.push(key); - while (this.usernameCacheKeys.length > this.usernameCacheMaxEntries) { - const oldestKey = this.usernameCacheKeys.shift(); - if (oldestKey) { - this.usernameCache.delete(oldestKey); - } - } + this.trimUsernameCacheKeys(this.usernameCacheKeys, this.usernameCache); } private setCachedUsername(key: string, value: string | null): void { @@ -1101,12 +1103,7 @@ export class GameManager { this.removeUsernameToIdCacheKey(key); this.usernameToIdCacheKeys.push(key); - while (this.usernameToIdCacheKeys.length > this.usernameCacheMaxEntries) { - const oldestKey = this.usernameToIdCacheKeys.shift(); - if (oldestKey) { - this.normalizedUsernameToIdCache.delete(oldestKey); - } - } + this.trimUsernameCacheKeys(this.usernameToIdCacheKeys, this.normalizedUsernameToIdCache); } private setCachedTelegramIdForUsername(key: string, telegramId: string): void { @@ -3287,7 +3284,8 @@ export class GameManager { ); if (messageText.length > TELEGRAM_MESSAGE_CHAR_LIMIT && participantDisplayNames.length > 0) { - for (let keep = participantDisplayNames.length; keep >= 0; keep -= 1) { + for (const offset of participantDisplayNames.keys()) { + const keep = participantDisplayNames.length - offset - 1; const omitted = Math.max(0, totalParticipants - keep); const candidate = composeMessage(participantDisplayNames.slice(0, keep), omitted); if (candidate.length <= TELEGRAM_MESSAGE_CHAR_LIMIT || keep === 0) { diff --git a/tests/game-manager.participants.test.ts b/tests/game-manager.participants.test.ts index 639d35fd..f2fdf337 100644 --- a/tests/game-manager.participants.test.ts +++ b/tests/game-manager.participants.test.ts @@ -184,7 +184,16 @@ describe("GameManager participants rendering", () => { ); expect(res.messageText.length).toBeLessThanOrEqual(4096); - expect(res.messageText).toMatch(/\n… and \d+ more/); + const displayedIds = [...res.messageText.matchAll(/user(\d+)x+/g)].map((match) => match[1]); + expect(displayedIds.length).toBeGreaterThan(0); + expect(displayedIds.length).toBeLessThan(participantIds.length); + expect(displayedIds).toEqual(participantIds.slice(0, displayedIds.length)); + expect(res.messageText).toContain( + `\n… and ${participantIds.length - displayedIds.length} more`, + ); + expect( + res.messageText.length + `user${participantIds[displayedIds.length]}${"x".repeat(80)}`.length, + ).toBeGreaterThan(4096); }); test("caps participant processing for huge games", async () => { diff --git a/tests/game-manager.username.test.ts b/tests/game-manager.username.test.ts index b09c0ac3..96a66f00 100644 --- a/tests/game-manager.username.test.ts +++ b/tests/game-manager.username.test.ts @@ -1,5 +1,6 @@ import { describe, test, expect } from "bun:test"; import fc from "fast-check"; +import type { Context } from "grammy"; import { TELEGRAM_USERNAME_CACHE_TTL_MS } from "../src/utils/constants"; import { makeDbStub, @@ -11,6 +12,50 @@ import { GameManager } from "../src/utils/game"; describe("GameManager Username Resolution", () => { describe("getUsernameFromTelegramId", () => { + test("keeps the last 500 users in both directions at the production cache limit", async () => { + resetGM(); + const persistedReads: string[] = []; + const networkReads: number[] = []; + const gm = GameManager.getInstance( + makeProgramStub(), + makeWalletStub(), + makeDbStub({ + extra: { + findTelegramIdByUsername(username: string) { + persistedReads.push(username); + return null; + }, + }, + }), + ); + const ctx = { + chat: { id: 88, type: "group" }, + api: { + async getChatMember(_chatId: number, id: number) { + networkReads.push(id); + return { user: { username: `refreshed${id}` } }; + }, + }, + } as unknown as Context; + + for (let index = 0; index < 500; index++) { + gm.primeUsernameCache(ctx, String(10000 + index), `@user${index}`, true); + } + expect(gm.findTelegramIdByUsername("@user0")).toBe("10000"); + expect(await gm.getUsernameFromTelegramId(ctx, "10000")).toBe("@user0"); + expect(persistedReads).toEqual([]); + expect(networkReads).toEqual([]); + + gm.primeUsernameCache(ctx, "10500", "@user500", true); + + expect(gm.findTelegramIdByUsername("@user1")).toBe("10001"); + expect(await gm.getUsernameFromTelegramId(ctx, "10001")).toBe("@user1"); + expect(gm.findTelegramIdByUsername("@user0")).toBeNull(); + expect(await gm.getUsernameFromTelegramId(ctx, "10000")).toBe("@refreshed10000"); + expect(persistedReads).toEqual(["@user0"]); + expect(networkReads).toEqual([10000]); + }); + test("returns null for invalid numeric ID", async () => { resetGM(); const gm = GameManager.getInstance(makeProgramStub(), makeWalletStub(), makeDbStub()); From 319c8c091b2058c04bd2e6dfdaeccf364bbe39a7 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 14:03:57 -0300 Subject: [PATCH 048/410] test(games): bound the wrapped SOL balance retry loop --- src/utils/game.ts | 18 ++++++----------- tests/game.funding-and-tokens.test.ts | 29 +++++++++++++++++++++++++++ 2 files changed, 35 insertions(+), 12 deletions(-) diff --git a/src/utils/game.ts b/src/utils/game.ts index 5f231c82..692ef824 100644 --- a/src/utils/game.ts +++ b/src/utils/game.ts @@ -2404,32 +2404,26 @@ export class GameManager { }; } - let updatedTokenBalance: number; - let updatedSolBalance: number; - const retryDelays = getWrapBalanceRetryDelays(); - - for (let attempt = 0; ; attempt++) { - [updatedTokenBalance, updatedSolBalance] = await Promise.all([ + const readBalances = () => + Promise.all([ this.wallet.getTokenBalance(telegramId, WSOL_MINT), this.wallet.getBalance(telegramId), ]); + let [updatedTokenBalance, updatedSolBalance] = await readBalances(); + for (const [attempt, delay] of retryDelays.entries()) { if (updatedTokenBalance >= requiredLamports) { break; } - if (attempt >= retryDelays.length) { - break; - } - const delay = retryDelays[attempt] ?? 0; - debugLog( `⏳ Waiting for WSOL balance propagation (attempt ${attempt + 1}/${ retryDelays.length + 1 })`, ); - await new Promise((resolve) => setTimeout(resolve, delay)); + await new Promise((resolve) => setTimeout(resolve, delay ?? 0)); + [updatedTokenBalance, updatedSolBalance] = await readBalances(); } if (updatedTokenBalance < requiredLamports) { diff --git a/tests/game.funding-and-tokens.test.ts b/tests/game.funding-and-tokens.test.ts index 8e6c5985..a8bd98d0 100644 --- a/tests/game.funding-and-tokens.test.ts +++ b/tests/game.funding-and-tokens.test.ts @@ -230,6 +230,35 @@ describe("GameManager ensureWrappedSolBalance", () => { timers.restore(); } }); + + test("stops on the first complete wrapped balance without a delay or another read", async () => { + const timers = stubInstantTimers(); + const requests: string[] = []; + const gm = setup({ + wrapSol: async () => "wrap-sig", + getTokenBalance: async () => { + requests.push("WSOL"); + if (requests.length > 2) throw new Error("unexpected repeated balance read"); + return REQUIRED; + }, + getBalance: async () => { + requests.push("SOL"); + return 100; + }, + }); + + try { + expect(await gm.ensureWrappedSolBalance(1n, REQUIRED, 0, 90_000, "create")).toEqual({ + success: true, + tokenBalance: REQUIRED, + solBalance: 100, + }); + expect(requests).toEqual(["WSOL", "SOL"]); + expect(timers.delays).toEqual([]); + } finally { + timers.restore(); + } + }); }); describe("GameManager ensureUnjoinFeePayerBalance", () => { From d698e2bc59e74c81240cc63a3f55b68e50b4e387 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 14:04:48 -0300 Subject: [PATCH 049/410] test(telegram): bound structured diagnostic scanning independently --- src/utils/outbound-error-guard.ts | 3 ++- tests/outbound-error-guard.test.ts | 5 +++++ 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/src/utils/outbound-error-guard.ts b/src/utils/outbound-error-guard.ts index 11129b19..cfd7e6a8 100644 --- a/src/utils/outbound-error-guard.ts +++ b/src/utils/outbound-error-guard.ts @@ -30,7 +30,8 @@ const looksLikeSerializedDiagnostic = (text: string): boolean => { if (!parsed || typeof parsed !== "object") return false; const inspect = (value: unknown, depth = 0): boolean => { - if (!value || typeof value !== "object" || depth > 5) return false; + if (depth > 5) return false; + if (!value || typeof value !== "object") return false; if (Array.isArray(value)) return value.some((entry) => inspect(entry, depth + 1)); const record = value as Record; diff --git a/tests/outbound-error-guard.test.ts b/tests/outbound-error-guard.test.ts index eccbf4f9..b0f608c4 100644 --- a/tests/outbound-error-guard.test.ts +++ b/tests/outbound-error-guard.test.ts @@ -26,6 +26,11 @@ describe("outbound Telegram error guard", () => { expect(guardOutboundText(text)).toBe(GENERIC_USER_ERROR_MESSAGE); }); + test("preserves structured user text that only contains short strings and primitive values", () => { + const text = '[{"room":["a",["b"],1,null,false]}]'; + expect(guardOutboundText(text)).toBe(text); + }); + test.each([ [5, true], [6, false], From 25d947b08e55238a964a89adb6f131b430f705fc Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 14:07:12 -0300 Subject: [PATCH 050/410] fix(faucet): reject unverified wallet balances before reserving payments --- src/handlers/faucet.ts | 12 ++++++++++-- tests/faucet-handler.test.ts | 36 ++++++++++++++++++++++++++++++++++++ 2 files changed, 46 insertions(+), 2 deletions(-) diff --git a/src/handlers/faucet.ts b/src/handlers/faucet.ts index 699a2c3e..e803bccb 100644 --- a/src/handlers/faucet.ts +++ b/src/handlers/faucet.ts @@ -187,6 +187,14 @@ export const createFaucetModule = (deps: FaucetModuleDeps) => { ((ctx: Context, text?: string, showAlert?: boolean) => text ? ctx.answerCallbackQuery({ text, show_alert: showAlert }) : ctx.answerCallbackQuery()); + const getVerifiedBalance = async (creatorId: bigint, amount: ParsedAmount): Promise => { + const balance = await deps.getBalance(creatorId, amount); + if (!Number.isInteger(balance) || balance < 0) { + throw new Error("Wallet returned an invalid raw balance"); + } + return balance; + }; + const renderWithApi = async ( api: Pick, faucetId: number, @@ -365,7 +373,7 @@ export const createFaucetModule = (deps: FaucetModuleDeps) => { } let balance: number; try { - balance = await deps.getBalance(creatorId, parsed); + balance = await getVerifiedBalance(creatorId, parsed); } catch { await replyEphemeralToSender(ctx, "❌ Could not verify your balance. Please try again."); return; @@ -472,7 +480,7 @@ export const createFaucetModule = (deps: FaucetModuleDeps) => { }; let balance: number; try { - balance = await deps.getBalance(BigInt(faucet.creator_id), parsedClaim); + balance = await getVerifiedBalance(BigInt(faucet.creator_id), parsedClaim); } catch (error) { const message = error instanceof Error ? error.message : String(error); deps.database.failClaim(faucetId, claimantId, message, now()); diff --git a/tests/faucet-handler.test.ts b/tests/faucet-handler.test.ts index 13f3a7f4..0655ab31 100644 --- a/tests/faucet-handler.test.ts +++ b/tests/faucet-handler.test.ts @@ -253,6 +253,21 @@ describe("faucet handler", () => { ]); }); + test.each([ + ["NaN", NaN], + ["infinite", Infinity], + ["negative", -1], + ["fractional", 1000.25], + ] as const)("does not create a faucet with %s raw balance data", async (_label, balance) => { + const harness = createHarness({ getBalance: async () => balance }); + await harness.module.handleCommand(harness.commandContext("/faucet 1 1")); + + expect(db.getFaucet(1)).toBeNull(); + expect(harness.replies).toEqual([ + { text: "❌ Could not verify your balance. Please try again.", options: ONLY_CREATOR }, + ]); + }); + test("rejects unsafe total multiplication", async () => { const harness = createHarness({ parse: () => ({ ...parsed, amount: Number.MAX_SAFE_INTEGER }), @@ -480,6 +495,27 @@ describe("faucet handler", () => { expect(harness.replies.at(-1)?.text).toContain("Could not verify the faucet balance"); }); + test.each([ + ["NaN", NaN], + ["infinite", Infinity], + ["negative", -1], + ["fractional", 1000.25], + ] as const)( + "releases a claim with %s raw balance data without making a transfer", + async (_label, invalidBalance) => { + let balance = 100; + const harness = createHarness({ getBalance: async () => balance }); + await harness.module.handleCommand(harness.commandContext("/faucet 1 1")); + balance = invalidBalance; + await harness.module.handleClaim(harness.callbackContext(20), 1); + + expect(harness.transferSenders).toEqual([]); + expect(db.getFaucet(1)?.status).toBe("active"); + expect(db.getClaim(1, 20n)?.status).toBe("failed"); + expect(harness.replies.at(-1)?.text).toContain("Could not verify the faucet balance"); + }, + ); + test("does not treat a bare custom program error as insufficient funds", async () => { const harness = createHarness({ transfer: async () => { From 9d796ba65d7ce7ad81db46f44c9a761dc80dc357 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 14:09:36 -0300 Subject: [PATCH 051/410] test(games): check callback registration and retired buttons --- tests/game-callbacks.module.test.ts | 43 ++++++++++++++++++++++++++++- 1 file changed, 42 insertions(+), 1 deletion(-) diff --git a/tests/game-callbacks.module.test.ts b/tests/game-callbacks.module.test.ts index a6cc2d51..f6dac9a1 100644 --- a/tests/game-callbacks.module.test.ts +++ b/tests/game-callbacks.module.test.ts @@ -688,9 +688,50 @@ describe("registered setup callbacks", () => { } return call; }; - return { ...h, dispatch, pendingGameCreations }; + const matchedArguments = (data: string) => + handlers.flatMap(({ trigger }) => { + if (typeof trigger === "string") return trigger === data ? [[]] : []; + const match = trigger.exec(data); + return match ? [match.slice(1)] : []; + }); + return { ...h, dispatch, matchedArguments, pendingGameCreations }; }; + test.each([ + ["amount_coinflip_123.45_777", ["coinflip", "123.45", "777"]], + ["players_giveaway_123.45_12_888", ["giveaway", "123.45", "12", "888"]], + ["ga|payload", []], + ["gp|payload", []], + ] as const)("registers exactly one route for %s with the expected arguments", (data, args) => { + expect(registered().matchedArguments(data)).toEqual([[...args]]); + }); + + test.each([ + "prefixed_amount_coinflip_12.34_777", + "amount_coinflip_12.x_777", + "amount_coinflip_12.34_777extra", + "prefixed_players_giveaway_12.34_12_777", + "players_giveaway_12.x_12_777", + "players_giveaway_12.34_12_777extra", + "prefixedga|payload", + "prefixedgp|payload", + "prefixed_confirm_game_retired", + ])("does not dispatch malformed or prefixed callback data %s", (data) => { + expect(registered().matchedArguments(data)).toEqual([]); + }); + + test.each(["game", "timeout", "visibility", "min_players"] as const)( + "acknowledges an old %s confirmation without restoring game setup", + async (kind) => { + const h = registered(); + const { answers } = await h.dispatch(`confirm_${kind}_old`); + expect(answers).toEqual([ + "This setup uses retired buttons. Start a new game with /coinflip or /giveaway.", + ]); + expect(h.pendingGameCreations.size).toBe(0); + }, + ); + test("a confirmation is refused while the same creator's game is being created", async () => { const h = registered(); h.pendingGameCreations.add("7_coinflip"); From 0f7b172d28f9f28f97289c590bac7021ab90a476 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 14:11:59 -0300 Subject: [PATCH 052/410] fix(db): delete expired games and linked rows atomically --- src/utils/game-database.ts | 49 ++++++++++++++++++----------------- tests/game-database.test.ts | 51 +++++++++++++++++++++++++++++++++++++ 2 files changed, 77 insertions(+), 23 deletions(-) diff --git a/src/utils/game-database.ts b/src/utils/game-database.ts index bb4f9892..eff367f7 100644 --- a/src/utils/game-database.ts +++ b/src/utils/game-database.ts @@ -599,21 +599,21 @@ export class GameDatabase extends BaseDatabase { } { const cutoffMs = Date.now() - daysOld * 24 * 60 * 60 * 1000; - // First delete participants for old games (due to FK constraint) - const participantsResult = this.run( - `DELETE FROM game_participants + const removeExpired = this.db.transaction(() => { + // Keep the game and its linked rows if any of the deletes fail. + const participantsResult = this.run( + `DELETE FROM game_participants WHERE game_address IN ( SELECT game_address FROM games WHERE created_at < ? )`, - [cutoffMs], - "deleting old game participants", - ); + [cutoffMs], + "deleting old game participants", + ); - // A challenge is saved before its game reaches the chain, so a failed - // creation leaves one without a game row: those go by their own age. - for (const table of ["game_challenges", "game_challenge_extra_players"]) { - this.run( - `DELETE FROM ${table} + // A failed creation can leave a challenge without a game row. + for (const table of ["game_challenges", "game_challenge_extra_players"]) { + this.run( + `DELETE FROM ${table} WHERE game_address IN ( SELECT game_address FROM games WHERE created_at < ? ) @@ -621,20 +621,23 @@ export class GameDatabase extends BaseDatabase { created_at < ? AND game_address NOT IN (SELECT game_address FROM games) )`, - [cutoffMs, cutoffMs], - "deleting old game challenges", - ); - } + [cutoffMs, cutoffMs], + "deleting old game challenges", + ); + } - // Then delete the games themselves - const gamesResult = this.run( - "DELETE FROM games WHERE created_at < ?", - [cutoffMs], - "deleting old games", - ); + const gamesResult = this.run( + "DELETE FROM games WHERE created_at < ?", + [cutoffMs], + "deleting old games", + ); + return { + participantsDeleted: participantsResult?.changes ?? 0, + gamesDeleted: gamesResult?.changes ?? 0, + }; + }); - const participantsDeleted = participantsResult?.changes ?? 0; - const gamesDeleted = gamesResult?.changes ?? 0; + const { gamesDeleted, participantsDeleted } = removeExpired(); if (gamesDeleted > 0 || participantsDeleted > 0) { console.log( diff --git a/tests/game-database.test.ts b/tests/game-database.test.ts index f7639a2c..45a96c85 100644 --- a/tests/game-database.test.ts +++ b/tests/game-database.test.ts @@ -1,4 +1,5 @@ import { expect, test, beforeEach, spyOn } from "bun:test"; +import type { Database } from "bun:sqlite"; import fc from "fast-check"; import { GameDatabase } from "../src/utils/game-database"; import { GAME_CREATION_RATE_LIMIT_WINDOW_MS } from "../src/utils/constants"; @@ -1268,6 +1269,56 @@ test("cleanupOldGames drops the challenges of the games it deletes only", () => expect(db.getGameChallenge("live_challenge")).toEqual([CID]); }); +test("cleanupOldGames keeps a game and its linked rows if deleting the game fails", () => { + const db = GameDatabase.getInstance(); + const raw = (db as unknown as { db: Database }).db; + const game = "old-protected-game"; + db.saveGame(game, "creator", 100, "coinflip"); + db.saveGameParticipant(game, "42", "player-wallet"); + db.saveGameChallenge(game, [RIVAL, BO]); + raw.prepare("UPDATE games SET created_at = ? WHERE game_address = ?").run(1_000, game); + raw.exec(`CREATE TEMP TRIGGER prevent_test_game_cleanup BEFORE DELETE ON games + WHEN OLD.game_address = 'old-protected-game' + BEGIN SELECT RAISE(ABORT, 'test game delete failed'); END`); + const error = spyOn(console, "error").mockImplementation(() => {}); + + try { + expect(() => db.cleanupOldGames()).toThrow("test game delete failed"); + expect(db.gameExists(game)).toBe(true); + expect(db.getGameParticipants(game)).toEqual(["42"]); + expect(db.getGameChallenge(game)).toEqual([RIVAL, BO]); + } finally { + error.mockRestore(); + raw.exec("DROP TRIGGER IF EXISTS prevent_test_game_cleanup"); + } +}); + +test("cleanupOldGames leaves games at the production thirty-day boundary", () => { + const db = GameDatabase.getInstance(); + const raw = (db as unknown as { db: Database }).db; + const now = 1_800_000_000_000; + const cutoff = now - 30 * 24 * 60 * 60 * 1_000; + const clock = spyOn(Date, "now").mockReturnValue(now); + + try { + db.saveGame("at-cutoff", "creator", 100, "coinflip"); + db.saveGame("before-cutoff", "creator", 100, "coinflip"); + db.saveGameParticipant("at-cutoff", "42", "boundary-wallet"); + db.saveGameParticipant("before-cutoff", "43", "old-wallet"); + raw.prepare("UPDATE games SET created_at = ? WHERE game_address = ?").run(cutoff, "at-cutoff"); + raw + .prepare("UPDATE games SET created_at = ? WHERE game_address = ?") + .run(cutoff - 1, "before-cutoff"); + + expect(db.cleanupOldGames()).toEqual({ gamesDeleted: 1, participantsDeleted: 1 }); + expect(db.gameExists("before-cutoff")).toBe(false); + expect(db.gameExists("at-cutoff")).toBe(true); + expect(db.getGameParticipants("at-cutoff")).toEqual(["42"]); + } finally { + clock.mockRestore(); + } +}); + test("cleanupOldGames drops old challenges whose game was never created", () => { const db = GameDatabase.getInstance(); const thirtyOneDaysAgo = Date.now() - 31 * 24 * 60 * 60 * 1000; From 2eab0929cb4defe61076942363b263cdc7c67c26 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 14:16:56 -0300 Subject: [PATCH 053/410] fix(wallet): refuse send confirmation for a missing token --- src/handlers/wallet-transactions.ts | 9 ++++----- tests/wallet-transactions.flows.test.ts | 14 ++++++++++++++ 2 files changed, 18 insertions(+), 5 deletions(-) diff --git a/src/handlers/wallet-transactions.ts b/src/handlers/wallet-transactions.ts index 8223cbf4..b9619c0d 100644 --- a/src/handlers/wallet-transactions.ts +++ b/src/handlers/wallet-transactions.ts @@ -511,11 +511,10 @@ export const createWalletTransactionsModule = ( const telegramId = requireTelegramId(ctx, "send confirmation"); const { tokenBalances } = await getCachedWalletData(telegramId); const selectedToken = findWalletToken(tokenBalances, token); - if (selectedToken) { - const safety = await wallet.getTokenTransferSafety(selectedToken.mint); - if (safety.blockedReason) throw new Error(safety.blockedReason); - transferWarnings = safety.warnings; - } + if (!selectedToken) throw new Error(`Token ${token} not found in wallet`); + const safety = await wallet.getTokenTransferSafety(selectedToken.mint); + if (safety.blockedReason) throw new Error(safety.blockedReason); + transferWarnings = safety.warnings; } const txId = generateTransactionId(); diff --git a/tests/wallet-transactions.flows.test.ts b/tests/wallet-transactions.flows.test.ts index 5de7a2fd..57e5d885 100644 --- a/tests/wallet-transactions.flows.test.ts +++ b/tests/wallet-transactions.flows.test.ts @@ -513,6 +513,20 @@ describe("input handlers guard their sessions", () => { reply: (text: string, options?: unknown) => bot.api.sendMessage(USER, text, options), }) as any; + test("cannot create a send confirmation after the selected token is gone", async () => { + const currentWallet = { solBalance: 5 * LAMPORTS, tokenBalances: [] }; + botModule.__test_setWalletCache(BigInt(USER), currentWallet); + + await expect( + botModule.__test_handleAddressInput( + ctxFor(USER), + { initiatorId: String(USER), token: "GONE", amount: "1" }, + recipient, + ), + ).rejects.toThrow("Token GONE not found in wallet"); + expect(lastText()).toBeUndefined(); + }); + test("reject input from someone other than the prompt's owner", async () => { await expect( botModule.__test_handleAddressInput( From 2e4c7a032e632bcd0d9b184621d2103fbebc8c46 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 14:16:56 -0300 Subject: [PATCH 054/410] test(games): bound participant retry fixtures and check name lookup limits --- tests/game.participants.test.ts | 43 ++++++++++++++++++++++++++++++++- 1 file changed, 42 insertions(+), 1 deletion(-) diff --git a/tests/game.participants.test.ts b/tests/game.participants.test.ts index e87a36b8..fefbd173 100644 --- a/tests/game.participants.test.ts +++ b/tests/game.participants.test.ts @@ -122,8 +122,13 @@ describe("GameManager verifyParticipantJoin retries", () => { test("waits with a growing delay between attempts and gives up with a warning", async () => { const player = await freshKey(); const saved: unknown[][] = []; + let reads = 0; const gm = makeManager( - { account: { game: { fetchNullable: async () => ({ participants: [] }) } } }, + { + account: { + game: { fetchNullable: async () => ({ participants: ++reads > 3 ? [player] : [] }) }, + }, + }, { getPlayerTelegramId: () => null, saveGameParticipant: (...args: unknown[]) => saved.push(args), @@ -133,6 +138,7 @@ describe("GameManager verifyParticipantJoin retries", () => { const verified = await gm.verifyParticipantJoin(GAME_PDA, player, "5", { maxAttempts: 3 }); expect(verified).toBe(false); + expect(reads).toBe(3); expect(timers.delays).toEqual([500, 1_000]); expect(saved).toEqual([]); expect(warnSpy).toHaveBeenCalledWith( @@ -171,6 +177,41 @@ describe("GameManager verifyParticipantJoin retries", () => { }); }); +describe("GameManager player name lookup", () => { + test.each([ + ["first lookup", 1, "@found", []], + ["fifth lookup", 5, "@found", [1, 1, 1, 1]], + ["exhausted lookup", 6, "BPFL…1111", [1, 1, 1, 1]], + ] as const)( + "handles the %s with at most five database reads", + async (_label, availableAt, name, delays) => { + GameManager.resetForTest(); + const timers = stubInstantTimers(); + const reads: string[] = []; + const usernames: string[] = []; + const gm = makeManager(undefined, { + getPlayerTelegramId(publicKey: string) { + reads.push(publicKey); + return reads.length >= availableAt ? "123" : null; + }, + }); + gm.getUsernameFromTelegramId = async (_context: unknown, id: string) => { + usernames.push(id); + return "@found"; + }; + try { + expect(await gm.getPlayerUsername({}, GAME_ADDRESS)).toBe(name); + expect(reads).toEqual(Array.from({ length: Math.min(availableAt, 5) }, () => GAME_ADDRESS)); + expect(usernames).toEqual(availableAt <= 5 ? ["123"] : []); + expect(timers.delays).toEqual([...delays]); + } finally { + timers.restore(); + GameManager.resetForTest(); + } + }, + ); +}); + describe("GameManager reconcilePendingParticipants", () => { let warnSpy: ReturnType; From d72f9b7300e0264a2990673cfc918a3ab099de4e Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 14:19:00 -0300 Subject: [PATCH 055/410] test(db): check audit fields and lease fencing for recovery --- tests/game-database.pending-creation.test.ts | 66 +++++++++++++++++--- 1 file changed, 58 insertions(+), 8 deletions(-) diff --git a/tests/game-database.pending-creation.test.ts b/tests/game-database.pending-creation.test.ts index 4364d38f..d9bcfc5e 100644 --- a/tests/game-database.pending-creation.test.ts +++ b/tests/game-database.pending-creation.test.ts @@ -393,15 +393,65 @@ describe("GameDatabase pending game creation lifecycle", () => { }); describe("resolvePendingGameCreation", () => { - test("keeps a confirmed record that has recovery evidence on the automatic path", () => { - db.savePendingGameCreation( - pendingInput({ state: "confirmed", transactionBlockhash: "FAKE_BLOCKHASH" }) as never, - ); + test.each([ + ["blockhash", { transactionBlockhash: "FAKE_BLOCKHASH" }], + ["signed transaction", { signedTransactionBase64: "ZmFrZS13aXJl" }], + ["last valid height zero", { lastValidBlockHeight: 0 }], + ["chain creation time zero", { onChainCreatedAt: 0 }], + ] as const)( + "keeps a confirmed record with %s on the automatic recovery path", + (_label, evidence) => { + db.savePendingGameCreation({ ...pendingInput(), state: "confirmed", ...evidence }); - expect(db.resolvePendingGameCreation("PENDING_1", "confirmed", "reason", "admin", NOW)).toBe( - false, - ); - expect(db.getPendingGameCreation("PENDING_1")?.state).toBe("confirmed"); + expect( + db.resolvePendingGameCreation("PENDING_1", "confirmed", "reason", "admin", NOW), + ).toBe(false); + expect(db.getPendingGameCreation("PENDING_1")?.state).toBe("confirmed"); + }, + ); + + test.each([ + ["blank reason", "PENDING_1", "unknown", " \t ", "operator"], + ["blank operator", "PENDING_1", "unknown", "checked", " \n "], + ["stale state", "PENDING_1", "confirmed", "checked", "operator"], + ["missing record", "MISSING", "unknown", "checked", "operator"], + ] as const)("leaves recovery untouched for a %s", (_label, game, state, reason, operator) => { + db.savePendingGameCreation({ ...pendingInput(), state: "unknown" }); + const original = db.getPendingGameCreation("PENDING_1"); + + expect(db.resolvePendingGameCreation(game, state, reason, operator, NOW)).toBe(false); + expect(db.getPendingGameCreation("PENDING_1")).toEqual(original); + }); + + test("allows an operator resolution only after the active lease ends", () => { + const game = "PENDING_1"; + db.savePendingGameCreation({ ...pendingInput(), state: "prepared" }); + const leaseEnds = NOW + 500; + expect(db.claimPendingGameCreationSubmission(game, "worker", leaseEnds, NOW)).toEqual({ + acquired: true, + }); + expect( + db.resolvePendingGameCreation(game, "submitted", "verified", "operator", leaseEnds - 1), + ).toBe(false); + expect(db.getPendingGameCreation(game)?.submission_lease_id).toBe("worker"); + + const reason = "verified ".repeat(100).trim(); + const operator = "agent ".repeat(50).trim(); + expect( + db.resolvePendingGameCreation(game, "submitted", ` ${reason} `, ` ${operator} `, leaseEnds), + ).toBe(true); + expect(db.getPendingGameCreation(game)).toMatchObject({ + state: "failed", + resolved_at: leaseEnds, + next_attempt_at: leaseEnds, + updated_at: leaseEnds, + resolution_reason: reason.slice(0, 500), + resolved_by: operator.slice(0, 200), + last_error: `operator resolution: ${reason}`.slice(0, 500), + submission_lease_id: null, + submission_lease_expires_at: null, + }); + expect(db.getPendingGameCreationForCreator("1001")).toBeNull(); }); test("resolves a legacy confirmed record that has no evidence", () => { From dc72107394c8b3807895f8684ceeb2418a86973e Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 14:19:00 -0300 Subject: [PATCH 056/410] test(faucet): check nested fund errors and permanent notification failures --- tests/faucet-handler.test.ts | 56 ++++++++++++++++++++++++++++++++++++ 1 file changed, 56 insertions(+) diff --git a/tests/faucet-handler.test.ts b/tests/faucet-handler.test.ts index 0655ab31..78157c72 100644 --- a/tests/faucet-handler.test.ts +++ b/tests/faucet-handler.test.ts @@ -478,6 +478,30 @@ describe("faucet handler", () => { expect(harness.replies.at(-1)?.text).toContain("faucet is empty"); }); + test.each([ + "INSUFFICIENT BALANCE", + "insufficient lamports", + "attempt to debit an account but found no record of a prior credit", + ])( + "finds %s in mixed program logs even if the RPC cause points back to the error", + async (reason) => { + const error = new Error("Transaction simulation failed"); + const nested = { cause: error, logs: ["Program started", `Program log: ${reason}`] }; + Object.assign(error, { cause: nested }); + const harness = createHarness({ + transfer: async () => { + throw error; + }, + }); + await harness.module.handleCommand(harness.commandContext("/faucet 1 1")); + await harness.module.handleClaim(harness.callbackContext(20), 1); + + expect(db.getFaucet(1)?.status).toBe("empty"); + expect(db.getClaim(1, 20n)?.status).toBe("failed"); + expect(harness.replies.at(-1)?.text).toContain("faucet is empty"); + }, + ); + test("keeps the faucet active when balance verification is unavailable", async () => { let balanceAvailable = true; const harness = createHarness({ @@ -658,6 +682,38 @@ describe("faucet handler", () => { expect(harness.edits.at(-1)?.text).toContain("Completed"); }); + test.each([400, 403])( + "does not retry a completed claim when Telegram rejects the notification with code %i", + async (code) => { + let currentTime = 1_000; + let attempts = 0; + const warning = spyOn(console, "warn").mockImplementation(() => {}); + const harness = createHarness({ + now: () => currentTime, + notify: async () => { + attempts++; + throw { error_code: code, description: "Recipient unavailable" }; + }, + }); + try { + await harness.module.handleCommand(harness.commandContext("/faucet 1 1")); + await harness.module.handleClaim(harness.callbackContext(20), 1); + currentTime += 60_000; + await harness.module.reconcile(); + + expect(attempts).toBe(1); + expect(harness.transferSenders).toEqual([10n]); + expect(db.getClaim(1, 20n)).toMatchObject({ + status: "paid", + notification_status: "failed", + notification_next_attempt_at: null, + }); + } finally { + warning.mockRestore(); + } + }, + ); + test("retries transient private notification failures without paying twice", async () => { let currentTime = 1_000; let notificationAttempts = 0; From 4e847e452f5215a80bac53b562262f6c82af180f Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 14:23:36 -0300 Subject: [PATCH 057/410] fix(transactions): keep reported replacement signatures during recovery --- src/utils/transaction-runner.ts | 9 ++++----- tests/transaction-runner.test.ts | 34 ++++++++++++++++++++++++++++++++ 2 files changed, 38 insertions(+), 5 deletions(-) diff --git a/src/utils/transaction-runner.ts b/src/utils/transaction-runner.ts index b8938960..a4c6f236 100644 --- a/src/utils/transaction-runner.ts +++ b/src/utils/transaction-runner.ts @@ -13,14 +13,13 @@ export const getConfirmationRetryDelays = (): number[] => { }; type ErrorWithCause = Error & { cause?: unknown }; -type ErrorWithLastSignature = Error & { lastSignature?: string }; type TimeoutErrorWithRecovery = ErrorWithCause & { recoveryErrors?: Error[] }; -const hasLastSignature = (error: unknown): error is ErrorWithLastSignature => +const hasLastSignature = (error: unknown): error is { lastSignature: string } => typeof error === "object" && error !== null && "lastSignature" in error && - typeof (error as { lastSignature?: unknown }).lastSignature === "string"; + typeof error.lastSignature === "string"; export type TransactionProbe = { label: string; @@ -164,8 +163,8 @@ export const confirmTransactionWithRecovery = async ( } catch (resubmitError) { const normalizedError = resubmitError instanceof Error ? resubmitError : new Error(String(resubmitError)); - const latestSignature = hasLastSignature(normalizedError) - ? normalizedError.lastSignature + const latestSignature = hasLastSignature(resubmitError) + ? resubmitError.lastSignature : undefined; if (latestSignature) { currentSignature = latestSignature; diff --git a/tests/transaction-runner.test.ts b/tests/transaction-runner.test.ts index a635ef27..e08890fc 100644 --- a/tests/transaction-runner.test.ts +++ b/tests/transaction-runner.test.ts @@ -223,6 +223,40 @@ describe("confirmTransactionWithRecovery", () => { ]); }); + test.each([ + [ + "structured signature", + { lastSignature: "replacement", message: "retry failed" }, + "replacement", + ], + ["missing signature", { message: "retry failed" }, "initial"], + ["numeric signature", { lastSignature: 42, message: "retry failed" }, "initial"], + ["empty signature", { lastSignature: "", message: "retry failed" }, "initial"], + ["plain retry error", "retry failed", "initial"], + ] as const)("checks the correct signature after a %s", async (_label, error, expected) => { + const { wallet, statusCalls } = makeWallet({ + confirm: async () => { + throw timeout(); + }, + statuses: (signature) => + signature === expected ? { confirmationStatus: "confirmed" } : null, + }); + const resubmit = mock(async () => { + throw error; + }); + + expect( + await confirmTransactionWithRecovery({ + wallet, + initialSignature: "initial", + operationLabel: "wallet payment", + resubmit, + retryDelays: [0], + }), + ).toBe(expected); + expect(statusCalls).toEqual([expected]); + }); + test("an expired blockhash also triggers resubmission", async () => { const { wallet } = makeWallet({ confirm: async (signature) => { From 1cd731a33c334323d05141aa74deadd0b441194d Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 14:23:36 -0300 Subject: [PATCH 058/410] fix(finance): reject future-dated sweep prices --- src/services/fee-sweeper.ts | 12 +++++----- tests/fee-sweeper.paths.test.ts | 39 +++++++++++++++++++++++++++++++++ 2 files changed, 45 insertions(+), 6 deletions(-) diff --git a/src/services/fee-sweeper.ts b/src/services/fee-sweeper.ts index 2ef5a7ef..31c68093 100644 --- a/src/services/fee-sweeper.ts +++ b/src/services/fee-sweeper.ts @@ -155,12 +155,12 @@ const validateSolPriceData = ( } const { maxAgeMs, previousPrice, maxDriftRatio } = options; - if (maxAgeMs) { - const now = Date.now(); - const normalizedTimestamp = normalizeTimestampMs(timestamp); - if (now - normalizedTimestamp > maxAgeMs) { - return { isValid: false, reason: "stale timestamp" }; - } + const ageMs = Date.now() - normalizeTimestampMs(timestamp); + if (ageMs < 0) { + return { isValid: false, reason: "future timestamp" }; + } + if (maxAgeMs && ageMs > maxAgeMs) { + return { isValid: false, reason: "stale timestamp" }; } if ( diff --git a/tests/fee-sweeper.paths.test.ts b/tests/fee-sweeper.paths.test.ts index 3f53076f..7972b141 100644 --- a/tests/fee-sweeper.paths.test.ts +++ b/tests/fee-sweeper.paths.test.ts @@ -154,6 +154,30 @@ describe("SOL price validation before swaps", () => { expect(await run({ price: 100, timestamp: Math.floor(Date.now() / 1000) })).toBe(1); }); + test("allows the one-minute expiry boundary and refuses prices before or after the valid window", async () => { + const now = 1_800_000_000_000; + const clock = spyOn(Date, "now").mockReturnValue(now); + try { + expect(await run({ price: 100, resolvedAt: now - 60_000 })).toBe(1); + expect(await run({ price: 100, resolvedAt: now - 60_001 })).toBe(0); + expect(logged(warnSpy, "stale timestamp")).toBe(true); + expect(await run({ price: 100, resolvedAt: now })).toBe(1); + expect(await run({ price: 100, resolvedAt: now + 1 })).toBe(0); + expect(logged(warnSpy, "future timestamp")).toBe(true); + } finally { + clock.mockRestore(); + } + }); + + test("reads one trillion as milliseconds, not seconds", async () => { + const clock = spyOn(Date, "now").mockReturnValue(1_000_000_000_000 + 60_000); + try { + expect(await run({ price: 100, timestamp: 1_000_000_000_000 })).toBe(1); + } finally { + clock.mockRestore(); + } + }); + test.each([NaN, Infinity])("rejects a non-finite SOL price timestamp %p", async (timestamp) => { expect(await run({ price: 100, resolvedAt: timestamp, timestamp })).toBe(0); expect(logged(warnSpy, "missing timestamp")).toBe(true); @@ -179,6 +203,21 @@ describe("SOL price validation before swaps", () => { } }); + test.each([ + [80, 1], + [120, 1], + [79, 0], + [121, 0], + ] as const)( + "checks the production twenty-percent drift boundary for price %i", + async (newPrice, swaps) => { + const { rememberPriceLookup } = await import("../src/utils/price-service"); + rememberPriceLookup({ price: 100, identifier: WSOL_MINT }, { tokenMint: WSOL_MINT }); + + expect(await run({ price: newPrice, resolvedAt: Date.now() })).toBe(swaps); + }, + ); + test("skips swaps when the price jumped too far from the cached one", async () => { const { rememberPriceLookup, __test_clearPriceServiceCache } = await import("../src/utils/price-service"); From 5dcc9d776aedeea11c24d238ebc280f37197bfeb Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 14:27:11 -0300 Subject: [PATCH 059/410] test(finance): verify Jupiter fee events and exact audit timestamps --- tests/finance-ledger.events.test.ts | 115 ++++++++++++++++++++++++++++ 1 file changed, 115 insertions(+) diff --git a/tests/finance-ledger.events.test.ts b/tests/finance-ledger.events.test.ts index 165bf53f..7f3e69de 100644 --- a/tests/finance-ledger.events.test.ts +++ b/tests/finance-ledger.events.test.ts @@ -302,6 +302,121 @@ describe("program finance events", () => { }); }); +describe("Jupiter finance events", () => { + const address = REFERRAL_TOKEN.toBase58(); + const source: Source = { + ...programSource, + sourceKey: `jupiter:${address}`, + sourceType: "jupiter", + address, + }; + const balance = (amount: string) => ({ + accountIndex: 1, + mint: MINT.toBase58(), + uiTokenAmount: { amount }, + }); + + test.each([ + [ + "earnings use the transaction timestamp", + "100", + "125", + PAYER, + 200, + 150, + "earned", + "25", + null, + 200_000, + ], + [ + "a claim uses the signature timestamp and fee of the configured payer", + "125", + "100", + PAYER, + null, + 150, + "claimed", + "25", + "5", + 150_000, + ], + [ + "a claim can use the clock but not another payer's fee", + "25", + "0", + PLAYER, + null, + null, + "claimed", + "25", + null, + 999_000, + ], + ] as const)( + "records %s", + async ( + _label, + pre, + post, + payer, + blockTime, + signatureTime, + kind, + amountRaw, + networkFeeLamports, + timestamp, + ) => { + const history = createHistory(source); + const transaction = { + blockTime, + transaction: { message: { staticAccountKeys: [payer] } }, + meta: { + err: null, + fee: 5, + loadedAddresses: { writable: [REFERRAL_TOKEN], readonly: [] }, + preTokenBalances: [balance(pre)], + postTokenBalances: [balance(post)], + }, + }; + await serviceFor(history, singleTransaction(transaction, signatureTime), { + payer: PAYER, + }).backfillNextBatch(0); + + expect(history.events).toEqual([ + { + eventId: `jupiter:sig-1:${address}:${kind}`, + source: "jupiter", + category: "swap_fee", + kind, + signature: "sig-1", + account: address, + mint: MINT.toBase58(), + amountRaw, + networkFeeLamports, + timestamp, + slot: 7, + }, + ]); + }, + ); + + test("advances the cursor without recording a fee when the balance did not change", async () => { + const history = createHistory(source); + const transaction = { + transaction: { message: { staticAccountKeys: [PAYER, REFERRAL_TOKEN] } }, + meta: { err: null, preTokenBalances: [balance("20")], postTokenBalances: [balance("20")] }, + }; + await serviceFor(history, singleTransaction(transaction)).backfillNextBatch(0); + + expect(history.events).toEqual([]); + expect(history.advances).toEqual([ + [source.sourceKey, "sig-1", false, 1], + [source.sourceKey, "sig-1", true, 0], + ]); + }); +}); + describe("backfill source handling", () => { test("reports completion when every source is done", async () => { const history = createHistory(null, { total: 3, completed: 3 }); From 7784050b924922436374b1bb7da5a923f75147d2 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 14:27:11 -0300 Subject: [PATCH 060/410] refactor(tokens): simplify default override presence checks --- src/utils/token-registry.ts | 4 ++-- tests/token-registry.test.ts | 19 +++++++++++++++++++ 2 files changed, 21 insertions(+), 2 deletions(-) diff --git a/src/utils/token-registry.ts b/src/utils/token-registry.ts index fa5dc852..370eab4d 100644 --- a/src/utils/token-registry.ts +++ b/src/utils/token-registry.ts @@ -120,10 +120,10 @@ export function resolveDefaultToken(options?: { const mintOverride = options?.mint ?? process.env["DEFAULT_TOKEN_MINT"]?.trim(); const tickerOverride = options?.ticker ?? process.env["DEFAULT_TOKEN_TICKER"]?.trim(); - if (mintOverride && mintOverride.length > 0) { + if (mintOverride) { return { mint: mintOverride, - ticker: tickerOverride && tickerOverride.length > 0 ? tickerOverride : "TOKEN", + ticker: tickerOverride || "TOKEN", }; } diff --git a/tests/token-registry.test.ts b/tests/token-registry.test.ts index 893be7ef..66b16b96 100644 --- a/tests/token-registry.test.ts +++ b/tests/token-registry.test.ts @@ -81,6 +81,25 @@ describe("token-registry", () => { expect(networkSpy).not.toHaveBeenCalled(); }); + test("distinguishes an empty explicit override from an absent environment value", () => { + delete process.env.DEFAULT_TOKEN_TICKER; + expect(resolveDefaultToken({ mint: "FixtureMint" })).toEqual({ + mint: "FixtureMint", + ticker: "TOKEN", + }); + + process.env.DEFAULT_TOKEN_MINT = "EnvironmentMint"; + process.env.DEFAULT_TOKEN_TICKER = "ENV"; + expect(resolveDefaultToken({ mint: "FixtureMint", ticker: "" })).toEqual({ + mint: "FixtureMint", + ticker: "TOKEN", + }); + expect(resolveDefaultToken({ mint: "", network: "mainnet" })).toEqual({ + mint: "F3A1baCgv4TF79TSjdMTvpMDtNv8DJvHZwNc9DG8pump", + ticker: "TIMBA", + }); + }); + test("buildTokenList dedupes default token and respects includeDefault", () => { networkSpy = spyOn(NetworkDetector, "getCurrentNetwork").mockReturnValue("mainnet"); From 1f7b4d114667a975d4a8f6b0700f8bd42caa180d Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 14:33:21 -0300 Subject: [PATCH 061/410] fix(swaps): reject invalid confirmed Jupiter referral fees --- src/utils/jupiter.ts | 9 ++------- tests/jupiter.utils.test.ts | 9 +++++++++ tests/swap-manager.execute-jupiter-edge-cases.test.ts | 11 +++++++++++ 3 files changed, 22 insertions(+), 7 deletions(-) diff --git a/src/utils/jupiter.ts b/src/utils/jupiter.ts index be1e83c5..a3012425 100644 --- a/src/utils/jupiter.ts +++ b/src/utils/jupiter.ts @@ -231,13 +231,8 @@ const extractJupiterErrorMessage = (errorText: string): string => { export const resolveAppliedFeeBps = ( data: Pick, ): number | null => { - if (typeof data.platformFee?.feeBps === "number" && Number.isFinite(data.platformFee.feeBps)) { - return data.platformFee.feeBps; - } - if (typeof data.feeBps === "number" && Number.isFinite(data.feeBps)) { - return data.feeBps; - } - return null; + const feeBps = data.platformFee?.feeBps ?? data.feeBps; + return typeof feeBps === "number" && Number.isSafeInteger(feeBps) && feeBps >= 0 ? feeBps : null; }; export interface JupiterExecuteResponse { diff --git a/tests/jupiter.utils.test.ts b/tests/jupiter.utils.test.ts index aece5945..c10d9ee0 100644 --- a/tests/jupiter.utils.test.ts +++ b/tests/jupiter.utils.test.ts @@ -400,6 +400,15 @@ describe("resolveAppliedFeeBps", () => { expect(resolveAppliedFeeBps({})).toBe(null); }); + test.each([12.5, -1, NaN, Infinity, Number.MAX_SAFE_INTEGER + 1])( + "does not use an invalid fee rate or substitute a total fee when a platform rate was supplied (%p)", + (feeBps) => { + expect(resolveAppliedFeeBps({ feeBps })).toBeNull(); + expect(resolveAppliedFeeBps({ platformFee: { feeBps, amount: "1" } })).toBeNull(); + expect(resolveAppliedFeeBps({ feeBps: 90, platformFee: { feeBps, amount: "1" } })).toBeNull(); + }, + ); + test("does not mistake gasless recoup in total feeBps for the referral fee", async () => { const request = { inputMint: "So11111111111111111111111111111111111111112", diff --git a/tests/swap-manager.execute-jupiter-edge-cases.test.ts b/tests/swap-manager.execute-jupiter-edge-cases.test.ts index 40f88eef..e35d6f79 100644 --- a/tests/swap-manager.execute-jupiter-edge-cases.test.ts +++ b/tests/swap-manager.execute-jupiter-edge-cases.test.ts @@ -151,6 +151,17 @@ describe("SwapManager.executeJupiterSwap admin payer flow", () => { expect(s.integrator).toHaveProperty("adminRouteLamports", 5000); }); + test("does not execute a sponsored swap on an unconfirmed fractional fee", async () => { + const s = await setup({ + orderOverrides: { platformFee: { amount: "1000", feeBps: 120.5, feeMint: SOL } }, + }); + + await expect(run(s)).rejects.toThrow( + "The sponsored route changed. Request a new quote before confirming.", + ); + expect(s.executeCalls).toHaveLength(0); + }); + test("logs a rent-shortage execution failure with the route context", async () => { const s = await setup({ orderOverrides: { rentFeeLamports: 2_000, prioritizationFeeLamports: 300 }, From a03e2192d13bf164e55f76c330202738d3a7ed64 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 14:33:36 -0300 Subject: [PATCH 062/410] test(ci): remove unrelated key generation from two fixtures --- tests/swap-manager.execute-jupiter.test.ts | 12 ++++++++---- tests/wallet.test.ts | 20 ++++++++++++++++---- 2 files changed, 24 insertions(+), 8 deletions(-) diff --git a/tests/swap-manager.execute-jupiter.test.ts b/tests/swap-manager.execute-jupiter.test.ts index 024ad277..72d5787e 100644 --- a/tests/swap-manager.execute-jupiter.test.ts +++ b/tests/swap-manager.execute-jupiter.test.ts @@ -51,9 +51,13 @@ describe("SwapManager.executeJupiterSwap", () => { { connection, timeNow: () => Date.now() }, ); const sm = new SwapManager(connection, wallet); - const user = await Keypair.generate(); - const admin = await Keypair.generate(); - const inputMint = (await Keypair.generate()).publicKey.toBase58(); + const user = { + publicKey: new PublicKey("11111111111111111111111111111112"), + } as unknown as Keypair; + const admin = { + publicKey: new PublicKey("11111111111111111111111111111113"), + } as unknown as Keypair; + const inputMint = "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"; const fallbackQuote = { inputMint, outputMint: "So11111111111111111111111111111111111111112", @@ -88,7 +92,7 @@ describe("SwapManager.executeJupiterSwap", () => { inputTicker: "TIMBA", outputTicker: "SOL", integrator: { - referralAccount: (await Keypair.generate()).publicKey.toBase58(), + referralAccount: "11111111111111111111111111111114", referralFee: 100, payer: admin.publicKey.toBase58(), closeAuthority: admin.publicKey.toBase58(), diff --git a/tests/wallet.test.ts b/tests/wallet.test.ts index 339db5c0..b0912038 100644 --- a/tests/wallet.test.ts +++ b/tests/wallet.test.ts @@ -1,4 +1,6 @@ -import { expect, test, vi } from "bun:test"; +import { expect, spyOn, test, vi } from "bun:test"; +import * as bip39 from "bip39"; +import { Keypair, PublicKey } from "#solana"; import { mkdtempSync, rmSync, writeFileSync } from "fs"; import { join } from "path"; import { tmpdir } from "os"; @@ -11,9 +13,19 @@ process.env.SOLANA_NETWORK = "https://api.devnet.solana.com"; test("getKeyPair returns same instance for same index", async () => { WalletManager.resetForTest(); const manager = WalletManager.getInstance(mnemonic); - const kp1 = await manager.getKeyPair(1n); - const kp2 = await manager.getKeyPair(1n); - expect(kp1).toBe(kp2); + const seed = Buffer.alloc(64, 1); + const fixture = { publicKey: PublicKey.default } as unknown as Keypair; + const deriveSeed = spyOn(bip39, "mnemonicToSeed").mockResolvedValue(seed); + const fromSeed = spyOn(Keypair, "fromSeed").mockResolvedValue(fixture); + try { + expect(await manager.getKeyPair(1n)).toBe(fixture); + expect(await manager.getKeyPair(1n)).toBe(fixture); + expect(deriveSeed.mock.calls).toEqual([[mnemonic, "1"]]); + expect(fromSeed.mock.calls).toEqual([[seed.subarray(0, 32)]]); + } finally { + deriveSeed.mockRestore(); + fromSeed.mockRestore(); + } }); test("getKeyPair derives different keys for different index", async () => { From e2c8f99e6ad89c68ead1bfa454f6fa6dc9536932 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 14:36:06 -0300 Subject: [PATCH 063/410] fix(wallet): bound quick keyboard layout and row cleanup --- src/utils/wallet-ui.ts | 21 +++++++++------------ tests/wallet-ui.test.ts | 19 +++++++++++++++++++ 2 files changed, 28 insertions(+), 12 deletions(-) diff --git a/src/utils/wallet-ui.ts b/src/utils/wallet-ui.ts index 27d47ee5..96bfc813 100644 --- a/src/utils/wallet-ui.ts +++ b/src/utils/wallet-ui.ts @@ -628,18 +628,16 @@ export const buildQuickAmountRows = ( buttons: QuickAmountKeyboardButton[], columns = 2, ): QuickAmountKeyboardButton[][] => { - if (!Number.isFinite(columns) || columns <= 0) { - return []; - } - + if (!Number.isFinite(columns)) return []; const normalizedColumns = Math.trunc(columns); + if (normalizedColumns < 1) return []; + const rows: QuickAmountKeyboardButton[][] = []; - for (let i = 0; i < buttons.length; i += normalizedColumns) { - const row = buttons.slice(i, i + normalizedColumns); - if (row.length > 0) { - rows.push(row); - } + for (const offset of buttons.keys()) { + if (offset % normalizedColumns !== 0) continue; + const row = buttons.slice(offset, offset + normalizedColumns); + if (row.length > 0) rows.push(row); } return rows; @@ -836,9 +834,8 @@ const buildWrapKeyboard = ( const trimTrailingEmptyRows = (keyboard: InlineKeyboard): InlineKeyboard => { const rows = keyboard.inline_keyboard; - while (rows.length > 0 && (rows[rows.length - 1]?.length ?? 0) === 0) { - rows.pop(); - } + const lastButtonRow = rows.findLastIndex((row) => (row?.length ?? 0) !== 0); + rows.splice(lastButtonRow + 1); return keyboard; }; diff --git a/tests/wallet-ui.test.ts b/tests/wallet-ui.test.ts index b8dbda92..4cdfe189 100644 --- a/tests/wallet-ui.test.ts +++ b/tests/wallet-ui.test.ts @@ -751,12 +751,19 @@ test("buildQuickAmountRows rejects invalid column counts and truncates fractiona expect(buildQuickAmountRows(buttons, 0)).toEqual([]); expect(buildQuickAmountRows(buttons, -1)).toEqual([]); expect(buildQuickAmountRows(buttons, Number.NaN)).toEqual([]); + expect(buildQuickAmountRows(buttons, Infinity)).toEqual([]); + expect(buildQuickAmountRows(buttons, "2" as unknown as number)).toEqual([]); + expect(buildQuickAmountRows(buttons, 1)).toEqual(buttons.map((button) => [button])); expect(buildQuickAmountRows(buttons, 2.9).map((row) => row.map((b) => b.label))).toEqual([ ["A", "B"], ["C"], ]); }); +test("buildQuickAmountRows refuses a width below one instead of looping", () => { + expect(buildQuickAmountRows([{ label: "A", callback: "a" }], 0.5)).toEqual([]); +}); + test("buildQuickAmountKeyboard places non-empty extra rows before the percentages", () => { const keyboard = buildQuickAmountKeyboard({ baseCallback: (value) => `buy_${value}`, @@ -846,6 +853,18 @@ describe("buildWalletActionMenu token selection", () => { ]); }); + test("returns no keyboard rows when every token action is filtered out", () => { + const menu = buildWalletActionMenu({ + title: "Pick", + walletAddress: "wallet", + bodyLines: [], + balances, + formatters, + quickActions: { type: "token-select", actionPrefix: "pick_", limit: 0 }, + }); + expect(menu.keyboard.inline_keyboard).toEqual([]); + }); + test("requires a wallet address and rejects unknown quick action types", () => { const base = { title: "Pick", bodyLines: [], balances, formatters }; expect(() => From 34f455dafffb1d2d0a35621be5c504815cb09f5e Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 14:39:19 -0300 Subject: [PATCH 064/410] fix(wallet): keep signed transaction context on provider errors --- src/utils/wallet.ts | 7 +++- tests/wallet.resubmit.test.ts | 69 ++++++++++++++++++++++++++++++++--- 2 files changed, 69 insertions(+), 7 deletions(-) diff --git a/src/utils/wallet.ts b/src/utils/wallet.ts index 9e23a564..10de961e 100644 --- a/src/utils/wallet.ts +++ b/src/utils/wallet.ts @@ -3049,8 +3049,11 @@ export class WalletManager { normalizedMessage.includes("last valid block height"); if (!isRecoverable || resubmitAttempts >= maxResubmits) { - (error as any).lastSignature = currentSignature; - throw error; + const failure = + error instanceof Error + ? error + : new Error(error?.message ?? String(error), { cause: error }); + throw Object.assign(failure, { lastSignature: currentSignature }); } resubmitAttempts += 1; diff --git a/tests/wallet.resubmit.test.ts b/tests/wallet.resubmit.test.ts index d1db1f78..8416f95e 100644 --- a/tests/wallet.resubmit.test.ts +++ b/tests/wallet.resubmit.test.ts @@ -1,5 +1,5 @@ -import { afterEach, beforeEach, describe, expect, test } from "bun:test"; -import { Connection, Keypair, TransactionInstruction } from "#solana"; +import { afterEach, beforeEach, describe, expect, spyOn, test } from "bun:test"; +import { Connection, Keypair, PublicKey, TransactionInstruction } from "#solana"; import { WalletManager } from "../src/utils/wallet"; import { stubInstantTimers } from "./helpers/timers"; @@ -80,8 +80,10 @@ describe("WalletManager sendAndConfirmWithResubmits", () => { timeNow: () => Date.now(), }); + const confirmed: string[] = []; (wallet as any).confirmTransaction = async (signature: string) => { - throw new Error(`Transaction ${signature} timed out`); + confirmed.push(signature); + if (confirmed.length <= 2) throw new Error(`Transaction ${signature} timed out`); }; const ix = new TransactionInstruction({ @@ -95,7 +97,64 @@ describe("WalletManager sendAndConfirmWithResubmits", () => { operationLabel: "Failing transaction", maxResubmits: 1, }), - ).rejects.toThrow(/timed out/); - expect(connection.sendCalls).toBeGreaterThanOrEqual(2); + ).rejects.toMatchObject({ message: "Transaction SIG2 timed out", lastSignature: "SIG2" }); + expect(confirmed).toEqual(["SIG1", "SIG2"]); + expect(connection.sendCalls).toBe(2); + }); + + test("keeps the original error and signature when resubmission is disabled", async () => { + const connection = new ResubmitConnection(); + const wallet = WalletManager.createForTest(MNEMONIC, { + connection: connection as unknown as Connection, + }); + const err = new Error("initial transaction timed out"); + const confirm = spyOn(wallet, "confirmTransaction") + .mockResolvedValue(undefined) + .mockRejectedValueOnce(err); + const send = spyOn(wallet, "sendTransaction").mockResolvedValue("UNEXPECTED"); + const ix = new TransactionInstruction({ + programId: PublicKey.default, + keys: [], + data: Buffer.alloc(0), + }); + const signer = { publicKey: PublicKey.default } as unknown as Keypair; + try { + await expect( + wallet.sendAndConfirmWithResubmits([ix], [signer], { + initialSignature: "initial", + maxResubmits: 0, + }), + ).rejects.toBe(err); + expect(err).toMatchObject({ lastSignature: "initial" }); + expect(confirm.mock.calls).toEqual([["initial"]]); + expect(send).not.toHaveBeenCalled(); + } finally { + confirm.mockRestore(); + send.mockRestore(); + } + }); + + test("reports a plain provider error instead of throwing while attaching the signed transaction", async () => { + const wallet = WalletManager.createForTest(MNEMONIC, { + connection: new ResubmitConnection() as unknown as Connection, + }); + const confirm = spyOn(wallet, "confirmTransaction") + .mockResolvedValue(undefined) + .mockRejectedValueOnce("provider unavailable"); + const ix = new TransactionInstruction({ + programId: PublicKey.default, + keys: [], + data: Buffer.alloc(0), + }); + const signer = { publicKey: PublicKey.default } as unknown as Keypair; + try { + await expect( + wallet.sendAndConfirmWithResubmits([ix], [signer], { + initialSignature: "initial", + }), + ).rejects.toMatchObject({ message: "provider unavailable", lastSignature: "initial" }); + } finally { + confirm.mockRestore(); + } }); }); From 913bbf30458dbba3f4226103d48b1d6641cf4b9c Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 14:45:25 -0300 Subject: [PATCH 065/410] fix(alerts): honor long pool cooldowns without timer overflow --- src/services/buy-alerts/pool-trades.ts | 16 ++++--- tests/buy-alerts.pool-trades.test.ts | 59 ++++++++++++++++++++++++++ 2 files changed, 70 insertions(+), 5 deletions(-) diff --git a/src/services/buy-alerts/pool-trades.ts b/src/services/buy-alerts/pool-trades.ts index 8edba583..6a2847ec 100644 --- a/src/services/buy-alerts/pool-trades.ts +++ b/src/services/buy-alerts/pool-trades.ts @@ -12,6 +12,7 @@ const GECKO_MIN_REQUEST_INTERVAL_MS = 10_000; const GECKO_DEFAULT_RATE_LIMIT_COOLDOWN_MS = 60_000; const GECKO_MAX_RATE_LIMIT_COOLDOWN_MS = 15 * 60_000; const GECKO_RATE_LIMIT_LOG_INTERVAL_MS = 60_000; +const MAX_TIMER_DELAY_MS = 2 ** 31 - 1; export const POOL_TRADE_POLL_MS = GECKO_MIN_REQUEST_INTERVAL_MS; export const MAX_SEEN_SIGNATURES_PER_MINT = 400; @@ -31,7 +32,8 @@ export function parseRetryAfterMs(value: string | null, nowMs = Date.now()): num const seconds = Number(normalized); if (Number.isFinite(seconds)) { - return seconds < 0 ? null : Math.round(seconds * 1_000); + const delayMs = Math.round(seconds * 1_000); + return seconds >= 0 && Number.isSafeInteger(delayMs) ? delayMs : null; } const retryAt = Date.parse(normalized); @@ -264,13 +266,17 @@ export function createPoolTradePoller(options: PoolTradePollerOptions = {}): Poo }; const waitForTradeSlot = async () => { - if (minRequestIntervalMs <= 0) return; + if (minRequestIntervalMs <= 0) return true; const current = now(); const scheduled = Math.max(current, nextTradeFetchAt); + const delayMs = scheduled - current; + // Longer timers can fire almost immediately. Keep the deadline and retry on a later cycle. + if (delayMs > MAX_TIMER_DELAY_MS) return false; nextTradeFetchAt = scheduled + minRequestIntervalMs; - if (scheduled > current) { - await wait(scheduled - current); + if (delayMs > 0) { + await wait(delayMs); } + return true; }; const deferAfterTradeFailure = (error: unknown) => { @@ -301,7 +307,7 @@ export function createPoolTradePoller(options: PoolTradePollerOptions = {}): Poo let payload: unknown; try { - await waitForTradeSlot(); + if (!(await waitForTradeSlot())) return false; if (!stillWatching(mint, watch)) { return false; } diff --git a/tests/buy-alerts.pool-trades.test.ts b/tests/buy-alerts.pool-trades.test.ts index 381eb9bb..056ecba2 100644 --- a/tests/buy-alerts.pool-trades.test.ts +++ b/tests/buy-alerts.pool-trades.test.ts @@ -52,6 +52,7 @@ test("parseRetryAfterMs accepts seconds and HTTP dates", () => { expect(parseRetryAfterMs(" 0.125 ", now)).toBe(125); expect(parseRetryAfterMs("0", now)).toBe(0); expect(parseRetryAfterMs("-1", now)).toBeNull(); + expect(parseRetryAfterMs("1e308", now)).toBeNull(); expect(parseRetryAfterMs("Thu, 03 Sep 2026 19:59:59 GMT", now)).toBe(0); expect(parseRetryAfterMs("Thu, 03 Sep 2026 20:00:45 GMT", now)).toBe(45_000); expect(parseRetryAfterMs("invalid", now)).toBeNull(); @@ -216,6 +217,64 @@ test("rememberSignature evicts the oldest hashes once the per-mint cap is hit", expect(rememberSignature(known, "b", 2)).toBe(false); }); +test("rememberSignature keeps the most recent 400 hashes at its default limit", () => { + const known = new Set(); + for (let index = 0; index < 400; index++) { + expect(rememberSignature(known, `sig-${index}`)).toBe(true); + } + expect(rememberSignature(known, "sig-0")).toBe(false); + expect(known.size).toBe(400); + + expect(rememberSignature(known, "sig-400")).toBe(true); + expect(known.size).toBe(400); + expect(known.has("sig-1")).toBe(true); + expect(known.has("sig-0")).toBe(false); +}); + +test("does not start another request when a cooldown exceeds the timer range", async () => { + const retryAfter = 2_147_483_648; + let now = 1_000; + let requests = 0; + const waits: number[] = []; + const poller = createPoolTradePoller({ + intervalMs: 60_000, + minRequestIntervalMs: 1_000, + fetchPairStats: async () => ({ + priceUsd: 1, + marketCapUsd: 1, + priceChangeH24: 1, + url: null, + dexId: "raydium", + quoteSymbol: "SOL", + pairAddress: "pair-slow", + tokenName: "TOKEN", + }), + fetchTrades: async () => { + if (++requests === 1) throw new GeckoRateLimitError(retryAfter); + return { data: [] }; + }, + now: () => now, + wait: async (delay) => { + waits.push(delay); + }, + onError: () => {}, + }); + + try { + poller.setMints([mint]); + await poller.pollNow(); + expect(requests).toBe(1); + expect(waits).toEqual([]); + + now += retryAfter; + await poller.pollNow(); + expect(requests).toBe(2); + expect(waits).toEqual([]); + } finally { + poller.stop(); + } +}); + test("pool trade poller watches every discovered pool", async () => { const received: string[] = []; const payloads = new Map }>([ From 1e64e88ace43d2ed38dfd03824da55096a6a7c69 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 14:47:28 -0300 Subject: [PATCH 066/410] test(wallet): bound confirmation polling with a fake clock --- tests/helpers/wallet-confirmation-clock.ts | 33 +++++++++++ tests/wallet.confirm-and-send.test.ts | 68 +++++++++++++++------- tests/wallet.transactions.test.ts | 58 +++++++++++------- 3 files changed, 118 insertions(+), 41 deletions(-) create mode 100644 tests/helpers/wallet-confirmation-clock.ts diff --git a/tests/helpers/wallet-confirmation-clock.ts b/tests/helpers/wallet-confirmation-clock.ts new file mode 100644 index 00000000..f28ebcb1 --- /dev/null +++ b/tests/helpers/wallet-confirmation-clock.ts @@ -0,0 +1,33 @@ +import { spyOn } from "bun:test"; +import type { WalletManager } from "../../src/utils/wallet"; + +/** Advance only when the wallet requests a delay, with a cap for a stalled poll. */ +export function useWalletConfirmationClock(wallet: WalletManager) { + const start = 1_700_000_000_000; + let now = start; + let reads = 0; + const delays: number[] = []; + const nowSpy = spyOn(Date, "now").mockImplementation(() => { + reads += 1; + if (reads > 500) throw new Error("Confirmation polling did not finish within the clock budget"); + return now; + }); + const originalSleep = Object.getOwnPropertyDescriptor(wallet, "sleep"); + Object.defineProperty(wallet, "sleep", { + configurable: true, + value: async (ms: number) => { + delays.push(ms); + now += ms; + }, + }); + + return { + delays, + elapsed: () => now - start, + restore: () => { + nowSpy.mockRestore(); + if (originalSleep) Object.defineProperty(wallet, "sleep", originalSleep); + else Reflect.deleteProperty(wallet, "sleep"); + }, + }; +} diff --git a/tests/wallet.confirm-and-send.test.ts b/tests/wallet.confirm-and-send.test.ts index cd28ace0..98a67cbd 100644 --- a/tests/wallet.confirm-and-send.test.ts +++ b/tests/wallet.confirm-and-send.test.ts @@ -4,6 +4,7 @@ import { TOKEN_PROGRAM_ID } from "#token"; import { WalletManager } from "../src/utils/wallet"; import { LAMPORTS_PER_SOL } from "../src/utils/constants"; import { stubInstantTimers } from "./helpers/timers"; +import { useWalletConfirmationClock } from "./helpers/wallet-confirmation-clock"; // Retry/backoff/poll sleeps are not under test here; run them instantly. let instantTimers: ReturnType; @@ -19,12 +20,16 @@ class ConnConfirmOk implements Partial { calls = 0; async getSignatureStatuses(_sig: string[]) { this.calls += 1; + if (this.calls > 1) throw new Error("Unexpected second confirmed-status lookup"); return { value: [{ confirmationStatus: "confirmed" }] } as any; } } class ConnConfirmErr implements Partial { + calls = 0; async getSignatureStatuses(_sig: string[]) { + this.calls += 1; + if (this.calls > 1) throw new Error("Unexpected second failed-status lookup"); return { value: [{ err: { Custom: 1 }, confirmationStatus: "processed" }], } as any; @@ -83,24 +88,34 @@ describe("WalletManager confirmTransaction and sendTransaction", () => { expect(sig).toBe("ABCDEF12"); }); - test("confirmTransaction retries on 429 then succeeds", async () => { - let calls = 0; - const conn: any = { - getSignatureStatuses: async () => { - calls += 1; - if (calls === 1) throw new Error("429 Too Many Requests"); - return { value: [{ confirmationStatus: "confirmed" }] }; - }, - getBlockHeight: async () => 1, - }; - const wm = WalletManager.createForTest(MNEMONIC, { - connection: conn, - fetch: globalThis.fetch as any, - timeNow: () => Date.now(), - }); - await wm.confirmTransaction("FAKESIG"); - expect(calls).toBeGreaterThanOrEqual(2); - }); + test.each(["429 Too Many Requests", "read timeout"])( + "retries '%s' once after two slots", + async (message) => { + let calls = 0; + const conn: any = { + getSignatureStatuses: async () => { + calls += 1; + if (calls === 1) throw new Error(message); + if (calls > 2) throw new Error("Unexpected third retry-status lookup"); + return { value: [{ confirmationStatus: "confirmed" }] }; + }, + getBlockHeight: async () => 1, + }; + const wm = WalletManager.createForTest(MNEMONIC, { + connection: conn, + fetch: globalThis.fetch as any, + timeNow: () => Date.now(), + }); + const clock = useWalletConfirmationClock(wm); + try { + await wm.confirmTransaction("FAKESIG"); + expect(calls).toBe(2); + expect(clock.delays).toEqual([800]); + } finally { + clock.restore(); + } + }, + ); test("confirmTransaction throws when blockhash expires", async () => { const conn: any = { @@ -119,7 +134,15 @@ describe("WalletManager confirmTransaction and sendTransaction", () => { recordedAt: Date.now() - 10_000, }); - await expect(wm.confirmTransaction("EXPIREME")).rejects.toThrow(/expired before confirmation/); + const clock = useWalletConfirmationClock(wm); + try { + await expect(wm.confirmTransaction("EXPIREME")).rejects.toThrow( + /expired before confirmation/, + ); + expect(clock.elapsed()).toBe(1_200); + } finally { + clock.restore(); + } }); test("probeTransactionAfterTimeout accepts versioned transactions", async () => { @@ -216,13 +239,16 @@ describe("WalletManager confirmTransaction and sendTransaction", () => { recordedAt: Date.now() - 5, }); + const clock = useWalletConfirmationClock(wm); try { await wm.confirmTransaction("TIMEOUT_SIG"); } finally { + clock.restore(); console.log = originalLog; } - expect(statusCalls).toBeGreaterThan(0); + expect(statusCalls).toBe(5); // Four in-window polls and one final lookup at 20ms. + expect(clock.delays).toEqual([5, 5, 5, 5]); expect(probeCalls).toBe(1); expect((wm as any).pendingSignatures.has("TIMEOUT_SIG")).toBe(false); expect(logs.some((entry) => entry.includes("Post-timeout probe recovered"))).toBe(true); @@ -264,11 +290,13 @@ describe("WalletManager confirmTransaction and sendTransaction", () => { errors.push(args.map((item) => String(item)).join(" ")); }; + const clock = useWalletConfirmationClock(wm); try { await expect(wm.confirmTransaction("MISSING_SIG")).rejects.toThrow( /Transaction confirmation timeout/, ); } finally { + clock.restore(); console.error = originalError; console.warn = originalWarn; } diff --git a/tests/wallet.transactions.test.ts b/tests/wallet.transactions.test.ts index 55f1daf5..ba9bc426 100644 --- a/tests/wallet.transactions.test.ts +++ b/tests/wallet.transactions.test.ts @@ -28,6 +28,7 @@ import { SIGNATURE_HISTORY_SEARCH_DELAY_MS, } from "../src/utils/constants"; import { stubInstantTimers } from "./helpers/timers"; +import { useWalletConfirmationClock } from "./helpers/wallet-confirmation-clock"; const MNEMONIC = process.env.MNEMONIC!; const USDC = "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"; @@ -60,20 +61,6 @@ const walletWith = (connection: Record, deps: Record { - const state = { now: 1_700_000_000_000 }; - const start = state.now; - const nowSpy = spyOn(Date, "now").mockImplementation(() => state.now); - (wallet as any).sleep = async (ms: number) => { - state.now += ms; - }; - return { - elapsed: () => state.now - start, - restore: () => nowSpy.mockRestore(), - }; -}; - const tokenAccountData = (options: { amount: bigint; owner: PublicKey; @@ -453,7 +440,7 @@ describe("confirmTransaction polling", () => { return calls < 25 ? { value: null } : { value: { confirmationStatus: "finalized" } }; }, }); - const clock = useFakeClock(wallet); + const clock = useWalletConfirmationClock(wallet); try { await wallet.confirmTransaction("SIG_SINGLE"); @@ -484,13 +471,13 @@ describe("confirmTransaction polling", () => { }; }, }); - const clock = useFakeClock(wallet); + const clock = useWalletConfirmationClock(wallet); elapsed = clock.elapsed; try { await wallet.confirmTransaction("SIG_HISTORY"); - expect(history[0]).toBe(false); - expect(history.at(-1)).toBe(true); + expect(history).toEqual([...Array(20).fill(false), ...Array(4).fill(true)]); + expect(clock.elapsed()).toBe(9_200); expect(messages(logSpy).some((line) => line.includes("history lookup enabled after"))).toBe( true, ); @@ -513,7 +500,7 @@ describe("confirmTransaction polling", () => { }; }, }); - const clock = useFakeClock(wallet); + const clock = useWalletConfirmationClock(wallet); try { await wallet.confirmTransaction("SIG_PROCESSED"); @@ -545,6 +532,35 @@ describe("confirmTransaction polling", () => { expect(logged[1]).toContain("plain failure"); }); + test("allows two blocks of grace but rejects the next block if no status is found", async () => { + const heights: number[] = []; + let elapsed = () => 0; + const wallet = walletWith({ + getSignatureStatuses: async () => ({ value: [null] }), + getBlockHeight: async () => { + heights.push(elapsed()); + return heights.length === 1 ? 102 : 103; + }, + }); + const signature = "SIG_GRACE"; + const clock = useWalletConfirmationClock(wallet); + elapsed = clock.elapsed; + (wallet as any).pendingSignatures.set(signature, { + blockhash: "BH", + lastValidBlockHeight: 100, + recordedAt: Date.now(), + }); + try { + await expect(wallet.confirmTransaction(signature)).rejects.toThrow( + "expired before confirmation (last valid block height 100, current 103)", + ); + expect(heights).toEqual([1_200, 2_400]); + expect((wallet as any).pendingSignatures.has(signature)).toBe(false); + } finally { + clock.restore(); + } + }); + test("block height read failures never decide the outcome", async () => { const wallet = walletWith({ getSignatureStatuses: async () => ({ value: [null] }), @@ -561,7 +577,7 @@ describe("confirmTransaction polling", () => { lastValidBlockHeight: 10, recordedAt: Date.now(), }); - const clock = useFakeClock(wallet); + const clock = useWalletConfirmationClock(wallet); try { const failure = await wallet.confirmTransaction("SIG_HEIGHT").catch((error) => error); @@ -593,7 +609,7 @@ describe("confirmTransaction polling", () => { }); fastProbe(wallet); (wallet as any).postTimeoutProbeBackoffMs = 0; - const clock = useFakeClock(wallet); + const clock = useWalletConfirmationClock(wallet); elapsed = clock.elapsed; return { wallet, clock }; }; From 5a0f0468f97a47594ff198cc0708e4fc96b375f7 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 14:50:44 -0300 Subject: [PATCH 067/410] test(telegram): verify wallet and game menu edit targets --- tests/menu-response.test.ts | 122 +++++++++++++++++++++++++++++++----- 1 file changed, 107 insertions(+), 15 deletions(-) diff --git a/tests/menu-response.test.ts b/tests/menu-response.test.ts index 9158cc20..c09498bf 100644 --- a/tests/menu-response.test.ts +++ b/tests/menu-response.test.ts @@ -1,4 +1,4 @@ -import { describe, expect, spyOn, test } from "bun:test"; +import { describe, expect, mock, spyOn, test } from "bun:test"; import { InlineKeyboard } from "grammy"; import { respondWithMenu } from "../src/utils/menu-response"; @@ -45,8 +45,8 @@ const makeCtx = (options: MakeCtxOptions = {}) => { calls.push({ type: "caption", args: [opts] }); return { ok: true }; }, - editMessageText: async (_text: string, opts: any) => { - calls.push({ type: "text", args: [opts] }); + editMessageText: async (text: string, opts: unknown) => { + calls.push({ type: "text", args: [text, opts] }); return { ok: true }; }, reply: async (text: string, opts: any) => { @@ -61,15 +61,27 @@ const makeCtx = (options: MakeCtxOptions = {}) => { }; describe("respondWithMenu", () => { - test("edits caption first when message supports caption", async () => { - const ctx = makeCtx(); - ctx.callbackQuery.message.caption = "previous caption"; - - const result = await respondWithMenu(ctx as any, basePayload); - - const calls = ctx.__calls; - expect(calls[0]?.type).toBe("caption"); - expect(calls.find((c: any) => c.type === "reply")).toBeUndefined(); + test.each([ + ["existing caption", { caption: "previous caption" }], + ["empty caption", { caption: "" }], + ["photo", { photo: [{ file_id: "photo" }] }], + ["video", { video: { file_id: "video" } }], + ["animation", { animation: { file_id: "animation" } }], + ["document", { document: { file_id: "document" } }], + ["audio", { audio: { file_id: "audio" } }], + ])("edits a caption for %s without sending a new message", async (_name, message) => { + const ctx = makeCtx({ message }); + + const result = await respondWithMenu(ctx, basePayload); + + expect(ctx.__calls).toEqual([ + { + type: "caption", + args: [ + { caption: basePayload.text, parse_mode: "HTML", reply_markup: basePayload.keyboard }, + ], + }, + ]); expect(result).toEqual({ messageId: 99, chatId: 42, @@ -161,9 +173,19 @@ describe("respondWithMenu", () => { const result = await respondWithMenu(ctx as any, basePayload); - const calls = ctx.__calls; - expect(calls[0]?.type).toBe("text"); - expect(calls.find((c: any) => c.type === "reply")).toBeUndefined(); + expect(ctx.__calls).toEqual([ + { + type: "text", + args: [ + basePayload.text, + { + parse_mode: "HTML", + reply_markup: basePayload.keyboard, + link_preview_options: { is_disabled: true }, + }, + ], + }, + ]); expect(result).toEqual({ messageId: 99, chatId: 42, @@ -171,6 +193,76 @@ describe("respondWithMenu", () => { }); }); + test("passes the selected parse mode and link-preview setting when replying", async () => { + const ctx = makeCtx(); + await respondWithMenu( + ctx, + { text: "*New menu*", parseMode: "MarkdownV2", disableLinkPreview: false }, + { skipEdit: true, replyToMessageId: 500 }, + ); + expect(ctx.__calls).toEqual([ + { + type: "reply", + args: [ + "*New menu*", + { + parse_mode: "MarkdownV2", + reply_markup: undefined, + link_preview_options: { is_disabled: false }, + reply_to_message_id: 500, + }, + ], + }, + ]); + }); + + test.each([ + ["trigger message", { message_id: 50, message_thread_id: 7 }, 7], + ["callback message", { message_id: 50 }, 8], + ["callback only", undefined, 8], + ])("sends a standalone card in the topic from the %s", async (_name, message, threadId) => { + const sendMessage = mock(async () => ({ message_id: 321 })); + const ctx = makeCtx({ message: { message_thread_id: 8 }, api: { sendMessage } }); + ctx.chat = { id: 42 }; + ctx.message = message; + const result = await respondWithMenu(ctx, basePayload, { + skipEdit: true, + replyToMessageId: null, + }); + expect(sendMessage).toHaveBeenCalledTimes(1); + expect(sendMessage).toHaveBeenCalledWith(42, basePayload.text, { + parse_mode: "HTML", + reply_markup: basePayload.keyboard, + link_preview_options: { is_disabled: true }, + message_thread_id: threadId, + }); + expect(ctx.__calls).toEqual([]); + expect(result).toEqual({ messageId: 321, chatId: 42, respondedWithReply: true }); + }); + + test("leaves invalid receipt IDs unknown instead of replacing the reply with an edit", async () => { + const ctx = makeCtx({ replyResult: { message_id: "not a number" } }); + ctx.chat = undefined; + const result = await respondWithMenu(ctx, basePayload, { skipEdit: true }); + expect(result).toEqual({ messageId: null, chatId: null, respondedWithReply: true }); + }); + + test("can disable both adapter and callback edits without disabling an explicit edit", async () => { + const ctx = makeCtx(); + ctx.__editAdapterTarget = { messageId: 10, chatId: 999 }; + + const edited = await respondWithMenu(ctx, basePayload, { + allowContextEdit: false, + targetMessageId: 31, + targetChatId: 37, + }); + const replied = await respondWithMenu(ctx, basePayload, { allowContextEdit: false }); + + expect(edited).toEqual({ messageId: 31, chatId: 37, respondedWithReply: false }); + expect(replied).toEqual({ messageId: 123, chatId: 42, respondedWithReply: true }); + expect(ctx.__calls.map(({ type }: { type: string }) => type)).toEqual(["api_text", "reply"]); + }); + test("skips edits and replies directly when skipEdit is true", async () => { const ctx = makeCtx(); From c725d32a4c39c1d0c5b7a316eab0ffef15b1f623 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 14:52:31 -0300 Subject: [PATCH 068/410] test(wallet): verify stale balance refresh boundaries --- tests/wallet-ui.swr.test.ts | 64 +++++++++++++++++++++++++++++++++++-- 1 file changed, 62 insertions(+), 2 deletions(-) diff --git a/tests/wallet-ui.swr.test.ts b/tests/wallet-ui.swr.test.ts index 5d87a4ab..21124982 100644 --- a/tests/wallet-ui.swr.test.ts +++ b/tests/wallet-ui.swr.test.ts @@ -10,6 +10,7 @@ import { WALLET_UPDATED_JUST_NOW_MS, buildWalletCaption, formatWalletUpdatedLabel, + type WalletTokenBalance, } from "../src/utils/wallet-ui"; import { RateLimitExceededError } from "../src/utils/rate-limiter"; @@ -19,9 +20,13 @@ const NOW = 5_000_000; const tgError = (description: string, code = 400) => Object.assign(new Error(description), { description, error_code: code }); -const page = (solBalance: number, fetchedAt?: number) => ({ +const page = ( + solBalance: number, + fetchedAt?: number, + tokenBalances: WalletTokenBalance[] = [], +) => ({ solBalance, - tokenBalances: [], + tokenBalances, page: 0, pageCount: 1, ...(fetchedAt === undefined ? {} : { fetchedAt }), @@ -177,6 +182,14 @@ describe("showWalletUI stale-while-revalidate", () => { expect(captured[0]).toContain("SOL: 1"); }); + test("balances at the five-second cache limit get a fresh read", async () => { + const { fetches, calls } = await run({ + cached: { data: page(1e9), fetchedAt: NOW - 5_000 }, + }); + expect(fetches()).toBe(1); + expect(calls.map(([kind]) => kind)).toEqual(["ctxEditText", "apiEditText"]); + }); + test("older cached pages render at once, then the message is edited when balances changed", async () => { const { captured, fetches, calls } = await run({ cached: { data: page(1e9), fetchedAt: NOW - 12_000 }, @@ -203,6 +216,53 @@ describe("showWalletUI stale-while-revalidate", () => { expect(calls.some(([kind]) => kind.startsWith("api"))).toBe(false); }); + const usdc: WalletTokenBalance = { + mint: "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v", + ticker: "USDC", + balance: 9_007_199_254_740_992, + decimals: 6, + rawBalance: "9007199254740992", + }; + + test.each([ + ["exact raw units", { ...usdc, rawBalance: "9007199254740993" }], + ["mint", { ...usdc, mint: "So11111111111111111111111111111111111111112" }], + ["numeric-only balance", { ...usdc, rawBalance: undefined, balance: 1 }], + ])( + "a change in %s refreshes the original message before its label expires", + async (_name, token) => { + const { calls, captured } = await run({ + cached: { data: page(1e9, undefined, [usdc]), fetchedAt: NOW - 12_000 }, + fresh: async () => page(1e9, NOW, [token]), + }); + expect(calls.map(([kind]) => kind)).toEqual(["ctxEditText", "apiEditText"]); + expect(calls[1]?.slice(1, 4)).toEqual([99, 11, captured[1]]); + expect(captured[1]).not.toContain("Updated"); + }, + ); + + test("refreshes a numeric-only balance even when cached and fresh SOL are equal", async () => { + const token = { ...usdc, rawBalance: undefined, balance: 1_000_000 }; + const { calls, captured } = await run({ + cached: { data: page(1e9, undefined, [token]), fetchedAt: NOW - 12_000 }, + fresh: async () => page(1e9, NOW, [{ ...token, balance: 2_000_000 }]), + }); + expect(calls.map(([kind]) => kind)).toEqual(["ctxEditText", "apiEditText"]); + expect(captured[0]).toContain("USDC: 1"); + expect(captured[1]).toContain("USDC: 2"); + }); + + test.each(["page", "pageCount"] as const)( + "refreshes changed %s even when all balances match", + async (field) => { + const { calls } = await run({ + cached: { data: page(1e9), fetchedAt: NOW - 12_000 }, + fresh: async () => ({ ...page(1e9, NOW), [field]: 2 }), + }); + expect(calls.map(([kind]) => kind)).toEqual(["ctxEditText", "apiEditText"]); + }, + ); + test("unchanged balances still refresh a stale Updated label", async () => { const { calls } = await run({ cached: { data: page(2e9), fetchedAt: NOW - WALLET_STALE_LABEL_REFRESH_MS }, From b8eb26bba97a269749e08634d99127f2e96ab73e Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 14:55:01 -0300 Subject: [PATCH 069/410] test(wallet): verify private export ownership and rate limits --- tests/bot-privatekey.flows.test.ts | 47 ++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) diff --git a/tests/bot-privatekey.flows.test.ts b/tests/bot-privatekey.flows.test.ts index 8805c299..16e07f93 100644 --- a/tests/bot-privatekey.flows.test.ts +++ b/tests/bot-privatekey.flows.test.ts @@ -166,6 +166,53 @@ describe("private key export", () => { expect(callsTo("sendMessage")).toHaveLength(3); }); + test("a pending confirmation belongs only to the requester and can be consumed once", async () => { + vi.useFakeTimers(); + try { + await at("cmd_privatekey"); + await at("confirm_privatekey", USER + 1_000_000); + expect(answers().at(-1)).toBe("❌ Confirmation expired. Try again."); + expect(callsTo("sendMessage")).toHaveLength(0); + + await Promise.all([at("confirm_privatekey"), at("confirm_privatekey")]); + const sent = callsTo("sendMessage"); + expect(sent).toHaveLength(1); + expect(sent[0]?.payload).toMatchObject({ chat_id: USER, parse_mode: "HTML" }); + expect(answers().slice(-2)).toContain("🔐 Private key shown"); + expect(answers().slice(-2)).toContain("❌ Confirmation expired. Try again."); + } finally { + vi.useRealTimers(); + } + }); + + test("a fourth export is refused until the exact one-hour boundary", async () => { + vi.useFakeTimers(); + const start = 1_730_000_000_000; + const clock = spyOn(Date, "now").mockReturnValue(start); + try { + for (let request = 0; request < 3; request += 1) { + await at("cmd_privatekey"); + await at("confirm_privatekey"); + } + clock.mockReturnValue(start + 3_599_999); + await at("cmd_privatekey"); + await at("confirm_privatekey"); + expect(answers().at(-1)).toBe("❌ Too many exports. Try again later."); + expect(callsTo("sendMessage")).toHaveLength(3); + + clock.mockReturnValue(start + 3_600_000); + await at("confirm_privatekey"); + expect(answers().at(-1)).toBe("❌ Confirmation expired. Try again."); + await at("cmd_privatekey"); + await at("confirm_privatekey"); + expect(answers().at(-1)).toBe("🔐 Private key shown"); + expect(callsTo("sendMessage")).toHaveLength(4); + } finally { + clock.mockRestore(); + vi.useRealTimers(); + } + }); + test("both steps are refused outside private chats", async () => { await press("cmd_privatekey", { userId: USER, chatId: -77 }); expect(answers().at(-1)).toBe("❌ Private key only available in private chat"); From f973681f8f0b560a2e5a0e35ca918e7c704e4924 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 14:57:59 -0300 Subject: [PATCH 070/410] refactor(games): bound confirmed account read retries --- src/utils/game.ts | 18 ++++++--- tests/game.participants.test.ts | 65 +++++++++++++++++++++++++++++++++ 2 files changed, 78 insertions(+), 5 deletions(-) diff --git a/src/utils/game.ts b/src/utils/game.ts index 692ef824..990382e3 100644 --- a/src/utils/game.ts +++ b/src/utils/game.ts @@ -4379,15 +4379,23 @@ export class GameManager { private async fetchConfirmedGame(gamePda: PublicKey) { const retryDelays = getConfirmationRetryDelays(); - for (let attempt = 0; ; attempt++) { + const readGame = () => this.program.account.game.fetch(gamePda); + let lastError: unknown; + try { + return await readGame(); + } catch (error) { + lastError = error; + } + for (const attempt of retryDelays.keys()) { + console.warn(`Retrying confirmed game account read for ${gamePda.toBase58()}:`, lastError); + await new Promise((resolve) => setTimeout(resolve, retryDelays[attempt])); try { - return await this.program.account.game.fetch(gamePda); + return await readGame(); } catch (error) { - if (attempt >= retryDelays.length) throw error; - console.warn(`Retrying confirmed game account read for ${gamePda.toBase58()}:`, error); - await new Promise((resolve) => setTimeout(resolve, retryDelays[attempt])); + lastError = error; } } + throw lastError; } public hasGameCreationRequest(telegramId: bigint, chatId?: number, messageId?: number): boolean { diff --git a/tests/game.participants.test.ts b/tests/game.participants.test.ts index fefbd173..7c9517d7 100644 --- a/tests/game.participants.test.ts +++ b/tests/game.participants.test.ts @@ -11,6 +11,71 @@ const makeManager = (program: any = { account: { game: {} } }, gameDb: any = {}) const freshKey = async () => (await Keypair.generate()).publicKey; +describe("confirmed game account reads", () => { + const productionDelays = [2_000, 4_000, 8_000, 12_000, 16_000, 20_000]; + let timers: ReturnType; + let originalEnvironment: string | undefined; + let warnSpy: ReturnType; + + beforeEach(() => { + GameManager.resetForTest(); + originalEnvironment = process.env.NODE_ENV; + process.env.NODE_ENV = "production"; + timers = stubInstantTimers(); + warnSpy = spyOn(console, "warn").mockImplementation(() => undefined); + }); + afterEach(() => { + timers.restore(); + warnSpy.mockRestore(); + if (originalEnvironment === undefined) delete process.env.NODE_ENV; + else process.env.NODE_ENV = originalEnvironment; + GameManager.resetForTest(); + }); + + test.each([0, 1, 6])("returns the account after %i transient read failures", async (failures) => { + const game = { players: [] }; + const addresses: string[] = []; + const gm = makeManager({ + account: { + game: { + fetch: async (pda: PublicKey) => { + addresses.push(pda.toBase58()); + if (addresses.length <= failures) throw new Error("RPC unavailable"); + return game; + }, + }, + }, + }); + + expect(await gm.fetchConfirmedGame(GAME_PDA)).toBe(game); + expect(addresses).toEqual(Array(failures + 1).fill(GAME_ADDRESS)); + expect(timers.delays).toEqual(productionDelays.slice(0, failures)); + expect(warnSpy).toHaveBeenCalledTimes(failures); + }); + + test("returns the final read error after the six production delays", async () => { + const finalError = new Error("last game account read failed"); + let reads = 0; + const gm = makeManager({ + account: { + game: { + fetch: async () => { + reads += 1; + if (reads < 7) throw new Error("transient RPC failure"); + if (reads === 7) throw finalError; + return { unexpectedExtraRead: true }; + }, + }, + }, + }); + + await expect(gm.fetchConfirmedGame(GAME_PDA)).rejects.toBe(finalError); + expect(reads).toBe(7); + expect(timers.delays).toEqual(productionDelays); + expect(warnSpy).toHaveBeenCalledTimes(6); + }); +}); + describe("GameManager isPlayerInGame", () => { let warnSpy: ReturnType; From 982e226109f3c80309235d9a6472b2565b9cc050 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 15:00:45 -0300 Subject: [PATCH 071/410] refactor(games): limit private join retry iteration --- src/utils/game.ts | 8 +++--- tests/game-manager.join-lifecycle.test.ts | 7 ++++- tests/game.unjoin-private.test.ts | 35 +++++++++++++++++++++-- 3 files changed, 42 insertions(+), 8 deletions(-) diff --git a/src/utils/game.ts b/src/utils/game.ts index 990382e3..8e3f5a55 100644 --- a/src/utils/game.ts +++ b/src/utils/game.ts @@ -6150,11 +6150,10 @@ export class GameManager { return { success: false, error: this.completedGameErrorMessage }; } - const maxAttempts = 2; + const attempts = [0, 1]; let lastSignature: string | undefined; - // The last attempt always returns or throws, so the loop has no exit condition. - for (let attempt = 0; ; attempt++) { + for (const attempt of attempts) { let setupInstructions: TransactionInstruction[] = []; let joinInstructions: TransactionInstruction[] = []; try { @@ -6227,7 +6226,7 @@ export class GameManager { const isExpiration = normalized.includes("expired before confirmation") || normalized.includes("last valid block height"); - const isLastAttempt = attempt === maxAttempts - 1; + const isLastAttempt = attempt === attempts.length - 1; if ((isTimeout || isExpiration) && !isLastAttempt) { const alreadyJoined = await this.isPlayerInGame(gamePda, playerKp.publicKey).catch( @@ -6255,6 +6254,7 @@ export class GameManager { throw joinError; } } + throw new Error("Private join retry ended without an outcome"); } catch (error: any) { console.error("Error joining private game:", error); if (isMissingAccountError(error)) { diff --git a/tests/game-manager.join-lifecycle.test.ts b/tests/game-manager.join-lifecycle.test.ts index 33bca8d7..7cf13fa1 100644 --- a/tests/game-manager.join-lifecycle.test.ts +++ b/tests/game-manager.join-lifecycle.test.ts @@ -361,7 +361,12 @@ describe("GameManager join lifecycle", () => { saveGameParticipant: (...args: any[]) => participantCalls.push(args), } as any; const gm = GameManager.getInstance({ account: { game } } as any, {} as any, gameDb); - (gm as any).isPlayerInGame = async () => false; + let reads = 0; + (gm as any).isPlayerInGame = async () => { + reads += 1; + if (reads > 1) throw new Error("Unexpected second membership check"); + return false; + }; const success = await (gm as any).verifyParticipantJoin( new PublicKey("BPFLoader3111111111111111111111111111111111"), (await Keypair.generate()).publicKey, diff --git a/tests/game.unjoin-private.test.ts b/tests/game.unjoin-private.test.ts index 9820265f..34a20103 100644 --- a/tests/game.unjoin-private.test.ts +++ b/tests/game.unjoin-private.test.ts @@ -1,4 +1,4 @@ -import { afterEach, beforeEach, describe, expect, spyOn, test } from "bun:test"; +import { afterEach, beforeEach, describe, expect, spyOn, test, vi } from "bun:test"; import { Keypair, PublicKey } from "#solana"; import { GameManager } from "../src/utils/game"; @@ -395,15 +395,44 @@ describe("joinPrivateGame failure branches", () => { test("a second timeout on the last attempt is rethrown to the friendly mapper", async () => { let sends = 0; + let membershipReads = 0; const { join } = await setup({ sendTransaction: async () => { sends += 1; - throw new Error("timeout again"); + if (sends > 2) throw new Error("Unexpected third private join attempt"); + throw new Error(sends === 1 ? "first timeout" : "timeout again"); + }, + isPlayerInGame: async () => { + membershipReads += 1; + return false; }, - isPlayerInGame: async () => false, }); expect(await join()).toEqual({ success: false, error: "friendly: timeout again" }); expect(sends).toBe(2); + expect(membershipReads).toBe(1); + }); + + test("a known first failure never submits again or reloads the game", async () => { + let loads = 0; + const failure = new Error("insufficient funds"); + const send = vi.fn(async () => { + throw failure; + }); + const membershipRead = vi.fn(async () => false); + const { join } = await setup({ + gameApi: { + fetchNullable: async () => { + loads += 1; + return { ok: 1 }; + }, + }, + sendTransaction: send, + isPlayerInGame: membershipRead, + }); + expect(await join()).toEqual({ success: false, error: "friendly: insufficient funds" }); + expect(send).toHaveBeenCalledTimes(1); + expect(loads).toBe(1); + expect(membershipRead).not.toHaveBeenCalled(); }); test("an oracle failure that reports a missing account maps to the expired message", async () => { From 38c75f6fdc7eea75067bbabee2fac492c8ec001b Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 15:03:59 -0300 Subject: [PATCH 072/410] refactor(games): bound completion redraws to one pass --- src/utils/game.ts | 52 +++++++++++++++++-------------------- tests/game.messages.test.ts | 29 ++++++++++++++++++++- 2 files changed, 52 insertions(+), 29 deletions(-) diff --git a/src/utils/game.ts b/src/utils/game.ts index 8e3f5a55..0da565ec 100644 --- a/src/utils/game.ts +++ b/src/utils/game.ts @@ -3649,6 +3649,7 @@ export class GameManager { updateGeneration?: number, updateRequest?: GameMessageUpdateRequest, updateOptions?: GameMessageUpdateOptions, + isTerminalRedraw = false, ): Promise { const request = updateRequest ?? { status, @@ -3700,6 +3701,27 @@ export class GameManager { if (!messageMap || messageMap.size === 0) return; + const redrawAsTerminal = async (terminal: TerminalGameMessageUpdate): Promise => { + // An update may switch once from active to terminal. A terminal redraw must not restart. + if (isTerminalRedraw) return; + await this.updateGameMessageInternal( + ctx, + gameAddress, + gameType, + amount, + creatorUsername, + terminal.status, + tokenTicker, + terminal.winnerAddress, + terminal.totalPot, + terminal.winnerSignature, + updateGeneration, + request, + undefined, + true, + ); + }; + let messageTextValue = ""; let inlineKeyboardValue: any; @@ -3727,20 +3749,7 @@ export class GameManager { winnerSignature, ); if (terminalBeforeDispatch && status.toLowerCase() !== "completed") { - await this.updateGameMessageInternal( - ctx, - gameAddress, - gameType, - amount, - creatorUsername, - terminalBeforeDispatch.status, - tokenTicker, - terminalBeforeDispatch.winnerAddress, - terminalBeforeDispatch.totalPot, - terminalBeforeDispatch.winnerSignature, - updateGeneration, - request, - ); + await redrawAsTerminal(terminalBeforeDispatch); return; } @@ -4141,20 +4150,7 @@ export class GameManager { const redirect = terminalRedirect as TerminalGameMessageUpdate | null; if (redirect) { - await this.updateGameMessageInternal( - ctx, - gameAddress, - gameType, - amount, - creatorUsername, - redirect.status, - tokenTicker, - redirect.winnerAddress, - redirect.totalPot, - redirect.winnerSignature, - updateGeneration, - request, - ); + await redrawAsTerminal(redirect); } } catch (error) { console.error("Error in updateGameMessage (preparation):", error); diff --git a/tests/game.messages.test.ts b/tests/game.messages.test.ts index 21f3baea..0008c08e 100644 --- a/tests/game.messages.test.ts +++ b/tests/game.messages.test.ts @@ -223,7 +223,12 @@ describe("updateGameMessageInternal", () => { }; const ctx: any = { api }; const keyboard = [[{ text: "Join", callback_data: "join" }]]; - gm.formatGameMessage = vi.fn(async () => ({ messageText: "FORMATTED", keyboard })); + let formats = 0; + gm.formatGameMessage = vi.fn(async () => { + formats += 1; + if (formats > 2) throw new Error("Unexpected third card format in a single update"); + return { messageText: "FORMATTED", keyboard }; + }); gm.buildGameMessagePayload = vi.fn(async () => ({ text: "PAYLOAD", keyboard, @@ -311,6 +316,16 @@ describe("updateGameMessageInternal", () => { expect(api.editMessageText).toHaveBeenCalledTimes(1); }); + test("does not redraw a card already formatted as completed, regardless of case", async () => { + const { gm, run, api } = setup(); + gm.getPersistedTerminalUpdate = queue([null, terminal], terminal); + await run("cOmPlEtEd"); + expect(gm.formatGameMessage.mock.calls.map((call: unknown[]) => call[5])).toEqual([ + "cOmPlEtEd", + ]); + expect(api.editMessageText).toHaveBeenCalledTimes(1); + }); + test("drops the update when a newer one supersedes it after formatting", async () => { const { gm, run, api } = setup(); gm.isSupersededActiveGameMessageUpdate = queue([false, true], false); @@ -340,6 +355,18 @@ describe("updateGameMessageInternal", () => { expect(edited).toEqual([1, 2]); }); + test("discards an active payload when completion lands before its Telegram edit", async () => { + const { gm, run, api } = setup(); + gm.getPersistedTerminalUpdate = queue([null, null, null, terminal], terminal); + await run("Active"); + expect(gm.buildGameMessagePayload.mock.calls.map((call: unknown[]) => call[1])).toEqual([ + expect.objectContaining({ status: "Active", winnerAddress: undefined }), + expect.objectContaining({ status: "Completed", winnerAddress: "W", totalPot: 9 }), + ]); + expect(api.editMessageText).toHaveBeenCalledTimes(1); + expect(api.editMessageText).toHaveBeenCalledWith(CHAT, MSG, "PAYLOAD", expect.any(Object)); + }); + test("stops editing remaining chats once superseded before building the payload", async () => { const { gm, run, api } = setup({ targets: [ From a192bb1b3e2a049db1ccb3049d5f52fbe2246a32 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 15:05:09 -0300 Subject: [PATCH 073/410] fix(games): keep the bounded join failure path reachable --- src/utils/game.ts | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/utils/game.ts b/src/utils/game.ts index 0da565ec..d31f3bcd 100644 --- a/src/utils/game.ts +++ b/src/utils/game.ts @@ -6148,6 +6148,7 @@ export class GameManager { const attempts = [0, 1]; let lastSignature: string | undefined; + let lastJoinError: unknown; for (const attempt of attempts) { let setupInstructions: TransactionInstruction[] = []; @@ -6247,10 +6248,11 @@ export class GameManager { ); } - throw joinError; + lastJoinError = joinError; + break; } } - throw new Error("Private join retry ended without an outcome"); + throw lastJoinError; } catch (error: any) { console.error("Error joining private game:", error); if (isMissingAccountError(error)) { From b8ddd9a210570baf313ac92d34817c7e65a49745 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 15:09:13 -0300 Subject: [PATCH 074/410] test(settings): verify exact chat default input limits --- tests/chat-defaults.handler.test.ts | 70 ++++++++++++++++++++++++++++- 1 file changed, 68 insertions(+), 2 deletions(-) diff --git a/tests/chat-defaults.handler.test.ts b/tests/chat-defaults.handler.test.ts index dcc67db1..b32fa377 100644 --- a/tests/chat-defaults.handler.test.ts +++ b/tests/chat-defaults.handler.test.ts @@ -1662,8 +1662,13 @@ describe("chat defaults menus and inputs", () => { expect(h.lastMenu().text).toContain("⚙️ Chat settings"); }); - const session = (setting: string) => - ({ type: "chat_defaults", chatId: 99, messageId: 11, setting, initiatorId: "123" }) as any; + const session = (setting: string): InputSessionState => ({ + type: "chat_defaults", + chatId: 99, + messageId: 11, + setting, + initiatorId: "123", + }); test("media replies store the file id and media type for each target", async () => { const h = setup(); @@ -1755,6 +1760,67 @@ describe("chat defaults menus and inputs", () => { expect(chatDb.getChatGameSettings(99)?.timeout_seconds).toBeNull(); }); + test.each([ + ["coinflip", "1", { coinflip_max_players: 2 }], + ["coinflip", "49", { coinflip_max_players: 49 }], + ["coinflip", "51", { coinflip_max_players: 50 }], + ["giveaway", "0", { giveaway_max_players: 1 }], + ["giveaway", " 50 ", { giveaway_max_players: 50 }], + ["timeout", "299", { timeout_seconds: 300 }], + ["timeout", "301", { timeout_seconds: 301 }], + ["timeout", "86401", { timeout_seconds: 86_400 }], + ] as const)("stores only the %s setting when given %s", async (setting, input, changed) => { + const h = setup(); + const previous = { coinflip_max_players: 3, giveaway_max_players: 7, timeout_seconds: 900 }; + chatDb.upsertChatGameSettings(99, previous); + + expect(await h.module.handleSettingsInput(h.ctxFor(), session(setting), input)).toBe(true); + + expect(chatDb.getChatGameSettings(99)).toMatchObject({ + ...previous, + ...changed, + set_by_telegram_id: "123", + }); + }); + + test.each(["coinflip", "timeout"] as const)( + "does not clear %s on a partial reset command", + async (setting) => { + const h = setup(); + chatDb.upsertChatGameSettings(99, { coinflip_max_players: 4, timeout_seconds: 900 }); + + for (const rejected of ["please clear", "remove this"]) { + await h.module.handleSettingsInput(h.ctxFor(), session(setting), rejected); + expect(chatDb.getChatGameSettings(99)).toMatchObject({ + coinflip_max_players: 4, + timeout_seconds: 900, + }); + } + expect(h.replies).toHaveLength(2); + expect(h.replies.every((reply) => reply.includes("❌"))).toBe(true); + + await h.module.handleSettingsInput(h.ctxFor(), session(setting), " ReMoVe "); + expect(chatDb.getChatGameSettings(99)).toMatchObject({ + coinflip_max_players: setting === "coinflip" ? null : 4, + timeout_seconds: setting === "timeout" ? null : 900, + }); + }, + ); + + test("persists exactly 30 join notices per minute but rejects negative and higher rates", async () => { + const h = setup(); + const input = { ...session(""), target: "join_rate_custom" }; + await h.module.handleSettingsInput(h.ctxFor(), input, "30"); + expect(chatDb.getChatGameSettings(99)?.join_notifications_per_minute).toBe(30); + for (const rejected of ["-1", "31"]) { + await h.module.handleSettingsInput(h.ctxFor(), input, rejected); + expect(chatDb.getChatGameSettings(99)?.join_notifications_per_minute).toBe(30); + expect(h.replies.at(-1)).toContain("Invalid rate"); + } + await h.module.handleSettingsInput(h.ctxFor(), input, "0"); + expect(chatDb.getChatGameSettings(99)?.join_notifications_per_minute).toBe(0); + }); + test("unknown tokens list at most ten supported tokens", async () => { const tokenManager = { ...baseTokenManager(), From b5f6c7328fea36d0b924248395a63679896d5c6c Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 15:09:14 -0300 Subject: [PATCH 075/410] test(keyboards): verify positions navigation and network actions --- tests/keyboards.test.ts | 44 ++++++++++++++++++++++++++++++++++++----- 1 file changed, 39 insertions(+), 5 deletions(-) diff --git a/tests/keyboards.test.ts b/tests/keyboards.test.ts index 8213ee57..030fdadd 100644 --- a/tests/keyboards.test.ts +++ b/tests/keyboards.test.ts @@ -114,6 +114,10 @@ describe("keyboards: main and wallet", () => { test("positions keyboard pages tokens without a DexScreener button", () => { const onePage = createPositionsKeyboard({ page: 0, pageCount: 1 }); + expect(onePage.inline_keyboard[0]).toEqual([ + expect.objectContaining({ callback_data: "cmd_swap" }), + expect.objectContaining({ callback_data: "wallet_pos_r_0" }), + ]); expect(extractCallbacks(onePage)).not.toContain("wallet_pos_1"); expect(extractCallbacks(onePage)).toContain("wallet_pos_r_0"); expect(extractTexts(onePage)).toContain("🔁 Refresh"); @@ -151,11 +155,41 @@ test("wallet keyboard adds page arrows only when more than one page exists", () expect(last.at(-1)).toEqual(["wallet_page_1"]); }); -test("positions keyboard shows a back arrow on later pages", () => { - const callbacks = extractCallbacks(createPositionsKeyboard({ page: 1, pageCount: 2 })); - expect(callbacks).toContain("wallet_pos_0"); - expect(callbacks).not.toContain("wallet_pos_2"); - expect(callbacks).toContain("wallet_pos_r_1"); +test.each([ + [0, [{ text: "→", callback_data: "wallet_pos_1" }]], + [ + 1, + [ + { text: "←", callback_data: "wallet_pos_0" }, + { text: "→", callback_data: "wallet_pos_2" }, + ], + ], + [2, [{ text: "←", callback_data: "wallet_pos_1" }]], +])("positions page %i keeps navigation and actions on separate rows", (page, navigation) => { + const keyboard = createPositionsKeyboard({ page, pageCount: 3 }); + expect(keyboard.inline_keyboard[0]).toEqual(navigation); + expect(keyboard.inline_keyboard[1]).toEqual([ + expect.objectContaining({ callback_data: "cmd_swap" }), + expect.objectContaining({ callback_data: `wallet_pos_r_${page}` }), + ]); + expect(keyboard.inline_keyboard[2]).toEqual([ + expect.objectContaining({ callback_data: "main_wallet" }), + ]); +}); + +test("wallet actions do not offer Solana callbacks on the EVM wallet", () => { + const keyboard = createWalletKeyboard(undefined, { + swap: "", + positions: "", + withdraw: "evm_wallet_withdraw", + refresh: "evm_wallet_refresh", + settings: "game_network", + }); + expect(keyboard.inline_keyboard).toEqual([ + [expect.objectContaining({ callback_data: "evm_wallet_withdraw" })], + [expect.objectContaining({ callback_data: "evm_wallet_refresh" })], + [expect.objectContaining({ callback_data: "game_network" })], + ]); }); test("back to settings keyboard returns wallet_settings callback", () => { From 40d45817fcf07f7e44ff236ccf7581ada78f6aa5 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 15:12:24 -0300 Subject: [PATCH 076/410] test(games): exercise the replaced media edit path --- tests/game.messages.test.ts | 60 +++++++++++++++++++++++++++---------- 1 file changed, 44 insertions(+), 16 deletions(-) diff --git a/tests/game.messages.test.ts b/tests/game.messages.test.ts index 0008c08e..8f003b70 100644 --- a/tests/game.messages.test.ts +++ b/tests/game.messages.test.ts @@ -212,6 +212,7 @@ describe("updateGameMessageInternal", () => { payloadMedia?: { fileId: string; mediaType: string }; edits?: Edits; targets?: Array<{ chatId: number; messageId: number }>; + maxFormats?: number; } = {}, ) { const { gm, db } = makeManager(); @@ -226,7 +227,7 @@ describe("updateGameMessageInternal", () => { let formats = 0; gm.formatGameMessage = vi.fn(async () => { formats += 1; - if (formats > 2) throw new Error("Unexpected third card format in a single update"); + if (formats > (options.maxFormats ?? 2)) throw new Error("Unexpected extra card format"); return { messageText: "FORMATTED", keyboard }; }); gm.buildGameMessagePayload = vi.fn(async () => ({ @@ -643,25 +644,52 @@ describe("updateGameMessageInternal", () => { }); test("drops a completion media edit that a newer edit replaced in the queue", async () => { - let release!: () => void; - const gate = new Promise((resolve) => { - release = resolve; - }); - const { gm, ctx, api } = setup({ + const entered = Promise.withResolvers(); + const gate = Promise.withResolvers(); + const captions: string[] = []; + const { gm, ctx, api, keyboard } = setup({ usesVideo: true, payloadMedia: media, - edits: { media: async () => (await gate, { message_id: MSG }) }, + maxFormats: 3, + edits: { + media: async (_chat: number, _message: number, input: { caption: string }) => { + captions.push(input.caption); + entered.resolve(); + await gate.promise; + return { message_id: MSG }; + }, + }, }); - const call = () => - gm.updateGameMessageInternal(ctx, GAME, "Coinflip", 1, "alice", "Completed", "TOK"); - const first = call(); - const second = call(); - const third = call(); - await new Promise((resolve) => setTimeout(resolve, 10)); - release(); - await Promise.all([first, second, third]); - // The first edit was in flight, the second was replaced, the third ran after the first. + gm.buildGameMessagePayload = vi.fn( + async (_ctx: unknown, request: { creatorUsername: string }) => ({ + text: request.creatorUsername, + keyboard, + media, + }), + ); + const call = (caption: string): Promise => + gm.updateGameMessageInternal(ctx, GAME, "Coinflip", 1, caption, "Completed", "TOK"); + const first = call("in flight"); + const updates = [first]; + try { + await Promise.race([entered.promise, first]); + expect(captions).toEqual(["in flight"]); + + let superseded = false; + const middle = call("replaced").then(() => { + superseded = true; + }); + updates.push(middle, call("latest")); + await Bun.sleep(0); + expect(superseded).toBe(true); + expect(captions).toEqual(["in flight"]); + } finally { + gate.resolve(); + await Promise.all(updates); + } + expect(gm.formatGameMessage).toHaveBeenCalledTimes(3); expect(api.editMessageMedia).toHaveBeenCalledTimes(2); + expect(captions).toEqual(["in flight", "latest"]); }); }); }); From 1df3e91398ed1b0e93d68b2fd41d86183262e8c2 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 15:15:57 -0300 Subject: [PATCH 077/410] fix(wallet): wait for the complete USD position cost basis --- src/services/positions.ts | 12 +++++-- tests/positions.test.ts | 66 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 76 insertions(+), 2 deletions(-) diff --git a/src/services/positions.ts b/src/services/positions.ts index f897f885..1118c281 100644 --- a/src/services/positions.ts +++ b/src/services/positions.ts @@ -427,10 +427,18 @@ export function buildTokenPositions(args: { const { qty, costSol, costUsdc, costUsdt, buyCount, sellCount } = lot; const costUsd = costUsdc + costUsdt; - const markedUsd = costUsd + (solPriceUsd > 0 ? costSol * solPriceUsd : 0); + // A USD average must include all costs. A missing SOL price is not zero cost. + const solCostUsd = + costSol > 0 + ? solPriceUsd > 0 && Number.isFinite(solPriceUsd) + ? costSol * solPriceUsd + : null + : 0; + const markedUsd = solCostUsd === null ? null : costUsd + solCostUsd; const avgEntrySol = costSol > 0 ? costSol / qty : null; const priceUsd = args.pricesUsd[holding.mint] ?? 0; - const avgEntryUsd = markedUsd > 0 ? markedUsd / qty : null; + const avgEntryUsd = + markedUsd !== null && Number.isFinite(markedUsd) && markedUsd > 0 ? markedUsd / qty : null; const pnlPercent = avgEntryUsd != null && avgEntryUsd > 0 && priceUsd > 0 ? (priceUsd - avgEntryUsd) / avgEntryUsd diff --git a/tests/positions.test.ts b/tests/positions.test.ts index a92de548..ca3839de 100644 --- a/tests/positions.test.ts +++ b/tests/positions.test.ts @@ -651,6 +651,72 @@ test("mixed SOL and USDC buys share one weighted USD average", () => { expect(formatPositionMessage(position!)).toContain("Spent: 1 SOL + 50 USDC, 2 buys"); }); +test("mixed-cost positions wait for the SOL quote instead of reporting a partial cost basis", async () => { + const address = "mixed-cost-quote-outage"; + const requests: string[][] = []; + const loader = { + walletAddress: address, + getHoldings: async () => [{ mint: TIMBA, ticker: "TIMBA", balance: 150, decimals: 6 }], + getSwaps: () => [ + swap({ + signature: "sol-buy", + amount_in: "1000000000", + amount_out: "100000000", + timestamp: 1, + }), + swap({ + signature: "usdc-buy", + input_mint: USDC_MINT, + input_ticker: "USDC", + amount_in: "50000000", + amount_out: "50000000", + timestamp: 2, + }), + ], + fetchPricesUSD: async (mints: string[]): Promise> => { + requests.push(mints); + return requests.length === 1 ? { [TIMBA]: 2 } : { [WSOL_MINT]: 100 }; + }, + }; + + try { + const [incomplete] = await loadTokenPositionsForWallet(loader); + expect(incomplete).toMatchObject({ + avgEntryUsd: null, + pnlPercent: null, + unrealizedUsd: null, + priceUsd: 2, + solSpent: 1, + usdcSpent: 50, + }); + const incompleteCard = incomplete && formatPositionMessage(incomplete); + expect(incompleteCard).toContain("Avg entry: -"); + expect(incompleteCard).toContain("Unrealized: -"); + + const [complete] = await loadTokenPositionsForWallet(loader); + expect(complete).toMatchObject({ avgEntryUsd: 1, pnlPercent: 1, unrealizedUsd: 150 }); + expect(requests).toEqual([[WSOL_MINT, TIMBA], [WSOL_MINT]]); + } finally { + clearPositionSnapshot(address); + } +}); + +test("a stablecoin-only position has a complete USD cost basis without a SOL quote", () => { + const [position] = buildTokenPositions({ + fills: fromSwaps([ + swap({ + input_mint: USDC_MINT, + input_ticker: "USDC", + amount_in: "50000000", + amount_out: "50000000", + }), + ]), + holdings: [{ mint: TIMBA, ticker: "TIMBA", balance: 50, decimals: 6 }], + pricesUsd: { [TIMBA]: 2 }, + }); + expect(position).toMatchObject({ avgEntryUsd: 1, pnlPercent: 1, unrealizedUsd: 50 }); +}); + test("selling more than the tracked lot just closes the books", () => { const fills = fromSwaps([ swap({ signature: "buy", amount_in: "1000000000", amount_out: "100000000", timestamp: 1 }), From a7c691190ee84513730d7d7a2a31d709592245a4 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 15:17:39 -0300 Subject: [PATCH 078/410] test(wallet): pin position snapshot expiry --- tests/positions.test.ts | 34 +++++++++++++++++++++++++++++++++- 1 file changed, 33 insertions(+), 1 deletion(-) diff --git a/tests/positions.test.ts b/tests/positions.test.ts index ca3839de..9a334fda 100644 --- a/tests/positions.test.ts +++ b/tests/positions.test.ts @@ -1,4 +1,4 @@ -import { expect, test } from "bun:test"; +import { expect, spyOn, test } from "bun:test"; import { WSOL_MINT } from "../src/utils/constants"; import { USDC_MINT, @@ -1033,6 +1033,38 @@ test("loadTokenPositionsForWallet reuses fills and prices across /start and Posi clearPositionSnapshot(); }); +test.each([ + [19_999, 1, 2], + [20_000, 2, 3], +] as const)( + "uses the expected price at the %i ms wallet cache boundary", + async (age, calls, mark) => { + const address = `position-cache-boundary-${age}`; + const start = 1_730_000_000_000; + const clock = spyOn(Date, "now").mockReturnValue(start); + const requested: string[][] = []; + const loader = { + walletAddress: address, + getHoldings: async () => [{ mint: TIMBA, ticker: "TIMBA", balance: 100, decimals: 6 }], + getSwaps: () => [swap({ amount_in: "1000000000", amount_out: "100000000" })], + fetchPricesUSD: async (mints: string[]) => { + requested.push(mints); + return { [WSOL_MINT]: 100, [TIMBA]: 1 + requested.length }; + }, + }; + try { + expect((await loadTokenPositionsForWallet(loader))[0]?.priceUsd).toBe(2); + clock.mockReturnValue(start + age); + const [position] = await loadTokenPositionsForWallet(loader); + expect(position?.priceUsd).toBe(mark); + expect(requested).toEqual(Array.from({ length: calls }, () => [WSOL_MINT, TIMBA])); + } finally { + clock.mockRestore(); + clearPositionSnapshot(address); + } + }, +); + test("loadTokenPositionsForWallet skips price requests when no swaps are tracked", async () => { clearPositionSnapshot(); let priceCalls = 0; From be4c6e35c3aa47d4ab2b458137d63d40bf211ae7 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 15:21:57 -0300 Subject: [PATCH 079/410] test(finance): verify ledger checkpoints and retention limits --- tests/finance-ledger.test.ts | 58 +++++++++++++++++++++ tests/transaction-history.test.ts | 85 +++++++++++++++++++++++++++++++ 2 files changed, 143 insertions(+) diff --git a/tests/finance-ledger.test.ts b/tests/finance-ledger.test.ts index 0acf3341..6064010e 100644 --- a/tests/finance-ledger.test.ts +++ b/tests/finance-ledger.test.ts @@ -44,6 +44,34 @@ describe("Jupiter referral ledger", () => { ).toBeNull(); expect(referralDeltaFromTransaction(transaction("125", "125"), ACCOUNT.toBase58())).toBeNull(); }); + + test.each([ + ["a newly funded account", false, true, 23n], + ["a closed account", true, false, -19n], + ] as const)( + "reads %s using the read-only lookup table index", + (_name, hasPre, hasPost, delta) => { + const data = transaction("19", "23"); + const unrelated = { + accountIndex: 1, + mint: OTHER.toBase58(), + uiTokenAmount: { amount: "400" }, + }; + const funds = (amount: string) => ({ + accountIndex: 2, + mint: MINT, + uiTokenAmount: { amount }, + }); + data.meta.loadedAddresses = { + writable: [new PublicKey(new Uint8Array(32).fill(7))], + readonly: [ACCOUNT], + }; + data.meta.preTokenBalances = hasPre ? [unrelated, funds("19")] : [unrelated]; + data.meta.postTokenBalances = hasPost ? [unrelated, funds("23")] : [unrelated]; + + expect(referralDeltaFromTransaction(data, ACCOUNT.toBase58())).toEqual({ mint: MINT, delta }); + }, + ); }); describe("incremental finance backfill", () => { @@ -239,6 +267,36 @@ describe("incremental finance backfill", () => { expect(history.events).toHaveLength(2); }); + test("does not recognize referral earnings from a failed transaction", async () => { + const history = createHistory(); + const connection = { + getSignaturesForAddress: async () => [{ signature: "failed", blockTime: 100, slot: 1 }], + getTransaction: async () => { + const failed = transaction("100", "125"); + failed.meta.err = { InstructionError: [0, { Custom: 1 }] }; + return failed; + }, + } as unknown as ConstructorParameters[0]; + const service = new FinanceLedgerService( + connection, + program, + history.store, + undefined, + referralReader, + { + requestDelayMs: 0, + }, + ); + + expect((await service.backfillNextBatch(0)).processedTransactions).toBe(1); + expect(history.events).toEqual([]); + expect(history.errors).toEqual([]); + expect(history.advances).toEqual([ + { signature: "failed", completed: false, processed: 1 }, + { signature: "failed", completed: true, processed: 0 }, + ]); + }); + test("keeps completed transaction progress when a later request is rate-limited", async () => { const history = createHistory(); const connection = { diff --git a/tests/transaction-history.test.ts b/tests/transaction-history.test.ts index 29586f46..079ebea1 100644 --- a/tests/transaction-history.test.ts +++ b/tests/transaction-history.test.ts @@ -187,6 +187,54 @@ describe("TransactionHistory query helpers", () => { TransactionHistory.resetForTesting(); }); + test("keeps a failed source checkpoint and moves to the oldest pending source", () => { + const history = TransactionHistory.getInstance(); + const clock = spyOn(Date, "now").mockReturnValue(1_000); + const source = { + sourceType: "program" as const, + address: "11111111111111111111111111111111", + startTimeMs: 123, + }; + const error = "x".repeat(500) + " not part of the stored error"; + try { + history.ensureFinanceBackfillSource({ ...source, sourceKey: "b" }); + history.ensureFinanceBackfillSource({ ...source, sourceKey: "a" }); + expect(history.getNextFinanceBackfillSource()?.sourceKey).toBe("a"); + + clock.mockReturnValue(2_000); + history.advanceFinanceBackfillSource("a", "checkpoint", false, 4); + history.recordFinanceBackfillError("a", error); + history.ensureFinanceBackfillSource({ ...source, sourceKey: "a", startTimeMs: 999 }); + expect(history.getFinanceBackfillProgress()).toEqual({ + totalSources: 2, + completedSources: 0, + processedTransactions: 4, + lastError: "x".repeat(500), + }); + expect(history.getNextFinanceBackfillSource()?.sourceKey).toBe("b"); + + clock.mockReturnValue(3_000); + history.advanceFinanceBackfillSource("b", "finished", true, 1); + expect(history.getNextFinanceBackfillSource()).toMatchObject({ + sourceKey: "a", + beforeSignature: "checkpoint", + startTimeMs: 123, + lastError: "x".repeat(500), + processedTransactions: 4, + }); + history.advanceFinanceBackfillSource("a", "recovered", true, 2); + expect(history.getNextFinanceBackfillSource()).toBeNull(); + expect(history.getFinanceBackfillProgress()).toEqual({ + totalSources: 2, + completedSources: 2, + processedTransactions: 7, + lastError: null, + }); + } finally { + clock.mockRestore(); + } + }); + test("TransactionHistory: query helpers and cleanup", () => { const db = TransactionHistory.getInstance(); const now = Date.now(); @@ -250,6 +298,43 @@ describe("TransactionHistory query helpers", () => { const removedNone = db.cleanOldTransactions(3650); expect(removedNone).toBe(0); }); + + test("keeps pending transactions and keeps completed ones at the exact 90-day limit", () => { + const history = TransactionHistory.getInstance(); + const now = 1_730_000_000_000; + const cutoff = now - 7_776_000_000; + const clock = spyOn(Date, "now").mockReturnValue(now); + try { + for (const [signature, offset, status] of [ + ["old-success", -1, "SUCCESS"], + ["old-failed", -2, "FAILED"], + ["old-pending", -3, "PENDING"], + ["at-limit", 0, "SUCCESS"], + ["after-limit", 1, "FAILED"], + ] as const) { + const transaction = createTransactionRecord( + "retention", + "BUY", + signature, + "SOL", + "TOK", + "1", + "2", + status, + ); + history.addTransaction({ ...transaction, timestamp: cutoff + offset }); + } + expect(history.cleanOldTransactions()).toBe(2); + expect(history.getUserHistory("retention").map(({ signature }) => signature)).toEqual([ + "after-limit", + "at-limit", + "old-pending", + ]); + expect(history.cleanOldTransactions()).toBe(0); + } finally { + clock.mockRestore(); + } + }); }); describe("TransactionHistory close", () => { From 26cb65f847825bf855a80be524e010267745dc32 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 15:25:55 -0300 Subject: [PATCH 080/410] fix(wallet): keep snapshot refreshes in their cache generation --- src/handlers/wallet-menu.ts | 31 +++++++--------- tests/wallet-menu.cache.test.ts | 66 ++++++++++++++++++++++++++++++++- 2 files changed, 79 insertions(+), 18 deletions(-) diff --git a/src/handlers/wallet-menu.ts b/src/handlers/wallet-menu.ts index 1f2e8054..dfe17814 100644 --- a/src/handlers/wallet-menu.ts +++ b/src/handlers/wallet-menu.ts @@ -157,7 +157,8 @@ export const createWalletMenuModule = (options: WalletMenuModuleOptions): Wallet { expiresAt: number; snapshot: WalletBalancesSnapshot } >(); const pendingWalletFetches = new Map>(); - const cacheInvalidations = new Map(); + // A clear starts a new generation even when the clock has not moved. + const cacheGenerations = new Map(); // Last fetched wallet page per user/endpoint, served instantly on the next // open while a background fetch refreshes it (stale-while-revalidate). const walletPageSnapshots = new Map(); @@ -214,7 +215,7 @@ export const createWalletMenuModule = (options: WalletMenuModuleOptions): Wallet deleteWalletPageSnapshots(cacheKey); pendingWalletFetches.delete(cacheKey); testKnownTokenOverrides.delete(telegramId.toString()); - cacheInvalidations.set(cacheKey, Date.now()); + cacheGenerations.set(cacheKey, Symbol()); }; wallet.onWalletCacheCleared((telegramId) => { @@ -289,7 +290,7 @@ export const createWalletMenuModule = (options: WalletMenuModuleOptions): Wallet const allowStaleOnError = staleNative !== undefined || (staleTokens?.length ?? 0) > 0; const fetchPromise = (async () => { - const fetchStart = Date.now(); + const generation = cacheGenerations.get(cacheKey); enforceWalletBudget(telegramId); try { let tokenCensus: WalletTokenCensus = { @@ -321,8 +322,7 @@ export const createWalletMenuModule = (options: WalletMenuModuleOptions): Wallet knownTokens, }; await pruneSoldHoldMarks(telegramId, tokenCensus); - const invalidatedAt = cacheInvalidations.get(cacheKey) ?? 0; - if (invalidatedAt < fetchStart) { + if (cacheGenerations.get(cacheKey) === generation) { walletSnapshotCache.set(cacheKey, { snapshot, expiresAt: Date.now() + walletRpcCacheTtlMs, @@ -353,8 +353,7 @@ export const createWalletMenuModule = (options: WalletMenuModuleOptions): Wallet tokenBalances: resolvedTokens, knownTokens, }; - const invalidatedAt = cacheInvalidations.get(cacheKey) ?? 0; - if (invalidatedAt < fetchStart) { + if (cacheGenerations.get(cacheKey) === generation) { walletSnapshotCache.set(cacheKey, { snapshot, expiresAt: Date.now() + walletRpcCacheTtlMs, @@ -415,8 +414,8 @@ export const createWalletMenuModule = (options: WalletMenuModuleOptions): Wallet * of reading the same balances again. */ const seedSnapshotFromPage = ( - telegramId: bigint, - fetchStart: number, + cacheKey: string, + generation: symbol | undefined, solBalance: number, tokenPage: Awaited>, knownTokens: WalletBalancesSnapshot["knownTokens"], @@ -432,8 +431,7 @@ export const createWalletMenuModule = (options: WalletMenuModuleOptions): Wallet return; } - const cacheKey = getCacheKey(telegramId); - if ((cacheInvalidations.get(cacheKey) ?? 0) >= fetchStart) { + if (cacheGenerations.get(cacheKey) !== generation) { return; } // Match getAllWalletTokenBalances ordering. @@ -469,10 +467,9 @@ export const createWalletMenuModule = (options: WalletMenuModuleOptions): Wallet requestedPage: number, pageSize: number, data: WalletPageData, - fetchStart: number, + generation: symbol | undefined, ) => { - const invalidatedAt = cacheInvalidations.get(cacheKey) ?? 0; - if (invalidatedAt >= fetchStart) return; + if (cacheGenerations.get(cacheKey) !== generation) return; const key = getPageSnapshotKey(cacheKey, requestedPage, pageSize); walletPageSnapshots.delete(key); walletPageSnapshots.set(key, { data, fetchedAt: data.fetchedAt }); @@ -487,8 +484,8 @@ export const createWalletMenuModule = (options: WalletMenuModuleOptions): Wallet page: number, pageSize: number, ): Promise => { - const fetchStart = Date.now(); const cacheKey = getCacheKey(telegramId); + const generation = cacheGenerations.get(cacheKey); enforceWalletBudget(telegramId); const tokenManager = getTokenManager(); const knownTokens = tokenManager ? tokenManager.getAllKnownTokensWithMetadata() : []; @@ -501,9 +498,9 @@ export const createWalletMenuModule = (options: WalletMenuModuleOptions): Wallet heldMints: tokenPage.heldMints ?? [], scannedMints: tokenPage.heldMints ?? [], }); - seedSnapshotFromPage(telegramId, fetchStart, solBalance, tokenPage, knownTokens); + seedSnapshotFromPage(cacheKey, generation, solBalance, tokenPage, knownTokens); const data: WalletPageData = { solBalance, ...tokenPage, fetchedAt: Date.now() }; - storeWalletPageSnapshot(cacheKey, page, pageSize, data, fetchStart); + storeWalletPageSnapshot(cacheKey, page, pageSize, data, generation); return data; }; diff --git a/tests/wallet-menu.cache.test.ts b/tests/wallet-menu.cache.test.ts index d0ee6399..2b1f482b 100644 --- a/tests/wallet-menu.cache.test.ts +++ b/tests/wallet-menu.cache.test.ts @@ -1,4 +1,4 @@ -import { describe, expect, mock, test } from "bun:test"; +import { describe, expect, mock, spyOn, test } from "bun:test"; import { createWalletMenuModule } from "../src/handlers/wallet-menu"; import { applyHoldMarks, createMemoryHoldMarkStore } from "../src/services/hold-marks"; import type { WalletTokenCensus } from "../src/utils/wallet"; @@ -95,6 +95,30 @@ const ensureBalanceCalled = (state: WalletState, expected: number) => expect(state.balanceCalls).toBe(expected); describe("wallet menu cache guards", () => { + test("only the fresh read can refill the cache when a clear and both reads share one millisecond", async () => { + const clock = spyOn(Date, "now").mockReturnValue(1_730_000_000_000); + const { wallet } = createStubWallet(); + const module = createModule(wallet); + const oldResult = Promise.withResolvers(); + const getBalance = mock(async () => 333); + getBalance.mockReturnValueOnce(oldResult.promise).mockResolvedValueOnce(222); + wallet.getBalance = getBalance; + const old = module.getCachedWalletData(1n); + try { + wallet.clearCachedWalletData(1n); + const fresh = await module.getCachedWalletData(1n); + expect(fresh.nativeSolBalance).toBe(222); + oldResult.resolve(111); + expect((await old).nativeSolBalance).toBe(111); + expect(await module.getCachedWalletData(1n)).toBe(fresh); + expect(getBalance).toHaveBeenCalledTimes(2); + } finally { + oldResult.resolve(111); + await Promise.allSettled([old]); + clock.mockRestore(); + } + }); + test("a superseded fetch cannot drop the newer fetch from the pending cache", async () => { const { wallet } = createStubWallet(); const module = createModule(wallet); @@ -384,6 +408,46 @@ describe("wallet page seeds the action-menu snapshot", () => { expect(snapshot.tokenBalances.map((entry) => entry.ticker)).toEqual(["AAA", "BBB"]); }); + test("a page read that starts right after a clear can fill both caches in the same millisecond", async () => { + const clock = spyOn(Date, "now").mockReturnValue(1_730_000_000_000); + const { module, state, getFullFetches } = createPageModule({ + tokenBalances: [], + heldMints: [], + complete: true, + page: 0, + pageCount: 1, + }); + try { + await module.clearWalletCache(1n); + const fresh = await module.getWalletPageData(1n, 0, 8); + expect(module.peekWalletPageData(1n, 0, 8)?.data).toBe(fresh); + expect((await module.getCachedWalletData(1n)).nativeSolBalance).toBe(1_000); + expect(getFullFetches()).toBe(0); + expect(state.balanceCalls).toBe(1); + } finally { + clock.mockRestore(); + } + }); + + test("a completed page cannot seed a cached wallet snapshot for a different RPC endpoint", async () => { + const page = { tokenBalances: [], heldMints: [], complete: true, page: 0, pageCount: 1 }; + const reply = Promise.withResolvers(); + const { wallet, state } = createStubWallet({ + endpoint: "rpc-a", + balanceValue: 111, + getWalletTokenBalancePage: () => reply.promise, + }); + const module = createModule(wallet, { holdMarks: createMemoryHoldMarkStore() }); + const previous = module.getWalletPageData(1n, 0, 8); + wallet.connection.rpcEndpoint = "rpc-b"; + state.balanceValue = 222; + reply.resolve(page); + expect((await previous).solBalance).toBe(111); + expect(module.peekWalletPageData(1n, 0, 8)).toBeUndefined(); + expect((await module.getCachedWalletData(1n)).nativeSolBalance).toBe(222); + expect(module.__test_getWalletSnapshotCacheKeys().sort()).toEqual(["1:rpc-a", "1:rpc-b"]); + }); + test("multi-page, incomplete or unknown-token pages still trigger a full fetch", async () => { const pages = [ { From e8d2a9ebf7e0ca97089c9987558bed58c65bd45f Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 15:26:40 -0300 Subject: [PATCH 081/410] test(wallet): pin message activity cache capacity and order --- tests/wallet-menu.page-snapshot.test.ts | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/tests/wallet-menu.page-snapshot.test.ts b/tests/wallet-menu.page-snapshot.test.ts index d25a4378..d463c146 100644 --- a/tests/wallet-menu.page-snapshot.test.ts +++ b/tests/wallet-menu.page-snapshot.test.ts @@ -278,7 +278,7 @@ describe("wallet menu caches and limits", () => { expect(module.peekWalletPageData(5_001n, 0, 8)).toBeDefined(); }); - test("views on messages evicted from the activity log are treated as stale", async () => { + test("the activity log keeps 5,000 messages and evicts the least recently touched view", async () => { const middlewares: Array<(ctx: any, next: () => Promise) => Promise> = []; const { wallet } = createStubWallet(); const module = createModule(wallet, { @@ -294,9 +294,16 @@ describe("wallet menu caches and limits", () => { await touch(0); const view = module.captureMessageView(1, 0); - for (let messageId = 1; messageId <= 5_000; messageId += 1) await touch(messageId); + for (let messageId = 1; messageId < 5_000; messageId += 1) await touch(messageId); + expect(view()).toBe(true); + const leastRecent = module.captureMessageView(1, 1); + await touch(0); expect(view()).toBe(false); + const refreshed = module.captureMessageView(1, 0); + await touch(5_000); + expect(leastRecent()).toBe(false); + expect(refreshed()).toBe(true); expect(module.captureMessageView(1, 5_000)()).toBe(true); }); }); From 83031493a00cba94248c1ccb452590acf963d6fe Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 15:29:44 -0300 Subject: [PATCH 082/410] fix(wallet): reject unrepresentable lamport fee budgets --- src/utils/fee-budget.ts | 4 ++-- tests/fee-budget.behavior.test.ts | 24 ++++++++++++++++++++++++ 2 files changed, 26 insertions(+), 2 deletions(-) diff --git a/src/utils/fee-budget.ts b/src/utils/fee-budget.ts index bae7c67a..3cacaf5e 100644 --- a/src/utils/fee-budget.ts +++ b/src/utils/fee-budget.ts @@ -275,7 +275,7 @@ export class FeeBudgetManager implements FeeBudgetProvider { const computation = (async () => { try { const value = await compute(); - if (Number.isFinite(value) && value > 0) { + if (Number.isSafeInteger(value) && value > 0) { this.cache.setWithTTL(key, value); return value; } @@ -361,7 +361,7 @@ export class FeeBudgetManager implements FeeBudgetProvider { const rawLamports = typeof fee === "number" ? fee : (fee?.value ?? null); const lamports = rawLamports === null ? null : Number(rawLamports); - if (typeof lamports === "number" && Number.isFinite(lamports) && lamports > 0) { + if (lamports !== null && Number.isSafeInteger(lamports) && lamports > 0) { return lamports; } } catch (error) { diff --git a/tests/fee-budget.behavior.test.ts b/tests/fee-budget.behavior.test.ts index baec6e74..49c7ce45 100644 --- a/tests/fee-budget.behavior.test.ts +++ b/tests/fee-budget.behavior.test.ts @@ -183,6 +183,30 @@ test.each([ expect(await manager.getSingleTransactionLamports()).toBe(100 + priority); }); +test.each([ + [0n, 37], + [100n, 100], + [9_007_199_254_740_993n, 37], +] as const)("uses a safe whole lamport fee when the RPC returns %p", async (fee, expected) => { + const { connection } = connectionFor(fee); + const manager = FeeBudgetManager.createForTest(connection, { + fallbackSingleTxLamports: 37, + singleTxMultiplier: 1, + singleTxExtraLamports: 0, + }); + expect(await manager.getSingleTransactionLamports()).toBe(expected); +}); + +test("falls back if a valid base fee overflows when the safety multiplier is applied", async () => { + const { connection } = connectionFor(9_007_199_254_740_991n); + const manager = FeeBudgetManager.createForTest(connection, { + fallbackSingleTxLamports: 37, + singleTxMultiplier: 2, + singleTxExtraLamports: 0, + }); + expect(await manager.getSingleTransactionLamports()).toBe(37); +}); + test("logs a failed estimate and still applies the multiplier to the fallback base fee", async () => { const { connection, getFee } = connectionFor(); const outage = new Error("fee RPC down"); From a006630d0a056ba6dd73c52f722f2b1677720bfa Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 15:31:09 -0300 Subject: [PATCH 083/410] test(evm): verify proposal expiry and isolated wallet routes --- src/evm/bot.test.ts | 46 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) diff --git a/src/evm/bot.test.ts b/src/evm/bot.test.ts index adf2f439..68d1df49 100644 --- a/src/evm/bot.test.ts +++ b/src/evm/bot.test.ts @@ -457,6 +457,26 @@ describe("EVM wallet commands", () => { expect(h.store.action(action.id)!.phase).toBe("failed"); }); + test.each([ + [300_000, "new"], + [300_001, "failed"], + ] as const)("an unsigned withdrawal has the expected state at %i ms", async (age, phase) => { + const start = 1_730_000_000_000; + const clock = spyOn(Date, "now").mockReturnValue(start); + try { + useEvm(); + await h.text(`/withdraw ${recipient} 1 ETH`); + const markup = h.calls.filter(({ method }) => method === "editMessageReplyMarkup").at(-1); + const confirm = markup?.payload.reply_markup.inline_keyboard[0][0].callback_data; + if (!confirm) throw new Error("Expected a withdrawal confirmation button"); + clock.mockReturnValue(start + age); + await h.click(confirm); + expect(h.store.action(confirm.split(":")[2])).toMatchObject({ phase, raw: null, hash: null }); + } finally { + clock.mockRestore(); + } + }); + test("a busy wallet cannot confirm another withdrawal", async () => { useEvm(); await h.text(`/withdraw ${recipient} 1 ETH`); @@ -621,6 +641,32 @@ describe("EVM game commands", () => { }); }); + test("accepts two-digit giveaway limits while an unrelated wallet is busy", async () => { + useEvm(); + h.store.add({ + id: "another-wallet", + user: "2", + chat: 2, + message: 56, + kind: "join", + body: "{}", + phase: "new", + raw: null, + hash: null, + }); + await h.text(`/ga 2\t${usdcAddress} 12 private`); + const action = h.store.pending().find(({ user }) => user === "1"); + if (!action) throw new Error("Expected a giveaway to be queued for the requesting wallet"); + expect(JSON.parse(action.body)).toMatchObject({ + token: usdcAddress, + amount: "2000000", + gameType: 1, + maxPlayers: 12, + isPrivate: true, + timeout: 3_600, + }); + }); + test("invalid game input shows usage", async () => { useEvm(); await h.text("/cf 0.0000001 USDC"); From 92564b7759b6b74c6967444b82c0e1d5a37900be Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 15:35:41 -0300 Subject: [PATCH 084/410] refactor(rpc): keep deadline and pacing checks observable --- src/utils/rpc-request-budget.ts | 16 ++++------ tests/helpers/timers.ts | 10 ++++++ tests/rpc-request-budget.happy-path.test.ts | 34 ++++++++++++++++++--- tests/rpc-request-budget.test.ts | 7 +++-- 4 files changed, 50 insertions(+), 17 deletions(-) diff --git a/src/utils/rpc-request-budget.ts b/src/utils/rpc-request-budget.ts index da0f34e7..16ac64d9 100644 --- a/src/utils/rpc-request-budget.ts +++ b/src/utils/rpc-request-budget.ts @@ -74,7 +74,7 @@ export async function backgroundRpc( signal.throwIfAborted(); if (lane.cooldown > Date.now()) throw new RpcRetryLaterError("Recovery RPC is cooling down", lane.cooldown); - while (foregroundRequests > 0 || lane.next > Date.now()) { + while (Date.now() < lane.next || foregroundRequests > 0) { await delay(Math.max(10, Math.min(50, lane.next - Date.now())), signal); } signal.throwIfAborted(); @@ -91,15 +91,11 @@ export async function backgroundRpc( export async function boundedRpc(request: () => Promise, timeoutMs: number): Promise { let timer: ReturnType | undefined; try { - return await Promise.race([ - request(), - new Promise((_, reject) => { - timer = setTimeout( - () => reject(new Error("RPC request timed out")), - Math.max(1, timeoutMs), - ); - }), - ]); + const response = Promise.resolve(request()); + const { promise, resolve, reject } = Promise.withResolvers(); + timer = setTimeout(() => reject(new Error("RPC request timed out")), Math.max(1, timeoutMs)); + void response.then(resolve, reject); + return await promise; } finally { clearTimeout(timer); } diff --git a/tests/helpers/timers.ts b/tests/helpers/timers.ts index 6b178880..26b97a85 100644 --- a/tests/helpers/timers.ts +++ b/tests/helpers/timers.ts @@ -1,3 +1,5 @@ +import { spyOn } from "bun:test"; + /** * Collapses every `setTimeout` delay to 0ms so retry/backoff/poll sleeps in the * code under test do not burn wall-clock time. Callbacks still run @@ -19,3 +21,11 @@ export const stubInstantTimers = () => { }, }; }; +export function mockDateNowWithReadLimit(readNow: () => number, maxReads = 1_000) { + let reads = 0; + return spyOn(Date, "now").mockImplementation(() => { + reads += 1; + if (reads > maxReads) throw new Error("Polling exceeded the fake clock read limit"); + return readNow(); + }); +} diff --git a/tests/rpc-request-budget.happy-path.test.ts b/tests/rpc-request-budget.happy-path.test.ts index a7a64eef..690e47b1 100644 --- a/tests/rpc-request-budget.happy-path.test.ts +++ b/tests/rpc-request-budget.happy-path.test.ts @@ -6,6 +6,7 @@ import { foregroundRpc, noteRpcRateLimit, } from "../src/utils/rpc-request-budget"; +import { mockDateNowWithReadLimit } from "./helpers/timers"; describe("backgroundRpc", () => { test("runs the request and returns its result when idle", async () => { @@ -64,8 +65,8 @@ describe("backgroundRpc", () => { test("paces two API keys on the same host at 500ms after a failed request", async () => { vi.useFakeTimers(); - let now = 0; - const clock = spyOn(Date, "now").mockImplementation(() => now); + let now = 1_000; + const clock = mockDateNowWithReadLimit(() => now); const controller = new AbortController(); const hits: Array = []; const waitForTick = async () => { @@ -97,13 +98,13 @@ describe("backgroundRpc", () => { now += 49; vi.advanceTimersByTime(49); await waitForTick(); - expect(hits).toEqual([["other host", 0]]); + expect(hits).toEqual([["other host", 1_000]]); now += 1; vi.advanceTimersByTime(1); await waitForTick(); expect(hits).toEqual([ - ["other host", 0], - ["same host", 500], + ["other host", 1_000], + ["same host", 1_500], ]); } finally { controller.abort(); @@ -153,6 +154,29 @@ test("bounded RPC stops hanging reads and clears a completed read's timer", asyn } }); +test("bounded RPC preserves both synchronous and asynchronous provider errors", async () => { + vi.useFakeTimers(); + const failure = new Error("provider disconnected"); + try { + const outcomes: unknown[] = []; + void boundedRpc(() => { + throw failure; + }, 2_000).then( + (value) => outcomes.push(value), + (error: unknown) => outcomes.push(error), + ); + void boundedRpc(() => Promise.reject(failure), 2_000).then( + (value) => outcomes.push(value), + (error: unknown) => outcomes.push(error), + ); + for (let step = 0; step < 8; step += 1) await Promise.resolve(); + expect(outcomes).toEqual([failure, failure]); + expect(vi.getTimerCount()).toBe(0); + } finally { + vi.useRealTimers(); + } +}); + test("a failed foreground request releases the background lane", async () => { const controller = new AbortController(); vi.useFakeTimers(); diff --git a/tests/rpc-request-budget.test.ts b/tests/rpc-request-budget.test.ts index 9f07f99d..20c1fd4e 100644 --- a/tests/rpc-request-budget.test.ts +++ b/tests/rpc-request-budget.test.ts @@ -1,5 +1,6 @@ -import { expect, spyOn, test, vi } from "bun:test"; +import { expect, test, vi } from "bun:test"; import { backgroundRpc, foregroundRpc, noteRpcRateLimit } from "../src/utils/rpc-request-budget"; +import { mockDateNowWithReadLimit } from "./helpers/timers"; const flushTasks = async () => { for (let step = 0; step < 12; step += 1) await Promise.resolve(); @@ -7,7 +8,7 @@ const flushTasks = async () => { test("background waits for foreground and rechecks shared-host cooldown", async () => { vi.useFakeTimers(); - const now = spyOn(Date, "now").mockReturnValue(1_000); + const now = mockDateNowWithReadLimit(() => 1_000); const gate = Promise.withResolvers(); const controller = new AbortController(); const outcomes: unknown[] = []; @@ -47,6 +48,7 @@ test("aborted background work never calls the provider", async () => { }); test("aborting while background work waits for foreground traffic rejects without calling", async () => { vi.useFakeTimers(); + const now = mockDateNowWithReadLimit(() => 1_000); const gate = Promise.withResolvers(); const controller = new AbortController(); const reason = new Error("scan cancelled"); @@ -68,6 +70,7 @@ test("aborting while background work waits for foreground traffic rejects withou controller.abort(); gate.resolve(); await foreground; + now.mockRestore(); vi.useRealTimers(); } }); From b3feae19d6a93fb4d293e9f48a2132c4f7d8916e Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 15:40:21 -0300 Subject: [PATCH 085/410] fix(rpc): bound malformed retry-after deadlines --- src/utils/rpc-request-budget.ts | 7 +++++-- tests/rpc-request-budget.happy-path.test.ts | 21 ++++++++++++++++++++- 2 files changed, 25 insertions(+), 3 deletions(-) diff --git a/src/utils/rpc-request-budget.ts b/src/utils/rpc-request-budget.ts index 16ac64d9..1186564a 100644 --- a/src/utils/rpc-request-budget.ts +++ b/src/utils/rpc-request-budget.ts @@ -28,11 +28,14 @@ export function noteRpcRateLimit( ): number { const seconds = retryAfter == null ? NaN : Number(retryAfter); const date = retryAfter == null ? NaN : Date.parse(retryAfter); - const retryAt = Number.isFinite(seconds) + const fallback = now + 5_000; + const requestedRetryAt = Number.isFinite(seconds) ? now + Math.max(1, seconds) * 1000 : Number.isFinite(date) ? Math.max(now + 1000, date) - : now + 5000; + : fallback; + // An unrepresentable deadline must not poison this host's cooldown indefinitely. + const retryAt = Number.isSafeInteger(Math.ceil(requestedRetryAt)) ? requestedRetryAt : fallback; const lane = laneFor(endpoint); lane.cooldown = Math.max(lane.cooldown, retryAt); return lane.cooldown; diff --git a/tests/rpc-request-budget.happy-path.test.ts b/tests/rpc-request-budget.happy-path.test.ts index 690e47b1..c4c926f0 100644 --- a/tests/rpc-request-budget.happy-path.test.ts +++ b/tests/rpc-request-budget.happy-path.test.ts @@ -120,12 +120,31 @@ test.each([ ["malformed", "later", 6_000], ["zero", "0", 2_000], ["a past date", "Thu, 01 Jan 1970 00:00:00 GMT", 2_000], -] as const)("a %s Retry-After uses the documented safe delay", (name, input, expected) => { + ["unrepresentable deadline", "9007199254740", 6_000], + ["overflowing delay", "1e308", 6_000], +] as const)("uses the safe Retry-After delay for %s", (name, input, expected) => { expect( noteRpcRateLimit(`https://retry-${name.replaceAll(" ", "-")}.test/fixture`, input, 1_000), ).toBe(expected); }); +test("an overflowing Retry-After cannot permanently block the RPC host", async () => { + const clock = spyOn(Date, "now").mockReturnValue(1_000); + const endpoint = "https://recover-invalid-retry.test/key"; + const signal = new AbortController().signal; + try { + expect(noteRpcRateLimit(endpoint, "1e308")).toBe(6_000); + clock.mockReturnValue(5_999); + await expect(backgroundRpc(endpoint, signal, async () => "too early")).rejects.toThrow( + "Recovery RPC is cooling down", + ); + clock.mockReturnValue(6_000); + expect(await backgroundRpc(endpoint, signal, async () => "available")).toBe("available"); + } finally { + clock.mockRestore(); + } +}); + test("bounded RPC stops hanging reads and clears a completed read's timer", async () => { vi.useFakeTimers(); const never = Promise.withResolvers(); From 1dd126b806d1ae16bde8d299acbc3d89562fd700 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 15:43:53 -0300 Subject: [PATCH 086/410] fix(telegram): guard media retries against timer overflow --- src/services/buy-alerts/pool-trades.ts | 2 +- src/utils/media.ts | 33 +++----------- src/utils/retry-delay.ts | 7 +++ src/utils/telegram-errors.ts | 13 +++--- tests/media.retry.test.ts | 60 ++++++++++++++++++++++++++ tests/telegram-errors.test.ts | 10 +++++ 6 files changed, 90 insertions(+), 35 deletions(-) create mode 100644 src/utils/retry-delay.ts diff --git a/src/services/buy-alerts/pool-trades.ts b/src/services/buy-alerts/pool-trades.ts index 6a2847ec..53f8c242 100644 --- a/src/services/buy-alerts/pool-trades.ts +++ b/src/services/buy-alerts/pool-trades.ts @@ -1,5 +1,6 @@ import { z } from "zod"; import { WSOL_MINT } from "../../utils/constants"; +import { MAX_TIMER_DELAY_MS } from "../../utils/retry-delay"; import { fetchDexScreenerPoolStats } from "./dexscreener"; import { mapDexFromPool } from "./parser"; import type { BuyEvent, BuyFeed, PairStats } from "./types"; @@ -12,7 +13,6 @@ const GECKO_MIN_REQUEST_INTERVAL_MS = 10_000; const GECKO_DEFAULT_RATE_LIMIT_COOLDOWN_MS = 60_000; const GECKO_MAX_RATE_LIMIT_COOLDOWN_MS = 15 * 60_000; const GECKO_RATE_LIMIT_LOG_INTERVAL_MS = 60_000; -const MAX_TIMER_DELAY_MS = 2 ** 31 - 1; export const POOL_TRADE_POLL_MS = GECKO_MIN_REQUEST_INTERVAL_MS; export const MAX_SEEN_SIGNATURES_PER_MINT = 400; diff --git a/src/utils/media.ts b/src/utils/media.ts index 629907ab..cf6dd45e 100644 --- a/src/utils/media.ts +++ b/src/utils/media.ts @@ -2,7 +2,8 @@ * Utility helpers for dealing with Telegram media operations. */ -import { getErrorDescription, isMessageNotModified } from "./telegram-errors"; +import { getErrorDescription, getRetryAfterSeconds, isMessageNotModified } from "./telegram-errors"; +import { MAX_TIMER_DELAY_MS } from "./retry-delay"; const isTooManyRequestsError = (error: any): boolean => { if (!error || typeof error !== "object") return false; @@ -14,30 +15,6 @@ const isTooManyRequestsError = (error: any): boolean => { return description.toLowerCase().includes("too many requests"); }; -const parseRetryAfterSeconds = (error: any): number => { - if (!error || typeof error !== "object") return 1; - - const parameters = (error as any).parameters; - const retryAfter = - (parameters && typeof parameters.retry_after === "number" - ? parameters.retry_after - : undefined) ?? - (typeof (error as any).retry_after === "number" ? (error as any).retry_after : undefined); - - if (typeof retryAfter === "number" && Number.isFinite(retryAfter)) { - return Math.max(0, retryAfter); - } - - const description = getErrorDescription(error); - const match = description.match(/retry after (\d+)/i); - if (match) { - // The capture group only matches digits, so the parsed value is always a non-negative integer. - return Number.parseInt(match[1]!, 10); - } - - return 1; -}; - const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, Math.max(0, ms))); type QueuedEditResult = { @@ -116,8 +93,10 @@ export const awaitTelegramRetry = async ( throw error; } - const delaySeconds = parseRetryAfterSeconds(error); - await sleep(delaySeconds * 1000); + const delayMs = (getRetryAfterSeconds(error) ?? 1) * 1_000; + // Do not retry early when the provider's delay exceeds the native timer range. + if (delayMs > MAX_TIMER_DELAY_MS) throw error; + await sleep(delayMs); } } }; diff --git a/src/utils/retry-delay.ts b/src/utils/retry-delay.ts new file mode 100644 index 00000000..21fe0bfd --- /dev/null +++ b/src/utils/retry-delay.ts @@ -0,0 +1,7 @@ +export const MAX_TIMER_DELAY_MS = 2 ** 31 - 1; + +/** A provider duration must be representable before it can become a deadline. */ +export function retrySecondsToMilliseconds(seconds: number): number | null { + const milliseconds = seconds * 1_000; + return milliseconds >= 0 && Number.isSafeInteger(Math.ceil(milliseconds)) ? milliseconds : null; +} diff --git a/src/utils/telegram-errors.ts b/src/utils/telegram-errors.ts index 2657ef85..854ef078 100644 --- a/src/utils/telegram-errors.ts +++ b/src/utils/telegram-errors.ts @@ -1,3 +1,5 @@ +import { retrySecondsToMilliseconds } from "./retry-delay"; + const getErrorString = (value: unknown): string => { if (typeof value === "string") { return value; @@ -95,17 +97,14 @@ export const getRetryAfterSeconds = (error: unknown): number | null => { (typeof (error as any).retry_after === "number" ? (error as any).retry_after : undefined); if (typeof retryAfter === "number" && Number.isFinite(retryAfter)) { - return Math.max(0, retryAfter); + const seconds = Math.max(0, retryAfter); + if (retrySecondsToMilliseconds(seconds) !== null) return seconds; } const description = getErrorString(error); const match = description.match(/retry after (\d+)/i); - if (match) { - // The capture group only matches digits, so the parsed value is always a non-negative integer. - return Number.parseInt(match[1]!, 10); - } - - return null; + const seconds = Number.parseInt(match?.[1] ?? "", 10); + return retrySecondsToMilliseconds(seconds) === null ? null : seconds; }; export const shouldFallbackToReply = (error: unknown): boolean => diff --git a/tests/media.retry.test.ts b/tests/media.retry.test.ts index d340cf05..a0146734 100644 --- a/tests/media.retry.test.ts +++ b/tests/media.retry.test.ts @@ -11,6 +11,66 @@ import { const originalSetTimeout = setTimeout; describe("media retry helpers", () => { + test("does not schedule a media retry beyond the native timer range", async () => { + vi.useFakeTimers(); + const error = Object.assign(new Error("Too Many Requests"), { + error_code: 429, + parameters: { retry_after: 2_147_483.648 }, + }); + const outcomes: unknown[] = []; + let attempts = 0; + try { + void awaitTelegramRetry(async () => { + attempts += 1; + throw error; + }).then( + (value) => outcomes.push(value), + (failure: unknown) => outcomes.push(failure), + ); + for (let step = 0; step < 8; step += 1) await Promise.resolve(); + expect(attempts).toBe(1); + expect(vi.getTimerCount()).toBe(0); + expect(outcomes).toEqual([error]); + } finally { + vi.clearAllTimers(); + vi.useRealTimers(); + } + }); + + test("waits for the full delay at the native timer limit", async () => { + vi.useFakeTimers(); + const error = Object.assign(new Error("Too Many Requests"), { + error_code: 429, + parameters: { retry_after: 2_147_483.647 }, + }); + const outcomes: unknown[] = []; + let attempts = 0; + const flush = async () => { + for (let step = 0; step < 8; step += 1) await Promise.resolve(); + }; + try { + void awaitTelegramRetry(async () => { + attempts += 1; + if (attempts === 1) throw error; + return "sent"; + }).then( + (result) => outcomes.push(result), + (failure: unknown) => outcomes.push(failure), + ); + await flush(); + vi.advanceTimersByTime(2_147_483_646); + await flush(); + expect(attempts).toBe(1); + vi.advanceTimersByTime(1); + await flush(); + expect(attempts).toBe(2); + expect(outcomes).toEqual(["sent"]); + } finally { + vi.clearAllTimers(); + vi.useRealTimers(); + } + }); + test("awaitTelegramRetry stops when error not retryable", async () => { let attempts = 0; const error = new Error("forbidden"); diff --git a/tests/telegram-errors.test.ts b/tests/telegram-errors.test.ts index 5ddfdb32..6a00fdbd 100644 --- a/tests/telegram-errors.test.ts +++ b/tests/telegram-errors.test.ts @@ -127,6 +127,16 @@ describe("telegram error helpers", () => { expect(getRetryAfterSeconds("retry after 9")).toBeNull(); }); + test("rejects Retry-After hints that cannot be represented in milliseconds", () => { + expect(getRetryAfterSeconds({ parameters: { retry_after: 1e308 } })).toBeNull(); + expect( + getRetryAfterSeconds({ description: `Too Many Requests: retry after ${"9".repeat(35)}` }), + ).toBeNull(); + expect( + getRetryAfterSeconds({ retry_after: 1e308, description: "Too Many Requests: retry after 7" }), + ).toBe(7); + }); + test("prefers the structured delay, keeps zero, and reads the whole fallback delay", () => { const description = "Too Many Requests: retry after 123"; expect( From 30abd738c02b2d33e723a2c881c57d3332d14d16 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 15:45:26 -0300 Subject: [PATCH 087/410] fix(telegram): preserve cooldowns when retry hints are invalid --- src/utils/telegram-rate-limiter.ts | 27 ++++++++++------ tests/telegram-rate-limiter.test.ts | 49 ++++++++++++++++++++++++++++- 2 files changed, 65 insertions(+), 11 deletions(-) diff --git a/src/utils/telegram-rate-limiter.ts b/src/utils/telegram-rate-limiter.ts index 24832a13..36be80fd 100644 --- a/src/utils/telegram-rate-limiter.ts +++ b/src/utils/telegram-rate-limiter.ts @@ -5,6 +5,8 @@ * Implements per-chat throttling and callback answer queuing. */ +import { MAX_TIMER_DELAY_MS, retrySecondsToMilliseconds } from "./retry-delay"; + // ================================ // Constants // ================================ @@ -206,8 +208,11 @@ export class TelegramRateLimiter { * Record a rate limit error and set the blocked period. */ recordRateLimit(retryAfterSeconds: number, chatId?: number): void { - const retryAfterMs = Math.max(0, retryAfterSeconds * 1000); + if (!Number.isFinite(retryAfterSeconds)) return; + const retryAfterMs = retrySecondsToMilliseconds(Math.max(0, retryAfterSeconds)); + if (retryAfterMs === null) return; const blockedUntil = Date.now() + retryAfterMs; + if (!Number.isSafeInteger(Math.ceil(blockedUntil))) return; if (chatId !== undefined) { this.chatStates.set(chatId, { retryAfterMs, blockedUntil }); @@ -248,11 +253,11 @@ export class TelegramRateLimiter { fn: () => Promise, options: { maxWait?: number } = {}, ): Promise { - const maxWait = options.maxWait ?? DEFAULT_RATE_LIMIT_TIMEOUT_MS; + const maxWait = Math.min(options.maxWait ?? DEFAULT_RATE_LIMIT_TIMEOUT_MS, MAX_TIMER_DELAY_MS); const waitTime = this.getWaitTimeMs(chatId); if (waitTime > 0) { - if (waitTime > maxWait) { + if (!(waitTime <= maxWait)) { throw new Error( `Rate limited for ${Math.ceil(waitTime / 1000)}s, exceeds max wait of ${Math.ceil(maxWait / 1000)}s`, ); @@ -420,18 +425,20 @@ export const extractRetryAfter = (error: unknown): number | null => { // Check for GrammyError pattern if ("parameters" in error) { const params = (error as any).parameters; - if (params && typeof params.retry_after === "number") { - return params.retry_after; + const seconds = params?.retry_after; + if ( + typeof seconds === "number" && + Number.isFinite(seconds) && + retrySecondsToMilliseconds(Math.max(0, seconds)) !== null + ) { + return seconds; } } // Try to parse from message const match = error.message.match(/retry after (\d+)/i); - if (match && match[1]) { - return parseInt(match[1], 10); - } - - return null; + const seconds = Number.parseInt(match?.[1] ?? "", 10); + return retrySecondsToMilliseconds(seconds) === null ? null : seconds; }; /** diff --git a/tests/telegram-rate-limiter.test.ts b/tests/telegram-rate-limiter.test.ts index 8b225684..f1182401 100644 --- a/tests/telegram-rate-limiter.test.ts +++ b/tests/telegram-rate-limiter.test.ts @@ -1,7 +1,7 @@ /** * Tests for Telegram Rate Limiter utilities */ -import { describe, test, expect, beforeEach } from "bun:test"; +import { describe, test, expect, beforeEach, spyOn, vi } from "bun:test"; import { TelegramRateLimiter, CallbackAnswerQueue, @@ -74,6 +74,21 @@ describe("TelegramRateLimiter", () => { expect(limiter.isLimited(123)).toBe(true); expect(limiter.isLimited()).toBe(true); }); + + test("an invalid provider delay does not overwrite an existing chat cooldown", () => { + const clock = spyOn(Date, "now").mockReturnValue(1_000); + try { + limiter.recordRateLimit(5, 123); + for (const invalid of [Infinity, NaN, 1e308]) { + limiter.recordRateLimit(invalid, 123); + expect(limiter.getWaitTimeMs(123)).toBe(5_000); + } + clock.mockReturnValue(6_000); + expect(limiter.isLimited(123)).toBe(false); + } finally { + clock.mockRestore(); + } + }); }); describe("clearLimit", () => { @@ -115,6 +130,30 @@ describe("TelegramRateLimiter", () => { ); }); + test("does not start work early when a configured wait exceeds the native timer range", async () => { + vi.useFakeTimers(); + const clock = spyOn(Date, "now").mockReturnValue(1_000); + const outcomes: unknown[] = []; + try { + limiter.recordRateLimit(2_147_483.648, 123); + void limiter + .throttle(123, async () => "not yet", { maxWait: Number.MAX_SAFE_INTEGER }) + .then( + (result) => outcomes.push(result), + (error: unknown) => outcomes.push(error), + ); + await Promise.resolve(); + expect(vi.getTimerCount()).toBe(0); + expect(outcomes).toEqual([ + expect.objectContaining({ message: expect.stringContaining("exceeds max wait") }), + ]); + } finally { + clock.mockRestore(); + vi.clearAllTimers(); + vi.useRealTimers(); + } + }); + test("waits when limited but within maxWait", async () => { limiter.recordRateLimit(0.05, 123); // 50ms const start = Date.now(); @@ -421,6 +460,14 @@ describe("Error helpers", () => { expect(extractRetryAfter(new Error("No retry info"))).toBe(null); }); + test("ignores numbers too large for a retry duration and uses a valid message hint", () => { + const error = Object.assign(new Error("retry after 7"), { + parameters: { retry_after: 1e308 }, + }); + expect(extractRetryAfter(error)).toBe(7); + expect(extractRetryAfter(new Error(`retry after ${"9".repeat(35)}`))).toBeNull(); + }); + test("returns null for non-Error objects", () => { expect(extractRetryAfter("string")).toBe(null); }); From c99b09574aa2b07aea238aca68b561de60e80195 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 15:47:51 -0300 Subject: [PATCH 088/410] fix(bot): honor long Telegram cooldowns on game card updates --- src/bot.ts | 11 +++++++ tests/game-message-debounce.test.ts | 46 +++++++++++++++++++++++++++-- 2 files changed, 54 insertions(+), 3 deletions(-) diff --git a/src/bot.ts b/src/bot.ts index 7cdcdb48..2b00ec45 100644 --- a/src/bot.ts +++ b/src/bot.ts @@ -197,6 +197,7 @@ import { getRetryAfterSeconds, isMessageNotModified, isRateLimited } from "./uti import { FaucetDatabase } from "./utils/faucet-database"; import { outboundErrorGuard } from "./utils/outbound-error-guard"; import { sendMediaWithFallback } from "./utils/media"; +import { MAX_TIMER_DELAY_MS } from "./utils/retry-delay"; import { isMintDecimals } from "./utils/token-decimals"; export type { CreateGameViaCommandOptions } from "./handlers/game-commands"; @@ -1957,6 +1958,16 @@ const scheduleGameMessageUpdate = ( ); state.nextDelayMs = undefined; + if (delayMs > MAX_TIMER_DELAY_MS) { + // Keep the pending update without giving the timer an out-of-range delay. + state.nextDelayMs = delayMs - MAX_TIMER_DELAY_MS; + state.timer = setTimeout(() => { + state.timer = undefined; + scheduleGameMessageUpdate(gameAddress, state.referenceChatId, state.latestTotalPot); + }, MAX_TIMER_DELAY_MS); + return; + } + // cancelPendingGameMessageUpdate() clears this timer, so it only fires for a // pending, non-cancelled update. state.timer = setTimeout(async () => { diff --git a/tests/game-message-debounce.test.ts b/tests/game-message-debounce.test.ts index 89d815ae..401ca6e6 100644 --- a/tests/game-message-debounce.test.ts +++ b/tests/game-message-debounce.test.ts @@ -1,6 +1,6 @@ -import { afterEach, beforeEach, describe, expect, mock, spyOn, test } from "bun:test"; +import { afterEach, beforeEach, describe, expect, mock, spyOn, test, vi } from "bun:test"; import BN from "bn.js"; -import { Keypair } from "#solana"; +import { Keypair, PublicKey } from "#solana"; import { botModule, callsTo, @@ -67,7 +67,7 @@ afterEach(() => { }); const joinEvent = async (totalAmount: unknown = new BN(2_500)) => ({ - gameKey: { toString: () => gameAddress }, + gameKey: new PublicKey(gameAddress), player: (await Keypair.generate()).publicKey, totalAmount, ticketsCount: 1, @@ -79,6 +79,46 @@ const joinEvent = async (totalAmount: unknown = new BN(2_500)) => ({ const settle = () => Bun.sleep(15); describe("debounced game message updates", () => { + test.each([ + [1.5, 1_500], + [2_147_483.648, 2_147_483_648], + ] as const)( + "does not rerender before the full %p second Telegram cooldown", + async (retryAfter, delayMs) => { + const event = { ...(await joinEvent()), totalAmount: new BN(2_500) }; + const latest = { ...event, totalAmount: new BN(4_500) }; + const failure = Object.assign(new Error("Too Many Requests"), { + error_code: 429, + parameters: { retry_after: retryAfter }, + }); + vi.useFakeTimers(); + const flush = async () => { + for (let step = 0; step < 8; step += 1) await Promise.resolve(); + }; + try { + updates.mockRejectedValueOnce(failure); + await botModule.__test_processPlayerEvent(event, "PlayerRefunded", [target]); + vi.advanceTimersByTime(1); + await flush(); + expect(updates).toHaveBeenCalledTimes(1); + + await botModule.__test_processPlayerEvent(latest, "PlayerRefunded", [target]); + vi.advanceTimersByTime(delayMs - 1); + await flush(); + expect(updates).toHaveBeenCalledTimes(1); + vi.advanceTimersByTime(1); + await flush(); + + expect(updates).toHaveBeenCalledTimes(2); + expect(updates.mock.calls[1]?.slice(1)).toEqual([gameAddress, "Active", undefined, 4_500]); + } finally { + botModule.__test_clearPendingGameMessageUpdates(); + vi.clearAllTimers(); + vi.useRealTimers(); + } + }, + ); + test("an active game refreshes with the latest pot", async () => { await botModule.__test_processPlayerEvent((await joinEvent()) as any, "PlayerRefunded", [ target, From 01308a7ab5ea3da689448236f5f4cacc973716cf Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 15:53:31 -0300 Subject: [PATCH 089/410] test(swaps): advance the token account polling deadline --- tests/swap-manager.token-account-wait.test.ts | 133 +++++++++++------- 1 file changed, 81 insertions(+), 52 deletions(-) diff --git a/tests/swap-manager.token-account-wait.test.ts b/tests/swap-manager.token-account-wait.test.ts index b0302b62..3dfd5914 100644 --- a/tests/swap-manager.token-account-wait.test.ts +++ b/tests/swap-manager.token-account-wait.test.ts @@ -1,22 +1,40 @@ -import { describe, expect, spyOn, test, vi } from "bun:test"; +import { describe, expect, test, vi } from "bun:test"; import { Keypair, PublicKey } from "#solana"; import { SwapManager } from "../src/utils/swap-manager"; +import { mockDateNowWithReadLimit } from "./helpers/timers"; const WSOL = "So11111111111111111111111111111111111111112"; -const createSwapManager = (connection: any, walletOverrides: Record = {}) => { +const createSwapManager = ( + connection: any, + walletOverrides: Record = {}, + advanceClock?: (milliseconds: number) => void, +) => { const wallet = { getConnection: () => connection, ...walletOverrides } as any; const sm = new SwapManager(connection, wallet, {} as any); const sleeps: number[] = []; Reflect.set(sm, "sleep", async (ms: number) => { sleeps.push(ms); + advanceClock?.(ms); }); return { sm, sleeps, wallet }; }; +const mockPollingClock = () => { + let now = 1_000_000; + const clock = mockDateNowWithReadLimit(() => now); + return { + advance: (ms: number) => { + now += ms; + }, + restore: () => clock.mockRestore(), + }; +}; + describe("SwapManager token-account setup wait", () => { const account = { data: new Uint8Array() }; - const keys = [new PublicKey("11111111111111111111111111111111"), new PublicKey(WSOL)]; + const firstKey = new PublicKey("11111111111111111111111111111111"); + const keys = [firstKey, new PublicKey(WSOL)]; test.each([ ["empty", []], @@ -33,23 +51,27 @@ describe("SwapManager token-account setup wait", () => { ): Promise => [account, account], ); getMultipleAccountsInfo.mockResolvedValueOnce(incomplete); - const { sm, sleeps } = createSwapManager({ getMultipleAccountsInfo }); - - await sm["waitForTokenAccounts"](keys); + const clock = mockPollingClock(); + const { sm, sleeps } = createSwapManager({ getMultipleAccountsInfo }, {}, clock.advance); + try { + await sm["waitForTokenAccounts"](keys); - expect(getMultipleAccountsInfo.mock.calls).toEqual([ - [keys, "confirmed"], - [keys, "confirmed"], - ]); - expect(sleeps).toEqual([250]); + expect(getMultipleAccountsInfo.mock.calls).toEqual([ + [keys, "confirmed"], + [keys, "confirmed"], + ]); + expect(sleeps).toEqual([250]); + } finally { + clock.restore(); + } }); test("stops a hung lookup at the 2-second visibility deadline", async () => { vi.useFakeTimers(); - const now = spyOn(Date, "now").mockReturnValue(1_000_000); + const clock = mockPollingClock(); const pending = Promise.withResolvers<(typeof account)[]>(); const getMultipleAccountsInfo = vi.fn(() => pending.promise); - const { sm, sleeps } = createSwapManager({ getMultipleAccountsInfo }); + const { sm, sleeps } = createSwapManager({ getMultipleAccountsInfo }, {}, clock.advance); const outcomes: unknown[] = []; const flush = async () => { for (let tick = 0; tick < 12; tick += 1) await Promise.resolve(); @@ -59,11 +81,11 @@ describe("SwapManager token-account setup wait", () => { () => outcomes.push("done"), (error: unknown) => outcomes.push(error), ); - now.mockReturnValue(1_001_999); + clock.advance(1_999); vi.advanceTimersByTime(1_999); await flush(); expect(outcomes).toEqual([]); - now.mockReturnValue(1_002_000); + clock.advance(1); vi.advanceTimersByTime(1); await flush(); expect(outcomes).toEqual(["done"]); @@ -72,7 +94,7 @@ describe("SwapManager token-account setup wait", () => { } finally { pending.resolve([account, account]); await flush(); - now.mockRestore(); + clock.restore(); vi.useRealTimers(); } }); @@ -87,7 +109,12 @@ describe("SwapManager token-account setup wait", () => { }), }; const sendAndConfirmWithResubmits = vi.fn(async () => "SETUP_SIG"); - const { sm, sleeps } = createSwapManager(connection, { sendAndConfirmWithResubmits }); + const clock = mockPollingClock(); + const { sm, sleeps } = createSwapManager( + connection, + { sendAndConfirmWithResubmits }, + clock.advance, + ); Reflect.set( sm, "createTokenAccountsIfNeeded", @@ -97,55 +124,57 @@ describe("SwapManager token-account setup wait", () => { }, ); - const user = await Keypair.generate(); - await expect( - sm.executeJupiterSwap( - { - inputMint: WSOL, - outputMint: created.toBase58(), - amount: "1", - userKeypair: user, - } as any, - { - inputMint: WSOL, - outputMint: created.toBase58(), - inputAmountRaw: "1", - providerQuote: {} as any, - providerQuoteTimestamp: 0, - } as any, - ), - ).rejects.toThrow("quote expired"); - - expect(sendAndConfirmWithResubmits).toHaveBeenCalledTimes(1); - expect(connection.getMultipleAccountsInfo).toHaveBeenCalledTimes(2); - expect(connection.getMultipleAccountsInfo.mock.calls[0] as unknown[]).toEqual([ - [created], - "confirmed", - ]); - expect(sleeps).toEqual([250]); + try { + const user = await Keypair.generate(); + await expect( + sm.executeJupiterSwap( + { + inputMint: WSOL, + outputMint: created.toBase58(), + amount: "1", + userKeypair: user, + } as any, + { + inputMint: WSOL, + outputMint: created.toBase58(), + inputAmountRaw: "1", + providerQuote: {} as any, + providerQuoteTimestamp: 0, + } as any, + ), + ).rejects.toThrow("quote expired"); + + expect(sendAndConfirmWithResubmits).toHaveBeenCalledTimes(1); + expect(connection.getMultipleAccountsInfo).toHaveBeenCalledTimes(2); + expect(connection.getMultipleAccountsInfo.mock.calls[0] as unknown[]).toEqual([ + [created], + "confirmed", + ]); + expect(sleeps).toEqual([250]); + } finally { + clock.restore(); + } }); test("gives up at the deadline and keeps polling through RPC errors", async () => { - const nowSpy = vi.spyOn(Date, "now"); - let now = 1_000_000; - nowSpy.mockImplementation(() => now); + const clock = mockPollingClock(); try { let calls = 0; const connection = { getMultipleAccountsInfo: vi.fn(async () => { calls += 1; - now += 900; + clock.advance(calls === 1 ? 900 : 750); if (calls === 1) throw new Error("rpc hiccup"); return [null]; }), }; - const { sm, sleeps } = createSwapManager(connection); - await (sm as any).waitForTokenAccounts([(await Keypair.generate()).publicKey]); + const { sm, sleeps } = createSwapManager(connection, {}, clock.advance); + await sm["waitForTokenAccounts"]([firstKey]); - expect(calls).toBe(3); - expect(sleeps).toEqual([250, 200]); + expect(calls).toBe(2); + expect(sleeps).toEqual([250, 100]); } finally { - nowSpy.mockRestore(); + clock.restore(); } }); From 6f37e086134b3ec9b4b2971c8b990a52e38882f9 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 15:55:38 -0300 Subject: [PATCH 090/410] test(rpc): verify cooldown priority and abort cleanup --- tests/rpc-request-budget.happy-path.test.ts | 33 +++++++ tests/rpc-request-budget.test.ts | 101 +++++++++++++++++++- 2 files changed, 133 insertions(+), 1 deletion(-) diff --git a/tests/rpc-request-budget.happy-path.test.ts b/tests/rpc-request-budget.happy-path.test.ts index c4c926f0..9208b0ca 100644 --- a/tests/rpc-request-budget.happy-path.test.ts +++ b/tests/rpc-request-budget.happy-path.test.ts @@ -113,6 +113,39 @@ describe("backgroundRpc", () => { vi.useRealTimers(); } }); + + test("does not spin on a lane that will unlock in one millisecond", async () => { + vi.useFakeTimers(); + let now = 1_000; + const clock = mockDateNowWithReadLimit(() => now); + const controller = new AbortController(); + const endpoint = "https://near-budget-boundary.test/rpc"; + const hits: number[] = []; + const flush = async () => { + for (let step = 0; step < 8; step += 1) await Promise.resolve(); + }; + try { + await backgroundRpc(endpoint, controller.signal, async () => undefined); + now = 1_499; + void backgroundRpc(endpoint, controller.signal, async () => { + hits.push(now); + }).catch((error: unknown) => error); + await flush(); + now = 1_500; + vi.advanceTimersByTime(1); + await flush(); + expect(hits).toEqual([]); + now = 1_509; + vi.advanceTimersByTime(9); + await flush(); + expect(hits).toEqual([1_509]); + } finally { + controller.abort(); + await flush(); + clock.mockRestore(); + vi.useRealTimers(); + } + }); }); test.each([ diff --git a/tests/rpc-request-budget.test.ts b/tests/rpc-request-budget.test.ts index 20c1fd4e..3c07a129 100644 --- a/tests/rpc-request-budget.test.ts +++ b/tests/rpc-request-budget.test.ts @@ -1,4 +1,5 @@ -import { expect, test, vi } from "bun:test"; +import { expect, spyOn, test, vi } from "bun:test"; +import { getEventListeners } from "node:events"; import { backgroundRpc, foregroundRpc, noteRpcRateLimit } from "../src/utils/rpc-request-budget"; import { mockDateNowWithReadLimit } from "./helpers/timers"; @@ -62,10 +63,12 @@ test("aborting while background work waits for foreground traffic rejects withou await flushTasks(); expect(outcomes).toEqual([]); expect(vi.getTimerCount()).toBe(1); + expect(getEventListeners(controller.signal, "abort")).toHaveLength(1); controller.abort(reason); await flushTasks(); expect(outcomes).toEqual([reason]); expect(vi.getTimerCount()).toBe(0); + expect(getEventListeners(controller.signal, "abort")).toHaveLength(0); } finally { controller.abort(); gate.resolve(); @@ -74,3 +77,99 @@ test("aborting while background work waits for foreground traffic rejects withou vi.useRealTimers(); } }); + +test.each([ + ["released", true], + ["still busy", false], +] as const)( + "aborting at the end of a delay works when foreground traffic is %s", + async (_label, releaseForeground) => { + vi.useFakeTimers(); + const now = mockDateNowWithReadLimit(() => 1_000); + const gate = Promise.withResolvers(); + const controller = new AbortController(); + const reason = new Error("cancelled at the end of the delay"); + const outcomes: unknown[] = []; + const foreground = foregroundRpc(() => gate.promise); + const removeEventListener = controller.signal.removeEventListener.bind(controller.signal); + const cleanup = spyOn(controller.signal, "removeEventListener").mockImplementation( + ( + type: string, + listener: EventListenerOrEventListenerObject, + options?: EventListenerOptions | boolean, + ) => { + removeEventListener(type, listener, options); + if (type === "abort") controller.abort(reason); + }, + ); + try { + void backgroundRpc( + "https://abort-after-delay.test/rpc", + controller.signal, + async () => "called", + ).then( + (result) => outcomes.push(result), + (error: unknown) => outcomes.push(error), + ); + await flushTasks(); + expect(vi.getTimerCount()).toBe(1); + if (releaseForeground) { + gate.resolve(); + await foreground; + } + + vi.advanceTimersByTime(10); + await flushTasks(); + expect(outcomes).toEqual([reason]); + } finally { + controller.abort(); + gate.resolve(); + await foreground; + cleanup.mockRestore(); + now.mockRestore(); + vi.useRealTimers(); + } + }, +); + +test("a cooling host rejects a background request even while foreground work is held", async () => { + vi.useFakeTimers(); + const clock = mockDateNowWithReadLimit(() => 1_000); + const gate = Promise.withResolvers(); + const controller = new AbortController(); + const endpoint = "https://cooldown-before-wait.test/rpc"; + const outcomes: unknown[] = []; + const foreground = foregroundRpc(() => gate.promise); + try { + noteRpcRateLimit(endpoint, "10"); + void backgroundRpc(endpoint, controller.signal, async () => "called").then( + (result) => outcomes.push(result), + (error: unknown) => outcomes.push(error), + ); + await flushTasks(); + expect(outcomes).toEqual([expect.objectContaining({ retryAt: 11_000 })]); + expect(vi.getTimerCount()).toBe(0); + } finally { + controller.abort(); + gate.resolve(); + await foreground; + clock.mockRestore(); + vi.useRealTimers(); + } +}); + +test("a request already cancelled reports the abort even when the host is cooling down", async () => { + const clock = mockDateNowWithReadLimit(() => 1_000); + const controller = new AbortController(); + const endpoint = "https://abort-before-cooldown.test/rpc"; + const reason = new Error("already cancelled"); + try { + noteRpcRateLimit(endpoint, "10"); + controller.abort(reason); + await expect(backgroundRpc(endpoint, controller.signal, async () => "called")).rejects.toBe( + reason, + ); + } finally { + clock.mockRestore(); + } +}); From fea4212f4d6a1dd485067a4f5396ef3e59306ac0 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 15:58:26 -0300 Subject: [PATCH 091/410] refactor(rpc): simplify optional retry date parsing --- src/utils/rpc-request-budget.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/utils/rpc-request-budget.ts b/src/utils/rpc-request-budget.ts index 1186564a..0b0985b5 100644 --- a/src/utils/rpc-request-budget.ts +++ b/src/utils/rpc-request-budget.ts @@ -27,7 +27,7 @@ export function noteRpcRateLimit( now = Date.now(), ): number { const seconds = retryAfter == null ? NaN : Number(retryAfter); - const date = retryAfter == null ? NaN : Date.parse(retryAfter); + const date = Date.parse(retryAfter ?? ""); const fallback = now + 5_000; const requestedRetryAt = Number.isFinite(seconds) ? now + Math.max(1, seconds) * 1000 From 7b0b6c6846cfe7857bb7d39585394f4778198ee3 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 16:00:08 -0300 Subject: [PATCH 092/410] test(games): bound waits when a retry timer never settles --- tests/game-manager.create-game.test.ts | 61 +++++++------ tests/game-manager.update-message.test.ts | 106 +++++++++++++--------- tests/game.funding-and-tokens.test.ts | 12 ++- tests/game.participants.test.ts | 28 ++++-- tests/helpers/timers.ts | 17 ++++ 5 files changed, 141 insertions(+), 83 deletions(-) diff --git a/tests/game-manager.create-game.test.ts b/tests/game-manager.create-game.test.ts index faa4539b..bc015824 100644 --- a/tests/game-manager.create-game.test.ts +++ b/tests/game-manager.create-game.test.ts @@ -1,3 +1,4 @@ +import { withinTestDeadline } from "./helpers/timers"; import { describe, test, expect, vi } from "bun:test"; import { getBase64EncodedWireTransaction, @@ -803,19 +804,22 @@ describe("GameManager.createGame", () => { hexToBuffer: (hex: string) => Buffer.from(hex, "hex"), }; - const res = await gm.createGame( - "coinflip", - { - amount: 800_000, - tokenMint: WSOL_MINT, - tokenTicker: "WSOL", - isSol: false, - requestedNativeSol: false, - }, - 2, - 2, - 60, - 1n, + const res = await withinTestDeadline( + gm.createGame( + "coinflip", + { + amount: 800_000, + tokenMint: WSOL_MINT, + tokenTicker: "WSOL", + isSol: false, + requestedNativeSol: false, + }, + 2, + 2, + 60, + 1n, + ), + "createGame", ); expect(res.success).toBe(true); @@ -1039,20 +1043,23 @@ describe("GameManager.createGame", () => { (gm as any).deriveAta = async () => (await Keypair.generate()).publicKey; (gm as any).confirmTransactionWithRecovery = async () => "CONFIRMED_SIG"; - const result = await gm.createGame( - "coinflip", - { - amount: 1_000_000, - tokenMint: PublicKey.default.toBase58(), - tokenTicker: "TIMBA", - isSol: false, - }, - 2, - 2, - 60, - 1n, - undefined, - 8200, + const result = await withinTestDeadline( + gm.createGame( + "coinflip", + { + amount: 1_000_000, + tokenMint: PublicKey.default.toBase58(), + tokenTicker: "TIMBA", + isSol: false, + }, + 2, + 2, + 60, + 1n, + undefined, + 8200, + ), + "createGame", ); expect(wallet.sendTransaction).toHaveBeenCalledTimes(1); diff --git a/tests/game-manager.update-message.test.ts b/tests/game-manager.update-message.test.ts index 89d4cf85..3732e3a2 100644 --- a/tests/game-manager.update-message.test.ts +++ b/tests/game-manager.update-message.test.ts @@ -1,3 +1,4 @@ +import { withinTestDeadline } from "./helpers/timers"; import { describe, test, expect, mock } from "bun:test"; import { PublicKey, Keypair } from "#solana"; import { @@ -144,15 +145,18 @@ describe("GameManager.updateGameMessage routing", () => { const msgMap = new Map(); msgMap.set(1, { chatId: 1, messageId: 43, usesVideo: true }); (gm as any).activeGameMessages.set(addr, msgMap); - await gm.updateGameMessage( - ctx as any, - addr, - "coinflip", - 1_000_000_000, - "@creator", - "Completed", - "TOK", - "SomeWinnerPubkey", + await withinTestDeadline( + gm.updateGameMessage( + ctx as any, + addr, + "coinflip", + 1_000_000_000, + "@creator", + "Completed", + "TOK", + "SomeWinnerPubkey", + ), + "updateGameMessage", ); const calls = (ctx as any).__calls; expect(calls[0][0]).toBe("media"); @@ -314,15 +318,18 @@ describe("GameManager.updateGameMessage routing", () => { const msgMap = new Map(); msgMap.set(1, { chatId: 1, messageId: 46, usesVideo: true }); (gm as any).activeGameMessages.set(addr, msgMap); - await gm.updateGameMessage( - ctx as any, - addr, - "coinflip", - 1_000_000_000, - "@creator", - "Completed", - "TOK", - "SomeWinner", + await withinTestDeadline( + gm.updateGameMessage( + ctx as any, + addr, + "coinflip", + 1_000_000_000, + "@creator", + "Completed", + "TOK", + "SomeWinner", + ), + "updateGameMessage", ); const calls = (ctx as any).__calls; expect(calls[0][0]).toBe("media"); @@ -359,15 +366,18 @@ describe("GameManager.updateGameMessage routing", () => { const msgMap = new Map(); msgMap.set(1, { chatId: 1, messageId: 46, usesVideo: true }); (gm as any).activeGameMessages.set(addr, msgMap); - await gm.updateGameMessage( - ctx as any, - addr, - "coinflip", - 1_000_000_000, - "@creator", - "Completed", - "TOK", - "SomeWinner", + await withinTestDeadline( + gm.updateGameMessage( + ctx as any, + addr, + "coinflip", + 1_000_000_000, + "@creator", + "Completed", + "TOK", + "SomeWinner", + ), + "updateGameMessage", ); const calls = (ctx as any).__calls; expect(calls[0][0]).toBe("media"); @@ -408,15 +418,18 @@ describe("GameManager.updateGameMessage routing", () => { const msgMap = new Map(); msgMap.set(1, { chatId: 1, messageId: 46, usesVideo: true }); (gm as any).activeGameMessages.set(addr, msgMap); - await gm.updateGameMessage( - ctx as any, - addr, - "coinflip", - 1_000_000_000, - "@creator", - "Completed", - "TOK", - "SomeWinner", + await withinTestDeadline( + gm.updateGameMessage( + ctx as any, + addr, + "coinflip", + 1_000_000_000, + "@creator", + "Completed", + "TOK", + "SomeWinner", + ), + "updateGameMessage", ); const calls = (ctx as any).__calls; expect(calls[0][0]).toBe("media"); @@ -458,15 +471,18 @@ describe("GameManager.updateGameMessage routing", () => { const msgMap = new Map(); msgMap.set(1, { chatId: 1, messageId: 46, usesVideo: true }); (gm as any).activeGameMessages.set(addr, msgMap); - await gm.updateGameMessage( - ctx as any, - addr, - "coinflip", - 1_000_000_000, - "@creator", - "Completed", - "TOK", - "SomeWinner", + await withinTestDeadline( + gm.updateGameMessage( + ctx as any, + addr, + "coinflip", + 1_000_000_000, + "@creator", + "Completed", + "TOK", + "SomeWinner", + ), + "updateGameMessage", ); const calls = (ctx as any).__calls; expect(calls[0][0]).toBe("media"); diff --git a/tests/game.funding-and-tokens.test.ts b/tests/game.funding-and-tokens.test.ts index a8bd98d0..31da0242 100644 --- a/tests/game.funding-and-tokens.test.ts +++ b/tests/game.funding-and-tokens.test.ts @@ -4,7 +4,7 @@ import { WSOL_MINT } from "../src/utils/constants"; import { GameManager } from "../src/utils/game"; import { __test_clearPriceServiceCache } from "../src/utils/price-service"; import { __test_resetPriceCache } from "../src/utils/prices"; -import { stubInstantTimers } from "./helpers/timers"; +import { stubInstantTimers, withinTestDeadline } from "./helpers/timers"; const GAME_PDA = new PublicKey("BPFLoader1111111111111111111111111111111111"); const PLAYER_PUBKEY = new PublicKey("BPFLoader2111111111111111111111111111111111"); @@ -176,7 +176,10 @@ describe("GameManager ensureWrappedSolBalance", () => { getBalance: async () => 50_000, }); - const result = await gm.ensureWrappedSolBalance(1n, REQUIRED, 0, 50_000, "create"); + const result = await withinTestDeadline( + gm.ensureWrappedSolBalance(1n, REQUIRED, 0, 50_000, "create"), + "ensureWrappedSolBalance", + ); expect(result).toEqual({ success: false, @@ -221,7 +224,10 @@ describe("GameManager ensureWrappedSolBalance", () => { try { process.env.NODE_ENV = "production"; - const result = await gm.ensureWrappedSolBalance(1n, REQUIRED, 0, 90_000, "create"); + const result = await withinTestDeadline( + gm.ensureWrappedSolBalance(1n, REQUIRED, 0, 90_000, "create"), + "ensureWrappedSolBalance", + ); expect(result).toEqual({ success: true, tokenBalance: REQUIRED, solBalance: 100 }); expect(timers.delays).toEqual([250, 500, 1_000, 2_000, 4_000, 8_000]); diff --git a/tests/game.participants.test.ts b/tests/game.participants.test.ts index 7c9517d7..fead4f41 100644 --- a/tests/game.participants.test.ts +++ b/tests/game.participants.test.ts @@ -1,7 +1,7 @@ import { afterEach, beforeEach, describe, expect, spyOn, test } from "bun:test"; import { Keypair, PublicKey } from "#solana"; import { GameManager } from "../src/utils/game"; -import { stubInstantTimers } from "./helpers/timers"; +import { stubInstantTimers, withinTestDeadline } from "./helpers/timers"; const GAME_PDA = new PublicKey("BPFLoader1111111111111111111111111111111111"); const GAME_ADDRESS = GAME_PDA.toBase58(); @@ -47,7 +47,9 @@ describe("confirmed game account reads", () => { }, }); - expect(await gm.fetchConfirmedGame(GAME_PDA)).toBe(game); + expect(await withinTestDeadline(gm.fetchConfirmedGame(GAME_PDA), "fetchConfirmedGame")).toBe( + game, + ); expect(addresses).toEqual(Array(failures + 1).fill(GAME_ADDRESS)); expect(timers.delays).toEqual(productionDelays.slice(0, failures)); expect(warnSpy).toHaveBeenCalledTimes(failures); @@ -69,7 +71,9 @@ describe("confirmed game account reads", () => { }, }); - await expect(gm.fetchConfirmedGame(GAME_PDA)).rejects.toBe(finalError); + await expect( + withinTestDeadline(gm.fetchConfirmedGame(GAME_PDA), "fetchConfirmedGame"), + ).rejects.toBe(finalError); expect(reads).toBe(7); expect(timers.delays).toEqual(productionDelays); expect(warnSpy).toHaveBeenCalledTimes(6); @@ -200,7 +204,10 @@ describe("GameManager verifyParticipantJoin retries", () => { }, ); - const verified = await gm.verifyParticipantJoin(GAME_PDA, player, "5", { maxAttempts: 3 }); + const verified = await withinTestDeadline( + gm.verifyParticipantJoin(GAME_PDA, player, "5", { maxAttempts: 3 }), + "verifyParticipantJoin", + ); expect(verified).toBe(false); expect(reads).toBe(3); @@ -232,9 +239,12 @@ describe("GameManager verifyParticipantJoin retries", () => { }, ); - expect(await gm.verifyParticipantJoin(GAME_PDA, player, "5", { joinSignature: "SIG" })).toBe( - true, - ); + expect( + await withinTestDeadline( + gm.verifyParticipantJoin(GAME_PDA, player, "5", { joinSignature: "SIG" }), + "verifyParticipantJoin", + ), + ).toBe(true); expect(timers.delays).toEqual([500]); expect(saved).toHaveLength(1); expect(saved[0]?.slice(0, 3)).toEqual([GAME_ADDRESS, "5", player.toBase58()]); @@ -265,7 +275,9 @@ describe("GameManager player name lookup", () => { return "@found"; }; try { - expect(await gm.getPlayerUsername({}, GAME_ADDRESS)).toBe(name); + expect( + await withinTestDeadline(gm.getPlayerUsername({}, GAME_ADDRESS), "getPlayerUsername"), + ).toBe(name); expect(reads).toEqual(Array.from({ length: Math.min(availableAt, 5) }, () => GAME_ADDRESS)); expect(usernames).toEqual(availableAt <= 5 ? ["123"] : []); expect(timers.delays).toEqual([...delays]); diff --git a/tests/helpers/timers.ts b/tests/helpers/timers.ts index 26b97a85..b7e40de4 100644 --- a/tests/helpers/timers.ts +++ b/tests/helpers/timers.ts @@ -1,5 +1,22 @@ import { spyOn } from "bun:test"; +const scheduleDeadline = globalThis.setTimeout; +const cancelDeadline = globalThis.clearTimeout; + +/** Use the normal test deadline even when a mutation removes a simulated timer. */ +export async function withinTestDeadline(result: Promise, action: string): Promise { + const timeout = Promise.withResolvers(); + const timer = scheduleDeadline( + () => timeout.reject(new Error(`${action} did not settle`)), + 5_000, + ); + try { + return await Promise.race([result, timeout.promise]); + } finally { + cancelDeadline(timer); + } +} + /** * Collapses every `setTimeout` delay to 0ms so retry/backoff/poll sleeps in the * code under test do not burn wall-clock time. Callbacks still run From fb13c81d0bd8ba5ffc3d95f37c33a4d63c7d368d Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 16:03:08 -0300 Subject: [PATCH 093/410] test(games): verify proof checkpoints and provider slot guards --- ...ame-creation-recovery.proof-guards.test.ts | 38 ++++++++++++++++++- 1 file changed, 36 insertions(+), 2 deletions(-) diff --git a/tests/game-creation-recovery.proof-guards.test.ts b/tests/game-creation-recovery.proof-guards.test.ts index d58b0cfb..a46e1330 100644 --- a/tests/game-creation-recovery.proof-guards.test.ts +++ b/tests/game-creation-recovery.proof-guards.test.ts @@ -1,4 +1,4 @@ -import { describe, expect, mock, test } from "bun:test"; +import { describe, expect, mock, spyOn, test } from "bun:test"; import { proveExpiredCreationAbsent, parseCreationProofCheckpoint, @@ -62,8 +62,11 @@ describe("restart jump to the expiry anchor", () => { ["decreasing", [1_001, 1_000]], ] as const) test(`a slot list that is ${label} leaves the creation unproven`, async () => { - const rpc = rpcFor(blocks, 1_014, { getBlocks: slots }); + const rpc = mock(rpcFor(blocks, 1_014, { getBlocks: slots })); expect(await proveExpiredCreationAbsent(input, rpc, rpc)).toBe(false); + expect( + rpc.mock.calls.filter(([method]) => method === "getBlock").map(([, [slot]]) => slot), + ).toEqual([1_014]); }); test("requests the intended finalized windows and accepts a one-slot candidate list", async () => { @@ -123,9 +126,40 @@ describe("resuming from a saved checkpoint", () => { expect(rpc.mock.calls.some(([method]) => method === "getSlot")).toBe(false); }); + test("a resumed batch spends only its new block allowance and preserves the next retry deadline", async () => { + const rpc = mock(rpcFor(chain(10, 14), 14)); + const saved: CreationProofCheckpoint[] = []; + const clock = spyOn(Date, "now").mockReturnValue(10_000); + try { + const result = await proveExpiredCreationAbsent(input, rpc, rpc, { + checkpoint, + maxBlocks: 2, + save: (state) => saved.push(state), + }).catch((error: unknown) => error); + expect(result).toMatchObject({ name: "RpcRetryLaterError", retryAt: 13_000 }); + expect(saved.map(({ cursor, checkedBlocks }) => [cursor.slot, checkedBlocks])).toEqual([ + [11, 3], + [10, 4], + ]); + const finalCheckpoint = saved.at(-1); + if (!finalCheckpoint) throw new Error("Expected a saved checkpoint at the original block"); + expect( + await proveExpiredCreationAbsent(input, rpc, rpc, { + checkpoint: finalCheckpoint, + maxBlocks: 1, + save: () => {}, + }), + ).toBe(true); + } finally { + clock.mockRestore(); + } + }); + test.each<[string, Record]>([ ["the wrong genesis hash", { genesis: "wrong" }], ["a negative count", { checkedBlocks: -1 }], + ["a fractional count", { checkedBlocks: 2.5 }], + ["a count inconsistent with the cursor height", { checkedBlocks: 1 }], ["a count beyond the scan window", { checkedBlocks: 256 }], ["a cursor after its anchor", { cursor: { slot: 15, hash: "hash12", height: 12 } }], ["a missing cursor", { cursor: null }], From 0e811a4f88daa2125e2cfa1aa63a1ddfeeb8ae1c Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 16:04:56 -0300 Subject: [PATCH 094/410] test(games): verify each recovery witness failure separately --- tests/game-creation-recovery.test.ts | 89 ++++++++++++++++++++-------- 1 file changed, 63 insertions(+), 26 deletions(-) diff --git a/tests/game-creation-recovery.test.ts b/tests/game-creation-recovery.test.ts index b7cf56f1..ca1df3c8 100644 --- a/tests/game-creation-recovery.test.ts +++ b/tests/game-creation-recovery.test.ts @@ -101,36 +101,73 @@ describe("Finalized creation absence proof", () => { blocks.get(12).signatures.push(input.signature); expect(await proveExpiredCreationAbsent(input, rpc, rpc)).toBe(false); }); - for (const mutate of [ - (blocks: Map) => blocks.delete(12), - (blocks: Map) => { - blocks.get(12).signatures = undefined; - }, - (blocks: Map) => { - blocks.get(12).blockhash = "other-fork"; - }, - (blocks: Map) => { - blocks.get(12).blockHeight = 1; - }, - (blocks: Map) => { - blocks.get(12).parentSlot = 12; - }, - ]) - test("incomplete or inconsistent history stays reserved", async () => { + const invalidBlocks: Array<[string, (blocks: ReturnType["blocks"]) => unknown]> = + [ + ["a missing block", (blocks) => blocks.delete(12)], + [ + "no signature list", + (blocks) => { + blocks.get(12).signatures = undefined; + }, + ], + [ + "a malformed signature", + (blocks) => { + blocks.get(12).signatures = [23]; + }, + ], + [ + "a different fork", + (blocks) => { + blocks.get(12).blockhash = "other-fork"; + }, + ], + [ + "an inconsistent block height", + (blocks) => { + blocks.get(12).blockHeight = 1; + }, + ], + [ + "a non-integer parent slot", + (blocks) => { + blocks.get(12).parentSlot = 11.5; + }, + ], + [ + "a parent equal to its child", + (blocks) => { + blocks.get(12).parentSlot = 12; + }, + ], + ]; + for (const [label, mutate] of invalidBlocks) + test(`history with ${label} leaves the original creation reserved`, async () => { const { input, rpc, blocks } = fixture(); mutate(blocks); expect(await proveExpiredCreationAbsent(input, rpc, rpc)).toBe(false); }); - for (const [method, result] of [ - ["getGenesisHash", "other-chain"], - ["getBlock", { blockhash: "other-fork", blockHeight: 14 }], - ["getSignatureStatuses", { value: [{ confirmationStatus: "finalized", err: null }] }], - ["getSignatureStatuses", {}], - ["getAccountInfo", { context: { slot: 14 }, value: { data: "exists" } }], - ["getAccountInfo", { context: { slot: 12 }, value: null }], - ["isBlockhashValid", { context: { slot: 14 }, value: true }], - ]) - test(`witness disagreement/lag in ${method} blocks replacement`, async () => { + for (const [label, method, result] of [ + ["different chain", "getGenesisHash", "other-chain"], + ["different anchor hash", "getBlock", { blockhash: "other-fork", blockHeight: 14 }], + ["different anchor height", "getBlock", { blockhash: "hash14", blockHeight: 15 }], + [ + "a finalized signature", + "getSignatureStatuses", + { value: [{ confirmationStatus: "finalized", err: null }] }, + ], + ["missing status data", "getSignatureStatuses", {}], + ["no status entries", "getSignatureStatuses", { value: [] }], + ["multiple status entries", "getSignatureStatuses", { value: [null, null] }], + ["an existing account", "getAccountInfo", { context: { slot: 14 }, value: { data: "exists" } }], + ["absent account response", "getAccountInfo", null], + ["an old account context", "getAccountInfo", { context: { slot: 12 }, value: null }], + ["an invalid account context", "getAccountInfo", { context: { slot: "14" }, value: null }], + ["a still-valid blockhash", "isBlockhashValid", { context: { slot: 14 }, value: true }], + ["missing blockhash validity", "isBlockhashValid", null], + ["an old validity context", "isBlockhashValid", { context: { slot: 13 }, value: false }], + ] as const) + test(`witness reporting ${label} blocks replacement`, async () => { const { input, rpc } = fixture(); const witness: RecoveryRpc = (m, p) => (m === method ? Promise.resolve(result) : rpc(m, p)); expect(await proveExpiredCreationAbsent(input, rpc, witness)).toBe(false); From cdeb3ea448a86722cf881ced9ad5ca146b5b27f4 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 16:07:37 -0300 Subject: [PATCH 095/410] fix(wallet): reject malformed transaction fee quotes --- src/utils/wallet.ts | 5 +++-- tests/wallet.internals.test.ts | 34 +++++++++++++++++++++++++++++----- 2 files changed, 32 insertions(+), 7 deletions(-) diff --git a/src/utils/wallet.ts b/src/utils/wallet.ts index 10de961e..e6e8234c 100644 --- a/src/utils/wallet.ts +++ b/src/utils/wallet.ts @@ -3090,8 +3090,9 @@ export class WalletManager { const feeResponse = await this.connection.getFeeForMessage(message); const fee = feeResponse?.value; - if ((typeof fee === "number" || typeof fee === "bigint") && Number.isFinite(Number(fee))) { - return Number(fee); + const lamports = typeof fee === "number" || typeof fee === "bigint" ? Number(fee) : NaN; + if (Number.isSafeInteger(lamports) && lamports >= 0) { + return lamports; } throw new Error("RPC returned no transaction fee estimate."); } catch (error) { diff --git a/tests/wallet.internals.test.ts b/tests/wallet.internals.test.ts index ae0bbc58..d3171967 100644 --- a/tests/wallet.internals.test.ts +++ b/tests/wallet.internals.test.ts @@ -35,8 +35,8 @@ const walletWith = (connection: Record) => }); describe("fee estimation", () => { - const transfer = async () => { - const from = (await Keypair.generate()).publicKey; + const transfer = () => { + const from = new PublicKey(new Uint8Array(32).fill(7)); return { payer: from, instruction: SystemProgram.transfer({ fromPubkey: from, toPubkey: from, lamports: 1 }), @@ -52,7 +52,7 @@ describe("fee estimation", () => { test("asks the RPC for the fee of the compiled message", async () => { const getFeeForMessage = mock(async () => ({ value: 7_500n })); const wallet = walletWith({ getLatestBlockhash: async () => blockhash, getFeeForMessage }); - const { payer, instruction } = await transfer(); + const { payer, instruction } = transfer(); expect(await (wallet as any).estimateFee(payer, [instruction])).toBe(7_500); expect(getFeeForMessage).toHaveBeenCalledTimes(1); @@ -63,7 +63,7 @@ describe("fee estimation", () => { getLatestBlockhash: async () => blockhash, getFeeForMessage: async () => ({ value: null }), }); - const { payer, instruction } = await transfer(); + const { payer, instruction } = transfer(); expect(await (wallet as any).estimateFee(payer, [instruction])).toBe(5_000); expect(warnSpy.mock.calls[0]?.[0]).toBe("⚠️ Failed to estimate fee, falling back to default:"); @@ -76,12 +76,36 @@ describe("fee estimation", () => { throw new Error("rpc down"); }, }); - const { payer, instruction } = await transfer(); + const { payer, instruction } = transfer(); await expect( (wallet as any).estimateFee(payer, [instruction], { allowFallback: false }), ).rejects.toThrow("Unable to estimate the sponsored transaction fee."); }); + + test.each([-1n, 1.25, 9_007_199_254_740_993n])( + "does not use a malformed RPC quote of %p lamports", + async (value) => { + const wallet = walletWith({ + getLatestBlockhash: async () => blockhash, + getFeeForMessage: async () => ({ value }), + }); + const { payer, instruction } = transfer(); + expect(await wallet["estimateFee"](payer, [instruction])).toBe(5_000); + await expect( + wallet["estimateFee"](payer, [instruction], { allowFallback: false }), + ).rejects.toThrow("Unable to estimate the sponsored transaction fee."); + }, + ); + + test("keeps an exact zero fee without a fallback", async () => { + const wallet = walletWith({ + getLatestBlockhash: async () => blockhash, + getFeeForMessage: async () => ({ value: 0n }), + }); + const { payer, instruction } = transfer(); + expect(await wallet["estimateFee"](payer, [instruction], { allowFallback: false })).toBe(0); + }); }); describe("default game transaction sender", () => { From 1ee68b9d93c473950b71a3b4424a3a06fa1efd04 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 16:10:11 -0300 Subject: [PATCH 096/410] fix(wallet): bound transaction resubmission limits --- src/utils/wallet.ts | 16 +++++--- tests/wallet.resubmit.test.ts | 69 ++++++++++++++++++----------------- 2 files changed, 46 insertions(+), 39 deletions(-) diff --git a/src/utils/wallet.ts b/src/utils/wallet.ts index e6e8234c..047843f7 100644 --- a/src/utils/wallet.ts +++ b/src/utils/wallet.ts @@ -3012,6 +3012,9 @@ export class WalletManager { onPrepared, priorityFee, } = options; + const requestedResubmits = Math.ceil(Math.max(0, maxResubmits)); + // A malformed limit must not authorize additional transactions. + const resubmitLimit = Number.isSafeInteger(requestedResubmits) ? requestedResubmits : 0; const startingSignature = typeof initialSignature === "string" && initialSignature.length > 0 @@ -3024,9 +3027,9 @@ export class WalletManager { let currentSignature = startingSignature; - let resubmitAttempts = 0; + let finalFailure: Error | undefined; - while (true) { + for (let resubmitAttempts = 0; resubmitAttempts <= resubmitLimit; resubmitAttempts += 1) { try { await this.confirmTransaction(currentSignature); @@ -3048,17 +3051,17 @@ export class WalletManager { normalizedMessage.includes("expired before confirmation") || normalizedMessage.includes("last valid block height"); - if (!isRecoverable || resubmitAttempts >= maxResubmits) { + if (!isRecoverable || resubmitAttempts >= resubmitLimit) { const failure = error instanceof Error ? error : new Error(error?.message ?? String(error), { cause: error }); - throw Object.assign(failure, { lastSignature: currentSignature }); + finalFailure = Object.assign(failure, { lastSignature: currentSignature }); + break; } - resubmitAttempts += 1; console.warn( - `♻️ ${operationLabel} resubmit ${resubmitAttempts}/${maxResubmits} after failure: ${ + `♻️ ${operationLabel} resubmit ${resubmitAttempts + 1}/${maxResubmits} after failure: ${ error?.message ?? error }`, ); @@ -3066,6 +3069,7 @@ export class WalletManager { currentSignature = await this.sendTransaction(instructions, signers, { priorityFee }); } } + throw finalFailure; } private async estimateFee( diff --git a/tests/wallet.resubmit.test.ts b/tests/wallet.resubmit.test.ts index 8416f95e..3d7f0037 100644 --- a/tests/wallet.resubmit.test.ts +++ b/tests/wallet.resubmit.test.ts @@ -72,7 +72,7 @@ describe("WalletManager sendAndConfirmWithResubmits", () => { expect(observedSignatures).toEqual(["SIG1", "SIG2"]); }); - test("surfaces error after exhausting resubmits", async () => { + test.each([1, 0.5])("surfaces error after exhausting %p resubmits", async (maxResubmits) => { const connection = new ResubmitConnection(); const wallet = WalletManager.createForTest(MNEMONIC, { connection: connection as any, @@ -95,44 +95,47 @@ describe("WalletManager sendAndConfirmWithResubmits", () => { await expect( wallet.sendAndConfirmWithResubmits([ix], [await Keypair.generate()], { operationLabel: "Failing transaction", - maxResubmits: 1, + maxResubmits, }), ).rejects.toMatchObject({ message: "Transaction SIG2 timed out", lastSignature: "SIG2" }); expect(confirmed).toEqual(["SIG1", "SIG2"]); expect(connection.sendCalls).toBe(2); }); - test("keeps the original error and signature when resubmission is disabled", async () => { - const connection = new ResubmitConnection(); - const wallet = WalletManager.createForTest(MNEMONIC, { - connection: connection as unknown as Connection, - }); - const err = new Error("initial transaction timed out"); - const confirm = spyOn(wallet, "confirmTransaction") - .mockResolvedValue(undefined) - .mockRejectedValueOnce(err); - const send = spyOn(wallet, "sendTransaction").mockResolvedValue("UNEXPECTED"); - const ix = new TransactionInstruction({ - programId: PublicKey.default, - keys: [], - data: Buffer.alloc(0), - }); - const signer = { publicKey: PublicKey.default } as unknown as Keypair; - try { - await expect( - wallet.sendAndConfirmWithResubmits([ix], [signer], { - initialSignature: "initial", - maxResubmits: 0, - }), - ).rejects.toBe(err); - expect(err).toMatchObject({ lastSignature: "initial" }); - expect(confirm.mock.calls).toEqual([["initial"]]); - expect(send).not.toHaveBeenCalled(); - } finally { - confirm.mockRestore(); - send.mockRestore(); - } - }); + test.each([0, -1, NaN, Infinity, Number.MAX_SAFE_INTEGER + 1])( + "keeps the original error and sends nothing else for retry limit %p", + async (maxResubmits) => { + const connection = new ResubmitConnection(); + const wallet = WalletManager.createForTest(MNEMONIC, { + connection: connection as unknown as Connection, + }); + const err = new Error("initial transaction timed out"); + const confirm = spyOn(wallet, "confirmTransaction") + .mockResolvedValue(undefined) + .mockRejectedValueOnce(err); + const send = spyOn(wallet, "sendTransaction").mockResolvedValue("UNEXPECTED"); + const ix = new TransactionInstruction({ + programId: PublicKey.default, + keys: [], + data: Buffer.alloc(0), + }); + const signer = { publicKey: PublicKey.default } as unknown as Keypair; + try { + await expect( + wallet.sendAndConfirmWithResubmits([ix], [signer], { + initialSignature: "initial", + maxResubmits, + }), + ).rejects.toBe(err); + expect(err).toMatchObject({ lastSignature: "initial" }); + expect(confirm.mock.calls).toEqual([["initial"]]); + expect(send).not.toHaveBeenCalled(); + } finally { + confirm.mockRestore(); + send.mockRestore(); + } + }, + ); test("reports a plain provider error instead of throwing while attaching the signed transaction", async () => { const wallet = WalletManager.createForTest(MNEMONIC, { From 1e526e779a25470ef5b0871d6f2cd0f60b43d4b4 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 16:13:32 -0300 Subject: [PATCH 097/410] refactor(rpc): skip parsing an absent retry hint --- src/utils/rpc-request-budget.ts | 17 ++++++++++------- 1 file changed, 10 insertions(+), 7 deletions(-) diff --git a/src/utils/rpc-request-budget.ts b/src/utils/rpc-request-budget.ts index 0b0985b5..606c9a7a 100644 --- a/src/utils/rpc-request-budget.ts +++ b/src/utils/rpc-request-budget.ts @@ -26,14 +26,17 @@ export function noteRpcRateLimit( retryAfter: string | null, now = Date.now(), ): number { - const seconds = retryAfter == null ? NaN : Number(retryAfter); - const date = Date.parse(retryAfter ?? ""); const fallback = now + 5_000; - const requestedRetryAt = Number.isFinite(seconds) - ? now + Math.max(1, seconds) * 1000 - : Number.isFinite(date) - ? Math.max(now + 1000, date) - : fallback; + let requestedRetryAt = fallback; + if (retryAfter != null) { + const seconds = Number(retryAfter); + if (Number.isFinite(seconds)) { + requestedRetryAt = now + Math.max(1, seconds) * 1_000; + } else { + const date = Date.parse(retryAfter); + if (Number.isFinite(date)) requestedRetryAt = Math.max(now + 1_000, date); + } + } // An unrepresentable deadline must not poison this host's cooldown indefinitely. const retryAt = Number.isSafeInteger(Math.ceil(requestedRetryAt)) ? requestedRetryAt : fallback; const lane = laneFor(endpoint); From a2fbd3f946f6cdec6a533ca3785123fe8e440b1b Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 16:18:03 -0300 Subject: [PATCH 098/410] refactor(swaps): use one quote expiry fallback --- src/utils/swap/quote-cache.ts | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/utils/swap/quote-cache.ts b/src/utils/swap/quote-cache.ts index 9f308d00..cb7d4cbf 100644 --- a/src/utils/swap/quote-cache.ts +++ b/src/utils/swap/quote-cache.ts @@ -10,12 +10,13 @@ export interface QuoteCacheOptions { const DEFAULT_TTL_MS = 5_000; export class SwapQuoteCache { - private readonly ttlMs: number; + private readonly ttlMs: number | undefined; private readonly jupiterCache = createExpiringCache(DEFAULT_TTL_MS); private readonly pendingJupiter = new Map>(); constructor(options: QuoteCacheOptions = {}) { - this.ttlMs = options.ttlMs && options.ttlMs > 0 ? options.ttlMs : DEFAULT_TTL_MS; + // The expiring cache uses its configured default for an invalid override. + this.ttlMs = options.ttlMs; } async getJupiterQuote( From 09db24ec8a146bf2248949501164b2c7d7c6fc25 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 16:23:25 -0300 Subject: [PATCH 099/410] test(games): verify wrapped balance retry progress --- tests/game.funding-and-tokens.test.ts | 80 +++++++++++++++++++-------- tests/helpers/timers.ts | 7 ++- 2 files changed, 61 insertions(+), 26 deletions(-) diff --git a/tests/game.funding-and-tokens.test.ts b/tests/game.funding-and-tokens.test.ts index 31da0242..97908157 100644 --- a/tests/game.funding-and-tokens.test.ts +++ b/tests/game.funding-and-tokens.test.ts @@ -1,4 +1,5 @@ import { afterEach, beforeEach, describe, expect, spyOn, test, vi } from "bun:test"; +import { AsyncLocalStorage } from "node:async_hooks"; import { PublicKey } from "#solana"; import { WSOL_MINT } from "../src/utils/constants"; import { GameManager } from "../src/utils/game"; @@ -11,6 +12,7 @@ const PLAYER_PUBKEY = new PublicKey("BPFLoader2111111111111111111111111111111111 const makeManager = ( options: { wallet?: any; program?: any; gameDb?: any; connection?: any } = {}, + Manager = GameManager, ): any => { const wallet = { formatSolBalance: (value: number | bigint | string) => `${value}`, @@ -18,7 +20,7 @@ const makeManager = ( `${value}@${decimals}`, ...options.wallet, }; - const gm: any = GameManager.getInstance( + const gm: any = Manager.getInstance( options.program ?? { account: { game: {} } }, wallet, options.gameDb ?? {}, @@ -43,8 +45,12 @@ describe("GameManager ensureWrappedSolBalance", () => { GameManager.resetForTest(); }); - const setup = (wallet: Record, buffers = { wrap: 10, min: 100 }) => { - const gm = makeManager({ wallet }); + const setup = ( + wallet: Record, + buffers = { wrap: 10, min: 100 }, + Manager = GameManager, + ) => { + const gm = makeManager({ wallet }, Manager); gm.feeBudget = { getWrapFeeBufferLamports: async () => buffers.wrap, getGameSafetyBufferLamports: async () => buffers.min, @@ -210,30 +216,58 @@ describe("GameManager ensureWrappedSolBalance", () => { test("uses the complete production backoff and accepts the exact stake and SOL reserve", async () => { const previousEnv = process.env.NODE_ENV; - const timers = stubInstantTimers(); - let reads = 0; - const gm = setup({ - wrapSol: async () => "wrap-sig", - getTokenBalance: async () => { - reads += 1; - if (reads > 7) throw new Error("Unexpected eighth WSOL lookup"); - return reads === 7 ? REQUIRED : 0; - }, - getBalance: async () => 100, - }); - + const previousDebug = process.env["TIMBA_DEBUG"]; + const debug = spyOn(console, "debug").mockImplementation(() => undefined); try { - process.env.NODE_ENV = "production"; - const result = await withinTestDeadline( - gm.ensureWrappedSolBalance(1n, REQUIRED, 0, 90_000, "create"), - "ensureWrappedSolBalance", + process.env["TIMBA_DEBUG"] = "true"; + const module: typeof import("../src/utils/game") = await import( + `../src/utils/game?${"test-production-wrap-debug"}` ); - - expect(result).toEqual({ success: true, tokenBalance: REQUIRED, solBalance: 100 }); - expect(timers.delays).toEqual([250, 500, 1_000, 2_000, 4_000, 8_000]); + const wrapScope = new AsyncLocalStorage(); + // Ignore timers scheduled by the manager's separate fee budget warmup. + const timers = stubInstantTimers(() => wrapScope.getStore() === true); + let reads = 0; + try { + const gm = setup( + { + wrapSol: async () => "wrap-sig", + getTokenBalance: async () => { + reads += 1; + if (reads > 7) throw new Error("Unexpected eighth WSOL lookup"); + return reads === 7 ? REQUIRED : 0; + }, + getBalance: async () => 100, + }, + undefined, + module.GameManager, + ); + process.env.NODE_ENV = "production"; + const result = await wrapScope.run(true, () => + withinTestDeadline( + gm.ensureWrappedSolBalance(1n, REQUIRED, 0, 90_000, "create"), + "ensureWrappedSolBalance", + ), + ); + + expect(result).toEqual({ success: true, tokenBalance: REQUIRED, solBalance: 100 }); + expect(timers.delays).toEqual([250, 500, 1_000, 2_000, 4_000, 8_000]); + const progress = debug.mock.calls.flatMap(([message]) => { + const match = /^⏳ Waiting for WSOL balance propagation \(attempt (\d+)\/(\d+)\)$/.exec( + String(message), + ); + return match ? [`${match[1]}/${match[2]}`] : []; + }); + expect(progress).toEqual(["1/7", "2/7", "3/7", "4/7", "5/7", "6/7"]); + expect(reads).toBe(7); + } finally { + timers.restore(); + module.GameManager.resetForTest(); + } } finally { process.env.NODE_ENV = previousEnv; - timers.restore(); + if (previousDebug === undefined) delete process.env["TIMBA_DEBUG"]; + else process.env["TIMBA_DEBUG"] = previousDebug; + debug.mockRestore(); } }); diff --git a/tests/helpers/timers.ts b/tests/helpers/timers.ts index b7e40de4..07f57ad8 100644 --- a/tests/helpers/timers.ts +++ b/tests/helpers/timers.ts @@ -21,13 +21,14 @@ export async function withinTestDeadline(result: Promise, action: string): * Collapses every `setTimeout` delay to 0ms so retry/backoff/poll sleeps in the * code under test do not burn wall-clock time. Callbacks still run * asynchronously (on a real 0ms timer), so ordering relative to promises is - * preserved. Requested delays are recorded in `delays`. Call `restore()` in - * `afterEach` (or a `finally`). + * preserved. Requested delays are recorded in `delays`. If supplied, a predicate + * selects which calls to stub. Call `restore()` in `afterEach` (or a `finally`). */ -export const stubInstantTimers = () => { +export const stubInstantTimers = (shouldStub?: () => boolean) => { const originalSetTimeout = globalThis.setTimeout; const delays: number[] = []; globalThis.setTimeout = ((callback: (...args: any[]) => void, ms?: number, ...args: any[]) => { + if (shouldStub && !shouldStub()) return originalSetTimeout(callback, ms, ...args); delays.push(ms ?? 0); return originalSetTimeout(callback, 0, ...args); }) as typeof setTimeout; From e6acc751c9b60babf2fd06f397e560b26d8ad32a Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 16:23:25 -0300 Subject: [PATCH 100/410] fix(wallet): count only active rate limit windows --- src/utils/rate-limiter.ts | 19 +++---- tests/rate-limiter.windows.test.ts | 79 ++++++++++++++++++++++++++++-- 2 files changed, 81 insertions(+), 17 deletions(-) diff --git a/src/utils/rate-limiter.ts b/src/utils/rate-limiter.ts index 6f4df2cf..a0e185ab 100644 --- a/src/utils/rate-limiter.ts +++ b/src/utils/rate-limiter.ts @@ -36,7 +36,7 @@ export class SlidingWindowRateLimiter { } consume(key: string | number | bigint, limit: number): RateLimiterConsumeResult { - const normalizedKey = typeof key === "bigint" ? key.toString() : String(key); + const normalizedKey = String(key); const normalizedLimit = Number(limit); if (!Number.isFinite(normalizedLimit) || normalizedLimit <= 0) { @@ -44,13 +44,10 @@ export class SlidingWindowRateLimiter { } const now = this.now(); - this.pruneExpiredBuckets(now); + this.pruneExpiredBuckets(now, false); const entry = this.buckets.get(normalizedKey); if (!entry || now - entry.windowStart >= this.windowMs) { - if (entry) { - this.buckets.delete(normalizedKey); - } this.buckets.set(normalizedKey, { windowStart: now, count: 1 }); return { allowed: true, @@ -59,14 +56,13 @@ export class SlidingWindowRateLimiter { }; } + const resetInMs = Math.max(entry.windowStart + this.windowMs - now, 0); if (entry.count >= normalizedLimit) { - const resetInMs = Math.max(entry.windowStart + this.windowMs - now, 0); return { allowed: false, remaining: 0, resetInMs }; } entry.count += 1; const remaining = Math.max(0, normalizedLimit - entry.count); - const resetInMs = Math.max(entry.windowStart + this.windowMs - now, 0); return { allowed: true, remaining, resetInMs }; } @@ -75,21 +71,20 @@ export class SlidingWindowRateLimiter { this.buckets.clear(); return; } - const normalizedKey = typeof key === "bigint" ? key.toString() : String(key); - this.buckets.delete(normalizedKey); + this.buckets.delete(String(key)); } getActiveEntries(): number { - this.pruneExpiredBuckets(this.now()); + this.pruneExpiredBuckets(this.now(), true); return this.buckets.size; } - private pruneExpiredBuckets(currentTime: number): void { + private pruneExpiredBuckets(currentTime: number, force: boolean): void { if (this.buckets.size === 0) { return; } - if (currentTime - this.lastPruneAt < this.windowMs) { + if (!force && currentTime - this.lastPruneAt < this.windowMs) { return; } diff --git a/tests/rate-limiter.windows.test.ts b/tests/rate-limiter.windows.test.ts index 81428834..2c3ad34f 100644 --- a/tests/rate-limiter.windows.test.ts +++ b/tests/rate-limiter.windows.test.ts @@ -1,5 +1,5 @@ -import { describe, expect, test } from "bun:test"; -import { SlidingWindowRateLimiter } from "../src/utils/rate-limiter"; +import { describe, expect, spyOn, test } from "bun:test"; +import { RateLimitExceededError, SlidingWindowRateLimiter } from "../src/utils/rate-limiter"; describe("SlidingWindowRateLimiter edge cases", () => { test("rejects a window that is not a positive finite duration", () => { @@ -32,8 +32,77 @@ describe("SlidingWindowRateLimiter edge cases", () => { }); test("the default clock is the wall clock", () => { - const limiter = new SlidingWindowRateLimiter(60_000); - expect(limiter.consume("wall", 1).allowed).toBe(true); - expect(limiter.consume("wall", 1).allowed).toBe(false); + let now = 40_000; + const wallClock = spyOn(Date, "now").mockImplementation(() => now); + try { + const limiter = new SlidingWindowRateLimiter(); + expect(limiter.consume("wall", 1)).toEqual({ + allowed: true, + remaining: 0, + resetInMs: 30_000, + }); + now += 29_999; + expect(limiter.consume("wall", 1)).toEqual({ allowed: false, remaining: 0, resetInMs: 1 }); + now += 1; + expect(limiter.consume("wall", 1)).toEqual({ + allowed: true, + remaining: 0, + resetInMs: 30_000, + }); + } finally { + wallClock.mockRestore(); + } }); + + test("reports the exact remaining time without sliding the window on a second consume", () => { + let now = 12_500; + const limiter = new SlidingWindowRateLimiter(1_000, () => now); + expect(limiter.consume("user", 2)).toEqual({ allowed: true, remaining: 1, resetInMs: 1_000 }); + now = 12_875; + expect(limiter.consume("user", 2)).toEqual({ allowed: true, remaining: 0, resetInMs: 625 }); + now = 13_499; + expect(limiter.consume("user", 2)).toEqual({ allowed: false, remaining: 0, resetInMs: 1 }); + now = 13_500; + expect(limiter.consume("user", 2)).toEqual({ allowed: true, remaining: 1, resetInMs: 1_000 }); + }); + + test("joins exact bigint and decimal-string keys without merging adjacent accounts", () => { + const limiter = new SlidingWindowRateLimiter(1_000, () => 0); + const first = 9_007_199_254_740_992n; + const second = 9_007_199_254_740_993n; + expect(limiter.consume(first, 1).allowed).toBe(true); + expect(limiter.consume(second, 1).allowed).toBe(true); + expect(limiter.consume("9007199254740992", 1).allowed).toBe(false); + expect(limiter.consume("9007199254740993", 1).allowed).toBe(false); + limiter.reset("9007199254740992"); + expect(limiter.consume(first, 1).allowed).toBe(true); + expect(limiter.consume(second, 1).allowed).toBe(false); + }); + + test("counts active windows even when two keys expire less than one window apart", () => { + let now = 0; + const limiter = new SlidingWindowRateLimiter(1_000, () => now); + limiter.consume("earlier", 1); + now = 500; + limiter.consume("later", 1); + now = 1_000; + expect(limiter.getActiveEntries()).toBe(1); + now = 1_499; + expect(limiter.getActiveEntries()).toBe(1); + now = 1_500; + expect(limiter.getActiveEntries()).toBe(0); + }); +}); + +test.each([ + [-1, 0], + [0, 0], + [1.49, 1], + [1.5, 2], +])("a rate-limit error identifies the failure and rounds a %p ms delay", (delay, expected) => { + const error = new RateLimitExceededError("Wallet refresh limit reached", delay); + expect(error).toBeInstanceOf(Error); + expect(error.name).toBe("RateLimitExceededError"); + expect(error.message).toBe("Wallet refresh limit reached"); + expect(error.retryAfterMs).toBe(expected); }); From f55dd3617ee60d2b6df47e11d83fbbd7aa6183ff Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 16:23:25 -0300 Subject: [PATCH 101/410] test(games): keep invalid direct amounts in command validation --- tests/game-command-input.test.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/tests/game-command-input.test.ts b/tests/game-command-input.test.ts index 127cae52..b52b9fdd 100644 --- a/tests/game-command-input.test.ts +++ b/tests/game-command-input.test.ts @@ -9,6 +9,7 @@ test.each([ [[".125"], "direct", undefined, ".125"], [[".abc"], "menu", ".abc", undefined], [["1.abc"], "menu", "1.abc", undefined], + [["1.abc", "BONK"], "direct", "BONK", "1.abc"], [["2.2", "bOnK"], "direct", "bOnK", "2.2"], [["2.2", "", "BONK"], "direct", "BONK", "2.2"], [["1", ".123"], "direct", undefined, "1"], From 8713a4b41fdf466eb8bd8f7613db61a52ea31872 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 16:27:05 -0300 Subject: [PATCH 102/410] fix(wallet): report mint lookup errors without hiding them as missing --- src/utils/token-programs.ts | 29 ++++++++++++++-------- tests/token-programs.test.ts | 47 +++++++++++++++++++++++++++++++++++- 2 files changed, 65 insertions(+), 11 deletions(-) diff --git a/src/utils/token-programs.ts b/src/utils/token-programs.ts index 55ff7124..b6976eb6 100644 --- a/src/utils/token-programs.ts +++ b/src/utils/token-programs.ts @@ -13,6 +13,16 @@ type AccountInfoLike = { type AccountInfoLoader = Pick; +function isMissingMintAccount(error: unknown): boolean { + const message = error instanceof Error ? error.message : error; + return ( + typeof message === "string" && + /\bcould not find (?:the )?(?:account|mint)\b|\b(?:account|mint)(?: [1-9A-HJ-NP-Za-km-z]{32,44})?(?: was)? not found\b/i.test( + message, + ) + ); +} + export async function detectTokenProgram( connection: AccountInfoLoader, mint: string | PublicKey, @@ -20,9 +30,15 @@ export async function detectTokenProgram( ): Promise { try { const mintKey = typeof mint === "string" ? new PublicKey(mint) : mint; - const accountInfo = - preloadedAccountInfo ?? - ((await connection.getAccountInfo(mintKey)) as AccountInfoLike | null); + let accountInfo = preloadedAccountInfo; + if (accountInfo == null) { + try { + accountInfo = await connection.getAccountInfo(mintKey); + } catch (error) { + if (isMissingMintAccount(error)) return null; + throw error; + } + } if (!accountInfo) { return null; @@ -59,13 +75,6 @@ export async function detectTokenProgram( }; } catch (error) { const mintAddress = typeof mint === "string" ? mint : mint.toBase58(); - const message = error instanceof Error ? error.message : typeof error === "string" ? error : ""; - if ( - message.toLowerCase().includes("could not find account") || - message.toLowerCase().includes("not found") - ) { - return null; - } console.log(`Error checking token program for ${mintAddress}:`, error); throw error; } diff --git a/tests/token-programs.test.ts b/tests/token-programs.test.ts index f5793c46..202bbae5 100644 --- a/tests/token-programs.test.ts +++ b/tests/token-programs.test.ts @@ -1,5 +1,5 @@ import { describe, test, expect, spyOn } from "bun:test"; -import { Connection, PublicKey } from "#solana"; +import { Connection, PublicKey, SolanaJSONRPCError } from "#solana"; import { TOKEN_2022_PROGRAM_ID, TOKEN_PROGRAM_ID } from "#token"; import { detectTokenProgram } from "../src/utils/token-programs"; @@ -97,6 +97,7 @@ describe("detectTokenProgram", () => { for (const failure of [ new Error("Could not find account 2zsB6q5fkvMS4L7HhQTF19EaiqRkJWhGXZ6Q3A1tqhzd"), "Account NOT FOUND", + "Mint 2zsB6q5fkvMS4L7HhQTF19EaiqRkJWhGXZ6Q3A1tqhzd was not found", ]) { const conn = { async getAccountInfo() { @@ -132,4 +133,48 @@ describe("detectTokenProgram", () => { logSpy.mockRestore(); } }); + + test.each([ + ["missing RPC method", new SolanaJSONRPCError({ code: -32601, message: "Method not found" })], + ["missing RPC endpoint", "Endpoint NOT FOUND"], + ["untyped provider failure", { status: 404 }], + ] as const)("reports %s rather than calling the mint absent", async (_name, failure) => { + const mint = TOKEN_PROGRAM_ID; + const connection = new Connection("http://localhost:8899"); + const lookup = spyOn(connection, "getAccountInfo").mockRejectedValue(failure); + const log = spyOn(console, "log").mockImplementation(() => {}); + try { + await expect(detectTokenProgram(connection, mint)).rejects.toBe(failure); + expect(lookup).toHaveBeenCalledWith(mint); + expect(log).toHaveBeenCalledWith( + `Error checking token program for ${mint.toBase58()}:`, + failure, + ); + } finally { + log.mockRestore(); + lookup.mockRestore(); + } + }); + + test("does not classify a malformed preloaded owner as a provider miss", async () => { + const mint = TOKEN_PROGRAM_ID; + const connection = new Connection("http://localhost:8899"); + const lookup = spyOn(connection, "getAccountInfo").mockRejectedValue( + new Error("unexpected lookup"), + ); + const log = spyOn(console, "log").mockImplementation(() => {}); + try { + await expect( + detectTokenProgram(connection, mint, { + owner: "account not found" as unknown as PublicKey, + }), + ).rejects.toThrow( + `Token mint ${mint.toBase58()} is owned by an unknown program (account not found)`, + ); + expect(lookup).not.toHaveBeenCalled(); + } finally { + log.mockRestore(); + lookup.mockRestore(); + } + }); }); From eb9fd7485483a49bfbdf8197aed2a98a3b4d1952 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 16:27:05 -0300 Subject: [PATCH 103/410] refactor(tokens): use the default grapheme segmentation --- src/utils/token-display.ts | 4 ++-- tests/token-display.test.ts | 8 ++++++++ 2 files changed, 10 insertions(+), 2 deletions(-) diff --git a/src/utils/token-display.ts b/src/utils/token-display.ts index eb5623e7..3da4ddb0 100644 --- a/src/utils/token-display.ts +++ b/src/utils/token-display.ts @@ -17,7 +17,7 @@ export function sanitizeTokenSymbol(symbol: unknown, mint?: string): string { if (!normalized) return abbreviateMint(mint); const graphemes = Array.from( - new Intl.Segmenter("en", { granularity: "grapheme" }).segment(normalized), + new Intl.Segmenter("en").segment(normalized), ({ segment }) => segment, ); if (graphemes.length <= MAX_TOKEN_SYMBOL_GRAPHEMES) return normalized; @@ -29,7 +29,7 @@ export function truncateTokenDisplay(value: unknown, maxGraphemes = 64): string .replace(/[\p{Cc}\p{Cf}\p{Cs}]/gu, "") .trim(); const graphemes = Array.from( - new Intl.Segmenter("en", { granularity: "grapheme" }).segment(normalized), + new Intl.Segmenter("en").segment(normalized), ({ segment }) => segment, ); if (graphemes.length <= maxGraphemes) return normalized; diff --git a/tests/token-display.test.ts b/tests/token-display.test.ts index 15cece24..393a6f27 100644 --- a/tests/token-display.test.ts +++ b/tests/token-display.test.ts @@ -33,6 +33,14 @@ test("truncates general display text by grapheme instead of UTF-16 code units", expect(truncateTokenDisplay("x".repeat(65))).toBe("x".repeat(63) + "…"); }); +test("treats a flag as one displayed character at both truncation limits", () => { + const flag = "🇦🇷"; + expect(sanitizeTokenSymbol(`${flag.repeat(9)}A`)).toBe(`${flag.repeat(9)}A`); + expect(sanitizeTokenSymbol(`${flag.repeat(9)}AB`)).toBe(`${flag.repeat(9)}…`); + expect(truncateTokenDisplay(`${flag}A`, 2)).toBe(`${flag}A`); + expect(truncateTokenDisplay(`${flag}AB`, 2)).toBe(`${flag}…`); +}); + test("adds the mint only to tickers that collide after normalization", () => { expect( resolveTokenDisplaySymbols([ From d67deea74e74d50eccf7d97379d8fee969d10042 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 16:28:20 -0300 Subject: [PATCH 104/410] test(telegram): verify display names and invisible mention separators --- tests/telegram-display.test.ts | 44 ++++++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 tests/telegram-display.test.ts diff --git a/tests/telegram-display.test.ts b/tests/telegram-display.test.ts new file mode 100644 index 00000000..e143ad44 --- /dev/null +++ b/tests/telegram-display.test.ts @@ -0,0 +1,44 @@ +import { expect, test } from "bun:test"; +import { + getTelegramUserDisplayName, + sanitizeTelegramDisplayName, + sanitizeTelegramDisplayNameWithoutMention, +} from "../src/utils/telegram-display"; + +test.each([ + [null, "Player"], + [undefined, "Player"], + [" \t ", "Player"], + [" Ada ", "Ada"], + ["@ada", "@ada"], +] as const)("normalizes a display name from %p", (name, expected) => { + expect(sanitizeTelegramDisplayName(name)).toBe(expected); +}); + +test("puts one invisible separator after each run of at signs, including in the fallback", () => { + expect(sanitizeTelegramDisplayNameWithoutMention(" @@Ada @Bob@@ ")).toBe( + "@@\u2060Ada @\u2060Bob@@\u2060", + ); + expect(sanitizeTelegramDisplayNameWithoutMention(null, "@Former")).toBe("@\u2060Former"); + expect(sanitizeTelegramDisplayNameWithoutMention("Ada")).toBe("Ada"); + expect(sanitizeTelegramDisplayName("@Ada", "Player", { preventMention: false })).toBe("@Ada"); +}); + +test.each([ + [null, "User"], + [undefined, "User"], + [{}, "User"], + [{ username: " @@Ada ", first_name: "Grace" }, "@Ada"], + [{ username: "Ad@home" }, "@Ad@home"], + [{ username: "@@", first_name: " Ada ", last_name: " Lovelace \t" }, "Ada Lovelace"], + [{ first_name: " ", last_name: " Lovelace " }, "Lovelace"], + [{ first_name: " Ada ", last_name: " \t" }, "Ada"], +] as const)("uses the normalized handle or name parts for %p", (user, expected) => { + expect(getTelegramUserDisplayName(user)).toBe(expected); +}); + +test("uses the caller's fallback when no handle or name parts are available", () => { + expect(getTelegramUserDisplayName({ username: " @@ ", first_name: " " }, "Unknown")).toBe( + "Unknown", + ); +}); From 3ca9e15787da082bcbabc228c6869708fa512677 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 16:31:35 -0300 Subject: [PATCH 105/410] test(logging): verify timestamped console calls --- tests/logging.test.ts | 41 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 tests/logging.test.ts diff --git a/tests/logging.test.ts b/tests/logging.test.ts new file mode 100644 index 00000000..da1fde21 --- /dev/null +++ b/tests/logging.test.ts @@ -0,0 +1,41 @@ +import { expect, mock, setSystemTime, test } from "bun:test"; + +test("installation adds one timestamp to every console level and preserves the original arguments", async () => { + const methods = ["log", "info", "warn", "error", "debug", "trace"] as const; + const captures = methods.map((method) => { + const original = console[method]; + const receivers: unknown[] = []; + const capture = mock(function (this: unknown, ..._args: unknown[]) { + receivers.push(this); + }); + console[method] = capture; + return { method, original, capture, receivers }; + }); + + try { + setSystemTime(new Date("2026-04-22T09:10:11.012Z")); + const logger: typeof import("../src/utils/logging") = await import( + `../src/utils/logging?${"test-install"}` + ); + const details = { count: 2 }; + for (const { method } of captures) console[method]("ready", details, undefined); + + // Explicit calls after the import must not wrap an already wrapped console. + logger.installTimestampLogger(); + logger.installTimestampLogger(); + setSystemTime(new Date("2026-04-22T09:10:11.013Z")); + for (const { method } of captures) console[method](details, 0); + + for (const { method, capture, receivers } of captures) { + expect(capture.mock.calls, method).toEqual([ + ["[2026-04-22T09:10:11.012Z]", "ready", details, undefined], + ["[2026-04-22T09:10:11.013Z]", details, 0], + ]); + expect(capture.mock.calls[0]?.[2], method).toBe(details); + expect(receivers, method).toEqual([console, console]); + } + } finally { + setSystemTime(); + for (const { method, original } of captures) console[method] = original; + } +}); From 11a9703771f3f3dcbe83f63fb05a28a5152fcff3 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 16:31:35 -0300 Subject: [PATCH 106/410] test(secrets): verify protected file precedence and errors --- src/utils/secrets.ts | 8 ++++++-- tests/secrets.test.ts | 36 +++++++++++++++++++++++++++++++++++- 2 files changed, 41 insertions(+), 3 deletions(-) diff --git a/src/utils/secrets.ts b/src/utils/secrets.ts index 27361d09..6ebef4c6 100644 --- a/src/utils/secrets.ts +++ b/src/utils/secrets.ts @@ -49,7 +49,9 @@ export function readProtectedSecretFile(filePath: string, label: string): string } } -export function loadWalletMnemonic(env: NodeJS.ProcessEnv = process.env): string { +export function loadWalletMnemonic( + env: Pick = process.env, +): string { const file = env.MNEMONIC_FILE?.trim(); const mnemonic = file ? readProtectedSecretFile(file, "Wallet mnemonic file") @@ -60,7 +62,9 @@ export function loadWalletMnemonic(env: NodeJS.ProcessEnv = process.env): string return mnemonic; } -export function loadOracleApiToken(env: NodeJS.ProcessEnv = process.env): string | undefined { +export function loadOracleApiToken( + env: Pick = process.env, +): string | undefined { const file = env.ORACLE_API_TOKEN_FILE?.trim(); return file ? readProtectedSecretFile(file, "Oracle API token file") diff --git a/tests/secrets.test.ts b/tests/secrets.test.ts index 64f8aea2..b4279480 100644 --- a/tests/secrets.test.ts +++ b/tests/secrets.test.ts @@ -38,6 +38,35 @@ describe("protected secrets", () => { ).toBe("token"); }); + test("uses a configured mnemonic file before the development environment value", () => { + const file = secretFile(` ${mnemonic}\n`); + expect(loadWalletMnemonic({ MNEMONIC_FILE: ` ${file} `, MNEMONIC: "invalid" })).toBe(mnemonic); + expect(loadWalletMnemonic({ MNEMONIC_FILE: " \t ", MNEMONIC: ` \n${mnemonic} ` })).toBe( + mnemonic, + ); + expect(() => + loadWalletMnemonic({ MNEMONIC_FILE: `${file}.missing`, MNEMONIC: mnemonic }), + ).toThrow(/ENOENT/); + }); + + test("uses a configured oracle token file and only falls back when no path was supplied", () => { + const file = secretFile("file-token\n"); + expect( + loadOracleApiToken({ ORACLE_API_TOKEN_FILE: ` ${file} `, ORACLE_API_TOKEN: "env-token" }), + ).toBe("file-token"); + expect( + loadOracleApiToken({ ORACLE_API_TOKEN_FILE: " \t ", ORACLE_API_TOKEN: " env-token " }), + ).toBe("env-token"); + expect(loadOracleApiToken({ ORACLE_API_TOKEN: " \t " })).toBeUndefined(); + expect(loadOracleApiToken({})).toBeUndefined(); + expect(() => + loadOracleApiToken({ + ORACLE_API_TOKEN_FILE: `${file}.missing`, + ORACLE_API_TOKEN: "env-token", + }), + ).toThrow(/ENOENT/); + }); + test("rejects group-readable files", () => { const file = secretFile("token"); chmodSync(file, 0o640); @@ -57,7 +86,12 @@ describe("protected secrets", () => { const target = secretFile("token"); const link = `${target}-link`; symlinkSync(target, link); - expect(() => readProtectedSecretFile(link, "Secret")).toThrow("not a symlink"); + expect(() => readProtectedSecretFile(link, "Secret")).toThrow( + expect.objectContaining({ + message: "Secret must be a regular file, not a symlink", + cause: expect.objectContaining({ code: "ELOOP" }), + }), + ); }); test("rejects invalid BIP-39 mnemonics", () => { From 1b26bfdf9c6cf5441d71109dd2c5caaa86dcfa34 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 16:31:35 -0300 Subject: [PATCH 107/410] refactor(telegram): parse update age overrides once --- src/utils/recent-update.ts | 18 +++++------------- tests/recent-update.guard.test.ts | 26 ++++++++++++++++++++++++++ 2 files changed, 31 insertions(+), 13 deletions(-) diff --git a/src/utils/recent-update.ts b/src/utils/recent-update.ts index b193cabb..8efd8031 100644 --- a/src/utils/recent-update.ts +++ b/src/utils/recent-update.ts @@ -24,21 +24,13 @@ function getUpdateUnixSeconds(ctx: Context): number | null { } function resolveMaxAgeSec(ctx: Context): number { - const legacyOverride = process.env["MAX_UPDATE_AGE_SEC"]; - if (legacyOverride) { - const parsed = Number(legacyOverride); - if (Number.isFinite(parsed) && parsed > 0) return parsed; - } + const legacyOverride = Number(process.env["MAX_UPDATE_AGE_SEC"]); + if (Number.isFinite(legacyOverride) && legacyOverride > 0) return legacyOverride; - const isCallback = Boolean((ctx as any).callbackQuery); + const isCallback = Boolean(ctx.callbackQuery); const envKey = isCallback ? "MAX_CALLBACK_AGE_SEC" : "MAX_MESSAGE_AGE_SEC"; - const envValue = process.env[envKey]; - if (envValue) { - const parsed = Number(envValue); - if (Number.isFinite(parsed) && parsed > 0) { - return parsed; - } - } + const ageOverride = Number(process.env[envKey]); + if (Number.isFinite(ageOverride) && ageOverride > 0) return ageOverride; return isCallback ? DEFAULT_MAX_CALLBACK_AGE_SEC : DEFAULT_MAX_MESSAGE_AGE_SEC; } diff --git a/tests/recent-update.guard.test.ts b/tests/recent-update.guard.test.ts index 66d7441c..65c2155c 100644 --- a/tests/recent-update.guard.test.ts +++ b/tests/recent-update.guard.test.ts @@ -106,6 +106,32 @@ test.each([ } }); +test.each([undefined, "", " \t ", "0", "-1", "invalid", "Infinity"])( + "ignores a non-positive or absent age override (%p)", + async (value) => { + const now = 1_700_000_000; + const clock = spyOn(Date, "now").mockReturnValue(now * 1_000); + const next = mock(async () => {}); + const answer = mock(async () => true); + try { + if (value !== undefined) { + process.env["MAX_UPDATE_AGE_SEC"] = value; + process.env["MAX_MESSAGE_AGE_SEC"] = value; + } + for (const age of [60, 61]) { + await recentUpdateGuard( + { message: { date: now - age }, answerCallbackQuery: answer } as unknown as Context, + next, + ); + } + expect(next).toHaveBeenCalledTimes(1); + expect(answer).not.toHaveBeenCalled(); + } finally { + clock.mockRestore(); + } + }, +); + test.each([ ["editedMessage", "edit_date"], ["channelPost", "date"], From a336af64cad3616fad6f328d87baa1116bd6be3b Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 16:33:32 -0300 Subject: [PATCH 108/410] test(swaps): verify selectable inputs in the custom swap prompt --- tests/swap-prompts.test.ts | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/tests/swap-prompts.test.ts b/tests/swap-prompts.test.ts index e716ab1e..fae22c6b 100644 --- a/tests/swap-prompts.test.ts +++ b/tests/swap-prompts.test.ts @@ -1,4 +1,5 @@ import { expect, test } from "bun:test"; +import { INPUT_TIMEOUT_HINT } from "../src/utils/constants"; import { buildCustomTokenPrompt } from "../src/utils/swap/prompts"; test("buildCustomTokenPrompt escapes HTML-sensitive token symbols", () => { @@ -7,3 +8,18 @@ test("buildCustomTokenPrompt escapes HTML-sensitive token symbols", () => { expect(prompt).toContain("Swapping FROM: <img src=x onerror="alert(1)">"); expect(prompt).not.toContain(''); }); + +test("keeps the selected input, reply instructions and both supported example inputs separate", () => { + const prompt = buildCustomTokenPrompt("SOL"); + const paragraphs = prompt.split("\n\n"); + expect(paragraphs).toHaveLength(5); + expect(paragraphs.every((paragraph) => paragraph.trim().length > 0)).toBe(true); + expect(paragraphs[1]).toContain("SOL"); + expect(paragraphs[2]).toMatch(/reply.+mint address or symbol/i); + const examples = Array.from( + (paragraphs[3] ?? "").matchAll(/([^<]+)<\/code>/g), + (match) => match[1], + ); + expect(examples).toEqual(["EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v", "BONK"]); + expect(paragraphs[4]).toBe(INPUT_TIMEOUT_HINT); +}); From b495317e1aa905316b59474d093c9fe8fe3fe674 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 16:37:40 -0300 Subject: [PATCH 109/410] test(wallet): expect malformed mint owner errors to remain visible --- tests/wallet.transactions.test.ts | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/tests/wallet.transactions.test.ts b/tests/wallet.transactions.test.ts index ba9bc426..4400b51f 100644 --- a/tests/wallet.transactions.test.ts +++ b/tests/wallet.transactions.test.ts @@ -252,23 +252,22 @@ describe("token metadata lookups", () => { ); }); - test("reports a mint whose owner lookup says it is missing", async () => { + test("does not report a malformed mint owner as a missing mint", async () => { const mint = await newMint(); + const ownerFailure = new Error("account not found"); const wallet = walletWith({ getAccountInfo: async () => ({ owner: { equals: () => { - throw new Error("account not found"); + throw ownerFailure; }, }, data: Buffer.alloc(0), }), }); - await expect(decimalsOf(wallet, mint)).rejects.toThrow( - "Token mint account not found or has no data", - ); - expect(messages(warnSpy)).toContain(`⚠️ Unsupported token mint detected: ${mint}`); + await expect(decimalsOf(wallet, mint)).rejects.toBe(ownerFailure); + expect(messages(warnSpy)).not.toContain(`⚠️ Unsupported token mint detected: ${mint}`); }); }); }); From 88a72ea2df611cf3de32ae6e3a67645d80c86017 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 16:37:41 -0300 Subject: [PATCH 110/410] fix(wallet): expire cached missing token mints --- src/utils/wallet.ts | 15 ++++++---- tests/wallet.balances-edge-cases.test.ts | 37 ++++++++++++++++++++++++ 2 files changed, 47 insertions(+), 5 deletions(-) diff --git a/src/utils/wallet.ts b/src/utils/wallet.ts index 047843f7..5886677e 100644 --- a/src/utils/wallet.ts +++ b/src/utils/wallet.ts @@ -400,7 +400,7 @@ export class WalletManager { private confirmationTimeoutMs = CONFIRMATION_TIMEOUT_MS; private signaturePollIntervalMs = SIGNATURE_POLL_INTERVAL_MS; private rebroadcastIntervalMs = REBROADCAST_INTERVAL_MS; - private mintProgramCache = new Map(); + private mintProgramCache = new Map(); private missingMintWarnings = new Map(); private nativeBalanceCache = createExpiringCache(WALLET_RPC_CACHE_TTL_MS); private walletTokenBalanceCache = @@ -672,7 +672,7 @@ export class WalletManager { ): void { for (const token of knownTokens) { const detection = this.mintProgramCache.get(token.token_mint); - if (detection) { + if (detection && "programId" in detection) { token.token_program_id = detection.programId.toBase58(); } } @@ -684,14 +684,19 @@ export class WalletManager { const mintKey = typeof mint === "string" ? new PublicKey(mint) : mint; const cacheKey = mintKey.toBase58(); const cached = this.mintProgramCache.get(cacheKey); - if (cached !== undefined) { - return cached; + if (cached) { + if ("programId" in cached) return cached; + if ((this.timeNow?.() ?? Date.now()) < cached.missingUntil) return null; + this.mintProgramCache.delete(cacheKey); } const detection = await detectTokenProgram(this.connection, mintKey); if (!detection) { this.logMissingMintWarning(cacheKey); - this.mintProgramCache.set(cacheKey, null); + // A missing mint may appear after the provider catches up or the mint is created. + this.mintProgramCache.set(cacheKey, { + missingUntil: (this.timeNow?.() ?? Date.now()) + WALLET_RPC_CACHE_TTL_MS, + }); return null; } this.mintProgramCache.set(cacheKey, detection); diff --git a/tests/wallet.balances-edge-cases.test.ts b/tests/wallet.balances-edge-cases.test.ts index 05d3ae1b..e7517017 100644 --- a/tests/wallet.balances-edge-cases.test.ts +++ b/tests/wallet.balances-edge-cases.test.ts @@ -11,6 +11,7 @@ import { type WalletTokenBalance, type WalletTokenCensus, } from "../src/utils/wallet"; +import { stubInstantTimers } from "./helpers/timers"; const MNEMONIC = process.env.MNEMONIC!; const USDC = "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"; @@ -220,6 +221,42 @@ describe("getTokenBalance", () => { expect(messages(warnSpy)).toContain(`⚠️ Unsupported token mint detected: ${USDC}`); }); + test("rechecks a missing mint after the wallet cache window and reads the new balance", async () => { + const startedAt = 1_000_000; + let now = startedAt; + let mintReads = 0; + const mint = new PublicKey(USDC); + const data = Buffer.alloc(AccountLayout.span); + const wallet = walletWith( + { + getAccountInfo: async (key: PublicKey) => { + if (key.equals(mint)) { + mintReads += 1; + return mintReads === 1 ? null : { owner: TOKEN_PROGRAM_ID }; + } + return { owner: TOKEN_PROGRAM_ID, data }; + }, + }, + { timeNow: () => now }, + ); + const owner = await wallet.getPublicKey(TELEGRAM_ID); + AccountLayout.encode({ mint, owner, amount: 12_345n, state: 1 }, data); + const timers = stubInstantTimers(); + try { + expect(await wallet.getTokenBalance(TELEGRAM_ID, USDC)).toBe(0); + now = startedAt + 19_999; + expect(await wallet.getTokenBalance(TELEGRAM_ID, USDC)).toBe(0); + expect(mintReads).toBe(1); + now += 1; + expect(await wallet.getTokenBalance(TELEGRAM_ID, USDC)).toBe(12_345); + now += 20_000; + expect(await wallet.getTokenBalance(TELEGRAM_ID, USDC)).toBe(12_345); + expect(mintReads).toBe(2); + } finally { + timers.restore(); + } + }); + test("gives up on auto-creating the account if the mint disappears meanwhile", async () => { const wallet = walletWith({ getAccountInfo: async (key: PublicKey) => From 5626f9026b0e351a1b71f26634f7baf67116e1ce Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 16:38:01 -0300 Subject: [PATCH 111/410] test(events): verify current payouts and legacy log boundaries --- src/utils/program-event-parser.ts | 4 ++- tests/program-event-parser.test.ts | 45 ++++++++++++++++++++++++++++++ 2 files changed, 48 insertions(+), 1 deletion(-) diff --git a/src/utils/program-event-parser.ts b/src/utils/program-event-parser.ts index d2349024..b39b9e3a 100644 --- a/src/utils/program-event-parser.ts +++ b/src/utils/program-event-parser.ts @@ -43,8 +43,9 @@ export function decodeProgramEventLog( } catch { /* Keep the legacy caller's fallback behavior. */ } + if (!decodeFallback) return null; try { - return decodeFallback?.(logBase64) ?? null; + return decodeFallback(logBase64) ?? null; } catch { return null; } @@ -66,5 +67,6 @@ export function parseProgramEventsFromTransaction( program: Pick, logs: readonly string[] | null | undefined, ): ProgramEvent[] { + // Stryker disable next-line ArrayDeclaration: The added string is not a program log, so the decoder discards it like an empty input. return parseProgramEventLogs(program.programId, logs ?? []); } diff --git a/tests/program-event-parser.test.ts b/tests/program-event-parser.test.ts index 9df6290f..fe1c40d3 100644 --- a/tests/program-event-parser.test.ts +++ b/tests/program-event-parser.test.ts @@ -121,9 +121,51 @@ describe("legacy PlayerRefunded layout", () => { const longer = Buffer.concat([legacy, Buffer.from([0])]).toString("base64"); expect(decodeLegacyPlayerRefunded(longer)).toBeNull(); }); + + test("does not recognize arbitrary data that happens to have the legacy length", () => { + expect(decodeLegacyPlayerRefunded(Buffer.alloc(104).toString("base64"))).toBeNull(); + }); }); describe("decodeProgramEventLog", () => { + test("adapts the moved participant in the current refund layout to a public key", () => { + const movedParticipant = new PublicKey("EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"); + const legacy = Buffer.from( + encodeLegacyPlayerRefunded({ + gameKey: GAME, + player: PLAYER, + totalAmount: 40n, + ticketsCount: 2, + ticketIndex: 0, + lastSlot: 17n, + timestamp: 123n, + }), + "base64", + ); + const payload = Buffer.concat([ + Buffer.from(EVENT_DISCRIMINATORS.PlayerRefunded), + legacy.subarray(8, 88), + Buffer.from([1]), + movedParticipant.toBuffer(), + legacy.subarray(88), + ]); + + const event = decodeProgramEventLog(payload.toString("base64")); + expect(event).toEqual({ + name: "PlayerRefunded", + data: { + gameKey: GAME, + player: PLAYER, + totalAmount: 40n, + ticketsCount: 2, + ticketIndex: 0, + movedParticipant, + lastSlot: 17n, + timestamp: 123n, + }, + }); + }); + test("uses legacy layout before current IDL so last_slot is not misread as Option", () => { const log = encodeLegacyPlayerRefunded({ gameKey: GAME, @@ -241,11 +283,14 @@ describe("parseProgramEventLogs", () => { const events = parseProgramEventLogs(programId, [ `Program ${programId.toBase58()} invoke [1]`, `Program data: ${truncated.toString("base64")}`, + `Program data: ${Buffer.alloc(104).toString("base64")}`, `Program data: ${encodeGameCompleted(3n)}`, `Program ${programId.toBase58()} success`, ]); expect(events.map((e) => e.name)).toEqual(["GameCompleted"]); expect(events[0]!.data["feeAmount"]).toBe(3n); + expect(events[0]!.data["winner"]).toEqual(PLAYER); + expect(events[0]!.data).not.toHaveProperty("gameType"); }); }); From 9b75cbb9fd584a27f26896356f72e95801fb29d3 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 16:42:39 -0300 Subject: [PATCH 112/410] refactor(swaps): choose sponsorship only for the uncovered fee buffer --- src/utils/integrator-fees.ts | 44 +++++++++++++++-------------------- tests/integrator-fees.test.ts | 31 ++++++++++++++++++++++++ 2 files changed, 50 insertions(+), 25 deletions(-) diff --git a/src/utils/integrator-fees.ts b/src/utils/integrator-fees.ts index bc1fb6c5..6a93b69d 100644 --- a/src/utils/integrator-fees.ts +++ b/src/utils/integrator-fees.ts @@ -63,7 +63,6 @@ const estimateTradeUsdValue = async ( }; const estimateSolUsdValue = async (lamports: number): Promise => { - if (lamports <= 0) return 0; const lookup = await getUsdPrice({ tokenMint: WSOL_MINT }); if (!lookup || lookup.price <= 0) return 0; return (lamports / LAMPORTS_PER_SOL) * lookup.price; @@ -84,9 +83,9 @@ export interface DynamicFeeContext { inputAmountRaw: number; /** SOL shortfall in lamports that admin needs to cover */ shortfallLamports: number; - /** Base fee in bps (default: 85) */ + /** Base fee in bps (default: 100) */ baseFeeBps?: number; - /** Maximum extra fee in bps (default: 170) */ + /** Maximum extra fee in bps (default: 155) */ maxExtraBps?: number; /** Whether to throw on price resolution failure (default: false) */ throwOnPriceFailure?: boolean; @@ -174,35 +173,30 @@ export const resolveIntegratorSwapParams = async ( } = context; const isUnwrappingSol = inputMint === WSOL_MINT && isSolMint(outputMint); - const availableForFeesLamports = availableSolLamports; - const referralConfig = getReferralConfig(); - - const requiresAdminPayer = - Boolean(referralConfig.adminPayer) && Boolean(referralConfig.adminCloseAuthority); - - const effectiveSolFeeBufferLamports = requiresAdminPayer - ? Math.max(solFeeBufferLamports ?? 0, JUPITER_MIN_SOL_BALANCE_LAMPORTS) - : (solFeeBufferLamports ?? 0); - + const { adminPayer, adminCloseAuthority } = referralConfig; const baseFeeBps = clampReferralFeeBps( referralConfig.baseFeeBps ?? DEFAULT_REFERRAL_BASE_FEE_BPS, MIN_JUPITER_SWAP_FEE_BPS, MAX_REFERRAL_FEE_BPS, ); - if (availableForFeesLamports >= effectiveSolFeeBufferLamports || !requiresAdminPayer) { - return { - referralAccount: referralConfig.referralAccount, - referralFee: baseFeeBps, - payer: userPublicKey, - closeAuthority: userPublicKey, - payerKind: "user", - }; - } + const userPayer: IntegratorSwapParams = { + referralAccount: referralConfig.referralAccount, + referralFee: baseFeeBps, + payer: userPublicKey, + closeAuthority: userPublicKey, + payerKind: "user", + }; + if (!adminPayer || !adminCloseAuthority) return userPayer; - const shortfallLamports = effectiveSolFeeBufferLamports - availableForFeesLamports; + const effectiveSolFeeBufferLamports = Math.max( + solFeeBufferLamports ?? 0, + JUPITER_MIN_SOL_BALANCE_LAMPORTS, + ); + if (availableSolLamports >= effectiveSolFeeBufferLamports) return userPayer; + const shortfallLamports = effectiveSolFeeBufferLamports - availableSolLamports; const maxExtraBps = referralConfig.maxExtraFeeBps ?? DEFAULT_MAX_EXTRA_FEE_BPS; // Use unified fee calculation @@ -239,8 +233,8 @@ export const resolveIntegratorSwapParams = async ( return { referralAccount: referralConfig.referralAccount, referralFee: referralFeeBps, - payer: referralConfig.adminPayer!, - closeAuthority: referralConfig.adminCloseAuthority!, + payer: adminPayer, + closeAuthority: adminCloseAuthority, payerKind: "admin", }; }; diff --git a/tests/integrator-fees.test.ts b/tests/integrator-fees.test.ts index cd009df3..e18e9989 100644 --- a/tests/integrator-fees.test.ts +++ b/tests/integrator-fees.test.ts @@ -120,6 +120,37 @@ describe("Integrator fee calculations", () => { expect(spy).not.toHaveBeenCalled(); }); + test("requests sponsorship for one lamport below a custom buffer, but not at the buffer", async () => { + __test_setReferralConfig({ + referralAccount: REFERRAL_ACCOUNT, + adminPayer: "sponsor-payer", + adminCloseAuthority: "sponsor-authority", + }); + const price = vi + .spyOn(priceService, "getUsdPrice") + .mockResolvedValue(priceLookup(1, "fixture")); + const input = { + inputMint: ADMIN_REF_MINT1, + outputMint: WSOL_MINT, + inputTicker: "TKN", + inputDecimals: 6, + inputAmountRaw: 1_000_000_000, + userPublicKey: "sender-public-key", + solFeeBufferLamports: 100_000_000, + }; + await expect( + resolveIntegratorSwapParams({ ...input, availableSolLamports: 100_000_000 }), + ).resolves.toMatchObject({ payerKind: "user", referralFee: 100 }); + expect(price).not.toHaveBeenCalled(); + await expect( + resolveIntegratorSwapParams({ ...input, availableSolLamports: 99_999_999 }), + ).resolves.toMatchObject({ payerKind: "admin", referralFee: 101 }); + expect(price.mock.calls).toEqual([ + [{ tokenMint: ADMIN_REF_MINT1 }], + [{ tokenMint: WSOL_MINT }], + ]); + }); + test.each([ ["only the payer", { adminPayer: "sponsor-payer" }], ["only the close authority", { adminCloseAuthority: "sponsor-authority" }], From ea8be346599b1cc08622cb466ad41435dc2698b7 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 16:44:05 -0300 Subject: [PATCH 113/410] test(tokens): verify snapshot format and request cleanup --- src/utils/verified-token-registry.ts | 4 +-- tests/verified-token-registry.test.ts | 49 +++++++++++++++++++++++++-- 2 files changed, 49 insertions(+), 4 deletions(-) diff --git a/src/utils/verified-token-registry.ts b/src/utils/verified-token-registry.ts index 74683c1a..cb16c5b6 100644 --- a/src/utils/verified-token-registry.ts +++ b/src/utils/verified-token-registry.ts @@ -23,7 +23,7 @@ function loadSnapshot(): { mints: Set; savedAt: number } { const mints = new Set(localMints()); try { const snapshot = verifiedTokenSnapshotSchema.parse( - JSON.parse(readFileSync(snapshotPath, "utf8")), + JSON.parse(readFileSync(snapshotPath).toString()), ); for (const mint of snapshot.mints) mints.add(mint); return { mints, savedAt: snapshot.savedAt }; @@ -39,7 +39,7 @@ function saveSnapshot(mints: ReadonlySet): void { writeFileSync( temporaryPath, JSON.stringify({ savedAt: Date.now(), mints: [...mints].sort() }), - { encoding: "utf8", mode: 0o600 }, + { mode: 0o600 }, ); renameSync(temporaryPath, snapshotPath); } catch { diff --git a/tests/verified-token-registry.test.ts b/tests/verified-token-registry.test.ts index ed8ff569..a7fc8890 100644 --- a/tests/verified-token-registry.test.ts +++ b/tests/verified-token-registry.test.ts @@ -1,6 +1,6 @@ import { afterEach, beforeEach, describe, expect, spyOn, test, vi } from "bun:test"; import { existsSync, mkdirSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs"; -import { dirname } from "node:path"; +import { dirname, join } from "node:path"; import { __test_reloadVerifiedTokenSnapshot, __test_setVerifiedTokenMints, @@ -144,6 +144,39 @@ describe("verified token registry refresh", () => { } }); + test.each([undefined, " \t "])( + "uses the working directory when BOT_DB_DIR is %p", + async (path) => { + const original = process.env["BOT_DB_DIR"]; + const modulePath = "../src/utils/verified-token-registry.ts"; + try { + if (path === undefined) delete process.env["BOT_DB_DIR"]; + else process.env["BOT_DB_DIR"] = path; + const registry: typeof import("../src/utils/verified-token-registry") = await import( + `${modulePath}?default-directory-${path === undefined ? "unset" : "blank"}` + ); + expect(registry.__test_snapshotPath).toBe(join(process.cwd(), "verified-tokens.json")); + } finally { + if (original === undefined) delete process.env["BOT_DB_DIR"]; + else process.env["BOT_DB_DIR"] = original; + } + }, + ); + + test("clears the request deadline immediately after reading the current list", async () => { + vi.useFakeTimers(); + try { + respondWith(() => Response.json([{ id: BONK }])); + expect((await refresh()).has(BONK)).toBe(true); + const signal = requests[0]?.init?.signal; + expect(signal).toBeInstanceOf(AbortSignal); + vi.advanceTimersByTime(3_000); + expect(signal?.aborted).toBe(false); + } finally { + vi.useRealTimers(); + } + }); + test("a persisted snapshot is loaded on the next start", async () => { respondWith(() => Response.json([{ id: BONK }])); await refresh(); @@ -162,6 +195,18 @@ describe("verified token registry refresh", () => { expect([...reloaded].sort()).toEqual([...new Set(localMints())].sort()); }); + test("loads a Unicode snapshot without exposing non-address defaults", () => { + writeFileSync(__test_snapshotPath, JSON.stringify({ savedAt: 100, label: "Crème 🇦🇷" })); + expect(__test_reloadVerifiedTokenSnapshot()).toEqual(new Set(localMints())); + writeFileSync( + __test_snapshotPath, + JSON.stringify({ savedAt: 100, label: "Crème 🇦🇷", mints: [BONK] }), + ); + expect(__test_reloadVerifiedTokenSnapshot()).toEqual(new Set([...localMints(), BONK])); + writeFileSync(__test_snapshotPath, `\ufeff${JSON.stringify({ mints: [BONK] })}`); + expect(__test_reloadVerifiedTokenSnapshot()).toEqual(new Set(localMints())); + }); + test("skips the request entirely without an API key", async () => { delete process.env["JUPITER_API_KEY"]; respondWith(() => Response.json([{ id: BONK }])); @@ -173,7 +218,7 @@ describe("verified token registry refresh", () => { }); test.each([ - ["an HTTP error", () => new Response("rate limited", { status: 429 })], + ["an HTTP error with valid-looking data", () => Response.json([{ id: BONK }], { status: 429 })], ["an invalid payload", () => Response.json([{ id: "not-a-mint" }])], [ "a network failure", From a7080b96690c0dc22d736b074b88a91663018537 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 16:44:05 -0300 Subject: [PATCH 114/410] refactor(wallet): use the non-null preloaded mint lookup --- src/utils/token-programs.ts | 10 ++++++++++ src/utils/wallet.ts | 7 +------ 2 files changed, 11 insertions(+), 6 deletions(-) diff --git a/src/utils/token-programs.ts b/src/utils/token-programs.ts index b6976eb6..c435f47a 100644 --- a/src/utils/token-programs.ts +++ b/src/utils/token-programs.ts @@ -23,6 +23,16 @@ function isMissingMintAccount(error: unknown): boolean { ); } +export function detectTokenProgram( + connection: AccountInfoLoader, + mint: string | PublicKey, + preloadedAccountInfo: AccountInfoLike, +): Promise; +export function detectTokenProgram( + connection: AccountInfoLoader, + mint: string | PublicKey, + preloadedAccountInfo?: AccountInfoLike | null, +): Promise; export async function detectTokenProgram( connection: AccountInfoLoader, mint: string | PublicKey, diff --git a/src/utils/wallet.ts b/src/utils/wallet.ts index 5886677e..4adcf039 100644 --- a/src/utils/wallet.ts +++ b/src/utils/wallet.ts @@ -1806,12 +1806,7 @@ export class WalletManager { throw new Error("Token mint account not found or has no data"); } - const detection = await detectTokenProgram(this.connection, mintPublicKey, accountInfo as any); - if (!detection) { - this.logMissingMintWarning(tokenMint); - throw new Error("Token mint account not found or has no data"); - } - + const detection = await detectTokenProgram(this.connection, mintPublicKey, accountInfo); const mint = unpackMint(mintPublicKey, accountInfo, detection.programId); return mint.decimals; } From 1a919780ca08369fa98fbab23060643eb8d379d2 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 16:45:40 -0300 Subject: [PATCH 115/410] refactor(telegram): parse retry text only when it contains a delay --- src/utils/telegram-errors.ts | 17 ++++++++--------- tests/telegram-errors.test.ts | 6 ++++++ 2 files changed, 14 insertions(+), 9 deletions(-) diff --git a/src/utils/telegram-errors.ts b/src/utils/telegram-errors.ts index 854ef078..09d19358 100644 --- a/src/utils/telegram-errors.ts +++ b/src/utils/telegram-errors.ts @@ -1,5 +1,7 @@ import { retrySecondsToMilliseconds } from "./retry-delay"; +type ErrorText = { description?: unknown; message?: unknown }; + const getErrorString = (value: unknown): string => { if (typeof value === "string") { return value; @@ -9,17 +11,13 @@ const getErrorString = (value: unknown): string => { return ""; } - const description = (value as any).description ?? (value as any).message; + const error = value as ErrorText; + const description = error.description ?? error.message; return typeof description === "string" ? description : ""; }; -const normalize = (value: unknown): string => getErrorString(value).toLowerCase(); - const matchesAny = (value: unknown, phrases: string[]): boolean => { - const description = normalize(value); - if (!description) { - return false; - } + const description = getErrorString(value).toLowerCase(); return phrases.some((phrase) => description.includes(phrase)); }; @@ -102,8 +100,9 @@ export const getRetryAfterSeconds = (error: unknown): number | null => { } const description = getErrorString(error); - const match = description.match(/retry after (\d+)/i); - const seconds = Number.parseInt(match?.[1] ?? "", 10); + const capturedSeconds = description.match(/retry after (\d+)/i)?.[1]; + if (capturedSeconds === undefined) return null; + const seconds = Number.parseInt(capturedSeconds, 10); return retrySecondsToMilliseconds(seconds) === null ? null : seconds; }; diff --git a/tests/telegram-errors.test.ts b/tests/telegram-errors.test.ts index 6a00fdbd..50cb2638 100644 --- a/tests/telegram-errors.test.ts +++ b/tests/telegram-errors.test.ts @@ -45,6 +45,10 @@ describe("telegram error helpers", () => { expect(getErrorDescription({ message: "From message" })).toBe("From message"); expect(getErrorDescription({ description: "From description" })).toBe("From description"); expect(getErrorDescription(42)).toBe(""); + expect(getErrorDescription({ description: null, message: "Message fallback" })).toBe( + "Message fallback", + ); + expect(getErrorDescription({ description: 429, message: "Message fallback" })).toBe(""); }); test("message predicates are case-insensitive", () => { @@ -149,6 +153,8 @@ describe("telegram error helpers", () => { expect(getRetryAfterSeconds({ parameters: { retry_after: NaN }, description })).toBe(123); expect(getRetryAfterSeconds({ retry_after: Infinity, description })).toBe(123); expect(getRetryAfterSeconds({ description })).toBe(123); + expect(getRetryAfterSeconds({ description: null, message: description })).toBe(123); + expect(getRetryAfterSeconds({ description: "Please retry after lunch" })).toBeNull(); expect(getRetryAfterSeconds(null)).toBeNull(); }); }); From 739da1ced102fd5d9457ccbb7fd286ad9662d0c5 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 16:48:23 -0300 Subject: [PATCH 116/410] test(rpc): verify the shared-host cooldown error --- src/utils/rpc-request-budget.ts | 3 +-- tests/rpc-request-budget.test.ts | 12 ++++++++++-- 2 files changed, 11 insertions(+), 4 deletions(-) diff --git a/src/utils/rpc-request-budget.ts b/src/utils/rpc-request-budget.ts index 606c9a7a..b27de2e5 100644 --- a/src/utils/rpc-request-budget.ts +++ b/src/utils/rpc-request-budget.ts @@ -33,8 +33,7 @@ export function noteRpcRateLimit( if (Number.isFinite(seconds)) { requestedRetryAt = now + Math.max(1, seconds) * 1_000; } else { - const date = Date.parse(retryAfter); - if (Number.isFinite(date)) requestedRetryAt = Math.max(now + 1_000, date); + requestedRetryAt = Math.max(now + 1_000, Date.parse(retryAfter)); } } // An unrepresentable deadline must not poison this host's cooldown indefinitely. diff --git a/tests/rpc-request-budget.test.ts b/tests/rpc-request-budget.test.ts index 3c07a129..3ac238c4 100644 --- a/tests/rpc-request-budget.test.ts +++ b/tests/rpc-request-budget.test.ts @@ -1,6 +1,11 @@ import { expect, spyOn, test, vi } from "bun:test"; import { getEventListeners } from "node:events"; -import { backgroundRpc, foregroundRpc, noteRpcRateLimit } from "../src/utils/rpc-request-budget"; +import { + backgroundRpc, + foregroundRpc, + noteRpcRateLimit, + RpcRetryLaterError, +} from "../src/utils/rpc-request-budget"; import { mockDateNowWithReadLimit } from "./helpers/timers"; const flushTasks = async () => { @@ -26,7 +31,10 @@ test("background waits for foreground and rechecks shared-host cooldown", async await foreground; vi.advanceTimersByTime(10); await flushTasks(); - expect(outcomes).toEqual([expect.objectContaining({ retryAt: 11_000 })]); + expect(outcomes).toEqual([ + expect.objectContaining({ retryAt: 11_000, message: "Recovery RPC is cooling down" }), + ]); + expect(outcomes[0]).toBeInstanceOf(RpcRetryLaterError); } finally { controller.abort(); gate.resolve(); From 3ac98ed23f9223bfff8d959c2c03539f45a02fd6 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 16:48:23 -0300 Subject: [PATCH 117/410] test(games): isolate finalized recovery proof failures --- ...ame-creation-recovery.proof-guards.test.ts | 75 ++++++++++++++++++- 1 file changed, 71 insertions(+), 4 deletions(-) diff --git a/tests/game-creation-recovery.proof-guards.test.ts b/tests/game-creation-recovery.proof-guards.test.ts index a46e1330..8f34de51 100644 --- a/tests/game-creation-recovery.proof-guards.test.ts +++ b/tests/game-creation-recovery.proof-guards.test.ts @@ -55,6 +55,7 @@ describe("restart jump to the expiry anchor", () => { for (const [label, slots] of [ ["not an array", { slots: [] }], + ["an object with a length", { 0: 13, length: 1 }], ["empty", []], ["containing a non-integer slot", [1_000.5]], ["containing a slot after the tip", [1_000, 2_000]], @@ -119,11 +120,18 @@ describe("resuming from a saved checkpoint", () => { test("can resume a checkpoint at its anchor before any blocks were checked", async () => { const rpc = mock(rpcFor(chain(10, 14), 14)); + const witness = rpcFor(chain(10, 14), 14); const atStart = { ...checkpoint, cursor: checkpoint.anchor, checkedBlocks: 0 }; expect( - await proveExpiredCreationAbsent(input, rpc, rpc, { checkpoint: atStart, save: () => {} }), + await proveExpiredCreationAbsent(input, rpc, witness, { + checkpoint: atStart, + save: () => {}, + }), ).toBe(true); expect(rpc.mock.calls.some(([method]) => method === "getSlot")).toBe(false); + expect( + rpc.mock.calls.filter(([method]) => method === "getBlock").map(([, [slot]]) => slot), + ).toEqual([14, 13, 12, 11, 10]); }); test("a resumed batch spends only its new block allowance and preserves the next retry deadline", async () => { @@ -157,16 +165,21 @@ describe("resuming from a saved checkpoint", () => { test.each<[string, Record]>([ ["the wrong genesis hash", { genesis: "wrong" }], - ["a negative count", { checkedBlocks: -1 }], + ["a negative count", { checkedBlocks: -1, cursor: { slot: 12, hash: "hash12", height: 15 } }], ["a fractional count", { checkedBlocks: 2.5 }], ["a count inconsistent with the cursor height", { checkedBlocks: 1 }], - ["a count beyond the scan window", { checkedBlocks: 256 }], + ["a count of 256", { checkedBlocks: 256, cursor: { slot: 10, hash: "hash10", height: -242 } }], ["a cursor after its anchor", { cursor: { slot: 15, hash: "hash12", height: 12 } }], ["a missing cursor", { cursor: null }], ["a missing anchor", { anchor: null }], - ["an anchor at the expiry height", { anchor: { slot: 14, hash: "hash14", height: 13 } }], + [ + "an anchor at the expiry height", + { checkedBlocks: 1, anchor: { slot: 13, hash: "hash13", height: 13 } }, + ], ["an invalid slot", { anchor: { slot: "14", hash: "hash14", height: 14 } }], ["an invalid cursor height", { cursor: { slot: 12, hash: "hash12", height: "12" } }], + ["a numeric anchor hash", { anchor: { slot: 14, hash: 14, height: 14 } }], + ["a missing cursor hash", { cursor: { slot: 12, height: 12 } }], ])("restarts rather than trusting a persisted checkpoint with %s", async (_label, patch) => { const rpc = mock(rpcFor(chain(10, 14), 14)); const saved = parseCreationProofCheckpoint(JSON.stringify({ ...checkpoint, ...patch })); @@ -185,6 +198,30 @@ describe("resuming from a saved checkpoint", () => { ); }); + test("a changed anchor height stops before consulting the witness", async () => { + const blocks = chain(10, 14); + blocks.get(14).blockHeight = 15; + const primary = rpcFor(blocks, 14); + const witness = mock(rpcFor(blocks, 14)); + expect( + await proveExpiredCreationAbsent(input, primary, witness, { checkpoint, save: () => {} }), + ).toBe(false); + expect(witness.mock.calls.map(([method]) => method)).toEqual(["getGenesisHash"]); + }); + + test("a changed cursor height stops before reading its parent", async () => { + const blocks = chain(10, 14); + blocks.get(12).blockHeight = 13; + const primary = mock(rpcFor(blocks, 14)); + const witness = rpcFor(blocks, 14); + expect( + await proveExpiredCreationAbsent(input, primary, witness, { checkpoint, save: () => {} }), + ).toBe(false); + expect( + primary.mock.calls.filter(([method]) => method === "getBlock").map(([, [slot]]) => slot), + ).toEqual([14, 12]); + }); + test("a missing cursor block is not trusted", async () => { const blocks = chain(10, 14); blocks.delete(12); @@ -194,3 +231,33 @@ describe("resuming from a saved checkpoint", () => { ); }); }); + +test("stops without reading the same block again when the finalized block is its own parent", async () => { + const blocks = chain(10, 14); + blocks.get(14).parentSlot = 14; + const primary = mock(rpcFor(blocks, 14)); + const witness = rpcFor(blocks, 14); + expect(await proveExpiredCreationAbsent(input, primary, witness)).toBe(false); + expect( + primary.mock.calls.filter(([method]) => method === "getBlock").map(([, [slot]]) => slot), + ).toEqual([14]); +}); + +test("stops without consulting the witness when the finalized block is missing", async () => { + const blocks = chain(10, 13); + const primary = mock(rpcFor(blocks, 14)); + const witness = mock(rpcFor(blocks, 14)); + expect(await proveExpiredCreationAbsent(input, primary, witness)).toBe(false); + expect(witness.mock.calls.map(([method]) => method)).toEqual(["getGenesisHash"]); +}); + +test.each([ + ["missing blockhash validity context", "isBlockhashValid", { value: false }], + ["missing signature status response", "getSignatureStatuses", null], + ["missing account context", "getAccountInfo", { value: null }], +] as const)("fails closed on %s", async (_label, method, result) => { + const blocks = chain(10, 14); + const primary = rpcFor(blocks, 14); + const witness = rpcFor(blocks, 14, { [method]: result }); + expect(await proveExpiredCreationAbsent(input, primary, witness)).toBe(false); +}); From 3d4bbe01612144c9fc185c0bd2aab3bd52b521c5 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 16:54:29 -0300 Subject: [PATCH 118/410] fix(games): reject invalid finalized slots before recovery lookups --- src/utils/game-creation-recovery.ts | 15 ++++++----- ...ame-creation-recovery.proof-guards.test.ts | 25 ++++++++++++++++++- 2 files changed, 33 insertions(+), 7 deletions(-) diff --git a/src/utils/game-creation-recovery.ts b/src/utils/game-creation-recovery.ts index 003f86e5..a495b00a 100644 --- a/src/utils/game-creation-recovery.ts +++ b/src/utils/game-creation-recovery.ts @@ -35,6 +35,10 @@ export type CreationProofProgress = { maxBlocks?: number; }; +function isFinalizedSlot(value: unknown): value is number { + return typeof value === "number" && Number.isSafeInteger(value) && value >= 0; +} + export async function proveExpiredCreationAbsent( input: ExpiredCreation, primary: RecoveryRpc, @@ -61,8 +65,8 @@ export async function proveExpiredCreationAbsent( Number.isSafeInteger(saved.checkedBlocks) && saved.checkedBlocks >= 0 && saved.checkedBlocks < 256 && - Number.isSafeInteger(saved.anchor?.slot) && - Number.isSafeInteger(saved.cursor?.slot) && + isFinalizedSlot(saved.anchor?.slot) && + isFinalizedSlot(saved.cursor?.slot) && saved.cursor.slot <= saved.anchor.slot && Number.isSafeInteger(saved.anchor?.height) && Number.isSafeInteger(saved.cursor?.height) && @@ -85,6 +89,7 @@ export async function proveExpiredCreationAbsent( return false; } else { slot = await primary("getSlot", [{ commitment: "finalized" }]); + if (!isFinalizedSlot(slot)) return false; block = await primary("getBlock", [slot, config]); if ( !block || @@ -106,9 +111,7 @@ export async function proveExpiredCreationAbsent( !slots.length || slots.some( (value: unknown, index: number) => - !Number.isSafeInteger(value) || - Number(value) > slot || - (index > 0 && Number(value) <= slots[index - 1]), + !isFinalizedSlot(value) || value > slot || (index > 0 && value <= slots[index - 1]), ) ) return false; @@ -190,7 +193,7 @@ export async function proveExpiredCreationAbsent( return false; if (block.signatures.includes(input.signature)) return false; if (block.blockhash === input.blockhash) return true; - if (!Number.isSafeInteger(block.parentSlot) || block.parentSlot >= currentSlot) return false; + if (!isFinalizedSlot(block.parentSlot) || block.parentSlot >= currentSlot) return false; const parent = await primary("getBlock", [block.parentSlot, config]); if ( !parent || diff --git a/tests/game-creation-recovery.proof-guards.test.ts b/tests/game-creation-recovery.proof-guards.test.ts index 8f34de51..bdc5e6c7 100644 --- a/tests/game-creation-recovery.proof-guards.test.ts +++ b/tests/game-creation-recovery.proof-guards.test.ts @@ -58,11 +58,12 @@ describe("restart jump to the expiry anchor", () => { ["an object with a length", { 0: 13, length: 1 }], ["empty", []], ["containing a non-integer slot", [1_000.5]], + ["containing a negative slot", [-1]], ["containing a slot after the tip", [1_000, 2_000]], ["not strictly increasing", [1_000, 1_000]], ["decreasing", [1_001, 1_000]], ] as const) - test(`a slot list that is ${label} leaves the creation unproven`, async () => { + test(`leaves the creation unproven with an invalid slot list (${label})`, async () => { const rpc = mock(rpcFor(blocks, 1_014, { getBlocks: slots })); expect(await proveExpiredCreationAbsent(input, rpc, rpc)).toBe(false); expect( @@ -177,6 +178,7 @@ describe("resuming from a saved checkpoint", () => { { checkedBlocks: 1, anchor: { slot: 13, hash: "hash13", height: 13 } }, ], ["an invalid slot", { anchor: { slot: "14", hash: "hash14", height: 14 } }], + ["a negative cursor slot", { cursor: { slot: -1, hash: "hash12", height: 12 } }], ["an invalid cursor height", { cursor: { slot: 12, hash: "hash12", height: "12" } }], ["a numeric anchor hash", { anchor: { slot: 14, hash: 14, height: 14 } }], ["a missing cursor hash", { cursor: { slot: 12, height: 12 } }], @@ -251,6 +253,27 @@ test("stops without consulting the witness when the finalized block is missing", expect(witness.mock.calls.map(([method]) => method)).toEqual(["getGenesisHash"]); }); +test.each([null, "14", -1, 14.5, Number.MAX_SAFE_INTEGER + 1])( + "rejects an unusable finalized slot before asking for a block (%p)", + async (slot) => { + const blocks = chain(10, 14); + const primary = mock(rpcFor(blocks, 14, { getSlot: slot })); + const witness = rpcFor(blocks, 14); + expect(await proveExpiredCreationAbsent(input, primary, witness)).toBe(false); + expect(primary.mock.calls.map(([method]) => method)).toEqual(["getGenesisHash", "getSlot"]); + }, +); + +test("rejects a negative parent slot without requesting a block for it", async () => { + const blocks = chain(10, 14); + blocks.get(14).parentSlot = -1; + const primary = mock(rpcFor(blocks, 14)); + expect(await proveExpiredCreationAbsent(input, primary, rpcFor(blocks, 14))).toBe(false); + expect( + primary.mock.calls.filter(([method]) => method === "getBlock").map(([, [slot]]) => slot), + ).toEqual([14]); +}); + test.each([ ["missing blockhash validity context", "isBlockhashValid", { value: false }], ["missing signature status response", "getSignatureStatuses", null], From aff1b1fa81eb4868ee059de64fb8518e9450e7f3 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 16:54:29 -0300 Subject: [PATCH 119/410] fix(transactions): preserve malformed confirmation failures --- src/utils/transaction-runner.ts | 39 ++++++++++++++--------------- tests/transaction-runner.test.ts | 42 ++++++++++++++++++++++++++++++++ 2 files changed, 60 insertions(+), 21 deletions(-) diff --git a/src/utils/transaction-runner.ts b/src/utils/transaction-runner.ts index a4c6f236..15bc22fe 100644 --- a/src/utils/transaction-runner.ts +++ b/src/utils/transaction-runner.ts @@ -3,7 +3,7 @@ import { TRANSACTION_RESUBMIT_ATTEMPTS } from "./constants"; const CONFIRMATION_RETRY_DELAYS_MS = [2000, 4000, 8000, 12000, 16000, 20000]; -const isTestEnv = () => (process.env.NODE_ENV ?? "").toLowerCase() === "test"; +const isTestEnv = () => process.env.NODE_ENV?.toLowerCase() === "test"; export const getConfirmationRetryDelays = (): number[] => { if (isTestEnv()) { @@ -120,23 +120,21 @@ export const confirmTransactionWithRecovery = async ( await wallet.confirmTransaction(currentSignature); logDebug(`✅ ${operationLabel} transaction confirmed: ${currentSignature}`); return currentSignature; - } catch (confirmError: any) { - console.warn( - `⚠️ ${operationLabel} confirmation failed: ${confirmError?.message ?? confirmError}`, - ); - - const normalizedMessage = confirmError?.message?.toLowerCase?.() ?? ""; - const isTimeout = - normalizedMessage.includes("timeout") || - normalizedMessage.includes("timed out") || - normalizedMessage.includes("not confirmed"); - const isExpiration = - normalizedMessage.includes("expired before confirmation") || - normalizedMessage.includes("last valid block height"); + } catch (confirmError) { + const detail = (confirmError as { message?: unknown } | null | undefined)?.message; + console.warn(`⚠️ ${operationLabel} confirmation failed: ${String(detail ?? confirmError)}`); + + const normalizedMessage = typeof detail === "string" ? detail.toLowerCase() : undefined; + const shouldRecover = + normalizedMessage?.includes("timeout") || + normalizedMessage?.includes("timed out") || + normalizedMessage?.includes("not confirmed") || + normalizedMessage?.includes("expired before confirmation") || + normalizedMessage?.includes("last valid block height"); let lastRecoveryError: Error | undefined; - if ((isTimeout || isExpiration) && resubmit) { + if (shouldRecover && resubmit) { for (let attempt = 0; attempt < TRANSACTION_RESUBMIT_ATTEMPTS; attempt++) { const attemptLabel = `${attempt + 1}/${TRANSACTION_RESUBMIT_ATTEMPTS}`; try { @@ -179,13 +177,12 @@ export const confirmTransactionWithRecovery = async ( } } - if (isTimeout || isExpiration) { - const retryPlan = retryDelays.length > 0 ? retryDelays : []; + if (shouldRecover) { const recoveryErrors: Error[] = lastRecoveryError ? [lastRecoveryError] : []; - for (let attempt = 0; attempt < retryPlan.length; attempt++) { - const delay = retryPlan[attempt] ?? 0; - const attemptLabel = `${attempt + 1}/${retryPlan.length}`; + for (const [attempt, retryDelay] of retryDelays.entries()) { + const delay = retryDelay ?? 0; + const attemptLabel = `${attempt + 1}/${retryDelays.length}`; logDebug(`🔄 ${operationLabel} confirmation retry ${attemptLabel} after ${delay}ms`); await sleep(delay); @@ -254,7 +251,7 @@ export const confirmTransactionWithRecovery = async ( } console.warn( - `⚠️ ${operationLabel} confirmation timed out after ${retryPlan.length} retries for ${currentSignature}`, + `⚠️ ${operationLabel} confirmation timed out after ${retryDelays.length} retries for ${currentSignature}`, ); throw timeoutError; } diff --git a/tests/transaction-runner.test.ts b/tests/transaction-runner.test.ts index e08890fc..f404c054 100644 --- a/tests/transaction-runner.test.ts +++ b/tests/transaction-runner.test.ts @@ -59,6 +59,19 @@ describe("getConfirmationRetryDelays", () => { process.env.NODE_ENV = previous; } }); + + test("uses the default production backoff when NODE_ENV is absent", () => { + const previous = process.env.NODE_ENV; + try { + delete process.env.NODE_ENV; + expect(getConfirmationRetryDelays()).toEqual([2_000, 4_000, 8_000, 12_000, 16_000, 20_000]); + process.env.NODE_ENV = "TesT"; + expect(getConfirmationRetryDelays()).toEqual([0, 0, 0, 0, 0, 0]); + } finally { + if (previous === undefined) delete process.env.NODE_ENV; + else process.env.NODE_ENV = previous; + } + }); }); describe("confirmTransactionWithRecovery", () => { @@ -201,6 +214,35 @@ describe("confirmTransactionWithRecovery", () => { ).rejects.toBe("boom"); }); + test.each([ + ["a missing failure value", null, "null"], + [ + "a structured failure without a string message", + { message: { toLowerCase: "not a method" } }, + "[object Object]", + ], + ["a symbol used as a failure sentinel", Symbol("confirm-failed"), "Symbol(confirm-failed)"], + ] as const)("preserves %s and does not retry", async (_label, failure, detail) => { + const resubmit = mock(async () => "never"); + const { wallet, statusCalls } = makeWallet({ + confirm: async () => { + throw failure; + }, + }); + await expect( + confirmTransactionWithRecovery({ + wallet, + initialSignature: "unconfirmed", + operationLabel: "Unjoin", + retryDelays: [0], + resubmit, + }), + ).rejects.toBe(failure); + expect(resubmit).not.toHaveBeenCalled(); + expect(statusCalls).toEqual([]); + expect(warnSpy).toHaveBeenCalledWith(`⚠️ Unjoin confirmation failed: ${detail}`); + }); + test("resubmits after a timeout and returns the confirmed replacement", async () => { const { wallet } = makeWallet({ confirm: async (signature) => { From ce30d9d86fd81b68eea2dd043395895be023ac92 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 16:57:08 -0300 Subject: [PATCH 120/410] refactor(state): share state expiration without mixing namespaces --- src/utils/user-state.ts | 65 +++++++++------------ tests/user-state.find-input-session.test.ts | 40 ++++++++++++- tests/user-state.util.test.ts | 18 ++++++ 3 files changed, 83 insertions(+), 40 deletions(-) diff --git a/src/utils/user-state.ts b/src/utils/user-state.ts index 175b2d1b..f6f43557 100644 --- a/src/utils/user-state.ts +++ b/src/utils/user-state.ts @@ -51,60 +51,49 @@ const clearNamespace = (namespace: string): void => { } }; -export function setUserState(userId: string, state: Record): void { +const storeTimedEntry = ( + entries: Map, + key: string, + fields: Record, +): void => { const now = Date.now(); - pruneExpiredEntries(userStates, now); - userStates.set(userId, { ...state, timestamp: now }); + pruneExpiredEntries(entries, now); + entries.set(key, { ...fields, timestamp: now }); +}; + +const readTimedEntry = ( + entries: Map, + key: string, + consume: boolean, +): (T & { timestamp: number }) | undefined => { + const entry = entries.get(key) as (T & { timestamp: number }) | undefined; + if (!entry) return undefined; + + const expired = Date.now() - entry.timestamp > USER_STATE_TIMEOUT; + if (expired || consume) entries.delete(key); + return expired ? undefined : entry; +}; + +export function setUserState(userId: string, state: Record): void { + storeTimedEntry(userStates, userId, state); } export function getUserState( userId: string, clear = false, ): (T & { timestamp: number }) | undefined { - const entry = userStates.get(userId) as (T & { timestamp: number }) | undefined; - if (!entry) { - return undefined; - } - - const now = Date.now(); - if (now - entry.timestamp > USER_STATE_TIMEOUT) { - userStates.delete(userId); - return undefined; - } - - if (clear) { - userStates.delete(userId); - } - - return entry; + return readTimedEntry(userStates, userId, clear); } export function storePendingTransaction(txId: string, transaction: Record): void { - const now = Date.now(); - pruneExpiredEntries(pendingTransactions, now); - pendingTransactions.set(txId, { ...transaction, timestamp: now }); + storeTimedEntry(pendingTransactions, txId, transaction); } export function getPendingTransaction( txId: string, remove = true, ): (T & { timestamp: number }) | undefined { - const tx = pendingTransactions.get(txId) as (T & { timestamp: number }) | undefined; - if (!tx) { - return undefined; - } - - const now = Date.now(); - if (now - tx.timestamp > USER_STATE_TIMEOUT) { - pendingTransactions.delete(txId); - return undefined; - } - - if (remove) { - pendingTransactions.delete(txId); - } - - return tx; + return readTimedEntry(pendingTransactions, txId, remove); } export type GameSetupSessionState = { diff --git a/tests/user-state.find-input-session.test.ts b/tests/user-state.find-input-session.test.ts index dc3e4a6c..b4a0c01f 100644 --- a/tests/user-state.find-input-session.test.ts +++ b/tests/user-state.find-input-session.test.ts @@ -1,5 +1,13 @@ -import { afterEach, expect, test } from "bun:test"; -import { clearAllInputSessions, findInputSession, setInputSession } from "../src/utils/user-state"; +import { afterEach, expect, spyOn, test } from "bun:test"; +import { INPUT_TIMEOUT_MS } from "../src/utils/constants"; +import { + clearAllGameSetupSessions, + clearAllInputSessions, + findInputSession, + getGameSetupSession, + setInputSession, + upsertGameSetupSession, +} from "../src/utils/user-state"; afterEach(() => { clearAllInputSessions(); @@ -37,3 +45,31 @@ test("findInputSession returns the newest matching prompt", () => { expect(found?.key).toBe("chat_new"); expect(found?.session["setting"]).toBe("video_buy_alerts"); }); + +test("selects the last matching prompt on a clock tie without inspecting other namespaces", () => { + const clock = spyOn(Date, "now").mockReturnValue(10_000); + try { + setInputSession("expired", { type: "send" }); + clock.mockReturnValue(10_010); + setInputSession("first", { type: "send", messageId: 1 }); + upsertGameSetupSession("first", {}); + setInputSession("latest", { type: "send", messageId: 2 }); + setInputSession("wrong-kind", { type: "withdraw" }); + clock.mockReturnValue(10_001 + INPUT_TIMEOUT_MS); + + const candidates: string[] = []; + const selected = findInputSession((key, session) => { + candidates.push(key); + return session.type === "send"; + }); + + expect(candidates).toEqual(["first", "latest", "wrong-kind"]); + expect(selected).toEqual({ key: "latest", session: { type: "send", messageId: 2 } }); + clearAllInputSessions(); + expect(findInputSession(() => true)).toBeUndefined(); + expect(getGameSetupSession("first")).toMatchObject({ waitingFor: "setup", gameType: "" }); + } finally { + clearAllGameSetupSessions(); + clock.mockRestore(); + } +}); diff --git a/tests/user-state.util.test.ts b/tests/user-state.util.test.ts index ac25f609..d5ccb98b 100644 --- a/tests/user-state.util.test.ts +++ b/tests/user-state.util.test.ts @@ -33,6 +33,24 @@ test("pending transactions store/get with remove option", () => { expect(tx2).toBeUndefined(); }); +test("default reads retain user state and consume pending transactions with the same key", () => { + const key = "shared-user-and-transaction"; + try { + setUserState(key, { type: "settings" }); + storePendingTransaction(key, { type: "swap" }); + expect(getUserState(key)).toMatchObject({ type: "settings" }); + expect(getPendingTransaction(key, false)).toMatchObject({ type: "swap" }); + expect(getPendingTransaction(key)).toMatchObject({ type: "swap" }); + expect(getPendingTransaction(key)).toBeUndefined(); + expect(getUserState(key)).toMatchObject({ type: "settings" }); + expect(getUserState(key, true)).toMatchObject({ type: "settings" }); + expect(getUserState(key)).toBeUndefined(); + } finally { + getPendingTransaction(key); + getUserState(key, true); + } +}); + test("setUserState prunes stale entries when adding new state", () => { const originalNow = Date.now; try { From 7aa2ec89baabc6533d77719d309dbcc9d2503898 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 17:04:08 -0300 Subject: [PATCH 121/410] test(tokens): verify SQLite diagnostics and unbound queries --- src/utils/token-database.ts | 12 ++++--- tests/token-database.schema.test.ts | 53 +++++++++++++++++++++++++++-- 2 files changed, 59 insertions(+), 6 deletions(-) diff --git a/src/utils/token-database.ts b/src/utils/token-database.ts index 2c17228c..771bd445 100644 --- a/src/utils/token-database.ts +++ b/src/utils/token-database.ts @@ -65,7 +65,7 @@ export class TokenDatabase extends BaseDatabase { try { const columns = this.all<{ name: string }>( "PRAGMA table_info(known_tokens)", - [], + undefined, "reading known_tokens schema", ); const columnNames = new Set(columns.map((col) => col.name)); @@ -73,7 +73,7 @@ export class TokenDatabase extends BaseDatabase { if (!columnNames.has("token_program_id")) { this.run( "ALTER TABLE known_tokens ADD COLUMN token_program_id TEXT", - [], + undefined, "adding token_program_id column to known_tokens", ); } @@ -101,7 +101,7 @@ export class TokenDatabase extends BaseDatabase { public getAllKnownTokens(): KnownToken[] { return this.all( "SELECT * FROM known_tokens ORDER BY token_ticker", - [], + undefined, "getting all known tokens", ); } @@ -115,6 +115,10 @@ export class TokenDatabase extends BaseDatabase { // ================================ public getTokenCount(): number { - return this.getCount("SELECT COUNT(*) as count FROM known_tokens", [], "getting token count"); + return this.getCount( + "SELECT COUNT(*) as count FROM known_tokens", + undefined, + "getting token count", + ); } } diff --git a/tests/token-database.schema.test.ts b/tests/token-database.schema.test.ts index b2bd6a0f..ad15c70e 100644 --- a/tests/token-database.schema.test.ts +++ b/tests/token-database.schema.test.ts @@ -74,10 +74,59 @@ describe("TokenDatabase known_tokens schema upgrade", () => { expect(() => TokenDatabase.getInstance()).not.toThrow(); - const messages = errorSpy.mock.calls.map((call: unknown[]) => String(call[0])); - expect(messages).toContain("Failed to ensure known_tokens schema:"); + expect(errorSpy).toHaveBeenCalledWith( + "[Token DB] Error during adding token_program_id column to known_tokens:", + expect.any(Error), + ); + expect(errorSpy).toHaveBeenCalledWith( + "Failed to ensure known_tokens schema:", + expect.any(Error), + ); } finally { errorSpy.mockRestore(); } }); }); + +test("a token added with a program keeps it through a lookup, ordered list and count", () => { + const db = TokenDatabase.getInstance(); + db.addKnownToken("z-mint", "ZED", 6); + db.addKnownToken("a-mint", "ALPHA", 9, "program-for-alpha"); + + expect(db.getKnownTokenByTicker("aLpHa")).toMatchObject({ + token_mint: "a-mint", + token_ticker: "ALPHA", + decimals: 9, + token_program_id: "program-for-alpha", + }); + expect(db.getKnownTokenByMint("z-mint")?.token_program_id).toBeNull(); + expect(db.getAllKnownTokens().map((token) => token.token_mint)).toEqual(["a-mint", "z-mint"]); + expect(db.getTokenCount()).toBe(2); +}); + +test("SQLite failures keep the error and identify the token operation that failed", () => { + const db = TokenDatabase.getInstance(); + withRawDatabase((raw) => raw.run("DROP TABLE known_tokens")); + const error = spyOn(console, "error").mockImplementation(() => {}); + try { + const operations = [ + ["adding known token", () => db.addKnownToken("test-mint", "TEST", 6)], + ["setting known token program id", () => db.setTokenProgramId("test-mint", "test-program")], + ["getting known token by ticker", () => db.getKnownTokenByTicker("TEST")], + ["getting known token by mint", () => db.getKnownTokenByMint("test-mint")], + ["getting all known tokens", () => db.getAllKnownTokens()], + ["getting token count", () => db.getTokenCount()], + ["removing known token", () => db.removeKnownToken("test-mint")], + ] as const; + + for (const [operation, action] of operations) { + expect(action).toThrow(/no such table: known_tokens/); + expect(error.mock.calls.at(-1)).toEqual([ + `[Token DB] Error during ${operation}:`, + expect.any(Error), + ]); + } + } finally { + error.mockRestore(); + } +}); From 706a0f381a2a55e66506f14887f0eb280d75d35e Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 17:04:08 -0300 Subject: [PATCH 122/410] fix(secrets): bound protected file reads --- src/utils/secrets.ts | 5 ++-- tests/secrets.test.ts | 58 +++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 61 insertions(+), 2 deletions(-) diff --git a/src/utils/secrets.ts b/src/utils/secrets.ts index 6ebef4c6..c3dfb1e2 100644 --- a/src/utils/secrets.ts +++ b/src/utils/secrets.ts @@ -33,12 +33,13 @@ export function readProtectedSecretFile(filePath: string, label: string): string // Bound the read too: another writer could grow the open file after fstat. const buffer = Buffer.alloc(MAX_SECRET_BYTES + 1); let length = 0; - while (length < buffer.length) { + // Even a series of one-byte reads needs at most the buffer length in calls. + for (let readsLeft = buffer.length; readsLeft > 0 && length < buffer.length; readsLeft--) { const bytesRead = fs.readSync(fd, buffer, length, buffer.length - length, null); if (bytesRead === 0) break; length += bytesRead; } - if (length !== stats.size || length > MAX_SECRET_BYTES) { + if (length !== stats.size) { throw new Error(`${label} has an invalid size`); } const value = buffer.toString("utf8", 0, length).trim(); diff --git a/tests/secrets.test.ts b/tests/secrets.test.ts index b4279480..000c5dc0 100644 --- a/tests/secrets.test.ts +++ b/tests/secrets.test.ts @@ -44,6 +44,11 @@ describe("protected secrets", () => { expect(loadWalletMnemonic({ MNEMONIC_FILE: " \t ", MNEMONIC: ` \n${mnemonic} ` })).toBe( mnemonic, ); + expect(loadWalletMnemonic({ MNEMONIC: mnemonic })).toBe(mnemonic); + expect(() => loadWalletMnemonic({})).toThrow("MNEMONIC_FILE is required"); + expect(() => loadWalletMnemonic({ MNEMONIC_FILE: secretFile("") })).toThrow( + "Wallet mnemonic file has an invalid size", + ); expect(() => loadWalletMnemonic({ MNEMONIC_FILE: `${file}.missing`, MNEMONIC: mnemonic }), ).toThrow(/ENOENT/); @@ -59,6 +64,9 @@ describe("protected secrets", () => { ).toBe("env-token"); expect(loadOracleApiToken({ ORACLE_API_TOKEN: " \t " })).toBeUndefined(); expect(loadOracleApiToken({})).toBeUndefined(); + expect(() => loadOracleApiToken({ ORACLE_API_TOKEN_FILE: secretFile("") })).toThrow( + "Oracle API token file has an invalid size", + ); expect(() => loadOracleApiToken({ ORACLE_API_TOKEN_FILE: `${file}.missing`, @@ -162,6 +170,26 @@ describe("protected secrets", () => { expect(() => readProtectedSecretFile(join(file, ".."), "Secret")).toThrow("regular file"); }); + test("rejects a non-regular file descriptor before attempting to read it", () => { + const file = secretFile("test-token"); + const original = fs.fstatSync; + const fstat = spyOn(fs, "fstatSync").mockImplementationOnce(((fd: number) => { + const result = original(fd); + Object.defineProperty(result, "isFile", { value: () => false }); + return result; + }) as typeof fs.fstatSync); + const read = spyOn(fs, "readSync"); + try { + expect(() => readProtectedSecretFile(file, "Secret")).toThrow( + "Secret must be a regular file", + ); + expect(read).not.toHaveBeenCalled(); + } finally { + read.mockRestore(); + fstat.mockRestore(); + } + }); + test("validates the opened file even if its path becomes a protected replacement", () => { const file = secretFile("unprotected-token"); chmodSync(file, 0o644); @@ -242,8 +270,38 @@ describe("protected secrets", () => { writeFileSync(file, "x".repeat(4097)); return stats; }) as typeof fs.fstatSync); + const read = spyOn(fs, "readSync"); try { expect(() => readProtectedSecretFile(file, "Secret")).toThrow("invalid size"); + expect(read.mock.calls.length).toBeGreaterThan(0); + const calls: ReadonlyArray> = read.mock.calls; + expect(calls.every((call) => typeof call[3] === "number" && call[3] > 0)).toBe(true); + } finally { + read.mockRestore(); + hook.mockRestore(); + } + }); + + test.each([7, 4096])("reads %i bytes one at a time and probes for EOF only once", (size) => { + const secret = "x".repeat(size); + const file = secretFile(secret); + const read = fs.readSync; + let eofReads = 0; + const hook = spyOn(fs, "readSync").mockImplementation((( + fd: number, + buffer: NodeJS.ArrayBufferView, + offset: number, + length: number, + position: number | bigint | null, + ) => { + const bytesRead = read(fd, buffer, offset, Math.min(length, 1), position); + if (bytesRead === 0 && ++eofReads > 1) throw new Error("Unexpected read after EOF"); + return bytesRead; + }) as typeof fs.readSync); + try { + expect(readProtectedSecretFile(file, "Secret")).toBe(secret); + expect(eofReads).toBe(1); + expect(hook).toHaveBeenCalledTimes(size + 1); } finally { hook.mockRestore(); } From c78035dfb615652500c5f5b487866875b295dcd2 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 17:04:08 -0300 Subject: [PATCH 123/410] refactor(telegram): normalize names without redundant checks --- src/utils/telegram-display.ts | 7 ++----- tests/telegram-display.test.ts | 22 +++++++++++++--------- 2 files changed, 15 insertions(+), 14 deletions(-) diff --git a/src/utils/telegram-display.ts b/src/utils/telegram-display.ts index 7b77517b..92e0a888 100644 --- a/src/utils/telegram-display.ts +++ b/src/utils/telegram-display.ts @@ -13,7 +13,7 @@ export const sanitizeTelegramDisplayName = ( const trimmed = typeof value === "string" ? value.trim() : ""; const normalized = trimmed.length > 0 ? trimmed : fallback; - if (!options?.preventMention || !normalized.includes("@")) { + if (!options?.preventMention) { return normalized; } @@ -39,9 +39,6 @@ export const getTelegramUserDisplayName = ( const username = user?.username?.trim().replace(/^@+/, ""); if (username) return `@${username}`; - const fullName = [user?.first_name, user?.last_name] - .map((part) => part?.trim()) - .filter(Boolean) - .join(" "); + const fullName = [user?.first_name, user?.last_name].map((part) => part?.trim()).join(" "); return sanitizeTelegramDisplayName(fullName, fallback); }; diff --git a/tests/telegram-display.test.ts b/tests/telegram-display.test.ts index e143ad44..7c7e7885 100644 --- a/tests/telegram-display.test.ts +++ b/tests/telegram-display.test.ts @@ -25,15 +25,19 @@ test("puts one invisible separator after each run of at signs, including in the }); test.each([ - [null, "User"], - [undefined, "User"], - [{}, "User"], - [{ username: " @@Ada ", first_name: "Grace" }, "@Ada"], - [{ username: "Ad@home" }, "@Ad@home"], - [{ username: "@@", first_name: " Ada ", last_name: " Lovelace \t" }, "Ada Lovelace"], - [{ first_name: " ", last_name: " Lovelace " }, "Lovelace"], - [{ first_name: " Ada ", last_name: " \t" }, "Ada"], -] as const)("uses the normalized handle or name parts for %p", (user, expected) => { + ["null user", null, "User"], + ["missing user", undefined, "User"], + ["empty user", {}, "User"], + ["handle with leading at signs", { username: " @@Ada ", first_name: "Grace" }, "@Ada"], + ["handle with an internal at sign", { username: "Ad@home" }, "@Ad@home"], + [ + "only at signs", + { username: "@@", first_name: " Ada ", last_name: " Lovelace \t" }, + "Ada Lovelace", + ], + ["last name only", { first_name: " ", last_name: " Lovelace " }, "Lovelace"], + ["first name only", { first_name: " Ada ", last_name: " \t" }, "Ada"], +] as const)("uses the normalized handle or name parts for %s", (_label, user, expected) => { expect(getTelegramUserDisplayName(user)).toBe(expected); }); From f02866fc0e39af699325e81593bf65bf714028ed Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 17:04:08 -0300 Subject: [PATCH 124/410] test(games): distinguish whole amounts from tickers with digits --- tests/game-command-input.test.ts | 3 +++ 1 file changed, 3 insertions(+) diff --git a/tests/game-command-input.test.ts b/tests/game-command-input.test.ts index b52b9fdd..11f85882 100644 --- a/tests/game-command-input.test.ts +++ b/tests/game-command-input.test.ts @@ -5,10 +5,13 @@ test.each([ [[], "menu", undefined, undefined], [["", "", "USDC"], "menu", "USDC", undefined], [["2."], "direct", undefined, "2."], + [["123"], "direct", undefined, "123"], + [["$42$"], "direct", undefined, "$42$"], [["$2.125"], "direct", undefined, "$2.125"], [[".125"], "direct", undefined, ".125"], [[".abc"], "menu", ".abc", undefined], [["1.abc"], "menu", "1.abc", undefined], + [["RUNE123"], "menu", "RUNE123", undefined], [["1.abc", "BONK"], "direct", "BONK", "1.abc"], [["2.2", "bOnK"], "direct", "bOnK", "2.2"], [["2.2", "", "BONK"], "direct", "BONK", "2.2"], From 3a8e04f067f1c946654440b45c59b40252223414 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 17:04:09 -0300 Subject: [PATCH 125/410] refactor(events): keep invalid events on the decoder fallback path --- src/utils/program-event-parser.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/utils/program-event-parser.ts b/src/utils/program-event-parser.ts index b39b9e3a..29472d24 100644 --- a/src/utils/program-event-parser.ts +++ b/src/utils/program-event-parser.ts @@ -39,7 +39,8 @@ export function decodeProgramEventLog( ): ProgramEvent | null { try { const event = decodeProgramEvent(Buffer.from(logBase64, "base64")); - if (event) return adapt(event); + const decoded = event && adapt(event); + if (decoded) return decoded; } catch { /* Keep the legacy caller's fallback behavior. */ } From d5eb5696893ef72a2f8ebe784566945b303ee640 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 17:04:09 -0300 Subject: [PATCH 126/410] refactor(tokens): resolve snapshot directories before joining the filename --- src/utils/verified-token-registry.ts | 3 ++- tests/verified-token-registry.test.ts | 16 +++++++++++----- 2 files changed, 13 insertions(+), 6 deletions(-) diff --git a/src/utils/verified-token-registry.ts b/src/utils/verified-token-registry.ts index cb16c5b6..cb49901c 100644 --- a/src/utils/verified-token-registry.ts +++ b/src/utils/verified-token-registry.ts @@ -14,8 +14,9 @@ const verifiedTokenSnapshotSchema = z.object({ const jupiterVerifiedTokensSchema = z.array(z.object({ id: SolanaAddressSchema }).passthrough()); const localMints = () => getSupportedTokens().map((token) => token.mint); +const configuredSnapshotDir = process.env["BOT_DB_DIR"]?.trim(); const snapshotPath = join( - resolve(process.env["BOT_DB_DIR"]?.trim() || process.cwd()), + configuredSnapshotDir ? resolve(configuredSnapshotDir) : process.cwd(), "verified-tokens.json", ); diff --git a/tests/verified-token-registry.test.ts b/tests/verified-token-registry.test.ts index a7fc8890..755c83b1 100644 --- a/tests/verified-token-registry.test.ts +++ b/tests/verified-token-registry.test.ts @@ -144,18 +144,24 @@ describe("verified token registry refresh", () => { } }); - test.each([undefined, " \t "])( - "uses the working directory when BOT_DB_DIR is %p", - async (path) => { + test.each([ + ["unset", undefined, ""], + ["blank", " \t ", ""], + ["relative", " ./verified-token-fixture ", "verified-token-fixture"], + ] as const)( + "resolves the snapshot path when BOT_DB_DIR is %s", + async (label, path, relativeDirectory) => { const original = process.env["BOT_DB_DIR"]; const modulePath = "../src/utils/verified-token-registry.ts"; try { if (path === undefined) delete process.env["BOT_DB_DIR"]; else process.env["BOT_DB_DIR"] = path; const registry: typeof import("../src/utils/verified-token-registry") = await import( - `${modulePath}?default-directory-${path === undefined ? "unset" : "blank"}` + `${modulePath}?snapshot-directory-${label}` + ); + expect(registry.__test_snapshotPath).toBe( + join(process.cwd(), relativeDirectory, "verified-tokens.json"), ); - expect(registry.__test_snapshotPath).toBe(join(process.cwd(), "verified-tokens.json")); } finally { if (original === undefined) delete process.env["BOT_DB_DIR"]; else process.env["BOT_DB_DIR"] = original; From 53758ae5bcf21845e3521893f720b3299196df9e Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 17:10:27 -0300 Subject: [PATCH 127/410] refactor(swaps): validate priced amounts in the fee calculation --- src/utils/integrator-fees.ts | 10 ++----- tests/integrator-fees.test.ts | 50 +++++++++++++++++++++++++++++------ 2 files changed, 44 insertions(+), 16 deletions(-) diff --git a/src/utils/integrator-fees.ts b/src/utils/integrator-fees.ts index 6a93b69d..27f1e1a4 100644 --- a/src/utils/integrator-fees.ts +++ b/src/utils/integrator-fees.ts @@ -54,18 +54,12 @@ const estimateTradeUsdValue = async ( const lookup = await getUsdPrice({ tokenMint: isSol ? WSOL_MINT : mint, }); - - if (!lookup || lookup.price <= 0) { - return 0; - } - - return amountDecimal * lookup.price; + return amountDecimal * (lookup?.price ?? 0); }; const estimateSolUsdValue = async (lamports: number): Promise => { const lookup = await getUsdPrice({ tokenMint: WSOL_MINT }); - if (!lookup || lookup.price <= 0) return 0; - return (lamports / LAMPORTS_PER_SOL) * lookup.price; + return (lamports / LAMPORTS_PER_SOL) * (lookup?.price ?? 0); }; /** diff --git a/tests/integrator-fees.test.ts b/tests/integrator-fees.test.ts index e18e9989..fa5c16b3 100644 --- a/tests/integrator-fees.test.ts +++ b/tests/integrator-fees.test.ts @@ -533,13 +533,10 @@ describe("calculateDynamicReferralFee", () => { }); test("scales fee proportionally for small shortfalls", async () => { - vi.spyOn(priceService, "getUsdPrice").mockImplementation(async (opts: any) => { - const resolvedAt = Date.now(); - if (opts?.tokenMint === WSOL_MINT) { - return { price: 200, source: "mock", identifier: WSOL_MINT, resolvedAt }; - } - return { price: 1, source: "mock", identifier: "TKN", resolvedAt }; - }); + vi.spyOn(priceService, "getUsdPrice").mockImplementation(async ({ tokenMint }) => + tokenMint === WSOL_MINT ? priceLookup(200, WSOL_MINT) : priceLookup(1, "TKN"), + ); + const log = vi.spyOn(console, "log").mockImplementation(() => {}); // Trade: 100 tokens @ $1 = $100, Shortfall: 0.001 SOL @ $200 = $0.20 const result = await calculateDynamicReferralFee({ @@ -553,6 +550,9 @@ describe("calculateDynamicReferralFee", () => { }); expect(result).toBe(105); // 85 + 20 + expect(log).toHaveBeenCalledWith( + "💰 Dynamic fee: base=85bps + extra=20bps = 105bps (trade=$100.00, deficit=$0.2000)", + ); }); test("clamps fee to MAX_REFERRAL_FEE_BPS of 255", async () => { @@ -635,6 +635,34 @@ describe("calculateDynamicReferralFee", () => { }, ); + test.each([ + ["zero token price", 0, 40], + ["negative token price", -1, 40], + ["zero SOL price", 1, 0], + ["negative SOL price", 1, -40], + ] as const)( + "uses the existing fallback or strict failure for a %s", + async (_label, tokenPrice, solPrice) => { + vi.spyOn(priceService, "getUsdPrice").mockImplementation(async ({ tokenMint }) => + priceLookup(tokenMint === WSOL_MINT ? solPrice : tokenPrice, "fixture"), + ); + const warn = vi.spyOn(console, "warn").mockImplementation(() => {}); + const input = { + inputMint: ADMIN_REF_MINT1, + inputTicker: "TKN", + inputDecimals: 6, + inputAmountRaw: 10_000_000, + shortfallLamports: 5_000_000, + baseFeeBps: 85, + }; + expect(await calculateDynamicReferralFee(input)).toBe(85); + await expect( + calculateDynamicReferralFee({ ...input, throwOnPriceFailure: true }), + ).rejects.toThrow("Cannot estimate referral surcharge for gas payer"); + expect(warn).not.toHaveBeenCalled(); + }, + ); + describe("when the input token has no price but SOL does", () => { beforeEach(() => { vi.spyOn(priceService, "getUsdPrice").mockImplementation(async (opts: any) => @@ -704,7 +732,9 @@ describe("calculateDynamicReferralFee", () => { }); test("returns base fee when price resolution throws", async () => { - vi.spyOn(priceService, "getUsdPrice").mockRejectedValue(new Error("Network error")); + const failure = new Error("Network error"); + vi.spyOn(priceService, "getUsdPrice").mockRejectedValue(failure); + const warn = vi.spyOn(console, "warn").mockImplementation(() => {}); const result = await calculateDynamicReferralFee({ inputMint: "SomeMint111111111111111111111111111111111", @@ -717,5 +747,9 @@ describe("calculateDynamicReferralFee", () => { }); expect(result).toBe(100); + expect(warn).toHaveBeenCalledWith( + "⚠️ Failed to calculate dynamic fee, using base fee:", + failure, + ); }); }); From 5449693a461532f4e9454482e1c7ff38ac146ae9 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 17:10:27 -0300 Subject: [PATCH 128/410] test(swaps): exclude only the cosmetic examples label --- src/utils/swap/prompts.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/src/utils/swap/prompts.ts b/src/utils/swap/prompts.ts index 94060c84..abec3b1d 100644 --- a/src/utils/swap/prompts.ts +++ b/src/utils/swap/prompts.ts @@ -11,6 +11,7 @@ export const buildCustomTokenPrompt = (fromToken: string): string => { "", "Reply to this message with the token mint address or symbol.", "", + // Stryker disable next-line StringLiteral: Cosmetic label only. The reply instructions and both usable examples are tested. "Examples:", "• EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v (USDC)", "• BONK", From 834cb74b135dec8471767ca1b80aaa7b6086965e Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 17:11:59 -0300 Subject: [PATCH 129/410] test(tokens): keep a stable display label when a token disappears --- tests/token-display.test.ts | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/tests/token-display.test.ts b/tests/token-display.test.ts index 393a6f27..298a27f9 100644 --- a/tests/token-display.test.ts +++ b/tests/token-display.test.ts @@ -50,3 +50,18 @@ test("adds the mint only to tickers that collide after normalization", () => { ]), ).toEqual(["ABC (1234…8901)", "ABC (mnop…tuvw)", "XYZ"]); }); + +test("uses a stable fallback when a token is removed during display name resolution", () => { + const tokens: Array<{ ticker: string; mint: string }> = [ + { ticker: "XYZ", mint: "12345678901" }, + { + get ticker() { + tokens.pop(); + return "XYZ"; + }, + mint: "temporary-token", + }, + ]; + + expect(resolveTokenDisplaySymbols(tokens)).toEqual(["XYZ (1234…8901)", "XYZ (TOKEN)"]); +}); From 4b333539d3f4241579223a99da792f9b1f89737f Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 17:11:59 -0300 Subject: [PATCH 130/410] refactor(tokens): reject invalid refresh data as one snapshot --- src/utils/verified-token-registry.ts | 6 ++---- tests/verified-token-registry.test.ts | 26 +++++++++++++++++++++++--- 2 files changed, 25 insertions(+), 7 deletions(-) diff --git a/src/utils/verified-token-registry.ts b/src/utils/verified-token-registry.ts index cb49901c..e1682dcc 100644 --- a/src/utils/verified-token-registry.ts +++ b/src/utils/verified-token-registry.ts @@ -66,11 +66,9 @@ async function refreshVerifiedMints(): Promise { }); if (!response.ok) return; - const payload = jupiterVerifiedTokensSchema.safeParse(await response.json()); - if (!payload.success) return; - + const entries = jupiterVerifiedTokensSchema.parse(await response.json()); const next = new Set(localMints()); - for (const entry of payload.data) next.add(entry.id); + for (const entry of entries) next.add(entry.id); verifiedMints = next; saveSnapshot(next); refreshAfter = Date.now() + REFRESH_INTERVAL_MS; diff --git a/tests/verified-token-registry.test.ts b/tests/verified-token-registry.test.ts index 755c83b1..0cf5c718 100644 --- a/tests/verified-token-registry.test.ts +++ b/tests/verified-token-registry.test.ts @@ -1,6 +1,6 @@ import { afterEach, beforeEach, describe, expect, spyOn, test, vi } from "bun:test"; import { existsSync, mkdirSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs"; -import { dirname, join } from "node:path"; +import { join } from "node:path"; import { __test_reloadVerifiedTokenSnapshot, __test_setVerifiedTokenMints, @@ -132,12 +132,13 @@ describe("verified token registry refresh", () => { test("stores snapshots under the configured database directory after trimming it", async () => { const original = process.env["BOT_DB_DIR"]; const modulePath = "../src/utils/verified-token-registry.ts"; + const directory = join(process.cwd(), "configured-snapshot-fixture"); try { - process.env["BOT_DB_DIR"] = ` ${dirname(__test_snapshotPath)} `; + process.env["BOT_DB_DIR"] = ` ${directory} `; const registry: typeof import("../src/utils/verified-token-registry") = await import( `${modulePath}?custom-database-directory` ); - expect(registry.__test_snapshotPath).toBe(__test_snapshotPath); + expect(registry.__test_snapshotPath).toBe(join(directory, "verified-tokens.json")); } finally { if (original === undefined) delete process.env["BOT_DB_DIR"]; else process.env["BOT_DB_DIR"] = original; @@ -183,6 +184,25 @@ describe("verified token registry refresh", () => { } }); + test("an invalid provider entry preserves the last valid snapshot and does not admit other entries", async () => { + const unlistedMint = "11111111111111111111111111111112"; + expect(localMints()).not.toContain(unlistedMint); + const now = spyOn(Date, "now").mockReturnValue(50_000); + try { + respondWith(() => Response.json([{ id: BONK }])); + expect((await refresh()).has(BONK)).toBe(true); + const saved = readFileSync(__test_snapshotPath, "utf8"); + now.mockReturnValue(50_000 + 21_600_000); + respondWith(() => Response.json([{ id: unlistedMint }, { id: "not-a-mint" }])); + const verified = await refresh(); + expect(verified).toEqual(new Set([...localMints(), BONK])); + expect(readFileSync(__test_snapshotPath, "utf8")).toBe(saved); + expect(requests).toHaveLength(2); + } finally { + now.mockRestore(); + } + }); + test("a persisted snapshot is loaded on the next start", async () => { respondWith(() => Response.json([{ id: BONK }])); await refresh(); From 06e0f52e1da749190d978fc657c262bd43185940 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 17:14:50 -0300 Subject: [PATCH 131/410] perf(games): skip unused recent history price lookups --- src/utils/game.ts | 29 ++++----------------------- tests/game.history.test.ts | 40 ++++++++++++++++++++++++++++++-------- 2 files changed, 36 insertions(+), 33 deletions(-) diff --git a/src/utils/game.ts b/src/utils/game.ts index d31f3bcd..80f42795 100644 --- a/src/utils/game.ts +++ b/src/utils/game.ts @@ -6339,7 +6339,7 @@ export class GameManager { const entries: GameHistoryEntry[] = []; const tickerCounts = new Map(); - const tickerInfo = new Map(); + const tickerDecimals = new Map(); for (const gameData of recentGamesData) { try { @@ -6374,11 +6374,8 @@ export class GameManager { // Track token frequency and info tickerCounts.set(tokenTicker, (tickerCounts.get(tokenTicker) || 0) + 1); - if (!tickerInfo.has(tokenTicker)) { - tickerInfo.set(tokenTicker, { - mint: tokenMint, - decimals: tokenDecimals, - }); + if (!tickerDecimals.has(tokenTicker)) { + tickerDecimals.set(tokenTicker, tokenDecimals); } // Get participant count @@ -6456,25 +6453,7 @@ export class GameManager { if (count > maxCount) { maxCount = count; primaryTicker = ticker; - primaryDecimals = tickerInfo.get(ticker)?.decimals ?? 6; - } - } - - // Get USD prices for all unique tokens - const tokenPrices = new Map(); - for (const [ticker, info] of tickerInfo) { - if (info.mint) { - try { - const priceMint = info.mint === "SOL" ? WSOL_MINT : info.mint; - const priceResult = await getUsdPrice({ - tokenMint: priceMint, - }); - if (priceResult?.price != null && priceResult.price > 0) { - tokenPrices.set(ticker, priceResult.price); - } - } catch { - // ignore - } + primaryDecimals = tickerDecimals.get(ticker) ?? 6; } } diff --git a/tests/game.history.test.ts b/tests/game.history.test.ts index 93982c09..89273908 100644 --- a/tests/game.history.test.ts +++ b/tests/game.history.test.ts @@ -196,13 +196,15 @@ describe("getUserGamesHistory fallbacks", () => { expect(errorSpy.mock.calls[0]![0]).toBe("Error processing game Bad:"); }); - test("looks up per-ticker prices and ignores lookup failures and non-positive prices", async () => { + const distinctGames = () => [ + baseGame({ game_address: "A", token_ticker: "AAA", token_mint: "SOL" }), + baseGame({ game_address: "B", token_ticker: "BBB", token_mint: "B_MINT" }), + baseGame({ game_address: "C", token_ticker: "CCC", token_mint: "C_MINT" }), + ]; + + test("keeps the game rows and primary ticker when no history totals are available", async () => { const { gm } = await build({ - games: [ - baseGame({ game_address: "A", token_ticker: "AAA", token_mint: "SOL" }), - baseGame({ game_address: "B", token_ticker: "BBB", token_mint: "B_MINT" }), - baseGame({ game_address: "C", token_ticker: "CCC", token_mint: "C_MINT" }), - ], + games: distinctGames(), }); priceSpy.mockImplementation((async ({ tokenMint }: { tokenMint: string }) => { if (tokenMint === "B_MINT") throw new Error("price api down"); @@ -212,9 +214,31 @@ describe("getUserGamesHistory fallbacks", () => { const result = await gm.getUserGamesHistory(CTX, 12345n); + expect(result).toMatchObject({ + primaryTicker: "AAA", + primaryDecimals: 6, + lost: { totalAmount: 15_000_000, totalUsd: 0 }, + won: { totalAmount: 0, totalUsd: 0 }, + }); + expect( + result.lost.games.map(({ gameAddress, tokenTicker, amount }) => [ + gameAddress, + tokenTicker, + amount, + ]), + ).toEqual([ + ["A", "AAA", 5_000_000], + ["B", "BBB", 5_000_000], + ["C", "CCC", 5_000_000], + ]); + }); + + test("does not request unused prices for recent history entries", async () => { + const { gm } = await build({ games: distinctGames() }); + const result = await gm.getUserGamesHistory(CTX, 12345n); + expect(result.lost.games).toHaveLength(3); - const asked = priceSpy.mock.calls.map((call: any[]) => call[0].tokenMint); - expect(asked).toEqual([WSOL_MINT, "B_MINT", "C_MINT"]); + expect(priceSpy).not.toHaveBeenCalled(); }); test("converts aggregated won and lost amounts to USD", async () => { From fec27090451483a63105726461fecf692af7611c Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 17:16:38 -0300 Subject: [PATCH 132/410] test(games): pin history amount and metadata boundaries --- tests/game.history.test.ts | 62 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 62 insertions(+) diff --git a/tests/game.history.test.ts b/tests/game.history.test.ts index 89273908..d464958c 100644 --- a/tests/game.history.test.ts +++ b/tests/game.history.test.ts @@ -115,6 +115,68 @@ describe("getUserGamesHistory fallbacks", () => { expect(result.lost.games[0]!.maxTickets).toBe(0); }); + test.each([ + ["negative", -3], + ["non-finite", Infinity], + ["invalid", "unavailable"], + ["zero", 0], + ] as const)("keeps the game row when the recorded amount is %s", async (_label, amount) => { + const clock = spyOn(Date, "now").mockReturnValue(1_750_000_000_000); + let metadataCalls = 0; + try { + const { gm } = await build({ + games: [ + baseGame({ amount, completed_at: 0, token_ticker: "", token_mint: "", max_players: 0 }), + ], + wallet: { + getTokenMetadata: async () => { + metadataCalls += 1; + return { decimals: 9 }; + }, + }, + db: { getGameParticipants: () => undefined }, + }); + const result = await gm.getUserGamesHistory(CTX, 12345n); + expect(result.lost.games).toHaveLength(1); + expect(result.lost.games[0]).toMatchObject({ + amount: 0, + completedAt: 1_750_000_000_000, + tokenTicker: "TOKENS", + tokenMint: "", + tokenDecimals: 6, + ticketCount: 0, + maxTickets: 0, + }); + expect(metadataCalls).toBe(0); + } finally { + clock.mockRestore(); + } + }); + + test("keeps zero-decimal amounts and uses the ticket count for an unknown capacity", async () => { + const lookup: string[] = []; + const { gm } = await build({ + games: [baseGame({ amount: 12, max_players: 0, token_mint: "ZERO_MINT" })], + wallet: { + getTokenMetadata: async (mint: string) => { + lookup.push(mint); + return { decimals: 0 }; + }, + }, + db: { getGameParticipantsCount: () => 4 }, + }); + + const result = await gm.getUserGamesHistory(CTX, 12345n); + expect(result.primaryDecimals).toBe(0); + expect(result.lost.games[0]).toMatchObject({ + amount: 12, + tokenDecimals: 0, + ticketCount: 4, + maxTickets: 4, + }); + expect(lookup).toEqual(["ZERO_MINT"]); + }); + test("uses a short player id when the creator has no username", async () => { const { gm } = await build({ games: [baseGame({ creator_telegram_id: "1234567890" })] }); (gm as any).getUsernameFromTelegramId = async () => null; From 4e02bf6b51e17e6973f209750d88443820ff5011 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 17:19:23 -0300 Subject: [PATCH 133/410] fix(games): value won and lost history with one quote per mint --- src/utils/game.ts | 84 ++++++++++++++++---------------------- tests/game.history.test.ts | 28 +++++++++++++ 2 files changed, 63 insertions(+), 49 deletions(-) diff --git a/src/utils/game.ts b/src/utils/game.ts index 80f42795..8882bfe9 100644 --- a/src/utils/game.ts +++ b/src/utils/game.ts @@ -6470,60 +6470,46 @@ export class GameManager { // This ensures /games and /lb show matching numbers const playerStats = this.gameDb.getPlayerGlobalStats(telegramIdStr); - let wonUsd = 0; - let lostUsd = 0; - - // Convert won amounts to USD - if (playerStats?.wonAmountByToken) { - for (const [tokenMint, wonAmount] of Object.entries(playerStats.wonAmountByToken)) { - if (wonAmount <= 0) continue; - try { - let decimals = 9; - try { - const meta = await this.wallet.getTokenMetadata(tokenMint); - if (meta?.decimals != null) decimals = meta.decimals; - } catch { - /* ignore */ - } - - const priceResult = await getUsdPrice({ - tokenMint: tokenMint === "SOL" ? WSOL_MINT : tokenMint, - }); - if (priceResult?.price && priceResult.price > 0) { - const divisor = Math.pow(10, decimals); - wonUsd += (wonAmount / divisor) * priceResult.price; - } - } catch { - /* ignore */ - } + // Use one valuation per mint so a quote change cannot create a profit or loss. + const quotes = new Map(); + const readQuote = async (tokenMint: string) => { + let decimals = 9; + try { + const meta = await this.wallet.getTokenMetadata(tokenMint); + decimals = meta?.decimals ?? decimals; + } catch { + // Keep the default units if metadata is unavailable. } - } - // Convert lost amounts to USD - if (playerStats?.lostAmountByToken) { - for (const [tokenMint, lostAmount] of Object.entries(playerStats.lostAmountByToken)) { - if (lostAmount <= 0) continue; - try { - let decimals = 9; - try { - const meta = await this.wallet.getTokenMetadata(tokenMint); - if (meta?.decimals != null) decimals = meta.decimals; - } catch { - /* ignore */ - } + try { + const lookup = await getUsdPrice({ + tokenMint: tokenMint === "SOL" ? WSOL_MINT : tokenMint, + }); + const price = lookup?.price; + return typeof price === "number" && Number.isFinite(price) && price > 0 + ? { price, divisor: Math.pow(10, decimals) } + : null; + } catch { + return null; + } + }; - const priceResult = await getUsdPrice({ - tokenMint: tokenMint === "SOL" ? WSOL_MINT : tokenMint, - }); - if (priceResult?.price && priceResult.price > 0) { - const divisor = Math.pow(10, decimals); - lostUsd += (lostAmount / divisor) * priceResult.price; - } - } catch { - /* ignore */ + const totalUsd = async (amounts: Readonly> | undefined) => { + let total = 0; + for (const [tokenMint, amount] of Object.entries(amounts ?? {})) { + if (amount <= 0) continue; + let quote = quotes.get(tokenMint); + if (quote === undefined) { + quote = await readQuote(tokenMint); + quotes.set(tokenMint, quote); } + if (quote) total += (amount / quote.divisor) * quote.price; } - } + return total; + }; + + const wonUsd = await totalUsd(playerStats?.wonAmountByToken); + const lostUsd = await totalUsd(playerStats?.lostAmountByToken); return { won: { diff --git a/tests/game.history.test.ts b/tests/game.history.test.ts index d464958c..c229e671 100644 --- a/tests/game.history.test.ts +++ b/tests/game.history.test.ts @@ -348,6 +348,34 @@ describe("getUserGamesHistory fallbacks", () => { expect(askedMints).toContain(WSOL_MINT); expect(askedMints).not.toContain("SOL"); }); + + test("values equal wins and losses for the same mint with one shared quote", async () => { + const mint = "COIN_MINT"; + const { gm } = await build({ + games: [], + stats: { + wonAmountByToken: { [mint]: 500_000 }, + lostAmountByToken: { [mint]: 500_000 }, + }, + }); + priceSpy.mockResolvedValueOnce({ price: 2, identifier: mint, resolvedAt: 0 }); + priceSpy.mockResolvedValueOnce({ price: 3, identifier: mint, resolvedAt: 1 }); + + const result = await gm.getUserGamesHistory(CTX, 12345n); + expect(result.won.totalUsd).toBe(1); + expect(result.lost.totalUsd).toBe(1); + expect(priceSpy.mock.calls).toEqual([[{ tokenMint: mint }]]); + }); + + test("does not put an unrepresentable quote in the history dollar totals", async () => { + const mint = "COIN_MINT"; + const { gm } = await build({ games: [], stats: { wonAmountByToken: { [mint]: 500_000 } } }); + priceSpy.mockResolvedValue({ price: Infinity, identifier: mint, resolvedAt: 0 }); + + const result = await gm.getUserGamesHistory(CTX, 12345n); + expect(result.won.totalUsd).toBe(0); + expect(result.lost.totalUsd).toBe(0); + }); }); describe("formatGamesHeader and formatGamesMessage", () => { From 15302ce4a2659f7f609293b39fb7eb5cdf1dc029 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 17:23:33 -0300 Subject: [PATCH 134/410] fix(chats): ignore defaults commands without a chat --- src/handlers/chat-defaults.ts | 7 +- tests/chat-defaults.handler.test.ts | 106 ++++++++++++++++++++++++++++ 2 files changed, 110 insertions(+), 3 deletions(-) diff --git a/src/handlers/chat-defaults.ts b/src/handlers/chat-defaults.ts index da1f15e6..7bad1710 100644 --- a/src/handlers/chat-defaults.ts +++ b/src/handlers/chat-defaults.ts @@ -230,7 +230,6 @@ const ensureAdmin = async (ctx: Context, deps: ChatDefaultsModuleDeps) => { }; const checkCallbackAdmin = async (ctx: Context, deps: ChatDefaultsModuleDeps): Promise => { - if (!ctx.chat) return false; const isAdmin = await ensureAdmin(ctx, deps); if (!isAdmin) { await safeAnswerCallbackQuery(ctx, "Only admins can change chat defaults"); @@ -690,7 +689,9 @@ export const createChatDefaultsModule = (deps: ChatDefaultsModuleDeps): ChatDefa }; const handleDefaultCommand = async (ctx: Context, args: string[] = []): Promise => { - if (ctx.chat?.type === "private") { + const chat = ctx.chat; + if (!chat) return; + if (chat.type === "private") { await deps.replyToMessage(ctx, "🚫 Default tokens can only be set in groups or channels."); return; } @@ -710,7 +711,7 @@ export const createChatDefaultsModule = (deps: ChatDefaultsModuleDeps): ChatDefa } if (tokenInput.toUpperCase() === "CLEAR" || tokenInput.toUpperCase() === "REMOVE") { - deps.getTokenManager().removeChatDefaultToken(ctx.chat!.id); + deps.getTokenManager().removeChatDefaultToken(chat.id); notifyBuyAlertsChanged(deps); await deps.replyToMessage( ctx, diff --git a/tests/chat-defaults.handler.test.ts b/tests/chat-defaults.handler.test.ts index b32fa377..09a72478 100644 --- a/tests/chat-defaults.handler.test.ts +++ b/tests/chat-defaults.handler.test.ts @@ -1554,6 +1554,112 @@ describe("chat defaults menus and inputs", () => { expect(chatDb.getChatGameSettings(99)).toBeNull(); }); + test("a command without a chat does not attempt to clear a default token", async () => { + const h = setup(); + h.tokenManager.setChatDefaultToken(99, "mint", "AAA", "1"); + const ctx = h.ctxFor(); + delete ctx.chat; + + await h.module.handleDefaultCommand(ctx, ["/default", "CLEAR"]); + + expect(h.tokenManager.getChatDefaultToken(99)?.token_ticker).toBe("AAA"); + expect(h.refreshes()).toBe(0); + expect(h.replies).toEqual([]); + }); + + test("without a usable actor the group command leaves settings intact", async () => { + const h = setup(); + h.tokenManager.setChatDefaultToken(99, "mint", "AAA", "1"); + const ctx = h.ctxFor(); + delete ctx.from; + + await h.module.handleDefaultCommand(ctx, ["/default", "CLEAR"]); + + expect(h.tokenManager.getChatDefaultToken(99)?.token_ticker).toBe("AAA"); + expect(h.refreshes()).toBe(0); + expect(h.replies).toEqual([]); + }); + + test("does not consume a reply to a different kind of prompt", async () => { + const h = setup(); + expect( + await h.module.handleSettingsInput(h.ctxFor(), { type: "withdraw", chatId: 99 }, "5"), + ).toBe(false); + expect(h.replies).toEqual([]); + expect(h.menus).toEqual([]); + expect(chatDb.getChatGameSettings(99)).toBeNull(); + }); + + test("all guarded callbacks reject a missing chat before editing settings", async () => { + const h = setup(); + const actions = [ + "chat_defaults_game_coinflip", + "chat_defaults_clear_token", + "chat_defaults_token", + "chat_defaults_set_public_game_feed_on", + "chat_defaults_set_buy_alerts_on", + "chat_defaults_set_buy_alerts_min_05", + "chat_defaults_set_buy_alerts_min_custom", + "chat_defaults_buy_alerts_media", + "chat_defaults_set_video_coinflip", + "chat_defaults_set_privacy_giveaway_public", + "chat_defaults_set_join_external_on", + "chat_defaults_set_join_rate_5", + "chat_defaults_set_join_rate_custom", + "chat_defaults_clear_join_notifications", + "chat_defaults_cancel", + ]; + for (const action of actions) { + const ctx = h.ctxFor(action); + delete ctx.chat; + await h.mockBot.dispatch(action, ctx); + } + expect(h.menus).toEqual([]); + expect(h.replies).toEqual([]); + expect(h.answers).toEqual([]); + expect(chatDb.getChatGameSettings(99)).toBeNull(); + expect(chatDb.getChatBuyAlerts(99)).toBeNull(); + }); + + test("routes the token and network buttons to their enabled settings", () => { + const original = process.env["EVM_BOT_CONFIG_FILE"]; + const callbacks = (isEvm: boolean) => + __test_buildMenuKeyboard(isEvm) + .inline_keyboard.flat() + .flatMap((button) => ("callback_data" in button ? [button.callback_data] : [])); + try { + delete process.env["EVM_BOT_CONFIG_FILE"]; + expect(callbacks(false)).toContain("chat_defaults_token"); + expect(callbacks(false)).not.toContain("game_network"); + process.env["EVM_BOT_CONFIG_FILE"] = "test-only-evm-settings"; + expect(callbacks(false)).toContain("game_network"); + expect(callbacks(true)).toContain("game_network_token"); + expect(callbacks(true)).not.toContain("chat_defaults_token"); + } finally { + if (original === undefined) delete process.env["EVM_BOT_CONFIG_FILE"]; + else process.env["EVM_BOT_CONFIG_FILE"] = original; + } + }); + + test("the join notification menu shows the current cap and the opposite action", async () => { + const h = setup(); + chatDb.upsertChatGameSettings(99, { + join_notifications_per_minute: 5, + join_notifications_external: true, + }); + + await h.press("chat_defaults_join_notifications"); + expect(h.lastMenu().text).toContain("Limit: up to 5/min"); + expect(h.lastMenu().text).toContain("Games from other groups: On"); + expect(h.lastCallbacks()).toContain("chat_defaults_set_join_external_off"); + expect(h.lastCallbacks()).not.toContain("chat_defaults_set_join_external_on"); + await h.press("chat_defaults_set_join_external_off"); + expect(chatDb.getChatGameSettings(99)).toMatchObject({ + join_notifications_per_minute: 5, + join_notifications_external: 0, + }); + }); + test("the public game feed can be toggled", async () => { const h = setup(); From 7a37063c1b07e2424f7fbfb5a3d7ed6ba2239479 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 17:26:07 -0300 Subject: [PATCH 135/410] refactor(state): keep prompt merges and namespace boundaries explicit --- src/utils/user-state.ts | 19 ++++------- tests/user-state.namespaces.test.ts | 53 ++++++++++++++++++++++++++++- 2 files changed, 58 insertions(+), 14 deletions(-) diff --git a/src/utils/user-state.ts b/src/utils/user-state.ts index f6f43557..ace3c37c 100644 --- a/src/utils/user-state.ts +++ b/src/utils/user-state.ts @@ -19,19 +19,15 @@ const pendingTransactions = new Map(); const buildNamespacedKey = (namespace: string, key: string): string => `${namespace}:${key}`; -const stripTimestamp = (state?: GenericState): T | undefined => { - if (!state) { - return undefined; - } - +const stripTimestamp = (state: GenericState): T => { const rest = { ...state }; Reflect.deleteProperty(rest, "timestamp"); return rest as T; }; const getNamespacedState = (namespace: string, key: string, clear = false): T | undefined => { - const raw = getUserState(buildNamespacedKey(namespace, key), clear); - return stripTimestamp(raw as unknown as GenericState | undefined); + const raw = getUserState(buildNamespacedKey(namespace, key), clear); + return raw === undefined ? undefined : stripTimestamp(raw); }; const setNamespacedState = (namespace: string, key: string, state: T): void => { @@ -135,7 +131,7 @@ export const upsertGameSetupSession = ( const next: GameSetupSessionState = { ...DEFAULT_GAME_SETUP_SESSION, - ...(existing ?? {}), + ...existing, ...updates, }; @@ -195,7 +191,7 @@ export const findInputSession = ( } const session = stripTimestamp(value); const key = namespacedKey.slice(prefix.length); - if (session && predicate(key, session) && (!latest || value.timestamp >= latest.timestamp)) { + if (predicate(key, session) && (!latest || value.timestamp >= latest.timestamp)) { latest = { key, session, timestamp: value.timestamp }; } } @@ -250,10 +246,7 @@ const listNamespaceEntries = (namespace: string): Array<[string, T]> => { continue; } - const stripped = stripTimestamp(value); - if (stripped) { - results.push([key.slice(prefix.length), stripped]); - } + results.push([key.slice(prefix.length), stripTimestamp(value)]); } return results; diff --git a/tests/user-state.namespaces.test.ts b/tests/user-state.namespaces.test.ts index b7f804f1..45148c16 100644 --- a/tests/user-state.namespaces.test.ts +++ b/tests/user-state.namespaces.test.ts @@ -1,10 +1,15 @@ -import { afterEach, beforeEach, expect, test } from "bun:test"; +import { afterEach, beforeEach, expect, spyOn, test } from "bun:test"; import { + __test_clearUserState, __test_listGameSetupSessions, __test_listInputSessions, clearAllGameSetupSessions, clearAllInputSessions, + getGameSetupSession, + getInputSession, + getUserState, setInputSession, + setUserState, upsertGameSetupSession, } from "../src/utils/user-state"; @@ -13,6 +18,52 @@ beforeEach(() => { clearAllInputSessions(); }); +test("partial setup changes retain previous fields without exposing stored metadata", () => { + upsertGameSetupSession("partial-game", { gameType: "coinflip", userBalance: 32 }); + upsertGameSetupSession("partial-game", { userBalance: 0 }); + + expect(getGameSetupSession("partial-game")).toEqual({ + waitingFor: "setup", + gameType: "coinflip", + userBalance: 0, + }); + expect(getGameSetupSession("unknown-game")).toBeUndefined(); +}); + +test("separate prompt namespaces do not overwrite a generic colon-prefixed key", () => { + const key = "shared-key"; + const plain = `:${key}`; + try { + setUserState(plain, { type: "unrelated" }); + upsertGameSetupSession(key, { gameType: "giveaway" }); + setInputSession(key, { type: "amount" }); + + expect(getUserState(plain)).toMatchObject({ type: "unrelated" }); + expect(getGameSetupSession(key)?.gameType).toBe("giveaway"); + expect(getInputSession(key)).toEqual({ type: "amount" }); + __test_clearUserState(plain); + expect(getUserState(plain)).toBeUndefined(); + } finally { + __test_clearUserState(plain); + } +}); + +test("session listings keep the exact expiry boundary but never return expired prompts", () => { + const clock = spyOn(Date, "now").mockReturnValue(2_000_000); + try { + upsertGameSetupSession("game-prompt", { gameType: "giveaway" }); + setInputSession("value-prompt", { type: "amount" }); + clock.mockReturnValue(2_900_000); + expect(__test_listGameSetupSessions().map(([key]) => key)).toEqual(["game-prompt"]); + expect(__test_listInputSessions()).toEqual([["value-prompt", { type: "amount" }]]); + clock.mockReturnValue(2_900_001); + expect(__test_listGameSetupSessions()).toEqual([]); + expect(__test_listInputSessions()).toEqual([]); + } finally { + clock.mockRestore(); + } +}); + afterEach(() => { clearAllGameSetupSessions(); clearAllInputSessions(); From 03d2bf184887d153fe8f4a16c30a6d64a23ecd79 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 17:31:52 -0300 Subject: [PATCH 136/410] test(tokens): verify canonical program lookup diagnostics --- tests/token-programs.test.ts | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/tests/token-programs.test.ts b/tests/token-programs.test.ts index 202bbae5..f57c7fa3 100644 --- a/tests/token-programs.test.ts +++ b/tests/token-programs.test.ts @@ -177,4 +177,38 @@ describe("detectTokenProgram", () => { lookup.mockRestore(); } }); + + test("keeps the caller's key at the RPC boundary and reports canonical mint and owner addresses", async () => { + class DisplayKey extends PublicKey { + override toString(): string { + return "display-only"; + } + } + + const mint = new DisplayKey("EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"); + const owner = new DisplayKey("11111111111111111111111111111111"); + const connection = new Connection("http://localhost:8899"); + const lookup = spyOn(connection, "getAccountInfo").mockResolvedValue({ + owner, + data: Buffer.alloc(0), + executable: false, + lamports: 0n, + rentEpoch: 0n, + space: 0n, + }); + const log = spyOn(console, "log").mockImplementation(() => {}); + try { + await expect(detectTokenProgram(connection, mint)).rejects.toThrow( + `Token mint ${mint.toBase58()} is owned by an unknown program (${owner.toBase58()})`, + ); + expect(lookup.mock.calls[0]?.[0]).toBe(mint); + expect(log).toHaveBeenCalledWith( + `Error checking token program for ${mint.toBase58()}:`, + expect.any(Error), + ); + } finally { + lookup.mockRestore(); + log.mockRestore(); + } + }); }); From accbd2f6a0d77651e7830a6d88e57b6322581f01 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 17:31:52 -0300 Subject: [PATCH 137/410] test(evm): verify database permissions and persisted routes --- tests/evm.store-boundaries.test.ts | 110 +++++++++++++++++++++++++++++ 1 file changed, 110 insertions(+) create mode 100644 tests/evm.store-boundaries.test.ts diff --git a/tests/evm.store-boundaries.test.ts b/tests/evm.store-boundaries.test.ts new file mode 100644 index 00000000..eb346e1e --- /dev/null +++ b/tests/evm.store-boundaries.test.ts @@ -0,0 +1,110 @@ +import { Database } from "bun:sqlite"; +import { afterEach, beforeEach, expect, spyOn, test } from "bun:test"; +import { mkdtempSync, rmSync, statSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { EvmBotStore, type EvmAction } from "../src/evm/store"; + +let folder: string; +beforeEach(() => { + folder = mkdtempSync(join(tmpdir(), "evm-store-boundaries-")); +}); +afterEach(() => { + rmSync(folder, { recursive: true, force: true }); +}); + +const game = "0x1234"; +const action = (id: string, kind: EvmAction["kind"], message: number): EvmAction => ({ + id, + user: "123", + chat: -99, + message, + kind, + body: JSON.stringify({ game }), + phase: "proposal", + raw: null, + hash: null, +}); + +test("only a successful create is available for a new game message", () => { + const store = new EvmBotStore(":memory:", "test-deployment"); + try { + const failedCreate = action("failed", "create", 4); + const successfulJoin = action("joined", "join", 5); + const successfulCreate = action("created", "create", 6); + for (const candidate of [failedCreate, successfulJoin, successfulCreate]) store.add(candidate); + + store.finish({ ...failedCreate, phase: "failed" }); + store.finish({ ...successfulJoin, phase: "done" }); + expect(store.messages()).toEqual([]); + store.finish({ ...successfulCreate, phase: "done" }); + + const messages = store.messages(); + expect(messages).toHaveLength(1); + expect(messages[0]).toMatchObject({ game, chat: -99, message: 6, body: "", creator: "123" }); + expect(store.action("failed")?.phase).toBe("failed"); + } finally { + store.close(); + } +}); + +test("an existing EVM action keeps its route after a different network is selected", () => { + const store = new EvmBotStore(":memory:", "test-deployment"); + try { + store.add(action("old-evm", "create", 5)); + expect(store.commandNetwork("old-evm", "-99", "solana")).toBe("evm"); + expect(store.commandNetwork("new-solana", "-99", "solana")).toBe("solana"); + store.setNetwork("-99", "evm"); + expect(store.commandNetwork("new-solana", "-99")).toBe("solana"); + } finally { + store.close(); + } +}); + +test("protects the database file and refuses missing query bindings", () => { + const path = join(folder, "db.sqlite"); + writeFileSync(path, "", { mode: 0o644 }); + const store = new EvmBotStore(path, "test-deployment"); + try { + expect(statSync(path).mode & 0o777).toBe(0o600); + expect(() => store.db.query("SELECT $deployment AS value").get({})).toThrow(); + } finally { + store.close(); + } +}); + +test("a database without a recorded identity is refused and closed", () => { + const path = join(folder, "db.sqlite"); + const db = new Database(path); + try { + db.exec("CREATE TABLE identity (id INTEGER PRIMARY KEY CHECK (id = 1), value TEXT NOT NULL);"); + db.exec( + "CREATE TRIGGER refuse_identity BEFORE INSERT ON identity BEGIN SELECT RAISE(IGNORE); END;", + ); + } finally { + db.close(); + } + const close = spyOn(Database.prototype, "close"); + try { + expect(() => new EvmBotStore(path, "test-deployment")).toThrow( + "EVM bot database deployment mismatch", + ); + expect(close).toHaveBeenCalledTimes(1); + } finally { + close.mockRestore(); + } +}); + +test("closing the EVM store releases its database handle", () => { + const store = new EvmBotStore(":memory:", "test-deployment"); + const close = spyOn(store.db, "close"); + try { + store.close(); + expect(close).toHaveBeenCalledTimes(1); + expect(() => store.pending()).toThrow(); + } finally { + const called = close.mock.calls.length > 0; + close.mockRestore(); + if (!called) store.db.close(); + } +}); From ed27860f5e8a1ea68df1611c66050e213a6c817a Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 17:34:10 -0300 Subject: [PATCH 138/410] fix(evm): close the database after startup errors --- src/evm/store.ts | 18 +++++++++++------- tests/evm.store-boundaries.test.ts | 19 +++++++++++++++++++ 2 files changed, 30 insertions(+), 7 deletions(-) diff --git a/src/evm/store.ts b/src/evm/store.ts index 78990efe..6bbf7a4a 100644 --- a/src/evm/store.ts +++ b/src/evm/store.ts @@ -24,8 +24,9 @@ export class EvmBotStore { readonly db: Database; constructor(path: string, identity: string) { this.db = new Database(path, { create: true, strict: true }); - if (path !== ":memory:") chmodSync(path, 0o600); - this.db.exec(`PRAGMA journal_mode=WAL; PRAGMA synchronous=FULL; + try { + if (path !== ":memory:") chmodSync(path, 0o600); + this.db.exec(`PRAGMA journal_mode=WAL; PRAGMA synchronous=FULL; CREATE TABLE IF NOT EXISTS command_networks (id TEXT PRIMARY KEY, chain TEXT NOT NULL CHECK(chain IN ('solana','evm'))); CREATE TABLE IF NOT EXISTS network_tokens (chat TEXT PRIMARY KEY, token TEXT NOT NULL); CREATE TABLE IF NOT EXISTS network_preferences (chat TEXT PRIMARY KEY, chain TEXT NOT NULL CHECK(chain IN ('solana','evm'))); @@ -33,12 +34,15 @@ export class EvmBotStore { CREATE TABLE IF NOT EXISTS actions (id TEXT PRIMARY KEY,user TEXT NOT NULL,chat INTEGER NOT NULL,message INTEGER NOT NULL,kind TEXT NOT NULL,body TEXT NOT NULL,phase TEXT NOT NULL,raw TEXT,hash TEXT,notified INTEGER NOT NULL DEFAULT 0); CREATE TABLE IF NOT EXISTS invitations (game TEXT NOT NULL,user TEXT NOT NULL,body TEXT NOT NULL,PRIMARY KEY(game,user)); CREATE TABLE IF NOT EXISTS game_messages (game TEXT NOT NULL,chat INTEGER NOT NULL,message INTEGER NOT NULL,body TEXT NOT NULL,creator TEXT NOT NULL,next_check INTEGER NOT NULL DEFAULT 0,PRIMARY KEY(game,chat,message));`); - this.db.query("INSERT OR IGNORE INTO identity VALUES (1,?)").run(identity); - if ( - this.db.query<{ value: string }, []>("SELECT value FROM identity").get()?.value !== identity - ) { + this.db.query("INSERT OR IGNORE INTO identity VALUES (1,?)").run(identity); + if ( + this.db.query<{ value: string }, []>("SELECT value FROM identity").get()?.value !== identity + ) { + throw new Error("EVM bot database deployment mismatch"); + } + } catch (error) { this.db.close(); - throw new Error("EVM bot database deployment mismatch"); + throw error; } } commandNetwork(id: string, chat: string, selected?: "solana" | "evm"): "solana" | "evm" { diff --git a/tests/evm.store-boundaries.test.ts b/tests/evm.store-boundaries.test.ts index eb346e1e..318eb4ca 100644 --- a/tests/evm.store-boundaries.test.ts +++ b/tests/evm.store-boundaries.test.ts @@ -95,6 +95,25 @@ test("a database without a recorded identity is refused and closed", () => { } }); +test("a failed schema initialization closes the database and retains the SQLite error", () => { + const path = join(folder, "db.sqlite"); + const db = new Database(path); + try { + db.exec("CREATE TABLE identity (value TEXT NOT NULL);"); + } finally { + db.close(); + } + const close = spyOn(Database.prototype, "close"); + try { + expect(() => new EvmBotStore(path, "test-deployment")).toThrow( + "table identity has 1 columns but 2 values were supplied", + ); + expect(close).toHaveBeenCalledTimes(1); + } finally { + close.mockRestore(); + } +}); + test("closing the EVM store releases its database handle", () => { const store = new EvmBotStore(":memory:", "test-deployment"); const close = spyOn(store.db, "close"); From d8eda05728b7e5724505be9944166592c66c2230 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 17:34:10 -0300 Subject: [PATCH 139/410] test(wallet): use fixed keys for unsigned recovery fixtures --- tests/wallet.transactions.test.ts | 44 +++++++++++++++++++++---------- 1 file changed, 30 insertions(+), 14 deletions(-) diff --git a/tests/wallet.transactions.test.ts b/tests/wallet.transactions.test.ts index 4400b51f..6bbe281e 100644 --- a/tests/wallet.transactions.test.ts +++ b/tests/wallet.transactions.test.ts @@ -85,7 +85,10 @@ const tokenAccountData = (options: { describe("getTokenBalance with createIfMissing", () => { test("reads the account that another request created in the meantime", async () => { const wallet = walletWith({}); - const owner = await wallet.getPublicKey(TELEGRAM_ID); + // The recovery path does not sign anything. Use a fixed, on-curve public key. + const owner = new PublicKey( + Buffer.from("d75a980182b10ab7d54bfed3c964073a0ee172f3daa62325af021a68f707511a", "hex"), + ); const ata = await getAssociatedTokenAddress( new PublicKey(USDC), owner, @@ -111,15 +114,29 @@ describe("getTokenBalance with createIfMissing", () => { return "never"; }; - const balance = await wallet.getTokenBalance(TELEGRAM_ID, USDC, { createIfMissing: true }); + const keys = spyOn(wallet, "getKeyPair").mockResolvedValue({ + publicKey: owner, + } as unknown as Keypair); + try { + const balance = await wallet.getTokenBalance(TELEGRAM_ID, USDC, { createIfMissing: true }); - expect(balance).toBe(777); - expect(ataReads).toBe(2); - expect(sent).toBe(0); + expect(balance).toBe(777); + expect(ataReads).toBe(2); + expect(sent).toBe(0); + } finally { + keys.mockRestore(); + } }); }); describe("token metadata lookups", () => { + let mintId = 0; + const newMint = () => { + const bytes = new Uint8Array(32); + bytes[0] = 200; + bytes[1] = ++mintId; + return new PublicKey(bytes).toBase58(); + }; const mintAccount = (decimals: number) => ({ owner: TOKEN_2022_PROGRAM_ID, data: Uint8Array.from( @@ -136,7 +153,7 @@ describe("token metadata lookups", () => { const noNetwork = async () => ({ ok: false, status: 503, json: async () => ({}) }); test("a failing local resolver falls back to the on-chain mint decimals", async () => { - const mint = (await Keypair.generate()).publicKey.toBase58(); + const mint = newMint(); const wallet = walletWith( { getAccountInfo: async (key: PublicKey) => (key.toBase58() === mint ? mintAccount(9) : null), @@ -162,7 +179,7 @@ describe("token metadata lookups", () => { new Error("lookup exploded"), ); try { - const mint = (await Keypair.generate()).publicKey.toBase58(); + const mint = newMint(); const failure = await wallet.getTokenMetadata(mint).catch((error) => error); expect(failure.message).toBe("Failed to get token metadata: lookup exploded"); @@ -177,7 +194,7 @@ describe("token metadata lookups", () => { }); test("full metadata works without an injected fetch and memoizes decimals", async () => { - const mint = (await Keypair.generate()).publicKey.toBase58(); + const mint = newMint(); const wallet = walletWith( { getAccountInfo: async () => null }, { tokenMetadataResolver: async () => ({ decimals: 7 }) }, @@ -204,7 +221,6 @@ describe("token metadata lookups", () => { describe("fetchMintDecimals", () => { const decimalsOf = (wallet: WalletManager, mint: string) => (wallet as any).fetchMintDecimals(mint) as Promise; - const newMint = async () => (await Keypair.generate()).publicKey.toBase58(); test("prefers the parsed account info when the RPC provides it", async () => { const wallet = walletWith({ @@ -216,11 +232,11 @@ describe("token metadata lookups", () => { }, }); - expect(await decimalsOf(wallet, await newMint())).toBe(4); + expect(await decimalsOf(wallet, newMint())).toBe(4); }); test("falls back to the raw mint account when parsed info fails or lacks decimals", async () => { - const mint = await newMint(); + const mint = newMint(); const connection: Record = { getParsedAccountInfo: async () => { throw new Error("parsed unavailable"); @@ -239,7 +255,7 @@ describe("token metadata lookups", () => { }); test("reports connections that cannot read accounts", async () => { - await expect(decimalsOf(walletWith({}), await newMint())).rejects.toThrow( + await expect(decimalsOf(walletWith({}), newMint())).rejects.toThrow( "RPC connection does not support getAccountInfo for mint metadata", ); }); @@ -247,13 +263,13 @@ describe("token metadata lookups", () => { test("reports a mint that does not exist", async () => { const wallet = walletWith({ getAccountInfo: async () => null }); - await expect(decimalsOf(wallet, await newMint())).rejects.toThrow( + await expect(decimalsOf(wallet, newMint())).rejects.toThrow( "Token mint account not found or has no data", ); }); test("does not report a malformed mint owner as a missing mint", async () => { - const mint = await newMint(); + const mint = newMint(); const ownerFailure = new Error("account not found"); const wallet = walletWith({ getAccountInfo: async () => ({ From 293b7bf6127669d7c851be8ae6b4ee57f305f131 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 17:41:06 -0300 Subject: [PATCH 140/410] fix(evm): route only recognized command aliases --- src/evm/command-router.ts | 30 ++++++++++---------- tests/evm.command-router.test.ts | 48 ++++++++++++++++++++++++++++++++ 2 files changed, 64 insertions(+), 14 deletions(-) create mode 100644 tests/evm.command-router.test.ts diff --git a/src/evm/command-router.ts b/src/evm/command-router.ts index 0d2c9938..70ec96e3 100644 --- a/src/evm/command-router.ts +++ b/src/evm/command-router.ts @@ -8,20 +8,22 @@ export function routeNetworkCommand(text: string, username: string, network: "so ) return null; const name = parsed[1]!.toLowerCase(); - const command = - ( - { - cf: "ecf", - coinflip: "ecf", - ga: "egiveaway", - giveaway: "egiveaway", - balance: "evm", - wallet: "evm", - invite: "einvite", - withdraw: "ewithdraw", - wh: "ewithdraw", - } as Record - )[name] ?? (name === "start" && !parsed[3] ? "evm" : undefined); + const aliases = { + cf: "ecf", + coinflip: "ecf", + ga: "egiveaway", + giveaway: "egiveaway", + balance: "evm", + wallet: "evm", + invite: "einvite", + withdraw: "ewithdraw", + wh: "ewithdraw", + }; + const command = Object.hasOwn(aliases, name) + ? aliases[name as keyof typeof aliases] + : name === "start" && !parsed[3] + ? "evm" + : undefined; if (!command) return null; let args = parsed[3] ?? ""; if (command === "ewithdraw") { diff --git a/tests/evm.command-router.test.ts b/tests/evm.command-router.test.ts new file mode 100644 index 00000000..5a8e5335 --- /dev/null +++ b/tests/evm.command-router.test.ts @@ -0,0 +1,48 @@ +import { expect, test } from "bun:test"; +import { routeNetworkCommand } from "../src/evm/command-router"; + +test.each([ + ["cf", "ecf"], + ["coinflip", "ecf"], + ["ga", "egiveaway"], + ["giveaway", "egiveaway"], + ["balance", "evm"], + ["wallet", "evm"], + ["invite", "einvite"], +] as const)("routes %s to %s only for an EVM chat", (alias, command) => { + expect( + routeNetworkCommand(`/${alias.toUpperCase()}@TIMBABOT payload`, "TimbaBot", "evm"), + ).toEqual({ + command, + args: "payload", + }); + expect(routeNetworkCommand(`/${alias} payload`, "TimbaBot", "solana")).toBeNull(); +}); + +test.each([ + "/unknown", + "/constructor", + "/start game-link", + "/wallet@AnotherBot", + "text /balance", + "/cf!", +])("leaves an unrelated command alone (%s)", (command) => { + expect(routeNetworkCommand(command, "TimbaBot", "evm")).toBeNull(); +}); + +test("only a bare start opens the EVM wallet", () => { + expect(routeNetworkCommand("/start", "TimbaBot", "evm")).toEqual({ command: "evm", args: "" }); + expect(routeNetworkCommand("/start@TimbaBot ", "TimbaBot", "evm")).toEqual({ + command: "evm", + args: "", + }); +}); + +test.each([ + ["/withdraw", "ETH "], + ["/withdraw 0xfixture", "ETH 0xfixture"], + ["/withdraw 0xfixture 2", "ETH 2 0xfixture"], + ["/wh@TimbaBot 0xfixture\t 2.75 TOKEN ", "TOKEN 2.75 0xfixture"], +])("normalizes the withdrawal field order for %s", (text, args) => { + expect(routeNetworkCommand(text, "TimbaBot", "evm")).toEqual({ command: "ewithdraw", args }); +}); From 352866c00315593f49831a60b0d9f6c823d31dac Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 17:43:32 -0300 Subject: [PATCH 141/410] fix(evm): reject incomplete saved transaction envelopes --- src/evm/service.ts | 11 ++- tests/evm.service-boundaries.test.ts | 135 +++++++++++++++++++++++++++ 2 files changed, 142 insertions(+), 4 deletions(-) create mode 100644 tests/evm.service-boundaries.test.ts diff --git a/src/evm/service.ts b/src/evm/service.ts index 613a9637..6cf5c2a4 100644 --- a/src/evm/service.ts +++ b/src/evm/service.ts @@ -125,18 +125,19 @@ export class EvmBotService { }); } async step(action: EvmAction) { - const wallet = this.wallet(action.user); + const { raw: savedRaw, hash: savedHash } = action; const body = JSON.parse(action.body) as ActionBody; - if (action.raw && action.hash) { + if (savedRaw !== null || savedHash !== null) { + if (!savedRaw || !savedHash) throw new Error("Incomplete saved EVM transaction"); const receipt = await this.client - .getTransactionReceipt({ hash: action.hash }) + .getTransactionReceipt({ hash: savedHash }) .catch((error) => { if (error?.name === "TransactionReceiptNotFoundError") return null; throw error; }); if (!receipt) { await this.client - .sendRawTransaction({ serializedTransaction: action.raw }) + .sendRawTransaction({ serializedTransaction: savedRaw }) .catch(() => undefined); return; } @@ -158,6 +159,7 @@ export class EvmBotService { if (action.phase === "approval") { if (!body.token || body.approvalAmount === undefined) throw new Error("Missing durable approval context"); + const wallet = this.wallet(action.user); const approved = await this.client.readContract({ address: body.token, abi: erc20Abi, @@ -188,6 +190,7 @@ export class EvmBotService { this.store.finish(action); return; } + const wallet = this.wallet(action.user); let tx: { to: Address; data: Hex; value?: bigint }; let spend = 0n; if (action.kind === "create") { diff --git a/tests/evm.service-boundaries.test.ts b/tests/evm.service-boundaries.test.ts new file mode 100644 index 00000000..7677ad70 --- /dev/null +++ b/tests/evm.service-boundaries.test.ts @@ -0,0 +1,135 @@ +import { afterEach, beforeEach, expect, spyOn, test } from "bun:test"; +import { EvmBotService } from "../src/evm/service"; +import { EvmBotStore, type EvmAction } from "../src/evm/store"; +import type { EvmBotConfig } from "../src/evm/config"; + +const config: EvmBotConfig = { + chainId: 31337, + address: "0x0000000000000000000000000000000000000001", + version: "0.1.0", + name: "Test chain", + rpcUrls: ["http://127.0.0.1:1"], + oracleUrl: "https://oracle.invalid/", + oracleTokenFile: "unused-test-file", + database: ":memory:", + webUrl: "https://app.invalid/", + confirmations: 2, +}; +let store: EvmBotStore; +let service: EvmBotService; +beforeEach(() => { + store = new EvmBotStore(":memory:", "test-deployment"); + service = new EvmBotService(config, "unused test mnemonic", "fixture-token", store); +}); +afterEach(() => { + store.close(); +}); + +const transaction = (raw: EvmAction["raw"], hash: EvmAction["hash"]): EvmAction => ({ + id: "recovery-id", + user: "123", + chat: -97, + message: 3, + kind: "withdraw", + body: "{}", + phase: "transaction", + raw, + hash, +}); + +test.each([ + ["missing hash", "0x11", null], + ["missing bytes", null, "0x22"], +] as const)( + "does not start a new action when a saved transaction has %s", + async (_label, raw, hash) => { + const wallet = spyOn(service, "wallet").mockImplementation(() => { + throw new Error("Unexpected wallet initialization"); + }); + try { + const action = transaction(raw, hash); + store.add(action); + await expect(service.step(action)).rejects.toThrow("Incomplete saved EVM transaction"); + expect(wallet).not.toHaveBeenCalled(); + expect(store.action(action.id)).toMatchObject(action); + } finally { + wallet.mockRestore(); + } + }, +); + +test("replays only the saved bytes for a complete transaction without opening the wallet", async () => { + const action = transaction("0x11", "0x22"); + store.add(action); + const wallet = spyOn(service, "wallet").mockImplementation(() => { + throw new Error("Unexpected wallet initialization"); + }); + const unavailable = new Error("receipt not found"); + unavailable.name = "TransactionReceiptNotFoundError"; + const receipt = spyOn(service.client, "getTransactionReceipt").mockRejectedValue(unavailable); + const send = spyOn(service.client, "sendRawTransaction").mockResolvedValue("0x22"); + try { + await service.step(action); + expect(receipt).toHaveBeenCalledWith({ hash: "0x22" }); + expect(send.mock.calls).toEqual([[{ serializedTransaction: "0x11" }]]); + expect(wallet).not.toHaveBeenCalled(); + expect(store.action(action.id)).toMatchObject(action); + } finally { + send.mockRestore(); + receipt.mockRestore(); + wallet.mockRestore(); + } +}); + +test("uses the configured oracle path and sends JSON only for a request with input", async () => { + const mockFetch = Object.assign(async () => Response.json({ ok: true }), { + preconnect: () => {}, + }); + const fetch = spyOn(globalThis, "fetch").mockImplementation(mockFetch); + try { + await expect(service.oracle("/evm/config")).resolves.toEqual({ ok: true }); + await expect(service.oracle("/evm/authorize", { amount: 12n })).resolves.toEqual({ ok: true }); + expect(fetch.mock.calls.map(([url, init]) => [String(url), init?.method, init?.body])).toEqual([ + ["https://oracle.invalid/evm/config", "GET", undefined], + ["https://oracle.invalid/evm/authorize", "POST", '{"amount":"12"}'], + ]); + for (const [, init] of fetch.mock.calls) { + expect(new Headers(init?.headers).get("content-type")).toBe("application/json"); + expect(new Headers(init?.headers).get("authorization")).toBe("Bearer fixture-token"); + expect(init?.signal).toBeInstanceOf(AbortSignal); + } + } finally { + fetch.mockRestore(); + } +}); + +test("rejects wrong oracle and RPC deployments independently", async () => { + const metadata = { + chainId: config.chainId, + address: config.address, + version: config.version, + confirmations: 2, + tokens: [{ address: config.address, symbol: "TEST", decimals: 18, minimumAmount: "1" }], + }; + const oracle = spyOn(service, "oracle").mockResolvedValue(metadata); + const chain = spyOn(service.client, "getChainId").mockResolvedValue(config.chainId); + try { + await expect(service.metadata()).resolves.toMatchObject(metadata); + expect(oracle).toHaveBeenCalledWith("/evm/config"); + chain.mockClear(); + oracle.mockResolvedValue({ ...metadata, chainId: config.chainId + 1 }); + await expect(service.metadata()).rejects.toThrow("EVM oracle deployment mismatch"); + oracle.mockResolvedValue({ + ...metadata, + address: "0x0000000000000000000000000000000000000002", + }); + await expect(service.metadata()).rejects.toThrow("EVM oracle deployment mismatch"); + expect(chain).not.toHaveBeenCalled(); + oracle.mockResolvedValue(metadata); + chain.mockResolvedValue(config.chainId + 1); + await expect(service.metadata()).rejects.toThrow("EVM RPC chain mismatch"); + } finally { + chain.mockRestore(); + oracle.mockRestore(); + } +}); From f6a84c1abecc48c78aefb7ab8c16c6f3a91601e6 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 17:46:11 -0300 Subject: [PATCH 142/410] refactor(recovery): make probe and checkpoint guards explicit --- src/utils/game-creation-recovery.ts | 4 +- src/utils/transaction-runner.ts | 32 ++++---- ...ame-creation-recovery.proof-guards.test.ts | 9 +++ tests/transaction-runner.test.ts | 80 ++++++++++++++++++- 4 files changed, 104 insertions(+), 21 deletions(-) diff --git a/src/utils/game-creation-recovery.ts b/src/utils/game-creation-recovery.ts index a495b00a..f3325ac0 100644 --- a/src/utils/game-creation-recovery.ts +++ b/src/utils/game-creation-recovery.ts @@ -68,8 +68,8 @@ export async function proveExpiredCreationAbsent( isFinalizedSlot(saved.anchor?.slot) && isFinalizedSlot(saved.cursor?.slot) && saved.cursor.slot <= saved.anchor.slot && - Number.isSafeInteger(saved.anchor?.height) && - Number.isSafeInteger(saved.cursor?.height) && + Number.isSafeInteger(saved.anchor.height) && + Number.isSafeInteger(saved.cursor.height) && saved.anchor.height > input.lastValidBlockHeight && saved.cursor.height + saved.checkedBlocks === saved.anchor.height && typeof saved.anchor.hash === "string" && diff --git a/src/utils/transaction-runner.ts b/src/utils/transaction-runner.ts index 15bc22fe..a73a667a 100644 --- a/src/utils/transaction-runner.ts +++ b/src/utils/transaction-runner.ts @@ -186,25 +186,23 @@ export const confirmTransactionWithRecovery = async ( logDebug(`🔄 ${operationLabel} confirmation retry ${attemptLabel} after ${delay}ms`); await sleep(delay); - if (probes.length > 0) { - for (const probe of probes) { - try { - const ok = await probe.check(); - if (ok) { - logDebug( - `✅ ${operationLabel} transaction confirmed via probe "${probe.label}" on retry ${attemptLabel}`, - ); - return currentSignature; - } - } catch (probeError) { - const normalizedProbeError = - probeError instanceof Error ? probeError : new Error(String(probeError)); - console.error( - `❌ Probe "${probe.label}" failed during ${operationLabel} retry ${attemptLabel}`, - normalizedProbeError, + for (const probe of probes) { + try { + const ok = await probe.check(); + if (ok) { + logDebug( + `✅ ${operationLabel} transaction confirmed via probe "${probe.label}" on retry ${attemptLabel}`, ); - throw normalizedProbeError; + return currentSignature; } + } catch (probeError) { + const normalizedProbeError = + probeError instanceof Error ? probeError : new Error(String(probeError)); + console.error( + `❌ Probe "${probe.label}" failed during ${operationLabel} retry ${attemptLabel}`, + normalizedProbeError, + ); + throw normalizedProbeError; } } diff --git a/tests/game-creation-recovery.proof-guards.test.ts b/tests/game-creation-recovery.proof-guards.test.ts index bdc5e6c7..2be35c11 100644 --- a/tests/game-creation-recovery.proof-guards.test.ts +++ b/tests/game-creation-recovery.proof-guards.test.ts @@ -79,6 +79,15 @@ describe("restart jump to the expiry anchor", () => { expect(rpc).toHaveBeenCalledWith("getBlocks", [8500, 11014, { commitment: "finalized" }]); }); + test("can walk to the original block at slot zero", async () => { + const rpc = mock(rpcFor(chain(0, 1), 1)); + const origin = { ...input, blockhash: "hash0", lastValidBlockHeight: 0 }; + expect(await proveExpiredCreationAbsent(origin, rpc, rpc)).toBe(true); + expect( + rpc.mock.calls.filter(([method]) => method === "getBlock").map(([, [slot]]) => slot), + ).toEqual([1, 1, 0]); + }); + test("does not request a restart jump at the exact distance boundary", async () => { const rpc = mock(rpcFor(chain(10, 77), 77)); expect(await proveExpiredCreationAbsent(input, rpc, rpc)).toBe(true); diff --git a/tests/transaction-runner.test.ts b/tests/transaction-runner.test.ts index f404c054..45796459 100644 --- a/tests/transaction-runner.test.ts +++ b/tests/transaction-runner.test.ts @@ -1,4 +1,14 @@ -import { afterEach, beforeEach, describe, expect, mock, spyOn, test, vi } from "bun:test"; +import { + afterEach, + beforeEach, + describe, + expect, + mock, + spyOn, + test, + vi, + type Mock, +} from "bun:test"; import { confirmTransactionWithRecovery, getConfirmationRetryDelays, @@ -32,7 +42,7 @@ const makeWallet = (options: { const timeout = () => new Error("Transaction confirmation timeout"); let warnSpy: ReturnType; -let errorSpy: ReturnType; +let errorSpy: Mock; beforeEach(() => { warnSpy = spyOn(console, "warn").mockImplementation(() => {}); let errors = 0; @@ -166,6 +176,40 @@ describe("confirmTransactionWithRecovery", () => { } }); + test.each([0, -1])("does not schedule a timer for a retry delay of %i", async (delay) => { + vi.useFakeTimers(); + const original = timeout(); + try { + const { wallet, statusCalls } = makeWallet({ + confirm: async () => { + throw original; + }, + statuses: () => ({ confirmationStatus: "confirmed" }), + }); + const outcomes: unknown[] = []; + const task = confirmTransactionWithRecovery({ + wallet, + initialSignature: "no-wait", + operationLabel: "Join", + retryDelays: [delay], + probes: [], + }).then( + (signature) => outcomes.push(signature), + (error: unknown) => outcomes.push(error), + ); + for (let step = 0; step < 12; step += 1) await Promise.resolve(); + const timerCount = vi.getTimerCount(); + const immediate = [...outcomes]; + vi.runAllTimers(); + await task; + expect(timerCount).toBe(0); + expect(immediate).toEqual(["no-wait"]); + expect(statusCalls).toEqual(["no-wait"]); + } finally { + vi.useRealTimers(); + } + }); + test("returns the original signature when it confirms", async () => { const { wallet } = makeWallet({}); const logger = mock(() => {}); @@ -250,6 +294,7 @@ describe("confirmTransactionWithRecovery", () => { }, }); const resubmit = mock(async (attempt: number, _previous: string) => `sig-${attempt + 2}`); + const logger = mock((_message: unknown) => {}); expect( await confirmTransactionWithRecovery({ @@ -257,12 +302,20 @@ describe("confirmTransactionWithRecovery", () => { initialSignature: "sig-1", operationLabel: "Op", resubmit, + logger, }), ).toBe("sig-3"); expect(resubmit.mock.calls).toEqual([ [0, "sig-1"], [1, "sig-2"], ]); + expect(logger.mock.calls).toEqual([ + ["🔄 Op resubmission attempt 1/2 after failure for sig-1"], + ["🔍 Op transaction resubmitted 1/2; confirming signature: sig-2"], + ["🔄 Op resubmission attempt 2/2 after failure for sig-2"], + ["🔍 Op transaction resubmitted 2/2; confirming signature: sig-3"], + ["✅ Op resubmitted transaction confirmed 2/2: sig-3"], + ]); }); test.each([ @@ -274,6 +327,7 @@ describe("confirmTransactionWithRecovery", () => { ["missing signature", { message: "retry failed" }, "initial"], ["numeric signature", { lastSignature: 42, message: "retry failed" }, "initial"], ["empty signature", { lastSignature: "", message: "retry failed" }, "initial"], + ["null retry error", null, "initial"], ["plain retry error", "retry failed", "initial"], ] as const)("checks the correct signature after a %s", async (_label, error, expected) => { const { wallet, statusCalls } = makeWallet({ @@ -369,6 +423,11 @@ describe("confirmTransactionWithRecovery", () => { expect(errorSpy.mock.calls[0]?.[1]?.message).toBe( "Resubmission callback did not return a transaction signature", ); + expect(errorSpy.mock.calls[0]?.[1]?.cause).toBe(original); + expect(errorSpy.mock.calls.map(([message]) => message)).toEqual([ + "❌ Op resubmission 1/2 failed", + "❌ Op resubmission 2/2 failed", + ]); }); test.each([ @@ -409,6 +468,11 @@ describe("confirmTransactionWithRecovery", () => { retryDelays: [0, 0], }), ).rejects.toThrow('Transaction s failed: {"InstructionError":[0,"Custom"]}'); + expect(errorSpy).toHaveBeenCalledTimes(1); + expect(errorSpy).toHaveBeenCalledWith( + "❌ Failed to verify transaction status during Op retry 1/2", + expect.objectContaining({ cause: { InstructionError: [0, "Custom"] } }), + ); }); test("a status lookup that throws a non-Error is normalised", async () => { @@ -530,6 +594,11 @@ describe("confirmTransactionWithRecovery", () => { ], }), ).rejects.toThrow("probe broke"); + expect(errorSpy).toHaveBeenCalledTimes(1); + expect(errorSpy).toHaveBeenCalledWith( + '❌ Probe "broken" failed during Op retry 1/1', + expect.objectContaining({ message: "probe broke" }), + ); }); test("falls back to the signature status when no probe confirms", async () => { @@ -541,6 +610,7 @@ describe("confirmTransactionWithRecovery", () => { statuses: () => (++lookups === 1 ? null : { confirmationStatus: "finalized" }), }); const check = mock(async () => false); + const logger = mock((_message: unknown) => {}); expect( await confirmTransactionWithRecovery({ @@ -549,9 +619,15 @@ describe("confirmTransactionWithRecovery", () => { operationLabel: "Op", retryDelays: [0, 0], probes: [{ label: "never", check }], + logger, }), ).toBe("s"); expect(check).toHaveBeenCalledTimes(2); expect(lookups).toBe(2); + expect(logger.mock.calls).toEqual([ + ["🔄 Op confirmation retry 1/2 after 0ms"], + ["🔄 Op confirmation retry 2/2 after 0ms"], + ["✅ Op transaction confirmed via signature status on retry 2/2: s"], + ]); }); }); From 689c7ea71ba5dd0e4463866e73c01e67b488ec96 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 17:46:19 -0300 Subject: [PATCH 143/410] fix(evm): keep blank signed phases from starting new work --- src/evm/service.ts | 11 ++++++++--- tests/evm.service-boundaries.test.ts | 13 ++++++++----- 2 files changed, 16 insertions(+), 8 deletions(-) diff --git a/src/evm/service.ts b/src/evm/service.ts index 6cf5c2a4..57181304 100644 --- a/src/evm/service.ts +++ b/src/evm/service.ts @@ -125,9 +125,14 @@ export class EvmBotService { }); } async step(action: EvmAction) { - const { raw: savedRaw, hash: savedHash } = action; + const { phase, raw: savedRaw, hash: savedHash } = action; const body = JSON.parse(action.body) as ActionBody; - if (savedRaw !== null || savedHash !== null) { + if ( + phase === "approval" || + phase === "transaction" || + savedRaw !== null || + savedHash !== null + ) { if (!savedRaw || !savedHash) throw new Error("Incomplete saved EVM transaction"); const receipt = await this.client .getTransactionReceipt({ hash: savedHash }) @@ -156,7 +161,7 @@ export class EvmBotService { this.store.update(action); return; } - if (action.phase === "approval") { + if (phase === "approval") { if (!body.token || body.approvalAmount === undefined) throw new Error("Missing durable approval context"); const wallet = this.wallet(action.user); diff --git a/tests/evm.service-boundaries.test.ts b/tests/evm.service-boundaries.test.ts index 7677ad70..c7373e37 100644 --- a/tests/evm.service-boundaries.test.ts +++ b/tests/evm.service-boundaries.test.ts @@ -38,16 +38,19 @@ const transaction = (raw: EvmAction["raw"], hash: EvmAction["hash"]): EvmAction }); test.each([ - ["missing hash", "0x11", null], - ["missing bytes", null, "0x22"], + ["missing hash", "transaction", "0x11", null], + ["missing bytes", "transaction", null, "0x22"], + ["no transaction bytes or hash", "transaction", null, null], + ["no approval bytes or hash", "approval", null, null], + ["unexpected saved bytes in a new action", "new", "0x11", null], ] as const)( - "does not start a new action when a saved transaction has %s", - async (_label, raw, hash) => { + "does not start a new action when the saved state has %s", + async (_label, phase, raw, hash) => { const wallet = spyOn(service, "wallet").mockImplementation(() => { throw new Error("Unexpected wallet initialization"); }); try { - const action = transaction(raw, hash); + const action = { ...transaction(raw, hash), phase }; store.add(action); await expect(service.step(action)).rejects.toThrow("Incomplete saved EVM transaction"); expect(wallet).not.toHaveBeenCalled(); From c8fc5a57de22887535524d156318407bea66b744 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 17:49:36 -0300 Subject: [PATCH 144/410] refactor(menus): log edit failures at one boundary --- src/utils/menu-response.ts | 69 +++++--------- tests/menu-response.test.ts | 185 ++++++++++++++++++++++++++++++++---- 2 files changed, 195 insertions(+), 59 deletions(-) diff --git a/src/utils/menu-response.ts b/src/utils/menu-response.ts index 0a4ad167..da0a6d33 100644 --- a/src/utils/menu-response.ts +++ b/src/utils/menu-response.ts @@ -57,7 +57,7 @@ type EditAttemptResult = { type EditTargetAttempt = { invoke: () => Promise; continueOnFailure?: boolean; - onFailure?: (result: EditAttemptResult) => void; + onFailure: (error: unknown) => void; shouldContinue?: (result: EditAttemptResult) => boolean; }; @@ -141,18 +141,17 @@ export const respondWithMenu = async ( }), ), shouldContinue: shouldContinueOnMissingContent, - // onFailure only runs for results that carry an error. - onFailure: (result) => { - if (isMissingEditableContent(result.error)) { + onFailure: (error) => { + if (isMissingEditableContent(error)) { console.warn( `${logLabel}: editMessageCaption failed (missing caption), attempting text edit:`, - result.error, + error, ); return; } console.warn( `${logLabel}: editMessageCaption failed for explicit target, replying instead:`, - result.error, + error, ); }, }); @@ -169,13 +168,11 @@ export const respondWithMenu = async ( ), ), continueOnFailure: false, - onFailure: (result) => { - if (result.error) { - console.warn( - `${logLabel}: editMessageText failed for explicit target, replying instead:`, - result.error, - ); - } + onFailure: (error) => { + console.warn( + `${logLabel}: editMessageText failed for explicit target, replying instead:`, + error, + ); }, }); @@ -206,13 +203,11 @@ export const respondWithMenu = async ( if (typeof (ctx as any).editMessageCaption === "function") { attempts.push({ invoke: () => editMenuMessage(ctx, payload, "caption"), - onFailure: (result) => { - if (result.error) { - console.warn( - `${logLabel}: adapter editMessageCaption failed, attempting text edit:`, - result.error, - ); - } + onFailure: (error) => { + console.warn( + `${logLabel}: adapter editMessageCaption failed, attempting text edit:`, + error, + ); }, }); } @@ -220,13 +215,8 @@ export const respondWithMenu = async ( attempts.push({ invoke: () => editMenuMessage(ctx, payload, "text"), continueOnFailure: false, - onFailure: (result) => { - if (result.error) { - console.warn( - `${logLabel}: adapter editMessageText failed, replying instead:`, - result.error, - ); - } + onFailure: (error) => { + console.warn(`${logLabel}: adapter editMessageText failed, replying instead:`, error); }, }); @@ -244,13 +234,8 @@ export const respondWithMenu = async ( if (supportsCaption) { attempts.push({ invoke: () => editMenuMessage(ctx, payload, "caption"), - onFailure: (result) => { - if (result.error) { - console.warn( - `${logLabel}: editMessageCaption failed, attempting text edit:`, - result.error, - ); - } + onFailure: (error) => { + console.warn(`${logLabel}: editMessageCaption failed, attempting text edit:`, error); }, }); } @@ -258,13 +243,11 @@ export const respondWithMenu = async ( attempts.push({ invoke: () => editMenuMessage(ctx, payload, "text"), continueOnFailure: false, - onFailure: (result) => { - if (result.error) { - const messageText = supportsCaption - ? `${logLabel}: editMessageText failed after caption fallback, replying instead:` - : `${logLabel}: editMessageText failed, falling back to reply:`; - console.warn(messageText, result.error); - } + onFailure: (error) => { + const messageText = supportsCaption + ? `${logLabel}: editMessageText failed after caption fallback, replying instead:` + : `${logLabel}: editMessageText failed, falling back to reply:`; + console.warn(messageText, error); }, }); @@ -297,8 +280,8 @@ export const respondWithMenu = async ( }; } - if (attempt.onFailure && result.error) { - attempt.onFailure(result); + if (result.error) { + attempt.onFailure(result.error); } const shouldContinue = attempt.shouldContinue diff --git a/tests/menu-response.test.ts b/tests/menu-response.test.ts index c09498bf..800ed7ad 100644 --- a/tests/menu-response.test.ts +++ b/tests/menu-response.test.ts @@ -349,23 +349,28 @@ describe("respondWithMenu", () => { ctx.callbackQuery = undefined; ctx.__editAdapterTarget = { chatId: 321, messageId: 654 }; - ctx.editMessageText = async () => { - const err: any = new Error("Too Many Requests"); - err.error_code = 429; - err.description = "Too Many Requests: retry after 25"; - throw err; - }; - - const result = await respondWithMenu(ctx as any, basePayload); - - expect(result).toEqual({ - messageId: 654, - chatId: 321, - respondedWithReply: false, + const error = Object.assign(new Error("Too Many Requests"), { + error_code: 429, + description: "Too Many Requests: retry after 25", }); - - const replies = ctx.__calls.filter((c: any) => c.type === "reply"); - expect(replies.length).toBe(0); + ctx.editMessageCaption = mock(async () => { + throw error; + }); + const warnings = spyOn(console, "warn").mockImplementation(() => {}); + try { + expect(await respondWithMenu(ctx, basePayload)).toEqual({ + messageId: 654, + chatId: 321, + respondedWithReply: false, + }); + expect(ctx.editMessageCaption).toHaveBeenCalledTimes(1); + expect(ctx.__calls).toEqual([]); + expect(warnings.mock.calls).toEqual([ + ["respondWithMenu: editMessage throttled, keeping current message", error], + ]); + } finally { + warnings.mockRestore(); + } }); test("falls back to reply when adapter edits cannot proceed", async () => { @@ -490,4 +495,152 @@ describe("respondWithMenu", () => { respondedWithReply: false, }); }); + + test.each(["HTML", "Markdown", "MarkdownV2"] as const)( + "passes %s through the explicit caption edit with both target IDs intact", + async (parseMode) => { + const editMessageCaption = mock( + async (_chat: number, _message: number, _options: unknown) => ({}), + ); + const ctx = makeCtx({ api: { editMessageCaption } }); + expect( + await respondWithMenu( + ctx, + { ...basePayload, parseMode }, + { + targetChatId: -123, + targetMessageId: 0, + }, + ), + ).toEqual({ messageId: 0, chatId: -123, respondedWithReply: false }); + expect(editMessageCaption.mock.calls).toEqual([ + [ + -123, + 0, + { caption: basePayload.text, parse_mode: parseMode, reply_markup: basePayload.keyboard }, + ], + ]); + expect(ctx.__calls).toEqual([]); + }, + ); + + test("uses adapter text directly when its caption method is absent", async () => { + const ctx = makeCtx({ message: { caption: "not the adapter message" } }); + ctx.__editAdapterTarget = { messageId: 0, chatId: -123 }; + ctx.editMessageCaption = undefined; + expect(await respondWithMenu(ctx, basePayload)).toEqual({ + messageId: 0, + chatId: -123, + respondedWithReply: false, + }); + expect(ctx.__calls).toEqual([ + { + type: "text", + args: [ + basePayload.text, + { + parse_mode: "HTML", + reply_markup: basePayload.keyboard, + link_preview_options: { is_disabled: true }, + }, + ], + }, + ]); + }); + + test("replies without a reply anchor for a callback with no message", async () => { + const ctx = makeCtx({ replyResult: { message_id: 0 } }); + ctx.callbackQuery = { inline_message_id: "inline-message" }; + ctx.chat = { id: -505 }; + expect(await respondWithMenu(ctx, basePayload)).toEqual({ + messageId: 0, + chatId: -505, + respondedWithReply: true, + }); + expect(ctx.__calls).toEqual([ + { + type: "reply", + args: [ + basePayload.text, + { + parse_mode: "HTML", + reply_markup: basePayload.keyboard, + link_preview_options: { is_disabled: true }, + reply_to_message_id: undefined, + }, + ], + }, + ]); + }); + + test.each([ + [ + "callback with caption", + { caption: "existing" }, + false, + [ + "respondWithMenu: editMessageCaption failed, attempting text edit:", + "respondWithMenu: editMessageText failed after caption fallback, replying instead:", + ], + ], + [ + "callback with text", + { text: "existing" }, + false, + ["respondWithMenu: editMessageText failed, falling back to reply:"], + ], + [ + "adapter", + {}, + true, + [ + "respondWithMenu: adapter editMessageCaption failed, attempting text edit:", + "respondWithMenu: adapter editMessageText failed, replying instead:", + ], + ], + ] as const)("logs each failed edit once for a %s", async (_label, message, adapter, expected) => { + const error = new Error("message cannot be edited"); + const fail = async () => { + throw error; + }; + const ctx = makeCtx({ message }); + if (adapter) { + ctx.callbackQuery = undefined; + ctx.__editAdapterTarget = { chatId: 99, messageId: 71 }; + } + ctx.editMessageCaption = fail; + ctx.editMessageText = fail; + const warnings = spyOn(console, "warn").mockImplementation(() => {}); + try { + expect(await respondWithMenu(ctx, basePayload)).toEqual({ + messageId: 123, + chatId: 42, + respondedWithReply: true, + }); + expect(warnings.mock.calls).toEqual(expected.map((message) => [message, error])); + } finally { + warnings.mockRestore(); + } + }); + + test("keeps falsey edit errors silent and still sends a reply", async () => { + const ctx = makeCtx({ message: { caption: "existing" } }); + ctx.editMessageCaption = async () => { + throw undefined; + }; + ctx.editMessageText = async () => { + throw 0; + }; + const warnings = spyOn(console, "warn").mockImplementation(() => {}); + try { + expect(await respondWithMenu(ctx, basePayload)).toEqual({ + messageId: 123, + chatId: 42, + respondedWithReply: true, + }); + expect(warnings).not.toHaveBeenCalled(); + } finally { + warnings.mockRestore(); + } + }); }); From 6d90d6a7cf997481660790f21d53319adffbcb19 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 17:52:39 -0300 Subject: [PATCH 145/410] fix(history): preserve recorded block height zero --- src/utils/transaction-history.ts | 4 +-- tests/transaction-history.paths.test.ts | 43 +++++++++++++++++++++++++ 2 files changed, 45 insertions(+), 2 deletions(-) diff --git a/src/utils/transaction-history.ts b/src/utils/transaction-history.ts index 73642f64..33304afc 100644 --- a/src/utils/transaction-history.ts +++ b/src/utils/transaction-history.ts @@ -515,7 +515,7 @@ export class TransactionHistory extends BaseDatabase { record.status, record.timestamp, record.network || "mainnet", - record.block_height || null, + record.block_height ?? null, ], "adding transaction record", ); @@ -543,7 +543,7 @@ export class TransactionHistory extends BaseDatabase { `UPDATE transaction_history SET status = ?, block_height = ?, updated_at = CURRENT_TIMESTAMP WHERE signature = ?`, - [status, blockHeight || null, signature], + [status, blockHeight ?? null, signature], "updating transaction status", ); console.log(`🔄 Updated transaction ${signature} status to ${status}`); diff --git a/tests/transaction-history.paths.test.ts b/tests/transaction-history.paths.test.ts index 0955dee4..6e16b4a8 100644 --- a/tests/transaction-history.paths.test.ts +++ b/tests/transaction-history.paths.test.ts @@ -207,6 +207,31 @@ describe("swap finance evidence", () => { }); describe("TransactionHistory error handling", () => { + test("keeps block height zero distinct from an unknown height on insert and update", () => { + const db = TransactionHistory.getInstance(); + db.addTransaction(record("known-at-insert", { block_height: 0 })); + db.addTransaction(record("known-at-update", { status: "PENDING" })); + db.addTransaction(record("still-unknown")); + db.updateTransactionStatus("known-at-update", "SUCCESS", 0); + const rows = withRawDatabase((raw) => + raw + .query< + { + signature: string; + status: string; + block_height: number | null; + }, + [] + >("SELECT signature, status, block_height FROM transaction_history ORDER BY signature") + .all(), + ); + expect(rows).toEqual([ + { signature: "known-at-insert", status: "SUCCESS", block_height: 0 }, + { signature: "known-at-update", status: "SUCCESS", block_height: 0 }, + { signature: "still-unknown", status: "SUCCESS", block_height: null }, + ]); + }); + test("addTransaction logs and rethrows on a duplicate signature", () => { const db = TransactionHistory.getInstance(); db.addTransaction(record("dup-sig")); @@ -232,16 +257,34 @@ describe("TransactionHistory error handling", () => { }); test("history readers fall back to empty results and zero counts", () => { + expect(db.getUserHistory("user-f")).toEqual([]); + expect(loggedErrors()).toContain( + "[TransactionHistory DB] Error during getting user history:", + ); + expect(loggedErrors()).toContain("Error getting user history:"); + expect(db.getUserHistoryByType("user-f", "BUY")).toEqual([]); + expect(loggedErrors()).toContain( + "[TransactionHistory DB] Error during getting user history by type:", + ); expect(loggedErrors()).toContain("Error getting user history by type:"); expect(db.getUserTransactionCount("user-f")).toBe(0); + expect(loggedErrors()).toContain( + "[TransactionHistory DB] Error during getting transaction count:", + ); expect(loggedErrors()).toContain("Error getting transaction count:"); expect(db.getRecentTransactions(5)).toEqual([]); + expect(loggedErrors()).toContain( + "[TransactionHistory DB] Error during getting recent transactions:", + ); expect(loggedErrors()).toContain("Error getting recent transactions:"); expect(db.cleanOldTransactions(1)).toBe(0); + expect(loggedErrors()).toContain( + "[TransactionHistory DB] Error during cleaning old transactions:", + ); expect(loggedErrors()).toContain("Error cleaning old transactions:"); }); }); From d2a07ef5498283b5f56a2a4201d7fed2e9d456e5 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 17:53:53 -0300 Subject: [PATCH 146/410] fix(rpc): reject blank single-endpoint fallbacks --- src/utils/rpc-endpoints.ts | 28 +++---- tests/rpc-endpoints.error-paths.test.ts | 97 ++++++++++++++++++++++++- 2 files changed, 104 insertions(+), 21 deletions(-) diff --git a/src/utils/rpc-endpoints.ts b/src/utils/rpc-endpoints.ts index 3d178c01..dd2359ee 100644 --- a/src/utils/rpc-endpoints.ts +++ b/src/utils/rpc-endpoints.ts @@ -362,21 +362,18 @@ export function parseRpcEndpointList( options: { fallback?: string | string[] } = {}, ): string[] { const { fallback } = options; - const fallbackList = - typeof fallback === "string" - ? [fallback] - : Array.isArray(fallback) - ? fallback.filter((item) => item && item.trim().length > 0) - : []; - - if (!value || value.trim().length === 0) { + const fallbackList = ( + typeof fallback === "string" ? [fallback] : Array.isArray(fallback) ? fallback : [] + ).filter((item) => item && item.trim().length > 0); + + const trimmed = value?.trim(); + if (!trimmed) { if (fallbackList.length === 0) { throw new Error("SOLANA_NETWORK is required"); } return fallbackList; } - const trimmed = value.trim(); let parsed: unknown; if (trimmed.startsWith("[") && trimmed.endsWith("]")) { @@ -387,16 +384,9 @@ export function parseRpcEndpointList( } } - let endpoints: string[]; - if (Array.isArray(parsed)) { - endpoints = parsed.map((item) => String(item ?? "")); - } else { - endpoints = trimmed - .split(",") - .map((segment) => segment.trim()) - .filter((segment) => segment.length > 0); - } - + const endpoints = Array.isArray(parsed) + ? parsed.map((item) => String(item ?? "")) + : trimmed.split(","); const unique: string[] = []; const seen = new Set(); for (const endpoint of endpoints) { diff --git a/tests/rpc-endpoints.error-paths.test.ts b/tests/rpc-endpoints.error-paths.test.ts index f0cf945f..de43afe5 100644 --- a/tests/rpc-endpoints.error-paths.test.ts +++ b/tests/rpc-endpoints.error-paths.test.ts @@ -1,5 +1,5 @@ -import { describe, expect, test } from "bun:test"; -import type { Connection } from "#solana"; +import { describe, expect, mock, test } from "bun:test"; +import type { Commitment, Connection } from "#solana"; import { DEFAULT_MAINNET_ENDPOINT, RpcEndpointManager, @@ -208,6 +208,72 @@ describe("RpcEndpointManager call handling", () => { expect(await manager.getConnection().getSlot()).toBe(55n); expect(primaryCalls).toBe(2); }); + + test.each([ + ["different cluster", "different"], + ["empty genesis", ""], + ["unavailable genesis method", undefined], + ] as const)("never reads from the fallback with %s", async (_label, fallbackGenesis) => { + const primary = mock(async () => 19n).mockRejectedValueOnce(resetError()); + const fromFallback = mock(async () => 28n); + const manager = new RpcEndpointManager(["https://rpc-primary"], { + fallbackEndpoint: "https://rpc-fallback", + connectionFactory: (endpoint) => + asConnection( + endpoint.endsWith("primary") + ? { + getSlot: primary, + getGenesisHash: async () => "same-cluster", + } + : { + getSlot: fromFallback, + getGenesisHash: + fallbackGenesis === undefined ? undefined : async () => fallbackGenesis, + }, + ), + }); + expect(await manager.getConnection().getSlot()).toBe(19n); + expect(primary).toHaveBeenCalledTimes(2); + expect(fromFallback).not.toHaveBeenCalled(); + expect(manager.getActiveEndpoint()).toBe("https://rpc-primary"); + }); + + test("verifies the same-cluster fallback only once and never promotes it", async () => { + const primary = mock(async () => { + throw resetError(); + }); + const primaryGenesis = mock(async () => "same-cluster"); + const fallbackGenesis = mock(async () => "same-cluster"); + const fromFallback = mock(async () => 20n).mockResolvedValueOnce(19n); + const factory = mock((endpoint: string, _commitment: Commitment) => + asConnection( + endpoint.endsWith("primary") + ? { + getSlot: primary, + getGenesisHash: primaryGenesis, + } + : { + getSlot: fromFallback, + getGenesisHash: fallbackGenesis, + }, + ), + ); + const manager = new RpcEndpointManager(["https://rpc-primary"], { + fallbackEndpoint: "https://rpc-fallback", + connectionFactory: factory, + }); + expect(await manager.getConnection().getSlot()).toBe(19n); + expect(await manager.getConnection().getSlot()).toBe(20n); + expect(primary).toHaveBeenCalledTimes(2); + expect(fromFallback).toHaveBeenCalledTimes(2); + expect(primaryGenesis).toHaveBeenCalledTimes(1); + expect(fallbackGenesis).toHaveBeenCalledTimes(1); + expect(factory.mock.calls).toEqual([ + ["https://rpc-primary", "confirmed"], + ["https://rpc-fallback", "confirmed"], + ]); + expect(manager.getActiveEndpoint()).toBe("https://rpc-primary"); + }); }); describe("parseRpcEndpointList edge cases", () => { @@ -217,6 +283,33 @@ describe("parseRpcEndpointList edge cases", () => { ]); }); + test.each(["", " \t "])( + "rejects a blank scalar fallback %j just like an empty list", + (fallback) => { + expect(() => parseRpcEndpointList(undefined, { fallback })).toThrow( + "SOLANA_NETWORK is required", + ); + expect(() => parseRpcEndpointList("[]", { fallback })).toThrow( + "SOLANA_NETWORK resolved to an empty list", + ); + }, + ); + + test("preserves the syntax error for a malformed JSON endpoint list", () => { + const parsingError: unknown = (() => { + try { + return parseRpcEndpointList('["https://rpc.example",]'); + } catch (error) { + return error; + } + })(); + expect(parsingError).toBeInstanceOf(Error); + expect(parsingError).toMatchObject({ + message: expect.stringContaining("Failed to parse SOLANA_NETWORK JSON array:"), + cause: expect.any(SyntaxError), + }); + }); + test("skips empty JSON array entries and keeps the remaining endpoints", () => { expect(parseRpcEndpointList('["", "https://a", " "]')).toEqual(["https://a"]); }); From dd3c3edbba7e7de407efb2f085f0ae7106b54e21 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 17:56:29 -0300 Subject: [PATCH 147/410] refactor(utils): keep file reads finite and parser fallbacks explicit --- src/utils/program-event-parser.ts | 3 +- src/utils/secrets.ts | 3 +- tests/program-event-parser.truncated.test.ts | 18 ++++++++++ tests/token-database.schema.test.ts | 38 ++++++++++++++++++++ 4 files changed, 59 insertions(+), 3 deletions(-) diff --git a/src/utils/program-event-parser.ts b/src/utils/program-event-parser.ts index 29472d24..cef7a593 100644 --- a/src/utils/program-event-parser.ts +++ b/src/utils/program-event-parser.ts @@ -44,9 +44,8 @@ export function decodeProgramEventLog( } catch { /* Keep the legacy caller's fallback behavior. */ } - if (!decodeFallback) return null; try { - return decodeFallback(logBase64) ?? null; + return decodeFallback?.(logBase64) ?? null; } catch { return null; } diff --git a/src/utils/secrets.ts b/src/utils/secrets.ts index c3dfb1e2..51a5ecef 100644 --- a/src/utils/secrets.ts +++ b/src/utils/secrets.ts @@ -34,7 +34,8 @@ export function readProtectedSecretFile(filePath: string, label: string): string const buffer = Buffer.alloc(MAX_SECRET_BYTES + 1); let length = 0; // Even a series of one-byte reads needs at most the buffer length in calls. - for (let readsLeft = buffer.length; readsLeft > 0 && length < buffer.length; readsLeft--) { + for (const _ of buffer.keys()) { + if (length >= buffer.length) break; const bytesRead = fs.readSync(fd, buffer, length, buffer.length - length, null); if (bytesRead === 0) break; length += bytesRead; diff --git a/tests/program-event-parser.truncated.test.ts b/tests/program-event-parser.truncated.test.ts index d90e60a2..7873baae 100644 --- a/tests/program-event-parser.truncated.test.ts +++ b/tests/program-event-parser.truncated.test.ts @@ -21,3 +21,21 @@ test("a truncated known event without a fallback decodes to null", () => { const log = Buffer.concat([GAME_COMPLETED, Buffer.alloc(10)]).toString("base64"); expect(decodeProgramEventLog(log)).toBeNull(); }); + +test("keeps malformed events absent when the fallback returns null or throws", () => { + const log = Buffer.concat([GAME_COMPLETED, Buffer.alloc(10)]).toString("base64"); + const inputs: string[] = []; + expect( + decodeProgramEventLog(log, (entry) => { + inputs.push(entry); + return null; + }), + ).toBeNull(); + expect( + decodeProgramEventLog(log, (entry) => { + inputs.push(entry); + throw new Error("fallback could not decode fixture"); + }), + ).toBeNull(); + expect(inputs).toEqual([log, log]); +}); diff --git a/tests/token-database.schema.test.ts b/tests/token-database.schema.test.ts index ad15c70e..d8637ccd 100644 --- a/tests/token-database.schema.test.ts +++ b/tests/token-database.schema.test.ts @@ -86,6 +86,44 @@ describe("TokenDatabase known_tokens schema upgrade", () => { errorSpy.mockRestore(); } }); + + test("does not attempt a migration when the token program column already exists", () => { + withRawDatabase((raw) => { + raw.run(`CREATE TABLE known_tokens ( + token_mint TEXT PRIMARY KEY, + token_ticker TEXT NOT NULL, + decimals INTEGER NOT NULL, + added_at INTEGER NOT NULL, + token_program_id TEXT + )`); + raw.run("INSERT INTO known_tokens VALUES ('present-mint', 'OLD', 6, 1, 'saved-program')"); + }); + const errors = spyOn(console, "error").mockImplementation(() => {}); + try { + const db = TokenDatabase.getInstance(); + expect(db.getKnownTokenByMint("present-mint")?.token_program_id).toBe("saved-program"); + expect(errors).not.toHaveBeenCalled(); + } finally { + errors.mockRestore(); + } + }); + + test("identifies a failure while reading the known tokens schema", () => { + withRawDatabase((raw) => { + raw.run("CREATE VIEW known_tokens AS SELECT * FROM missing_imported_tokens"); + }); + const errors = spyOn(console, "error").mockImplementation(() => {}); + try { + expect(() => TokenDatabase.getInstance()).not.toThrow(); + expect(errors.mock.calls).toEqual([ + ["[Token DB] Error during reading known_tokens schema:", expect.any(Error)], + ["Failed to ensure known_tokens schema:", expect.any(Error)], + ]); + expect(errors.mock.calls[0]?.[1]).toBe(errors.mock.calls[1]?.[1]); + } finally { + errors.mockRestore(); + } + }); }); test("a token added with a program keeps it through a lookup, ordered list and count", () => { From 78c1a2156be7d5f0a81515981eccac5bc2a5860b Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 17:58:25 -0300 Subject: [PATCH 148/410] test(rpc): pin the read deadline and subscription ownership --- tests/rpc-endpoints.error-paths.test.ts | 19 ++++++++++- tests/rpc-endpoints.test.ts | 42 +++++++++++++++++++++++++ 2 files changed, 60 insertions(+), 1 deletion(-) diff --git a/tests/rpc-endpoints.error-paths.test.ts b/tests/rpc-endpoints.error-paths.test.ts index de43afe5..fb449bbf 100644 --- a/tests/rpc-endpoints.error-paths.test.ts +++ b/tests/rpc-endpoints.error-paths.test.ts @@ -1,4 +1,4 @@ -import { describe, expect, mock, test } from "bun:test"; +import { describe, expect, mock, spyOn, test } from "bun:test"; import type { Commitment, Connection } from "#solana"; import { DEFAULT_MAINNET_ENDPOINT, @@ -168,6 +168,23 @@ describe("RpcEndpointManager call handling", () => { ]); }); + test("does not start a read at the exact deadline", async () => { + const getSlot = mock(async () => 7n); + const manager = new RpcEndpointManager(["https://rpc-only"], { + readTimeoutMs: 0, + connectionFactory: () => asConnection({ getSlot }), + }); + const now = spyOn(Date, "now").mockReturnValue(10_000); + try { + await expect(manager.getConnection().getSlot()).rejects.toThrow( + "RPC invocation failed without specific error", + ); + expect(getSlot).not.toHaveBeenCalled(); + } finally { + now.mockRestore(); + } + }); + test("rethrows a non-retryable error raised while verifying the fallback provider", async () => { const fatal = new Error("invalid genesis response"); const manager = new RpcEndpointManager(["https://rpc-only"], { diff --git a/tests/rpc-endpoints.test.ts b/tests/rpc-endpoints.test.ts index 28658da9..3e1d35ac 100644 --- a/tests/rpc-endpoints.test.ts +++ b/tests/rpc-endpoints.test.ts @@ -343,3 +343,45 @@ test("subscription removals retain their owner while new listeners follow HTTP f [endpoints[1], id], ]); }); + +test("a failed subscription removal keeps the original owner for the retry", async () => { + const removals: Array<[string, number]> = []; + const failure = new Error("connection has not closed the subscription"); + let attempt = 0; + const primary = "https://rpc-primary"; + const secondary = "https://rpc-secondary"; + const manager = new RpcEndpointManager([primary, secondary], { + connectionFactory: (endpoint, commitment) => + Object.assign(new FakeConnection(endpoint, commitment, endpoint === primary), { + onLogs: () => 31, + async removeOnLogsListener(id: number) { + removals.push([endpoint, id]); + if (++attempt === 1) throw failure; + }, + }) as unknown as Connection, + }); + const connection = manager.getConnection(); + const subscription = connection.onLogs("all", () => {}); + await connection.getSlot(); + expect(manager.getActiveEndpoint()).toBe(secondary); + await expect(connection.removeOnLogsListener(subscription)).rejects.toBe(failure); + await connection.removeOnLogsListener(subscription); + expect(removals).toEqual([ + [primary, 31], + [primary, 31], + ]); +}); + +test("an underlying listener without a numeric ID does not consume a proxy ID", () => { + const endpoint = "https://rpc-primary"; + let requests = 0; + const manager = new RpcEndpointManager([endpoint], { + connectionFactory: (_endpoint, commitment) => + Object.assign(new FakeConnection(endpoint, commitment, false), { + onLogs: () => (++requests === 1 ? undefined : 31), + }) as unknown as Connection, + }); + const connection = manager.getConnection(); + expect(connection.onLogs("all", () => {})).toBeUndefined(); + expect(connection.onLogs("all", () => {})).toBe(1); +}); From c1607a96c6f7484f247dfbfb1ea22d1e1e4e28d0 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 17:58:41 -0300 Subject: [PATCH 149/410] test(games): verify SQLite rollback and stale creation guards --- tests/game-database.pending-creation.test.ts | 32 +++++++++++ tests/game-database.queries.test.ts | 58 ++++++++++++++++++++ 2 files changed, 90 insertions(+) diff --git a/tests/game-database.pending-creation.test.ts b/tests/game-database.pending-creation.test.ts index d9bcfc5e..35a5b1ee 100644 --- a/tests/game-database.pending-creation.test.ts +++ b/tests/game-database.pending-creation.test.ts @@ -281,6 +281,38 @@ describe("GameDatabase pending game creation lifecycle", () => { ); expect(db.getPendingGameCreation("PENDING_1")?.state).toBe("failed"); }); + + test("treats a stale snapshot as a no-op even when another worker started submission", () => { + db.savePendingGameCreation({ ...pendingInput(), state: "prepared" }); + expect(db.claimPendingGameCreationSubmission("PENDING_1", "owner", NOW + 1_000, NOW)).toEqual( + { acquired: true }, + ); + expect( + db.failPreparedGameCreationIfCurrent("PENDING_1", "stale prepared row", NOW + 2_000), + ).toBe(false); + expect(db.clearPendingGameCreationIfState("PENDING_1", ["failed"])).toBe(false); + expect( + db.setPendingGameCreationStateIfCurrent("PENDING_1", [], "failed", { now: NOW + 2_000 }), + ).toBe(false); + expect(db.clearPendingGameCreationIfState("PENDING_1", [])).toBe(false); + expect(db.getPendingGameCreation("PENDING_1")).toMatchObject({ + state: "submitted", + submission_lease_id: "owner", + submission_lease_expires_at: NOW + 1_000, + transaction_signature: "SIG_ONE", + last_error: null, + }); + expect( + db.setPendingGameCreationStateIfCurrent("PENDING_1", ["prepared", "submitted"], "failed", { + now: NOW + 1_000, + expectedSignature: "SIG_ONE", + clearSubmissionLease: true, + error: "confirmed failure", + }), + ).toBe(true); + expect(db.clearPendingGameCreationIfState("PENDING_1", ["failed"])).toBe(true); + expect(db.getPendingGameCreation("PENDING_1")).toBeNull(); + }); }); describe("replacing a proven-absent game transaction", () => { diff --git a/tests/game-database.queries.test.ts b/tests/game-database.queries.test.ts index b2033877..79437003 100644 --- a/tests/game-database.queries.test.ts +++ b/tests/game-database.queries.test.ts @@ -76,6 +76,64 @@ describe("GameDatabase query edge cases", () => { } }); + test("keeps membership at the exact age boundary and samples a batch clock only once", () => { + const now = 2_000_000; + const clock = spyOn(Date, "now").mockReturnValue(now); + try { + db.saveMembershipCacheBatch(-99, [ + { telegramId: "present", isMember: true }, + { telegramId: "absent", isMember: false }, + ]); + expect(clock).toHaveBeenCalledTimes(1); + clock.mockReturnValue(now + 30 * 60 * 1000); + expect(db.getCachedMembership(-99, "present")).toBe(true); + expect(db.getCachedMemberships(-99, ["absent", "present", "missing"])).toEqual( + new Map([ + ["present", true], + ["absent", false], + ]), + ); + expect(db.getCachedMemberships(-100, ["present"]).size).toBe(0); + clock.mockReturnValue(now + 30 * 60 * 1000 + 1); + expect(db.getCachedMembership(-99, "present")).toBeNull(); + expect(db.getCachedMemberships(-99, ["absent", "present"]).size).toBe(0); + } finally { + clock.mockRestore(); + } + }); + + test("rolls back earlier membership writes if a later row fails", () => { + db.saveMembershipCache(-99, "kept", false); + raw.exec(`CREATE TRIGGER reject_membership_fixture BEFORE INSERT ON chat_membership_cache + WHEN NEW.telegram_id = 'rejected' + BEGIN SELECT RAISE(ABORT, 'fixture write rejected'); END`); + expect(() => + db.saveMembershipCacheBatch(-99, [ + { telegramId: "kept", isMember: true }, + { telegramId: "new", isMember: true }, + { telegramId: "rejected", isMember: true }, + ]), + ).not.toThrow(); + expect(db.getCachedMemberships(-99, ["kept", "new", "rejected"])).toEqual( + new Map([["kept", false]]), + ); + expect(errorSpy.mock.calls).toEqual([ + ["[Game DB] Error during saving membership cache:", expect.any(Error)], + ["Error saving membership cache:", expect.any(Error)], + ]); + }); + + test("does not query the database for an empty list of membership IDs", () => { + raw.exec("DROP TABLE chat_membership_cache"); + expect(db.getCachedMemberships(55, []).size).toBe(0); + expect(errorSpy.mock.calls).toEqual([]); + expect(db.getCachedMemberships(55, ["unknown"]).size).toBe(0); + expect(errorSpy.mock.calls).toEqual([ + ["[Game DB] Error during getting cached memberships:", expect.any(Error)], + ["Error getting cached memberships:", expect.any(Error)], + ]); + }); + describe("participant address bookkeeping", () => { test("an unknown game or a new game has no participant addresses", () => { expect(db.getGameParticipantAddresses("UNKNOWN")).toEqual([]); From 6e813fa0cff1dbe8dfa7cddefc4b5265caed5e7f Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 18:02:10 -0300 Subject: [PATCH 150/410] fix(games): preserve finite completion timestamps --- src/utils/game-database.ts | 5 +++-- tests/game-database.queries.test.ts | 26 ++++++++++++++++++++++++++ 2 files changed, 29 insertions(+), 2 deletions(-) diff --git a/src/utils/game-database.ts b/src/utils/game-database.ts index eff367f7..ca84554a 100644 --- a/src/utils/game-database.ts +++ b/src/utils/game-database.ts @@ -501,8 +501,9 @@ export class GameDatabase extends BaseDatabase { completedAt?: number, totalPot?: number, ): void { - const timestamp = completedAt || Date.now(); - const params: any[] = [winnerAddress, timestamp, "completed"]; + const timestamp = + typeof completedAt === "number" && Number.isFinite(completedAt) ? completedAt : Date.now(); + const params: Array = [winnerAddress, timestamp, "completed"]; let sql = "UPDATE games SET winner_address = ?, completed_at = ?, status = ?"; if (totalPot !== undefined) { diff --git a/tests/game-database.queries.test.ts b/tests/game-database.queries.test.ts index 79437003..79d0984e 100644 --- a/tests/game-database.queries.test.ts +++ b/tests/game-database.queries.test.ts @@ -76,6 +76,32 @@ describe("GameDatabase query edge cases", () => { } }); + test.each([ + ["zero", 0, 0], + ["known", 123, 123], + ["pre-epoch", -1, -1], + ["unknown", undefined, 7_000], + ["NaN", Number.NaN, 7_000], + ["infinite", Number.POSITIVE_INFINITY, 7_000], + ] as const)( + "records the %s explicit completion timestamp and zero pot", + (_label, time, expected) => { + const clock = spyOn(Date, "now").mockReturnValue(7_000); + try { + db.saveGame("DONE", "1", 5, "coinflip"); + db.completeGame("DONE", "winner", time, 0); + expect(db.getGame("DONE")).toMatchObject({ + status: "completed", + winner_address: "winner", + completed_at: expected, + total_amount: 0, + }); + } finally { + clock.mockRestore(); + } + }, + ); + test("keeps membership at the exact age boundary and samples a batch clock only once", () => { const now = 2_000_000; const clock = spyOn(Date, "now").mockReturnValue(now); From 411bd7f3c212efcc06856dba7a8b5d6f3633d7ea Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 18:05:03 -0300 Subject: [PATCH 151/410] fix(callbacks): keep malformed provider errors from blocking replies --- src/types/index.ts | 2 +- src/utils/context-helpers.ts | 13 +++++++++---- src/utils/errors/formatter.ts | 6 +++++- src/utils/errors/parser.ts | 12 ++++++++++++ tests/context-helpers.edge.test.ts | 25 +++++++++++++++++++++++++ 5 files changed, 52 insertions(+), 6 deletions(-) diff --git a/src/types/index.ts b/src/types/index.ts index 06eeaabe..3f45b9f1 100644 --- a/src/types/index.ts +++ b/src/types/index.ts @@ -251,7 +251,7 @@ export type PlayerEvent = PlayerJoinedEvent | PlayerRefundedEvent; export interface CallbackError { message?: string; - code?: string; + code?: string | number; isAccountNotFound?: boolean; } diff --git a/src/utils/context-helpers.ts b/src/utils/context-helpers.ts index a7d052e9..93a2b7e4 100644 --- a/src/utils/context-helpers.ts +++ b/src/utils/context-helpers.ts @@ -2,6 +2,7 @@ import type { Context } from "grammy"; import type { EphemeralMessageParameters } from "grammy/types"; import type { CallbackError, ErrorHandlingOptions } from "../types"; import { formatUserFriendlyError, truncateMessage } from "./errors"; +import { stringifyUnknownError } from "./errors/parser"; import { isMissingAccountError } from "./account-errors"; import { getErrorDescription, isBotNotAdmin, isRequestRefused } from "./telegram-errors"; import { @@ -200,12 +201,16 @@ export const createMessageEditAdapter = ( /** * Categorizes errors for better handling */ -export const categorizeError = (error: any): CallbackError => { - const errorMessage = error?.message || error?.toString() || "Unknown error"; +export const categorizeError = (error: unknown): CallbackError => { + const details = error as { message?: unknown; code?: unknown } | null | undefined; + const message = details?.message; + const errorMessage = + typeof message === "string" && message.length > 0 ? message : stringifyUnknownError(error); + const code = details?.code; return { message: errorMessage, - code: error?.code, + code: typeof code === "number" || typeof code === "string" ? code : undefined, isAccountNotFound: isMissingAccountError(error) || errorMessage.includes("could not find account"), }; @@ -554,7 +559,7 @@ export const resolveTelegramIdOrRespond = async ( */ export const handleCallbackErrorSafe = async ( ctx: any, - error: any, + error: unknown, action: string, options: ErrorHandlingOptions = {}, ): Promise => { diff --git a/src/utils/errors/formatter.ts b/src/utils/errors/formatter.ts index 69d784be..32a3d5bc 100644 --- a/src/utils/errors/formatter.ts +++ b/src/utils/errors/formatter.ts @@ -13,6 +13,7 @@ import { isTransactionTimeoutError, isTransactionExpiredError, extractSignature, + stringifyUnknownError, } from "./parser"; const RENT_INSUFFICIENT_FUNDS_PATTERNS = ["insufficient funds for rent", "rent-exempt"]; @@ -244,7 +245,10 @@ export const parseTransactionError = async ( walletManager?: WalletManager, connection?: Connection, ): Promise => { - const errorMessage = error instanceof Error ? error.message : String(error); + const errorMessage = + error instanceof Error && typeof error.message === "string" + ? error.message + : stringifyUnknownError(error); const lowerMessage = errorMessage.toLowerCase(); // Handle transaction timeout errors diff --git a/src/utils/errors/parser.ts b/src/utils/errors/parser.ts index 5d1bc4dc..be200445 100644 --- a/src/utils/errors/parser.ts +++ b/src/utils/errors/parser.ts @@ -20,6 +20,18 @@ const TRANSACTION_EXPIRED_PATTERNS = [ // This also matches the "Check signature" form. const SIGNATURE_PATTERNS = [/signature ([A-Za-z0-9]{44,})/, /\b([A-Za-z0-9]{80,88})\b/]; +export const stringifyUnknownError = (error: unknown): string => { + try { + if (error != null) { + const message = String(error); + if (message) return message; + } + } catch { + // Providers can throw objects without a usable string representation. + } + return "Unknown error"; +}; + export const extractLamportsInfo = ( errorMessage: string, ): { current: number; needed: number } | null => { diff --git a/tests/context-helpers.edge.test.ts b/tests/context-helpers.edge.test.ts index 231fb34d..a30c9d00 100644 --- a/tests/context-helpers.edge.test.ts +++ b/tests/context-helpers.edge.test.ts @@ -8,6 +8,7 @@ import { getRequiredTelegramIdForContext, getTelegramId, getTelegramIdString, + handleCallbackErrorSafe, requireTelegramId, resolveTelegramIdOrRespond, safeAnswerCallbackQuery, @@ -226,8 +227,32 @@ test("categorizes a missing error or an error supplied as a string", () => { code: undefined, isAccountNotFound: true, }); + expect(categorizeError("")).toEqual({ + message: "Unknown error", + code: undefined, + isAccountNotFound: false, + }); }); +test.each([ + ["structured message", { message: { detail: "unavailable" }, code: 503 }, "[object Object]", 503], + ["null prototype", Object.create(null), "Unknown error", undefined], + ["non-callable toString", { toString: 42 }, "Unknown error", undefined], + ["malformed Error message", Object.assign(new Error(), { message: 42 }), "Error: 42", undefined], +] as const)( + "still answers the callback when the error has a %s", + async (_label, error, message, code) => { + expect(categorizeError(error)).toEqual({ message, code, isAccountNotFound: false }); + const answerCallbackQuery = mock(async (_text: string) => {}); + await handleCallbackErrorSafe({ answerCallbackQuery }, error, "test action"); + expect(answerCallbackQuery.mock.calls).toEqual([ + [ + "❌ Something went wrong\nThat didn't go through. Try again in a moment, or ask an admin if it keeps happening.", + ], + ]); + }, +); + describe("createMessageEditAdapter", () => { test("requires a chat id", () => { expect(() => createMessageEditAdapter({ api: {} } as any, 1)).toThrow( From 3e94f90300b32d437cc9d8cd0696432e862ea6ee Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 18:05:35 -0300 Subject: [PATCH 152/410] fix(keyboards): use layouts only for known game types --- src/utils/keyboards.ts | 28 ++++++++----- tests/keyboards.fallbacks.test.ts | 69 ++++++++++++++++++++++++++++--- 2 files changed, 81 insertions(+), 16 deletions(-) diff --git a/src/utils/keyboards.ts b/src/utils/keyboards.ts index 436da98e..a1456018 100644 --- a/src/utils/keyboards.ts +++ b/src/utils/keyboards.ts @@ -370,18 +370,24 @@ export const createAmountSelectionKeyboard = ( return result; }; -const PLAYER_SELECTION_LAYOUTS: Record = { - coinflip: [ - [2, 3, 4], - [5, 10, 15], - [20, 25, 50], +const PLAYER_SELECTION_LAYOUTS = new Map([ + [ + "coinflip", + [ + [2, 3, 4], + [5, 10, 15], + [20, 25, 50], + ], ], - giveaway: [ - [1, 2, 3], - [5, 10, 15], - [20, 25, 50], + [ + "giveaway", + [ + [1, 2, 3], + [5, 10, 15], + [20, 25, 50], + ], ], -}; +]); export const createPlayerSelectionKeyboard = ( gameType: string, @@ -391,7 +397,7 @@ export const createPlayerSelectionKeyboard = ( const keyboard = new InlineKeyboard(); const typedGameType = gameType as GameType; const { guard, hasOverflow } = createCallbackGuard(); - const layout = PLAYER_SELECTION_LAYOUTS[gameType] ?? []; + const layout = PLAYER_SELECTION_LAYOUTS.get(gameType) ?? []; for (const row of layout) { for (const count of row) { diff --git a/tests/keyboards.fallbacks.test.ts b/tests/keyboards.fallbacks.test.ts index d25ad0bb..3038c3bf 100644 --- a/tests/keyboards.fallbacks.test.ts +++ b/tests/keyboards.fallbacks.test.ts @@ -23,6 +23,29 @@ describe("getFeeWarningMessage game type fallback", () => { test("capitalizes a regular game type", () => { expect(getFeeWarningMessage("giveaway", 100, 20)).toContain("Select Amount - Giveaway"); }); + + test.each([ + [ + 19.5, + undefined, + "⚠️ Low Balance Warning\nYour balance: 20 TEST\nContract minimum: 20 TEST\n\nOracle fees (~5-10%) will reduce winnings significantly with small bets.\n\n", + ], + [ + 19.5, + false, + "⚠️ Low Balance Warning\nContract minimum: 20 TEST\n\nOracle fees (~5-10%) can impact small bets.\n\n", + ], + [20, true, ""], + [20, false, ""], + [21, undefined, ""], + ] as const)( + "writes exact warning text for balance %f (show balance %j)", + (balance, includeBalanceInfo, warning) => { + expect(getFeeWarningMessage("coinflip", balance, 20, "TEST", { includeBalanceInfo })).toBe( + `💰 Select Amount - Coinflip\n\n${warning}Choose how much you want to play with:`, + ); + }, + ); }); describe("createGameConfirmKeyboard without a creator", () => { @@ -94,10 +117,46 @@ describe("createGameConfirmKeyboard visibility lock", () => { }); describe("createPlayerSelectionKeyboard layout lookup", () => { - test("renders only the back row for an unknown game type", () => { - const kb = createPlayerSelectionKeyboard("roulette", "10"); - const all = buttons(kb); - expect(all.some((b) => b.text.startsWith("👥"))).toBe(false); - expect(all.length).toBeGreaterThan(0); + test.each(["roulette", "constructor", "toString", "__proto__"])( + "uses the generic controls when %s has no layout", + (gameType) => { + expect(buttons(createPlayerSelectionKeyboard(gameType, "10"))).toEqual([ + { text: "📊 Custom Players", callback_data: `custom_players_${gameType}_10` }, + { text: "← Back to Amount", callback_data: `back_to_amounts_${gameType}` }, + ]); + }, + ); + + test.each([ + [ + "coinflip", + [ + [2, 3, 4], + [5, 10, 15], + [20, 25, 50], + ], + ], + [ + "giveaway", + [ + [1, 2, 3], + [5, 10, 15], + [20, 25, 50], + ], + ], + ] as const)("keeps the exact %s player counts and callback rows", (gameType, counts) => { + const grid = createPlayerSelectionKeyboard(gameType, "10").inline_keyboard; + expect(grid.slice(0, 3)).toEqual( + counts.map((row) => + row.map((count) => ({ + text: `👥 ${count}`, + callback_data: `players_${gameType}_10_${count}`, + })), + ), + ); + expect(grid.slice(3).flat()).toEqual([ + { text: "📊 Custom Players", callback_data: `custom_players_${gameType}_10` }, + { text: "← Back to Amount", callback_data: `back_to_amounts_${gameType}` }, + ]); }); }); From 39658ea4a719a9848d337e63f02b8b3685f94157 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 18:08:54 -0300 Subject: [PATCH 153/410] fix(finance): leave invalid report valuations unpriced --- src/services/finance-report.ts | 29 ++++++------ tests/finance-report.test.ts | 87 ++++++++++++++++++++++++++++++++++ 2 files changed, 102 insertions(+), 14 deletions(-) diff --git a/src/services/finance-report.ts b/src/services/finance-report.ts index 239aee9e..5c5eb5b4 100644 --- a/src/services/finance-report.ts +++ b/src/services/finance-report.ts @@ -90,14 +90,22 @@ export function resolveFinanceWindow(period: FinancePeriod, now: number = Date.n const safeBigInt = (value: string | null | undefined): bigint => { try { - return BigInt(value ?? "0"); + return BigInt(value ?? 0n); } catch { return 0n; } }; -const decimalAmount = (rawAmount: bigint, decimals: number): number => - Number(rawAmount) / 10 ** decimals; +const priceRawAmount = ( + rawAmount: bigint, + decimals: number, + price: number | null, +): number | null => { + if (price === null || !Number.isFinite(price) || price < 0) return null; + if (price === 0) return 0; + const value = (Number(rawAmount) / 10 ** decimals) * price; + return Number.isFinite(value) ? value : null; +}; function aggregateEvents( events: FinanceEventRecord[], @@ -138,10 +146,7 @@ async function priceBalances( ticker: metadata?.ticker ?? mint, decimals, rawAmount: amountRaw, - usdValue: - price !== null && Number.isFinite(price) - ? decimalAmount(amountRaw, decimals) * price - : null, + usdValue: priceRawAmount(amountRaw, decimals, price), }; }), ); @@ -177,7 +182,7 @@ export async function buildFinanceReport( swapClaimed, gameClaimable, swapClaimable, - rawSolPrice, + solPrice, ] = await Promise.all([ priceBalances(aggregateEvents(events, "game_fee", "earned"), dependencies), priceBalances(aggregateEvents(events, "swap_fee", "earned"), dependencies), @@ -187,8 +192,6 @@ export async function buildFinanceReport( priceBalances(dependencies.swapClaimable, dependencies), dependencies.resolveTokenPriceUsd(WSOL_MINT), ]); - const solPrice = rawSolPrice !== null && Number.isFinite(rawSolPrice) ? rawSolPrice : null; - let sponsorCostLamports = 0n; let sponsorReimbursementLamports = 0n; let hasEstimatedSponsorExpenses = false; @@ -207,8 +210,7 @@ export async function buildFinanceReport( (event) => event.category === "game_fee" && event.kind === "earned", ); const collectionFeeLamports = uniqueNetworkFees(events, (event) => event.kind === "claimed"); - const lamportsToUsd = (lamports: bigint) => - solPrice === null ? 0 : decimalAmount(lamports, 9) * solPrice; + const lamportsToUsd = (lamports: bigint) => priceRawAmount(lamports, 9, solPrice) ?? 0; const completionNetworkExpensesUsd = lamportsToUsd(completionFeeLamports); const sponsorNetworkExpensesUsd = lamportsToUsd(unrecoveredSponsorLamports); const collectionNetworkExpensesUsd = lamportsToUsd(collectionFeeLamports); @@ -264,8 +266,7 @@ export async function buildFinanceReport( totalExpensesUsd, netProfitUsd: grossRevenueUsd - totalExpensesUsd, contractRentLamports: dependencies.contractRentLamports, - contractRentUsd: - solPrice === null ? null : decimalAmount(dependencies.contractRentLamports, 9) * solPrice, + contractRentUsd: priceRawAmount(dependencies.contractRentLamports, 9, solPrice), contractRentEstimated: dependencies.contractRentEstimated ?? false, monthlyExpenses: dependencies.monthlyExpenses, hasUnpricedTokens: allTokens.some((total) => total.usdValue === null), diff --git a/tests/finance-report.test.ts b/tests/finance-report.test.ts index b00813f0..0d810d3c 100644 --- a/tests/finance-report.test.ts +++ b/tests/finance-report.test.ts @@ -223,6 +223,49 @@ describe("finance report", () => { }, ); + test("marks non-finite token values as unpriced without dropping the raw amount", async () => { + const overflow = "overflow-mint"; + const zero = "zero-price-mint"; + const rawAmount = 10n ** 305n; + const report = await buildFinanceReport( + "30d", + reportInputs({ + financeEvents: [ + event({ mint: overflow, amountRaw: rawAmount.toString() }), + event({ mint: zero }), + ], + resolveTokenMetadata: async (mint) => ({ ticker: mint, decimals: 0 }), + resolveTokenPriceUsd: async (mint) => (mint === overflow ? 1e5 : -0), + }), + ); + expect( + report.gameRevenue.map(({ mint, rawAmount, usdValue }) => ({ mint, rawAmount, usdValue })), + ).toEqual([ + { mint: overflow, rawAmount, usdValue: null }, + { mint: zero, rawAmount: 1_000_000n, usdValue: 0 }, + ]); + expect(report.hasUnpricedTokens).toBe(true); + expect(report.gameRevenueUsd).toBe(0); + expect(report.netProfitUsd).toBe(0); + }); + + test("does not value revenue, expenses or contract rent with a negative rate", async () => { + const report = await buildFinanceReport( + "30d", + reportInputs({ + financeEvents: [event({})], + contractRentLamports: 2_000_000_000n, + resolveTokenPriceUsd: async () => -1, + }), + ); + expect(report.gameRevenue[0]?.usdValue).toBeNull(); + expect(report.hasUnpricedTokens).toBe(true); + expect(report.completedGames).toBe(1); + expect(report.contractRentUsd).toBeNull(); + expect(report.completionNetworkExpensesUsd).toBe(0); + expect(report.netProfitUsd).toBe(0); + }); + test("separates earned, claimed, and currently claimable fees", async () => { const report = await buildFinanceReport("30d", { now: NOW, @@ -335,6 +378,50 @@ describe("finance report", () => { expect(report.sponsorNetworkExpensesUsd).toBeCloseTo(0.0005); expect(report.totalExpensesUsd).toBeCloseTo(0.0005); }); + + test.each([ + ["partial", "600000000", "100000000", 40], + ["exact", "600000000", "500000000", 0], + ["excess", "600000000", "600000000", 0], + ] as const)( + "keeps the expected expense and estimate for %s reimbursement", + async (_label, cost, reimbursement, expected) => { + const swap = { + feeMint: USDC, + inputMint: USDC, + outputMint: TIMBA, + amountIn: "1000000", + amountOut: "1000000", + feeAmount: "10000", + feeBps: 100, + }; + const report = await buildFinanceReport( + "30d", + reportInputs({ + financeEvents: [event({ networkFeeLamports: "200000000" })], + sponsorRecords: [ + { + ...swap, + sponsorCostLamports: cost, + sponsorReimbursementLamports: reimbursement, + sponsorCostEstimated: 1, + }, + { + ...swap, + sponsorCostLamports: "100000000", + sponsorReimbursementLamports: "200000000", + sponsorCostEstimated: 0, + }, + ], + }), + ); + expect(report.hasEstimatedSponsorExpenses).toBe(true); + expect(report.hasUnpricedTokens).toBe(false); + expect(report.completionNetworkExpensesUsd).toBe(20); + expect(report.sponsorNetworkExpensesUsd).toBe(expected); + expect(report.networkExpensesUsd).toBe(expected + 20); + }, + ); }); describe("finance authorization", () => { From 511fce944a084a2876512a1d4a0a8bed7ea4370a Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 18:10:24 -0300 Subject: [PATCH 154/410] refactor(games): share expiry filters and use SQLite change counts --- src/utils/game-database.ts | 21 +++------ tests/game-database.queries.test.ts | 68 +++++++++++++++++++++++++++++ 2 files changed, 73 insertions(+), 16 deletions(-) diff --git a/src/utils/game-database.ts b/src/utils/game-database.ts index ca84554a..a1f0ebf5 100644 --- a/src/utils/game-database.ts +++ b/src/utils/game-database.ts @@ -633,8 +633,8 @@ export class GameDatabase extends BaseDatabase { "deleting old games", ); return { - participantsDeleted: participantsResult?.changes ?? 0, - gamesDeleted: gamesResult?.changes ?? 0, + participantsDeleted: participantsResult.changes, + gamesDeleted: gamesResult.changes, }; }); @@ -659,12 +659,9 @@ export class GameDatabase extends BaseDatabase { ? `AND game_address NOT IN (${excludeAddresses.map(() => "?").join(",")})` : ""; - const expiringParams = excludeAddresses.length - ? [cutoffMs, ...excludeAddresses, limit] - : [cutoffMs, limit]; const expiring = this.all( `SELECT * FROM games WHERE ${expireClause} ${excludeClause} ORDER BY expires_at ASC LIMIT ?`, - expiringParams, + [cutoffMs, ...excludeAddresses, limit], "getting expiring games", ); @@ -674,17 +671,9 @@ export class GameDatabase extends BaseDatabase { const remainingLimit = limit - expiring.length; - const fallbackExcludeClause = excludeAddresses.length - ? `AND game_address NOT IN (${excludeAddresses.map(() => "?").join(",")})` - : ""; - - const fallbackParams = excludeAddresses.length - ? [...excludeAddresses, remainingLimit] - : [remainingLimit]; - const fallback = this.all( - `SELECT * FROM games WHERE status != 'completed' AND expires_at IS NULL ${fallbackExcludeClause} ORDER BY created_at ASC LIMIT ?`, - fallbackParams, + `SELECT * FROM games WHERE status != 'completed' AND expires_at IS NULL ${excludeClause} ORDER BY created_at ASC LIMIT ?`, + [...excludeAddresses, remainingLimit], "getting games missing expiration", ); diff --git a/tests/game-database.queries.test.ts b/tests/game-database.queries.test.ts index 79d0984e..d3254748 100644 --- a/tests/game-database.queries.test.ts +++ b/tests/game-database.queries.test.ts @@ -160,6 +160,74 @@ describe("GameDatabase query edge cases", () => { ]); }); + test("uses the same exclusions for expiring and undated games", () => { + const save = (address: string, created: number, expires?: number) => { + db.saveGame( + address, + "1", + 5, + "coinflip", + undefined, + undefined, + 2, + 2, + -99, + undefined, + expires, + created, + ); + }; + save("excluded-expiring", 0, 5); + save("excluded-undated", 0); + save("at-cutoff", 1, 10); + save("later", 2, 11); + save("undated-newer", 5); + save("undated-older", 3); + save("old-but-completed", 0, 5); + db.completeGame("old-but-completed", "winner", 7); + const ids = (rows: ReturnType) => + rows.map(({ game_address }) => game_address); + expect(ids(db.getGamesExpiringBefore(10, 0))).toEqual([]); + expect(ids(db.getGamesExpiringBefore(10, 1))).toEqual(["excluded-expiring"]); + expect( + ids( + db.getGamesExpiringBefore(10, 2, [ + "excluded-expiring", + "excluded-undated", + "excluded-expiring", + ]), + ), + ).toEqual(["at-cutoff", "undated-older"]); + }); + + test("cleanup reports zero changes and keeps rows at the exact cutoff", () => { + const clock = spyOn(Date, "now").mockReturnValue(30 * 86_400_000); + try { + db.saveGame( + "KEEP", + "1", + 5, + "coinflip", + undefined, + undefined, + 2, + 2, + 1, + undefined, + undefined, + 0, + ); + db.saveGameParticipant("KEEP", "1", "player"); + logSpy.mockClear(); + expect(db.cleanupOldGames()).toEqual({ gamesDeleted: 0, participantsDeleted: 0 }); + expect(db.getGame("KEEP")?.created_at).toBe(0); + expect(db.getGameParticipants("KEEP")).toEqual(["1"]); + expect(logSpy.mock.calls).toEqual([]); + } finally { + clock.mockRestore(); + } + }); + describe("participant address bookkeeping", () => { test("an unknown game or a new game has no participant addresses", () => { expect(db.getGameParticipantAddresses("UNKNOWN")).toEqual([]); From 9a87e94119927cf1ee286df635b8b18c42b14c9f Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 18:14:50 -0300 Subject: [PATCH 155/410] fix(format): preserve inferred precision for small token amounts --- src/utils/format-amount.ts | 5 ++--- tests/format-amount.test.ts | 7 +++++-- 2 files changed, 7 insertions(+), 5 deletions(-) diff --git a/src/utils/format-amount.ts b/src/utils/format-amount.ts index 208630a4..d4bee402 100644 --- a/src/utils/format-amount.ts +++ b/src/utils/format-amount.ts @@ -103,9 +103,8 @@ export function formatTokenDisplay(value: number, options: FormatTokenDisplayOpt if (Number.isFinite(decimals)) { precision = Math.max(0, Math.min(Math.trunc(decimals), 6)); } else { - const decimal = value.toString(); - // A negative exponent here means more fractional places than we can display. - precision = decimal.includes("e-") ? 6 : Math.min(decimal.split(".")[1]?.length ?? 0, 6); + const [, fractional = ""] = value.toString().split("."); + precision = Math.min(fractional.replace(/0+$/, "").length, 6); } const maximumFractionDigits = precision; diff --git a/tests/format-amount.test.ts b/tests/format-amount.test.ts index 70dbe413..e741bc59 100644 --- a/tests/format-amount.test.ts +++ b/tests/format-amount.test.ts @@ -210,8 +210,11 @@ test.each<[number, number | undefined, string]>([ [1.002, undefined, "1.002"], [1.002, Number.POSITIVE_INFINITY, "1.002"], [1.002, 0, "1"], - [1e-7, undefined, "0.000000"], - [-1.2e-10, undefined, "-0.000000"], + [1e-7, undefined, "0"], + [5e-7, undefined, "0"], + [5e-7, Number.NaN, "0"], + [5e-7, 6, "0.000001"], + [-1.2e-10, undefined, "-0.0000"], ])("formatTokenDisplay(%p) with %p decimals is %s", (value, decimals, expected) => { expect(formatTokenDisplay(value, decimals === undefined ? {} : { decimals })).toBe(expected); }); From f5e1a6b6b9e6b3b45401a3c344db501189db29de Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 18:25:20 -0300 Subject: [PATCH 156/410] fix(games): bind setup state to the delivered Telegram prompt --- src/handlers/game-callbacks.ts | 207 +++++------- src/handlers/game-callbacks/ui-builders.ts | 2 +- src/handlers/game-setup.ts | 2 +- tests/game-callbacks.module.test.ts | 17 +- tests/game-callbacks.prompt-target.test.ts | 347 +++++++++++++++++++++ 5 files changed, 445 insertions(+), 130 deletions(-) create mode 100644 tests/game-callbacks.prompt-target.test.ts diff --git a/src/handlers/game-callbacks.ts b/src/handlers/game-callbacks.ts index 893073d8..8d0bb120 100644 --- a/src/handlers/game-callbacks.ts +++ b/src/handlers/game-callbacks.ts @@ -45,7 +45,7 @@ import { restoreConfirmMessage, snapshotConfirmMessage, } from "./game-callbacks/confirm-restore"; -import { respondWithMenu } from "../utils/menu-response"; +import { respondWithMenu, type MenuResponseResult } from "../utils/menu-response"; import { getRequiredTelegramIdForContext, requireTelegramId, @@ -118,6 +118,28 @@ export type GameCallbacksModule = { export const JOIN_PENDING_TOAST = "⏳ Joining…"; const ALREADY_JOINED_TOAST = "You already joined this game."; +const storeSetupPromptSession = ( + ctx: Context, + creatorContext: CreatorCallbackContext, + response: MenuResponseResult, + updates: Partial, +): void => { + const originalChatId = ctx.chat?.id ?? 0; + const originalMessageId = ctx.callbackQuery?.message?.message_id ?? 0; + const chatId = response.chatId ?? originalChatId; + const messageId = response.messageId ?? originalMessageId; + if (chatId === originalChatId && messageId === originalMessageId) { + creatorContext.updateSession({ ...updates, chatId, messageId }); + return; + } + // The reply middleware identifies a setup by the message the user replies to. + creatorContext.updateSession( + { ...creatorContext.session, ...updates, chatId, messageId }, + `${chatId}_${messageId}`, + ); + creatorContext.clearSession(); +}; + /** * After the "Joining…" toast, a join result can no longer be shown as a toast. * Success is visible on the refreshed game card; anything else goes to the @@ -618,14 +640,33 @@ export const createGameCallbacksModule = (deps: GameCallbacksModuleDeps): GameCa } const sessionSnapshot = { ...userSession }; - const restoreSession = (overrides: Partial = {}) => { - upsertGameSetupSession(sessionKey, { - ...sessionSnapshot, - ...overrides, - }); - }; clearGameSetupSession(sessionKey); + const editOrReply = async ( + text: string, + options: { parse_mode: "HTML"; reply_markup?: InlineKeyboard }, + ) => { + const chatId = userSession.chatId ?? ctx.chat?.id ?? 0; + const messageId = userSession.messageId ?? replyToMessageId; + try { + await ctx.api.editMessageText(chatId, messageId, text, options); + return { chatId, messageId }; + } catch { + const sent = await ctx.reply(text, options); + return { chatId: sent?.chat?.id ?? chatId, messageId: sent?.message_id ?? messageId }; + } + }; + const saveAtPrompt = ( + target: { chatId: number; messageId: number }, + state: Partial, + ) => { + upsertGameSetupSession(`${target.chatId}_${target.messageId}`, { ...state, ...target }); + }; + const retryAtPrompt = async (text: string) => { + const target = await editOrReply(text, { parse_mode: "HTML" }); + saveAtPrompt(target, sessionSnapshot); + }; + const defaultMetadata = await deps.getDefaultTokenMetadata(); const tokenTicker = userSession.tokenTicker ?? DEFAULT_TOKEN_TICKER; const tokenDecimals = userSession.tokenDecimals ?? defaultMetadata.decimals; @@ -653,18 +694,9 @@ export const createGameCallbacksModule = (deps: GameCallbacksModuleDeps): GameCa ); if (players === null || players < minPlayers || players > maxPlayers) { - const errorMessage = `❌ Invalid number of players. Please enter a number between ${minPlayers} and ${maxPlayers}.`; - try { - await ctx.api.editMessageText( - userSession.chatId!, - userSession.messageId!, - errorMessage, - { parse_mode: "HTML" }, - ); - } catch (error) { - await ctx.reply(errorMessage, { parse_mode: "HTML" }); - } - restoreSession({ waitingFor: "players_input" }); + await retryAtPrompt( + `❌ Invalid number of players. Please enter a number between ${minPlayers} and ${maxPlayers}.`, + ); return; } @@ -704,23 +736,11 @@ export const createGameCallbacksModule = (deps: GameCallbacksModuleDeps): GameCa ui: ctx.chat?.type === "private" ? { lockVisibilityToPublic: true } : undefined, }); - try { - await ctx.api.editMessageText( - userSession.chatId!, - userSession.messageId!, - confirmMessage, - confirmMenu.replyMarkup, - ); - } catch (error) { - await ctx.reply(confirmMessage, confirmMenu.replyMarkup); - } - - upsertGameSetupSession(sessionKey, { + const target = await editOrReply(confirmMessage, confirmMenu.replyMarkup); + saveAtPrompt(target, { waitingFor: "setup", gameType: userSession.gameType, userBalance: userSession.userBalance, - messageId: userSession.messageId, - chatId: userSession.chatId, amount: userSession.amount, players, creatorId: userSession.creatorId, @@ -750,18 +770,7 @@ export const createGameCallbacksModule = (deps: GameCallbacksModuleDeps): GameCa if (isUsdInput) { if (digits > 18 || usdAmount! <= 0) { - const errorMessage = "❌ Invalid USD amount. Try something like $10."; - try { - await ctx.api.editMessageText( - userSession.chatId!, - userSession.messageId!, - errorMessage, - { parse_mode: "HTML" }, - ); - } catch (error) { - await ctx.reply(errorMessage, { parse_mode: "HTML" }); - } - restoreSession({ waitingFor: "amount_input" }); + await retryAtPrompt("❌ Invalid USD amount. Try something like $10."); return; } @@ -770,18 +779,9 @@ export const createGameCallbacksModule = (deps: GameCallbacksModuleDeps): GameCa }); if (tokenPriceUSD == null || !Number.isFinite(tokenPriceUSD) || tokenPriceUSD <= 0) { - const errorMessage = `❌ USD pricing unavailable for ${tokenTicker}. Please enter the amount in ${tokenTicker}.`; - try { - await ctx.api.editMessageText( - userSession.chatId!, - userSession.messageId!, - errorMessage, - { parse_mode: "HTML" }, - ); - } catch (error) { - await ctx.reply(errorMessage, { parse_mode: "HTML" }); - } - restoreSession({ waitingFor: "amount_input" }); + await retryAtPrompt( + `❌ USD pricing unavailable for ${tokenTicker}. Please enter the amount in ${tokenTicker}.`, + ); return; } @@ -800,41 +800,17 @@ export const createGameCallbacksModule = (deps: GameCallbacksModuleDeps): GameCa } if (Number.isNaN(resolvedAmount) || resolvedAmount <= 0) { - const errorMessage = "❌ Invalid amount. Please use /coinflip or /giveaway to try again."; - try { - await ctx.api.editMessageText(userSession.chatId!, userSession.messageId!, errorMessage, { - parse_mode: "HTML", - }); - } catch (error) { - await ctx.reply(errorMessage, { parse_mode: "HTML" }); - } - restoreSession({ waitingFor: "amount_input" }); + await retryAtPrompt("❌ Invalid amount. Please use /coinflip or /giveaway to try again."); return; } if (resolvedAmount > userSession.userBalance) { - const errorMessage = "❌ Amount too high. Please try a lower amount."; - try { - await ctx.api.editMessageText(userSession.chatId!, userSession.messageId!, errorMessage, { - parse_mode: "HTML", - }); - } catch (error) { - await ctx.reply(errorMessage, { parse_mode: "HTML" }); - } - restoreSession({ waitingFor: "amount_input" }); + await retryAtPrompt("❌ Amount too high. Please try a lower amount."); return; } if (resolvedAmount < minAllowed) { - const errorMessage = `❌ Amount below current minimum of ${minAllowed} ${tokenTicker}.`; - try { - await ctx.api.editMessageText(userSession.chatId!, userSession.messageId!, errorMessage, { - parse_mode: "HTML", - }); - } catch (error) { - await ctx.reply(errorMessage, { parse_mode: "HTML" }); - } - restoreSession({ waitingFor: "amount_input" }); + await retryAtPrompt(`❌ Amount below current minimum of ${minAllowed} ${tokenTicker}.`); return; } @@ -851,32 +827,18 @@ export const createGameCallbacksModule = (deps: GameCallbacksModuleDeps): GameCa usdApproximation, ); - try { - await ctx.api.editMessageText(userSession.chatId!, userSession.messageId!, playerMessage, { - parse_mode: "HTML", - reply_markup: createPlayerSelectionKeyboard( - userSession.gameType, - resolvedAmount.toString(), - userSession.creatorId, - ), - }); - } catch (error) { - await ctx.reply(playerMessage, { - parse_mode: "HTML", - reply_markup: createPlayerSelectionKeyboard( - userSession.gameType, - resolvedAmount.toString(), - userSession.creatorId, - ), - }); - } - - upsertGameSetupSession(sessionKey, { + const target = await editOrReply(playerMessage, { + parse_mode: "HTML", + reply_markup: createPlayerSelectionKeyboard( + userSession.gameType, + resolvedAmount.toString(), + userSession.creatorId, + ), + }); + saveAtPrompt(target, { waitingFor: "setup", gameType: userSession.gameType, userBalance: userSession.userBalance, - messageId: userSession.messageId, - chatId: userSession.chatId, amount: resolvedAmount.toString(), creatorId: userSession.creatorId, tokenMint: userSession.tokenMint, @@ -1779,7 +1741,8 @@ export const createGameCallbacksModule = (deps: GameCallbacksModuleDeps): GameCa resolveCreatorId: (ctx) => ctx.match?.[2], failureText: "❌ Only the game creator can modify this setup!", }, - async (ctx, { session, tokenContext, updateSession, creatorId }) => { + async (ctx, creatorContext) => { + const { session, tokenContext, creatorId } = creatorContext; try { const gameType = ctx.match![1] as "coinflip" | "giveaway"; // withCreatorSessionContext already refused callbacks without a sender id. @@ -1807,7 +1770,7 @@ export const createGameCallbacksModule = (deps: GameCallbacksModuleDeps): GameCa tokenContext.tokenDecimals, ); - await presentCustomAmountPrompt({ + const response = await presentCustomAmountPrompt({ ctx, gameType, tokenTicker: tokenContext.tokenTicker, @@ -1815,17 +1778,14 @@ export const createGameCallbacksModule = (deps: GameCallbacksModuleDeps): GameCa creatorId, }); - await safeAnswerCallbackQuery(ctx, "Type your amount..."); - - updateSession({ + storeSetupPromptSession(ctx, creatorContext, response, { waitingFor: "amount_input", gameType, userBalance, - messageId: ctx.callbackQuery?.message?.message_id || 0, - chatId: ctx.chat?.id || 0, contractMinimum: contractMin, amount: session?.amount, }); + await safeAnswerCallbackQuery(ctx, "Type your amount..."); } catch (error) { console.error("Error in creator-protected custom_amount callback:", error); await safeAnswerCallbackQuery(ctx, "❌ Error setting up text input"); @@ -1842,7 +1802,8 @@ export const createGameCallbacksModule = (deps: GameCallbacksModuleDeps): GameCa resolveCreatorId: (ctx) => ctx.match?.[3], failureText: "❌ Only the game creator can modify this setup!", }, - async (ctx, { session, tokenContext, updateSession, creatorId }) => { + async (ctx, creatorContext) => { + const { session, tokenContext, creatorId } = creatorContext; try { const gameType = ctx.match![1] as "coinflip" | "giveaway"; const amount = ctx.match![2] as string; @@ -1867,7 +1828,7 @@ export const createGameCallbacksModule = (deps: GameCallbacksModuleDeps): GameCa `Range: ${minPlayers}-${maxPlayers} players`, ].join("\n"); - await respondWithMenu(ctx, { + const response = await respondWithMenu(ctx, { text: playersMessage, parseMode: "HTML", keyboard: new InlineKeyboard() @@ -1875,15 +1836,11 @@ export const createGameCallbacksModule = (deps: GameCallbacksModuleDeps): GameCa .row(), }); - await safeAnswerCallbackQuery(ctx, "Type the number of players..."); - - updateSession({ + storeSetupPromptSession(ctx, creatorContext, response, { waitingFor: "players_input", gameType, userBalance: 0, amount, - messageId: ctx.callbackQuery?.message?.message_id || 0, - chatId: ctx.chat?.id || 0, contractMinimum: session?.contractMinimum, tokenMint: session?.tokenMint, tokenTicker: session?.tokenTicker, @@ -1892,6 +1849,7 @@ export const createGameCallbacksModule = (deps: GameCallbacksModuleDeps): GameCa timeoutSeconds: session?.timeoutSeconds ?? DEFAULT_GAME_TIMEOUT, isPrivate: session?.isPrivate ?? false, }); + await safeAnswerCallbackQuery(ctx, "Type the number of players..."); } catch (error) { console.error("Error in creator-protected custom_players callback:", error); await safeAnswerCallbackQuery(ctx, "❌ Error setting up players input"); @@ -1936,7 +1894,7 @@ export const createGameCallbacksModule = (deps: GameCallbacksModuleDeps): GameCa `Range: ${minPlayers}-${maxPlayers} players`, ].join("\n"); - await respondWithMenu(ctx, { + const response = await respondWithMenu(ctx, { text: playersMessage, parseMode: "HTML", keyboard: new InlineKeyboard() @@ -1944,9 +1902,7 @@ export const createGameCallbacksModule = (deps: GameCallbacksModuleDeps): GameCa .row(), }); - await safeAnswerCallbackQuery(ctx, "Type the number of players..."); - - creatorContext.updateSession({ + storeSetupPromptSession(ctx, creatorContext, response, { ...(creatorContext.session ?? {}), waitingFor: "players_input", gameType, @@ -1954,6 +1910,7 @@ export const createGameCallbacksModule = (deps: GameCallbacksModuleDeps): GameCa minPlayers, maxPlayersLimit: maxPlayers, }); + await safeAnswerCallbackQuery(ctx, "Type the number of players..."); }, ), ); diff --git a/src/handlers/game-callbacks/ui-builders.ts b/src/handlers/game-callbacks/ui-builders.ts index c34847be..7a7ede7b 100644 --- a/src/handlers/game-callbacks/ui-builders.ts +++ b/src/handlers/game-callbacks/ui-builders.ts @@ -216,7 +216,7 @@ export const presentCustomAmountPrompt = async (params: CustomAmountPromptParams `Min: ${contractMin} ${tokenTicker}`, ].join("\n"); - await respondWithMenu(ctx, { + return respondWithMenu(ctx, { text: groupMessage, parseMode: "HTML", keyboard, diff --git a/src/handlers/game-setup.ts b/src/handlers/game-setup.ts index 82484fa8..2cfa71a7 100644 --- a/src/handlers/game-setup.ts +++ b/src/handlers/game-setup.ts @@ -116,7 +116,7 @@ export type CreatorCallbackContext = { userId: number; session?: GameSetupSession; tokenContext: TokenContext; - updateSession: (updates: Partial) => GameSetupSession; + updateSession: (updates: Partial, keyOverride?: string) => GameSetupSession; clearSession: () => void; }; diff --git a/tests/game-callbacks.module.test.ts b/tests/game-callbacks.module.test.ts index f6dac9a1..f7ad2e1c 100644 --- a/tests/game-callbacks.module.test.ts +++ b/tests/game-callbacks.module.test.ts @@ -562,7 +562,12 @@ describe("typed game setup input", () => { expect(result.replies).toEqual([ "❌ Invalid number of players. Please enter a number between 2 and 50.", ]); - expect(getGameSetupSession(`${CHAT}_30`)?.waitingFor).toBe("players_input"); + expect(getGameSetupSession(`${CHAT}_30`)).toBeUndefined(); + expect(getGameSetupSession(`${CHAT}_41`)).toMatchObject({ + waitingFor: "players_input", + messageId: 41, + chatId: CHAT, + }); }); test("a valid player count shows the confirmation and uses the session price", async () => { @@ -572,8 +577,10 @@ describe("typed game setup input", () => { const result = await input(h, "4", { failEdits: true }); expect(result.replies[0]).toContain("Confirm Coinflip"); - expect(getGameSetupSession(`${CHAT}_30`)).toMatchObject({ + expect(getGameSetupSession(`${CHAT}_30`)).toBeUndefined(); + expect(getGameSetupSession(`${CHAT}_41`)).toMatchObject({ waitingFor: "setup", + messageId: 41, players: 4, tokenPriceUSD: 2, }); @@ -595,6 +602,8 @@ describe("typed game setup input", () => { const replied = await input(h, text, { failEdits: true }); expect(replied.replies.at(-1)).toBe(message); + expect(getGameSetupSession(`${CHAT}_30`)).toBeUndefined(); + expect(getGameSetupSession(`${CHAT}_41`)?.waitingFor).toBe("amount_input"); }); test("converts USD amounts with the live price and moves to player selection", async () => { @@ -604,8 +613,10 @@ describe("typed game setup input", () => { const result = await input(h, "10 usd", { failEdits: true }); expect(result.replies[0]).toContain("Amount: 20"); - expect(getGameSetupSession(`${CHAT}_30`)).toMatchObject({ + expect(getGameSetupSession(`${CHAT}_30`)).toBeUndefined(); + expect(getGameSetupSession(`${CHAT}_41`)).toMatchObject({ waitingFor: "setup", + messageId: 41, amount: "20", tokenPriceUSD: 0.5, }); diff --git a/tests/game-callbacks.prompt-target.test.ts b/tests/game-callbacks.prompt-target.test.ts new file mode 100644 index 00000000..520b53b3 --- /dev/null +++ b/tests/game-callbacks.prompt-target.test.ts @@ -0,0 +1,347 @@ +import { afterEach, beforeEach, expect, mock, spyOn, test } from "bun:test"; +import type { Bot, Context } from "grammy"; +import { createGameCallbacksModule } from "../src/handlers/game-callbacks"; +import { GAME_SETUP_COPY, createGameSetupModule } from "../src/handlers/game-setup"; +import { encodeCustomPlayersPayload } from "../src/utils/callback-data"; +import { + getTelegramId, + getTelegramIdString, + safeAnswerCallbackQuery, +} from "../src/utils/context-helpers"; +import { createAmountSelectionKeyboard, getSuggestedStakeAmounts } from "../src/utils/keyboards"; +import { + clearAllGameSetupSessions, + clearGameSetupSession, + getGameSetupSession, + upsertGameSetupSession, +} from "../src/utils/user-state"; + +const CHAT = -100; +const OLD = 5; +const SENT = 99; +const CREATOR = "7"; +const oldKey = `${CHAT}_${OLD}`; +const sentKey = `${CHAT}_${SENT}`; + +let spies: Array<{ mockRestore(): void }>; +beforeEach(() => { + clearAllGameSetupSessions(); + spies = [ + spyOn(console, "warn").mockImplementation(() => {}), + spyOn(console, "log").mockImplementation(() => {}), + ]; +}); +afterEach(() => { + for (const spy of spies) spy.mockRestore(); + clearAllGameSetupSessions(); +}); + +function makeHandlers() { + type Dependencies = Parameters[0]; + const registered: Array<{ pattern: RegExp | string; handle: (ctx: Context) => Promise }> = + []; + const bot = { + on: () => {}, + callbackQuery: (pattern: RegExp | string, handle: (ctx: Context) => Promise) => { + registered.push({ pattern, handle }); + }, + } as unknown as Bot; + const wallet = { getTokenBalance: async () => 3_000_000 } as unknown as Dependencies["wallet"]; + const getDefaultTokenMetadata = async () => ({ decimals: 6 }); + const getTokenPolicyMinimumAmount = async () => ({ formatted: 1, raw: 1_000_000, decimals: 6 }); + const fetchTokenPriceUSD = async () => null; + const setup = createGameSetupModule({ + wallet, + getTokenManager: () => undefined, + getDefaultTokenMetadata, + getTokenPolicyMinimumAmount, + fetchTokenPriceUSD, + createAmountSelectionKeyboard, + getSuggestedStakeAmounts, + getGameSetupSession, + upsertGameSetupSession, + clearGameSetupSession, + safeAnswerCallbackQuery, + getTelegramId, + getTelegramIdString, + }); + const callbacks = createGameCallbacksModule({ + bot, + wallet, + getGameManager: () => { + throw new Error("Unexpected game access"); + }, + gameDb: {} as unknown as Dependencies["gameDb"], + wrapCallbackHandler: (handler) => async (ctx, next) => { + await handler(ctx, next); + }, + withCreatorContext: setup.withCreatorContext, + withCreatorSessionContext: setup.withCreatorSessionContext, + pendingGameCreations: new Set(), + getOracleMaxPlayers: () => 20, + getDefaultTokenMetadata, + getTokenPolicyMinimumAmount, + fetchTokenPriceUSD, + getProgram: () => { + throw new Error("Unexpected program access"); + }, + validateGameTokenData: () => ({ isValid: true }), + gameSetupCopy: GAME_SETUP_COPY, + }); + callbacks.registerHandlers(); + const invoke = async (data: string, useReply: boolean) => { + const answerCallbackQuery = mock(async (_text?: string) => {}); + const reply = mock(async (_text: string, _options?: unknown) => ({ + message_id: SENT, + chat: { id: CHAT }, + })); + const editMessageText = mock(async (_text: string, _options?: unknown) => { + if (useReply) throw new Error("fixture edit unavailable"); + return true; + }); + for (const { pattern, handle } of registered) { + const match = + typeof pattern === "string" ? (pattern === data ? [data] : null) : data.match(pattern); + if (!match) continue; + const ctx = { + from: { id: Number(CREATOR) }, + chat: { id: CHAT, type: "supergroup" }, + match, + callbackQuery: { + id: "fixture-callback", + data, + message: { message_id: OLD, chat: { id: CHAT } }, + }, + answerCallbackQuery, + reply, + editMessageText, + } as unknown as Context; + await handle(ctx); + return { answerCallbackQuery, reply, editMessageText }; + } + throw new Error("No callback handler accepted the fixture"); + }; + return { callbacks, invoke }; +} + +function seedSession() { + upsertGameSetupSession(oldKey, { + waitingFor: "setup", + userBalance: 10, + creatorId: CREATOR, + gameType: "coinflip", + amount: "2", + chatId: CHAT, + messageId: OLD, + tokenMint: "mint-fixture", + tokenTicker: "TKN", + tokenDecimals: 6, + contractMinimum: 1, + timeoutSeconds: 4_500, + }); +} + +const compactPlayers = (): string => { + const data = encodeCustomPlayersPayload({ + gameType: "coinflip", + amount: "2", + creatorId: CREATOR, + }); + if (!data) throw new Error("Invalid compact fixture"); + return data; +}; + +test.each([ + [ + "amount", + (): string => `custom_amount_coinflip_${CREATOR}`, + "amount_input", + "Type your amount...", + ], + [ + "legacy players", + (): string => `custom_players_coinflip_2_${CREATOR}`, + "players_input", + "Type the number of players...", + ], + ["compact players", compactPlayers, "players_input", "Type the number of players..."], +] as const)( + "stores the %s prompt under the reply that was actually sent", + async (_label, data, waitingFor, toast) => { + seedSession(); + const { callbacks, invoke } = makeHandlers(); + const { answerCallbackQuery, reply, editMessageText } = await invoke(data(), true); + expect(editMessageText).toHaveBeenCalledTimes(1); + expect(reply).toHaveBeenCalledTimes(1); + expect(answerCallbackQuery.mock.calls).toEqual([[toast]]); + expect(getGameSetupSession(oldKey)).toBeUndefined(); + expect(getGameSetupSession(sentKey)).toMatchObject({ + waitingFor, + chatId: CHAT, + messageId: SENT, + creatorId: CREATOR, + amount: "2", + tokenMint: "mint-fixture", + tokenTicker: "TKN", + tokenDecimals: 6, + contractMinimum: 1, + timeoutSeconds: 4_500, + }); + const next = mock(async () => {}); + const editReply = mock( + async (_chat: number, _id: number, _text: string, _options: unknown) => true, + ); + const message = { + from: { id: Number(CREATOR) }, + chat: { id: CHAT, type: "supergroup" }, + message: { + text: waitingFor === "amount_input" ? "3" : "4", + reply_to_message: { message_id: SENT }, + }, + api: { editMessageText: editReply }, + } as unknown as Context; + await callbacks.__test_handleGameSetupTextInput(message, next); + expect(next).not.toHaveBeenCalled(); + expect(editReply.mock.calls).toEqual([[CHAT, SENT, expect.any(String), expect.any(Object)]]); + expect(getGameSetupSession(sentKey)).toMatchObject({ + waitingFor: "setup", + tokenMint: "mint-fixture", + amount: waitingFor === "amount_input" ? "3" : "2", + }); + }, +); + +test("keeps the existing custom players card and its precise text when it can be edited", async () => { + seedSession(); + const { invoke } = makeHandlers(); + const { reply, editMessageText } = await invoke(compactPlayers(), false); + expect(reply).not.toHaveBeenCalled(); + expect(editMessageText.mock.calls).toEqual([ + [ + "👥 Type Custom Players - Coinflip\n\nAmount: 2 TKN\n\nPlease type the number of players for this game.\n\nRange: 2-20 players", + expect.objectContaining({ parse_mode: "HTML" }), + ], + ]); + expect(getGameSetupSession(oldKey)).toMatchObject({ + waitingFor: "players_input", + chatId: CHAT, + messageId: OLD, + creatorId: CREATOR, + amount: "2", + tokenMint: "mint-fixture", + timeoutSeconds: 4_500, + }); + expect(getGameSetupSession(sentKey)).toBeUndefined(); +}); + +test("updates a compact player prompt on the original message without a stored session", async () => { + const { invoke } = makeHandlers(); + const { reply, editMessageText } = await invoke(compactPlayers(), false); + expect(reply).not.toHaveBeenCalled(); + expect(editMessageText).toHaveBeenCalledTimes(1); + expect(getGameSetupSession(oldKey)).toMatchObject({ + waitingFor: "players_input", + chatId: CHAT, + messageId: OLD, + creatorId: CREATOR, + amount: "2", + minPlayers: 2, + maxPlayersLimit: 20, + }); +}); + +test.each([ + [ + "players_input", + "outside range", + "❌ Invalid number of players. Please enter a number between 2 and 20.", + ], + ["amount_input", "$0", "❌ Invalid USD amount. Try something like $10."], + ["amount_input", "$2", "❌ USD pricing unavailable for TKN. Please enter the amount in TKN."], + ["amount_input", "0", "❌ Invalid amount. Please use /coinflip or /giveaway to try again."], + ["amount_input", "100", "❌ Amount too high. Please try a lower amount."], + ["amount_input", "0.25", "❌ Amount below current minimum of 1 TKN."], +] as const)( + "keeps the replacement %s prompt active after input %j", + async (waitingFor, text, error) => { + seedSession(); + upsertGameSetupSession(oldKey, { waitingFor, maxPlayersLimit: 20 }); + const { callbacks } = makeHandlers(); + const editMessageText = mock( + async (_chat: number, _id: number, _text: string, _options: unknown) => { + throw new Error("fixture edit failed"); + }, + ); + const reply = mock(async (_text: string, _options: unknown) => ({ + message_id: SENT, + chat: { id: CHAT }, + })); + const next = mock(async () => {}); + const ctx = { + from: { id: Number(CREATOR) }, + chat: { id: CHAT, type: "supergroup" }, + message: { text, reply_to_message: { message_id: OLD } }, + api: { editMessageText }, + reply, + } as unknown as Context; + await callbacks.__test_handleGameSetupTextInput(ctx, next); + expect(editMessageText.mock.calls).toEqual([[CHAT, OLD, error, { parse_mode: "HTML" }]]); + expect(reply.mock.calls).toEqual([[error, { parse_mode: "HTML" }]]); + expect(next).not.toHaveBeenCalled(); + expect(getGameSetupSession(oldKey)).toBeUndefined(); + expect(getGameSetupSession(sentKey)).toMatchObject({ + waitingFor, + creatorId: CREATOR, + chatId: CHAT, + messageId: SENT, + amount: "2", + tokenMint: "mint-fixture", + timeoutSeconds: 4_500, + }); + }, +); + +test.each([ + ["players_input", "4", "2", "Confirm Coinflip", { players: 4 }], + ["amount_input", "3", "3", "Choose Maximum Players", {}], +] as const)( + "binds successful %s output to a fallback reply", + async (waitingFor, text, amount, label, extra) => { + seedSession(); + upsertGameSetupSession(oldKey, { waitingFor, maxPlayersLimit: 20 }); + const { callbacks } = makeHandlers(); + const editMessageText = mock( + async (_chat: number, _id: number, _text: string, _options: unknown) => { + throw new Error("fixture edit failed"); + }, + ); + const reply = mock(async (_text: string, _options: unknown) => ({ + message_id: SENT, + chat: { id: CHAT }, + })); + const next = mock(async () => {}); + const ctx = { + from: { id: Number(CREATOR) }, + chat: { id: CHAT, type: "supergroup" }, + message: { text, reply_to_message: { message_id: OLD } }, + api: { editMessageText }, + reply, + } as unknown as Context; + await callbacks.__test_handleGameSetupTextInput(ctx, next); + expect(editMessageText.mock.calls).toEqual([ + [CHAT, OLD, expect.stringContaining(label), expect.any(Object)], + ]); + expect(reply.mock.calls).toEqual([[expect.stringContaining(label), expect.any(Object)]]); + expect(next).not.toHaveBeenCalled(); + expect(getGameSetupSession(oldKey)).toBeUndefined(); + expect(getGameSetupSession(sentKey)).toMatchObject({ + waitingFor: "setup", + creatorId: CREATOR, + chatId: CHAT, + messageId: SENT, + amount, + tokenMint: "mint-fixture", + ...extra, + }); + }, +); From d64a6b58ca703653256285697081887cb290ba8f Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 18:29:26 -0300 Subject: [PATCH 157/410] fix(tokens): match Jupiter mint metadata case sensitively --- src/utils/jupiter.ts | 45 +++++++++++++--------------- tests/jupiter.client-errors.test.ts | 46 +++++++++++++++++++++++++++++ tests/jupiter.utils.test.ts | 17 +++++++++++ tests/token-metadata.test.ts | 12 ++++++++ 4 files changed, 96 insertions(+), 24 deletions(-) diff --git a/src/utils/jupiter.ts b/src/utils/jupiter.ts index a3012425..77a607e2 100644 --- a/src/utils/jupiter.ts +++ b/src/utils/jupiter.ts @@ -829,15 +829,7 @@ export class JupiterClient { * Convert SOL to WSOL mint for Jupiter */ export function getJupiterMint(mint: string): string { - // SOL should be represented as WSOL mint for Jupiter - if (mint === "SOL") { - return WSOL_MINT; // WSOL mint - } - // WSOL mint is already correct - if (mint === WSOL_MINT) { - return mint; - } - return mint; + return mint === "SOL" ? WSOL_MINT : mint; } /** @@ -887,17 +879,26 @@ export interface JupiterTokenMetadata { decimals: number; } +const isCanonicalMintQuery = (query: string): boolean => { + try { + return new PublicKey(query).toBase58() === query; + } catch { + return false; + } +}; + export async function fetchJupiterTokenMetadata( query: string, fetchImpl: FetchLike = globalThis.fetch as unknown as FetchLike, ): Promise { - if (!query || !query.trim()) { + const trimmedQuery = query?.trim(); + if (!trimmedQuery) { return null; } try { const url = new URL("https://api.jup.ag/tokens/v2/search"); - url.searchParams.set("query", query.trim()); + url.searchParams.set("query", trimmedQuery); const apiKey = process.env.JUPITER_API_KEY; @@ -919,20 +920,16 @@ export async function fetchJupiterTokenMetadata( return null; } - const normalizedQuery = query.trim().toLowerCase(); const entries = parsed.data; - - const exactId = entries.find( - (item) => typeof item.id === "string" && item.id.trim().toLowerCase() === normalizedQuery, - ); - - const exactSymbol = entries.find( - (item) => - typeof item.symbol === "string" && item.symbol.trim().toLowerCase() === normalizedQuery, - ); - - // `entries` is non-empty: an empty result returned null above. - const candidate = exactId ?? exactSymbol ?? entries[0]!; + const exactId = entries.find((item) => item.id.trim() === trimmedQuery); + // Mint addresses are case-sensitive. Text search can still use fuzzy results. + if (!exactId && isCanonicalMintQuery(trimmedQuery)) return null; + const normalizedQuery = trimmedQuery.toLowerCase(); + const candidate = + exactId ?? + entries.find((item) => item.id.trim().toLowerCase() === normalizedQuery) ?? + entries.find((item) => item.symbol.trim().toLowerCase() === normalizedQuery) ?? + entries[0]!; return { id: candidate.id, diff --git a/tests/jupiter.client-errors.test.ts b/tests/jupiter.client-errors.test.ts index cd9b0d24..b0c2fdc7 100644 --- a/tests/jupiter.client-errors.test.ts +++ b/tests/jupiter.client-errors.test.ts @@ -265,6 +265,10 @@ describe("JupiterClient", () => { }); describe("fetchJupiterTokenMetadata", () => { + const mint = "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"; + const otherMint = "EPjfWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"; + const exact = { id: mint, symbol: "EXACT", decimals: 6 }; + const other = { id: otherMint, symbol: "OTHER", decimals: 9 }; let errorSpy: ReturnType; beforeEach(() => { @@ -294,4 +298,46 @@ describe("fetchJupiterTokenMetadata", () => { expect(await fetchJupiterTokenMetadata("SOL", fetchImpl as any)).toBeNull(); expect(errorSpy).toHaveBeenCalledWith("Failed to fetch Jupiter token metadata:", failure); }); + + test("uses an exact mint even if a case-different mint appears first", async () => { + const calls: FetchCall[] = []; + const fetchImpl = async (input: RequestInfo | URL, init?: RequestInit) => { + calls.push({ url: String(input), init }); + return Response.json([other, exact]); + }; + const prior = process.env.JUPITER_API_KEY; + process.env.JUPITER_API_KEY = "fake-test-key"; + try { + expect(await fetchJupiterTokenMetadata(` ${mint} `, fetchImpl)).toMatchObject(exact); + expect(calls).toHaveLength(1); + expect(calls[0]?.url).toBe(`https://api.jup.ag/tokens/v2/search?query=${mint}`); + expect(calls[0]?.init?.method).toBe("GET"); + expect(new Headers(calls[0]?.init?.headers).get("accept")).toBe("application/json"); + expect(new Headers(calls[0]?.init?.headers).get("x-api-key")).toBe("fake-test-key"); + expect(calls[0]?.init?.signal).toBeInstanceOf(AbortSignal); + } finally { + if (prior === undefined) delete process.env.JUPITER_API_KEY; + else process.env.JUPITER_API_KEY = prior; + } + }); + + test("does not substitute a different token for a valid mint search", async () => { + expect(await fetchJupiterTokenMetadata(mint, async () => Response.json([other]))).toBeNull(); + }); + + test("keeps symbol search case-insensitive and falls back to the first textual match", async () => { + const fetchImpl = async () => Response.json([other, exact]); + expect(await fetchJupiterTokenMetadata(" exACT ", fetchImpl)).toMatchObject(exact); + expect(await fetchJupiterTokenMetadata("text search", fetchImpl)).toMatchObject(other); + }); + + test("ignores HTTP failures, empty results, and missing fields without throwing", async () => { + expect( + await fetchJupiterTokenMetadata("SOL", async () => new Response("busy", { status: 503 })), + ).toBeNull(); + expect(await fetchJupiterTokenMetadata("SOL", async () => Response.json([]))).toBeNull(); + expect( + await fetchJupiterTokenMetadata("SOL", async () => Response.json([{ id: mint }])), + ).toBeNull(); + }); }); diff --git a/tests/jupiter.utils.test.ts b/tests/jupiter.utils.test.ts index c10d9ee0..c8933c40 100644 --- a/tests/jupiter.utils.test.ts +++ b/tests/jupiter.utils.test.ts @@ -21,9 +21,24 @@ describe("jupiter utils", () => { ).toContain("EPjF"); }); + test.each([ + ["SOL", "So11111111111111111111111111111111111111112"], + ["So11111111111111111111111111111111111111112", "So11111111111111111111111111111111111111112"], + [ + "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v", + "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v", + ], + ["sol", "sol"], + ["", ""], + ] as const)("maps only the exact native SOL alias %j", (input, expected) => { + expect(getJupiterMint(input)).toBe(expected); + }); + test("isPriceImpactTooHigh compares numeric percent", () => { expect(isPriceImpactTooHigh("4.99", 5)).toBe(false); expect(isPriceImpactTooHigh("5.01", 5)).toBe(true); + expect(isPriceImpactTooHigh("5")).toBe(false); + expect(isPriceImpactTooHigh("5.01")).toBe(true); }); test("validateSlippage enforces min and max bounds", () => { @@ -31,6 +46,8 @@ describe("jupiter utils", () => { expect(validateSlippage(500).valid).toBe(true); expect(validateSlippage(9).valid).toBe(false); expect(validateSlippage(501).valid).toBe(false); + expect(validateSlippage(9).error).toBe("Slippage too low. Minimum: 0.1%"); + expect(validateSlippage(501).error).toBe("Slippage too high. Maximum: 5%"); }); }); diff --git a/tests/token-metadata.test.ts b/tests/token-metadata.test.ts index 35aad5e7..72310dae 100644 --- a/tests/token-metadata.test.ts +++ b/tests/token-metadata.test.ts @@ -89,6 +89,18 @@ describe("resolveTokenMetadata", () => { expect(result).toEqual({ symbol: "USDC", name: "USDC", decimals: 6 }); }); + test("does not use another mint's ticker or decimals after its metadata account is unavailable", async () => { + const result = await resolveTokenMetadata({ + connection: connectionWith(null) as unknown as Connection, + mintAddress: MINT, + fetch: jupiterFetch([ + { id: "EPjfWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v", symbol: "OTHER", decimals: 4 }, + ]), + defaultDecimals: 9, + }); + expect(result).toEqual({ decimals: 9 }); + }); + test("survives a failing metadata RPC lookup", async () => { const connection = { getAccountInfo: async () => { From 3dc45672e613c7a035d60d4dc1a32c12b85e7c96 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 18:33:32 -0300 Subject: [PATCH 158/410] fix(fees): use defaults for blank budget overrides --- src/utils/fee-budget.ts | 2 +- tests/fee-budget.behavior.test.ts | 22 ++++++++++++++++++++++ 2 files changed, 23 insertions(+), 1 deletion(-) diff --git a/src/utils/fee-budget.ts b/src/utils/fee-budget.ts index 3cacaf5e..75465b99 100644 --- a/src/utils/fee-budget.ts +++ b/src/utils/fee-budget.ts @@ -50,7 +50,7 @@ const parseEnvNumber = ( fallback: number, options: { min?: number; label?: string } = {}, ): number => { - if (value === undefined) return fallback; + if (!value?.trim()) return fallback; const parsed = Number(value); if (!Number.isFinite(parsed)) { diff --git a/tests/fee-budget.behavior.test.ts b/tests/fee-budget.behavior.test.ts index 49c7ce45..6e4c1787 100644 --- a/tests/fee-budget.behavior.test.ts +++ b/tests/fee-budget.behavior.test.ts @@ -93,6 +93,28 @@ test("warns exactly when the cache TTL is below its minimum", () => { } }); +test.each(["", " \t\n "])("treats blank fee overrides %j as unset, not zero", (empty) => { + const warn = spyOn(console, "warn").mockImplementation(() => {}); + try { + const overrides = Object.fromEntries(Object.keys(env).map((key) => [key, empty])); + expect(loadFeeBudgetConfigFromEnv(overrides)).toEqual(loadFeeBudgetConfigFromEnv({})); + expect(warn).not.toHaveBeenCalled(); + } finally { + warn.mockRestore(); + } +}); + +test("keeps explicit zero and surrounding whitespace on valid fee overrides", () => { + const config = loadFeeBudgetConfigFromEnv({ + FEE_CACHE_TTL_MS: " 100 ", + FEE_SINGLE_TX_EXTRA_LAMPORTS: " 0 ", + FEE_GAME_BUFFER_MULTIPLIER: " 1.5 ", + }); + expect(config.cacheTtlMs).toBe(100); + expect(config.singleTxExtraLamports).toBe(0); + expect(config.gameBufferMultiplier).toBe(1.5); +}); + test("uses the configured default buffer formulas before any RPC calls", async () => { const keys = Object.keys(env) as Array; const original = keys.map((key) => [key, process.env[key]] as const); From ad0a1276b65123d9b090f6acb040e97fab9d20a2 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 18:33:32 -0300 Subject: [PATCH 159/410] test(games): check the delivered giveaway prompt in integration --- tests/game-menu.input-session.test.ts | 18 +++++++++++------- 1 file changed, 11 insertions(+), 7 deletions(-) diff --git a/tests/game-menu.input-session.test.ts b/tests/game-menu.input-session.test.ts index d78ae1b0..67877329 100644 --- a/tests/game-menu.input-session.test.ts +++ b/tests/game-menu.input-session.test.ts @@ -264,7 +264,7 @@ describe("game setup typed input handling", () => { } }); - test("restores session after invalid players input even when edit fails", async () => { + test("keeps a valid giveaway selection on the replacement message when editing fails", async () => { const session = { waitingFor: "players_input", gameType: "giveaway", @@ -277,7 +277,7 @@ describe("game setup typed input handling", () => { tokenTicker: "USDC", tokenDecimals: 6, contractMinimum: 1, - } as any; + } as const; upsertGameSetupSession(`${CHAT_ID}_${session.messageId}`, session); @@ -307,11 +307,15 @@ describe("game setup typed input handling", () => { expect(String(firstReply.text)).toContain("Confirm Giveaway"); expect(String(firstReply.text)).toContain("Players: 1"); - const restored = getGameSetupSession(`${CHAT_ID}_${session.messageId}`) as any; - expect(restored.waitingFor).toBe("setup"); - expect(restored.tokenTicker).toBe("USDC"); - expect(restored.tokenMint).toBe("MintGiveaway222"); - expect(restored.creatorId).toBe(TELEGRAM_USER_ID.toString()); + expect(getGameSetupSession(`${CHAT_ID}_${session.messageId}`)).toBeUndefined(); + expect(getGameSetupSession(`${CHAT_ID}_${firstReply.message_id}`)).toMatchObject({ + waitingFor: "setup", + messageId: firstReply.message_id, + chatId: CHAT_ID, + tokenTicker: "USDC", + tokenMint: "MintGiveaway222", + creatorId: TELEGRAM_USER_ID.toString(), + }); }); test("ignores timeout text replies now that timeout adjustments are button-driven", async () => { From 76128ee8a02edbfb3693a552dfefef664fcc55cc Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 18:36:54 -0300 Subject: [PATCH 160/410] test(games): bound player mapping fixtures at five lookups --- tests/game-manager.update-message.test.ts | 24 +++++++++++++++---- tests/game-manager.username.test.ts | 28 ++++++++++++++++++----- 2 files changed, 41 insertions(+), 11 deletions(-) diff --git a/tests/game-manager.update-message.test.ts b/tests/game-manager.update-message.test.ts index 3732e3a2..4d9c150d 100644 --- a/tests/game-manager.update-message.test.ts +++ b/tests/game-manager.update-message.test.ts @@ -82,6 +82,20 @@ function ctxStub( return ctx; } +function completedCoinflipDb(extra: Record = {}) { + let playerReads = 0; + return makeDbStub({ + gameOverride: { game_type: "coinflip" }, + extra: { + ...extra, + getPlayerTelegramId: () => { + if (++playerReads > 5) throw new Error("Unexpected sixth player mapping lookup"); + return null; + }, + }, + }); +} + describe("GameManager.updateGameMessage routing", () => { test("coinflip active -> edits caption only", async () => { resetGM(); @@ -138,7 +152,7 @@ describe("GameManager.updateGameMessage routing", () => { makeWalletStub({ tokenFormatter: (n, d) => (Number(n) / Math.pow(10, d)).toFixed(0), }), - makeDbStub({ gameOverride: { game_type: "coinflip" } }), + completedCoinflipDb(), ); const ctx = ctxStub(); const addr = new PublicKey("11111111111111111111111111111112").toBase58(); @@ -309,7 +323,7 @@ describe("GameManager.updateGameMessage routing", () => { makeWalletStub({ tokenFormatter: (n, d) => (Number(n) / Math.pow(10, d)).toFixed(0), }), - makeDbStub({ gameOverride: { game_type: "coinflip" } }), + completedCoinflipDb(), ); const ctx = ctxStub({ failMedia: { description: "Bad Request: wrong file identifier/HTTP URL specified" }, @@ -355,7 +369,7 @@ describe("GameManager.updateGameMessage routing", () => { makeWalletStub({ tokenFormatter: (n, d) => (Number(n) / Math.pow(10, d)).toFixed(0), }), - makeDbStub({ gameOverride: { game_type: "coinflip" }, extra: { saveGameMessage } }), + completedCoinflipDb({ saveGameMessage }), ); const ctx = ctxStub({ failMedia: { description: "Bad Request: wrong file identifier/HTTP URL specified" }, @@ -408,7 +422,7 @@ describe("GameManager.updateGameMessage routing", () => { makeWalletStub({ tokenFormatter: (n, d) => (Number(n) / Math.pow(10, d)).toFixed(0), }), - makeDbStub({ gameOverride: { game_type: "coinflip" }, extra: { saveGameMessage } }), + completedCoinflipDb({ saveGameMessage }), ); const ctx = ctxStub({ failMedia: { description: "Bad Request: wrong file identifier/HTTP URL specified" }, @@ -459,7 +473,7 @@ describe("GameManager.updateGameMessage routing", () => { makeWalletStub({ tokenFormatter: (n, d) => (Number(n) / Math.pow(10, d)).toFixed(0), }), - makeDbStub({ gameOverride: { game_type: "coinflip" }, extra: { saveGameMessage } }), + completedCoinflipDb({ saveGameMessage }), ); const ctx = ctxStub({ failMedia: { description: "Bad Request: wrong file identifier/HTTP URL specified" }, diff --git a/tests/game-manager.username.test.ts b/tests/game-manager.username.test.ts index 96a66f00..ddad53c3 100644 --- a/tests/game-manager.username.test.ts +++ b/tests/game-manager.username.test.ts @@ -1,4 +1,4 @@ -import { describe, test, expect } from "bun:test"; +import { describe, test, expect, spyOn } from "bun:test"; import fc from "fast-check"; import type { Context } from "grammy"; import { TELEGRAM_USERNAME_CACHE_TTL_MS } from "../src/utils/constants"; @@ -473,17 +473,33 @@ describe("GameManager Username Resolution", () => { test("falls back to address when mapping missing", async () => { resetGM(); + const address = "BPFLoader1111111111111111111111111111111111"; + const lookups: string[] = []; const gm = GameManager.getInstance( makeProgramStub(), makeWalletStub(), - makeDbStub({ extra: { getPlayerTelegramId: () => null } }), + makeDbStub({ + extra: { + getPlayerTelegramId: (publicKey: string) => { + lookups.push(publicKey); + if (lookups.length > 5) throw new Error("Unexpected sixth player mapping lookup"); + return null; + }, + }, + }), ); const ctx = { chat: { id: 1, type: "private" }, api: { getChatMember: async () => ({ user: {} }) }, - } as any; - const label = await gm.getPlayerUsername(ctx, "BPFLoader1111111111111111111111111111111111"); - expect(label).toBe("BPFL…1111"); + } as unknown as Context; + const timer = spyOn(globalThis, "setTimeout"); + try { + expect(await gm.getPlayerUsername(ctx, address)).toBe("BPFL…1111"); + expect(lookups).toEqual([address, address, address, address, address]); + expect(timer.mock.calls.map(([, delay]) => delay)).toEqual([1, 1, 1, 1]); + } finally { + timer.mockRestore(); + } }); test("retries until telegram id mapping appears", async () => { @@ -508,7 +524,7 @@ describe("GameManager Username Resolution", () => { const gm = GameManager.getInstance(makeProgramStub(), makeWalletStub(), stubDb); const label = await gm.getPlayerUsername(ctx, "LazyPublicKey"); expect(label).toBe("@delayed"); - expect(attempts).toBeGreaterThan(1); + expect(attempts).toBe(2); }); }); From d1ad6ba9774258c5b69dfbf11c7bec8955f2f8dc Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 18:40:20 -0300 Subject: [PATCH 161/410] refactor(recovery): keep transaction abort and withdrawal boundaries explicit --- src/evm/command-router.ts | 6 ++-- src/utils/transaction-runner.ts | 1 - tests/evm.command-router.test.ts | 1 + tests/transaction-runner.test.ts | 52 +++++++++++++++++++++++++++++++- 4 files changed, 56 insertions(+), 4 deletions(-) diff --git a/src/evm/command-router.ts b/src/evm/command-router.ts index 70ec96e3..dc30c83b 100644 --- a/src/evm/command-router.ts +++ b/src/evm/command-router.ts @@ -27,8 +27,10 @@ export function routeNetworkCommand(text: string, username: string, network: "so if (!command) return null; let args = parsed[3] ?? ""; if (command === "ewithdraw") { - const [address, amount, symbol = "ETH"] = args.trim().split(/\s+/); - args = `${symbol} ${amount ?? ""} ${address ?? ""}`; + // A split without a limit always contains the first field, even when it is empty. + const fields = args.trim().split(/\s+/) as [string, string?, string?]; + const [address, amount = "", symbol = "ETH"] = fields; + args = `${symbol} ${amount} ${address}`; } return { command, args }; } diff --git a/src/utils/transaction-runner.ts b/src/utils/transaction-runner.ts index a73a667a..80063a55 100644 --- a/src/utils/transaction-runner.ts +++ b/src/utils/transaction-runner.ts @@ -228,7 +228,6 @@ export const confirmTransactionWithRecovery = async ( statusProbeError instanceof Error ? statusProbeError : new Error(String(statusProbeError)); - recoveryErrors.push(normalizedError); console.error( `❌ Failed to verify transaction status during ${operationLabel} retry ${attemptLabel}`, normalizedError, diff --git a/tests/evm.command-router.test.ts b/tests/evm.command-router.test.ts index 5a8e5335..7ea5b240 100644 --- a/tests/evm.command-router.test.ts +++ b/tests/evm.command-router.test.ts @@ -42,6 +42,7 @@ test.each([ ["/withdraw", "ETH "], ["/withdraw 0xfixture", "ETH 0xfixture"], ["/withdraw 0xfixture 2", "ETH 2 0xfixture"], + ["/withdraw 0xfixture 2 ", "ETH 2 0xfixture"], ["/wh@TimbaBot 0xfixture\t 2.75 TOKEN ", "TOKEN 2.75 0xfixture"], ])("normalizes the withdrawal field order for %s", (text, args) => { expect(routeNetworkCommand(text, "TimbaBot", "evm")).toEqual({ command: "ewithdraw", args }); diff --git a/tests/transaction-runner.test.ts b/tests/transaction-runner.test.ts index 45796459..0d6f13b7 100644 --- a/tests/transaction-runner.test.ts +++ b/tests/transaction-runner.test.ts @@ -14,7 +14,7 @@ import { getConfirmationRetryDelays, } from "../src/utils/transaction-runner"; -type Status = { err?: unknown; confirmationStatus?: string; confirmations?: number | null } | null; +type Status = { err?: unknown; confirmationStatus?: string; confirmations?: unknown } | null; const makeWallet = (options: { confirm?: (signature: string) => Promise; @@ -430,6 +430,31 @@ describe("confirmTransactionWithRecovery", () => { ]); }); + test("does not confirm a non-string signature returned by a resubmission callback", async () => { + const original = timeout(); + const { wallet } = makeWallet({ + confirm: async () => { + throw original; + }, + }); + // This fixture represents a malformed response from outside the type-checked boundary. + const resubmit = mock(async () => 42 as unknown as string); + await expect( + confirmTransactionWithRecovery({ + wallet, + initialSignature: "original-signature", + operationLabel: "Withdraw", + resubmit, + retryDelays: [], + }), + ).rejects.toBe(original); + expect(wallet.confirmTransaction.mock.calls).toEqual([["original-signature"]]); + expect(resubmit).toHaveBeenCalledTimes(2); + expect(original.cause).toMatchObject({ + message: "Resubmission callback did not return a transaction signature", + }); + }); + test.each([ ["confirmed", { confirmationStatus: "confirmed" }], ["finalized", { confirmationStatus: "finalized" }], @@ -452,6 +477,31 @@ describe("confirmTransactionWithRecovery", () => { ).toBe("s"); }); + test.each(["2", true, null])( + "leaves a transaction pending for a non-numeric count %j", + async (confirmations) => { + const original = timeout(); + const { wallet, statusCalls } = makeWallet({ + confirm: async () => { + throw original; + }, + statuses: () => ({ confirmationStatus: "processed", confirmations }), + }); + await expect( + confirmTransactionWithRecovery({ + wallet, + initialSignature: "pending-signature", + operationLabel: "Withdraw", + retryDelays: [0], + }), + ).rejects.toBe(original); + expect(statusCalls).toEqual(["pending-signature"]); + expect(original.cause).toMatchObject({ + message: "Transaction pending-signature still pending after retry 1", + }); + }, + ); + test("a failed on-chain status aborts recovery", async () => { const { wallet } = makeWallet({ confirm: async () => { From 2b2215c80f9ed40df8baf80ab45d4cb850f03575 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 18:41:34 -0300 Subject: [PATCH 162/410] test(evm): verify bounded transports and receipt failure handling --- tests/evm.service-boundaries.test.ts | 64 ++++++++++++++++++++++++++++ 1 file changed, 64 insertions(+) diff --git a/tests/evm.service-boundaries.test.ts b/tests/evm.service-boundaries.test.ts index c7373e37..da64dc8c 100644 --- a/tests/evm.service-boundaries.test.ts +++ b/tests/evm.service-boundaries.test.ts @@ -37,6 +37,33 @@ const transaction = (raw: EvmAction["raw"], hash: EvmAction["hash"]): EvmAction hash, }); +test("wires the configured EVM chain and bounded RPC transport in order", () => { + const rpcUrls = ["http://127.0.0.1:1", "http://127.0.0.1:2"]; + const configured = new EvmBotService( + { ...config, rpcUrls }, + "unused test mnemonic", + "fixture-token", + store, + ); + expect(configured.chain).toMatchObject({ + id: 31337, + name: "Test chain", + nativeCurrency: { name: "Ether", symbol: "ETH", decimals: 18 }, + rpcUrls: { default: { http: rpcUrls } }, + }); + expect(configured.client.transport.retryCount).toBe(0); + expect( + configured.client.transport.transports.map(({ config, value }) => ({ + url: value?.url, + retryCount: config.retryCount, + timeout: config.timeout, + })), + ).toEqual([ + { url: "http://127.0.0.1:1", retryCount: 0, timeout: 3_000 }, + { url: "http://127.0.0.1:2", retryCount: 0, timeout: 3_000 }, + ]); +}); + test.each([ ["missing hash", "transaction", "0x11", null], ["missing bytes", "transaction", null, "0x22"], @@ -84,6 +111,22 @@ test("replays only the saved bytes for a complete transaction without opening th } }); +test("does not rebroadcast after an unrecognized receipt lookup failure", async () => { + const action = transaction("0x11", "0x22"); + store.add(action); + const receipt = spyOn(service.client, "getTransactionReceipt").mockRejectedValue(null); + const send = spyOn(service.client, "sendRawTransaction").mockResolvedValue("0x22"); + try { + await expect(service.step(action)).rejects.toBeNull(); + expect(receipt).toHaveBeenCalledWith({ hash: "0x22" }); + expect(send).not.toHaveBeenCalled(); + expect(store.action(action.id)).toMatchObject(action); + } finally { + send.mockRestore(); + receipt.mockRestore(); + } +}); + test("uses the configured oracle path and sends JSON only for a request with input", async () => { const mockFetch = Object.assign(async () => Response.json({ ok: true }), { preconnect: () => {}, @@ -106,6 +149,27 @@ test("uses the configured oracle path and sends JSON only for a request with inp } }); +test("applies an oracle deadline and rejects an HTTP failure before reading its JSON", async () => { + let bodyReads = 0; + const response = new Response("busy", { status: 503 }); + const readBody = spyOn(response, "json").mockImplementation(async () => { + bodyReads++; + return {}; + }); + const mockFetch = Object.assign(async () => response, { preconnect: () => {} }); + const fetch = spyOn(globalThis, "fetch").mockImplementation(mockFetch); + const deadline = spyOn(AbortSignal, "timeout"); + try { + await expect(service.oracle("/evm/config")).rejects.toThrow("EVM oracle request failed"); + expect(deadline.mock.calls).toEqual([[12_000]]); + expect(bodyReads).toBe(0); + } finally { + deadline.mockRestore(); + fetch.mockRestore(); + readBody.mockRestore(); + } +}); + test("rejects wrong oracle and RPC deployments independently", async () => { const metadata = { chainId: config.chainId, From f11304fee2d13a9cc6b50cb86eb22ddcbcfff841 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 18:42:48 -0300 Subject: [PATCH 163/410] test(format): pin exponent padding and document equivalent fallback --- src/utils/program-event-parser.ts | 1 + tests/format-amount.test.ts | 2 ++ 2 files changed, 3 insertions(+) diff --git a/src/utils/program-event-parser.ts b/src/utils/program-event-parser.ts index cef7a593..4a005a2e 100644 --- a/src/utils/program-event-parser.ts +++ b/src/utils/program-event-parser.ts @@ -45,6 +45,7 @@ export function decodeProgramEventLog( /* Keep the legacy caller's fallback behavior. */ } try { + // Stryker disable next-line OptionalChaining: Calling an absent fallback throws, and this catch returns the same null. return decodeFallback?.(logBase64) ?? null; } catch { return null; diff --git a/tests/format-amount.test.ts b/tests/format-amount.test.ts index e741bc59..54be3c50 100644 --- a/tests/format-amount.test.ts +++ b/tests/format-amount.test.ts @@ -215,6 +215,8 @@ test.each<[number, number | undefined, string]>([ [5e-7, Number.NaN, "0"], [5e-7, 6, "0.000001"], [-1.2e-10, undefined, "-0.0000"], + [1.2e-100, undefined, "0.0000"], + [-1.2e-200, undefined, "-0.0000"], ])("formatTokenDisplay(%p) with %p decimals is %s", (value, decimals, expected) => { expect(formatTokenDisplay(value, decimals === undefined ? {} : { decimals })).toBe(expected); }); From 3d5c57df28e0c786e2c43195a32cf5b0f8de0716 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 18:49:07 -0300 Subject: [PATCH 164/410] fix(games): keep live targets and discard expired player events --- src/bot.ts | 27 ++++--- tests/pending-player-events.test.ts | 114 ++++++++++++++++++++++------ 2 files changed, 103 insertions(+), 38 deletions(-) diff --git a/src/bot.ts b/src/bot.ts index 2b00ec45..e57450f8 100644 --- a/src/bot.ts +++ b/src/bot.ts @@ -1785,15 +1785,17 @@ const getGameMessageTargets = (gameAddress: string): GameMessageTarget[] => { console.warn(`Error getting game messages from DB for ${gameAddress}`, error); } - // Check legacy fallback - const gameRecord = gameDb.getGame(gameAddress); - if (gameRecord && gameRecord.chat_id && gameRecord.message_id) { - if (!uniqueTargets.has(gameRecord.chat_id)) { + // Keep the other targets when the legacy lookup is unavailable. + try { + const gameRecord = gameDb.getGame(gameAddress); + if (gameRecord?.chat_id && gameRecord.message_id && !uniqueTargets.has(gameRecord.chat_id)) { uniqueTargets.set(gameRecord.chat_id, { chatId: gameRecord.chat_id, messageId: gameRecord.message_id, }); } + } catch (error) { + console.warn(`Error getting legacy game message for ${gameAddress}`, error); } return Array.from(uniqueTargets.values()); @@ -2196,15 +2198,14 @@ async function flushPendingPlayerEvents( } state.timer = undefined; + state.events = prunePendingPlayerEvents(state); + if (state.events.length === 0) { + pendingPlayerEvents.delete(gameAddress); + return; + } + const targets = getGameMessageTargets(gameAddress); if (targets.length === 0) { - state.events = prunePendingPlayerEvents(state); - - if (state.events.length === 0) { - pendingPlayerEvents.delete(gameAddress); - return; - } - pendingPlayerEvents.set(gameAddress, state); if (reason === "notify") { console.warn( @@ -2217,9 +2218,7 @@ async function flushPendingPlayerEvents( pendingPlayerEvents.delete(gameAddress); - if (state.events.length > 0) { - console.log(`📬 Flushing ${state.events.length} pending player event(s) for ${gameAddress}`); - } + console.log(`📬 Flushing ${state.events.length} pending player event(s) for ${gameAddress}`); for (const payload of state.events) { await processPlayerEvent(payload.event, payload.eventName, targets); diff --git a/tests/pending-player-events.test.ts b/tests/pending-player-events.test.ts index eff63ef7..793f2cb3 100644 --- a/tests/pending-player-events.test.ts +++ b/tests/pending-player-events.test.ts @@ -1,4 +1,4 @@ -import { beforeEach, afterEach, describe, expect, test } from "bun:test"; +import { beforeEach, afterEach, describe, expect, spyOn, test } from "bun:test"; import { Keypair, PublicKey } from "#solana"; import BN from "bn.js"; import { ChatDatabase } from "../src/utils/chat-database"; @@ -31,6 +31,7 @@ describe("Pending player events", async () => { botModule.__test_clearPendingPlayerEvents(); botModule.__test_clearPendingGameMessageUpdates(); + botModule.__test_clearJoinNotificationBuckets(); botModule.__test_setGameManager({ updateGameMessageFromData: async () => {}, getPlayerUsername: async () => "", @@ -77,6 +78,76 @@ describe("Pending player events", async () => { }); }; + test("keeps the live message when a legacy database lookup fails", async () => { + enableJoinAnnouncementsForTest(); + const gameAddress = baseGameKey.toBase58(); + const failure = new Error("legacy read unavailable"); + let lookups = 0; + botModule.__test_setGameDatabase({ + getGameLastSlotWithTimestamp: () => ({ lastSlot: null, timestamp: null }), + getCreatorInfo: () => ({ telegramId: null, publicKey: null }), + getGame: () => { + if (++lookups === 1) throw failure; + return { game_type: "coinflip", chat_id: 77 }; + }, + getGameMessages: () => [{ chatId: 77, messageId: 302 }], + } as unknown as ReturnType); + const warn = spyOn(console, "warn").mockImplementation(() => {}); + try { + botModule.__test_enqueuePendingPlayerEvent(gameAddress, { + event: makePlayerEvent(new PublicKey("So11111111111111111111111111111111111111112"), 3, 12), + eventName: "PlayerJoined", + receivedAt: Date.now(), + }); + await botModule.__test_flushPendingPlayerEvents(gameAddress, "notify"); + expect(sendCalls).toHaveLength(1); + expect(sendCalls[0]?.options?.reply_to_message_id).toBe(301); + expect(botModule.__test_getPendingPlayerEventsState(gameAddress)).toBeUndefined(); + expect(warn).toHaveBeenCalledWith( + `Error getting legacy game message for ${gameAddress}`, + failure, + ); + } finally { + warn.mockRestore(); + } + }); + + test("drops expired events even when a message becomes available", async () => { + enableJoinAnnouncementsForTest(); + const gameAddress = baseGameKey.toBase58(); + const expired = new PublicKey("So11111111111111111111111111111111111111112"); + const recent = new PublicKey("EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"); + const clock = spyOn(Date, "now").mockReturnValue(1_000_000); + const warn = spyOn(console, "warn").mockImplementation(() => {}); + botModule.__test_setGameManager({ + updateGameMessageFromData: async () => {}, + getPlayerUsername: async (_ctx: unknown, mint: string) => + mint === recent.toBase58() ? "Recent" : "Expired", + getActiveGameMessages: () => new Map([[77, { chatId: 77, messageId: 301 }]]), + } as unknown as ReturnType); + try { + for (const [player, age] of [ + [expired, 15_001], + [recent, 15_000], + ] as const) { + botModule.__test_enqueuePendingPlayerEvent(gameAddress, { + event: makePlayerEvent(player, 3, 12), + eventName: "PlayerJoined", + receivedAt: Date.now() - age, + }); + } + await botModule.__test_flushPendingPlayerEvents(gameAddress, "notify"); + expect(sendCalls.map(({ text }) => text)).toEqual(["👤 Recent joined the coinflip!"]); + expect(warn).toHaveBeenCalledWith( + "⚠️ Dropping stale PlayerJoined event after waiting 15001ms", + ); + expect(botModule.__test_getPendingPlayerEventsState(gameAddress)).toBeUndefined(); + } finally { + warn.mockRestore(); + clock.mockRestore(); + } + }); + test("player join announcements escape display names", async () => { const target = { chatId: 77, messageId: 301 }; const event = makePlayerEvent((await Keypair.generate()).publicKey, 5, 10); @@ -368,7 +439,7 @@ describe("Pending player events", async () => { expect(botModule.__test_getPendingPlayerEventsState(gameAddress)).toBeUndefined(); }); - test("pending events near age limit flush once target becomes available", async () => { + test("pending events at the exact age limit flush once a target becomes available", async () => { const gameAddress = "BOUNDARY_GAME"; const player = (await Keypair.generate()).publicKey; enableJoinAnnouncementsForTest(88); @@ -396,32 +467,27 @@ describe("Pending player events", async () => { getGameMessages: () => [], } as any); - const eventReceivedAt = Date.now() - (15_000 - 100); - - botModule.__test_enqueuePendingPlayerEvent(gameAddress, { - event: makePlayerEvent(player, 7, 30), - eventName: "PlayerJoined", - receivedAt: eventReceivedAt, - }); + const clock = spyOn(Date, "now").mockReturnValue(1_000_000); + try { + botModule.__test_enqueuePendingPlayerEvent(gameAddress, { + event: makePlayerEvent(player, 7, 30), + eventName: "PlayerJoined", + receivedAt: Date.now() - 15_000, + }); - await botModule.__test_flushPendingPlayerEvents(gameAddress, "notify"); + await botModule.__test_flushPendingPlayerEvents(gameAddress, "notify"); + expect(botModule.__test_getPendingPlayerEventsState(gameAddress)?.events.length).toBe(1); - const pendingState = botModule.__test_getPendingPlayerEventsState(gameAddress); - expect(pendingState?.events.length).toBe(1); + targetReady = true; + dbRecord = { chat_id: target.chatId, message_id: target.messageId }; + await botModule.__test_flushPendingPlayerEvents(gameAddress, "notify"); - if (pendingState?.timer) { - clearTimeout(pendingState.timer); - pendingState.timer = undefined; + expect(sendCalls.length).toBe(1); + expect(sendCalls[0]?.text).toContain("Boundary"); + expect(botModule.__test_getPendingPlayerEventsState(gameAddress)).toBeUndefined(); + } finally { + clock.mockRestore(); } - - targetReady = true; - dbRecord = { chat_id: target.chatId, message_id: target.messageId }; - - await botModule.__test_flushPendingPlayerEvents(gameAddress, "notify"); - - expect(sendCalls.length).toBe(1); - expect(sendCalls[0]?.text).toContain("Boundary"); - expect(botModule.__test_getPendingPlayerEventsState(gameAddress)).toBeUndefined(); }); test("pending events retry on their own once the target becomes available", async () => { From 7c7f64d3ca719a0e7e4199d906d4fe7d7bc2663d Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 18:51:27 -0300 Subject: [PATCH 165/410] test(games): cover live and persisted notification target precedence --- tests/pending-player-events.test.ts | 105 ++++++++++++++++++++++++++++ 1 file changed, 105 insertions(+) diff --git a/tests/pending-player-events.test.ts b/tests/pending-player-events.test.ts index 793f2cb3..89564ab3 100644 --- a/tests/pending-player-events.test.ts +++ b/tests/pending-player-events.test.ts @@ -112,6 +112,111 @@ describe("Pending player events", async () => { } }); + test.each([ + [ + "all sources", + false, + false, + 99, + [ + [77, 301], + [88, 401], + [99, 501], + ], + ], + [ + "legacy overlap", + false, + false, + 88, + [ + [77, 301], + [88, 401], + ], + ], + [ + "live read failure", + true, + false, + 99, + [ + [77, 302], + [88, 401], + [99, 501], + ], + ], + [ + "persisted read failure", + false, + true, + 99, + [ + [77, 301], + [99, 501], + ], + ], + ] as const)( + "sends one notification per chat with %s", + async (_label, failLive, failPersisted, legacyChatId, expected) => { + const gameAddress = baseGameKey.toBase58(); + for (const chatId of [77, 88, 99]) { + ChatDatabase.getInstance().upsertChatGameSettings(chatId, { + join_notifications_per_minute: 50, + join_notifications_external: true, + }); + } + const persistedError = new Error("persisted target unavailable"); + botModule.__test_setGameManager({ + updateGameMessageFromData: async () => {}, + getPlayerUsername: async () => "New Player", + getActiveGameMessages: () => { + if (failLive) throw new Error("live target unavailable"); + return new Map([[77, { chatId: 77, messageId: 301 }]]); + }, + } as unknown as ReturnType); + botModule.__test_setGameDatabase({ + getGameLastSlotWithTimestamp: () => ({ lastSlot: null, timestamp: null }), + getCreatorInfo: () => ({ telegramId: null, publicKey: null }), + getGame: () => ({ game_type: "coinflip", chat_id: legacyChatId, message_id: 501 }), + getGameMessages: () => { + if (failPersisted) throw persistedError; + return [ + { chatId: 77, messageId: 302 }, + { chatId: 88, messageId: 401 }, + ]; + }, + } as unknown as ReturnType); + const warn = spyOn(console, "warn").mockImplementation(() => {}); + try { + botModule.__test_enqueuePendingPlayerEvent(gameAddress, { + event: makePlayerEvent( + new PublicKey("So11111111111111111111111111111111111111112"), + 3, + 12, + ), + eventName: "PlayerJoined", + receivedAt: Date.now(), + }); + await botModule.__test_flushPendingPlayerEvents(gameAddress, "notify"); + expect( + sendCalls.map(({ chatId, options }) => [chatId, options.reply_to_message_id]), + ).toEqual(expected.map(([chatId, messageId]) => [chatId, messageId])); + expect( + sendCalls.every(({ text }) => text === "👤 New Player joined the coinflip!"), + ).toBe(true); + const warnings = failLive + ? [[`Game manager not ready when resolving message targets for ${gameAddress}`]] + : failPersisted + ? [[`Error getting game messages from DB for ${gameAddress}`, persistedError]] + : []; + expect(warn.mock.calls).toEqual(warnings); + expect(botModule.__test_getPendingPlayerEventsState(gameAddress)).toBeUndefined(); + } finally { + warn.mockRestore(); + } + }, + ); + test("drops expired events even when a message becomes available", async () => { enableJoinAnnouncementsForTest(); const gameAddress = baseGameKey.toBase58(); From afa538884fc4e11af696db797c9701fe4ecea101 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 18:56:07 -0300 Subject: [PATCH 166/410] test(fees): pin the SOL reserve and disabled sweep boundaries --- tests/fee-sweeper.test.ts | 111 +++++++++++++++++++++++++------------- 1 file changed, 75 insertions(+), 36 deletions(-) diff --git a/tests/fee-sweeper.test.ts b/tests/fee-sweeper.test.ts index 7b963f71..24d997fe 100644 --- a/tests/fee-sweeper.test.ts +++ b/tests/fee-sweeper.test.ts @@ -7,6 +7,7 @@ import { __test_runReferralSweep, __test_resolveFeeSweepTokens, sweepFees, + type FeeSweepOptions, } from "../src/services/fee-sweeper"; import type { SwapRequest } from "../src/utils/swap/types"; import { WSOL_MINT, parseEnableFeeSweeperFlag } from "../src/utils/constants"; @@ -557,47 +558,85 @@ describe("sweepFees integration hooks", async () => { expect(swapRuns).toBe(1); }); - test("skips swaps when SOL balance exceeds threshold", async () => { - let swapRuns = 0; - - await sweepFees({ + test.each([ + { name: "one lamport below the reserve", threshold: 12, balance: 11_999_999_999, swap: 12 }, + { name: "at the reserve", threshold: 12, balance: 12_000_000_000, swap: null }, + { name: "above the reserve", threshold: 12, balance: 12_000_000_001, swap: null }, + { name: "zero reserve uses the default", threshold: 0, balance: 14_999_999_999, swap: 15 }, + { + name: "negative reserve uses the default", + threshold: -1, + balance: 15_000_000_000, + swap: null, + }, + { name: "NaN reserve uses the default", threshold: NaN, balance: 14_999_999_999, swap: 15 }, + { + name: "infinite reserve uses the default", + threshold: Infinity, + balance: 15_000_000_000, + swap: null, + }, + { + name: "unspecified reserve uses the default", + threshold: undefined, + balance: 14_999_999_999, + swap: 15, + }, + { + name: "swaps disabled before the price and balance reads", + threshold: 12, + balance: 0, + swap: null, + enabled: false, + }, + ])("checks the SOL balance $name", async ({ threshold, balance, swap, enabled }) => { + const calls: unknown[][] = []; + const programContext = fakeContext(); + programContext.provider.connection.getBalance = async (owner?: PublicKey) => { + calls.push(["balance", owner?.toBase58()]); + return balance; + }; + const result = await sweepFees({ walletManager: wallet, - tokenConfigs: tokens, + tokenConfigs: [], referralAccount: "referral", - solUsdThreshold: 15, - priceResolver: async () => ({ - price: 30, - identifier: "SOL", - resolvedAt: Date.now(), - }), - contextFactory: (() => ({ - provider: { connection: { getBalance: async () => 1_000_000_000 } }, - program: { programId: { toBase58: () => "test-program" } }, - })) as any, - referralSweeper: async () => 0, - tokenToSolSweeper: async () => { - swapRuns += 1; + solUsdThreshold: threshold, + enableSwapToSol: enabled, + priceResolver: async ({ tokenMint }) => { + calls.push(["price", tokenMint]); + return { price: 1, identifier: "SOL", resolvedAt: Date.now() }; }, - }); - - expect(swapRuns).toBe(0); - }); - - test("can disable swaps explicitly", async () => { - let swapRuns = 0; - - await sweepFees({ - walletManager: wallet, - tokenConfigs: tokens, - referralAccount: "referral", - enableSwapToSol: false, - contextFactory: fakeContext as any, - referralSweeper: async () => 0, - tokenToSolSweeper: async () => { - swapRuns += 1; + contextFactory: () => + programContext as unknown as ReturnType>, + referralSweeper: async (_connection, payer, referral) => { + calls.push(["referral", payer.publicKey.toBase58(), referral]); + return 2; + }, + tokenToSolSweeper: async (_wallet, _connection, _tokens, _factory, reserve) => { + calls.push(["swap", reserve]); + }, + balanceFetcher: async (_connection, owner, mint) => { + calls.push(["unwrap balance", owner.toBase58(), mint.toBase58()]); + return 0n; }, }); - expect(swapRuns).toBe(0); + const payer = admin.publicKey.toBase58(); + expect(result).toEqual({ tokenWithdrawals: 0, referralClaims: 2 }); + expect(calls).toEqual([ + ["referral", payer, "referral"], + ...(enabled === false + ? [] + : [ + ["balance", payer], + ["price", WSOL_MINT], + ]), + ...(swap === null + ? [] + : [ + ["swap", swap], + ["unwrap balance", payer, WSOL_MINT], + ]), + ]); }); }); From 788c9a0f8446ac58957fabf4fa53b80c157d5430 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 19:03:58 -0300 Subject: [PATCH 167/410] test(evm): pin transaction and provider boundary behavior --- src/evm/service.test.ts | 164 +++++++++++++++++++++------ src/evm/service.ts | 4 +- tests/evm.service-boundaries.test.ts | 46 ++++++++ 3 files changed, 179 insertions(+), 35 deletions(-) diff --git a/src/evm/service.test.ts b/src/evm/service.test.ts index 428ef607..7cd41677 100644 --- a/src/evm/service.test.ts +++ b/src/evm/service.test.ts @@ -1,4 +1,4 @@ -import { afterEach, beforeEach, describe, expect, test } from "bun:test"; +import { afterEach, beforeEach, describe, expect, spyOn, test } from "bun:test"; import { decodeFunctionData, erc20Abi, @@ -37,6 +37,7 @@ type OracleCall = { url: string; method: string; body: any; auth: string | null let store: EvmBotStore; let service: EvmBotService; let sent: Hex[]; +let preparedTransactions: unknown[]; let oracleCalls: OracleCall[]; let oracleHandler: (path: string, body: any) => { status?: number; body: unknown }; type ReadName = "getGame" | "creationNonces" | "owner" | "allowance"; @@ -44,6 +45,7 @@ let reads: Partial unknown>>; let receipt: unknown; let receiptError: unknown; let blockNumber: bigint; +let blockNumberOptions: unknown[]; let blockTimestamp: bigint; let chainId: number; const originalFetch = globalThis.fetch; @@ -78,11 +80,13 @@ beforeEach(() => { store = new EvmBotStore(":memory:", "test"); service = new EvmBotService(config, mnemonic, "api-token", store); sent = []; + preparedTransactions = []; oracleCalls = []; oracleHandler = () => ({ body: {} }); receipt = null; receiptError = undefined; blockNumber = 100n; + blockNumberOptions = []; blockTimestamp = 1_000n; chainId = 31337; reads = {}; @@ -103,7 +107,10 @@ beforeEach(() => { (service as any).client = { getChainId: async () => chainId, getBlock: async () => ({ timestamp: blockTimestamp }), - getBlockNumber: async () => blockNumber, + getBlockNumber: async (options: unknown) => { + blockNumberOptions.push(options); + return blockNumber; + }, readContract: async (args: any) => { const handler = reads[args.functionName as ReadName]; if (!handler) throw new Error(`unexpected read ${args.functionName}`); @@ -127,15 +134,18 @@ beforeEach(() => { return { account, signTypedData: (data: any) => account.signTypedData(data), - prepareTransactionRequest: async (tx: any) => ({ - ...tx, - chainId: config.chainId, - nonce: 0, - gas: 100_000n, - maxFeePerGas: 2n, - maxPriorityFeePerGas: 1n, - type: "eip1559", - }), + prepareTransactionRequest: async (tx: Record) => { + preparedTransactions.push(tx); + return { + ...tx, + chainId: config.chainId, + nonce: 0, + gas: 100_000n, + maxFeePerGas: 2n, + maxPriorityFeePerGas: 1n, + type: "eip1559", + }; + }, signTransaction: (prepared: any) => { const { account: _ignored, ...request } = prepared; return account.signTransaction(request); @@ -161,6 +171,7 @@ describe("EvmBotService oracle and metadata", () => { ["POST", "Bearer api-token"], ]); expect(oracleCalls[1]!.body).toEqual({ value: "1" }); + expect(oracleCalls[0]!.body).toBeUndefined(); oracleHandler = () => ({ status: 500, body: {} }); await expect(service.oracle("/evm/config")).rejects.toThrow("EVM oracle request failed"); @@ -242,7 +253,10 @@ describe("EvmBotService.step for new actions", () => { test("create obtains an oracle authorization, then asks for token approval", async () => { authorize(); - reads.creationNonces = () => 5n; + reads.creationNonces = ({ args }) => { + expect(args).toEqual([service.account("101").address]); + return 5n; + }; reads.owner = () => operator.address; reads.allowance = () => 0n; (service as any).client.verifyTypedData = async (args: any) => { @@ -311,6 +325,46 @@ describe("EvmBotService.step for new actions", () => { const decoded = decodeFunctionData({ abi: timbaAbi, data: tx.data! }); expect(decoded.functionName).toBe("createGame"); expect(decoded.args?.[2]).toBe(true); + expect(oracleCalls.at(-1)?.body).toMatchObject({ + isPrivate: false, + minPlayers: 2, + maxPlayers: 2, + }); + }); + + test("stores the giveaway authorization before a failed allowance read", async () => { + authorize(); + reads.creationNonces = () => 7n; + reads.owner = () => operator.address; + const verification = spyOn(service.client, "verifyTypedData").mockResolvedValue(true); + reads.allowance = () => { + throw new Error("allowance unavailable"); + }; + const created = addAction({ + kind: "create", + body: json({ token, amount: "10", gameType: 1 }), + }); + try { + await expect(service.step(created)).rejects.toThrow("allowance unavailable"); + const row = stored(created.id); + expect(row).toMatchObject({ phase: "new", raw: null, hash: null }); + const body = JSON.parse(row.body); + expect(body).toMatchObject({ + request: { amount: "10", nonce: "7", gameType: 1 }, + game: gameIdFor(config, service.account("101").address, 7n), + signature: "0x00", + }); + expect(sent).toEqual([]); + + reads.allowance = () => 10n; + await service.step(row); + const decoded = decodeFunctionData({ abi: timbaAbi, data: lastSentCall().tx.data! }); + expect(decoded.functionName).toBe("createGame"); + expect(decoded.args?.[2]).toBe(false); + expect(oracleCalls).toHaveLength(1); + } finally { + verification.mockRestore(); + } }); test("create rejects authorizations that are not signed by the contract owner", async () => { @@ -330,22 +384,24 @@ describe("EvmBotService.step for new actions", () => { await expect(service.step(created)).rejects.toThrow("Oracle changed game terms"); }); - test("create drops an expired authorization so it can be renewed with the same terms", async () => { - const created = addAction({ - kind: "create", - body: json({ - token, - amount: "10", - request: { amount: "10", nonce: "1", deadline: "999", gameType: 0 }, - signature: "0x12", - }), - }); - await service.step(created); - const body = JSON.parse(stored(created.id).body); - expect(body.request).toBeUndefined(); - expect(body.signature).toBeUndefined(); - expect(sent).toHaveLength(0); - }); + test.each(["999", "1000"])( + "create renews a spent deadline %s with the same terms", + async (deadline) => { + const created = addAction({ + kind: "create", + body: json({ + token, + amount: "10", + request: { amount: "10", nonce: "1", deadline, gameType: 0 }, + signature: "0x12", + }), + }); + await service.step(created); + const body = JSON.parse(stored(created.id).body); + expect(body).toEqual({ token, amount: "10" }); + expect(sent).toHaveLength(0); + }, + ); test("create without a stake is rejected", async () => { const created = addAction({ kind: "create", body: json({ token }) }); @@ -360,6 +416,9 @@ describe("EvmBotService.step for new actions", () => { }); await service.step(native); expect(lastSentCall().tx).toMatchObject({ to: recipient, value: 77n }); + expect(preparedTransactions).toEqual([ + expect.objectContaining({ to: recipient, value: 77n, data: "0x" }), + ]); expect(stored(native.id).phase).toBe("transaction"); const erc20 = addAction({ @@ -376,9 +435,23 @@ describe("EvmBotService.step for new actions", () => { await expect(service.step(invalid)).rejects.toThrow("Invalid withdrawal"); }); + test.each([ + { amount: "1", recipient: token }, + { recipient: token, native: true }, + { amount: "1", native: true }, + ])("refuses a withdrawal missing a required field: %p", async (body) => { + const invalid = addAction({ kind: "withdraw", body: json(body) }); + await expect(service.step(invalid)).rejects.toThrow("Invalid withdrawal"); + expect(stored(invalid.id)).toMatchObject({ phase: "new", raw: null, hash: null }); + expect(sent).toEqual([]); + }); + test("join pays the ticket, reusing a sufficient allowance and forwarding invitations", async () => { reads.getGame = () => ({ token, gameType: 0, ticketAmount: 40n }); - reads.allowance = () => 40n; + reads.allowance = ({ args }) => { + expect(args).toEqual([service.account("101").address, config.address]); + return 40n; + }; const joined = addAction({ kind: "join", body: json({ game: gameId, invitation: { deadline: "1300", signature: "0xabcd" } }), @@ -389,6 +462,7 @@ describe("EvmBotService.step for new actions", () => { expect(JSON.parse(row.body).token).toBe(token); const decoded = decodeFunctionData({ abi: timbaAbi, data: lastSentCall().tx.data! }); expect(decoded.functionName).toBe("joinGame"); + expect(decoded.args).toEqual([gameId, 1300n, "0xabcd"]); }); test("join resets a nonzero but insufficient allowance before approving", async () => { @@ -432,7 +506,7 @@ describe("EvmBotService.step for new actions", () => { expect(decoded.args?.[1]).toBe(player); expect(JSON.parse(stored(closeWithPlayer.id).body).refundingPlayer).toBe(true); - reads.getGame = () => ({ status: 0, gameType: 1, participants: [] }); + reads.getGame = () => ({ status: 0, gameType: 1, participants: [player] }); const close = addAction({ user: "103", kind: "close", body: json({ game: gameId }) }); await service.step(close); expect(decodeFunctionData({ abi: timbaAbi, data: lastSentCall().tx.data! }).functionName).toBe( @@ -440,8 +514,8 @@ describe("EvmBotService.step for new actions", () => { ); }); - test("closing an already finished game completes without a transaction", async () => { - reads.getGame = () => ({ status: 3, gameType: 1, participants: [] }); + test.each([2, 3])("closing a finished game in state %i sends no transaction", async (status) => { + reads.getGame = () => ({ status, gameType: 1, participants: [] }); const close = addAction({ kind: "close", body: json({ game: gameId }) }); await service.step(close); expect(stored(close.id).phase).toBe("done"); @@ -483,6 +557,19 @@ describe("EvmBotService.step for submitted transactions", () => { const pending = submitted(); await service.step(pending); expect(stored(pending.id).phase).toBe("transaction"); + expect(blockNumberOptions).toEqual([{ cacheTime: 0 }]); + + blockNumber = 101n; + await service.step(pending); + expect(stored(pending.id).phase).toBe("done"); + expect(blockNumberOptions).toEqual([{ cacheTime: 0 }, { cacheTime: 0 }]); + expect(sent).toEqual([]); + }); + + test("recognizes a hash-only record as an incomplete saved transaction", async () => { + const pending = submitted({ raw: null, phase: "new" }); + await expect(service.step(pending)).rejects.toThrow("Incomplete saved EVM transaction"); + expect(sent).toEqual([]); }); test("marks reverted transactions as failed", async () => { @@ -494,7 +581,10 @@ describe("EvmBotService.step for submitted transactions", () => { test("confirmed approvals restart the action once the allowance is in place", async () => { receipt = { status: "success", blockNumber: 90n }; - reads.allowance = () => 50n; + reads.allowance = ({ args }) => { + expect(args).toEqual([service.account("101").address, config.address]); + return 50n; + }; const approval = submitted({ phase: "approval", body: json({ token, approvalAmount: "50" }), @@ -533,6 +623,14 @@ describe("EvmBotService.step for submitted transactions", () => { expect(JSON.parse(row.body)).toEqual({ game: gameId }); }); + test("a confirmed direct close finishes without scheduling a second close", async () => { + receipt = { status: "success", blockNumber: 90n }; + const close = submitted({ kind: "close", body: json({ game: gameId }) }); + await service.step(close); + expect(stored(close.id).phase).toBe("done"); + expect(sent).toEqual([]); + }); + test("confirmed creations finish and record the game message", async () => { receipt = { status: "success", blockNumber: 90n }; const created = submitted({ kind: "create", body: json({ game: gameId }) }); diff --git a/src/evm/service.ts b/src/evm/service.ts index 57181304..69fc9837 100644 --- a/src/evm/service.ts +++ b/src/evm/service.ts @@ -67,7 +67,7 @@ export class EvmBotService { }); this.transport = fallback( config.rpcUrls.map((url) => http(url, { timeout: 3_000, retryCount: 0 })), - { rank: false, retryCount: 0 }, + { retryCount: 0 }, // Viem preserves the configured order unless ranking is enabled. ); this.client = createPublicClient({ chain: this.chain, transport: this.transport }); } @@ -85,7 +85,7 @@ export class EvmBotService { const response = await fetch(new URL(path, this.config.oracleUrl), { method: input === undefined ? "GET" : "POST", headers: { authorization: `Bearer ${this.apiToken}`, "content-type": "application/json" }, - body: input === undefined ? undefined : json(input), + body: json(input), signal: AbortSignal.timeout(12_000), }); if (!response.ok) throw new Error("EVM oracle request failed"); diff --git a/tests/evm.service-boundaries.test.ts b/tests/evm.service-boundaries.test.ts index da64dc8c..5aeb7710 100644 --- a/tests/evm.service-boundaries.test.ts +++ b/tests/evm.service-boundaries.test.ts @@ -64,6 +64,48 @@ test("wires the configured EVM chain and bounded RPC transport in order", () => ]); }); +test("tries providers in the configured order without background RPC probes", async () => { + const rpcUrls = ["https://first.rpc.invalid/", "https://second.rpc.invalid/"]; + const calls: Array<{ url: string; method: string }> = []; + const fakeFetch = Object.assign( + async (request: Request | URL | string, init?: RequestInit) => { + const rpcRequest = new Request(request, init); + const body: { id: number; method: string } = await rpcRequest.json(); + calls.push({ url: rpcRequest.url, method: body.method }); + if (body.method !== "eth_chainId") { + return Response.json({ jsonrpc: "2.0", id: body.id, result: true }); + } + if (rpcRequest.url === rpcUrls[0]) return new Response("offline", { status: 503 }); + return Response.json({ jsonrpc: "2.0", id: body.id, result: "0x7a69" }); + }, + { preconnect: () => {} }, + ); + const fetch = spyOn(globalThis, "fetch").mockImplementation(fakeFetch); + const realTimer = globalThis.setTimeout; + const timer = spyOn(globalThis, "setTimeout").mockImplementation( + new Proxy(realTimer, { + apply: (target, receiver, args) => + Reflect.apply(target, receiver, args[1] === 4_000 ? [() => {}, 0] : args), + }), + ); + try { + const configured = new EvmBotService( + { ...config, rpcUrls }, + "unused test mnemonic", + "fixture-token", + store, + ); + await expect(configured.client.getChainId()).resolves.toBe(31_337); + expect(calls).toEqual([ + { url: "https://first.rpc.invalid/", method: "eth_chainId" }, + { url: "https://second.rpc.invalid/", method: "eth_chainId" }, + ]); + } finally { + timer.mockRestore(); + fetch.mockRestore(); + } +}); + test.each([ ["missing hash", "transaction", "0x11", null], ["missing bytes", "transaction", null, "0x22"], @@ -135,9 +177,13 @@ test("uses the configured oracle path and sends JSON only for a request with inp try { await expect(service.oracle("/evm/config")).resolves.toEqual({ ok: true }); await expect(service.oracle("/evm/authorize", { amount: 12n })).resolves.toEqual({ ok: true }); + await expect(service.oracle("/evm/authorize", null)).resolves.toEqual({ ok: true }); + await expect(service.oracle("/evm/authorize", false)).resolves.toEqual({ ok: true }); expect(fetch.mock.calls.map(([url, init]) => [String(url), init?.method, init?.body])).toEqual([ ["https://oracle.invalid/evm/config", "GET", undefined], ["https://oracle.invalid/evm/authorize", "POST", '{"amount":"12"}'], + ["https://oracle.invalid/evm/authorize", "POST", "null"], + ["https://oracle.invalid/evm/authorize", "POST", "false"], ]); for (const [, init] of fetch.mock.calls) { expect(new Headers(init?.headers).get("content-type")).toBe("application/json"); From 80699ac929526d2d42550883d30c4af3bf2e9e03 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 19:06:32 -0300 Subject: [PATCH 168/410] test(evm): pin game card refresh and retry delays --- src/evm/bot.test.ts | 115 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 115 insertions(+) diff --git a/src/evm/bot.test.ts b/src/evm/bot.test.ts index 68d1df49..9518c1f7 100644 --- a/src/evm/bot.test.ts +++ b/src/evm/bot.test.ts @@ -890,6 +890,121 @@ describe("EVM refresh loop", () => { game.mockRestore(); }); + test.each([ + { label: "open", status: 1, withPrize: false, delay: 2_000, followUp: false }, + { + label: "completed without a result", + status: 2, + withPrize: false, + delay: 2_000, + followUp: true, + }, + { + label: "completed with a result", + status: 2, + withPrize: true, + delay: 3_600_000, + followUp: true, + }, + { label: "closed", status: 3, withPrize: false, delay: 3_600_000, followUp: false }, + ])( + "defers the unchanged $label game until its next check", + async ({ status, withPrize, delay, followUp }) => { + const start = 1_800_000_000_000; + const clock = spyOn(Date, "now").mockReturnValue(start); + const player = h.runtime.service.account("2").address; + const onChainGame = { + creator: player, + token: tokenAddress, + gameType: 1, + status, + ticketAmount: 0n, + totalAmount: 2n * 10n ** 18n, + minPlayers: 1, + maxPlayers: 5, + participants: [player], + } as unknown as Awaited>; + const game = spyOn(h.runtime.service, "game").mockResolvedValue(onChainGame); + const oracle = spyOn(h.runtime.service, "oracle").mockResolvedValue({ + events: withPrize + ? [{ event: { kind: "completed", winner: player, prize: "2000000000000000000" } }] + : [{ event: { kind: "joined" } }], + }); + try { + h.store.message({ game: gameId, chat: -100, message: 9, body: "", creator: "1" }); + await h.runtime.refresh(); + await h.runtime.refresh(); + const edits = h.calls.filter((call) => call.method === "editMessageText"); + expect(edits).toHaveLength(1); + expect(edits[0]?.payload).toMatchObject({ + chat_id: -100, + message_id: 9, + parse_mode: "HTML", + }); + if (status === 2) expect(edits[0]?.payload.text).toContain("Status: Completed"); + if (status === 3) expect(edits[0]?.payload.text).toContain("Status: Closed"); + if (withPrize) expect(edits[0]?.payload.text).toContain(`Winner: ${player}\nPrize: 2 TEST`); + else expect(edits[0]?.payload.text).not.toContain("Winner:"); + expect(oracle.mock.calls).toEqual( + followUp ? [[`/evm/games/${gameId}`], [`/evm/games/${gameId}`]] : [], + ); + + clock.mockReturnValue(start + delay - 1); + expect(h.store.messages()).toEqual([]); + clock.mockReturnValue(start + delay); + expect(h.store.messages()).toEqual([ + expect.objectContaining({ game: gameId, chat: -100, message: 9 }), + ]); + } finally { + oracle.mockRestore(); + game.mockRestore(); + clock.mockRestore(); + } + }, + ); + + test("retries a game card exactly thirty seconds after a failed edit", async () => { + const start = 1_800_000_000_000; + const clock = spyOn(Date, "now").mockReturnValue(start); + const player = h.runtime.service.account("2").address; + const onChainGame = { + creator: player, + token: tokenAddress, + gameType: 0, + status: 1, + ticketAmount: 10n ** 18n, + totalAmount: 2n * 10n ** 18n, + minPlayers: 2, + maxPlayers: 4, + participants: [player], + } as unknown as Awaited>; + const game = spyOn(h.runtime.service, "game").mockResolvedValue(onChainGame); + try { + h.store.message({ game: gameId, chat: -100, message: 9, body: "old card", creator: "1" }); + h.failApi(new Error("Telegram offline")); + await h.runtime.refresh(); + h.failApi(); + + clock.mockReturnValue(start + 29_999); + await h.runtime.refresh(); + expect(game).toHaveBeenCalledTimes(1); + clock.mockReturnValue(start + 30_000); + expect(h.store.messages()).toEqual([expect.objectContaining({ body: "old card" })]); + await h.runtime.refresh(); + + const edits = h.calls.filter((call) => call.method === "editMessageText"); + expect(edits).toHaveLength(2); + expect(edits[1]?.payload.text).toBe(edits[0]?.payload.text); + expect(h.store.messages()).toEqual([ + expect.objectContaining({ body: edits[1]?.payload.text }), + ]); + } finally { + h.failApi(); + game.mockRestore(); + clock.mockRestore(); + } + }); + test("an unavailable oracle is logged once per minute", async () => { h.metadata.mockRejectedValue(new Error("offline")); const warn = spyOn(console, "warn").mockImplementation(() => {}); From 1231728cb7e6b65fc9783862d5823e493fc5be55 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 19:08:30 -0300 Subject: [PATCH 169/410] test(finance): keep exact referral balances and account routing --- tests/finance-ledger.events.test.ts | 45 ++++++++++++++++++++++++++++ tests/finance-ledger.parsing.test.ts | 29 ++++++++++++++++++ 2 files changed, 74 insertions(+) diff --git a/tests/finance-ledger.events.test.ts b/tests/finance-ledger.events.test.ts index 7f3e69de..ec444b66 100644 --- a/tests/finance-ledger.events.test.ts +++ b/tests/finance-ledger.events.test.ts @@ -589,6 +589,51 @@ describe("finance snapshot", () => { expect(snapshot.swapClaimable).toEqual([{ mint: MINT.toBase58(), amountRaw: 25n }]); }); + test("uses listed legacy and Token-2022 balances without fetching the same account again", async () => { + __test_setReferralConfig({ + referralAccount: REFERRAL.toBase58(), + buildFeeAccount: BUILD_FEE.toBase58(), + }); + const history = createHistory(null, { total: 2, completed: 2 }); + const requestedAccounts: string[] = []; + const directlyFetched: string[] = []; + const snapshot = await serviceFor( + history, + { + getParsedAccountInfo: async (account: PublicKey) => { + directlyFetched.push(account.toBase58()); + return { value: null }; + }, + }, + { + referralReader: { + getReferralTokenAccountsV2: async (referral: string) => { + requestedAccounts.push(referral); + return { + tokenAccounts: [ + { pubkey: REFERRAL_TOKEN, account: { mint: MINT, amount: 25n } }, + { pubkey: PLAYER, account: { mint: PLAYER, amount: 0n } }, + ], + token2022Accounts: [ + { pubkey: BUILD_FEE, account: { mint: GAME, amount: 9_007_199_254_740_993n } }, + ], + }; + }, + }, + }, + ).getSnapshot(); + + expect(requestedAccounts).toEqual([REFERRAL.toBase58()]); + expect(directlyFetched).toEqual([]); + expect(snapshot).toMatchObject({ + coverage: "complete", + swapClaimable: [ + { mint: MINT.toBase58(), amountRaw: 25n }, + { mint: GAME.toBase58(), amountRaw: 9_007_199_254_740_993n }, + ], + }); + }); + test("falls back to empty balances when claimable lookups fail", async () => { const history = createHistory(null, { total: 2, completed: 2 }); const failingReader = { diff --git a/tests/finance-ledger.parsing.test.ts b/tests/finance-ledger.parsing.test.ts index 1dd68b4d..8ef6a46c 100644 --- a/tests/finance-ledger.parsing.test.ts +++ b/tests/finance-ledger.parsing.test.ts @@ -35,6 +35,35 @@ describe("referral delta amount parsing", () => { delta: -10n, }); }); + + test.each([ + [ + "only the post amount is present", + undefined, + { amount: "9007199254740993" }, + 9_007_199_254_740_993n, + ], + [ + "only the pre amount is present", + { amount: "9007199254740993" }, + undefined, + -9_007_199_254_740_993n, + ], + [ + "both sides exceed safe number precision", + { amount: "9007199254740992" }, + { amount: "9007199254740993" }, + 1n, + ], + ])("keeps the exact referral delta when %s", (_label, pre, post, delta) => { + const transaction = tokenTransaction("0", "0"); + transaction.meta.preTokenBalances[0].uiTokenAmount = pre; + transaction.meta.postTokenBalances[0].uiTokenAmount = post; + expect(referralDeltaFromTransaction(transaction, ACCOUNT.toBase58())).toEqual({ + mint: MINT, + delta, + }); + }); }); describe("program event identifiers", () => { From 299fe4cda3b1a990025ef335f99c432120103178 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 19:13:57 -0300 Subject: [PATCH 170/410] fix(settings): bind join-rate input to the delivered prompt --- src/handlers/chat-defaults.ts | 19 +++++----- tests/chat-defaults.handler.test.ts | 56 ++++++++++++++++++++++++++++- 2 files changed, 65 insertions(+), 10 deletions(-) diff --git a/src/handlers/chat-defaults.ts b/src/handlers/chat-defaults.ts index 7bad1710..435fe79e 100644 --- a/src/handlers/chat-defaults.ts +++ b/src/handlers/chat-defaults.ts @@ -1152,19 +1152,20 @@ export const createChatDefaultsModule = (deps: ChatDefaultsModuleDeps): ChatDefa if (!(await checkCallbackAdmin(ctx, deps))) return; const keyboard = new InlineKeyboard().text("← Back", "chat_defaults_cancel"); - await respondWithMenu(ctx, { + const { messageId, chatId } = await respondWithMenu(ctx, { text: `Enter a custom rate limit (0-${MAX_JOIN_NOTIFICATIONS_PER_MINUTE} per minute):`, keyboard, }); - const telegramIdStr = getTelegramIdString(ctx); - setInputSession(`${ctx.chat.id}_${ctx.callbackQuery?.message?.message_id}`, { - type: "chat_defaults", - target: "join_rate_custom", - chatId: ctx.chat.id, - messageId: ctx.callbackQuery?.message?.message_id, - initiatorId: telegramIdStr, - }); + if (messageId != null && chatId != null) { + setInputSession(`${chatId}_${messageId}`, { + type: "chat_defaults", + target: "join_rate_custom", + chatId, + messageId, + initiatorId: getTelegramIdString(ctx), + }); + } await safeAnswerCallbackQuery(ctx); }), ); diff --git a/tests/chat-defaults.handler.test.ts b/tests/chat-defaults.handler.test.ts index 09a72478..644bffb6 100644 --- a/tests/chat-defaults.handler.test.ts +++ b/tests/chat-defaults.handler.test.ts @@ -1,4 +1,4 @@ -import { beforeEach, describe, expect, test } from "bun:test"; +import { beforeEach, describe, expect, spyOn, test } from "bun:test"; import { Bot } from "grammy"; import { createChatDefaultsModule, @@ -12,6 +12,7 @@ import { resetTestDatabase } from "./helpers/database"; import { clearAllInputSessions, findInputSession, + getInputSession, type InputSessionState, } from "../src/utils/user-state"; @@ -1754,6 +1755,59 @@ describe("chat defaults menus and inputs", () => { }); }); + test.each([ + { label: "an editable menu", edited: true, delivered: true, id: 11 }, + { label: "a fallback reply", edited: false, delivered: true, id: 50 }, + { label: "a missing reply receipt", edited: false, delivered: false, id: null }, + ])("routes the join-rate input after $label", async ({ edited, delivered, id }) => { + const h = setup(); + const callback = "chat_defaults_set_join_rate_custom"; + const ctx = h.ctxFor(callback); + if (edited) { + ctx.editMessageText = (text: string, options: unknown) => + ctx.api.editMessageText(99, 11, text, options); + } else { + ctx.api.editMessageText = async () => { + throw new Error("message cannot be edited"); + }; + ctx.editMessageText = ctx.api.editMessageText; + } + if (!delivered) ctx.reply = async () => ({}); + + const warn = spyOn(console, "warn").mockImplementation(() => {}); + try { + expect(await h.mockBot.dispatch(callback, ctx)).toBe(true); + expect(warn).toHaveBeenCalledTimes(edited ? 0 : 1); + } finally { + warn.mockRestore(); + } + + expect(h.answers).toEqual([undefined]); + if (id !== 11) expect(getInputSession("99_11")).toBeUndefined(); + if (id === null) { + expect(promptSession()).toBeUndefined(); + expect(chatDb.getChatGameSettings(99)).toBeNull(); + return; + } + + expect(h.lastMenu().text).toBe("Enter a custom rate limit (0-30 per minute):"); + expect(h.lastCallbacks()).toEqual(["chat_defaults_cancel"]); + const input = getInputSession(`99_${id}`); + expect(input).toMatchObject({ + type: "chat_defaults", + target: "join_rate_custom", + chatId: 99, + messageId: id, + initiatorId: "123", + }); + if (!input) throw new Error("Expected the confirmed prompt to have an input session"); + await h.module.handleSettingsInput(h.ctxFor(), input, "12"); + expect(chatDb.getChatGameSettings(99)).toMatchObject({ + join_notifications_per_minute: 12, + set_by_telegram_id: "123", + }); + }); + test("cancel closes the prompt and returns to the menu", async () => { const h = setup(); await h.press("chat_defaults_timeout"); From e7565a96bfe1c51736ce032e643f1e8430837cfa Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 19:16:10 -0300 Subject: [PATCH 171/410] test(games): check timeout button bounds and snap ties --- tests/keyboards.test.ts | 44 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) diff --git a/tests/keyboards.test.ts b/tests/keyboards.test.ts index 030fdadd..94d6c4b0 100644 --- a/tests/keyboards.test.ts +++ b/tests/keyboards.test.ts @@ -443,6 +443,50 @@ describe("keyboards: player selection and confirm", () => { expect(texts).toContain("Min 2"); expect(texts).toContain("MAX"); }); + + test.each([ + [5, [null, null, null, 5, 5], [55, 355, 715, 1435]], + [10, [-5, null, null, 5, 10], [50, 350, 710, 1430]], + [15, [-5, -5, null, 5, 15], [45, 345, 705, 1425]], + [60, [-30, -15, null, 30, 60], [null, 300, 660, 1380]], + [1080, [-600, -360, null, 360, 360], [-1020, -720, -360, 360]], + [1440, [-720, -360, null, null, null], [-1380, -1080, -720, null]], + ] as const)("encodes the timeout controls at %i minutes", (minutes, multipliers, presets) => { + const keyboard = createGameConfirmKeyboard("coinflip", "30", "6", "318", { + timeoutSeconds: minutes * 60, + }); + const [confirm, multiplierRow, presetRow] = keyboard.inline_keyboard; + expect(confirm).toHaveLength(1); + expect(multiplierRow).toHaveLength(multipliers.length); + expect(presetRow).toHaveLength(presets.length); + + const create = confirm?.[0]; + if (!create || !("callback_data" in create)) throw new Error("Missing game confirmation"); + expect(decodeGameConfirmPayload(create.callback_data)).toMatchObject({ + timeoutSeconds: minutes * 60, + creatorId: "318", + }); + + for (const [row, deltas] of [ + [multiplierRow, multipliers], + [presetRow, presets], + ] as const) { + for (const [index, deltaMinutes] of deltas.entries()) { + const button = row?.[index]; + if (!button || !("callback_data" in button)) throw new Error("Missing timeout control"); + if (deltaMinutes === null) expect(button.callback_data).toBe("noop"); + else { + expect(decodeTimeoutChangePayload(button.callback_data)).toEqual({ + gameType: "coinflip", + amount: "30", + players: 6, + deltaMinutes, + creatorId: "318", + }); + } + } + } + }); }); describe("keyboards: callback overflow protection", () => { From 1bb5e3838149ee29d2687b5851444c9e8486e7d5 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 19:18:06 -0300 Subject: [PATCH 172/410] fix(games): avoid infinite stake suggestions from price rounding --- src/utils/keyboards.ts | 3 ++- tests/keyboards.test.ts | 27 +++++++++++++++++++++++++++ 2 files changed, 29 insertions(+), 1 deletion(-) diff --git a/src/utils/keyboards.ts b/src/utils/keyboards.ts index a1456018..84de820a 100644 --- a/src/utils/keyboards.ts +++ b/src/utils/keyboards.ts @@ -158,7 +158,8 @@ const roundToPrecision = (value: number, precision: number): number => { if (precision <= 0) return Math.round(value); const factor = Math.pow(10, precision); - return Math.round(value * factor) / factor; + const scaled = value * factor; + return Number.isFinite(scaled) ? Math.round(scaled) / factor : 0; }; const withCreatorSuffix = (base: string, creatorId?: string): string => diff --git a/tests/keyboards.test.ts b/tests/keyboards.test.ts index 94d6c4b0..d79635f5 100644 --- a/tests/keyboards.test.ts +++ b/tests/keyboards.test.ts @@ -11,6 +11,7 @@ import { createPlayerSelectionKeyboard, createGameConfirmKeyboard, getFeeWarningMessage, + getSuggestedStakeAmounts, } from "../src/utils/keyboards"; import { decodeGameConfirmPayload, @@ -351,6 +352,32 @@ describe("keyboards: amount selection", () => { expect(callbacks).toEqual(expected); }); + test.each([undefined, 0, -0, -0.01, NaN, Infinity])( + "uses the exact token minimum and multipliers when the USD price is %p", + (tokenPriceUSD) => { + const keyboard = createAmountSelectionKeyboard("coinflip", undefined, undefined, 20, { + tokenPriceUSD, + }); + expect( + extractCallbacks(keyboard).filter((value) => value.startsWith("amount_coinflip_")), + ).toEqual(expectedDefaultCallbacks); + expect(extractTexts(keyboard).filter((value) => value.includes("$"))).toEqual([]); + }, + ); + + test("offers only the minimum when rounding USD tiers overflows", () => { + const tokenPriceUSD = 1e-308; + expect(getSuggestedStakeAmounts(20, undefined, tokenPriceUSD)).toEqual([{ amount: 20 }]); + const keyboard = createAmountSelectionKeyboard("coinflip", undefined, undefined, 20, { + tokenPriceUSD, + }); + expect(extractCallbacks(keyboard)).toEqual([ + "amount_coinflip_20", + "custom_amount_coinflip", + "cancel_game_setup", + ]); + }); + test("minimum bet button renders USD equivalent when price is provided", () => { const kb = createAmountSelectionKeyboard("coinflip", undefined, undefined, 20, { decimals: 2, From e88428da83045a601eae231e0ff208c11b817a71 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 19:26:57 -0300 Subject: [PATCH 173/410] fix(wallet): avoid replacing transactions with unknown outcomes --- src/utils/transaction-runner.ts | 16 +++++-- src/utils/wallet.ts | 21 +++++---- tests/transaction-runner.test.ts | 74 +++++++++++++++++++++++++++++++ tests/wallet.resubmit.test.ts | 33 +++++++++++++- tests/wallet.transactions.test.ts | 37 ++++++++++++++++ 5 files changed, 167 insertions(+), 14 deletions(-) diff --git a/src/utils/transaction-runner.ts b/src/utils/transaction-runner.ts index 80063a55..48c8bedb 100644 --- a/src/utils/transaction-runner.ts +++ b/src/utils/transaction-runner.ts @@ -1,4 +1,4 @@ -import type { WalletManager } from "./wallet"; +import { TransactionOutcomeUnknownError, type WalletManager } from "./wallet"; import { TRANSACTION_RESUBMIT_ATTEMPTS } from "./constants"; const CONFIRMATION_RETRY_DELAYS_MS = [2000, 4000, 8000, 12000, 16000, 20000]; @@ -125,7 +125,9 @@ export const confirmTransactionWithRecovery = async ( console.warn(`⚠️ ${operationLabel} confirmation failed: ${String(detail ?? confirmError)}`); const normalizedMessage = typeof detail === "string" ? detail.toLowerCase() : undefined; + const outcomeUnknown = confirmError instanceof TransactionOutcomeUnknownError; const shouldRecover = + outcomeUnknown || normalizedMessage?.includes("timeout") || normalizedMessage?.includes("timed out") || normalizedMessage?.includes("not confirmed") || @@ -133,8 +135,9 @@ export const confirmTransactionWithRecovery = async ( normalizedMessage?.includes("last valid block height"); let lastRecoveryError: Error | undefined; + let recoveryFailure = confirmError; - if (shouldRecover && resubmit) { + if (shouldRecover && !outcomeUnknown && resubmit) { for (let attempt = 0; attempt < TRANSACTION_RESUBMIT_ATTEMPTS; attempt++) { const attemptLabel = `${attempt + 1}/${TRANSACTION_RESUBMIT_ATTEMPTS}`; try { @@ -168,11 +171,16 @@ export const confirmTransactionWithRecovery = async ( currentSignature = latestSignature; } - lastRecoveryError = normalizedError; console.error( `❌ ${operationLabel} resubmission ${attemptLabel} failed`, normalizedError, ); + if (resubmitError instanceof TransactionOutcomeUnknownError) { + currentSignature = resubmitError.signature; + recoveryFailure = resubmitError; + break; + } + lastRecoveryError = normalizedError; } } } @@ -237,7 +245,7 @@ export const confirmTransactionWithRecovery = async ( } const timeoutError: TimeoutErrorWithRecovery = - confirmError instanceof Error ? confirmError : new Error(String(confirmError)); + recoveryFailure instanceof Error ? recoveryFailure : new Error(String(recoveryFailure)); if (recoveryErrors.length > 0) { timeoutError.recoveryErrors = recoveryErrors; } diff --git a/src/utils/wallet.ts b/src/utils/wallet.ts index 4adcf039..7faf0b4c 100644 --- a/src/utils/wallet.ts +++ b/src/utils/wallet.ts @@ -2379,7 +2379,9 @@ export class WalletManager { now: number, force: boolean = false, ): Promise => { - if (!trackedSignature) { + // The blockhash deadline only rules out a transaction that has not landed. + // A processed status can still confirm even when a later RPC read is empty. + if (!trackedSignature || firstStatusObservedAt !== null) { return null; } @@ -3044,14 +3046,15 @@ export class WalletManager { return currentSignature; } catch (error: any) { const normalizedMessage = error?.message?.toLowerCase?.() ?? ""; - const isRecoverable = - normalizedMessage.includes("timeout") || - normalizedMessage.includes("timed out") || - normalizedMessage.includes("not confirmed") || - normalizedMessage.includes("expired before confirmation") || - normalizedMessage.includes("last valid block height"); - - if (!isRecoverable || resubmitAttempts >= resubmitLimit) { + const shouldResubmit = + !(error instanceof TransactionOutcomeUnknownError) && + (normalizedMessage.includes("timeout") || + normalizedMessage.includes("timed out") || + normalizedMessage.includes("not confirmed") || + normalizedMessage.includes("expired before confirmation") || + normalizedMessage.includes("last valid block height")); + + if (!shouldResubmit || resubmitAttempts >= resubmitLimit) { const failure = error instanceof Error ? error diff --git a/tests/transaction-runner.test.ts b/tests/transaction-runner.test.ts index 0d6f13b7..89d48ddc 100644 --- a/tests/transaction-runner.test.ts +++ b/tests/transaction-runner.test.ts @@ -13,6 +13,7 @@ import { confirmTransactionWithRecovery, getConfirmationRetryDelays, } from "../src/utils/transaction-runner"; +import { TransactionOutcomeUnknownError } from "../src/utils/wallet"; type Status = { err?: unknown; confirmationStatus?: string; confirmations?: unknown } | null; @@ -318,6 +319,79 @@ describe("confirmTransactionWithRecovery", () => { ]); }); + test("keeps checking the original signature when its outcome is unknown", async () => { + const { wallet, statusCalls } = makeWallet({ + confirm: async (signature) => { + throw new TransactionOutcomeUnknownError(signature, "Transaction confirmation timeout"); + }, + statuses: (signature) => + signature === "original" ? { confirmationStatus: "confirmed" } : null, + }); + const resubmit = mock(async () => "replacement"); + await expect( + confirmTransactionWithRecovery({ + wallet, + initialSignature: "original", + operationLabel: "Player join", + resubmit, + retryDelays: [0], + }), + ).resolves.toBe("original"); + expect(resubmit).not.toHaveBeenCalled(); + expect(statusCalls).toEqual(["original"]); + }); + + test("does not replace an already retried transaction with an unknown outcome", async () => { + const pending = new TransactionOutcomeUnknownError( + "replacement", + "Transaction confirmation timeout", + ); + const { wallet, statusCalls } = makeWallet({ + confirm: async (signature) => { + if (signature === "original") throw new Error("Transaction expired before confirmation"); + throw pending; + }, + }); + const resubmit = mock(async (attempt: number, _previous: string) => + attempt === 0 ? "replacement" : "another", + ); + await expect( + confirmTransactionWithRecovery({ + wallet, + initialSignature: "original", + operationLabel: "Player join", + resubmit, + retryDelays: [0], + }), + ).rejects.toBe(pending); + expect(resubmit.mock.calls).toEqual([[0, "original"]]); + expect(statusCalls).toEqual(["replacement"]); + }); + + test("reads the signature from a resubmission that did not return normally", async () => { + const { wallet, statusCalls } = makeWallet({ + confirm: async () => { + throw new Error("Transaction expired before confirmation"); + }, + statuses: (signature) => + signature === "new-signature" ? { confirmationStatus: "confirmed" } : null, + }); + const resubmit = mock(async (_attempt: number, _previous: string) => { + throw new TransactionOutcomeUnknownError("new-signature", "Status unknown after send"); + }); + await expect( + confirmTransactionWithRecovery({ + wallet, + initialSignature: "expired", + operationLabel: "Player join", + resubmit, + retryDelays: [0], + }), + ).resolves.toBe("new-signature"); + expect(resubmit.mock.calls).toEqual([[0, "expired"]]); + expect(statusCalls).toEqual(["new-signature"]); + }); + test.each([ [ "structured signature", diff --git a/tests/wallet.resubmit.test.ts b/tests/wallet.resubmit.test.ts index 3d7f0037..197903d9 100644 --- a/tests/wallet.resubmit.test.ts +++ b/tests/wallet.resubmit.test.ts @@ -1,6 +1,6 @@ import { afterEach, beforeEach, describe, expect, spyOn, test } from "bun:test"; import { Connection, Keypair, PublicKey, TransactionInstruction } from "#solana"; -import { WalletManager } from "../src/utils/wallet"; +import { TransactionOutcomeUnknownError, WalletManager } from "../src/utils/wallet"; import { stubInstantTimers } from "./helpers/timers"; // Retry/backoff/poll sleeps are not under test here; run them instantly. @@ -72,6 +72,37 @@ describe("WalletManager sendAndConfirmWithResubmits", () => { expect(observedSignatures).toEqual(["SIG1", "SIG2"]); }); + test("does not sign again when confirmation could not determine the original outcome", async () => { + const wallet = WalletManager.createForTest(MNEMONIC, { + connection: new ResubmitConnection() as unknown as Connection, + }); + const pending = new TransactionOutcomeUnknownError( + "initial", + "Transaction confirmation timeout", + ); + const confirm = spyOn(wallet, "confirmTransaction") + .mockResolvedValue(undefined) + .mockRejectedValueOnce(pending); + const send = spyOn(wallet, "sendTransaction").mockResolvedValue("replacement"); + const ix = new TransactionInstruction({ + programId: PublicKey.default, + keys: [], + data: Buffer.alloc(0), + }); + const signer = await Keypair.generate(); + try { + await expect( + wallet.sendAndConfirmWithResubmits([ix], [signer], { initialSignature: "initial" }), + ).rejects.toBe(pending); + expect(pending).toMatchObject({ lastSignature: "initial" }); + expect(confirm.mock.calls).toEqual([["initial"]]); + expect(send).not.toHaveBeenCalled(); + } finally { + send.mockRestore(); + confirm.mockRestore(); + } + }); + test.each([1, 0.5])("surfaces error after exhausting %p resubmits", async (maxResubmits) => { const connection = new ResubmitConnection(); const wallet = WalletManager.createForTest(MNEMONIC, { diff --git a/tests/wallet.transactions.test.ts b/tests/wallet.transactions.test.ts index 6bbe281e..3a72be49 100644 --- a/tests/wallet.transactions.test.ts +++ b/tests/wallet.transactions.test.ts @@ -658,6 +658,43 @@ describe("confirmTransaction polling", () => { } }); + test.each(["first poll", "final check"] as const)( + "looks up the original signature after a processed status on the %s", + async (observedAt) => { + const signature = "SIG_LATE_LANDED"; + const readConfirmed = spyOn({ lookup: async () => ({ meta: { err: null } }) }, "lookup"); + let elapsed = () => 0; + const { wallet, clock } = lateStatus(null, { + getSignatureStatuses: async () => ({ + value: [ + (observedAt === "first poll" && elapsed() === 0) || + (observedAt === "final check" && elapsed() >= CONFIRMATION_TIMEOUT_MS) + ? { confirmationStatus: "processed", confirmations: 0 } + : null, + ], + }), + getBlockHeight: async () => + observedAt === "first poll" || elapsed() >= CONFIRMATION_TIMEOUT_MS ? 200 : 50, + getTransaction: readConfirmed, + }); + elapsed = clock.elapsed; + (wallet as any).pendingSignatures.set(signature, { + blockhash: "BH", + lastValidBlockHeight: 100, + recordedAt: Date.now(), + }); + try { + await expect(wallet.confirmTransaction(signature)).resolves.toBeUndefined(); + expect(readConfirmed).toHaveBeenCalledWith(signature, { commitment: "confirmed" }); + expect(readConfirmed).toHaveBeenCalledTimes(1); + expect(clock.elapsed()).toBeGreaterThanOrEqual(CONFIRMATION_TIMEOUT_MS); + } finally { + clock.restore(); + readConfirmed.mockRestore(); + } + }, + ); + test("a blockhash that expired during the window is reported", async () => { let elapsed = () => 0; const { wallet, clock } = lateStatus(null, { From ee4f783794780533ab4524ecea8a8874c76ea064 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 19:29:29 -0300 Subject: [PATCH 174/410] fix(wallet): check transaction history when the final RPC times out --- src/utils/wallet.ts | 37 +++++++++++---- tests/wallet.transactions.test.ts | 78 +++++++++++++++++++++++++++++++ 2 files changed, 106 insertions(+), 9 deletions(-) diff --git a/src/utils/wallet.ts b/src/utils/wallet.ts index 7faf0b4c..2d9b47b7 100644 --- a/src/utils/wallet.ts +++ b/src/utils/wallet.ts @@ -2336,6 +2336,15 @@ export class WalletManager { ); const hasStatusesMethod = typeof boundGetSignatureStatuses === "function"; + const isTransientStatusLookupError = (error: unknown): boolean => { + const detail = (error as { message?: unknown } | null | undefined)?.message; + if (typeof detail !== "string") return false; + const message = detail.toLowerCase(); + return ( + message.includes("429") || message.includes("timeout") || message.includes("timed out") + ); + }; + const fetchStatus = async (useHistory: boolean) => { if (hasStatusesMethod) { const response = await boundGetSignatureStatuses( @@ -2435,11 +2444,8 @@ export class WalletManager { let status: any = null; try { status = await fetchStatus(shouldUseHistory); - } catch (error: any) { - if ( - typeof error?.message === "string" && - (error.message.includes("429") || error.message.includes("timeout")) - ) { + } catch (error) { + if (isTransientStatusLookupError(error)) { networkRetryCount += 1; console.warn( `⚠️ Network issue checking ${signature} (poll ${pollCount}, ${elapsed}ms), retrying with longer delay`, @@ -2517,7 +2523,17 @@ export class WalletManager { } console.log(`🔄 Performing final status check for ${signature} after ${pollCount} polls`); - const finalStatus = await fetchStatus(true); + const { status: finalStatus, available: finalStatusAvailable } = await fetchStatus(true).then( + (status) => ({ status, available: true }), + (error: unknown) => { + if (!isTransientStatusLookupError(error)) throw error; + networkRetryCount += 1; + console.warn( + `⚠️ Final status lookup unavailable for ${signature}, checking transaction history`, + ); + return { status: null, available: false }; + }, + ); const finalNow = Date.now(); if (finalStatus) { @@ -2551,9 +2567,12 @@ export class WalletManager { ); } - const finalExpirationMessage = await checkForExpiration(finalNow, true); - if (finalExpirationMessage) { - throw new Error(finalExpirationMessage); + // A failed RPC request is not an empty status. Verify from history first. + if (finalStatusAvailable) { + const finalExpirationMessage = await checkForExpiration(finalNow, true); + if (finalExpirationMessage) { + throw new Error(finalExpirationMessage); + } } } finally { this.pendingSignatures.delete(signature); diff --git a/tests/wallet.transactions.test.ts b/tests/wallet.transactions.test.ts index 3a72be49..bb92e17b 100644 --- a/tests/wallet.transactions.test.ts +++ b/tests/wallet.transactions.test.ts @@ -547,6 +547,28 @@ describe("confirmTransaction polling", () => { expect(logged[1]).toContain("plain failure"); }); + test.each(["RPC timeout", "RPC request Timed Out", "RPC status 429"])( + "backs off the same signature after %s", + async (message) => { + const calls: string[][] = []; + const wallet = walletWith({ + getSignatureStatuses: async (signatures: string[]) => { + calls.push(signatures); + if (calls.length === 1) throw new Error(message); + return { value: [{ confirmationStatus: "confirmed" }] }; + }, + }); + const clock = useWalletConfirmationClock(wallet); + try { + await wallet.confirmTransaction("SIG_RPC_RETRY"); + expect(calls).toEqual([["SIG_RPC_RETRY"], ["SIG_RPC_RETRY"]]); + expect(clock.delays).toEqual([800]); + } finally { + clock.restore(); + } + }, + ); + test("allows two blocks of grace but rejects the next block if no status is found", async () => { const heights: number[] = []; let elapsed = () => 0; @@ -715,6 +737,62 @@ describe("confirmTransaction polling", () => { } }); + test.each([true, false])( + "checks history when the last RPC timed out and the signature is found=%p", + async (confirmed) => { + const signature = "SIG_LAST_READ_TIMEOUT"; + const history = spyOn( + { lookup: async () => (confirmed ? { meta: { err: null } } : null) }, + "lookup", + ); + let elapsed = () => 0; + const { wallet, clock } = lateStatus(null, { + getSignatureStatuses: async () => { + if (elapsed() >= CONFIRMATION_TIMEOUT_MS) throw new Error("RPC request timed out"); + return { value: [null] }; + }, + getBlockHeight: async () => (elapsed() >= CONFIRMATION_TIMEOUT_MS ? 200 : 50), + getTransaction: history, + }); + elapsed = clock.elapsed; + (wallet as any).pendingSignatures.set(signature, { + blockhash: "BH", + lastValidBlockHeight: 100, + recordedAt: Date.now(), + }); + try { + const observation = wallet.confirmTransaction(signature); + if (confirmed) await expect(observation).resolves.toBeUndefined(); + else await expect(observation).rejects.toBeInstanceOf(TransactionOutcomeUnknownError); + expect(history).toHaveBeenCalledWith(signature, { commitment: "confirmed" }); + expect(history).toHaveBeenCalledTimes(1); + expect(messages(warnSpy)).toContain( + `⚠️ Final status lookup unavailable for ${signature}, checking transaction history`, + ); + } finally { + history.mockRestore(); + clock.restore(); + } + }, + ); + + test("preserves a non-transient error from the final provider read", async () => { + const error = new TypeError("invalid provider result"); + let elapsed = () => 0; + const { wallet, clock } = lateStatus(null, { + getSignatureStatuses: async () => { + if (elapsed() >= CONFIRMATION_TIMEOUT_MS) throw error; + return { value: [null] }; + }, + }); + elapsed = clock.elapsed; + try { + await expect(wallet.confirmTransaction("SIG_INVALID_PROVIDER")).rejects.toBe(error); + } finally { + clock.restore(); + } + }); + test("a transaction found failed by the probe is reported as failed", async () => { const { wallet, clock } = lateStatus(null, { getTransaction: async () => ({ meta: { err: { Custom: 1 } } }), From e20692897ca7412a72fa9ac55a2e22536cbf0308 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 19:33:44 -0300 Subject: [PATCH 175/410] test(wallet): cover partial parsed mint responses and precision limits --- tests/wallet.transactions.test.ts | 66 ++++++++++++++++++++++++------- 1 file changed, 52 insertions(+), 14 deletions(-) diff --git a/tests/wallet.transactions.test.ts b/tests/wallet.transactions.test.ts index bb92e17b..b22ac9d5 100644 --- a/tests/wallet.transactions.test.ts +++ b/tests/wallet.transactions.test.ts @@ -222,20 +222,27 @@ describe("token metadata lookups", () => { const decimalsOf = (wallet: WalletManager, mint: string) => (wallet as any).fetchMintDecimals(mint) as Promise; - test("prefers the parsed account info when the RPC provides it", async () => { - const wallet = walletWith({ - getParsedAccountInfo: async () => ({ - value: { data: { parsed: { info: { decimals: 4 } } } }, - }), - getAccountInfo: async () => { - throw new Error("must not be reached"); - }, - }); + test.each([0, 4, 255])( + "prefers parsed mint precision %i without a raw read", + async (decimals) => { + const mint = newMint(); + const parsedReads: string[] = []; + const wallet = walletWith({ + getParsedAccountInfo: async (key: PublicKey) => { + parsedReads.push(key.toBase58()); + return { value: { data: { parsed: { info: { decimals } } } } }; + }, + getAccountInfo: async () => { + throw new Error("must not be reached"); + }, + }); - expect(await decimalsOf(wallet, newMint())).toBe(4); - }); + expect(await decimalsOf(wallet, mint)).toBe(decimals); + expect(parsedReads).toEqual([mint]); + }, + ); - test("falls back to the raw mint account when parsed info fails or lacks decimals", async () => { + test("falls back to the raw mint account when the parsed read fails", async () => { const mint = newMint(); const connection: Record = { getParsedAccountInfo: async () => { @@ -249,10 +256,41 @@ describe("token metadata lookups", () => { expect( messages(warnSpy).some((line) => line.includes("Parsed account metadata unavailable")), ).toBe(true); + }); - connection["getParsedAccountInfo"] = async () => ({ value: null }) as any; - expect(await decimalsOf(wallet, mint)).toBe(9); + const parsedMint = (decimals: unknown) => ({ + value: { data: { parsed: { info: { decimals } } } }, }); + test.each([ + ["no response", null], + ["no value", { value: null }], + ["no data", { value: { data: null } }], + ["no parsed data", { value: { data: { parsed: null } } }], + ["no info", { value: { data: { parsed: { info: null } } } }], + ["no decimals", parsedMint(undefined)], + ["negative decimals", parsedMint(-1)], + ["fractional decimals", parsedMint(1.5)], + ["precision past the mint byte", parsedMint(256)], + ["numeric text", parsedMint("7")], + ["overflowed precision", parsedMint(Infinity)], + ])( + "reads the raw mint once for %s without treating it as an RPC exception", + async (_label, response) => { + const mint = newMint(); + const rawReads: string[] = []; + const wallet = walletWith({ + getParsedAccountInfo: async () => response, + getAccountInfo: async (key: PublicKey) => { + rawReads.push(key.toBase58()); + return mintAccount(9); + }, + }); + + expect(await decimalsOf(wallet, mint)).toBe(9); + expect(rawReads).toEqual([mint]); + expect(warnSpy).not.toHaveBeenCalled(); + }, + ); test("reports connections that cannot read accounts", async () => { await expect(decimalsOf(walletWith({}), newMint())).rejects.toThrow( From 6803583d6f2e261d1f4e13e16102dee92a38977e Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 19:37:35 -0300 Subject: [PATCH 176/410] fix(tokens): convert fiat with the full quoted price before rounding --- src/utils/token-manager.ts | 30 +++++---------- tests/token-manager.amounts.test.ts | 57 ++++++++++++++++++++++++++++- 2 files changed, 66 insertions(+), 21 deletions(-) diff --git a/src/utils/token-manager.ts b/src/utils/token-manager.ts index 3eb6988c..6f657b02 100644 --- a/src/utils/token-manager.ts +++ b/src/utils/token-manager.ts @@ -578,33 +578,23 @@ export class TokenManager { const price = priceLookup?.price ?? 0; const USD_MICROS = 1_000_000n; - const MAX_SAFE = Number.MAX_SAFE_INTEGER; - const PRICE_SCALE_CANDIDATES = [ - 1_000_000_000_000_000, 100_000_000_000_000, 10_000_000_000_000, 1_000_000_000_000, - 100_000_000_000, 10_000_000_000, 1_000_000_000, 100_000_000, 10_000_000, 1_000_000, 100_000, - 10_000, 1_000, 100, 10, 1, - ] as const; - - if (!priceLookup?.price || !Number.isFinite(price) || price <= 0) { + // Keep the existing minimum usable quote, even though conversion now keeps its full precision. + if (!priceLookup || !Number.isFinite(price) || price * 1e15 < 0.5) { return { ok: false, reason: "unsupported_token" }; } - const selectedScale = - PRICE_SCALE_CANDIDATES.find((candidate) => { - const scaled = price * candidate; - return Number.isFinite(scaled) && scaled > 0 && scaled <= MAX_SAFE; - }) ?? 1; - - const scaledPriceNumber = Math.round(price * selectedScale); - if (!Number.isFinite(scaledPriceNumber) || scaledPriceNumber <= 0) { - return { ok: false, reason: "unsupported_token" }; - } + // Preserve the decimal quote and floor only when converting to whole token units. + const [coefficient = "", exponent = "0"] = price.toString().split("e"); + const [integer = "", fraction = ""] = coefficient.split("."); + const priceDigits = BigInt(integer + fraction); + const priceExponent = Number(exponent) - fraction.length; + const priceNumerator = priceDigits * 10n ** BigInt(Math.max(0, priceExponent)); + const priceDenominator = 10n ** BigInt(Math.max(0, -priceExponent)); const scaledDecimals = BigInt(Math.max(0, targetDecimals)); const decimalsFactor = 10n ** scaledDecimals; const rawAmountBigInt = - (usdMicros * decimalsFactor * BigInt(selectedScale)) / - (BigInt(scaledPriceNumber) * USD_MICROS); + (usdMicros * decimalsFactor * priceDenominator) / (priceNumerator * USD_MICROS); if (rawAmountBigInt <= 0n) { return { ok: false, reason: "invalid_amount", detail: "fiat_amount_too_small" }; } diff --git a/tests/token-manager.amounts.test.ts b/tests/token-manager.amounts.test.ts index 9a30d7b8..042ce59b 100644 --- a/tests/token-manager.amounts.test.ts +++ b/tests/token-manager.amounts.test.ts @@ -12,7 +12,8 @@ const priceLookup = (price: number) => ({ resolvedAt: 1_000, }); -const makeManager = () => TokenManager.getInstance(createWalletStub(), "MINT", "TOK"); +const makeManager = (decimals = 6) => + TokenManager.getInstance(createWalletStub({ decimals }), "MINT", "TOK"); type Failure = Extract; const failure = (result: ParseAmountResult): Failure => { @@ -116,9 +117,63 @@ describe("parseAmount USD conversion", () => { }); expect(lookup.mock.calls).toEqual([[{ tokenMint: "MINT" }]]); }); + + test.each([ + [1, "$1.000006", 1_000_006], + [1.0000000000000002, "$1.000006", 1_000_005], + [9.007199254740991, "$81064793292.668910", 8_999_999_999_999_999], + [9.007199254740993, "$81064793292.668910", 8_999_999_999_999_997], + [2e-15, "$0.000001", 500_000_000_000_000], + [5e-16, "$0.000001", 2_000_000_000_000_000], + [1, "$9007199254.740991", 9_007_199_254_740_991], + ])( + "uses the quoted price %p before rounding %s to %i whole units", + async (price, input, amount) => { + const quote = priceLookup(price); + spyOn(priceService, "getUsdPrice").mockResolvedValue(quote); + + expect(await makeManager().parseAmount(["/cf", input], 1, 1, "game")).toMatchObject({ + success: true, + data: { amount, decimals: 6, tokenMint: "MINT", priceLookup: quote }, + }); + }, + ); + + test("rejects the first raw unit beyond the safe integer range", async () => { + spyOn(priceService, "getUsdPrice").mockResolvedValue(priceLookup(1)); + + expect(await makeManager().parseAmount(["/cf", "$9007199254.740992"], 1, 1, "game")).toEqual({ + success: false, + error: "amount_too_large", + reason: undefined, + }); + }); + + test("converts a quote with a positive exponent using the selected token precision", async () => { + spyOn(priceService, "getUsdPrice").mockResolvedValue(priceLookup(1e21)); + + expect(await makeManager(18).parseAmount(["/cf", "$1000000000"], 1, 1, "game")).toMatchObject({ + success: true, + data: { amount: 1_000_000, decimals: 18 }, + }); + }); }); describe("parseAmount USD conversion failures", () => { + test.each([0, -0, -1, Infinity, NaN, 4.999999999999999e-16])( + "does not convert with price %p outside the supported range", + async (price) => { + spyOn(priceService, "getUsdPrice").mockResolvedValue(priceLookup(price)); + + expect(await makeManager().parseAmount(["/cf", "$1"], 1, 1, "game")).toEqual({ + success: false, + error: "unsupported_token", + unknownToken: "USD", + reason: "fiat_pricing_unavailable", + }); + }, + ); + test("marker amounts that are not numbers are invalid, not unsupported", async () => { const priceSpy = spyOn(priceService, "getUsdPrice").mockResolvedValue(priceLookup(1)); const tm = makeManager(); From ff5c6c828877956bda97b42038b67a2259f4ef0c Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 19:41:53 -0300 Subject: [PATCH 177/410] fix(tokens): respect explicit tokens over the native SOL default --- src/utils/token-manager.ts | 1 + tests/token-manager.metadata.test.ts | 45 ++++++++++++++++++++++++++++ 2 files changed, 46 insertions(+) diff --git a/src/utils/token-manager.ts b/src/utils/token-manager.ts index 6f657b02..252f482c 100644 --- a/src/utils/token-manager.ts +++ b/src/utils/token-manager.ts @@ -423,6 +423,7 @@ export class TokenManager { tokenDecimals = resolvedToken.decimals; resolvedTokenMint = resolvedToken.token_mint; resolvedTokenTicker = resolvedToken.token_ticker; + isSol = false; // An explicit token replaces the default's native SOL status. const requestedNativeSolByTicker = resolvedToken.isNativeSol && candidateLooksLikeTicker && candidateUpper === "SOL"; diff --git a/tests/token-manager.metadata.test.ts b/tests/token-manager.metadata.test.ts index ee630090..d5db081b 100644 --- a/tests/token-manager.metadata.test.ts +++ b/tests/token-manager.metadata.test.ts @@ -427,6 +427,51 @@ describe("resolveGameTokenContext", () => { }); }); + test.each(["game", "tip"] as const)( + "an explicit USDC %s does not inherit a native SOL default", + async (context) => { + const tm = TokenManager.getInstance(createWalletStub(), "SOL", "SOL"); + + expect(await tm.resolveGameTokenContext(undefined, "USDC", context)).toEqual({ + success: true, + tokenMint: USDC_MINT, + tokenTicker: "USDC", + decimals: 6, + isSol: false, + tokenWasSpecified: true, + requestedNativeSol: false, + }); + expect( + await tm.parseAmount(["/amount", "1.25", "USDC"], 1, undefined, context), + ).toMatchObject({ + success: true, + data: { + amount: 1_250_000, + formattedAmount: "1.25 USDC", + tokenMint: USDC_MINT, + isSol: false, + }, + }); + }, + ); + + test.each([ + ["game", "wrapped", WSOL_MINT, false], + ["tip", "native", "SOL", true], + ] as const)("an explicit SOL %s uses %s SOL", async (context, _kind, mint, isSol) => { + const tm = TokenManager.getInstance(createWalletStub(), "SOL", "SOL"); + + expect(await tm.resolveGameTokenContext(undefined, " SOL ", context)).toEqual({ + success: true, + tokenMint: mint, + tokenTicker: "SOL", + decimals: 9, + isSol, + tokenWasSpecified: true, + requestedNativeSol: true, + }); + }); + test("game token support without a chat default follows the contract policy", async () => { const tm = makeManager(); await tm.addToken(UNKNOWN_MINT, "SIDE", 6); From 67285a84945798d199f70971cc27edb835d108bb Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 19:43:44 -0300 Subject: [PATCH 178/410] test(wallet): bound fixtures for nonretryable RPC status errors --- tests/wallet.transactions.test.ts | 41 ++++++++++++++++++++----------- 1 file changed, 27 insertions(+), 14 deletions(-) diff --git a/tests/wallet.transactions.test.ts b/tests/wallet.transactions.test.ts index b22ac9d5..6e7a34e0 100644 --- a/tests/wallet.transactions.test.ts +++ b/tests/wallet.transactions.test.ts @@ -567,23 +567,36 @@ describe("confirmTransaction polling", () => { } }); - test("a non-network status error is logged and rethrown", async () => { - for (const thrown of [new Error("boom"), "plain failure"]) { + test.each([ + [new Error("boom"), "boom"], + ["plain failure", "plain failure"], + ] as const)( + "logs and rethrows a non-network status error %p without polling again", + async (thrown, message) => { + const calls: string[][] = []; const wallet = walletWith({ - getSignatureStatuses: async () => { - throw thrown; + getSignatureStatuses: async (signatures: string[]) => { + calls.push(signatures); + if (calls.length === 1) throw thrown; + // If a mutation retries a permanent error, resolve immediately so the assertion fails. + return { value: [{ confirmationStatus: "confirmed" }] }; }, }); - - await expect(wallet.confirmTransaction("SIG_ERR")).rejects.toBe(thrown); - } - const logged = messages(errorSpy).filter((line) => - line.includes("Error checking transaction status"), - ); - expect(logged).toHaveLength(2); - expect(logged[0]).toContain("boom"); - expect(logged[1]).toContain("plain failure"); - }); + const clock = useWalletConfirmationClock(wallet); + try { + await expect(wallet.confirmTransaction("SIG_ERR")).rejects.toBe(thrown); + expect(calls).toEqual([["SIG_ERR"]]); + expect(clock.delays).toEqual([]); + const logged = messages(errorSpy).filter((line) => + line.includes("Error checking transaction status"), + ); + expect(logged).toHaveLength(1); + expect(logged[0]).toContain(message); + } finally { + clock.restore(); + } + }, + ); test.each(["RPC timeout", "RPC request Timed Out", "RPC status 429"])( "backs off the same signature after %s", From 29eedb8cde4e1ae4f12893f45ce81b8ec3e7d983 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 19:46:18 -0300 Subject: [PATCH 179/410] test(tokens): keep configured game mints distinct from chat defaults --- tests/token-manager.metadata.test.ts | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/tests/token-manager.metadata.test.ts b/tests/token-manager.metadata.test.ts index d5db081b..fe1c1c7d 100644 --- a/tests/token-manager.metadata.test.ts +++ b/tests/token-manager.metadata.test.ts @@ -488,6 +488,31 @@ describe("resolveGameTokenContext", () => { // A blank mint is only rejected when the Oracle policy does not decide support. expect(supports(" ", false)).toBe(contractCapabilities.oracleTokenPolicy); }); + + test("the configured game mint remains distinct from a case-different chat mint", async () => { + const configured = UNKNOWN_MINT; + const chatMint = configured.replace("Token", "token"); + const chat = 77; + const tm = TokenManager.getInstance(createWalletStub(), ` ${configured} `, "BASE"); + expect(await tm.addToken(configured, "BASE", 7)).toBe(true); + expect(await tm.addToken(chatMint, "OTHER", 5)).toBe(true); + tm.setChatDefaultToken(chat, chatMint, "OTHER", "123"); + + expect(await tm.resolveGameTokenContext(chat, " BASE ", "game")).toMatchObject({ + success: true, + tokenMint: configured, + tokenTicker: "BASE", + decimals: 7, + tokenWasSpecified: true, + }); + + const other = await tm.resolveGameTokenContext(chat, "OTHER", "game"); + if (contractCapabilities.oracleTokenPolicy) { + expect(other).toMatchObject({ success: true, tokenMint: chatMint, decimals: 5 }); + } else { + expect(other).toEqual({ success: false, error: "unsupported_token", unknownToken: "OTHER" }); + } + }); }); describe("TokenManager missing-decimals handling", () => { From d258798e743d067ee905124923efb0a657f5d28a Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 19:49:18 -0300 Subject: [PATCH 180/410] refactor(tokens): recognize the exact ASCII native SOL ticker --- src/utils/token-manager.ts | 18 ++++-------------- tests/token-manager.metadata.test.ts | 20 ++++++++++++++++++++ 2 files changed, 24 insertions(+), 14 deletions(-) diff --git a/src/utils/token-manager.ts b/src/utils/token-manager.ts index 252f482c..7745c0b6 100644 --- a/src/utils/token-manager.ts +++ b/src/utils/token-manager.ts @@ -36,15 +36,6 @@ export interface TokenRegistrationResult { resolvedTicker?: string; } -const looksLikeTokenTicker = (candidate: string): boolean => { - const trimmed = candidate.trim(); - if (trimmed.length < 2 || trimmed.length > 12) { - return false; - } - - return /^[A-Za-z]+$/.test(trimmed); -}; - type ResolvedTokenMetadata = { ticker: string; decimals: number; @@ -405,15 +396,13 @@ export class TokenManager { if (candidate) { const numericCandidate = /^[0-9]+(?:\.[0-9]+)?$/.test(candidate); if (!numericCandidate) { - const normalizedCandidate = candidate.trim(); - const candidateUpper = normalizedCandidate.toUpperCase(); - const candidateLooksLikeTicker = looksLikeTokenTicker(normalizedCandidate); + const candidateUpper = candidate.toUpperCase(); const metadataFailureSink: { value: MetadataFailure | null } = { value: null, }; try { - const resolvedToken = await this.resolveSwapToken(normalizedCandidate, { + const resolvedToken = await this.resolveSwapToken(candidate, { persistDiscovered: context !== "game", metadataFailureSink, }); @@ -425,8 +414,9 @@ export class TokenManager { resolvedTokenTicker = resolvedToken.token_ticker; isSol = false; // An explicit token replaces the default's native SOL status. + // Native SOL requires the ASCII ticker, not a wrapped mint or a Unicode case alias. const requestedNativeSolByTicker = - resolvedToken.isNativeSol && candidateLooksLikeTicker && candidateUpper === "SOL"; + resolvedToken.isNativeSol && /^[sS][oO][lL]$/.test(candidate); if (requestedNativeSolByTicker) { requestedNativeSol = true; diff --git a/tests/token-manager.metadata.test.ts b/tests/token-manager.metadata.test.ts index fe1c1c7d..c064c7a2 100644 --- a/tests/token-manager.metadata.test.ts +++ b/tests/token-manager.metadata.test.ts @@ -472,6 +472,26 @@ describe("resolveGameTokenContext", () => { }); }); + test.each([ + ["sOl", "SOL", "SOL", true], + [" \n SoL \t", "SOL", "SOL", true], + ["WSOL", WSOL_MINT, "WSOL", false], + ["ſOL", WSOL_MINT, "SOL", false], + ] as const)( + "only the ASCII SOL ticker requests native SOL for a tip with %p", + async (input, mint, ticker, native) => { + expect(await makeManager().resolveGameTokenContext(undefined, input, "tip")).toEqual({ + success: true, + tokenMint: mint, + tokenTicker: ticker, + decimals: 9, + isSol: native, + tokenWasSpecified: true, + requestedNativeSol: native, + }); + }, + ); + test("game token support without a chat default follows the contract policy", async () => { const tm = makeManager(); await tm.addToken(UNKNOWN_MINT, "SIDE", 6); From d6b0c6c164c287e772a157cc11eea5414fd57bc1 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 19:50:25 -0300 Subject: [PATCH 181/410] test(tokens): document equivalent chat-mint branch mutations --- src/utils/token-manager.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/src/utils/token-manager.ts b/src/utils/token-manager.ts index 7745c0b6..826ef088 100644 --- a/src/utils/token-manager.ts +++ b/src/utils/token-manager.ts @@ -149,6 +149,7 @@ export class TokenManager { return true; } + // Stryker disable next-line BlockStatement,ConditionalExpression,EqualityOperator: Both branches return the same static mint membership check. if (normalizedMint === normalizedChatMint) { return SUPPORTED_TOKEN_MINTS.has(normalizedMint); } From 3ab433129262bd49f08a09c5397c704609cd4779 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 19:54:04 -0300 Subject: [PATCH 182/410] test(wallet): keep the original signature through provider timeout recovery --- tests/wallet.transactions.test.ts | 37 +++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) diff --git a/tests/wallet.transactions.test.ts b/tests/wallet.transactions.test.ts index 6e7a34e0..bd4f5804 100644 --- a/tests/wallet.transactions.test.ts +++ b/tests/wallet.transactions.test.ts @@ -844,6 +844,43 @@ describe("confirmTransaction polling", () => { } }); + test("does not sign a replacement when the real confirmation path returns an unknown outcome", async () => { + const signature = "SIG_SUBMITTED_BEFORE_RPC_TIMEOUT"; + const signer = await Keypair.generate(); + const instruction = SystemProgram.transfer({ + fromPubkey: signer.publicKey, + toPubkey: PublicKey.default, + lamports: 3, + }); + let elapsed = () => 0; + const { wallet, clock } = lateStatus(null, { + getSignatureStatuses: async () => { + if (elapsed() >= CONFIRMATION_TIMEOUT_MS) throw new Error("RPC rate limit: 429"); + return { value: [null] }; + }, + }); + elapsed = clock.elapsed; + const send = spyOn(wallet, "sendTransaction").mockRejectedValue( + new Error("Unexpected replacement transaction"), + ); + try { + await expect( + wallet.sendAndConfirmWithResubmits([instruction], [signer], { + initialSignature: signature, + maxResubmits: 2, + }), + ).rejects.toMatchObject({ + name: "TransactionOutcomeUnknownError", + signature, + lastSignature: signature, + }); + expect(send).not.toHaveBeenCalled(); + } finally { + send.mockRestore(); + clock.restore(); + } + }); + test("a transaction found failed by the probe is reported as failed", async () => { const { wallet, clock } = lateStatus(null, { getTransaction: async () => ({ meta: { err: { Custom: 1 } } }), From a98157456ed98948433af6e5db3cf10b58f6f846 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 19:58:07 -0300 Subject: [PATCH 183/410] fix(format): preserve the invalid-scale diagnostic from main --- src/utils/format-amount.ts | 3 ++- tests/format-amount.test.ts | 6 ++++++ 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/src/utils/format-amount.ts b/src/utils/format-amount.ts index d4bee402..18b58286 100644 --- a/src/utils/format-amount.ts +++ b/src/utils/format-amount.ts @@ -77,7 +77,8 @@ export function formatAmount( const { sign, digits } = toBigIntString(raw); // Always reserve at least one digit before the decimal point. - const padded = digits.padStart(decimals + 1, "0"); + const leadingZeros = Math.max(decimals + 1 - digits.length, 0); + const padded = "0".repeat(leadingZeros) + digits; let integerPart = decimals === 0 ? padded : padded.slice(0, -decimals) || "0"; const fractional = decimals === 0 ? "" : padded.slice(-decimals); const desired = Math.max(0, Math.min(maxFractionDigits, decimals)); diff --git a/tests/format-amount.test.ts b/tests/format-amount.test.ts index 54be3c50..fe3e2158 100644 --- a/tests/format-amount.test.ts +++ b/tests/format-amount.test.ts @@ -97,6 +97,12 @@ test("formatAmount default maxFractionDigits equals decimals", () => { expect(formatAmount(1, 18)).toBe("0.000000000000000001"); }); +test("formatAmount reports an infinite scale as invalid instead of an allocation error", () => { + const invalidScale = () => formatAmount(15n, Infinity); + expect(invalidScale).toThrow(RangeError); + expect(invalidScale).toThrow(/Infinity/i); +}); + test.each<[string, number | bigint | string, number, FormatOptions, string]>([ ["number zero", 0, 2, { trim: false }, "0.00"], ["negative number zero", -0, 2, { trim: false }, "-0.00"], From c7299da9b23188ae9aec196427dbdb65ca76641a Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 20:06:07 -0300 Subject: [PATCH 184/410] fix(wallet): preserve malformed provider errors during recovery --- src/utils/errors/parser.ts | 14 +++++++------- src/utils/transaction-runner.ts | 19 ++++++++++++++----- src/utils/wallet.ts | 14 ++++++++------ tests/errors.parser.test.ts | 15 +++++++++++++++ tests/transaction-runner.test.ts | 21 +++++++++++++++++++++ tests/wallet.resubmit.test.ts | 23 +++++++++++++++++------ 6 files changed, 82 insertions(+), 24 deletions(-) diff --git a/src/utils/errors/parser.ts b/src/utils/errors/parser.ts index be200445..78fa72a7 100644 --- a/src/utils/errors/parser.ts +++ b/src/utils/errors/parser.ts @@ -20,18 +20,18 @@ const TRANSACTION_EXPIRED_PATTERNS = [ // This also matches the "Check signature" form. const SIGNATURE_PATTERNS = [/signature ([A-Za-z0-9]{44,})/, /\b([A-Za-z0-9]{80,88})\b/]; -export const stringifyUnknownError = (error: unknown): string => { +/** Keep printable thrown values as-is, including empty and null status sentinels. */ +export const stringifyErrorDetail = (detail: unknown): string => { try { - if (error != null) { - const message = String(error); - if (message) return message; - } + return String(detail); } catch { - // Providers can throw objects without a usable string representation. + return "Unknown error"; } - return "Unknown error"; }; +export const stringifyUnknownError = (error: unknown): string => + (error == null ? "" : stringifyErrorDetail(error)) || "Unknown error"; + export const extractLamportsInfo = ( errorMessage: string, ): { current: number; needed: number } | null => { diff --git a/src/utils/transaction-runner.ts b/src/utils/transaction-runner.ts index 48c8bedb..212004a8 100644 --- a/src/utils/transaction-runner.ts +++ b/src/utils/transaction-runner.ts @@ -1,5 +1,6 @@ import { TransactionOutcomeUnknownError, type WalletManager } from "./wallet"; import { TRANSACTION_RESUBMIT_ATTEMPTS } from "./constants"; +import { stringifyErrorDetail } from "./errors/parser"; const CONFIRMATION_RETRY_DELAYS_MS = [2000, 4000, 8000, 12000, 16000, 20000]; @@ -122,7 +123,9 @@ export const confirmTransactionWithRecovery = async ( return currentSignature; } catch (confirmError) { const detail = (confirmError as { message?: unknown } | null | undefined)?.message; - console.warn(`⚠️ ${operationLabel} confirmation failed: ${String(detail ?? confirmError)}`); + console.warn( + `⚠️ ${operationLabel} confirmation failed: ${stringifyErrorDetail(detail ?? confirmError)}`, + ); const normalizedMessage = typeof detail === "string" ? detail.toLowerCase() : undefined; const outcomeUnknown = confirmError instanceof TransactionOutcomeUnknownError; @@ -163,7 +166,9 @@ export const confirmTransactionWithRecovery = async ( return currentSignature; } catch (resubmitError) { const normalizedError = - resubmitError instanceof Error ? resubmitError : new Error(String(resubmitError)); + resubmitError instanceof Error + ? resubmitError + : new Error(stringifyErrorDetail(resubmitError)); const latestSignature = hasLastSignature(resubmitError) ? resubmitError.lastSignature : undefined; @@ -205,7 +210,9 @@ export const confirmTransactionWithRecovery = async ( } } catch (probeError) { const normalizedProbeError = - probeError instanceof Error ? probeError : new Error(String(probeError)); + probeError instanceof Error + ? probeError + : new Error(stringifyErrorDetail(probeError)); console.error( `❌ Probe "${probe.label}" failed during ${operationLabel} retry ${attemptLabel}`, normalizedProbeError, @@ -235,7 +242,7 @@ export const confirmTransactionWithRecovery = async ( const normalizedError = statusProbeError instanceof Error ? statusProbeError - : new Error(String(statusProbeError)); + : new Error(stringifyErrorDetail(statusProbeError)); console.error( `❌ Failed to verify transaction status during ${operationLabel} retry ${attemptLabel}`, normalizedError, @@ -245,7 +252,9 @@ export const confirmTransactionWithRecovery = async ( } const timeoutError: TimeoutErrorWithRecovery = - recoveryFailure instanceof Error ? recoveryFailure : new Error(String(recoveryFailure)); + recoveryFailure instanceof Error + ? recoveryFailure + : new Error(stringifyErrorDetail(recoveryFailure)); if (recoveryErrors.length > 0) { timeoutError.recoveryErrors = recoveryErrors; } diff --git a/src/utils/wallet.ts b/src/utils/wallet.ts index 2d9b47b7..2c8e833d 100644 --- a/src/utils/wallet.ts +++ b/src/utils/wallet.ts @@ -87,6 +87,7 @@ import { } from "./constants"; import { formatAmount } from "./format-amount"; import { isMissingAccountError } from "./account-errors"; +import { stringifyErrorDetail } from "./errors/parser"; import { WSOL_MINT } from "./token-registry"; import { resolveTokenMetadata } from "./token-metadata"; import { isMintDecimals } from "./token-decimals"; @@ -3063,10 +3064,13 @@ export class WalletManager { } return currentSignature; - } catch (error: any) { - const normalizedMessage = error?.message?.toLowerCase?.() ?? ""; + } catch (error) { + const detail = (error as { message?: unknown } | null | undefined)?.message; + const errorText = typeof detail === "string" ? detail : undefined; + const normalizedMessage = errorText?.toLowerCase(); const shouldResubmit = !(error instanceof TransactionOutcomeUnknownError) && + normalizedMessage !== undefined && (normalizedMessage.includes("timeout") || normalizedMessage.includes("timed out") || normalizedMessage.includes("not confirmed") || @@ -3077,15 +3081,13 @@ export class WalletManager { const failure = error instanceof Error ? error - : new Error(error?.message ?? String(error), { cause: error }); + : new Error(stringifyErrorDetail(detail ?? error), { cause: error }); finalFailure = Object.assign(failure, { lastSignature: currentSignature }); break; } console.warn( - `♻️ ${operationLabel} resubmit ${resubmitAttempts + 1}/${maxResubmits} after failure: ${ - error?.message ?? error - }`, + `♻️ ${operationLabel} resubmit ${resubmitAttempts + 1}/${maxResubmits} after failure: ${errorText}`, ); currentSignature = await this.sendTransaction(instructions, signers, { priorityFee }); diff --git a/tests/errors.parser.test.ts b/tests/errors.parser.test.ts index e018c838..7b631456 100644 --- a/tests/errors.parser.test.ts +++ b/tests/errors.parser.test.ts @@ -7,6 +7,8 @@ import { extractSignature, isTransactionExpiredError, isTransactionTimeoutError, + stringifyErrorDetail, + stringifyUnknownError, } from "../src/utils/errors/parser"; const connection = new Connection("http://localhost:8899"); @@ -24,6 +26,19 @@ beforeEach(() => { }); afterEach(() => debugSpy.mockRestore()); +test.each([ + ["null", null, "null", "Unknown error"], + ["undefined", undefined, "undefined", "Unknown error"], + ["an empty string", "", "", "Unknown error"], + ["an explicit zero", 0, "0", "0"], + ["an opaque symbol", Symbol("status"), "Symbol(status)", "Symbol(status)"], + ["an object with no conversion", Object.create(null), "Unknown error", "Unknown error"], + ["an object with empty text", { toString: () => "" }, "", "Unknown error"], +])("handles %s according to the caller's diagnostic policy", (_label, value, detail, fallback) => { + expect(stringifyErrorDetail(value)).toBe(detail); + expect(stringifyUnknownError(value)).toBe(fallback); +}); + describe("collectErrorLogs", () => { test("ignores non-object errors", async () => { expect(await collectErrorLogs(null, new Set(), connection)).toEqual([]); diff --git a/tests/transaction-runner.test.ts b/tests/transaction-runner.test.ts index 89d48ddc..1894fe8f 100644 --- a/tests/transaction-runner.test.ts +++ b/tests/transaction-runner.test.ts @@ -341,6 +341,27 @@ describe("confirmTransactionWithRecovery", () => { expect(statusCalls).toEqual(["original"]); }); + test("leaves an unprintable provider failure intact without retrying", async () => { + const failure = Object.create(null); + const { wallet, statusCalls } = makeWallet({ + confirm: async () => { + throw failure; + }, + }); + const resubmit = mock(async () => "not-sent"); + await expect( + confirmTransactionWithRecovery({ + wallet, + initialSignature: "original", + operationLabel: "Player join", + resubmit, + }), + ).rejects.toBe(failure); + expect(warnSpy).toHaveBeenCalledWith("⚠️ Player join confirmation failed: Unknown error"); + expect(resubmit).not.toHaveBeenCalled(); + expect(statusCalls).toEqual([]); + }); + test("does not replace an already retried transaction with an unknown outcome", async () => { const pending = new TransactionOutcomeUnknownError( "replacement", diff --git a/tests/wallet.resubmit.test.ts b/tests/wallet.resubmit.test.ts index 197903d9..91394b7c 100644 --- a/tests/wallet.resubmit.test.ts +++ b/tests/wallet.resubmit.test.ts @@ -168,13 +168,20 @@ describe("WalletManager sendAndConfirmWithResubmits", () => { }, ); - test("reports a plain provider error instead of throwing while attaching the signed transaction", async () => { + test.each([ + ["plain message", "provider unavailable", "provider unavailable"], + ["null error", null, "null"], + ["numeric message", { message: 429 }, "429"], + ["non-callable lowercase conversion", { message: { toLowerCase: 42 } }, "[object Object]"], + ["unprintable message", { message: Object.create(null) }, "Unknown error"], + ])("keeps the original cause and signature for %s", async (_label, providerFailure, message) => { const wallet = WalletManager.createForTest(MNEMONIC, { connection: new ResubmitConnection() as unknown as Connection, }); const confirm = spyOn(wallet, "confirmTransaction") .mockResolvedValue(undefined) - .mockRejectedValueOnce("provider unavailable"); + .mockRejectedValueOnce(providerFailure); + const send = spyOn(wallet, "sendTransaction").mockResolvedValue("UNEXPECTED"); const ix = new TransactionInstruction({ programId: PublicKey.default, keys: [], @@ -182,12 +189,16 @@ describe("WalletManager sendAndConfirmWithResubmits", () => { }); const signer = { publicKey: PublicKey.default } as unknown as Keypair; try { - await expect( - wallet.sendAndConfirmWithResubmits([ix], [signer], { + const failure = await wallet + .sendAndConfirmWithResubmits([ix], [signer], { initialSignature: "initial", - }), - ).rejects.toMatchObject({ message: "provider unavailable", lastSignature: "initial" }); + }) + .catch((error: unknown) => error); + expect(failure).toMatchObject({ message, lastSignature: "initial" }); + expect(failure instanceof Error && failure.cause).toBe(providerFailure); + expect(send).not.toHaveBeenCalled(); } finally { + send.mockRestore(); confirm.mockRestore(); } }); From 0d7e42e98409a49303983b4b8b73daba15a0ddf0 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 20:08:49 -0300 Subject: [PATCH 185/410] test(wallet): preserve funded balances across partial ATA batches --- tests/wallet.balances-edge-cases.test.ts | 78 ++++++++++++++++++++++++ 1 file changed, 78 insertions(+) diff --git a/tests/wallet.balances-edge-cases.test.ts b/tests/wallet.balances-edge-cases.test.ts index e7517017..7d1ddb8e 100644 --- a/tests/wallet.balances-edge-cases.test.ts +++ b/tests/wallet.balances-edge-cases.test.ts @@ -417,6 +417,84 @@ describe("getAllWalletTokenBalances edge cases", () => { expect(errors).toHaveLength(1); }); + test("keeps funded ATA balances when an RPC batch has missing and extra rows", async () => { + const mints = fixtureMints(5); + const [_missing, first, zero, second, foreign] = mints; + if (!first || !zero || !second || !foreign) throw new Error("Missing token fixtures"); + const requests: string[][] = []; + const order: string[] = []; + let infoRows: Array<{ owner: PublicKey; data: Buffer; lamports: number } | null> = []; + const wallet = walletWith( + baseConnection({ + getMultipleAccountsInfo: async (keys: PublicKey[]) => { + requests.push(keys.map((key) => key.toBase58())); + return infoRows; + }, + }), + ); + const owner = await wallet.getPublicKey(TELEGRAM_ID); + const account = (mint: PublicKey, amount: bigint, programId = TOKEN_PROGRAM_ID) => { + const data = Buffer.alloc(AccountLayout.span); + AccountLayout.encode({ mint, owner, amount, state: 1 }, data); + return { owner: programId, data, lamports: 1 }; + }; + infoRows = [ + null, + account(first, 7_500_000n), + account(zero, 0n), + account(second, 2_500_000n), + account(foreign, 1n, TOKEN_2022_PROGRAM_ID), + account(first, 1_000_000n), + ]; + const metadata = spyOn(wallet, "getFullTokenMetadata").mockImplementation(async (mint) => { + order.push(`metadata ${mint}`); + return { decimals: 6, symbol: mint === first.toBase58() ? "FIRST" : "SECOND" }; + }); + const format = wallet.formatTokenBalance.bind(wallet); + const display = spyOn(wallet, "formatTokenBalance").mockImplementation((raw, decimals) => { + order.push(`format ${raw}`); + return format(raw, decimals); + }); + const { censuses, onCensus } = collectCensus(); + try { + const balances = await wallet.getAllWalletTokenBalances( + TELEGRAM_ID, + mints.map((mint) => knownToken(mint.toBase58(), mint.toBase58())), + { onCensus }, + ); + expect(requests).toEqual([ + await Promise.all( + mints.map(async (mint) => (await getAssociatedTokenAddress(mint, owner)).toBase58()), + ), + ]); + expect( + balances.map(({ mint, ticker, rawBalance, formattedBalance }) => [ + mint, + ticker, + rawBalance, + formattedBalance, + ]), + ).toEqual([ + [first.toBase58(), "FIRST", "7500000", "7.5"], + [second.toBase58(), "SECOND", "2500000", "2.5"], + ]); + expect(order).toEqual([ + `metadata ${first.toBase58()}`, + `metadata ${second.toBase58()}`, + "format 7500000", + "format 2500000", + ]); + expect(censuses).toEqual([ + { complete: true, heldMints: [first.toBase58(), second.toBase58()], scannedMints: [] }, + ]); + expect(messages(logSpy)).toContain("📦 Loaded 3 known token accounts via ATA lookups"); + expect(errorSpy).not.toHaveBeenCalled(); + } finally { + display.mockRestore(); + metadata.mockRestore(); + } + }); + test("discovery skips malformed accounts and keeps zero balances out of the result", async () => { const zeroMint = await newMint(); const unknownMint = await newMint(); From 9068795010ea5db3a67f1bbba4fd4653e7544775 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 20:13:38 -0300 Subject: [PATCH 186/410] test(tokens): pin the metadata address and fallback diagnostics --- tests/token-metadata.test.ts | 25 +++++++++++++++++++------ 1 file changed, 19 insertions(+), 6 deletions(-) diff --git a/tests/token-metadata.test.ts b/tests/token-metadata.test.ts index 72310dae..ac33491b 100644 --- a/tests/token-metadata.test.ts +++ b/tests/token-metadata.test.ts @@ -1,6 +1,6 @@ import { afterEach, beforeEach, describe, expect, mock, spyOn, test } from "bun:test"; import { getMetadataAccountDataSerializer } from "@metaplex-foundation/mpl-token-metadata"; -import type { Connection } from "#solana"; +import type { Connection, PublicKey } from "#solana"; import { resolveTokenMetadata } from "../src/utils/token-metadata"; const MINT = "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"; @@ -30,7 +30,7 @@ const metaplexAccount = (symbol: string, name: string) => ({ }); const connectionWith = (account: unknown) => ({ - getAccountInfo: mock(async () => account), + getAccountInfo: mock(async (_address: PublicKey) => account), }); const jupiterFetch = (entries: unknown[] | null) => @@ -55,15 +55,20 @@ afterEach(() => { describe("resolveTokenMetadata", () => { test("prefers on-chain Metaplex metadata and strips null padding", async () => { const fetch = jupiterFetch([]); + const connection = connectionWith(metaplexAccount(" \0USDC\0 ", " \0USD Coin\0 ")); const result = await resolveTokenMetadata({ - connection: connectionWith(metaplexAccount("USDC\0\0\0", "USD Coin\0\0")) as any, + connection: connection as unknown as Connection, mintAddress: MINT, fetch, getDecimals: async () => 6, }); expect(result).toEqual({ symbol: "USDC", name: "USD Coin", decimals: 6 }); + expect(connection.getAccountInfo).toHaveBeenCalledTimes(1); + expect(String(connection.getAccountInfo.mock.calls[0]?.[0])).toBe( + "5x38Kp4hvdomTCnCrAny4UtMUt5rQBdB6px2K1Ui45Wq", + ); expect(fetch).not.toHaveBeenCalled(); }); @@ -75,6 +80,7 @@ describe("resolveTokenMetadata", () => { }); expect(result).toEqual({ symbol: "BONK", name: "BONK", decimals: 5 }); + expect(warnSpy).not.toHaveBeenCalled(); }); test("ignores an UNKNOWN Metaplex symbol and falls back to Jupiter", async () => { @@ -164,6 +170,7 @@ describe("resolveTokenMetadata", () => { expect(result).toEqual({ symbol: "HOOK", decimals: 4 }); expect(calls).toEqual(["throws", "empty", "hit"]); + expect(warnSpy).toHaveBeenCalledTimes(1); expect(warnSpy.mock.calls[0]?.[0]).toBe(`Token metadata hook failed for ${MINT}:`); expect(fetch).not.toHaveBeenCalled(); }); @@ -189,15 +196,21 @@ describe("resolveTokenMetadata", () => { expect(getDecimals).toHaveBeenCalledTimes(1); }); - test("falls back to decimals only when nothing knows the token", async () => { + test.each([ + ["a missing account", null], + ["an account without data", { data: null }], + ] as const)("falls back to decimals without a decode error for %s", async (_label, account) => { + const fetch = jupiterFetch([]); const result = await resolveTokenMetadata({ - connection: connectionWith({ data: null }) as any, + connection: connectionWith(account) as unknown as Connection, mintAddress: MINT, - fetch: jupiterFetch([]), + fetch, getDecimals: async () => 2, }); expect(result).toEqual({ decimals: 2 }); + expect(fetch).toHaveBeenCalledTimes(1); + expect(logSpy).not.toHaveBeenCalled(); }); test.each([ From d8b785941fa821e4dd95be8df00df125e9dd562e Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 20:15:02 -0300 Subject: [PATCH 187/410] test(wallet): cover pending history after a plain timeout error --- tests/transaction-runner.test.ts | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/tests/transaction-runner.test.ts b/tests/transaction-runner.test.ts index 1894fe8f..197399bd 100644 --- a/tests/transaction-runner.test.ts +++ b/tests/transaction-runner.test.ts @@ -362,6 +362,33 @@ describe("confirmTransactionWithRecovery", () => { expect(statusCalls).toEqual([]); }); + test("reports pending history when a plain timeout failure cannot be printed", async () => { + const failure = Object.assign(Object.create(null), { message: "Transaction timed out" }); + const { wallet, statusCalls } = makeWallet({ + confirm: async () => { + throw failure; + }, + }); + + await expect( + confirmTransactionWithRecovery({ + wallet, + initialSignature: "original", + operationLabel: "Player join", + retryDelays: [0], + }), + ).rejects.toMatchObject({ + message: "Unknown error", + cause: { message: "Transaction original still pending after retry 1" }, + recoveryErrors: [{ message: "Transaction original still pending after retry 1" }], + }); + expect(statusCalls).toEqual(["original"]); + expect(warnSpy.mock.calls).toEqual([ + ["⚠️ Player join confirmation failed: Transaction timed out"], + ["⚠️ Player join confirmation timed out after 1 retries for original"], + ]); + }); + test("does not replace an already retried transaction with an unknown outcome", async () => { const pending = new TransactionOutcomeUnknownError( "replacement", From 2db1ad5abff98c59187f8b4b0e911bd811b5559a Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 20:17:47 -0300 Subject: [PATCH 188/410] test(rpc): pin fallback diagnostics and provider code prefixes --- tests/rpc-endpoints.error-paths.test.ts | 50 +++++++++++++++++++++++++ tests/rpc-endpoints.test.ts | 8 ++++ 2 files changed, 58 insertions(+) diff --git a/tests/rpc-endpoints.error-paths.test.ts b/tests/rpc-endpoints.error-paths.test.ts index fb449bbf..de132c28 100644 --- a/tests/rpc-endpoints.error-paths.test.ts +++ b/tests/rpc-endpoints.error-paths.test.ts @@ -22,6 +22,21 @@ describe("isRetryableRpcError status codes", () => { expect(isRetryableRpcError({ code: 404, message: "missing" })).toBe(false); }); + test.each([ + ["EcOnNrEsEt", true], + ["eTimedOutExtra", true], + ["prefixEconn", false], + ["prefixEtimedout", false], + ["UNRECOGNIZED_CODE", false], + ] as const)( + "classifies the provider code %s without relying on its message", + (code, expected) => { + expect(isRetryableRpcError(Object.assign(new Error("provider response"), { code }))).toBe( + expected, + ); + }, + ); + test("follows nested causes and stops at a cycle", () => { expect(isRetryableRpcError(null)).toBe(false); expect(isRetryableRpcError({ cause: { code: "ETIMEDOUT" } })).toBe(true); @@ -116,6 +131,41 @@ describe("RpcEndpointManager listeners", () => { expect(errors).toEqual([["RPC endpoint change listener threw:", boom]]); expect(seen).toEqual(["https://rpc-secondary"]); }); + + test.each([undefined, {}])( + "isolates listener errors without an error logger %p", + async (logger) => { + const endpoints: [string, string] = [ + "https://rpc-primary.example", + "https://rpc-secondary.example", + ]; + const manager = new RpcEndpointManager(endpoints, { + connectionFactory: (endpoint) => + asConnection({ + getSlot: async () => { + if (endpoint === endpoints[0]) throw resetError(); + return 7n; + }, + }), + logger, + }); + const survivor = mock(() => {}); + const failure = new Error("listener failed"); + manager.onActiveEndpointChange(() => { + throw failure; + }); + manager.onActiveEndpointChange(async () => { + throw failure; + }); + manager.onActiveEndpointChange(survivor); + + const connection = manager.getConnection(); + expect(await connection.getSlot()).toBe(7n); + expect(await connection.getSlot()).toBe(7n); + expect(survivor).toHaveBeenCalledTimes(1); + expect(connection.rpcEndpoint).toBe(endpoints[1]); + }, + ); }); describe("RpcEndpointManager call handling", () => { diff --git a/tests/rpc-endpoints.test.ts b/tests/rpc-endpoints.test.ts index 3e1d35ac..a1b386e2 100644 --- a/tests/rpc-endpoints.test.ts +++ b/tests/rpc-endpoints.test.ts @@ -76,6 +76,11 @@ describe("redactRpcEndpoint", () => { expect(redactRpcEndpoint(DEFAULT_MAINNET_ENDPOINT)).toBe(DEFAULT_MAINNET_ENDPOINT); expect(redactRpcEndpoint("not a url secret")).toBe(""); }); + + test("ignores a slash-only path but redacts a later path segment", () => { + expect(redactRpcEndpoint("https://rpc.example///")).toBe("https://rpc.example"); + expect(redactRpcEndpoint("https://rpc.example///secret///")).toBe("https://rpc.example/…"); + }); }); describe("RpcEndpointManager", () => { @@ -112,6 +117,9 @@ describe("RpcEndpointManager", () => { const logged = JSON.stringify(lines.map((args) => args.map(String))); expect(logged).not.toContain("secret"); + expect(lines).toContainEqual([ + "RPC call getSlot failed on https://rpc-primary.example/…; trying next endpoint (1/2).", + ]); expect(lines.at(-1)).toEqual([ "RPC call getBlockTime rejected by https://rpc-secondary.example/…: Block not available for slot 1", ]); From 95a236cf1a7ea8cef558c2a704c32030bd4aff20 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 20:19:29 -0300 Subject: [PATCH 189/410] refactor(rpc): detect non-slash endpoint path data directly --- src/utils/rpc-endpoints.ts | 2 +- tests/rpc-endpoints.test.ts | 13 ++++++++++--- 2 files changed, 11 insertions(+), 4 deletions(-) diff --git a/src/utils/rpc-endpoints.ts b/src/utils/rpc-endpoints.ts index dd2359ee..0f2fc8bc 100644 --- a/src/utils/rpc-endpoints.ts +++ b/src/utils/rpc-endpoints.ts @@ -55,7 +55,7 @@ const TRANSIENT_ERROR_TOKENS = [ export function redactRpcEndpoint(endpoint: string): string { try { const url = new URL(endpoint); - const hasSecretParts = url.pathname.replace(/\/+$/, "").length > 0 || url.search.length > 0; + const hasSecretParts = /[^/]/.test(url.pathname) || url.search.length > 0; return hasSecretParts ? `${url.origin}/…` : url.origin; } catch { return ""; diff --git a/tests/rpc-endpoints.test.ts b/tests/rpc-endpoints.test.ts index a1b386e2..7e61fc04 100644 --- a/tests/rpc-endpoints.test.ts +++ b/tests/rpc-endpoints.test.ts @@ -77,9 +77,16 @@ describe("redactRpcEndpoint", () => { expect(redactRpcEndpoint("not a url secret")).toBe(""); }); - test("ignores a slash-only path but redacts a later path segment", () => { - expect(redactRpcEndpoint("https://rpc.example///")).toBe("https://rpc.example"); - expect(redactRpcEndpoint("https://rpc.example///secret///")).toBe("https://rpc.example/…"); + test.each([ + ["https://rpc.example///", "https://rpc.example"], + ["https://rpc.example///secret///", "https://rpc.example/…"], + ["https://rpc.example/%2F", "https://rpc.example/…"], + ["https://rpc.example/#fragment", "https://rpc.example"], + ["https://rpc.example///?secret=yes", "https://rpc.example/…"], + ["file:///", "null"], + ["mailto:wallet@example.com", "null/…"], + ] as const)("redacts path and query data for %s", (url, expected) => { + expect(redactRpcEndpoint(url)).toBe(expected); }); }); From d493d581428b46574b4b8c8c302c02148be73b98 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 20:21:37 -0300 Subject: [PATCH 190/410] test(rpc): stop fallback reads at the exact provider deadline --- tests/rpc-endpoints.error-paths.test.ts | 53 +++++++++++++++++++++++++ 1 file changed, 53 insertions(+) diff --git a/tests/rpc-endpoints.error-paths.test.ts b/tests/rpc-endpoints.error-paths.test.ts index de132c28..97b8b2fe 100644 --- a/tests/rpc-endpoints.error-paths.test.ts +++ b/tests/rpc-endpoints.error-paths.test.ts @@ -235,6 +235,59 @@ describe("RpcEndpointManager call handling", () => { } }); + test.each(["after a failed read", "during cluster verification"] as const)( + "does not start a fallback or a repeat read at the exact deadline %s", + async (stage) => { + let clock = 10_000; + let primaryCalls = 0; + const readTimeoutMs = 90; + const deadline = clock + readTimeoutMs; + const failure = resetError("primary temporarily unavailable"); + const primaryRead = mock(async () => { + if (++primaryCalls > 1) return 44n; + if (stage === "after a failed read") clock = deadline; + throw failure; + }); + const fallbackRead = mock(async () => 37n); + const primaryGenesis = mock(async () => "same-cluster"); + const fallbackGenesis = mock(async () => { + clock = deadline; + return "same-cluster"; + }); + const first = "https://rpc-primary.example"; + const second = "https://rpc-fallback.example"; + const connectionFactory = mock((endpoint: string, _commitment: Commitment) => + endpoint === first + ? asConnection({ getSlot: primaryRead, getGenesisHash: primaryGenesis }) + : asConnection({ getSlot: fallbackRead, getGenesisHash: fallbackGenesis }), + ); + const manager = new RpcEndpointManager([first], { + readTimeoutMs, + fallbackEndpoint: second, + connectionFactory, + }); + const now = spyOn(Date, "now").mockImplementation(() => clock); + try { + await expect(manager.getConnection().getSlot()).rejects.toBe(failure); + expect(primaryRead).toHaveBeenCalledTimes(1); + expect(fallbackRead).not.toHaveBeenCalled(); + const verified = stage === "during cluster verification"; + expect(primaryGenesis).toHaveBeenCalledTimes(verified ? 1 : 0); + expect(fallbackGenesis).toHaveBeenCalledTimes(verified ? 1 : 0); + expect(connectionFactory.mock.calls).toEqual( + verified + ? [ + [first, "confirmed"], + [second, "confirmed"], + ] + : [[first, "confirmed"]], + ); + } finally { + now.mockRestore(); + } + }, + ); + test("rethrows a non-retryable error raised while verifying the fallback provider", async () => { const fatal = new Error("invalid genesis response"); const manager = new RpcEndpointManager(["https://rpc-only"], { From cd0a2078135ce7b0a67f0e2961a4f6df96838e81 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 20:23:02 -0300 Subject: [PATCH 191/410] test(history): preserve exact optional amounts and page boundaries --- tests/transaction-history.paths.test.ts | 61 +++++++++++++++++++++++++ 1 file changed, 61 insertions(+) diff --git a/tests/transaction-history.paths.test.ts b/tests/transaction-history.paths.test.ts index 6e16b4a8..ec88709d 100644 --- a/tests/transaction-history.paths.test.ts +++ b/tests/transaction-history.paths.test.ts @@ -207,6 +207,53 @@ describe("swap finance evidence", () => { }); describe("TransactionHistory error handling", () => { + test("stores exact optional amounts and separates blank values from zero", () => { + const db = TransactionHistory.getInstance(); + db.addTransaction( + record("provided", { + amount_out: "9007199254740993.1234", + price_impact: "-0.25", + fee: "0.000000001", + network: "devnet", + }), + ); + db.addTransaction( + record("zero", { amount_out: "0", price_impact: "0", fee: "0", network: "" }), + ); + db.addTransaction(record("blank", { amount_out: "", price_impact: "", fee: "" })); + + const stored = withRawDatabase((raw) => + raw + .query( + "SELECT signature, amount_out, price_impact, fee, network FROM transaction_history ORDER BY signature", + ) + .all(), + ); + expect(stored).toEqual([ + { signature: "blank", amount_out: null, price_impact: null, fee: null, network: "mainnet" }, + { + signature: "provided", + amount_out: "9007199254740993.1234", + price_impact: "-0.25", + fee: "0.000000001", + network: "devnet", + }, + { signature: "zero", amount_out: "0", price_impact: "0", fee: "0", network: "mainnet" }, + ]); + }); + + test("applies the history offset after filtering the user and sorting newest first", () => { + const db = TransactionHistory.getInstance(); + db.addTransaction(record("middle", { timestamp: 2 })); + db.addTransaction(record("oldest", { timestamp: 1 })); + db.addTransaction(record("someone-else", { user_id: "other-user", timestamp: 4 })); + db.addTransaction(record("newest", { timestamp: 3 })); + + expect(db.getUserHistory("user-f", 1, 1).map((row) => row.signature)).toEqual(["middle"]); + expect(db.getUserHistory("user-f", 1, 2).map((row) => row.signature)).toEqual(["oldest"]); + expect(db.getUserHistory("user-f", 1, 3)).toEqual([]); + }); + test("keeps block height zero distinct from an unknown height on insert and update", () => { const db = TransactionHistory.getInstance(); db.addTransaction(record("known-at-insert", { block_height: 0 })); @@ -291,6 +338,20 @@ describe("TransactionHistory error handling", () => { }); describe("formatTransactionForDisplay icons and links", () => { + test.each([ + ["FAILED", undefined, "TOK", "❌🟢 1 SOL"], + ["PENDING", "7", "", "⏳🟢 1 SOL"], + ["SUCCESS", "0", "TOK", "✅🟢 1 SOL → 0 TOK"], + ] as const)( + "formats the %s buy with only a complete output amount", + (status, amount, token, expected) => { + const text = formatTransactionForDisplay( + record("sig", { status, amount_out: amount, to_token: token }), + ); + expect(text.split("\n")[0]).toBe(expected); + }, + ); + test("uses a distinct icon for each transaction type", () => { const iconFor = (type: string) => formatTransactionForDisplay(record(`sig-${type}`, { transaction_type: type as any })); From 2eb0d924b5dfcbf9eb1585bc4aeb491dce06ed40 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 20:26:01 -0300 Subject: [PATCH 192/410] fix(rpc): preserve malformed provider failures without repeating writes --- src/utils/rpc-endpoints.ts | 7 +++++-- tests/rpc-endpoints.error-paths.test.ts | 26 +++++++++++++++++++++++++ 2 files changed, 31 insertions(+), 2 deletions(-) diff --git a/src/utils/rpc-endpoints.ts b/src/utils/rpc-endpoints.ts index 0f2fc8bc..d5f89b6f 100644 --- a/src/utils/rpc-endpoints.ts +++ b/src/utils/rpc-endpoints.ts @@ -1,3 +1,4 @@ +import { stringifyErrorDetail } from "./errors/parser"; import { boundedRpc, foregroundRpc } from "./rpc-request-budget"; import { Connection, type Commitment } from "#solana"; @@ -81,7 +82,9 @@ export function isRetryableRpcError(error: unknown, seen = new Set()): return true; } - const message = error instanceof Error ? error.message : String(error); + const message: unknown = error instanceof Error ? error.message : stringifyErrorDetail(error); + // A malformed message must not authorize a repeat request. + if (typeof message !== "string") return false; const normalized = message.toLowerCase(); return TRANSIENT_ERROR_TOKENS.some((token) => normalized.includes(token)); } @@ -290,7 +293,7 @@ export class RpcEndpointManager { if (!isRetryableRpcError(error)) { // The request itself was rejected (for example a skipped slot). The // caller receives the error, so a one-line note is enough here. - const message = error instanceof Error ? error.message : String(error); + const message = stringifyErrorDetail(error instanceof Error ? error.message : error); this.logger?.warn?.(`RPC call ${methodName} rejected by ${safeEndpoint}: ${message}`); throw error; } diff --git a/tests/rpc-endpoints.error-paths.test.ts b/tests/rpc-endpoints.error-paths.test.ts index 97b8b2fe..494b8a6b 100644 --- a/tests/rpc-endpoints.error-paths.test.ts +++ b/tests/rpc-endpoints.error-paths.test.ts @@ -235,6 +235,32 @@ describe("RpcEndpointManager call handling", () => { } }); + test.each([ + ["an unprintable object", Object.create(null), "Unknown error"], + ["a numeric Error message", Object.assign(new Error(), { message: 429 }), "429"], + ] as const)("preserves %s without trying another write", async (_label, failure, detail) => { + const primary = mock(async () => { + throw failure; + }); + const secondary = mock(async () => "never-sent"); + const warn = mock((..._args: unknown[]) => {}); + const first = "https://rpc-primary.example/?token=fake"; + const manager = new RpcEndpointManager([first, "https://rpc-secondary.example"], { + connectionFactory: (endpoint) => + asConnection({ sendRawTransaction: endpoint === first ? primary : secondary }), + logger: { warn }, + }); + + await expect(manager.getConnection().sendRawTransaction(new Uint8Array(1))).rejects.toBe( + failure, + ); + expect(primary).toHaveBeenCalledTimes(1); + expect(secondary).not.toHaveBeenCalled(); + expect(warn.mock.calls).toEqual([ + ["RPC call sendRawTransaction rejected by https://rpc-primary.example/…: " + detail], + ]); + }); + test.each(["after a failed read", "during cluster verification"] as const)( "does not start a fallback or a repeat read at the exact deadline %s", async (stage) => { From d4c55df6c6c9fb079d7a46c347b1f56a233e53d4 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 20:29:53 -0300 Subject: [PATCH 193/410] fix(finance): keep exact confirmed fees from the Solana client --- src/utils/transaction-fee.ts | 7 ++- tests/swap-service.edge-cases.test.ts | 8 ++-- tests/transaction-fee.test.ts | 64 +++++++++++++++++++++++++++ 3 files changed, 74 insertions(+), 5 deletions(-) diff --git a/src/utils/transaction-fee.ts b/src/utils/transaction-fee.ts index e90676f3..6851407b 100644 --- a/src/utils/transaction-fee.ts +++ b/src/utils/transaction-fee.ts @@ -11,8 +11,11 @@ export async function getConfirmedTransactionFeeLamports( commitment: "confirmed", maxSupportedTransactionVersion: 0, }); - const fee = transaction?.meta?.fee; - return typeof fee === "number" && Number.isSafeInteger(fee) && fee >= 0 ? fee : null; + const fee: unknown = transaction?.meta?.fee; + // The Kit-backed client returns bigint. Older connections returned number. + if (typeof fee !== "bigint" && typeof fee !== "number") return null; + const lamports = Number(fee); + return Number.isSafeInteger(lamports) && lamports >= 0 ? lamports : null; } catch (error) { console.warn(`Unable to read network fee for ${signature}:`, error); return null; diff --git a/tests/swap-service.edge-cases.test.ts b/tests/swap-service.edge-cases.test.ts index 8bdc9df1..0de78f0b 100644 --- a/tests/swap-service.edge-cases.test.ts +++ b/tests/swap-service.edge-cases.test.ts @@ -5,7 +5,7 @@ import { TransactionHistory } from "../src/utils/transaction-history"; const formatSol = (lamports: number) => `${lamports / 1e9}`; -const makeWallet = (balance: number, fee: number | null = 5_000) => ({ +const makeWallet = (balance: number, fee: number | bigint | null = 5_000) => ({ getConnection: () => ({ rpcEndpoint: "http://test-swap-service", getBalance: async () => balance, @@ -88,9 +88,11 @@ describe("SwapService", () => { test("records sponsor cost from the confirmed fee and omits an absent reimbursement", async () => { const { backend, executed } = makeBackend("sig-sponsor"); - const service = new SwapService(makeWallet(10_000_000, 7_500) as any, backend); + const service = new SwapService(makeWallet(10_000_000, 7_500n) as any, backend); const user = await Keypair.generate(); - const quote = adminQuote(); + const quote = adminQuote({ + providerQuote: { signatureFeeLamports: 5_000, prioritizationFeeLamports: 1_000 }, + }); expect(await service.execute(quote, user)).toBe("sig-sponsor"); diff --git a/tests/transaction-fee.test.ts b/tests/transaction-fee.test.ts index 43a9601d..5ae5afe7 100644 --- a/tests/transaction-fee.test.ts +++ b/tests/transaction-fee.test.ts @@ -1,4 +1,5 @@ import { afterEach, beforeEach, describe, expect, mock, spyOn, test } from "bun:test"; +import { Connection } from "#solana"; import { getConfirmedTransactionFeeLamports } from "../src/utils/transaction-fee"; let warnSpy: ReturnType; @@ -41,6 +42,69 @@ describe("getConfirmedTransactionFeeLamports", () => { test("returns null when the connection cannot fetch transactions", async () => { expect(await getConfirmedTransactionFeeLamports({} as any, "sig")).toBeNull(); + expect(warnSpy).not.toHaveBeenCalled(); + }); + + test("reads the exact fee through the real Solana client without a live request", async () => { + const signature = "1".repeat(64); + const publicKey = "11111111111111111111111111111111"; + let calls = 0; + let request: { id: string; method: unknown; params: unknown } | undefined; + const fetch = Object.assign( + async (_input: string | URL | Request, init?: RequestInit) => { + calls++; + if (typeof init?.body !== "string") throw new Error("Expected a JSON request body"); + const payload: { id: string; method: unknown; params: unknown } = JSON.parse(init.body); + request = payload; + return Response.json({ + jsonrpc: "2.0", + id: payload.id, + result: { + slot: 10, + version: "legacy", + transaction: { + signatures: [signature], + message: { + accountKeys: [publicKey], + header: { + numRequiredSignatures: 1, + numReadonlySignedAccounts: 0, + numReadonlyUnsignedAccounts: 0, + }, + instructions: [], + recentBlockhash: publicKey, + }, + }, + meta: { err: null, fee: 7_500, preBalances: [10_000], postBalances: [2_500] }, + }, + }); + }, + { preconnect: () => {} }, + ); + const connection = new Connection("https://rpc.example", { fetch }); + + const fee = await getConfirmedTransactionFeeLamports(connection, signature); + expect(calls).toBe(1); + expect(warnSpy.mock.calls).toEqual([]); + expect(request).toMatchObject({ + method: "getTransaction", + params: [signature, { commitment: "confirmed", maxSupportedTransactionVersion: 0 }], + }); + expect(fee).toBe(7_500); + }); + + test.each([ + ["zero", 0n, 0], + ["the largest safe integer", 9_007_199_254_740_991n, Number.MAX_SAFE_INTEGER], + ["one above the safe integer range", 9_007_199_254_740_992n, null], + ["the largest chain fee field", 18_446_744_073_709_551_615n, null], + ["a negative integer", -1n, null], + ] as const)("handles a bigint fee of %s without rounding", async (_label, fee, expected) => { + const connection = connectionReturning({ meta: { fee } }); + const rpc = connection as unknown as Pick; + + expect(await getConfirmedTransactionFeeLamports(rpc, "sig")).toBe(expected); + expect(warnSpy).not.toHaveBeenCalled(); }); test.each([ From 630570091c6842bc1aaf8afadc75cb7b33b49013 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 20:32:51 -0300 Subject: [PATCH 194/410] test(telegram): verify rate-limit error shape and fallback delay --- tests/telegram-errors.test.ts | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/tests/telegram-errors.test.ts b/tests/telegram-errors.test.ts index 50cb2638..f1fa35ca 100644 --- a/tests/telegram-errors.test.ts +++ b/tests/telegram-errors.test.ts @@ -117,11 +117,37 @@ describe("telegram error helpers", () => { test("recognizes a bare numeric 429 and otherwise uses the response text", () => { expect(isRateLimited({ error_code: 429 })).toBe(true); + expect(isRateLimited({ error_code: "429" })).toBe(false); expect(isRateLimited({ error_code: 400 })).toBe(false); expect(isRateLimited(null)).toBe(false); expect(isRateLimited({ message: "Retry After 123" })).toBe(true); }); + test("does not inspect a thrown callback as a Telegram error object", () => { + let reads = 0; + const callback = () => {}; + Object.defineProperties(callback, { + error_code: { + get() { + reads++; + return 429; + }, + }, + description: { + get() { + reads++; + return "Too many requests: retry after 7"; + }, + }, + }); + + expect(getErrorDescription(callback)).toBe(""); + expect(isRateLimited(callback)).toBe(false); + expect(isBotInitiationForbidden(callback)).toBe(false); + expect(getRetryAfterSeconds(callback)).toBeNull(); + expect(reads).toBe(0); + }); + test("getRetryAfterSeconds reads retry_after from Telegram error objects and descriptions", () => { expect(getRetryAfterSeconds({ error_code: 429, parameters: { retry_after: 7 } })).toBe(7); expect(getRetryAfterSeconds({ retry_after: 2 })).toBe(2); @@ -151,6 +177,7 @@ describe("telegram error helpers", () => { getRetryAfterSeconds({ parameters: { retry_after: "4" }, retry_after: 7, description }), ).toBe(7); expect(getRetryAfterSeconds({ parameters: { retry_after: NaN }, description })).toBe(123); + expect(getRetryAfterSeconds({ parameters: { retry_after: -Infinity }, description })).toBe(123); expect(getRetryAfterSeconds({ retry_after: Infinity, description })).toBe(123); expect(getRetryAfterSeconds({ description })).toBe(123); expect(getRetryAfterSeconds({ description: null, message: description })).toBe(123); From 0e71397162173c7cd83286f3e76f4ca8fabd268f Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 20:34:11 -0300 Subject: [PATCH 195/410] refactor(telegram): test retry hints with one finite-number check --- src/utils/telegram-errors.ts | 11 +++++++---- tests/telegram-errors.test.ts | 11 +++++++++++ 2 files changed, 18 insertions(+), 4 deletions(-) diff --git a/src/utils/telegram-errors.ts b/src/utils/telegram-errors.ts index 09d19358..cbf336c8 100644 --- a/src/utils/telegram-errors.ts +++ b/src/utils/telegram-errors.ts @@ -1,6 +1,9 @@ import { retrySecondsToMilliseconds } from "./retry-delay"; type ErrorText = { description?: unknown; message?: unknown }; +type RetryAfterFields = { parameters?: { retry_after?: unknown } | null; retry_after?: unknown }; + +const isFiniteNumber = (value: unknown): value is number => Number.isFinite(value); const getErrorString = (value: unknown): string => { if (typeof value === "string") { @@ -87,14 +90,14 @@ export const getRetryAfterSeconds = (error: unknown): number | null => { return null; } - const parameters = (error as any).parameters; + const response = error as RetryAfterFields; + const parameters = response.parameters; const retryAfter = (parameters && typeof parameters.retry_after === "number" ? parameters.retry_after - : undefined) ?? - (typeof (error as any).retry_after === "number" ? (error as any).retry_after : undefined); + : undefined) ?? (typeof response.retry_after === "number" ? response.retry_after : undefined); - if (typeof retryAfter === "number" && Number.isFinite(retryAfter)) { + if (isFiniteNumber(retryAfter)) { const seconds = Math.max(0, retryAfter); if (retrySecondsToMilliseconds(seconds) !== null) return seconds; } diff --git a/tests/telegram-errors.test.ts b/tests/telegram-errors.test.ts index f1fa35ca..6cb9c1af 100644 --- a/tests/telegram-errors.test.ts +++ b/tests/telegram-errors.test.ts @@ -167,6 +167,17 @@ describe("telegram error helpers", () => { ).toBe(7); }); + test.each([ + ["fractional seconds", 1.25, 1.25], + ["negative seconds", -1.25, 0], + ["negative zero", -0, 0], + ["a numeric string", "1.25", 7], + ["an infinite value", -Infinity, 7], + ["an absent value", undefined, 7], + ] as const)("reads %s without coercing the provider field", (_label, retry_after, expected) => { + expect(getRetryAfterSeconds({ retry_after, description: "Retry after 7" })).toBe(expected); + }); + test("prefers the structured delay, keeps zero, and reads the whole fallback delay", () => { const description = "Too Many Requests: retry after 123"; expect( From c58279e9ce82bacc678b25c25146da1d7f3c4335 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 20:36:44 -0300 Subject: [PATCH 196/410] test(alerts): pin the preview and failed delivery diagnostics --- tests/buy-alerts.publisher.test.ts | 99 ++++++++++++++++++------------ 1 file changed, 61 insertions(+), 38 deletions(-) diff --git a/tests/buy-alerts.publisher.test.ts b/tests/buy-alerts.publisher.test.ts index 5c47aee7..d7a81721 100644 --- a/tests/buy-alerts.publisher.test.ts +++ b/tests/buy-alerts.publisher.test.ts @@ -276,19 +276,26 @@ test("publisher retries a signature when every delivery fails", async () => { chatDb.upsertChatBuyAlerts(-20, { enabled: true }); let attempts = 0; + const failure = new Error("temporary Telegram failure"); const publisher = createBuyAlertPublisher({ chatDb, tokenManager, sendHtml: async () => { attempts += 1; if (attempts === 1) { - throw new Error("temporary Telegram failure"); + throw failure; } }, fetchPairStats: async () => null, }); - expect((await publisher.publish(event({ signature: "retry-all" }))).posted).toBe(0); + const errorLog = spyOn(console, "error").mockImplementation(() => {}); + try { + expect((await publisher.publish(event({ signature: "retry-all" }))).posted).toBe(0); + expect(errorLog.mock.calls).toEqual([["Failed to send buy alert to chat -20:", failure]]); + } finally { + errorLog.mockRestore(); + } expect((await publisher.publish(event({ signature: "retry-all" }))).posted).toBe(1); expect((await publisher.publish(event({ signature: "retry-all" }))).skipped).toEqual([ "duplicate", @@ -448,42 +455,58 @@ test("allows the exact lamport minimum but rejects missing and non-finite SOL si expect(posted).toHaveLength(1); }); -test("preview uses the selected pool label, SOL conversion, and configured Telegram media", async () => { - const chatDb = ChatDatabase.getInstance(); - chatDb.upsertChatBuyAlerts(-1, { enabled: false, media_file_id: " video-id " }); - const pair: PairStats = { - priceUsd: null, - marketCapUsd: null, - priceChangeH24: null, - url: null, - dexId: "Raydium CLMM", - quoteSymbol: "SOL", - pairAddress: null, - tokenName: null, - }; - const sent: Array<{ html: string; media: unknown }> = []; - const publisher = createBuyAlertPublisher({ - chatDb, - tokenManager, - fetchPairStats: async () => pair, - fetchSolPriceUsd: async () => 100, - sendHtml: async (_id, html, media) => { - sent.push({ html, media }); - }, - }); - await publisher.sendTest(-1); - expect(sent).toEqual([ - { - html: expect.stringContaining("Spent: 1.8998 SOL ($189.98)"), - media: { fileId: "video-id", mediaType: "video" }, - }, - ]); - expect(sent[0]?.html).toContain("Raydium AMM"); - expect(sent[0]?.html).toContain("111111...1112"); - chatDb.upsertChatBuyAlerts(-1, { media_file_id: CHAT_MEDIA_DISABLED_SENTINEL }); - expect(resolveBuyAlertMedia(chatDb.getChatBuyAlerts(-1))).toBeNull(); - expect(resolveBuyAlertMedia(null)).toBeNull(); -}); +test.each([ + ["Raydium CLMM", "DEX: ⚡ Raydium AMM SOL"], + [null, "DEX: 💊 Pump.fun SOL"], +] as const)( + "preview uses pool %p, the conversion, and the configured media", + async (dexId, label) => { + const chatDb = ChatDatabase.getInstance(); + chatDb.upsertChatBuyAlerts(-1, { enabled: false, media_file_id: " video-id " }); + const pair: PairStats = { + priceUsd: null, + marketCapUsd: null, + priceChangeH24: null, + url: null, + dexId, + quoteSymbol: "SOL", + pairAddress: null, + tokenName: null, + }; + const sent: Array<{ html: string; media: unknown }> = []; + const publisher = createBuyAlertPublisher({ + chatDb, + tokenManager, + now: () => 123_456, + fetchPairStats: async () => pair, + fetchSolPriceUsd: async () => 100, + sendHtml: async (_id, html, media) => { + sent.push({ html, media }); + }, + }); + const env: { SOLANA_NETWORK?: string } = process.env; + const previousNetwork = env.SOLANA_NETWORK; + env.SOLANA_NETWORK = "https://api.mainnet-beta.solana.com"; + try { + await publisher.sendTest(-1); + } finally { + if (previousNetwork === undefined) delete env.SOLANA_NETWORK; + else env.SOLANA_NETWORK = previousNetwork; + } + expect(sent).toEqual([ + { + html: expect.stringContaining("Spent: 1.8998 SOL ($189.98)"), + media: { fileId: "video-id", mediaType: "video" }, + }, + ]); + expect(sent[0]?.html.split("\n")).toContain(label); + expect(sent[0]?.html).toContain('[Txn]'); + expect(sent[0]?.html).toContain("111111...1112"); + chatDb.upsertChatBuyAlerts(-1, { media_file_id: CHAT_MEDIA_DISABLED_SENTINEL }); + expect(resolveBuyAlertMedia(chatDb.getChatBuyAlerts(-1))).toBeNull(); + expect(resolveBuyAlertMedia(null)).toBeNull(); + }, +); test("refreshing a partially delivered signature does not block expiry of an older neighbor", async () => { let now = 1_000; From b04808fd96f09e7ebf229884d78b965ca8c027b4 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 20:39:37 -0300 Subject: [PATCH 197/410] test(bot): bound listener retries and invalid history traversal --- tests/event-listeners.failover.test.ts | 11 +++--- tests/game-completion-recovery.test.ts | 47 +++++++++++++++++++++----- 2 files changed, 45 insertions(+), 13 deletions(-) diff --git a/tests/event-listeners.failover.test.ts b/tests/event-listeners.failover.test.ts index 20e5eb36..1cba6b16 100644 --- a/tests/event-listeners.failover.test.ts +++ b/tests/event-listeners.failover.test.ts @@ -100,7 +100,7 @@ describe("program event listener management", () => { test("retries removal and retains failed listener handles", async () => { await __test_registerProgramEventListeners(); - const removalFailures = new Set([1]); + let remainingFailures = 3; __test_setProgram({ addEventListener: async (eventName: string) => { addCalls.push(eventName); @@ -108,7 +108,9 @@ describe("program event listener management", () => { }, removeEventListener: async (id: number) => { removeCalls.push(id); - if (removalFailures.has(id)) { + // The fourth call succeeds so an incorrect retry loop fails the + // retained-handle assertion instead of starving the test deadline. + if (id === 1 && remainingFailures-- > 0) { throw new Error("remove failed"); } }, @@ -127,7 +129,7 @@ describe("program event listener management", () => { test("retries failover restart when cleanup previously failed", async () => { const callbacks: Array<(change: ActiveEndpointChange) => void> = []; - let failCleanup = true; + let remainingFailures = 3; (wallet as any).onRpcEndpointChange = (listener: (change: ActiveEndpointChange) => void) => { callbacks.push(listener); @@ -151,7 +153,7 @@ describe("program event listener management", () => { }, removeEventListener: async (id: number) => { removeCalls.push(id); - if (failCleanup && id === 1) { + if (id === 1 && remainingFailures-- > 0) { throw new Error("remove failed"); } }, @@ -180,7 +182,6 @@ describe("program event listener management", () => { expect(afterFailedRestart.playerJoinedListenerId).toBeNull(); expect(afterFailedRestart.playerRefundedListenerId).toBeNull(); - failCleanup = false; failoverCallback?.(change); await new Promise((resolve) => setTimeout(resolve, 0)); diff --git a/tests/game-completion-recovery.test.ts b/tests/game-completion-recovery.test.ts index 0904baca..233a0bd7 100644 --- a/tests/game-completion-recovery.test.ts +++ b/tests/game-completion-recovery.test.ts @@ -15,6 +15,32 @@ const botModulePromise = import("../src/bot"); const createTestGameAddress = async () => (await Keypair.generate()).publicKey.toBase58(); +const checkedHistory = (records: T[]) => { + const invalidOffsets: number[] = []; + const rejectNegativeOffset = (offset: number) => { + if (offset >= 0) return; + invalidOffsets.push(offset); + throw new RangeError("Completion history read moved backwards"); + }; + const rows = new Proxy(records, { + get(target, property, receiver) { + if (property !== "slice") return Reflect.get(target, property, receiver); + return (offset: number, end: number) => { + rejectNegativeOffset(offset); + return new Proxy(target.slice(offset, end), { + get(window, index, windowReceiver) { + if (typeof index === "string" && /^-\d+$/.test(index)) { + rejectNegativeOffset(Number(index)); + } + return Reflect.get(window, index, windowReceiver); + }, + }); + }; + }, + }); + return { rows, invalidOffsets }; +}; + const createCompletionEvent = ( gameAddress: string, overrides: Partial> = {}, @@ -152,14 +178,16 @@ describe("Game completion recovery", () => { test("the default parser reads events for the configured program", async () => { const gameAddress = await createTestGameAddress(); + const history = checkedHistory([{ signature: "sig-1" }]); const connectionStub = { - getSignaturesForAddress: async () => [{ signature: "sig-1" }], + getSignaturesForAddress: async () => history.rows, getTransaction: async () => ({ meta: { logMessages: ["Program log: nothing here"] } }), }; const originalGetConnection = botModule.wallet.getConnection.bind(botModule.wallet); botModule.wallet.getConnection = () => connectionStub as any; try { expect(await botModule.__test_fetchCompletionDetailsFromHistory(gameAddress)).toBeNull(); + expect(history.invalidOffsets).toEqual([]); } finally { botModule.wallet.getConnection = originalGetConnection; } @@ -168,17 +196,19 @@ describe("Game completion recovery", () => { test("history lookups without a program, signatures or transactions find nothing", async () => { const gameAddress = await createTestGameAddress(); const originalGetConnection = botModule.wallet.getConnection.bind(botModule.wallet); - let signatures: Array<{ signature?: string }> = []; + let history = checkedHistory<{ signature?: string }>([]); botModule.wallet.getConnection = () => ({ - getSignaturesForAddress: async () => signatures, + getSignaturesForAddress: async () => history.rows, getTransaction: async () => null, }) as any; try { expect(await botModule.__test_fetchCompletionDetailsFromHistory(gameAddress)).toBeNull(); + expect(history.invalidOffsets).toEqual([]); - signatures = [{ signature: "" }, { signature: "missing-tx" }]; + history = checkedHistory([{ signature: "" }, { signature: "missing-tx" }]); expect(await botModule.__test_fetchCompletionDetailsFromHistory(gameAddress)).toBeNull(); + expect(history.invalidOffsets).toEqual([]); botModule.__test_setProgram(undefined); expect(await botModule.__test_fetchCompletionDetailsFromHistory(gameAddress)).toBeNull(); @@ -275,9 +305,9 @@ describe("Game completion recovery", () => { test("fetch completion history continues after empty batches", async () => { const gameAddress = await createTestGameAddress(); - const signatures = Array.from({ length: 6 }, (_, index) => ({ - signature: `completion-${index}`, - })); + const history = checkedHistory( + Array.from({ length: 6 }, (_, index) => ({ signature: `completion-${index}` })), + ); const transactionResponses: Array<{ meta: { logMessages: string[] } } | null> = [ null, @@ -295,7 +325,7 @@ describe("Game completion recovery", () => { let txCallCount = 0; const connectionStub = { - getSignaturesForAddress: async () => signatures, + getSignaturesForAddress: async () => history.rows, getTransaction: async () => { const response = transactionResponses[txCallCount]; txCallCount += 1; @@ -321,6 +351,7 @@ describe("Game completion recovery", () => { try { const details = await botModule.__test_fetchCompletionDetailsFromHistory(gameAddress); + expect(history.invalidOffsets).toEqual([]); expect(details).toEqual({ winnerAddress: "WinnerPubkey", totalPot: 24_240, From 2b0b7e315fd3c1eb8f8eeff667f8962c16281668 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 20:41:36 -0300 Subject: [PATCH 198/410] test(game): distinguish confirmed completion events from other logs --- tests/game-completion-recovery.test.ts | 27 ++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/tests/game-completion-recovery.test.ts b/tests/game-completion-recovery.test.ts index 233a0bd7..7f9b88ee 100644 --- a/tests/game-completion-recovery.test.ts +++ b/tests/game-completion-recovery.test.ts @@ -142,6 +142,33 @@ describe("Game completion recovery", () => { }); }); + test.each(["GameCompleted", "gameCompleted"] as const)( + "accepts %s after an empty event and an unrelated game event", + async (name) => { + const gameAddress = await createTestGameAddress(); + const wrongEvent = { + ...createCompletionEvent(gameAddress, { winner: "WrongWinner" }), + name: "PlayerJoined", + }; + const rightEvent = { + ...createCompletionEvent(gameAddress, { winner: "ActualWinner" }), + name, + }; + const parser = { + parseLogs: () => [null, wrongEvent, rightEvent], + } as unknown as Parameters[1]; + + expect( + botModule.__test_parseCompletionEventFromLogs(["Program log"], parser, gameAddress), + ).toEqual({ + winnerAddress: "ActualWinner", + totalPot: 24_240, + feeAmountRaw: "240", + winnerAmount: 24_000, + }); + }, + ); + test("accepts plain and bigint amounts and ignores unreadable ones", async () => { const gameAddress = await createTestGameAddress(); const parse = (overrides: Record) => From ea1f2a06e2b0904906c6018c3b1dbbb42240331a Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 20:43:44 -0300 Subject: [PATCH 199/410] test(game): skip winner announcements for cancelled results --- tests/bot.flows.test.ts | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/tests/bot.flows.test.ts b/tests/bot.flows.test.ts index 2b7bfdd2..8e1e832b 100644 --- a/tests/bot.flows.test.ts +++ b/tests/bot.flows.test.ts @@ -214,6 +214,20 @@ describe("game completion announcements", () => { expect(texts().some((text) => text.includes("A&B won the coinflip!"))).toBe(true); }); + + test.each([ + ["a blank winner", ""], + ["a cancellation", "cancelled"], + ["the empty Solana address", "11111111111111111111111111111111"], + ] as const)("does not announce %s", async (_label, winner) => { + const usernameFor = mock((_address: string) => "Unexpected Winner"); + setup("coinflip", usernameFor); + + await botModule.__test_processGameCompletion("GAME_WITHOUT_WINNER", winner); + + expect(usernameFor).not.toHaveBeenCalled(); + expect(callsTo("sendMessage")).toEqual([]); + }); }); describe("/leaderboard membership edge cases", () => { From 0e516462411a9c0ad99807eb23880450945d3ca2 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 20:45:27 -0300 Subject: [PATCH 200/410] test(game): verify winner prize precedence and zero boundaries --- tests/bot.flows.test.ts | 67 ++++++++++++++++++++++++++++++++++++++--- 1 file changed, 63 insertions(+), 4 deletions(-) diff --git a/tests/bot.flows.test.ts b/tests/bot.flows.test.ts index 8e1e832b..7f092624 100644 --- a/tests/bot.flows.test.ts +++ b/tests/bot.flows.test.ts @@ -177,17 +177,36 @@ describe("game completion announcements", () => { botModule.__test_setGameManager(savedGameManager); }); - const setup = (gameType: string, usernameFor: (winner: string) => string) => { + type PrizeLookup = ReturnType["getPrizeDisplay"]; + + const setup = ( + gameType: string, + usernameFor: (winner: string) => string, + options: { + amount?: number; + storedTotal?: number; + participantCount?: number; + getPrizeDisplay?: PrizeLookup; + } = {}, + ) => { botModule.__test_setGameDatabase({ - getGame: () => ({ chat_id: 42, message_id: 24, game_type: gameType }), + getGame: () => ({ + chat_id: 42, + message_id: 24, + game_type: gameType, + amount: options.amount, + total_amount: options.storedTotal, + token_ticker: "GOLD", + token_mint: "mint-for-prize", + }), completeGame: () => {}, - getGameParticipantsCount: () => 2, + getGameParticipantsCount: () => options.participantCount ?? 2, getGameMessages: () => [], } as any); botModule.__test_setGameManager({ updateGameMessageFromData: async () => {}, getPlayerUsername: async (_ctx: unknown, winner: string) => usernameFor(winner), - getPrizeDisplay: async () => undefined, + getPrizeDisplay: options.getPrizeDisplay ?? (async () => null), getActiveGameMessage: () => ({ chatId: 42, messageId: 24 }), } as any); }; @@ -228,6 +247,46 @@ describe("game completion announcements", () => { expect(usernameFor).not.toHaveBeenCalled(); expect(callsTo("sendMessage")).toEqual([]); }); + + test.each([ + ["winner amount", "coinflip", 7, 50, 90, 100, 2, 7], + ["reported pot", "coinflip", undefined, 50, 90, 100, 2, 50], + ["stored total", "coinflip", undefined, undefined, 90, 100, 2, 90], + ["per-player stake", "coinflip", undefined, undefined, undefined, 100, 3, 300], + ["standalone giveaway", "giveaway", undefined, undefined, undefined, 100, 3, 100], + ["empty game", "coinflip", undefined, undefined, undefined, 100, 0, null], + ["explicit zero", "coinflip", 0, 50, 90, 100, 2, null], + ] as const)( + "uses the %s when calculating the winner's prize", + async ( + _label, + gameType, + winnerAmount, + reportedPot, + storedTotal, + amount, + participantCount, + expected, + ) => { + const getPrizeDisplay = mock(async () => null); + setup(gameType, () => "Winner", { amount, storedTotal, participantCount, getPrizeDisplay }); + + await botModule.__test_processGameCompletion( + "GAME_PRIZE", + "winner-address", + reportedPot, + undefined, + winnerAmount, + ); + + expect(getPrizeDisplay.mock.calls).toEqual( + expected === null ? [] : [["GAME_PRIZE", expected, "GOLD", "mint-for-prize"]], + ); + expect(callsTo("sendMessage").map((call) => call.payload.text)).toEqual([ + `🏆 Winner won the ${gameType}!`, + ]); + }, + ); }); describe("/leaderboard membership edge cases", () => { From 48a35cb55fd0191d9abb5bc7b7b4bcc619e3e022 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 20:47:28 -0300 Subject: [PATCH 201/410] test(bot): keep join and refresh callbacks in the game queue --- tests/bot-main.test.ts | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/tests/bot-main.test.ts b/tests/bot-main.test.ts index 086be265..9c5015b3 100644 --- a/tests/bot-main.test.ts +++ b/tests/bot-main.test.ts @@ -1,4 +1,5 @@ import { describe, test, expect, beforeAll, afterAll } from "bun:test"; +import { Context } from "grammy"; import { LAMPORTS_PER_SOL } from "../src/utils/constants"; let botModule: typeof import("../src/bot"); @@ -164,6 +165,33 @@ describe("Bot Main Entry Point Tests", () => { } as any), ).toBe("42"); }); + + test.each([ + ["join_GameAddress", ["42", "game_GameAddress"]], + ["refresh_GameAddress", ["42", "game_GameAddress"]], + ["wallet_page_2", "42"], + ["unrelated_join_", "42"], + ["unrelated_refresh_", "42"], + ["", "42"], + ] as const)("selects the exact queue for callback %p", (data, expected) => { + const context = new Context( + { + update_id: 10, + callback_query: { + id: "test-callback", + chat_instance: "test-chat", + from: { id: 42, is_bot: false, first_name: "Player" }, + data, + }, + }, + botModule.bot.api, + botModule.bot.botInfo, + ); + + expect(botModule.__test_getSequentializationKey(context)).toEqual( + typeof expected === "string" ? expected : [...expected], + ); + }); }); describe("Global State Management", () => { From 40d7ec62ac557be828cc68fb465b945f5ae049be Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 20:48:30 -0300 Subject: [PATCH 202/410] test(swap): verify SOL price aliases and exact referral fees --- tests/swap-integrator-sanitization.test.ts | 35 ++++++++++++++++++++++ 1 file changed, 35 insertions(+) diff --git a/tests/swap-integrator-sanitization.test.ts b/tests/swap-integrator-sanitization.test.ts index f543b2a1..5bd6895c 100644 --- a/tests/swap-integrator-sanitization.test.ts +++ b/tests/swap-integrator-sanitization.test.ts @@ -799,6 +799,41 @@ describe("buildAdminIntegratorConfig funding and pricing", () => { restoreConn(); } }); + + test.each([ + ["wrapped SOL mint", WSOL_MINT, "UNKNOWN", WSOL_MINT, 100, 200, 95], + ["trimmed SOL ticker", "token-input", " sOl ", WSOL_MINT, 100, 200, 95], + ["another token", "token-input", "TOKEN", "token-input", 20, 100, 135], + ] as const)( + "prices the %s with the correct mint and surcharge", + async ( + _label, + tradeMint, + tradeTicker, + expectedMint, + tradePrice, + laterSolPrice, + expectedFee, + ) => { + const restoreConn = stubWalletConnection(10_000_000_000); + const priceSpy = vi.spyOn(priceService, "getUsdPrice").mockResolvedValue(null); + priceSpy + .mockResolvedValueOnce({ price: tradePrice, identifier: expectedMint, resolvedAt: 1_000 }) + .mockResolvedValueOnce({ price: laterSolPrice, identifier: WSOL_MINT, resolvedAt: 1_000 }); + try { + const config = await build({ tradeMint, tradeTicker, solFeeBufferLamports: 1_000_000 }); + + expect(priceSpy.mock.calls).toEqual([ + [{ tokenMint: expectedMint }], + [{ tokenMint: WSOL_MINT }], + ]); + expect(config.referralFee).toBe(expectedFee); + } finally { + priceSpy.mockRestore(); + restoreConn(); + } + }, + ); }); describe("prepareIntegratorForQuote without an integrator", () => { From c169a854f4a77e3c9faab6c56251f3950a13188b Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 20:52:57 -0300 Subject: [PATCH 203/410] test(game): verify orphan cleanup at the oracle and ticket boundaries --- tests/game-manager.cancel-orphaned.test.ts | 62 ++++++++++++++++++++-- 1 file changed, 59 insertions(+), 3 deletions(-) diff --git a/tests/game-manager.cancel-orphaned.test.ts b/tests/game-manager.cancel-orphaned.test.ts index 624ac59a..b7a3d4ba 100644 --- a/tests/game-manager.cancel-orphaned.test.ts +++ b/tests/game-manager.cancel-orphaned.test.ts @@ -1,13 +1,69 @@ -import { describe, test, expect } from "bun:test"; +import { describe, test, expect, mock, spyOn } from "bun:test"; import { GameManager } from "../src/utils/game"; import { PublicKey } from "#solana"; +import { GAME_EXPIRATION_BUFFER_TIME } from "../src/utils/constants"; function resetGM() { - // @ts-ignore - GameManager["instance"] = undefined; + GameManager.resetForTest(); } describe("GameManager.cancelOrphanedGame and scan", () => { + test.each([ + ["minimum at the last buffer second", "coinflip", 2, 2, 0, false], + ["above minimum before the buffer ends", "giveaway", 3, 2, -1, false], + ["minimum after the buffer ends", "coinflip", 2, 2, 1, true], + ["below minimum before the buffer ends", "coinflip", 1, 2, 0, true], + ["zero minimum before the buffer ends", "giveaway", 0, 0, 0, true], + ["missing minimum before the buffer ends", "coinflip", 0, undefined, 0, true], + ] as const)( + "scans an unknown game with %s", + async (_label, type, ticketsCount, minTickets, offsetFromBuffer, cleansUp) => { + type GameDependencies = Parameters; + const address = new PublicKey("BPFLoader1111111111111111111111111111111111"); + const createdAt = 1_700_000_000; + const timeout = 60; + const account = { + createdAt, + timeout, + ticketsCount, + minTickets, + maxTickets: 4, + gameType: { [type]: {} }, + }; + const fetch = mock(async (_address: PublicKey) => account); + const program = { + account: { game: { all: async () => [{ publicKey: address, account }], fetch } }, + }; + const db = { gameExists: () => false }; + const manager = GameManager.getInstance( + program as unknown as GameDependencies[0], + {} as GameDependencies[1], + db as unknown as GameDependencies[2], + ); + type Cleanup = (game: PublicKey, data: unknown, address: string) => Promise; + const handlers = manager as unknown as { + handleExpiredCoinflip: Cleanup; + handleExpiredGiveaway: Cleanup; + }; + const cleanCoinflip = spyOn(handlers, "handleExpiredCoinflip").mockResolvedValue(true); + const cleanGiveaway = spyOn(handlers, "handleExpiredGiveaway").mockResolvedValue(true); + const now = spyOn(Date, "now").mockReturnValue( + (createdAt + timeout + GAME_EXPIRATION_BUFFER_TIME + offsetFromBuffer) * 1_000, + ); + try { + await manager.scanBlockchainForOrphanedGames(); + expect(fetch.mock.calls).toEqual([[address]]); + const expected: Parameters[] = [[address, account, address.toBase58()]]; + expect(cleanCoinflip.mock.calls).toEqual(cleansUp && type === "coinflip" ? expected : []); + expect(cleanGiveaway.mock.calls).toEqual(cleansUp && type === "giveaway" ? expected : []); + } finally { + now.mockRestore(); + cleanCoinflip.mockRestore(); + cleanGiveaway.mockRestore(); + } + }, + ); + test("cancelOrphanedGame returns false when not expired", async () => { resetGM(); const addr = new PublicKey("BPFLoader1111111111111111111111111111111111").toBase58(); From 134657df8a1af88338493e25f42ef0cae5777bfb Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 20:52:57 -0300 Subject: [PATCH 204/410] test(game): keep manager dependencies current across restarts --- tests/game-manager.restart.test.ts | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/tests/game-manager.restart.test.ts b/tests/game-manager.restart.test.ts index da68b146..5261ab19 100644 --- a/tests/game-manager.restart.test.ts +++ b/tests/game-manager.restart.test.ts @@ -20,6 +20,32 @@ function walletStub() { } describe("GameManager restart fallback", () => { + test.each(["program", "wallet", "database"] as const)( + "reuses the manager until its %s changes", + (dependency) => { + resetGM(); + type GameDb = Parameters[2]; + const makeDb = () => ({ getGame: () => null }) as unknown as GameDb; + const program = programStub(); + const wallet = walletStub(); + const db = makeDb(); + try { + const initial = GameManager.getInstance(program, wallet, db); + expect(GameManager.getInstance(program, wallet, db)).toBe(initial); + + const nextProgram = dependency === "program" ? programStub() : program; + const nextWallet = dependency === "wallet" ? walletStub() : wallet; + const nextDb = dependency === "database" ? makeDb() : db; + const updated = GameManager.getInstance(nextProgram, nextWallet, nextDb); + + expect(updated).not.toBe(initial); + expect(GameManager.getInstance(nextProgram, nextWallet, nextDb)).toBe(updated); + } finally { + resetGM(); + } + }, + ); + test("updateGameMessage restores message targets from database when in-memory map is empty", async () => { resetGM(); From 9ea6525b489938ac2e135b52bea62b4154c1e732 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 20:56:41 -0300 Subject: [PATCH 205/410] test(game): verify fallback card recovery after an unavailable account --- tests/game-manager.create-message.test.ts | 61 ++++++++++++++++++++--- 1 file changed, 54 insertions(+), 7 deletions(-) diff --git a/tests/game-manager.create-message.test.ts b/tests/game-manager.create-message.test.ts index ba9d1315..dd34ee07 100644 --- a/tests/game-manager.create-message.test.ts +++ b/tests/game-manager.create-message.test.ts @@ -1,10 +1,10 @@ -import { describe, test, expect } from "bun:test"; +import { describe, test, expect, mock, spyOn } from "bun:test"; import { GameManager } from "../src/utils/game"; import { PublicKey } from "#solana"; +import { stubInstantTimers, withinTestDeadline } from "./helpers/timers"; function resetGM() { - // @ts-ignore - GameManager["instance"] = undefined; + GameManager.resetForTest(); } function ctxStub(options: { videoError?: any } = {}) { @@ -62,8 +62,8 @@ describe("GameManager.createGameMessage", () => { "coinflip", 1_000_000_000, "@creator", - "Active", "TOK", + "Active", ); expect(id).toBe(333); expect((ctx as any).__calls[0][0]).toBe("video"); @@ -106,8 +106,8 @@ describe("GameManager.createGameMessage", () => { "giveaway", 1_000_000_000, "@creator", - "Active", "TOK", + "Active", ); expect(id).toBe(333); expect((ctx as any).__calls[0][0]).toBe("video"); @@ -152,8 +152,8 @@ describe("GameManager.createGameMessage", () => { "coinflip", 1_000_000_000, "@creator", - "Active", "TOK", + "Active", ); expect(id).toBe(444); const calls = (ctx as any).__calls; @@ -190,8 +190,8 @@ describe("GameManager.createGameMessage", () => { "coinflip", 1_000_000_000, "@creator", - "Active", "TOK", + "Active", ); const firstCall = (ctx as any).__calls[0]; @@ -200,4 +200,51 @@ describe("GameManager.createGameMessage", () => { expect(sentText).toContain("temporarily unavailable"); expect(sentText).not.toContain("Submit"); }); + + test("stores the fallback card and recovers it once the missing account returns", async () => { + resetGM(); + type GameDeps = Parameters; + const address = "BPFLoader4111111111111111111111111111111111"; + let accountAvailable = false; + let status = "active"; + const fetchNullable = mock(async (_address: PublicKey) => (accountAvailable ? {} : null)); + const saveGameMessage = mock((_address: string, _messageId: number, _chatId: number) => {}); + const program = { account: { game: { fetchNullable } } }; + const wallet = { formatTokenBalance: (amount: number) => String(amount) }; + const db = { getGame: () => ({ status }), saveGameMessage }; + const manager = GameManager.getInstance( + program as unknown as GameDeps[0], + wallet as unknown as GameDeps[1], + db as unknown as GameDeps[2], + ); + const fallback = ctxStub(); + const ctx = { ...fallback, chat: { id: 3 } }; + const recovered = Promise.withResolvers(); + const refresh = spyOn(manager, "updateGameMessageFromData").mockImplementation(async () => { + status = "completed"; + recovered.resolve(); + }); + const timers = stubInstantTimers(); + try { + const id = await manager.createGameMessage(ctx, address, "coinflip", 1_000, "Creator", "TOK"); + expect(id).toBe(333); + const firstCall = fallback.__calls[0]; + expect(firstCall[1].caption).toContain("temporarily unavailable"); + expect(firstCall[1].reply_markup.inline_keyboard).toEqual([ + [{ text: "🔁 Refresh", callback_data: `refresh_${address}` }], + ]); + expect(saveGameMessage.mock.calls).toEqual([[address, 333, 3]]); + + accountAvailable = true; + await withinTestDeadline(recovered.promise, "game state recovery"); + await Bun.sleep(0); + expect(refresh.mock.calls).toEqual([[ctx, address, "Active"]]); + expect(fetchNullable).toHaveBeenCalledTimes(2); + expect(timers.delays).toEqual([1_000]); + } finally { + timers.restore(); + refresh.mockRestore(); + resetGM(); + } + }); }); From 322462332743c9aeaa0e673f71149f3841e57231 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 20:59:06 -0300 Subject: [PATCH 206/410] test(game): preserve public cards with unknown expiry timing --- tests/game-manager.public-page.test.ts | 54 +++++++++++++++++++++++++- 1 file changed, 53 insertions(+), 1 deletion(-) diff --git a/tests/game-manager.public-page.test.ts b/tests/game-manager.public-page.test.ts index 96d4b592..d23ac564 100644 --- a/tests/game-manager.public-page.test.ts +++ b/tests/game-manager.public-page.test.ts @@ -196,6 +196,45 @@ describe("GameManager.getActivePublicGamesPage", () => { expect(second.games[0]!.gameAddress).toBe(later.publicKey.toBase58()); }); + test("expires a timed card after its last second without hiding cards with unknown timing", async () => { + const current = 1_700_000_000; + const clock = spyOn(Date, "now").mockReturnValue(current * 1_000); + const boundary = await makeGame({ createdAt: current - 60, timeout: 60 }); + const expired = await makeGame({ createdAt: current - 61, timeout: 60 }); + const hidden = await makeGame({ isPrivate: true }); + const unknown = await Promise.all( + [ + { createdAt: 0, timeout: 60 }, + { createdAt: -1, timeout: 60 }, + { createdAt: -Infinity, timeout: 60 }, + { createdAt: current - 100, timeout: 0 }, + { createdAt: current - 100, timeout: -1 }, + { createdAt: current - 100, timeout: -Infinity }, + ].map((timing) => makeGame(timing)), + ); + const all = vi.fn(async () => [expired, hidden, boundary, ...unknown]); + const manager = createManager( + { account: { game: { all } } }, + { getTokenMetadata: async () => ({ symbol: "TIMBA" }) }, + ); + stubFormatting(manager); + const readAddresses = async () => { + const result = await manager.getActivePublicGamesPage({} as Context, { + page: 0, + pageSize: 20, + }); + expect(result.totalGames).toBe(result.games.length); + return new Set(result.games.map((game) => game.gameAddress)); + }; + const unknownAddresses = unknown.map((game) => game.publicKey.toBase58()); + expect(await readAddresses()).toEqual( + new Set([boundary.publicKey.toBase58(), ...unknownAddresses]), + ); + clock.mockReturnValue((current + 1) * 1_000); + expect(await readAddresses()).toEqual(new Set(unknownAddresses)); + expect(all).toHaveBeenCalledTimes(1); + }); + test("filters by game type and ticker", async () => { const timbaMint = (await Keypair.generate()).publicKey; const coinflip = await makeGame({ tokenMint: timbaMint }); @@ -270,6 +309,8 @@ describe("GameManager active list batching", () => { gameDb, ); stubFormatting(manager); + const warn = spyOn(console, "warn").mockImplementation(() => {}); + const logError = spyOn(console, "error").mockImplementation(() => {}); const games = await manager.getChatActiveGames({} as any, -100); @@ -278,10 +319,13 @@ describe("GameManager active list batching", () => { expect(fetchNullable).not.toHaveBeenCalled(); expect(games.map((game) => game.gameAddress)).toEqual([present]); expect(games[0]).toMatchObject({ currentTickets: 1, maxTickets: 4, minTickets: 2 }); + expect(warn.mock.calls).toEqual([[`Omitting stale active game ${missing}; account is absent`]]); + expect(logError.mock.calls).toEqual([["Invalid game address", "not-a-key", expect.any(Error)]]); }); test("falls back to single lookups when the batch call fails", async () => { const address = (await Keypair.generate()).publicKey.toBase58(); + const failure = new Error("rpc down"); const fetchNullable = vi.fn(async () => ({ ticketsCount: 0, maxTickets: 2 })); const gameDb = { getActiveGames: vi.fn(() => [{ game_address: address, game_type: "coinflip" }]), @@ -291,7 +335,7 @@ describe("GameManager active list batching", () => { account: { game: { fetchMultiple: vi.fn(async () => { - throw new Error("rpc down"); + throw failure; }), fetchNullable, }, @@ -301,10 +345,14 @@ describe("GameManager active list batching", () => { gameDb, ); stubFormatting(manager); + const warn = spyOn(console, "warn").mockImplementation(() => {}); const games = await manager.getUserActiveGames({} as any, 7n); expect(fetchNullable).toHaveBeenCalledTimes(1); expect(games).toHaveLength(1); + expect(warn.mock.calls).toEqual([ + ["Batch game account lookup failed; falling back to single lookups:", failure], + ]); }); test("keeps a game returned by the single lookup when the batch omits it", async () => { @@ -326,9 +374,13 @@ describe("GameManager active list batching", () => { }, ); stubFormatting(manager); + const warn = spyOn(console, "warn").mockImplementation(() => {}); const games = await manager.getUserActiveGames({} as any, 7n); expect(fetchNullable.mock.calls.map(([key]) => key.toBase58())).toEqual([omittedAddress]); expect(games.map((row) => row.gameAddress)).toEqual([omittedAddress]); + expect(warn.mock.calls).toEqual([ + [`Omitting stale active game ${missingAddress}; account is absent`], + ]); }); }); From 4e8bdc0d5098cb1c849572c37bccdc5c4f8ba9a8 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 21:01:07 -0300 Subject: [PATCH 207/410] test(evm): reject malformed invitation IDs at the command boundary --- src/evm/bot.test.ts | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/src/evm/bot.test.ts b/src/evm/bot.test.ts index 9518c1f7..94fadf91 100644 --- a/src/evm/bot.test.ts +++ b/src/evm/bot.test.ts @@ -521,6 +521,7 @@ describe("EVM wallet commands", () => { signature: "0x12", }); await h.text(`/invite ${gameId} 202`); + expect(invite).toHaveBeenCalledWith(gameId, "1", "202"); expect(h.replies().at(-1)).toContain("Invitation saved for five minutes"); expect(h.store.invitation(gameId, "202")).toEqual({ body: JSON.stringify({ deadline: "1300", signature: "0x12" }), @@ -530,6 +531,29 @@ describe("EVM wallet commands", () => { expect(h.replies().at(-1)).toContain("Only the creator can invite"); invite.mockRestore(); }); + + test.each([ + ["extra prefix", `extra${gameId}`, "202"], + ["extra suffix", `${gameId}a`, "202"], + ["non-hex digits", `0x${"g".repeat(64)}`, "202"], + ["a short ID", `0x${"a".repeat(63)}`, "202"], + ["missing player", gameId, ""], + ] as const)("does not call the invitation service with %s", async (_label, game, player) => { + useEvm(); + const invite = spyOn(h.runtime.service, "invite").mockResolvedValue({ + deadline: "1300", + signature: "0x12", + }); + try { + await h.text(`/invite ${game} ${player}`); + expect(invite).not.toHaveBeenCalled(); + expect(h.replies().at(-1)).toBe( + "Only the creator can invite a Telegram ID to an open private game. Use /invite GAME_ID TELEGRAM_ID.", + ); + } finally { + invite.mockRestore(); + } + }); }); describe("EVM game commands", () => { From a9cb5d2a88230099fedd131c311b7d6ee3a48133 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 21:02:26 -0300 Subject: [PATCH 208/410] test(evm): preserve a single withdrawal unit without signing --- src/evm/bot.test.ts | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) diff --git a/src/evm/bot.test.ts b/src/evm/bot.test.ts index 94fadf91..d729e100 100644 --- a/src/evm/bot.test.ts +++ b/src/evm/bot.test.ts @@ -443,6 +443,37 @@ describe("EVM wallet commands", () => { expect(h.store.action(confirmSecond.split(":")[2])!.phase).toBe("new"); }); + test.each([ + ["eTh", "0.000000000000000001", "ETH", true], + ["uSdC", "0.000001", "USDC", false], + ] as const)( + "a mixed-case %s withdrawal keeps one exact base unit", + async (inputTicker, amount, ticker, native) => { + useEvm(); + await h.text(`/withdraw ${recipient} ${amount} ${inputTicker}`); + expect(h.replies().at(-1)).toBe( + `Withdraw ${amount} ${ticker} on Anvil to ${recipient}? Network fees are paid from this wallet's ETH balance.`, + ); + const markup = h.calls.filter(({ method }) => method === "editMessageReplyMarkup").at(-1); + const confirmation = markup?.payload.reply_markup.inline_keyboard[0][0].callback_data; + if (!confirmation) throw new Error("Expected a withdrawal confirmation button"); + const proposal = h.store.action(confirmation.split(":")[2]); + if (!proposal) throw new Error("Expected a withdrawal proposal"); + expect(proposal).toMatchObject({ + kind: "withdraw", + phase: "proposal", + raw: null, + hash: null, + }); + expect(JSON.parse(proposal.body)).toMatchObject({ + recipient, + native, + amount: "1", + ...(native ? {} : { token: usdcAddress }), + }); + }, + ); + test("expired withdrawal proposals fail instead of sending", async () => { useEvm(); await h.text(`/withdraw ${recipient} 1 ETH`); @@ -502,6 +533,11 @@ describe("EVM wallet commands", () => { for (const command of [ `/withdraw ${recipient} abc ETH`, `/withdraw ${recipient} 0 ETH`, + `/withdraw ${recipient} -1 ETH`, + `/withdraw ${recipient} +1 ETH`, + `/withdraw ${recipient} .1 ETH`, + `/withdraw ${recipient} 1. ETH`, + `/withdraw ${recipient} 1e-3 ETH`, `/withdraw ${recipient} 1.1234567 USDC`, `/withdraw not-an-address 1 ETH`, ]) { From 9eab990dfb93835ae98df39c345697fde2940826 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 21:04:01 -0300 Subject: [PATCH 209/410] test(evm): pin exact game card amounts and explorer links --- src/evm/bot.test.ts | 28 +++++++++++++++++++++++++--- 1 file changed, 25 insertions(+), 3 deletions(-) diff --git a/src/evm/bot.test.ts b/src/evm/bot.test.ts index d729e100..2a1ef6d3 100644 --- a/src/evm/bot.test.ts +++ b/src/evm/bot.test.ts @@ -882,24 +882,37 @@ describe("EVM refresh loop", () => { test("game messages are rendered, deferred when unchanged and show winners", async () => { h.store.message({ game: gameId, chat: 1, message: 9, body: "", creator: "1" }); const player = h.runtime.service.account("2").address; + const players = Array.from( + { length: 12 }, + (_, index): Address => `0x${(index + 1).toString(16).padStart(40, "0")}`, + ); const game = spyOn(h.runtime.service, "game").mockResolvedValue({ creator: player, token: tokenAddress, gameType: 0, status: 1, ticketAmount: 10n ** 18n, - totalAmount: 10n ** 18n, + totalAmount: 3n * 10n ** 18n, minPlayers: 2, - maxPlayers: 2, - participants: [player], + maxPlayers: 20, + participants: players, } as any); await h.runtime.refresh(); const open = h.calls.filter((c) => c.method === "editMessageText").at(-1)!; + expect(open.payload.text.split("\n")[0]).toBe("🪙 Coinflip 🔎 • 1 TEST"); + expect(open.payload.text).toContain(`Creator: ${player} • 12/20 players`); expect(open.payload.text).toContain("Network: Anvil"); + expect(open.payload.text).toContain("Prize pool: 3 TEST"); expect(open.payload.text).toContain(`Game: ${gameId}`); + expect(open.payload.text.split("\n").filter((line: Address) => players.includes(line))).toEqual( + players.slice(0, 10), + ); const buttons = open.payload.reply_markup.inline_keyboard.flat().map((b: any) => b.text); expect(buttons).toEqual(["View game", "Join", "Refund", "Close"]); + expect(open.payload.reply_markup.inline_keyboard[0][0].url).toBe( + `http://localhost/en/play/games/${gameId}?chainId=31337&deployment=${address}`, + ); // Unchanged text is deferred instead of edited again. const editsBefore = h.calls.filter((c) => c.method === "editMessageText").length; @@ -926,9 +939,18 @@ describe("EVM refresh loop", () => { h.store.db.query("UPDATE game_messages SET next_check=0").run(); await h.runtime.refresh(); const completed = h.calls.filter((c) => c.method === "editMessageText").at(-1)!; + expect(completed.payload.text.split("\n")[0]).toBe("🎁 Giveaway 🔎 • 2 TEST"); expect(completed.payload.text).toContain("Status: Completed"); expect(completed.payload.text).toContain(`Winner: ${player}`); expect(completed.payload.text).toContain("Prize: 2 TEST"); + expect(completed.payload.reply_markup.inline_keyboard).toEqual([ + [ + { + text: "View game", + url: `http://localhost/en/play/games/${gameId}?chainId=31337&deployment=${address}`, + }, + ], + ]); oracle.mockRestore(); game.mockResolvedValue({ From f816dc986b6a187452631892e9f08375469c7ee2 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 21:05:46 -0300 Subject: [PATCH 210/410] test(evm): route withdrawals to the correct configured network --- src/evm/bot.test.ts | 27 ++++++++++++++++++++++++++- 1 file changed, 26 insertions(+), 1 deletion(-) diff --git a/src/evm/bot.test.ts b/src/evm/bot.test.ts index 2a1ef6d3..98904587 100644 --- a/src/evm/bot.test.ts +++ b/src/evm/bot.test.ts @@ -268,7 +268,9 @@ describe("EVM token choice between networks", () => { ? { address: "sol-default", symbol: "SOL" } : value.toLowerCase() === "usdc" ? { address: "sol-usdc", symbol: "USDC" } - : null, + : value.toLowerCase() === "only" + ? { address: "sol-only", symbol: "ONLY" } + : null, }); }); @@ -346,6 +348,29 @@ describe("EVM token choice between networks", () => { expect(h.replies()).not.toContain("Choose the token for this game:"); expect(h.store.pending()).toHaveLength(1); }); + + test("a Solana-only withdrawal stays on Solana even when EVM is preferred", async () => { + useEvm(); + const command = `/withdraw ${recipient} 1 ONLY`; + + await h.text(command); + + expect(h.fallthrough).toEqual([command]); + expect(h.replies()).toEqual([]); + expect(h.calls.some(({ method }) => method === "editMessageReplyMarkup")).toBe(false); + }); + + test("withdrawals of a token available on both networks follow the chat preference", async () => { + const command = `/withdraw ${recipient} 1 USDC`; + await h.text(command); + expect(h.fallthrough).toEqual([command]); + expect(h.replies()).toEqual([]); + + useEvm(); + await h.text(command); + expect(h.fallthrough).toEqual([command]); + expect(h.replies().at(-1)).toContain(`Withdraw 1 USDC on Anvil to ${recipient}?`); + }); }); describe("network and token settings", () => { From be32b1181e7131d7e8246e9056123ae312477566 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 21:10:39 -0300 Subject: [PATCH 211/410] test(wallet): render callback media for matching bot authors --- tests/wallet-ui.handler.test.ts | 109 +++++++++++++++++++------------- 1 file changed, 66 insertions(+), 43 deletions(-) diff --git a/tests/wallet-ui.handler.test.ts b/tests/wallet-ui.handler.test.ts index c31eeab9..1f1ec9af 100644 --- a/tests/wallet-ui.handler.test.ts +++ b/tests/wallet-ui.handler.test.ts @@ -57,50 +57,73 @@ function makeCtx(options: MakeCtxOptions = {}) { } describe("wallet handler showWalletUI", () => { - test("edits existing wallet media for bot-authored callback messages", async () => { - const ctx: any = makeCtx(); - ctx.callbackQuery = { - message: { - message_id: 11, - from: { id: 42, is_bot: true }, - }, - }; - let capturedLines: any; - const deps: any = { - wallet: { - getKeyPair: () => ({ - publicKey: { toBase58: () => "WALLETADDR11111111111111111111111111111111" }, + test.each([ + ["an explicit bot author", undefined, 42, true, "edit"], + ["the matching bot ID", 42, 42, false, "edit"], + ["a serialized matching ID", 42, "42", false, "edit"], + ["another user", 42, 7, false, "video"], + ["a missing author ID", 42, undefined, false, "video"], + ["a missing bot ID", undefined, 42, false, "video"], + ["both IDs missing", undefined, undefined, false, "video"], + ] as const)( + "renders the wallet for %s with the correct media operation", + async (_label, botId, authorId, authorIsBot, expectedOperation) => { + const ctx: any = makeCtx(); + ctx.me.id = botId; + ctx.callbackQuery = { + message: { + message_id: 11, + from: { id: authorId, is_bot: authorIsBot }, + }, + }; + let capturedLines: any; + const deps: any = { + wallet: { + getKeyPair: () => ({ + publicKey: { toBase58: () => "WALLETADDR11111111111111111111111111111111" }, + }), + formatSolBalance: (_: number) => "0.000000", + formatTokenBalance: (n: number, d: number) => (n / Math.pow(10, d)).toFixed(0), + }, + getCachedWalletData: async () => ({ + solBalance: 0, + tokenBalances: [{ mint: "EPjF...USDC", ticker: "USDC", balance: 1000000, decimals: 6 }], }), - formatSolBalance: (_: number) => "0.000000", - formatTokenBalance: (n: number, d: number) => (n / Math.pow(10, d)).toFixed(0), - }, - getCachedWalletData: async () => ({ - solBalance: 0, - tokenBalances: [{ mint: "EPjF...USDC", ticker: "USDC", balance: 1000000, decimals: 6 }], - }), - fetchPricesUSD: async (references: string[]) => { - const record: Record = {}; - for (const reference of references) { - record[reference] = 1; - } - return record; - }, - buildWalletCaption: (_: string, lines: any) => { - capturedLines = lines; - return "CAPTION"; - }, - createWalletKeyboard: () => ({ rows: [] }) as any, - WINNER_VIDEO_ID: "VID", - }; - await showWalletUI(ctx, deps); - const calls = ctx.__calls; - expect(calls).toHaveLength(1); - expect(calls[0][0]).toBe("edit"); - expect(capturedLines).toEqual([ - { ticker: "SOL", amount: "0.000000", copyAmount: "0", usdValue: "0", unit: "SOL" }, - { ticker: "USDC", mint: "EPjF...USDC", amount: "1", copyAmount: "1", usdValue: "1" }, - ]); - }); + fetchPricesUSD: async (references: string[]) => { + const record: Record = {}; + for (const reference of references) { + record[reference] = 1; + } + return record; + }, + buildWalletCaption: (_: string, lines: any) => { + capturedLines = lines; + return "CAPTION"; + }, + createWalletKeyboard: () => ({ rows: [] }) as any, + WINNER_VIDEO_ID: "VID", + }; + await showWalletUI(ctx, deps); + const calls = ctx.__calls; + expect(calls).toHaveLength(1); + expect(calls[0][0]).toBe(expectedOperation); + if (expectedOperation === "edit") { + expect(calls[0][1]).toEqual({ + type: "video", + media: "VID", + caption: "CAPTION", + parse_mode: "HTML", + }); + } else { + expect(calls[0][1]).toBe("VID"); + expect(calls[0][2]).toMatchObject({ caption: "CAPTION", parse_mode: "HTML" }); + } + expect(capturedLines).toEqual([ + { ticker: "SOL", amount: "0.000000", copyAmount: "0", usdValue: "0", unit: "SOL" }, + { ticker: "USDC", mint: "EPjF...USDC", amount: "1", copyAmount: "1", usdValue: "1" }, + ]); + }, + ); test("sends new wallet video when invoked via command context", async () => { const ctx: any = makeCtx(); From 0cd80fb42f2c1f22c1c80684b64e7f274e52e252 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 21:10:39 -0300 Subject: [PATCH 212/410] test(wallet): bound game recovery after repeated confirmation errors --- tests/game-manager.confirm-reload.test.ts | 33 ++++++++++++++--------- tests/game-manager.unjoin-errors.test.ts | 30 ++++++++++++++------- 2 files changed, 40 insertions(+), 23 deletions(-) diff --git a/tests/game-manager.confirm-reload.test.ts b/tests/game-manager.confirm-reload.test.ts index d76b8824..94d2cf44 100644 --- a/tests/game-manager.confirm-reload.test.ts +++ b/tests/game-manager.confirm-reload.test.ts @@ -2,14 +2,12 @@ import { describe, test, expect } from "bun:test"; import { GameManager } from "../src/utils/game"; import { PublicKey, Keypair } from "#solana"; import { formatUserFriendlyError } from "../src/utils/errors"; -import { TRANSACTION_RESUBMIT_ATTEMPTS } from "../src/utils/constants"; const DEFAULT_GAME_PDA = new PublicKey("BPFLoader1111111111111111111111111111111111"); const DEFAULT_PLAYER_PUBKEY = new PublicKey("BPFLoader2111111111111111111111111111111111"); function resetGM() { - // @ts-ignore - GameManager["instance"] = undefined; + GameManager.resetForTest(); } const createDefaultProgram = () => @@ -69,9 +67,13 @@ describe("GameManager confirm/reload helpers", () => { }); test("confirmTransactionWithRecovery resubmits using the latest failed signature", async () => { + const confirmationAttempts: string[] = []; const wallet = { - confirmTransaction: async () => { - throw new Error("transaction confirmation timeout"); + confirmTransaction: async (signature: string) => { + confirmationAttempts.push(signature); + if (confirmationAttempts.length <= 2) { + throw new Error("transaction confirmation timeout"); + } }, } as any; const { gm } = setupGameManager({ wallet }); @@ -94,6 +96,7 @@ describe("GameManager confirm/reload helpers", () => { ); expect(finalSignature).toBe("SIG_SUCCESS"); + expect(confirmationAttempts).toEqual(["SIG_ORIGINAL", "SIG_SUCCESS"]); expect(resubmitAttempts).toEqual([ { attempt: 0, previousSignature: "SIG_ORIGINAL" }, { attempt: 1, previousSignature: "SIG_FROM_ERROR" }, @@ -111,22 +114,25 @@ describe("GameManager confirm/reload helpers", () => { }, } as any; const { gm } = setupGameManager({ wallet }); - const resubmittedFrom: string[] = []; + const resubmittedFrom: Array<[number, string]> = []; const finalSignature = await (gm as any).confirmTransactionWithRecovery( "SIG_ORIGINAL", DEFAULT_GAME_PDA, "Game creation", undefined, - async (_attempt: number, previousSignature: string) => { - resubmittedFrom.push(previousSignature); + async (attempt: number, previousSignature: string) => { + resubmittedFrom.push([attempt, previousSignature]); return resubmittedFrom.length === 1 ? "SIG_RETRY_1" : "SIG_RETRY_2"; }, ); expect(finalSignature).toBe("SIG_RETRY_2"); expect(confirmationAttempts).toEqual(["SIG_ORIGINAL", "SIG_RETRY_1", "SIG_RETRY_2"]); - expect(resubmittedFrom).toEqual(["SIG_ORIGINAL", "SIG_RETRY_1"]); + expect(resubmittedFrom).toEqual([ + [0, "SIG_ORIGINAL"], + [1, "SIG_RETRY_1"], + ]); }); test("confirmTransactionWithRecovery treats expirations as recoverable", async () => { @@ -322,8 +328,8 @@ describe("GameManager confirm/reload helpers", () => { test("confirmTransactionWithRecovery preserves last resubmit error after max attempts", async () => { const wallet = { - confirmTransaction: async () => { - throw new Error("transaction confirmation timeout"); + confirmTransaction: async (signature: string) => { + if (signature !== "EXTRA_SIGNATURE") throw new Error("transaction confirmation timeout"); }, getConnection: () => ({ getSignatureStatuses: async () => ({ value: [null] }), @@ -346,6 +352,7 @@ describe("GameManager confirm/reload helpers", () => { DEFAULT_PLAYER_PUBKEY, async () => { attempts += 1; + if (attempts > 2) return "EXTRA_SIGNATURE"; const err = new Error(`resubmit attempt ${attempts}`); throw err; }, @@ -355,10 +362,10 @@ describe("GameManager confirm/reload helpers", () => { } catch (error: any) { expect(error.message).toMatch(/transaction confirmation timeout/); expect(error.cause).toBeInstanceOf(Error); - expect((error.cause as Error).message).toMatch(/resubmit attempt/); + expect((error.cause as Error).message).toBe("resubmit attempt 2"); } - expect(attempts).toBe(TRANSACTION_RESUBMIT_ATTEMPTS); + expect(attempts).toBe(2); }); test("confirmTransactionWithRecovery preserves timeout message when recovery fails", async () => { diff --git a/tests/game-manager.unjoin-errors.test.ts b/tests/game-manager.unjoin-errors.test.ts index 1ec8cc95..be07b8ca 100644 --- a/tests/game-manager.unjoin-errors.test.ts +++ b/tests/game-manager.unjoin-errors.test.ts @@ -3,8 +3,7 @@ import { PublicKey, Keypair } from "#solana"; import { GameManager } from "../src/utils/game"; function resetGM() { - // @ts-ignore - GameManager["instance"] = undefined; + GameManager.resetForTest(); } function baseProgram(gameAccount: any) { @@ -165,6 +164,7 @@ describe("GameManager unjoin errors", () => { const player = await Keypair.generate(); const gamePda = new PublicKey("BPFLoader8111111111111111111111111111111111"); const removed: any[][] = []; + const confirmations: string[] = []; const db = baseDb({ getGameParticipants: (_: string) => ["123"], getPlayerPublicKey: (_: string) => player.publicKey.toBase58(), @@ -188,8 +188,11 @@ describe("GameManager unjoin errors", () => { } as any; const wallet = { getKeyPair: () => player, - confirmTransaction: async () => { - throw new Error("transaction confirmation timeout"); + confirmTransaction: async (signature: string) => { + confirmations.push(signature); + if (confirmations.length <= 3) { + throw new Error("transaction confirmation timeout"); + } }, getConnection: () => ({ getSignatureStatuses: async () => ({ value: [null] }) }), } as any; @@ -197,30 +200,32 @@ describe("GameManager unjoin errors", () => { (gm as any).recoverParticipantsFromChain = () => {}; (gm as any).buildUnjoinAccounts = async () => ({}); (gm as any).sendInstructionsWithFallback = async () => "SIG"; - return { gm: gm as any, gamePda, player, removed }; + return { gm: gm as any, gamePda, player, removed, confirmations }; }; test("an RPC error while checking the game keeps the local record and throws", async () => { - const { gm, gamePda, player, removed } = await setup(async () => { + const { gm, gamePda, player, removed, confirmations } = await setup(async () => { throw new Error("rpc down"); }); await expect( gm.unjoinPlayerFromGame(gamePda, player, player.publicKey, "123"), ).rejects.toThrow(/rpc down/); + expect(confirmations).toEqual(["SIG", "SIG", "SIG"]); expect(removed).toEqual([]); }); test("a game that is really gone counts as the player removed", async () => { - const { gm, gamePda, player, removed } = await setup(async () => null); + const { gm, gamePda, player, removed, confirmations } = await setup(async () => null); await gm.unjoinPlayerFromGame(gamePda, player, player.publicKey, "123"); + expect(confirmations).toEqual(["SIG", "SIG", "SIG"]); expect(removed).toEqual([[gamePda.toBase58(), "123"]]); }); test("without fetchNullable, a missing-account error from fetch counts as removed", async () => { - const { gm, gamePda, player, removed } = await setup(async () => null); + const { gm, gamePda, player, removed, confirmations } = await setup(async () => null); let reads = 0; gm.program.account.game.fetchNullable = undefined; gm.program.account.game.fetch = async () => { @@ -231,25 +236,30 @@ describe("GameManager unjoin errors", () => { await gm.unjoinPlayerFromGame(gamePda, player, player.publicKey, "123"); + expect(confirmations).toEqual(["SIG", "SIG", "SIG"]); expect(removed).toEqual([[gamePda.toBase58(), "123"]]); }); test("a player no longer in the on-chain list counts as removed", async () => { - const { gm, gamePda, player, removed } = await setup(async () => ({ participants: [] })); + const { gm, gamePda, player, removed, confirmations } = await setup(async () => ({ + participants: [], + })); await gm.unjoinPlayerFromGame(gamePda, player, player.publicKey, "123"); + expect(confirmations).toEqual(["SIG", "SIG", "SIG"]); expect(removed).toEqual([[gamePda.toBase58(), "123"]]); }); test("a player still in the on-chain list is not removed", async () => { - const { gm, gamePda, player, removed } = await setup(async () => ({ + const { gm, gamePda, player, removed, confirmations } = await setup(async () => ({ participants: [player.publicKey], })); await expect( gm.unjoinPlayerFromGame(gamePda, player, player.publicKey, "123"), ).rejects.toThrow(/still pending|timeout/i); + expect(confirmations).toEqual(["SIG", "SIG", "SIG"]); expect(removed).toEqual([]); }); }); From 8a3c247a79eeb42d6590d627c132b9a8aa3f74b4 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 21:12:20 -0300 Subject: [PATCH 213/410] test(wallet): refresh each media shape in the original message --- tests/wallet-ui.swr.test.ts | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/tests/wallet-ui.swr.test.ts b/tests/wallet-ui.swr.test.ts index 21124982..180482b0 100644 --- a/tests/wallet-ui.swr.test.ts +++ b/tests/wallet-ui.swr.test.ts @@ -37,6 +37,7 @@ type Setup = { fresh?: () => Promise>; callbackData?: string; callbackMessage?: Record | null; + contextCanEditCaption?: boolean; editText?: (...args: any[]) => Promise; editCaption?: (...args: any[]) => Promise; isCurrent?: () => boolean; @@ -66,6 +67,14 @@ const run = async (setup: Setup) => { calls.push(["ctxEditText", ...args]); return true; }, + ...(setup.contextCanEditCaption + ? { + editMessageCaption: async (...args: unknown[]) => { + calls.push(["ctxEditCaption", ...args]); + return true; + }, + } + : {}), reply: async (...args: any[]) => { calls.push(["reply", ...args]); return { message_id: 500, chat: { id: 99 } }; @@ -293,6 +302,29 @@ describe("showWalletUI stale-while-revalidate", () => { expect(apiCalls).toEqual(["apiEditCaption", "apiEditText"]); }); + test.each([ + ["photo", { photo: [{ file_id: "photo" }] }, "apiEditCaption"], + ["video", { video: { file_id: "video" } }, "apiEditCaption"], + ["animation", { animation: { file_id: "animation" } }, "apiEditCaption"], + ["document", { document: { file_id: "document" } }, "apiEditCaption"], + ["empty caption", { caption: "" }, "apiEditCaption"], + ["plain text", { text: "old" }, "apiEditText"], + ] as const)( + "refreshes a %s in the original message and mode", + async (_label, callbackMessage, mode) => { + const { calls } = await run({ + cached: { data: page(1e9), fetchedAt: NOW - 12_000 }, + callbackMessage, + contextCanEditCaption: true, + }); + const edits = calls + .filter(([kind]) => kind.startsWith("apiEdit")) + .map(([kind, chatId, messageId]) => [kind, chatId, messageId]); + expect(edits).toEqual([[mode, 99, 11]]); + expect(calls.some(([kind]) => kind === "reply")).toBe(false); + }, + ); + test.each([ ["not modified", tgError("Bad Request: message is not modified")], ["rate limited", tgError("Too Many Requests: retry after 5", 429)], From 12d162d155f975941526c827112a12da64989b4d Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 21:14:20 -0300 Subject: [PATCH 214/410] test(wallet): ignore malformed refresh receipts without extra sends --- tests/wallet-handler.edge.test.ts | 54 +++++++++++++++++++++---------- 1 file changed, 37 insertions(+), 17 deletions(-) diff --git a/tests/wallet-handler.edge.test.ts b/tests/wallet-handler.edge.test.ts index 815d2de7..ff03a6ce 100644 --- a/tests/wallet-handler.edge.test.ts +++ b/tests/wallet-handler.edge.test.ts @@ -292,27 +292,47 @@ describe("background refresh targets", () => { expect(edit[3].caption).toContain("SOL=3"); }); - test("falls back to the pressed message when the send result has no message ids", async () => { - const { ctx, calls } = makeCtx({ - callbackQuery: { id: "cb", message: { message_id: 33, chat: { id: 1 }, caption: "old" } }, - }); - ctx.replyWithVideo = async () => ({ ok: true }); - - await showWalletUI(ctx, cachedDeps(3e9)); - await ctx.__walletBackgroundRefresh; - - const edit = calls.find(([kind]) => kind === "apiEditCaption")!; - expect(edit.slice(1, 3)).toEqual([1, 33]); - }); - - test("does not refresh when there is no message to edit", async () => { + test.each([ + ["no IDs", { ok: true }], + ["an invalid message ID", { message_id: "700", chat: { id: 1 } }], + ["a missing chat", { message_id: 700 }], + ] as const)( + "falls back to the pressed message when the receipt has %s", + async (_label, receipt) => { + const { ctx, calls } = makeCtx({ + callbackQuery: { id: "cb", message: { message_id: 33, chat: { id: 1 }, caption: "old" } }, + }); + ctx.replyWithVideo = async () => receipt; + + await showWalletUI(ctx, cachedDeps(3e9)); + await ctx.__walletBackgroundRefresh; + + const edit = calls.find(([kind]) => kind === "apiEditCaption")!; + expect(edit.slice(1, 3)).toEqual([1, 33]); + }, + ); + + test.each([ + ["no IDs", { ok: true }], + ["a missing chat", { message_id: 700 }], + ["a string message ID", { message_id: "700", chat: { id: 1 } }], + ["a string chat ID", { message_id: 700, chat: { id: "1" } }], + ] as const)("does not edit or add a message when the receipt has %s", async (_label, receipt) => { const { ctx, calls } = makeCtx(); - ctx.replyWithVideo = async () => ({ ok: true }); + const sendVideo = mock(async () => receipt); + ctx.replyWithVideo = sendVideo; + const captureMessageView = mock((_chatId: number, _messageId: number) => () => true); + const fixture = cachedDeps(3e9); + const fetchWallet = mock(fixture.getWalletPageData); - await showWalletUI(ctx, cachedDeps(3e9)); + await showWalletUI(ctx, { ...fixture, captureMessageView, getWalletPageData: fetchWallet }); await ctx.__walletBackgroundRefresh; - expect(calls.some(([kind]) => kind.startsWith("apiEdit"))).toBe(false); + expect(fetchWallet).toHaveBeenCalledTimes(1); + expect(sendVideo).toHaveBeenCalledTimes(1); + expect(captureMessageView).not.toHaveBeenCalled(); + expect(errorSpy).not.toHaveBeenCalled(); + expect(calls).toEqual([]); }); }); From 7652468e35fa193dd71535853292768b6b833844 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 21:15:47 -0300 Subject: [PATCH 215/410] refactor(tokens): use decoded metadata text directly --- src/utils/token-metadata.ts | 6 ++---- tests/token-metadata.test.ts | 34 ++++++++++++++++++++++++++++++++++ 2 files changed, 36 insertions(+), 4 deletions(-) diff --git a/src/utils/token-metadata.ts b/src/utils/token-metadata.ts index 86c25667..5493f774 100644 --- a/src/utils/token-metadata.ts +++ b/src/utils/token-metadata.ts @@ -51,10 +51,8 @@ async function tryMetaplexMetadata( return null; } const metadata = deserializeMetadata(metadataAccount as any); - const rawSymbol = (metadata as any).symbol ?? ""; - const rawName = (metadata as any).name ?? ""; - const symbol = String(rawSymbol).replace(/\0/g, "").trim(); - const name = String(rawName).replace(/\0/g, "").trim(); + const symbol = metadata.symbol.replace(/\0/g, "").trim(); + const name = metadata.name.replace(/\0/g, "").trim(); if (symbol && symbol !== "UNKNOWN") { return { diff --git a/tests/token-metadata.test.ts b/tests/token-metadata.test.ts index ac33491b..eef11a85 100644 --- a/tests/token-metadata.test.ts +++ b/tests/token-metadata.test.ts @@ -95,6 +95,40 @@ describe("resolveTokenMetadata", () => { expect(result).toEqual({ symbol: "USDC", name: "USDC", decimals: 6 }); }); + test.each([ + ["an empty symbol", ""], + ["only padding", " \0\0 "], + ] as const)("falls back without a decode error for %s", async (_label, symbol) => { + const fetch = jupiterFetch([{ id: MINT, symbol: "USDC", name: "USD Coin", decimals: 6 }]); + const connection = connectionWith(metaplexAccount(symbol, "Ignored on-chain name")); + + expect( + await resolveTokenMetadata({ + connection: connection as unknown as Connection, + mintAddress: MINT, + fetch, + }), + ).toEqual({ symbol: "USDC", name: "USD Coin", decimals: 6 }); + expect(fetch).toHaveBeenCalledTimes(1); + expect(logSpy).not.toHaveBeenCalled(); + }); + + test("falls back after an invalid encoded metadata record and keeps the decode diagnostic", async () => { + const connection = connectionWith({ data: new Uint8Array([0]) }); + const fetch = jupiterFetch([{ id: MINT, symbol: "USDC", name: "USD Coin", decimals: 6 }]); + const result = await resolveTokenMetadata({ + connection: connection as unknown as Connection, + mintAddress: MINT, + fetch, + }); + + expect(result).toEqual({ symbol: "USDC", name: "USD Coin", decimals: 6 }); + expect(logSpy.mock.calls).toEqual([ + ["Metaplex metadata not available for", MINT, expect.any(Error)], + ]); + expect(logSpy.mock.calls[0]?.[2]).toMatchObject({ name: "UnexpectedAccountError" }); + }); + test("does not use another mint's ticker or decimals after its metadata account is unavailable", async () => { const result = await resolveTokenMetadata({ connection: connectionWith(null) as unknown as Connection, From 6e041c458a0a2d29e76abf8b2fc12b7935e2fd20 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 21:18:25 -0300 Subject: [PATCH 216/410] test(wallet): pin exact wrap controls and custom amount examples --- tests/wallet-transactions.flows.test.ts | 30 ++++++++++++++++++++++--- 1 file changed, 27 insertions(+), 3 deletions(-) diff --git a/tests/wallet-transactions.flows.test.ts b/tests/wallet-transactions.flows.test.ts index 57e5d885..354cd20e 100644 --- a/tests/wallet-transactions.flows.test.ts +++ b/tests/wallet-transactions.flows.test.ts @@ -282,9 +282,32 @@ describe("wrap and unwrap flows", () => { await press("cmd_wrap", { userId: USER }); expect(lastText()).toContain("Native SOL: 5"); expect(lastText()).toContain("WSOL: 2"); - const data = buttons(lastMessage()).map((button) => button.data); - expect(data).toContain("wrap_amount_50%"); - expect(data).toContain("wrap_custom"); + expect(buttons(lastMessage())).toEqual([ + { text: "25%", data: "wrap_amount_25%" }, + { text: "50%", data: "wrap_amount_50%" }, + { text: "75%", data: "wrap_amount_75%" }, + { text: "MAX", data: "wrap_amount_MAX" }, + { text: "✏️ Custom Amount", data: "wrap_custom" }, + { text: "← Back to Settings", data: "wallet_settings" }, + ]); + }); + + test.each([ + ["25%", "25%"], + ["75%", "75%"], + ["MAX", "MAX"], + ["1.25", null], + ] as const)("shows the correct selection label for wrap amount %s", async (choice, label) => { + await press(`wrap_amount_${choice}`, { userId: USER }); + + expect(lastText()).toContain("Wrap Confirmation"); + if (label) { + expect(lastText()).toContain(`Selection: ${label} of available SOL`); + } else { + expect(lastText()).not.toContain("Selection:"); + expect(confirmButton("confirm_wrap_")).toBe("confirm_wrap_1250000000"); + } + expect(transfers).toEqual([]); }); test("quick wrap amounts ask for confirmation and then wrap", async () => { @@ -345,6 +368,7 @@ describe("wrap and unwrap flows", () => { test("custom wrap amounts are entered as a reply", async () => { await press("wrap_custom", { userId: USER }); expect(lastText()).toContain("Custom Wrap Amount"); + expect(lastText()).toContain("• 0.5\n• 1.25"); await replyToPrompt("0.25"); expect(lastText()).toContain("Wrap Confirmation"); expect(lastText()).toContain("0.25"); From 86e3b155ba8a822d8bc787f730a862ad799903da Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 21:24:05 -0300 Subject: [PATCH 217/410] test(finance): keep the highest fee and count unique swaps --- tests/finance-report.test.ts | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/tests/finance-report.test.ts b/tests/finance-report.test.ts index 0d810d3c..14b0a36a 100644 --- a/tests/finance-report.test.ts +++ b/tests/finance-report.test.ts @@ -164,10 +164,39 @@ describe("finance report", () => { contractRentLamports: 2_000_000_000n, contractRentUsd: 200, contractRentEstimated: true, + hasEstimatedSponsorExpenses: false, monthlyExpenses: expenses, }); }); + test("counts each earned swap signature and keeps the earlier larger fee", async () => { + const report = await buildFinanceReport( + "30d", + reportInputs({ + financeEvents: [ + event({ eventId: "largest", signature: "game-1", networkFeeLamports: "300000000" }), + event({ eventId: "smaller", signature: "game-1", networkFeeLamports: "100000000" }), + event({ eventId: "game-2", signature: "game-2", networkFeeLamports: "200000000" }), + event({ eventId: "swap-first", signature: "swap-1", category: "swap_fee" }), + event({ eventId: "swap-repeat", signature: "swap-1", category: "swap_fee" }), + event({ eventId: "swap-second", signature: "swap-2", category: "swap_fee" }), + event({ + eventId: "swap-claim", + signature: "swap-claim", + category: "swap_fee", + kind: "claimed", + networkFeeLamports: "400000000", + }), + ], + }), + ); + + expect(report.feeGeneratingSwaps).toBe(2); + expect(report.completionNetworkExpensesUsd).toBe(50); + expect(report.collectionNetworkExpensesUsd).toBe(40); + expect(report.networkExpensesUsd).toBe(90); + }); + test("combines claimable raw units and omits zero or negative totals before resolving metadata", async () => { const unknown = "unpriced-mint"; const neverLookUp = "unused-mint"; @@ -377,6 +406,7 @@ describe("finance report", () => { expect(report.sponsorNetworkExpensesUsd).toBeCloseTo(0.0005); expect(report.totalExpensesUsd).toBeCloseTo(0.0005); + expect(report.hasEstimatedSponsorExpenses).toBe(false); }); test.each([ From 588ee0f5be5a11ff1adc85ea6ff64bb5653f6e23 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 21:26:51 -0300 Subject: [PATCH 218/410] test(format): keep the leading zero when rounding below one unit --- tests/format-amount.test.ts | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/tests/format-amount.test.ts b/tests/format-amount.test.ts index fe3e2158..b8e93d29 100644 --- a/tests/format-amount.test.ts +++ b/tests/format-amount.test.ts @@ -85,6 +85,27 @@ test("formatAmount rounds fractional carry when integer part is empty", () => { expect(formatAmount(5, 3, { maxFractionDigits: 2 })).toBe("0.01"); }); +test.each([ + [15n, 2, 1, "0.2"], + [-15n, 2, 1, "-0.2"], + [105n, 3, 2, "0.11"], + [-105n, 3, 2, "-0.11"], +] as const)( + "formatAmount keeps a leading zero when rounding %p below one unit", + (raw, decimals, maxFractionDigits, expected) => { + expect(formatAmount(raw, decimals, { maxFractionDigits })).toBe(expected); + }, +); + +test.each([ + ["unknown scale", 5n, NaN, "0"], + ["negative amount and unknown scale", -5n, NaN, "-0"], + ["fractional positive scale", 5n, 0.5, "0"], + ["fractional negative scale", -5n, -0.5, "-1"], +] as const)("formatAmount preserves the fallback amount for %s", (_label, raw, scale, expected) => { + expect(formatAmount(raw, scale)).toBe(expected); +}); + test("formatAmount shows tiny non-zero values with full precision by default", () => { expect(formatAmount(1, 9)).toBe("0.000000001"); expect(formatAmount(5, 9)).toBe("0.000000005"); From 39df08ab4a9968375ee97e031cc79f736e24ea70 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 21:31:35 -0300 Subject: [PATCH 219/410] test(finance): pin signed report text and period buttons --- tests/finance-report.test.ts | 85 +++++++++++++++++++++++++++++++++++- 1 file changed, 84 insertions(+), 1 deletion(-) diff --git a/tests/finance-report.test.ts b/tests/finance-report.test.ts index 14b0a36a..24f9ec5a 100644 --- a/tests/finance-report.test.ts +++ b/tests/finance-report.test.ts @@ -197,6 +197,70 @@ describe("finance report", () => { expect(report.networkExpensesUsd).toBe(90); }); + test("renders exact priced and unpriced lines, prorated expense, and negative result", async () => { + const unknownMint = "unpriced-mint"; + const report = await buildFinanceReport( + "7d", + reportInputs({ + financeEvents: [ + event({ eventId: "priced", amountRaw: "2000000" }), + event({ eventId: "unpriced", category: "swap_fee", mint: unknownMint }), + ], + monthlyExpenses: [{ category: "hosting", description: "VPS & DB", amountUsd: 30 }], + contractRentLamports: 1_250_000_000n, + coverage: "partial", + backfill: { + totalSources: 0, + completedSources: 0, + processedTransactions: 0, + lastError: null, + }, + resolveTokenMetadata: async (mint) => + mint === unknownMint ? { ticker: "UNKNOWN<&>", decimals: 6 } : metadata(mint), + resolveTokenPriceUsd: async (mint) => + mint === unknownMint || mint === SOL ? null : price(mint), + }), + ); + expect(formatFinanceReport(report)).toBe( + [ + "📊 Timba Finance: Last 7 days", + "", + "Revenue", + "Game fees earned: $0.02", + "Swap fees earned: $0.00", + "Total: $0.02", + "", + "Expenses", + "Game completion transactions: $0.00", + "Sponsored swap transactions: $0.00", + "Fee collection transactions: $0.00", + "VPS & DB: $7.00", + "Total: $7.00", + "", + "Result: −$6.98", + "", + "Activity", + "1 completed games", + "1 fee-generating swaps", + "", + "Fee status", + "", + "Capital (not profit)", + "Contract deposits: 1.25 SOL", + "", + "Game revenue by token", + "2 TIMBA ≈ $0.02", + "", + "Swap revenue by token", + "1 UNKNOWN<&> (unpriced)", + "", + "Data coverage: partial; historical backfill has not started.", + "Unpriced tokens are excluded from USD totals.", + "Token values use current market prices.", + ].join("\n"), + ); + }); + test("combines claimable raw units and omits zero or negative totals before resolving metadata", async () => { const unknown = "unpriced-mint"; const neverLookUp = "unused-mint"; @@ -494,18 +558,37 @@ describe("finance authorization", () => { trackBackgroundTask: (task: Promise) => backgroundTasks.push(task), }); let message = ""; + let deliveredOptions: unknown; await handlers.handleCommand({ chat: { type: "private" }, from: { id: 123 }, reply: async () => ({ chat: { id: 123 }, message_id: 456 }), api: { - editMessageText: async (_chatId: number, _messageId: number, text: string) => { + editMessageText: async ( + _chatId: number, + _messageId: number, + text: string, + options: unknown, + ) => { message = text; + deliveredOptions = options; }, }, } as any); await Promise.all(backgroundTasks); expect(message).toContain("Timba Finance"); + expect(deliveredOptions).toMatchObject({ + parse_mode: "HTML", + reply_markup: { + inline_keyboard: [ + [ + { text: "7 days", callback_data: "finance:7d" }, + { text: "30 days", callback_data: "finance:30d" }, + { text: "90 days", callback_data: "finance:90d" }, + ], + ], + }, + }); }); test("returns after acknowledging while report assembly continues in the background", async () => { From 4fcfba2236b04e1056a5fee5e2f28a495ac22b4f Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 21:34:33 -0300 Subject: [PATCH 220/410] test(finance): check sponsor estimates and report access guards --- tests/finance-report.test.ts | 64 ++++++++++++++++++++++++++++++------ 1 file changed, 54 insertions(+), 10 deletions(-) diff --git a/tests/finance-report.test.ts b/tests/finance-report.test.ts index 24f9ec5a..488adb19 100644 --- a/tests/finance-report.test.ts +++ b/tests/finance-report.test.ts @@ -12,6 +12,7 @@ import { formatFinanceReport, } from "../src/handlers/finance"; import type { FinanceEventRecord } from "../src/utils/transaction-history"; +import { makeTestTelegramContext } from "./helpers/grammy"; const TIMBA = "timba-mint"; const USDC = "usdc-mint"; @@ -403,18 +404,29 @@ describe("finance report", () => { expect(report.recurringExpensesUsd).toBe(6); expect(formatFinanceReport(report)).toContain("complete on-chain history"); expect(formatFinanceReport(report)).toContain("Game revenue by token"); + const partial = { + ...report, + coverage: "partial" as const, + backfill: { + totalSources: 4, + completedSources: 1, + processedTransactions: 30, + lastError: null, + }, + }; + expect(formatFinanceReport(partial).split("\n").at(-2)).toBe( + "Data coverage: partial; backfill 1/4 sources, 30 transactions indexed.", + ); expect( formatFinanceReport({ - ...report, - coverage: "partial", - backfill: { - totalSources: 4, - completedSources: 1, - processedTransactions: 30, - lastError: "429 Too Many Requests", - }, - }), - ).toContain("backfill 1/4 sources, 30 transactions indexed; retrying after an RPC error"); + ...partial, + backfill: { ...partial.backfill, lastError: "429 Too Many Requests" }, + }) + .split("\n") + .at(-2), + ).toBe( + "Data coverage: partial; backfill 1/4 sources, 30 transactions indexed; retrying after an RPC error.", + ); }); test("ignores malformed stored raw amounts instead of failing the report", async () => { @@ -514,6 +526,11 @@ describe("finance report", () => { expect(report.completionNetworkExpensesUsd).toBe(20); expect(report.sponsorNetworkExpensesUsd).toBe(expected); expect(report.networkExpensesUsd).toBe(expected + 20); + expect( + formatFinanceReport(report) + .split("\n") + .find((line) => line.startsWith("Sponsored swap transactions:")), + ).toBe(`Sponsored swap transactions: $${expected}.00 estimated`); }, ); }); @@ -551,6 +568,33 @@ describe("finance authorization", () => { expect(replies).toBe(0); }); + test("requires both a private chat and a sender on the update", async () => { + const handlers = createFinanceHandlers(makeDependencies()); + const admin = { id: 123, is_bot: false, first_name: "Admin" }; + const noChat = makeTestTelegramContext({ + update_id: 1, + inline_query: { id: "inline", from: admin, query: "finance", offset: "" }, + }); + const noSender = makeTestTelegramContext({ + update_id: 2, + message: { + message_id: 15, + date: NOW / 1_000, + chat: { id: 123, type: "private", first_name: "Admin" }, + from: admin, + text: "/finance", + }, + }); + // Non-channel messages must have a sender, but the guard also handles an incomplete context. + Object.defineProperty(noSender, "from", { value: undefined }); + for (const ctx of [noChat, noSender]) { + expect(handlers.isAuthorized(ctx)).toBe(false); + const reply = spyOn(ctx, "reply"); + await handlers.handleCommand(ctx); + expect(reply).not.toHaveBeenCalled(); + } + }); + test("returns the report to an allowlisted private-chat admin", async () => { const backgroundTasks: Promise[] = []; const handlers = createFinanceHandlers({ From 47c4e1d2d28ae36efbd14bc29916fd28dda1bdf4 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 21:34:56 -0300 Subject: [PATCH 221/410] test(finance): cover missing balance sides and exact claimable units --- tests/finance-ledger.events.test.ts | 56 +++++++++++++++++++++++++++-- 1 file changed, 53 insertions(+), 3 deletions(-) diff --git a/tests/finance-ledger.events.test.ts b/tests/finance-ledger.events.test.ts index ec444b66..522fdbb6 100644 --- a/tests/finance-ledger.events.test.ts +++ b/tests/finance-ledger.events.test.ts @@ -1,4 +1,5 @@ import { afterEach, beforeEach, describe, expect, spyOn, test } from "bun:test"; +import BN from "bn.js"; import { PublicKey } from "#solana"; import { FinanceLedgerService } from "../src/services/finance-ledger"; import { EVENT_DISCRIMINATORS } from "@timbagame/protocol/contracts/events"; @@ -247,6 +248,51 @@ describe("program finance events", () => { }); }); + test.each([ + ["preTokenBalances", "postTokenBalances"], + ["postTokenBalances", "preTokenBalances"], + ] as const)( + "infers a mint from %s alone and uses wall time when both block times are missing", + async (balanceSide, absentSide) => { + const history = createHistory(programSource); + const { meta, ...transaction } = programTransaction([gameCompleted(5n, 0n)], { + blockTime: null, + }); + const clock = spyOn(Date, "now").mockReturnValue(1_800_000_000_321); + try { + const ledgerTransaction = { + ...transaction, + meta: { + ...meta, + [absentSide]: undefined, + [balanceSide]: [ + { accountIndex: 1, mint: "", uiTokenAmount: { amount: "0" } }, + { accountIndex: 2, mint: MINT.toBase58(), uiTokenAmount: { amount: "5" } }, + ], + }, + }; + await serviceFor(history, singleTransaction(ledgerTransaction, null)).backfillNextBatch(0); + expect(history.events).toEqual([ + { + eventId: `program:sig-1:game:${GAME.toBase58()}`, + source: "program", + category: "game_fee", + kind: "earned", + signature: "sig-1", + account: GAME.toBase58(), + mint: MINT.toBase58(), + amountRaw: "5", + networkFeeLamports: null, + timestamp: 1_800_000_000_000, + slot: 7, + }, + ]); + } finally { + clock.mockRestore(); + } + }, + ); + test("skips a completed game whose mint cannot be determined", async () => { const history = createHistory(programSource); const transaction = programTransaction([gameCompleted(5n, 1n)], { @@ -560,8 +606,10 @@ describe("finance snapshot", () => { const snapshot = await serviceFor(history, connection, { referralReader, gameTokens: [ - { account: { tokenMint: MINT, feeAmount: { toString: () => "12" } } }, - { account: { tokenMint: PLAYER, feeAmount: 0 } }, + { account: { tokenMint: MINT, feeAmount: new BN("9007199254740993") } }, + { account: { tokenMint: PLAYER, feeAmount: new BN(0) } }, + { account: { tokenMint: PAYER, feeAmount: new BN(-1) } }, + { account: { tokenMint: GAME, feeAmount: "not-an-integer" } }, ], }).getSnapshot(); @@ -571,7 +619,9 @@ describe("finance snapshot", () => { { mint: GAME.toBase58(), amountRaw: 9n }, ]); expect(snapshot.gameClaimable).toEqual( - contractCapabilities.gameTokenAccount ? [{ mint: MINT.toBase58(), amountRaw: 12n }] : [], + contractCapabilities.gameTokenAccount + ? [{ mint: MINT.toBase58(), amountRaw: 9_007_199_254_740_993n }] + : [], ); }); From 9fee7c09a9d3fdae1de08315e15c88edef87009b Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 21:36:21 -0300 Subject: [PATCH 222/410] test(finance): pin empty backfill pages and zero-delay reads --- tests/finance-ledger.events.test.ts | 59 +++++++++++++++++++++++------ 1 file changed, 48 insertions(+), 11 deletions(-) diff --git a/tests/finance-ledger.events.test.ts b/tests/finance-ledger.events.test.ts index 522fdbb6..9f17d4a8 100644 --- a/tests/finance-ledger.events.test.ts +++ b/tests/finance-ledger.events.test.ts @@ -142,6 +142,7 @@ const serviceFor = ( referralReader?: any; resolveGameMint?: (game: string) => string | null; batchSize?: number; + sleep?: (milliseconds: number) => Promise; gameTokens?: unknown[] | (() => Promise); } = {}, ) => @@ -164,6 +165,7 @@ const serviceFor = ( { batchSize: options.batchSize ?? 5, requestDelayMs: 0, + sleep: options.sleep, now: () => 999_000, resolveGameMint: options.resolveGameMint, }, @@ -542,30 +544,65 @@ describe("backfill source handling", () => { expect(history.errors).toEqual(["Error: 429"]); }); - test("a source with no more signatures is completed", async () => { - const history = createHistory({ ...programSource, beforeSignature: "cursor" }); - - const result = await serviceFor(history, { - getSignaturesForAddress: async () => [], - }).backfillNextBatch(0); + test.each([ + [0, 0, false], + [3, 2, false], + [3, 3, true], + ] as const)( + "an empty page keeps the cursor and reports progress with %i sources and %i complete", + async (total, completed, complete) => { + const history = createHistory( + { ...programSource, beforeSignature: "cursor" }, + { + total, + completed, + }, + ); + const result = await serviceFor(history, { + getSignaturesForAddress: async () => [], + getTransaction: async () => { + throw new Error("An empty page has no transaction to load"); + }, + }).backfillNextBatch(0); - expect(result.processedTransactions).toBe(0); - expect(history.advances).toEqual([[programSource.sourceKey, "cursor", true, 0]]); - }); + expect(result).toEqual({ + complete, + processedTransactions: 0, + progress: { + totalSources: total, + completedSources: completed, + processedTransactions: 0, + lastError: null, + }, + }); + expect(history.advances).toEqual([[programSource.sourceKey, "cursor", true, 0]]); + }, + ); test("stops at signatures older than the backfill start", async () => { const history = createHistory({ ...programSource, startTimeMs: 100_000 }); + const loadedSignatures: string[] = []; + const delays: number[] = []; const connection = { getSignaturesForAddress: async () => [ { signature: "new", blockTime: 150, slot: 2 }, { signature: "old", blockTime: 50, slot: 1 }, ], - getTransaction: async () => programTransaction([]), + getTransaction: async (signature: string) => { + loadedSignatures.push(signature); + return programTransaction([]); + }, }; - const result = await serviceFor(history, connection).backfillNextBatch(0); + const result = await serviceFor(history, connection, { + sleep: async (milliseconds) => { + delays.push(milliseconds); + }, + }).backfillNextBatch(0); expect(result.processedTransactions).toBe(1); + expect(loadedSignatures).toEqual(["new"]); + expect(delays).toEqual([]); expect(history.advances).toEqual([ [programSource.sourceKey, "new", false, 1], [programSource.sourceKey, "new", true, 0], From d4360b07d67ba126976f763cc914019e3901ff92 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 21:37:49 -0300 Subject: [PATCH 223/410] test(db): verify exact and missing creation audit records --- tests/game-database.pending-creation.test.ts | 24 ++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/tests/game-database.pending-creation.test.ts b/tests/game-database.pending-creation.test.ts index 35a5b1ee..f7e131d8 100644 --- a/tests/game-database.pending-creation.test.ts +++ b/tests/game-database.pending-creation.test.ts @@ -52,6 +52,30 @@ describe("GameDatabase pending game creation lifecycle", () => { rmSync(dir, { recursive: true, force: true }); }); + test("audit lookup returns an exact game or none and includes failed creations in order", () => { + db.savePendingGameCreation({ ...pendingInput(), state: "submitted" }); + db.savePendingGameCreation({ + ...pendingInput({ + gameAddress: "FAILED_GAME", + transactionSignature: "FAILED_SIG", + now: NOW + 1, + }), + state: "failed", + }); + + expect(db.getPendingGameCreationAuditRecords("MISSING_GAME")).toEqual([]); + expect(db.getPendingGameCreationAuditRecords("FAILED_GAME")).toMatchObject([ + { game_address: "FAILED_GAME", transaction_signature: "FAILED_SIG", state: "failed" }, + ]); + expect(db.getPendingGameCreationAuditRecords().map((record) => record.game_address)).toEqual([ + "FAILED_GAME", + "PENDING_1", + ]); + expect(db.getPendingGameCreations(NOW + 1).map((record) => record.game_address)).toEqual([ + "PENDING_1", + ]); + }); + describe("savePendingGameCreation", () => { test("rejects a second game for a creation request that already has a game", () => { db.savePendingGameCreation(pendingInput({ replyToMessageId: 7 }) as never); From e4febd0254b74c301bf531e9c32a6e5bd4482b61 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 21:39:51 -0300 Subject: [PATCH 224/410] refactor(db): use the SQL default for missing leaderboard mints --- src/utils/game-database.ts | 6 ++-- tests/game-database.player-stats.test.ts | 39 ++++++++++++++++++++++++ 2 files changed, 42 insertions(+), 3 deletions(-) diff --git a/src/utils/game-database.ts b/src/utils/game-database.ts index a1f0ebf5..2dfedd2f 100644 --- a/src/utils/game-database.ts +++ b/src/utils/game-database.ts @@ -2557,7 +2557,7 @@ export class GameDatabase extends BaseDatabase { const lostAmountByToken: Record = {}; const netAmountByToken: Record = {}; for (const row of netAmountRows) { - const tokenMint = String(row.token_mint ?? "SOL").trim(); + const tokenMint = String(row.token_mint).trim(); const wonAmount = Number(row.won_amount ?? 0); const lostAmount = Number(row.lost_amount ?? 0); wonAmountByToken[tokenMint] = wonAmount; @@ -2842,7 +2842,7 @@ export class GameDatabase extends BaseDatabase { const netAmountMap = new Map>(); for (const row of netAmountRows) { const telegramId = String(row.telegram_id ?? "").trim(); - const tokenMint = String(row.token_mint ?? "SOL").trim(); + const tokenMint = String(row.token_mint).trim(); const netAmount = Number(row.net_amount ?? 0); if (!telegramId) continue; @@ -3085,7 +3085,7 @@ export class GameDatabase extends BaseDatabase { const netAmountMap = new Map>(); for (const row of netAmountRows) { const telegramId = String(row.telegram_id ?? "").trim(); - const tokenMint = String(row.token_mint ?? "SOL").trim(); + const tokenMint = String(row.token_mint).trim(); const netAmount = Number(row.net_amount ?? 0); if (!telegramId) continue; diff --git a/tests/game-database.player-stats.test.ts b/tests/game-database.player-stats.test.ts index 5fe4e4ca..4da5dc78 100644 --- a/tests/game-database.player-stats.test.ts +++ b/tests/game-database.player-stats.test.ts @@ -1,4 +1,5 @@ import { beforeEach, describe, expect, test } from "bun:test"; +import { Database } from "bun:sqlite"; import { GameDatabase } from "../src/utils/game-database"; const CHAT = -100200300; @@ -49,6 +50,44 @@ describe("GameDatabase.getPlayerGlobalStats", () => { expect(db.getPlayerGlobalStats("UNKNOWN")).toBeNull(); }); + test("groups missing and native mints together without changing stored blank and explicit mints", () => { + db.savePlayerMapping("PK_ALICE", "1001"); + db.savePlayerMapping("PK_BOB", "1002"); + const games = [ + ["legacy", undefined, 100], + ["native", "SOL", 200], + ["new-blank", "", 300], + ["token", " TOKEN ", 400], + ["stored-blank", undefined, 500], + ] as const; + for (const [game, mint, stake] of games) { + db.saveGame(game, "1001", stake, "coinflip", mint, undefined, 2, 2, CHAT); + db.saveGameParticipant(game, "1001", "PK_ALICE"); + db.saveGameParticipant(game, "1002", "PK_BOB"); + db.completeGame(game, "PK_ALICE", undefined, 2 * stake); + } + const sqlite: unknown = Reflect.get(db, "db"); + if (!(sqlite instanceof Database)) throw new Error("Expected the SQLite fixture"); + sqlite.query("UPDATE games SET token_mint = '' WHERE game_address = ?").run("stored-blank"); + + expect(db.getGame("legacy")?.token_mint).toBeNull(); + expect(db.getGame("new-blank")?.token_mint).toBeNull(); + expect(db.getGame("stored-blank")?.token_mint).toBe(""); + expect(db.getPlayerGlobalStats("1001")?.netAmountByToken).toEqual({ + SOL: 600, + "": 500, + TOKEN: 400, + }); + for (const ranks of [db.getLeaderboardStats(CHAT), db.getGlobalLeaderboardStats()]) { + expect( + ranks.map(({ telegramId, netAmountByToken }) => [telegramId, netAmountByToken]), + ).toEqual([ + ["1001", { SOL: 600, "": 500, TOKEN: 400 }], + ["1002", { SOL: -600, "": -500, TOKEN: -400 }], + ]); + } + }); + test("aggregates wins, losses, volume and per-token net amounts", () => { db.savePlayerMapping("PK_ALICE", "ALICE", "alice"); db.savePlayerMapping("PK_BOB", "BOB", "bob"); From 0d475bd1be6e61e3fc63138d85fc9cf8ac5d588c Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 21:41:41 -0300 Subject: [PATCH 225/410] test(db): enforce submission lease expiry and owner renewal --- tests/game-database.pending-creation.test.ts | 69 ++++++++++++++++++++ 1 file changed, 69 insertions(+) diff --git a/tests/game-database.pending-creation.test.ts b/tests/game-database.pending-creation.test.ts index f7e131d8..3f9a6e64 100644 --- a/tests/game-database.pending-creation.test.ts +++ b/tests/game-database.pending-creation.test.ts @@ -200,6 +200,75 @@ describe("GameDatabase pending game creation lifecycle", () => { expect(db.getPendingGameCreation("PENDING_1")?.state).toBe("prepared"); }); + test.each([null, NOW + 1])( + "reports an active competing lease with expiry %p without a write", + (expiry) => { + db.savePendingGameCreation({ ...pendingInput(), state: "submitted" }); + raw + .query( + "UPDATE pending_game_creations SET submission_lease_id = ?, submission_lease_expires_at = ? WHERE game_address = ?", + ) + .run("lease-other", expiry, "PENDING_1"); + raw.exec("PRAGMA query_only = ON"); + try { + expect( + db.claimPendingGameCreationSubmission("PENDING_1", "lease-new", NOW + 2, NOW), + ).toEqual({ + acquired: false, + reason: "in-flight", + state: "submitted", + leaseExpiresAt: expiry, + }); + } finally { + raw.exec("PRAGMA query_only = OFF"); + } + }, + ); + + test.each([-1, 0, 1] as const)( + "fences a competing worker at lease expiry offset %i", + (offset) => { + db.savePendingGameCreation({ ...pendingInput(), state: "prepared" }); + expect( + db.claimPendingGameCreationSubmission("PENDING_1", "lease-a", NOW + offset, NOW - 2), + ).toEqual({ acquired: true }); + + const result = db.claimPendingGameCreationSubmission("PENDING_1", "lease-b", NOW + 10, NOW); + if (offset <= 0) { + expect(result).toEqual({ acquired: true }); + expect(db.getPendingGameCreation("PENDING_1")).toMatchObject({ + submission_lease_id: "lease-b", + submission_lease_expires_at: NOW + 10, + }); + } else { + expect(result).toEqual({ + acquired: false, + reason: "in-flight", + state: "submitted", + leaseExpiresAt: NOW + 1, + }); + expect(db.getPendingGameCreation("PENDING_1")).toMatchObject({ + submission_lease_id: "lease-a", + submission_lease_expires_at: NOW + 1, + }); + } + }, + ); + + test("allows only the current owner to renew a lease without waiting for expiry", () => { + db.savePendingGameCreation({ ...pendingInput(), state: "prepared" }); + expect(db.claimPendingGameCreationSubmission("PENDING_1", "lease-a", NOW + 10, NOW)).toEqual({ + acquired: true, + }); + expect( + db.claimPendingGameCreationSubmission("PENDING_1", "lease-a", NOW + 20, NOW + 1), + ).toEqual({ acquired: true }); + expect(db.getPendingGameCreation("PENDING_1")).toMatchObject({ + submission_lease_id: "lease-a", + submission_lease_expires_at: NOW + 20, + }); + }); + describe("when another writer wins the race after the pre-check", () => { let runSpy: ReturnType; From 8b43f49277f73f4e3d01ebf6cc3e8af33d1359b5 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 21:43:47 -0300 Subject: [PATCH 226/410] fix(db): type the stored player display name --- src/types/index.ts | 1 + tests/game-database.test.ts | 38 ++++++++++++++++++++++++++++++++++++- 2 files changed, 38 insertions(+), 1 deletion(-) diff --git a/src/types/index.ts b/src/types/index.ts index 3f45b9f1..e5e80ed6 100644 --- a/src/types/index.ts +++ b/src/types/index.ts @@ -39,6 +39,7 @@ export interface GameData { export interface PlayerMapping { public_key: string; telegram_id: string; + display_name?: string | null; } export interface ChatTokenConfig { diff --git a/tests/game-database.test.ts b/tests/game-database.test.ts index 45a96c85..9ad524b3 100644 --- a/tests/game-database.test.ts +++ b/tests/game-database.test.ts @@ -1,5 +1,5 @@ import { expect, test, beforeEach, spyOn } from "bun:test"; -import type { Database } from "bun:sqlite"; +import { Database } from "bun:sqlite"; import fc from "fast-check"; import { GameDatabase } from "../src/utils/game-database"; import { GAME_CREATION_RATE_LIMIT_WINDOW_MS } from "../src/utils/constants"; @@ -877,6 +877,42 @@ test("username mapping lookup persists normalized usernames", () => { expect(db.findTelegramIdByUsername("@missing")).toBeNull(); }); +test.each([ + [" Alice 🎲 ", "Alice 🎲"], + [" \t ", null], + ["", null], + [undefined, null], + [null, null], +] as const)("persists only a nonblank display name for %p", (displayName, expected) => { + const db = GameDatabase.getInstance(); + db.savePlayerMapping(" wallet-key ", " 123 ", displayName); + db.saveUsernameMapping(" Example_USER ", " 123 ", displayName); + + expect(db.getPlayerPublicKey("123")).toBe("wallet-key"); + expect(db.getPlayerDisplayName("123")).toBe(expected); + expect(db.findTelegramIdByUsername("@EXAMPLE_USER")).toBe("123"); + const sqlite: unknown = Reflect.get(db, "db"); + if (!(sqlite instanceof Database)) throw new Error("Expected the SQLite fixture"); + expect( + sqlite + .query("SELECT display_name, trusted FROM username_mappings WHERE normalized_username = ?") + .get("example_user"), + ).toEqual({ display_name: expected, trusted: 1 }); + expect(db.getAllPlayerMappings().map((mapping) => mapping.display_name)).toEqual([expected]); +}); + +test("treats a legacy stored blank display name as missing", () => { + const db = GameDatabase.getInstance(); + db.savePlayerMapping("legacy-wallet", "123", "Alice"); + const sqlite: unknown = Reflect.get(db, "db"); + if (!(sqlite instanceof Database)) throw new Error("Expected the SQLite fixture"); + sqlite + .query("UPDATE player_mappings SET display_name = ? WHERE public_key = ?") + .run(" \t ", "legacy-wallet"); + expect(db.getPlayerDisplayName("123")).toBeNull(); + expect(db.getPlayerDisplayName("missing")).toBeNull(); +}); + test("renames remove old handles and stale invalidations preserve new owners", () => { const db = GameDatabase.getInstance(); db.saveUsernameMapping("old", "111"); From dc51503fa42bd998131afc2ef191d25edbdbb6a0 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 21:45:53 -0300 Subject: [PATCH 227/410] test(db): pin game delivery and expiration page boundaries --- tests/game-database.test.ts | 39 +++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) diff --git a/tests/game-database.test.ts b/tests/game-database.test.ts index 9ad524b3..bd7b06cb 100644 --- a/tests/game-database.test.ts +++ b/tests/game-database.test.ts @@ -248,6 +248,25 @@ test("reserves each game message destination exactly once", () => { expect(db.getGameMessages("delivery-game")).toEqual([{ chatId: -1001, messageId: 42 }]); }); +test.each([ + ["default age minus one millisecond", undefined, 299_999, false], + ["exact default age", undefined, 300_000, true], + ["default age plus one millisecond", undefined, 300_001, true], + ["exact custom age", 250, 250, true], + ["zero age", 0, 0, true], + ["negative age", -25, 0, true], +] as const)("reserves a game message again at %s", (_label, age, elapsed, acquired) => { + const db = GameDatabase.getInstance(); + db.saveGame("retry-delivery", "creator", 100, "coinflip"); + expect(db.reserveGameMessageDelivery("retry-delivery", -1001, 1_000, age)).toEqual({ + acquired: true, + }); + expect(db.reserveGameMessageDelivery("retry-delivery", -1001, 1_000 + elapsed, age)).toEqual( + acquired ? { acquired: true } : { acquired: false, reason: "in-flight" }, + ); + expect(db.getGameMessages("retry-delivery")).toEqual([]); +}); + test("persists and retries confirmed game setup records", () => { const db = GameDatabase.getInstance(); db.savePendingGameCreation({ @@ -773,6 +792,26 @@ test("getGamesExpiringBefore honors excludes and fills with oldest non-expiring" expect(results.map((g) => g.game_address)).toEqual(["exp-2", "no-exp-1", "no-exp-2"]); }); +test("expiration pages retain exact cutoff, zero limit, and unbounded SQLite behavior", () => { + const db = GameDatabase.getInstance(); + const save = (name: string, expiry?: number) => + db.saveGame(name, "creator", 50, "coinflip", undefined, undefined, 2, 2, 1, 1, expiry); + save("before", 999); + save("exact", 1_000); + save("after", 1_001); + save("fallback"); + save("completed", 998); + db.completeGame("completed", "winner"); + + const addresses = (limit: number) => + db.getGamesExpiringBefore(1_000, limit).map((game) => game.game_address); + expect(addresses(0)).toEqual([]); + expect(addresses(1)).toEqual(["before"]); + expect(addresses(2)).toEqual(["before", "exact"]); + expect(addresses(3)).toEqual(["before", "exact", "fallback"]); + expect(addresses(-1)).toEqual(["before", "exact"]); +}); + test("keeps positive and negative membership results until the exact 30-minute boundary", () => { const db = GameDatabase.getInstance(); let now = 100_000_000; From 78ac91b23111d70ca4774577ef715c412c61bef9 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 21:47:10 -0300 Subject: [PATCH 228/410] test(db): report cleanup counts only when rows change --- tests/game-database.test.ts | 38 +++++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) diff --git a/tests/game-database.test.ts b/tests/game-database.test.ts index bd7b06cb..8d9a9409 100644 --- a/tests/game-database.test.ts +++ b/tests/game-database.test.ts @@ -1374,6 +1374,7 @@ test("cleanupOldGames leaves games at the production thirty-day boundary", () => const now = 1_800_000_000_000; const cutoff = now - 30 * 24 * 60 * 60 * 1_000; const clock = spyOn(Date, "now").mockReturnValue(now); + const log = spyOn(console, "log").mockImplementation(() => {}); try { db.saveGame("at-cutoff", "creator", 100, "coinflip"); @@ -1389,7 +1390,44 @@ test("cleanupOldGames leaves games at the production thirty-day boundary", () => expect(db.gameExists("before-cutoff")).toBe(false); expect(db.gameExists("at-cutoff")).toBe(true); expect(db.getGameParticipants("at-cutoff")).toEqual(["42"]); + expect(log.mock.calls).toEqual([ + ["🧹 Cleaned up 1 games and 1 participants older than 30 days"], + ]); } finally { + log.mockRestore(); + clock.mockRestore(); + } +}); + +test("cleanup reports a game with no players once and stays quiet when no rows remain", () => { + const db = GameDatabase.getInstance(); + const now = 1_800_000_000_000; + const day = 86_400_000; + const clock = spyOn(Date, "now").mockReturnValue(now); + const log = spyOn(console, "log").mockImplementation(() => {}); + try { + db.saveGame( + "expired-empty-game", + "creator", + 50, + "coinflip", + undefined, + undefined, + 2, + 2, + 1, + undefined, + undefined, + now - day - 1, + ); + + expect(db.cleanupOldGames(1)).toEqual({ gamesDeleted: 1, participantsDeleted: 0 }); + expect(db.cleanupOldGames(1)).toEqual({ gamesDeleted: 0, participantsDeleted: 0 }); + expect(log.mock.calls).toEqual([ + ["🧹 Cleaned up 1 games and 0 participants older than 1 days"], + ]); + } finally { + log.mockRestore(); clock.mockRestore(); } }); From cd1d26d902a9a3085a7d438933850ff21bc580a3 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 21:50:06 -0300 Subject: [PATCH 229/410] test(finance): record only outgoing referral claims at exact times --- tests/fee-sweeper.paths.test.ts | 134 +++++++++++++++++++------------- 1 file changed, 79 insertions(+), 55 deletions(-) diff --git a/tests/fee-sweeper.paths.test.ts b/tests/fee-sweeper.paths.test.ts index 7972b141..706a5b9c 100644 --- a/tests/fee-sweeper.paths.test.ts +++ b/tests/fee-sweeper.paths.test.ts @@ -14,7 +14,7 @@ import { import { WSOL_MINT } from "../src/utils/constants"; import { contractCapabilities } from "../src/utils/contract-idl"; import { getSupportedTokens } from "../src/utils/token-registry"; -import { TransactionHistory } from "../src/utils/transaction-history"; +import { TransactionHistory, type FinanceEventRecord } from "../src/utils/transaction-history"; const price = (value: number, extra: Record = {}) => (async () => ({ price: value, identifier: "x", resolvedAt: Date.now(), ...extra })) as any; @@ -329,6 +329,7 @@ describe("WSOL unwrap with the default balance reader", () => { }); describe("referral claims", () => { + type SweepInputs = Parameters; const referral = "GPBNTRmo26MRoaLSvRXwhWaQZhYjwVWgEkgwRZVU6x9U"; test("the default provider reads referral token accounts from the connection", async () => { @@ -411,7 +412,6 @@ describe("referral claims", () => { }); test("skips empty entries and sends each referral claim once in provider order", async () => { - type SweepInputs = Parameters; const first = { ...fakeTx(), serialize: () => new Uint8Array([8]) }; const second = { ...fakeTx(), serialize: () => new Uint8Array([9]) }; const s = await claimSetup({ transactions: [undefined, first, undefined, second] }); @@ -429,60 +429,84 @@ describe("referral claims", () => { expect(second.sign).toHaveBeenCalledTimes(1); }); - test("signs each claim with a fresh blockhash and records claimed deltas", async () => { - const tx = fakeTx(); - const s = await claimSetup({ transactions: [undefined, tx] }); - const events: any[] = []; - const history = TransactionHistory.getInstance(); - const record = spyOn(history, "recordFinanceEvent").mockImplementation((event: any) => { - events.push(event); - }); - const confirmed = { - slot: 12, - blockTime: 300, - meta: { - fee: 5000, - preTokenBalances: [ - { accountIndex: 1, mint: s.mint.toBase58(), uiTokenAmount: { amount: "9" } }, - ], - postTokenBalances: [ - { accountIndex: 1, mint: s.mint.toBase58(), uiTokenAmount: { amount: "2" } }, - ], - }, - transaction: { message: { staticAccountKeys: [s.payer.publicKey, s.accountKey] } }, - }; - (s.connection as any).getTransaction = async () => confirmed; - try { - const claims = await __test_runReferralSweep( - s.connection as any, - s.payer, - referral, - price(1), - () => s.provider as any, - ); - - expect(claims).toBe(1); - expect(tx.message.recentBlockhash).toBe("11111111111111111111111111111111"); - expect(tx.sign).toHaveBeenCalledWith([s.payer]); - expect(events).toEqual([ - { - eventId: `jupiter:claim-1:${s.accountKey.toBase58()}:claimed`, - source: "sweeper", - category: "swap_fee", - kind: "claimed", - signature: "claim-1", - account: s.accountKey.toBase58(), - mint: s.mint.toBase58(), - amountRaw: "7", - networkFeeLamports: "5000", - timestamp: 300_000, - slot: 12, + test.each([ + [300, 300_000], + [0, 0], + [null, 1_800_000_000_000], + ] as const)( + "signs each claim and records only an outgoing delta with block time %p", + async (blockTime, timestamp) => { + const tx = fakeTx(); + const s = await claimSetup({ transactions: [undefined, tx] }); + const incoming = (await Keypair.generate()).publicKey; + const unchanged = (await Keypair.generate()).publicKey; + const absent = (await Keypair.generate()).publicKey; + const list = spyOn(s.provider, "getReferralTokenAccountsV2").mockResolvedValue({ + tokenAccounts: [s.accountKey, incoming, unchanged, absent].map((pubkey) => ({ + pubkey, + account: { mint: s.mint, amount: 10_000_000_000n }, + })), + token2022Accounts: [], + }); + const clock = spyOn(Date, "now").mockReturnValue(1_800_000_000_321); + const events: FinanceEventRecord[] = []; + const history = TransactionHistory.getInstance(); + const record = spyOn(history, "recordFinanceEvent").mockImplementation((event) => { + events.push(event); + }); + const balance = (accountIndex: number, amount: string) => ({ + accountIndex, + mint: s.mint.toBase58(), + uiTokenAmount: { amount }, + }); + const confirmed = { + slot: 12, + blockTime, + meta: { + fee: 5000, + preTokenBalances: [balance(1, "9"), balance(2, "3"), balance(3, "5")], + postTokenBalances: [balance(1, "2"), balance(2, "8"), balance(3, "5")], }, - ]); - } finally { - record.mockRestore(); - } - }); + transaction: { + message: { staticAccountKeys: [s.payer.publicKey, s.accountKey, incoming, unchanged] }, + }, + }; + const connection = { ...s.connection, getTransaction: async () => confirmed }; + try { + const claims = await __test_runReferralSweep( + connection as unknown as SweepInputs[0], + s.payer, + referral, + price(1), + () => s.provider as unknown as ReturnType>, + ); + + expect(claims).toBe(1); + expect(tx.message.recentBlockhash).toBe("11111111111111111111111111111111"); + expect(tx.sign).toHaveBeenCalledWith([s.payer]); + expect(events).toEqual([ + { + eventId: `jupiter:claim-1:${s.accountKey.toBase58()}:claimed`, + source: "sweeper", + category: "swap_fee", + kind: "claimed", + signature: "claim-1", + account: s.accountKey.toBase58(), + mint: s.mint.toBase58(), + amountRaw: "7", + networkFeeLamports: "5000", + timestamp, + slot: 12, + }, + ]); + expect(warnSpy.mock.calls).toEqual([]); + } finally { + record.mockRestore(); + clock.mockRestore(); + list.mockRestore(); + } + }, + ); test("a claim that cannot be recorded is still counted", async () => { const s = await claimSetup({ transactions: [fakeTx()] }); From 18bdc598fec5232a79ed3b293aba56262019eb30 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 21:51:31 -0300 Subject: [PATCH 230/410] test(finance): cover default Oracle and legacy fee branches --- tests/fee-sweeper.paths.test.ts | 80 +++++++++++++++++++++++++++++++++ 1 file changed, 80 insertions(+) diff --git a/tests/fee-sweeper.paths.test.ts b/tests/fee-sweeper.paths.test.ts index 706a5b9c..ece6a8bf 100644 --- a/tests/fee-sweeper.paths.test.ts +++ b/tests/fee-sweeper.paths.test.ts @@ -1,6 +1,7 @@ import { afterEach, beforeEach, describe, expect, mock, spyOn, test } from "bun:test"; import { Keypair, PublicKey } from "#solana"; import { TOKEN_2022_PROGRAM_ID, TOKEN_PROGRAM_ID } from "#token"; +import { TokenPolicySchema } from "@timbagame/protocol/oracle"; import { __test_processTokenFee, __test_resolveFeeSweepTokens, @@ -10,9 +11,11 @@ import { __test_sweepTokensToSol, __test_unwrapWsolBalance, sweepFees, + type FeeSweepOptions, } from "../src/services/fee-sweeper"; import { WSOL_MINT } from "../src/utils/constants"; import { contractCapabilities } from "../src/utils/contract-idl"; +import { OracleClient } from "../src/utils/oracle"; import { getSupportedTokens } from "../src/utils/token-registry"; import { TransactionHistory, type FinanceEventRecord } from "../src/utils/transaction-history"; @@ -62,6 +65,42 @@ describe("fee token resolution", () => { expect(logged(errorSpy, "Failed to load dynamic token policies")).toBe(true); } }); + + test("uses the wallet's default Oracle client only on contracts with token policies", async () => { + const mint = (await Keypair.generate()).publicKey.toBase58(); + const getTokenMetadata = mock(async (_mint: string) => ({ symbol: " NEW ", decimals: 6 })); + const wallet = { getTokenMetadata } as unknown as Parameters< + typeof __test_resolveFeeSweepTokens + >[0]; + const getTokenPolicies = mock(async () => [ + TokenPolicySchema.parse({ + mint, + enabled: true, + revision: 1, + minimumAmountRaw: "1", + acceptedMinimumAmountRaw: "1", + effectiveAt: "2026-09-03T00:00:00.000Z", + }), + ]); + const oracle = spyOn(OracleClient, "getInstance").mockReturnValue({ + getTokenPolicies, + } as unknown as OracleClient); + try { + const tokens = await __test_resolveFeeSweepTokens(wallet); + if (contractCapabilities.oracleTokenPolicy) { + expect(oracle.mock.calls).toEqual([[wallet]]); + expect(getTokenPolicies.mock.calls).toEqual([[]]); + expect(getTokenMetadata.mock.calls).toEqual([[mint]]); + expect(tokens).toEqual([...getSupportedTokens(), { mint, ticker: "NEW" }]); + } else { + expect(oracle).not.toHaveBeenCalled(); + expect(getTokenMetadata).not.toHaveBeenCalled(); + expect(tokens).toEqual(getSupportedTokens()); + } + } finally { + oracle.mockRestore(); + } + }); }); describe("withdrawal threshold", () => { @@ -599,6 +638,47 @@ describe("sweepFees orchestration", () => { expect(result.tokenWithdrawals).toBe(contractCapabilities.gameTokenAccount ? 1 : 0); }); + test("legacy game fee sweeping counts only successful withdrawals and continues after an error", async () => { + const admin = await Keypair.generate(); + const wallet = { + getOperatorKeypair: async () => admin, + formatSolBalance: String, + } as unknown as NonNullable; + const tokenConfigs = [ + { mint: "one", ticker: "ONE" }, + { mint: "bad", ticker: "BAD" }, + { mint: "empty", ticker: "EMPTY" }, + { mint: "two", ticker: "TWO" }, + ]; + const visited: string[] = []; + const failure = new Error("withdraw failed"); + const result = await sweepFees({ + walletManager: wallet, + tokenConfigs, + referralAccount: "referral", + enableSwapToSol: false, + contextFactory: context(), + tokenFeeProcessor: async (_program, _connection, actualWallet, payer, _operator, token) => { + expect(actualWallet).toBe(wallet); + expect(payer).toBe(admin); + visited.push(token.ticker); + if (token.ticker === "BAD") throw failure; + return token.ticker !== "EMPTY"; + }, + referralSweeper: async () => 3, + }); + + if (contractCapabilities.gameTokenAccount) { + expect(visited).toEqual(["ONE", "BAD", "EMPTY", "TWO"]); + expect(result).toEqual({ tokenWithdrawals: 2, referralClaims: 3 }); + expect(errorSpy.mock.calls).toEqual([["❌ Failed withdrawing BAD:", failure]]); + } else { + expect(visited).toEqual([]); + expect(result).toEqual({ tokenWithdrawals: 0, referralClaims: 3 }); + expect(errorSpy.mock.calls).toEqual([]); + } + }); + test("builds the default swap manager for token sweeps", async () => { const admin = await Keypair.generate(); let manager: unknown; From d167f5ccc0a36d1d366c38262158b19fcf596329 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 21:52:53 -0300 Subject: [PATCH 231/410] test(finance): reject unusable SOL quotes before swaps --- tests/fee-sweeper.paths.test.ts | 37 +++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) diff --git a/tests/fee-sweeper.paths.test.ts b/tests/fee-sweeper.paths.test.ts index ece6a8bf..d69c2665 100644 --- a/tests/fee-sweeper.paths.test.ts +++ b/tests/fee-sweeper.paths.test.ts @@ -231,6 +231,43 @@ describe("SOL price validation before swaps", () => { expect(logged(warnSpy, reason)).toBe(true); }); + test.each([0, -0, -1, Number.POSITIVE_INFINITY])( + "rejects a SOL quote of %p even with a current timestamp", + async (value) => { + expect(await run({ price: value, resolvedAt: Date.now() })).toBe(0); + expect(warnSpy.mock.calls).toEqual([ + [ + "⚠️ skipping due to unreliable SOL price (missing or non-positive price); skipping token-to-SOL sweeps.", + ], + ]); + expect(errorSpy.mock.calls).toEqual([]); + }, + ); + + test("does not let a cached zero price block a current positive quote", async () => { + const { rememberPriceLookup } = await import("../src/utils/price-service"); + rememberPriceLookup({ price: 0, identifier: WSOL_MINT }, { tokenMint: WSOL_MINT }); + expect(await run({ price: 100, resolvedAt: Date.now() })).toBe(1); + expect(warnSpy.mock.calls).toEqual([]); + }); + + test("uses the provider timestamp only when the resolution time is missing", async () => { + const now = 1_800_000_000_000; + const clock = spyOn(Date, "now").mockReturnValue(now); + try { + expect(await run({ price: 100, resolvedAt: null, timestamp: now })).toBe(1); + expect(await run({ price: 100, resolvedAt: now, timestamp: now + 1 })).toBe(1); + expect(await run({ price: 100, resolvedAt: now + 1, timestamp: now })).toBe(0); + expect(warnSpy.mock.calls).toEqual([ + [ + "⚠️ skipping due to unreliable SOL price (future timestamp); skipping token-to-SOL sweeps.", + ], + ]); + } finally { + clock.mockRestore(); + } + }); + test("allows a price within the drift limit of the cached one", async () => { const { rememberPriceLookup, __test_clearPriceServiceCache } = await import("../src/utils/price-service"); From 38d4612d1e3fa40779001860d669da642e6ca095 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 21:57:41 -0300 Subject: [PATCH 232/410] fix(finance): validate referral quotes and mint precision --- src/services/fee-sweeper.ts | 19 ++-- tests/fee-sweeper.referral-decimals.test.ts | 100 ++++++++++++++++---- 2 files changed, 88 insertions(+), 31 deletions(-) diff --git a/src/services/fee-sweeper.ts b/src/services/fee-sweeper.ts index 31c68093..01bdee38 100644 --- a/src/services/fee-sweeper.ts +++ b/src/services/fee-sweeper.ts @@ -33,6 +33,7 @@ import type { SwapRequest } from "../utils/swap/types"; import { TransactionHistory } from "../utils/transaction-history"; import { referralDeltaFromTransaction } from "./finance-ledger"; import { OracleClient } from "../utils/oracle"; +import { isMintDecimals } from "../utils/token-decimals"; import { sanitizeTokenSymbol } from "../utils/token-display"; import type { TokenPolicy } from "@timbagame/protocol/oracle"; @@ -488,20 +489,18 @@ async function runReferralSweep( if (amount === 0n) continue; // Try to get price for this token - const priceData = await priceResolver({ tokenMint: mint }); - if (!priceData?.price || !Number.isFinite(priceData.price)) continue; + const unitPrice = (await priceResolver({ tokenMint: mint }))?.price ?? 0; + if (!Number.isFinite(unitPrice) || unitPrice <= 0) continue; // Fetch decimals for this token - const mintInfo = await connection.getParsedAccountInfo(tokenAccount.account.mint); - const decimals = - mintInfo.value && - "parsed" in mintInfo.value.data && - mintInfo.value.data.parsed?.info?.decimals != null - ? mintInfo.value.data.parsed.info.decimals - : 9; + const { value } = await connection.getParsedAccountInfo(tokenAccount.account.mint); + const mintData = value?.data; + const parsedDecimals = + mintData && "parsed" in mintData ? mintData.parsed?.info?.decimals : undefined; + const decimals = isMintDecimals(parsedDecimals) ? parsedDecimals : SOL_DECIMALS; const tokenAmount = Number(amount) / 10 ** decimals; - totalUsdValue += finiteUsdValue(tokenAmount, priceData.price); + totalUsdValue += finiteUsdValue(tokenAmount, unitPrice); } if (!Number.isFinite(totalUsdValue) || totalUsdValue < MIN_USD_THRESHOLD) { diff --git a/tests/fee-sweeper.referral-decimals.test.ts b/tests/fee-sweeper.referral-decimals.test.ts index 8c12a25e..84ec64ad 100644 --- a/tests/fee-sweeper.referral-decimals.test.ts +++ b/tests/fee-sweeper.referral-decimals.test.ts @@ -1,8 +1,9 @@ import { afterEach, beforeEach, describe, expect, spyOn, test } from "bun:test"; -import { Keypair } from "#solana"; +import { Keypair, type PublicKey } from "#solana"; import { __test_runReferralSweep } from "../src/services/fee-sweeper"; const referral = "11111111111111111111111111111111"; +type SweepInputs = Parameters; let logSpy: ReturnType; beforeEach(() => { @@ -14,14 +15,22 @@ afterEach(() => { const logged = (text: string) => logSpy.mock.calls.some((call: unknown[]) => String(call[0]).includes(text)); -const setup = async (decimals: number, amount: bigint) => { +const setup = async (decimalsOrAccount: number | { value: unknown }, amount: bigint) => { const payer = await Keypair.generate(); const mint = (await Keypair.generate()).publicKey; const accountKey = (await Keypair.generate()).publicKey; + const requestedMints: string[] = []; const connection = { - getParsedAccountInfo: async () => ({ - value: { data: { program: "spl-token", parsed: { info: { decimals } } } }, - }), + getParsedAccountInfo: async (requestedMint: PublicKey) => { + requestedMints.push(requestedMint.toBase58()); + return typeof decimalsOrAccount === "number" + ? { + value: { + data: { program: "spl-token", parsed: { info: { decimals: decimalsOrAccount } } }, + }, + } + : decimalsOrAccount; + }, }; const claimCalls: unknown[] = []; const provider = { @@ -34,8 +43,20 @@ const setup = async (decimals: number, amount: bigint) => { return []; }, }; - const price = async () => ({ price: 1, identifier: "x", resolvedAt: Date.now() }) as any; - return { payer, connection, provider, claimCalls, price }; + const price: NonNullable = async () => ({ + price: 1, + identifier: "x", + resolvedAt: Date.now(), + }); + const sweep = (priceResolver = price, referralProvider = provider) => + __test_runReferralSweep( + connection as unknown as SweepInputs[0], + payer, + referral, + priceResolver, + () => referralProvider as unknown as ReturnType>, + ); + return { mint, accountKey, provider, claimCalls, requestedMints, sweep }; }; describe("referral sweep uses on-chain mint decimals", () => { @@ -44,13 +65,7 @@ describe("referral sweep uses on-chain mint decimals", () => { // fallback the same raw amount would be worth $0.01 and be skipped. const s = await setup(6, 10_000_000n); - const claimed = await __test_runReferralSweep( - s.connection as any, - s.payer, - referral, - s.price, - () => s.provider as any, - ); + const claimed = await s.sweep(); expect(claimed).toBe(0); expect(s.claimCalls).toHaveLength(1); @@ -61,16 +76,59 @@ describe("referral sweep uses on-chain mint decimals", () => { // 10_000_000 raw at 9 decimals is 0.01 tokens, below the $5 threshold. const s = await setup(9, 10_000_000n); - const claimed = await __test_runReferralSweep( - s.connection as any, - s.payer, - referral, - s.price, - () => s.provider as any, - ); + const claimed = await s.sweep(); expect(claimed).toBe(0); expect(s.claimCalls).toHaveLength(0); expect(logged("Skipping referral claim: total value ≈ $0.01")).toBe(true); }); + + test("distinguishes a valid zero-decimal mint from the nine-decimal fallback", async () => { + const s = await setup(0, 5n); + await s.sweep(); + expect(s.claimCalls).toHaveLength(1); + expect(logged("Collecting Jupiter referral fees (~$5.00)")).toBe(true); + }); + + test.each([ + ["no account", { value: null }], + ["no parsed value", { value: { data: { parsed: null } } }], + ["no parsed info", { value: { data: { parsed: {} } } }], + ["no precision", { value: { data: { parsed: { info: {} } } } }], + ["negative precision", -1], + ["fractional precision", 0.5], + ["a numeric string", { value: { data: { parsed: { info: { decimals: "0" } } } } }], + ] as const)("uses nine decimals for %s", async (_case, account) => { + const s = await setup(account, 10_000_000n); + await s.sweep(); + expect(s.claimCalls).toEqual([]); + expect(logged("Skipping referral claim: total value ≈ $0.01")).toBe(true); + }); + + test("ignores a negative quote without reducing another mint below the claim threshold", async () => { + const s = await setup(0, 5n); + const invalidMint = (await Keypair.generate()).publicKey; + const invalidAccount = (await Keypair.generate()).publicKey; + const provider = { + ...s.provider, + getReferralTokenAccountsV2: async () => ({ + tokenAccounts: [ + { pubkey: s.accountKey, account: { mint: s.mint, amount: 5n } }, + { pubkey: invalidAccount, account: { mint: invalidMint, amount: 10n } }, + ], + token2022Accounts: [], + }), + }; + await s.sweep( + async ({ tokenMint }) => ({ + price: tokenMint === s.mint.toBase58() ? 1 : -1, + identifier: tokenMint ?? "missing", + resolvedAt: Date.now(), + }), + provider, + ); + expect(s.claimCalls).toHaveLength(1); + expect(s.requestedMints).toEqual([s.mint.toBase58()]); + expect(logged("Collecting Jupiter referral fees (~$5.00)")).toBe(true); + }); }); From 5e1b9d9dfe9ab1b1b22eae6c5f478c51411e57af Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 22:00:53 -0300 Subject: [PATCH 233/410] test(wallet): keep exact refresh amounts and error policy --- tests/wallet-ui.swr.test.ts | 80 ++++++++++++++++++++++++++++--------- 1 file changed, 61 insertions(+), 19 deletions(-) diff --git a/tests/wallet-ui.swr.test.ts b/tests/wallet-ui.swr.test.ts index 180482b0..80128c32 100644 --- a/tests/wallet-ui.swr.test.ts +++ b/tests/wallet-ui.swr.test.ts @@ -1,5 +1,5 @@ import "./setup-env"; -import { describe, expect, test } from "bun:test"; +import { describe, expect, spyOn, test } from "bun:test"; import { InlineKeyboard } from "grammy"; import { WALLET_BACKGROUND_REFRESH_MIN_AGE_MS, @@ -234,7 +234,6 @@ describe("showWalletUI stale-while-revalidate", () => { }; test.each([ - ["exact raw units", { ...usdc, rawBalance: "9007199254740993" }], ["mint", { ...usdc, mint: "So11111111111111111111111111111111111111112" }], ["numeric-only balance", { ...usdc, rawBalance: undefined, balance: 1 }], ])( @@ -250,6 +249,33 @@ describe("showWalletUI stale-while-revalidate", () => { }, ); + test("refreshes a one-unit raw change beyond the safe number range", async () => { + const { calls, captured } = await run({ + cached: { data: page(1e9, undefined, [usdc]), fetchedAt: NOW - 12_000 }, + fresh: async () => page(1e9, NOW, [{ ...usdc, rawBalance: "9007199254740993" }]), + }); + expect(calls.map(([kind]) => kind)).toEqual(["ctxEditText", "apiEditText"]); + expect(captured[0]).toContain("USDC: 9007199254.740992"); + expect(captured[1]).toContain("USDC: 9007199254.740993"); + const [, chatId, messageId, text, options] = calls[1]; + expect([chatId, messageId, text]).toEqual([99, 11, captured[1]]); + expect(options).toMatchObject({ + parse_mode: "HTML", + link_preview_options: { is_disabled: true }, + }); + }); + + test("keeps an unchanged raw amount when only the rounded numeric copy changes", async () => { + const { calls, captured, fetches } = await run({ + cached: { data: page(1e9, undefined, [usdc]), fetchedAt: NOW - 12_000 }, + fresh: async () => page(1e9, NOW, [{ ...usdc, balance: 9_007_199_254_740_994 }]), + }); + expect(fetches()).toBe(1); + expect(captured).toHaveLength(1); + expect(captured[0]).toContain("USDC: 9007199254.740992"); + expect(calls.map(([kind]) => kind)).toEqual(["ctxEditText"]); + }); + test("refreshes a numeric-only balance even when cached and fresh SOL are equal", async () => { const token = { ...usdc, rawBalance: undefined, balance: 1_000_000 }; const { calls, captured } = await run({ @@ -330,26 +356,42 @@ describe("showWalletUI stale-while-revalidate", () => { ["rate limited", tgError("Too Many Requests: retry after 5", 429)], ["other", tgError("Bad Request: chat not found")], ])("edit errors (%s) are swallowed without replies", async (_label, error) => { - const { calls } = await run({ - cached: { data: page(1e9), fetchedAt: NOW - 12_000 }, - editText: async () => { - throw error; - }, - }); - expect(calls.filter(([kind]) => kind === "apiEditText")).toHaveLength(1); - expect(calls.some(([kind]) => kind === "reply")).toBe(false); - }); - - test("background fetch failures keep the cached view", async () => { - for (const failure of [new RateLimitExceededError("slow down", 1_000), new Error("rpc down")]) { - const { calls, fetches } = await run({ + const warn = spyOn(console, "warn").mockImplementation(() => {}); + try { + const { calls } = await run({ cached: { data: page(1e9), fetchedAt: NOW - 12_000 }, - fresh: async () => { - throw failure; + editText: async () => { + throw error; }, }); - expect(fetches()).toBe(1); - expect(calls.some(([kind]) => kind.startsWith("api"))).toBe(false); + expect(calls.map(([kind]) => kind)).toEqual(["ctxEditText", "apiEditText"]); + expect(warn.mock.calls).toEqual( + _label === "other" + ? [["Background wallet refresh could not edit the wallet message:", error]] + : [], + ); + } finally { + warn.mockRestore(); + } + }); + + test("background fetch failures keep the cached view", async () => { + const warn = spyOn(console, "warn").mockImplementation(() => {}); + const rpcFailure = new Error("rpc down"); + try { + for (const failure of [new RateLimitExceededError("slow down", 1_000), rpcFailure]) { + const { calls, fetches } = await run({ + cached: { data: page(1e9), fetchedAt: NOW - 12_000 }, + fresh: async () => { + throw failure; + }, + }); + expect(fetches()).toBe(1); + expect(calls.map(([kind]) => kind)).toEqual(["ctxEditText"]); + } + expect(warn.mock.calls).toEqual([["Background wallet refresh failed for 1:", rpcFailure]]); + } finally { + warn.mockRestore(); } }); From 5745ee2a33c28379db12646833967098d1656eaa Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 22:02:18 -0300 Subject: [PATCH 234/410] test(wallet): report retries and invalid chain time exactly --- tests/wallet.resubmit.test.ts | 54 +++++++++++++++++++++++++++++++++++ tests/wallet.time.test.ts | 6 ++++ 2 files changed, 60 insertions(+) diff --git a/tests/wallet.resubmit.test.ts b/tests/wallet.resubmit.test.ts index 91394b7c..7542567d 100644 --- a/tests/wallet.resubmit.test.ts +++ b/tests/wallet.resubmit.test.ts @@ -30,6 +30,60 @@ class ResubmitConnection implements Partial { } describe("WalletManager sendAndConfirmWithResubmits", () => { + test.each([0, 1, 2] as const)( + "reports the confirmed signature after %i resubmits", + async (retries) => { + const connection = new ResubmitConnection(); + const wallet = WalletManager.createForTest(MNEMONIC, { + connection: connection as unknown as Connection, + }); + let checked = 0; + const confirm = spyOn(wallet, "confirmTransaction").mockImplementation(async (signature) => { + checked += 1; + if (checked <= retries) throw new Error(`Transaction ${signature} timed out`); + }); + const log = spyOn(console, "log").mockImplementation(() => {}); + const warn = spyOn(console, "warn").mockImplementation(() => {}); + try { + const signers = [await Keypair.generate()]; + const instruction = new TransactionInstruction({ + programId: PublicKey.default, + keys: [], + data: Buffer.alloc(0), + }); + const result = await wallet.sendAndConfirmWithResubmits([instruction], signers, { + operationLabel: "Test claim", + maxResubmits: 2, + }); + expect(result).toBe(`SIG${retries + 1}`); + expect(connection.sendCalls).toBe(retries + 1); + expect(confirm.mock.calls).toEqual( + Array.from({ length: retries + 1 }, (_, index) => [`SIG${index + 1}`]), + ); + const namedLogs = (calls: unknown[][]) => + calls.filter(([value]) => typeof value === "string" && value.includes("Test claim")); + expect(namedLogs(warn.mock.calls)).toEqual( + Array.from({ length: retries }, (_, index) => [ + `♻️ Test claim resubmit ${index + 1}/2 after failure: Transaction SIG${index + 1} timed out`, + ]), + ); + expect(namedLogs(log.mock.calls)).toEqual( + retries === 0 + ? [] + : [ + [ + `✅ Test claim confirmed after ${retries} ${retries === 1 ? "resubmit" : "resubmits"}: SIG${retries + 1}`, + ], + ], + ); + } finally { + confirm.mockRestore(); + log.mockRestore(); + warn.mockRestore(); + } + }, + ); + test("re-signs and confirms on blockhash expiry", async () => { const connection = new ResubmitConnection(); const wallet = WalletManager.createForTest(MNEMONIC, { diff --git a/tests/wallet.time.test.ts b/tests/wallet.time.test.ts index ce3eaed6..4a5f0ffa 100644 --- a/tests/wallet.time.test.ts +++ b/tests/wallet.time.test.ts @@ -28,6 +28,12 @@ describe("WalletManager time-related helpers", () => { expect(await wallet.getBlockchainTime()).toBe(1_700_000_010); expect(await wallet.getBlockchainTime()).toBe(1_700_000_010); expect(getBlockTime.mock.calls).toEqual([[42n], [42n]]); + expect(logger.mock.calls).toEqual([ + [ + "Falling back to system time:", + expect.objectContaining({ message: "Could not get blockchain time" }), + ], + ]); } finally { now.mockRestore(); logger.mockRestore(); From 38bea90d9348219a74827ef25712617042d97055 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 22:03:07 -0300 Subject: [PATCH 235/410] test(wallet): expire local mint metadata at the exact TTL --- tests/wallet.injection.test.ts | 36 +++++++++++++++++++++++++++++++++- 1 file changed, 35 insertions(+), 1 deletion(-) diff --git a/tests/wallet.injection.test.ts b/tests/wallet.injection.test.ts index 69a4a612..d8143a42 100644 --- a/tests/wallet.injection.test.ts +++ b/tests/wallet.injection.test.ts @@ -1,4 +1,4 @@ -import { afterEach, beforeEach, describe, expect, test } from "bun:test"; +import { afterEach, beforeEach, describe, expect, spyOn, test } from "bun:test"; import { WalletManager } from "../src/utils/wallet"; import { Keypair, PublicKey } from "#solana"; import { @@ -201,6 +201,40 @@ describe("WalletManager dependency injection", () => { expect(await wallet.getTokenMetadata(mint)).toEqual({ decimals: 9 }); }); + test("caches valid resolver metadata by mint through the five-minute window", async () => { + const mintA = "11111111111111111111111111111111"; + const mintB = "So11111111111111111111111111111111111111112"; + const resolved: string[] = []; + const start = 1_800_000_000_000; + let now = start; + let symbol = "OLD"; + const clock = spyOn(Date, "now").mockImplementation(() => now); + try { + const wallet = WalletManager.createForTest("test mnemonic", { + connection: makeMockConnection(), + fetch: async () => { + throw new Error("Cached local metadata must not use HTTP"); + }, + tokenMetadataResolver: async (mint) => { + resolved.push(mint); + return mint === mintA ? { decimals: 0, symbol } : { decimals: 9, symbol: "OTHER" }; + }, + }); + + expect(await wallet.getTokenMetadata(mintA)).toEqual({ decimals: 0, symbol: "OLD" }); + expect(await wallet.getTokenMetadata(mintB)).toEqual({ decimals: 9, symbol: "OTHER" }); + symbol = "NEW"; + now = start + 299_999; + expect(await wallet.getTokenMetadata(mintA)).toEqual({ decimals: 0, symbol: "OLD" }); + now += 1; + expect(await wallet.getTokenMetadata(mintA)).toEqual({ decimals: 0, symbol: "NEW" }); + expect(await wallet.getTokenMetadata(mintA)).toEqual({ decimals: 0, symbol: "NEW" }); + expect(resolved).toEqual([mintA, mintB, mintA]); + } finally { + clock.mockRestore(); + } + }); + test("getFullTokenMetadata falls back to Jupiter and reads decimals via RPC", async () => { const conn = makeMockConnection(); const mint = "11111111111111111111111111111111"; // valid base58, not in knownTokens From 3be51c688581e218aa0e8785a0a44c381a8ff017 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 22:04:27 -0300 Subject: [PATCH 236/410] test(wallet): pin recovered status timing and retry count --- tests/wallet.confirm-and-send.test.ts | 19 ++++++++++++++----- 1 file changed, 14 insertions(+), 5 deletions(-) diff --git a/tests/wallet.confirm-and-send.test.ts b/tests/wallet.confirm-and-send.test.ts index 98a67cbd..a1129928 100644 --- a/tests/wallet.confirm-and-send.test.ts +++ b/tests/wallet.confirm-and-send.test.ts @@ -1,4 +1,4 @@ -import { afterEach, beforeEach, describe, expect, test } from "bun:test"; +import { afterEach, beforeEach, describe, expect, spyOn, test } from "bun:test"; import { Connection, Keypair, PublicKey } from "#solana"; import { TOKEN_PROGRAM_ID } from "#token"; import { WalletManager } from "../src/utils/wallet"; @@ -92,7 +92,7 @@ describe("WalletManager confirmTransaction and sendTransaction", () => { "retries '%s' once after two slots", async (message) => { let calls = 0; - const conn: any = { + const conn = { getSignatureStatuses: async () => { calls += 1; if (calls === 1) throw new Error(message); @@ -102,16 +102,25 @@ describe("WalletManager confirmTransaction and sendTransaction", () => { getBlockHeight: async () => 1, }; const wm = WalletManager.createForTest(MNEMONIC, { - connection: conn, - fetch: globalThis.fetch as any, - timeNow: () => Date.now(), + connection: conn as unknown as Connection, }); const clock = useWalletConfirmationClock(wm); + const warn = spyOn(console, "warn").mockImplementation(() => {}); + const log = spyOn(console, "log").mockImplementation(() => {}); try { await wm.confirmTransaction("FAKESIG"); expect(calls).toBe(2); expect(clock.delays).toEqual([800]); + expect(clock.elapsed()).toBe(800); + expect(warn.mock.calls).toEqual([ + ["⚠️ Network issue checking FAKESIG (poll 1, 0ms), retrying with longer delay"], + ]); + expect(log.mock.calls.at(-1)).toEqual([ + "✅ Transaction FAKESIG confirmed in 800ms (2 polls, history=not-used, firstStatus=800ms, networkRetries=1)", + ]); } finally { + warn.mockRestore(); + log.mockRestore(); clock.restore(); } }, From abaa8f3cfbba9430fbbb7b38e78f6fcb15a6cd08 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 22:06:33 -0300 Subject: [PATCH 237/410] test(recovery): run production backoff on bounded timers --- ...ame-manager.cancel-creator.success.test.ts | 7 +-- tests/game-manager.confirm-reload.test.ts | 3 ++ tests/game-manager.create-game.test.ts | 7 +-- tests/game-manager.unjoin-errors.test.ts | 3 ++ tests/game.create-game.test.ts | 3 ++ tests/game.funding-and-tokens.test.ts | 4 +- tests/helpers/timers.ts | 19 ++++++-- tests/transaction-runner.test.ts | 43 +++++++++++++++++++ 8 files changed, 78 insertions(+), 11 deletions(-) diff --git a/tests/game-manager.cancel-creator.success.test.ts b/tests/game-manager.cancel-creator.success.test.ts index 9ef36e0d..8bcc33bb 100644 --- a/tests/game-manager.cancel-creator.success.test.ts +++ b/tests/game-manager.cancel-creator.success.test.ts @@ -4,11 +4,12 @@ import { PublicKey, Keypair } from "#solana"; import { WalletManager } from "../src/utils/wallet"; import { TOKEN_PROGRAM_ID, ASSOCIATED_TOKEN_PROGRAM_ID } from "#token"; import { contractCapabilities } from "../src/utils/contract-idl"; +import { useInstantRecoveryBackoff } from "./helpers/timers"; + +useInstantRecoveryBackoff(); function resetGM() { - // reset singleton - // @ts-ignore - GameManager["instance"] = undefined; + GameManager.resetForTest(); } const MNEMONIC = diff --git a/tests/game-manager.confirm-reload.test.ts b/tests/game-manager.confirm-reload.test.ts index 94d2cf44..6aedcd86 100644 --- a/tests/game-manager.confirm-reload.test.ts +++ b/tests/game-manager.confirm-reload.test.ts @@ -2,6 +2,9 @@ import { describe, test, expect } from "bun:test"; import { GameManager } from "../src/utils/game"; import { PublicKey, Keypair } from "#solana"; import { formatUserFriendlyError } from "../src/utils/errors"; +import { useInstantRecoveryBackoff } from "./helpers/timers"; + +useInstantRecoveryBackoff(); const DEFAULT_GAME_PDA = new PublicKey("BPFLoader1111111111111111111111111111111111"); const DEFAULT_PLAYER_PUBKEY = new PublicKey("BPFLoader2111111111111111111111111111111111"); diff --git a/tests/game-manager.create-game.test.ts b/tests/game-manager.create-game.test.ts index bc015824..1296e9c1 100644 --- a/tests/game-manager.create-game.test.ts +++ b/tests/game-manager.create-game.test.ts @@ -1,4 +1,4 @@ -import { withinTestDeadline } from "./helpers/timers"; +import { useInstantRecoveryBackoff, withinTestDeadline } from "./helpers/timers"; import { describe, test, expect, vi } from "bun:test"; import { getBase64EncodedWireTransaction, @@ -20,6 +20,8 @@ import { contractCapabilities } from "../src/utils/contract-idl"; import { decodeGameTransaction } from "../src/utils/game-transaction"; import type { ChallengedPlayer } from "../src/utils/game-database"; +useInstantRecoveryBackoff(); + const TEST_ORACLE = await Keypair.generate(); async function signGameTransactionAsOracle(txBase64: string): Promise { @@ -29,8 +31,7 @@ async function signGameTransactionAsOracle(txBase64: string): Promise { } function resetGM() { - // @ts-ignore - GameManager["instance"] = undefined; + GameManager.resetForTest(); } function getGameManager(...args: Parameters): GameManager { diff --git a/tests/game-manager.unjoin-errors.test.ts b/tests/game-manager.unjoin-errors.test.ts index be07b8ca..ae91fdfa 100644 --- a/tests/game-manager.unjoin-errors.test.ts +++ b/tests/game-manager.unjoin-errors.test.ts @@ -1,6 +1,9 @@ import { afterEach, beforeEach, describe, test, expect, spyOn } from "bun:test"; import { PublicKey, Keypair } from "#solana"; import { GameManager } from "../src/utils/game"; +import { useInstantRecoveryBackoff } from "./helpers/timers"; + +useInstantRecoveryBackoff(); function resetGM() { GameManager.resetForTest(); diff --git a/tests/game.create-game.test.ts b/tests/game.create-game.test.ts index 74848c68..aeaabe07 100644 --- a/tests/game.create-game.test.ts +++ b/tests/game.create-game.test.ts @@ -7,6 +7,9 @@ import { PDAManager } from "../src/utils/pda"; import { decodeGameTransaction } from "../src/utils/game-transaction"; import { getCachedPriceLookup } from "../src/utils/price-service"; import { WSOL_MINT } from "../src/utils/constants"; +import { useInstantRecoveryBackoff } from "./helpers/timers"; + +useInstantRecoveryBackoff(); const TEST_ORACLE = await Keypair.generate(); const FIXED_PDA = new PublicKey("11111111111111111111111111111111"); diff --git a/tests/game.funding-and-tokens.test.ts b/tests/game.funding-and-tokens.test.ts index 97908157..4321230d 100644 --- a/tests/game.funding-and-tokens.test.ts +++ b/tests/game.funding-and-tokens.test.ts @@ -5,7 +5,9 @@ import { WSOL_MINT } from "../src/utils/constants"; import { GameManager } from "../src/utils/game"; import { __test_clearPriceServiceCache } from "../src/utils/price-service"; import { __test_resetPriceCache } from "../src/utils/prices"; -import { stubInstantTimers, withinTestDeadline } from "./helpers/timers"; +import { stubInstantTimers, useInstantRecoveryBackoff, withinTestDeadline } from "./helpers/timers"; + +useInstantRecoveryBackoff(); const GAME_PDA = new PublicKey("BPFLoader1111111111111111111111111111111111"); const PLAYER_PUBKEY = new PublicKey("BPFLoader2111111111111111111111111111111111"); diff --git a/tests/helpers/timers.ts b/tests/helpers/timers.ts index 07f57ad8..b6e4e8bf 100644 --- a/tests/helpers/timers.ts +++ b/tests/helpers/timers.ts @@ -1,4 +1,4 @@ -import { spyOn } from "bun:test"; +import { afterEach, beforeEach, spyOn } from "bun:test"; const scheduleDeadline = globalThis.setTimeout; const cancelDeadline = globalThis.clearTimeout; @@ -22,13 +22,13 @@ export async function withinTestDeadline(result: Promise, action: string): * code under test do not burn wall-clock time. Callbacks still run * asynchronously (on a real 0ms timer), so ordering relative to promises is * preserved. Requested delays are recorded in `delays`. If supplied, a predicate - * selects which calls to stub. Call `restore()` in `afterEach` (or a `finally`). + * selects delays to stub. Call `restore()` in `afterEach` (or a `finally`). */ -export const stubInstantTimers = (shouldStub?: () => boolean) => { +export const stubInstantTimers = (shouldStub?: (delayMs: number) => boolean) => { const originalSetTimeout = globalThis.setTimeout; const delays: number[] = []; globalThis.setTimeout = ((callback: (...args: any[]) => void, ms?: number, ...args: any[]) => { - if (shouldStub && !shouldStub()) return originalSetTimeout(callback, ms, ...args); + if (shouldStub && !shouldStub(ms ?? 0)) return originalSetTimeout(callback, ms, ...args); delays.push(ms ?? 0); return originalSetTimeout(callback, 0, ...args); }) as typeof setTimeout; @@ -39,6 +39,17 @@ export const stubInstantTimers = (shouldStub?: () => boolean) => { }, }; }; + +/** Keep recovery fixtures bounded even when they use the production backoff. */ +export function useInstantRecoveryBackoff() { + const recoveryDelays = new Set([2_000, 4_000, 8_000, 12_000, 16_000, 20_000]); + let timers: ReturnType; + beforeEach(() => { + timers = stubInstantTimers((delayMs) => recoveryDelays.has(delayMs)); + }); + afterEach(() => timers.restore()); +} + export function mockDateNowWithReadLimit(readNow: () => number, maxReads = 1_000) { let reads = 0; return spyOn(Date, "now").mockImplementation(() => { diff --git a/tests/transaction-runner.test.ts b/tests/transaction-runner.test.ts index 197399bd..9e343cde 100644 --- a/tests/transaction-runner.test.ts +++ b/tests/transaction-runner.test.ts @@ -14,6 +14,9 @@ import { getConfirmationRetryDelays, } from "../src/utils/transaction-runner"; import { TransactionOutcomeUnknownError } from "../src/utils/wallet"; +import { stubInstantTimers, useInstantRecoveryBackoff, withinTestDeadline } from "./helpers/timers"; + +useInstantRecoveryBackoff(); type Status = { err?: unknown; confirmationStatus?: string; confirmations?: unknown } | null; @@ -86,6 +89,46 @@ describe("getConfirmationRetryDelays", () => { }); describe("confirmTransactionWithRecovery", () => { + test("checks the original signature through the full production schedule", async () => { + const previous = process.env.NODE_ENV; + const timers = stubInstantTimers(); + process.env.NODE_ENV = "production"; + let checks = 0; + const { wallet, statusCalls } = makeWallet({ + confirm: async () => { + throw timeout(); + }, + statuses: () => { + checks += 1; + return checks === 6 ? { confirmationStatus: "confirmed" } : null; + }, + }); + try { + const result = await withinTestDeadline( + confirmTransactionWithRecovery({ + wallet, + initialSignature: "original", + operationLabel: "Create game", + }), + "production confirmation backoff", + ); + expect(result).toBe("original"); + expect(statusCalls).toEqual([ + "original", + "original", + "original", + "original", + "original", + "original", + ]); + expect(timers.delays).toEqual([2_000, 4_000, 8_000, 12_000, 16_000, 20_000]); + } finally { + if (previous === undefined) delete process.env.NODE_ENV; + else process.env.NODE_ENV = previous; + timers.restore(); + } + }); + test.each([ ["absent RPC result", undefined], ["null RPC result", null], From d3b65c8ef1a09cc39429279f6f48e066bb3a208f Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 22:10:34 -0300 Subject: [PATCH 238/410] test(tokens): pin positional numeric amount arguments --- tests/token-manager.amounts.test.ts | 32 +++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/tests/token-manager.amounts.test.ts b/tests/token-manager.amounts.test.ts index 042ce59b..a2fbba85 100644 --- a/tests/token-manager.amounts.test.ts +++ b/tests/token-manager.amounts.test.ts @@ -54,6 +54,18 @@ describe("parseAmount argument validation", () => { }); }); + test("rejects an absent command argument list without looking up a price", async () => { + const tm = makeManager(); + const quote = spyOn(priceService, "getUsdPrice"); + for (const args of [undefined, null, []]) { + expect(await Reflect.apply(tm.parseAmount, tm, [args, 0, 1, "game"])).toEqual({ + success: false, + error: "invalid_amount", + }); + } + expect(quote).not.toHaveBeenCalled(); + }); + test("rejects a non-numeric token amount", async () => { const tm = makeManager(); @@ -87,6 +99,26 @@ describe("parseAmount argument validation", () => { error: "invalid_amount", }); }); + + test.each(["7", "10", "123456789012345678", "10.125"])( + "keeps a following numeric argument %s separate from a first-position stake", + async (following) => { + const tm = makeManager(); + expect(await tm.parseAmount(["2.25", following], 0, 1, "game")).toEqual({ + success: true, + data: { + amount: 2_250_000, + formattedAmount: "2.25 DISC", + tokenMint: "MINT", + tokenTicker: "DISC", + decimals: 6, + isSol: false, + tokenWasSpecified: false, + requestedNativeSol: false, + }, + }); + }, + ); }); describe("parseAmount USD conversion", () => { From 2538e20167f1afad3bf15f0abfd8bdefe4f17870 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 22:10:41 -0300 Subject: [PATCH 239/410] test(tokens): keep exact wrapped SOL and precision fallback --- tests/token-manager.metadata.test.ts | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/tests/token-manager.metadata.test.ts b/tests/token-manager.metadata.test.ts index c064c7a2..76ae423e 100644 --- a/tests/token-manager.metadata.test.ts +++ b/tests/token-manager.metadata.test.ts @@ -62,6 +62,17 @@ describe("addToken decimals validation", () => { }); }); + test("does not coerce a decimal string reported by a wallet provider", async () => { + const getFull = vi.fn(async (_mint: string) => full({ decimals: "6" })); + const getToken = vi.fn(async (_mint: string) => ({ decimals: 0 })); + const tm = makeManager({ getFullTokenMetadata: getFull, getTokenMetadata: getToken }); + + expect(await tm.autoDiscoverTokenInfo(UNKNOWN_MINT)).toEqual({ ticker: "DISC", decimals: 0 }); + expect(getFull.mock.calls).toEqual([[UNKNOWN_MINT]]); + expect(getToken.mock.calls).toEqual([[UNKNOWN_MINT]]); + expect(tm.getKnownTokenByMint(UNKNOWN_MINT)).toBeNull(); + }); + test("rejects invalid decimals reported by the wallet and logs the failure", async () => { const tm = makeManager({ getTokenMetadata: async () => ({ decimals: 40 }) }); @@ -85,6 +96,16 @@ describe("autoDiscoverTokenInfo metadata resolution", () => { expect(getToken).not.toHaveBeenCalled(); }); + test("labels discovery by wrapped SOL mint as WSOL without querying the wallet", async () => { + const getFull = vi.fn(async () => full()); + const getToken = vi.fn(async () => ({ decimals: 0 })); + const tm = makeManager({ getFullTokenMetadata: getFull, getTokenMetadata: getToken }); + + expect(await tm.autoDiscoverTokenInfo(WSOL_MINT)).toEqual({ ticker: "WSOL", decimals: 9 }); + expect(getFull).not.toHaveBeenCalled(); + expect(getToken).not.toHaveBeenCalled(); + }); + test("falls back to on-chain decimals and a TOKEN_ ticker when full metadata fails", async () => { const tm = makeManager({ getFullTokenMetadata: async () => { From f692a0caab34e524859a7d50d52ae1a05b8b2922 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 22:13:59 -0300 Subject: [PATCH 240/410] test(wallet): retain safe wrap errors and operator detail --- tests/wallet-transactions.flows.test.ts | 23 +++++++++++++++++++---- 1 file changed, 19 insertions(+), 4 deletions(-) diff --git a/tests/wallet-transactions.flows.test.ts b/tests/wallet-transactions.flows.test.ts index 354cd20e..cfa41aff 100644 --- a/tests/wallet-transactions.flows.test.ts +++ b/tests/wallet-transactions.flows.test.ts @@ -1,4 +1,4 @@ -import { afterEach, beforeAll, beforeEach, describe, expect, test } from "bun:test"; +import { afterEach, beforeAll, beforeEach, describe, expect, spyOn, test } from "bun:test"; import { Keypair } from "#solana"; import { bot, @@ -346,9 +346,24 @@ describe("wrap and unwrap flows", () => { wraps.push(args); return "fake-wrap"; }); - await press(`confirm_wrap_${amount}`, { userId: USER }); - expect(wraps).toEqual([]); - expect(answers().at(-1)).toBe("❌ Wrap failed"); + const errors = spyOn(console, "error").mockImplementation(() => {}); + try { + await press(`confirm_wrap_${amount}`, { userId: USER }); + expect(wraps).toEqual([]); + expect(answers().at(-1)).toBe("❌ Wrap failed"); + expect(lastText()).toContain("❌ Something went wrong"); + expect(lastText()).not.toContain("Invalid wrap amount"); + expect( + errors.mock.calls.filter(([stage]) => stage === "Error in wrap confirmation:"), + ).toEqual([ + [ + "Error in wrap confirmation:", + expect.objectContaining({ message: "Invalid wrap amount" }), + ], + ]); + } finally { + errors.mockRestore(); + } }); test("wrap failures and invalid amounts show an error", async () => { From 6efcb34d27a50a3daaa021ddac5593639cbbd308 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 22:14:10 -0300 Subject: [PATCH 241/410] test(recovery): ignore pending creation rows cleared by another worker --- tests/game.creation-recovery.test.ts | 35 ++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) diff --git a/tests/game.creation-recovery.test.ts b/tests/game.creation-recovery.test.ts index 144b56d6..76d81817 100644 --- a/tests/game.creation-recovery.test.ts +++ b/tests/game.creation-recovery.test.ts @@ -86,6 +86,41 @@ function makeCtx(chatId = 5) { return { ctx, calls }; } +describe("recovery with a stale pending-creation snapshot", () => { + test.each([true, false])( + "does not redeliver a row seen initially=%p and then cleared", + async (seenInitially) => { + const pending = makePending({ + state: "failed", + last_error: "stale intent", + creation_message_id: 9, + }); + const { ctx, calls } = makeCtx(); + let reads = 0; + const writes: unknown[][] = []; + const manager = makeManager({ + db: { + getPendingGameCreation: (address: string) => { + expect(address).toBe(GAME); + return reads++ === 0 && seenInitially ? pending : null; + }, + clearPendingGameCreationIfState: (...args: unknown[]) => { + writes.push(args); + }, + getGame: () => { + throw new Error("Cleared attempts must not read a game account"); + }, + }, + }); + + expect(await manager.recoverPendingGameCreation(ctx, pending)).toBe(true); + expect(calls).toEqual([]); + expect(writes).toEqual([]); + expect(errorSpy).not.toHaveBeenCalled(); + }, + ); +}); + describe("deliverPendingGameCreation", () => { function setup(db: Record, gm?: Record) { const manager = makeManager({ db }); From 031755a14c1805e90e31a99a10352acaca8d6ea7 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 22:15:17 -0300 Subject: [PATCH 242/410] test(game): restore old controls when rollback is already complete --- tests/game-manager.update-message.test.ts | 26 ++++++++++++++++------- 1 file changed, 18 insertions(+), 8 deletions(-) diff --git a/tests/game-manager.update-message.test.ts b/tests/game-manager.update-message.test.ts index 4d9c150d..8eb5ea60 100644 --- a/tests/game-manager.update-message.test.ts +++ b/tests/game-manager.update-message.test.ts @@ -511,13 +511,23 @@ describe("GameManager.updateGameMessage routing", () => { }); const deleteGone = { description: "Bad Request: message to delete not found" }; + const editGone = { description: "Bad Request: message to edit not found" }; const notModified = { description: "Bad Request: message is not modified" }; - for (const [label, failDelete, strandReplacement, originalAlreadyCleared] of [ - ["", undefined, false, false], - [" (delete fails)", new Error("synthetic delete unavailable"), false, false], - [" (replacement already gone)", deleteGone, false, false], - [" (replacement stranded)", new Error("synthetic delete unavailable"), true, false], - [" (original keyboard already cleared)", undefined, false, true], + const deleteUnavailable = new Error("synthetic delete unavailable"); + for (const [ + label, + failDelete, + strandReplacement, + originalAlreadyCleared, + replacementRetireError, + ] of [ + ["", undefined, false, false, undefined], + [" (delete fails)", deleteUnavailable, false, false, undefined], + [" (replacement already gone)", deleteGone, false, false, editGone], + [" (replacement removed before editing)", deleteUnavailable, false, false, editGone], + [" (replacement keyboard already cleared)", deleteUnavailable, false, false, notModified], + [" (replacement stranded)", deleteUnavailable, true, false, undefined], + [" (original keyboard already cleared)", undefined, false, true, undefined], ] as const) { test(`coinflip retires the replacement card when persisting it fails${label}`, async () => { resetGM(); @@ -548,8 +558,8 @@ describe("GameManager.updateGameMessage routing", () => { failRetireMessageIds: strandReplacement ? [777] : undefined, retireErrorsOnce: originalAlreadyCleared ? new Map([[46, notModified]]) - : failDelete === deleteGone - ? new Map([[777, { description: "Bad Request: message to edit not found" }]]) + : replacementRetireError + ? new Map([[777, replacementRetireError]]) : undefined, }); const addr = new PublicKey("11111111111111111111111111111115").toBase58(); From 886099724df4f58bfe8eb54a994ef10f8bcad82a Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 22:16:34 -0300 Subject: [PATCH 243/410] test(game): scope inline username hints to the sender chat --- tests/game.messages-and-usernames.test.ts | 39 +++++++++++++++++++++++ 1 file changed, 39 insertions(+) diff --git a/tests/game.messages-and-usernames.test.ts b/tests/game.messages-and-usernames.test.ts index ab4280a8..623825a3 100644 --- a/tests/game.messages-and-usernames.test.ts +++ b/tests/game.messages-and-usernames.test.ts @@ -4,6 +4,7 @@ import { ChatDatabase } from "../src/utils/chat-database"; import { GameManager } from "../src/utils/game"; import { formatPlayerAddress } from "../src/utils/game-ui"; import { resetTestDatabase } from "./helpers/database"; +import { makeTestTelegramContext } from "./helpers/grammy"; const GAME_PDA = new PublicKey("BPFLoader1111111111111111111111111111111111"); const GAME_ADDRESS = GAME_PDA.toBase58(); @@ -88,6 +89,44 @@ describe("GameManager username normalisation and priming", () => { gm.primeUsernameCache(ctx, "12", " alice "); expect(gm.usernameCache.get(gm.buildUsernameCacheKey(ctx, "12"))).toBe("alice"); }); + + test("uses the inline sender's private chat for a primed name, not another chat", async () => { + const gm = makeManager({ gameDb: { saveUsernameMapping: () => {} } }); + const actor = { id: 5, is_bot: false, first_name: "Actor" }; + const inline = makeTestTelegramContext({ + update_id: 1, + inline_query: { id: "inline", from: actor, query: "", offset: "" }, + }); + const privateChat = (id: number) => + makeTestTelegramContext({ + update_id: id, + message: { + message_id: 1, + date: 1_700_000_000, + chat: { id, type: "private", first_name: "Test chat" }, + from: { ...actor, id }, + text: "game", + }, + }); + const ownChat = privateChat(5); + const otherChat = privateChat(6); + const member = { + status: "member" as const, + user: { id: 12, is_bot: false, first_name: "Fresh", username: "live" }, + }; + const ownLookup = spyOn(ownChat.api, "getChatMember").mockResolvedValue(member); + const otherLookup = spyOn(otherChat.api, "getChatMember").mockResolvedValue(member); + try { + gm.primeUsernameCache(inline, "12", "Inline name"); + expect(await gm.getUsernameFromTelegramId(ownChat, "12")).toBe("Inline name"); + expect(await gm.getUsernameFromTelegramId(otherChat, "12")).toBe("@live"); + expect(ownLookup).not.toHaveBeenCalled(); + expect(otherLookup.mock.calls).toEqual([[6, 12]]); + } finally { + ownLookup.mockRestore(); + otherLookup.mockRestore(); + } + }); }); describe("GameManager getUsernameFromTelegramId without a network lookup", () => { From d276c1274d25a9e1392f1608fc21ccba9dec6e43 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 22:17:14 -0300 Subject: [PATCH 244/410] test(settings): verify token reset aliases and privacy defaults --- tests/chat-defaults.handler.test.ts | 46 +++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) diff --git a/tests/chat-defaults.handler.test.ts b/tests/chat-defaults.handler.test.ts index 644bffb6..29cbad0b 100644 --- a/tests/chat-defaults.handler.test.ts +++ b/tests/chat-defaults.handler.test.ts @@ -1568,6 +1568,52 @@ describe("chat defaults menus and inputs", () => { expect(h.replies).toEqual([]); }); + test.each(["cLeAr", "rEmOvE"])( + "the group command %s resets the token and refreshes feeds once", + async (alias) => { + const h = setup(); + h.tokenManager.setChatDefaultToken(99, "mint", "AAA", "1"); + + await h.module.handleDefaultCommand(h.ctxFor(), ["/default", alias]); + + expect(h.tokenManager.getChatDefaultToken(99)).toBeNull(); + expect(h.refreshes()).toBe(1); + expect(h.replies).toEqual([ + "✅ Default token cleared for this chat. Using bot default token now.", + ]); + expect(h.menus).toEqual([]); + }, + ); + + test("resets each game privacy to its own default and acknowledges only the affected setting", async () => { + const h = setup(); + await h.press("chat_defaults_game_coinflip"); + expect(h.lastMenu().text).toContain("👁️ Privacy: Public 🌍"); + await h.press("chat_defaults_game_giveaway"); + expect(h.lastMenu().text).toContain("👁️ Privacy: Private 🔒"); + + await h.press("chat_defaults_set_privacy_coinflip_private"); + await h.press("chat_defaults_set_privacy_giveaway_public"); + await h.press("chat_defaults_set_privacy_coinflip_clear"); + expect(chatDb.getChatGameSettings(99)).toMatchObject({ + coinflip_default_privacy: null, + giveaway_default_privacy: "public", + }); + await h.press("chat_defaults_set_privacy_giveaway_clear"); + expect(chatDb.getChatGameSettings(99)).toMatchObject({ + coinflip_default_privacy: null, + giveaway_default_privacy: null, + }); + expect(h.answers).toEqual([ + undefined, + undefined, + "Privacy setting updated", + "Privacy setting updated", + "Privacy setting reset", + "Privacy setting reset", + ]); + }); + test("without a usable actor the group command leaves settings intact", async () => { const h = setup(); h.tokenManager.setChatDefaultToken(99, "mint", "AAA", "1"); From 867bde323271ef538f5b21350c5d7394e33f71db Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 22:19:05 -0300 Subject: [PATCH 245/410] test(history): retain pending transactions until final status --- tests/transaction-history.paths.test.ts | 27 +++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/tests/transaction-history.paths.test.ts b/tests/transaction-history.paths.test.ts index ec88709d..54dc4a7a 100644 --- a/tests/transaction-history.paths.test.ts +++ b/tests/transaction-history.paths.test.ts @@ -338,6 +338,33 @@ describe("TransactionHistory error handling", () => { }); describe("formatTransactionForDisplay icons and links", () => { + test("keeps an omitted status pending until confirmed failed, and only then permits expiry", () => { + const firstSeen = 1_800_000_000_000; + let now = firstSeen; + const clock = spyOn(Date, "now").mockImplementation(() => now); + try { + const db = TransactionHistory.getInstance(); + const signature = "unsigned-tx-fixture"; + db.addTransaction(createTransactionRecord("user-f", "SWAP", signature, "SOL", "TOK", "0.25")); + const pending = db.getUserHistory("user-f")[0]; + expect(pending).toMatchObject({ signature, status: "PENDING", timestamp: firstSeen }); + if (!pending) throw new Error("Pending transaction is missing"); + expect(formatTransactionForDisplay(pending).split("\n")[0]).toBe("⏳🔀 0.25 SOL"); + + now += 91 * 86_400_000; + expect(db.cleanOldTransactions()).toBe(0); + db.updateTransactionStatus(signature, "FAILED", 0); + const failed = db.getUserHistory("user-f")[0]; + expect(failed).toMatchObject({ signature, status: "FAILED", block_height: 0 }); + if (!failed) throw new Error("Failed transaction is missing"); + expect(formatTransactionForDisplay(failed).split("\n")[0]).toBe("❌🔀 0.25 SOL"); + expect(db.cleanOldTransactions()).toBe(1); + expect(db.getUserHistory("user-f")).toEqual([]); + } finally { + clock.mockRestore(); + } + }); + test.each([ ["FAILED", undefined, "TOK", "❌🟢 1 SOL"], ["PENDING", "7", "", "⏳🟢 1 SOL"], From 68b87b248da5630e1386f7a29021b6ec31ef77a8 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 22:23:31 -0300 Subject: [PATCH 246/410] test(commands): pin creation receipts and rate-limit notices --- tests/game-commands.module.test.ts | 99 +++++++++++++++++++++++++++++- 1 file changed, 97 insertions(+), 2 deletions(-) diff --git a/tests/game-commands.module.test.ts b/tests/game-commands.module.test.ts index 0cf4fc4a..15d7e605 100644 --- a/tests/game-commands.module.test.ts +++ b/tests/game-commands.module.test.ts @@ -92,6 +92,44 @@ afterEach(() => { }); describe("createGameViaCommand validation", () => { + test.each([ + ["no receipt", undefined, undefined], + ["no chat", { message_id: 501 }, undefined], + ["no chat id", { chat: {}, message_id: 501 }, undefined], + ["no message id", { chat: { id: -100 } }, undefined], + ["complete receipt", { chat: { id: -100 }, message_id: 501 }, 501], + ] as const)( + "only attaches and deletes a complete creation receipt with %s", + async (_label, receipt, id) => { + const { module, gameManager } = setup(); + const { ctx } = makeCtx(); + ctx.reply = mock(async () => receipt); + ctx.from = { id: 1, first_name: "" }; + + await module.createGameViaCommand( + ctx, + ["/cf", "5", "TKN"], + 1n, + module.COINFLIP_COMMAND_OPTIONS, + ); + + const creation = gameManager.createGame.mock.calls[0] as unknown[] | undefined; + expect(creation?.[6]).toMatchObject({ creationMessageId: id, replyToMessageId: 10 }); + expect(creation?.[8]).toBe(1_700_000_000_000); + const card = gameManager.createGameMessage.mock.calls[0] as unknown[] | undefined; + expect(card?.slice(1, 7)).toEqual([ + "GAME", + "Coinflip", + 5_000_000, + "Unknown", + "TKN", + "Active", + ]); + expect(ctx.api.deleteMessage.mock.calls).toEqual(id === undefined ? [] : [[-100, id]]); + expect(errorSpy).not.toHaveBeenCalled(); + }, + ); + test("rejects an amount below the token policy minimum", async () => { const { module, gameManager } = setup({ deps: { parseAmount: async () => parsedAmount({ amount: 999_999 }) }, @@ -171,6 +209,43 @@ describe("createGameViaCommand validation", () => { expect(gameManager.createGameMessage).not.toHaveBeenCalled(); }); + test("limits creation notices per sender until the exact next minute", async () => { + const { module } = setup({ + gameManager: { + createGame: mock(async () => ({ + success: false, + error: "Game creation rate limit reached", + })), + }, + }); + let now = 0; + const clock = spyOn(Date, "now").mockImplementation(() => now); + const notice = "❌ Too many games are being created. Please try again shortly."; + const attempt = async (sender: number) => { + const { ctx, replies } = makeCtx(); + ctx.from = { id: sender, first_name: "Sender" }; + await module.createGameViaCommand( + ctx, + ["/cf", "5"], + BigInt(sender), + module.COINFLIP_COMMAND_OPTIONS, + ); + return replies; + }; + try { + expect(await attempt(1)).toEqual(["⏳ Creating game…", notice]); + expect(await attempt(1)).toEqual(["⏳ Creating game…"]); + expect(await attempt(2)).toEqual(["⏳ Creating game…", notice]); + now = 59_999; + expect(await attempt(1)).toEqual(["⏳ Creating game…"]); + now = 60_000; + expect(await attempt(1)).toEqual(["⏳ Creating game…", notice]); + expect(await attempt(1)).toEqual(["⏳ Creating game…"]); + } finally { + clock.mockRestore(); + } + }); + test("rejects a token amount above the wallet balance", async () => { const { module, gameManager, deps } = setup({ wallet: { getTokenBalance: mock(async () => 4_999_999) }, @@ -472,6 +547,25 @@ describe("handleGiveawayCommand", () => { expect(deps.startInteractiveGameSetup).toHaveBeenCalledWith(ctx, 1n, copy.giveaway, undefined); }); + test.each([undefined, { message_id: 10, photo: [] }])( + "opens the giveaway menu when the context has no command text", + async (message) => { + const { module, deps, gameManager } = setup(); + const { ctx } = makeCtx(); + ctx.message = message; + + await module.handleGiveawayCommand(ctx); + + expect(deps.startInteractiveGameSetup).toHaveBeenCalledWith( + ctx, + 1n, + copy.giveaway, + undefined, + ); + expect(gameManager.createGame).not.toHaveBeenCalled(); + }, + ); + test("opens the menu with a resolved token override", async () => { const override = { tokenMint: TOKEN, tokenTicker: "TKN", tokenDecimals: 6 }; const { module, deps } = setup({ @@ -498,14 +592,15 @@ describe("handleGiveawayCommand", () => { }); test("creates a giveaway from arguments", async () => { - const { module, gameManager } = setup(); - const { ctx } = makeCtx("/ga 5 TKN"); + const { module, gameManager, deps } = setup(); + const { ctx } = makeCtx(" \t/ga \t5 TKN \n"); await module.handleGiveawayCommand(ctx); const call = gameManager.createGame.mock.calls[0] as any[]; expect(call[0]).toBe("giveaway"); expect(call[3]).toBe(1); + expect(deps.parseAmount).toHaveBeenCalledWith(["/ga", "5", "TKN"], 1, -100); }); test("apologises when setup throws", async () => { From fad1dd24dd2c31d2bed1f714ba3ba672730c8213 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 22:24:27 -0300 Subject: [PATCH 247/410] test(commands): keep only durable recovery acknowledgements --- tests/game-commands.module.test.ts | 36 ++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) diff --git a/tests/game-commands.module.test.ts b/tests/game-commands.module.test.ts index 15d7e605..d84f1b6e 100644 --- a/tests/game-commands.module.test.ts +++ b/tests/game-commands.module.test.ts @@ -429,6 +429,42 @@ describe("createGameViaCommand outcomes", () => { expect(replies).toEqual(["⏳ Creating game…"]); }); + test.each([ + ["owned receipt", true, true, true], + ["unowned receipt", false, true, true], + ["missing recovery hook", true, false, true], + ["missing chat", false, true, false], + ] as const)( + "recovers a confirmed game and keeps only durable receipts for %s", + async (_case, owned, hasHook, hasChat) => { + const ownsReceipt = mock((_game: string, _chat: number, _msg: number) => owned); + const recover = mock(async (_context: unknown, _game: string) => {}); + const { module, gameManager } = setup({ + gameManager: { + createGame: mock(async () => ({ + success: false, + confirmedSignature: "SIG", + gameAddress: "GAME", + })), + ownsPendingCreationMessage: ownsReceipt, + recoverPendingGameCreationByAddress: hasHook ? recover : undefined, + }, + }); + const { ctx, replies, deleted } = makeCtx(); + if (!hasChat) delete ctx.chat; + + await module.createGameViaCommand(ctx, ["/cf", "5"], 1n, module.COINFLIP_COMMAND_OPTIONS); + + expect(ownsReceipt.mock.calls).toEqual([["GAME", -100, 501]]); + expect(recover.mock.calls).toEqual(hasHook && hasChat ? [[ctx, "GAME"]] : []); + expect(deleted).toEqual(owned ? [] : [501]); + expect(replies).toEqual(["⏳ Creating game…"]); + expect(gameManager.clearPendingGameCreation).not.toHaveBeenCalled(); + expect(gameManager.createGameMessage).not.toHaveBeenCalled(); + expect(errorSpy).not.toHaveBeenCalled(); + }, + ); + test("reports an unexpected error with the command's error message", async () => { const { module } = setup({ deps: { From 01cb632739efa5b6b3cd62ca1deb9a77513cfc00 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 22:26:55 -0300 Subject: [PATCH 248/410] test(alerts): check pool discovery and queued replacement --- .../buy-alerts.pool-trades-edge-cases.test.ts | 36 +++++++++++++++++++ 1 file changed, 36 insertions(+) diff --git a/tests/buy-alerts.pool-trades-edge-cases.test.ts b/tests/buy-alerts.pool-trades-edge-cases.test.ts index 75b6aedb..d1e62f2f 100644 --- a/tests/buy-alerts.pool-trades-edge-cases.test.ts +++ b/tests/buy-alerts.pool-trades-edge-cases.test.ts @@ -136,6 +136,42 @@ describe("pool trade poller", () => { now: () => 0, }; + test("skips absent pools, folds duplicate addresses, and removes obsolete work from the next cycle", async () => { + const start = Date.parse("2026-09-03T20:00:00Z"); + let pools: PairStats[] = [{ ...pool(""), pairAddress: null }, pool(" ")]; + const requested: string[] = []; + const observed: Array<[string, string | null | undefined]> = []; + const poller = track( + createPoolTradePoller({ + ...base, + now: () => start, + poolsPerCycle: 1, + fetchPoolStats: async () => pools, + fetchTrades: async (pair) => { + requested.push(pair); + return { data: [trade(`${pair}-after`, start + 1), trade(`${pair}-before`, start - 1)] }; + }, + }), + ); + poller.onTrade((event) => observed.push([event.signature, event.dexId])); + poller.setMints([mint]); + await poller.pollNow(); + expect(requested).toEqual([]); + + pools = [pool(" pair-a "), { ...pool("pair-a"), dexId: "meteora" }, pool("pair-b")]; + await poller.pollNow(); + + pools = [pool("pair-b"), pool("pair-c")]; + await poller.pollNow(); + await poller.pollNow(); + expect(requested).toEqual(["pair-a", "pair-b", "pair-c"]); + expect(observed).toEqual([ + ["pair-a-after", "raydium"], + ["pair-b-after", "raydium"], + ["pair-c-after", "raydium"], + ]); + }); + test.each([ ["removed", false], ["re-added", true], From 639f4560823baea8f1432a21ff30b7d66aa4d5f1 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 22:30:36 -0300 Subject: [PATCH 249/410] test(alerts): isolate equivalent empty discovery mutations --- src/services/buy-alerts/pool-trades.ts | 2 ++ .../buy-alerts.pool-trades-edge-cases.test.ts | 30 +++++++++++++++++++ 2 files changed, 32 insertions(+) diff --git a/src/services/buy-alerts/pool-trades.ts b/src/services/buy-alerts/pool-trades.ts index 53f8c242..d7c44a26 100644 --- a/src/services/buy-alerts/pool-trades.ts +++ b/src/services/buy-alerts/pool-trades.ts @@ -366,6 +366,7 @@ export function createPoolTradePoller(options: PoolTradePollerOptions = {}): Poo pools = await fetchPoolStats(mint); } catch (error) { reportError(error); + // Stryker disable next-line ArrayDeclaration: The injected string has no pair address and the queue discards it. return []; } if (!stillWatching(mint, watch)) return []; @@ -378,6 +379,7 @@ export function createPoolTradePoller(options: PoolTradePollerOptions = {}): Poo } const poolsToPoll = Array.from(uniquePools.values()); if (poolsToPoll.length === 0) { + // Stryker disable next-line ArrayDeclaration: The injected string has no pair address and the queue discards it. return []; } diff --git a/tests/buy-alerts.pool-trades-edge-cases.test.ts b/tests/buy-alerts.pool-trades-edge-cases.test.ts index d1e62f2f..96e931f8 100644 --- a/tests/buy-alerts.pool-trades-edge-cases.test.ts +++ b/tests/buy-alerts.pool-trades-edge-cases.test.ts @@ -172,6 +172,36 @@ describe("pool trade poller", () => { ]); }); + test("reports a discovery error without fetching trades and retries on the next poll", async () => { + const failure = new Error("pool index unavailable"); + let unavailable = true; + const errors: unknown[] = []; + const requests: string[] = []; + const poller = track( + createPoolTradePoller({ + ...base, + onError: (error) => errors.push(error), + fetchPoolStats: async () => { + if (unavailable) throw failure; + return [pool("recovered")]; + }, + fetchTrades: async (pair) => { + requests.push(pair); + return { data: [] }; + }, + }), + ); + poller.setMints([mint]); + await poller.pollNow(); + expect(errors).toEqual([failure, failure]); + expect(requests).toEqual([]); + + unavailable = false; + await poller.pollNow(); + expect(errors).toEqual([failure, failure]); + expect(requests).toEqual(["recovered"]); + }); + test.each([ ["removed", false], ["re-added", true], From 15cb6b6396cbf6fdf7258993ae69d68bf3b76260 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 22:32:46 -0300 Subject: [PATCH 250/410] test(format): preserve compact scientific mantissa digits --- tests/format-amount.test.ts | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/tests/format-amount.test.ts b/tests/format-amount.test.ts index b8e93d29..b697c160 100644 --- a/tests/format-amount.test.ts +++ b/tests/format-amount.test.ts @@ -270,6 +270,14 @@ test("formatCompactTokenDisplay scales to large suffixes", () => { expect(formatCompactTokenDisplay(1_000_000_000_000_000)).toBe("1P"); }); +test.each<[string | number, string]>([ + [1.02e40, "1.02e+22E"], + [-1.02e40, "-1.02e+22E"], + [" 1.02e+40 ", "1.02e+22E"], +])("formatCompactTokenDisplay keeps the exponent mantissa for %p", (value, expected) => { + expect(formatCompactTokenDisplay(value)).toBe(expected); +}); + test.each<[number | string, string]>([ [999, "999"], [1_000, "1k"], From 575d460c6ae0a569361e33b144a79aba16380edf Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 22:38:58 -0300 Subject: [PATCH 251/410] test(evm): name each invalid withdrawal fixture --- src/evm/service.test.ts | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/evm/service.test.ts b/src/evm/service.test.ts index 7cd41677..18be78fc 100644 --- a/src/evm/service.test.ts +++ b/src/evm/service.test.ts @@ -436,10 +436,10 @@ describe("EvmBotService.step for new actions", () => { }); test.each([ - { amount: "1", recipient: token }, - { recipient: token, native: true }, - { amount: "1", native: true }, - ])("refuses a withdrawal missing a required field: %p", async (body) => { + ["asset", { amount: "1", recipient: token }], + ["amount", { recipient: token, native: true }], + ["recipient", { amount: "1", native: true }], + ] as const)("refuses a withdrawal without its %s", async (_field, body) => { const invalid = addAction({ kind: "withdraw", body: json(body) }); await expect(service.step(invalid)).rejects.toThrow("Invalid withdrawal"); expect(stored(invalid.id)).toMatchObject({ phase: "new", raw: null, hash: null }); From d3be920aa65b923b8f7baf9787bc6c9bddbd853f Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 22:45:22 -0300 Subject: [PATCH 252/410] test(evm): pin whole config fields and RPC order --- src/evm/config.test.ts | 49 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 src/evm/config.test.ts diff --git a/src/evm/config.test.ts b/src/evm/config.test.ts new file mode 100644 index 00000000..d882aae0 --- /dev/null +++ b/src/evm/config.test.ts @@ -0,0 +1,49 @@ +import { expect, test } from "bun:test"; +import { mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { evmBotConfigSchema, loadEvmBotConfig } from "./config"; + +const address: `0x${string}` = `0x${"12".repeat(20)}`; +const valid = { + chainId: 8453, + address, + version: "0.1.0" as const, + name: "Base Mainnet", + rpcUrls: ["https://first-rpc.example.invalid"], + oracleUrl: "https://oracle.example.invalid", + oracleTokenFile: "clé-oracle.txt", + database: "tést.sqlite", + webUrl: "https://bot.example.invalid", +}; + +test.each([ + ["address prefix", { address: `x${address}` }, "address"], + ["address suffix", { address: `${address}x` }, "address"], + ["name prefix", { name: "@Base Mainnet" }, "name"], + ["name suffix", { name: "Base Mainnet@" }, "name"], + ["41-character name", { name: "A".repeat(41) }, "name"], + ["empty RPC list", { rpcUrls: [] }, "rpcUrls"], +] as const)("rejects invalid config for %s", (_case, invalid, field) => { + const result = evmBotConfigSchema.safeParse({ ...valid, ...invalid }); + expect(result).toMatchObject({ + success: false, + error: { issues: [expect.objectContaining({ path: [field] })] }, + }); +}); + +test("loads multiple RPC endpoints and UTF-8 paths without changing their order", () => { + const dir = mkdtempSync(join(tmpdir(), "evm-config-test-")); + try { + const file = join(dir, "config.json"); + const config = { + ...valid, + name: "N".repeat(40), + rpcUrls: [...valid.rpcUrls, "https://fallback-rpc.example.invalid"], + }; + writeFileSync(file, JSON.stringify(config), "utf8"); + expect(loadEvmBotConfig(file)).toEqual({ ...config, confirmations: 2 }); + } finally { + rmSync(dir, { recursive: true, force: true }); + } +}); From 7d0a1bcdd2e41107798716020478ff8c0b388356 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 22:45:22 -0300 Subject: [PATCH 253/410] test(evm): pin safe wallet identity boundaries --- src/evm/evm.test.ts | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/src/evm/evm.test.ts b/src/evm/evm.test.ts index 98e359cd..a3fc06b6 100644 --- a/src/evm/evm.test.ts +++ b/src/evm/evm.test.ts @@ -1,4 +1,5 @@ import { expect, test } from "bun:test"; +import { mnemonicToAccount } from "viem/accounts"; import { evmAccount } from "./wallet"; import { EvmBotStore } from "./store"; import { gameCallback, callbackGame } from "./bot"; @@ -10,6 +11,22 @@ test("EVM wallet derivation is stable and separated by Telegram identity", () => for (const id of ["0", "-1", "1.0", "01", ""]) expect(() => evmAccount(mnemonic, id)).toThrow(); }); +test.each(["101suffix", "901e2", " 101 ", "9007199254740992"])( + "rejects the entire invalid EVM wallet identity %s before deriving it", + (id) => { + expect(() => evmAccount(mnemonic, id)).toThrow("Invalid Telegram wallet identity"); + }, +); + +test("derives the last safe wallet identity on the same path as the confirmed wallet fixture", () => { + const id = "9007199254740991"; + const normal = mnemonicToAccount(mnemonic, { passphrase: id }); + expect(evmAccount(mnemonic, id).address).toBe(normal.address); + expect(evmAccount(mnemonic, id).address).not.toBe( + evmAccount(mnemonic, "9007199254740990").address, + ); +}); + test("game callbacks fit Telegram's 64 byte limit and round trip full bytes32 IDs", () => { const game = `0x${"fe".repeat(32)}` as const; const callback = gameCallback("j", game); From 4438bf72e5a0466a164cf656533d7c43f6602ed1 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 22:45:22 -0300 Subject: [PATCH 254/410] test(evm): accept complete multi-digit setup callbacks --- src/evm/setup.test.ts | 36 ++++++++++++++++++++++++++++++++---- 1 file changed, 32 insertions(+), 4 deletions(-) diff --git a/src/evm/setup.test.ts b/src/evm/setup.test.ts index 304a87c3..bbb9d53b 100644 --- a/src/evm/setup.test.ts +++ b/src/evm/setup.test.ts @@ -97,9 +97,10 @@ function fixture() { expect(button).toBeDefined(); return button.callback_data as string; }, - open: () => - bot.handleUpdate({ - update_id: 1, + open: (openingUpdateId = 1) => { + updateId = Math.max(updateId, openingUpdateId); + return bot.handleUpdate({ + update_id: openingUpdateId, message: { message_id: 1, date: 1, @@ -108,7 +109,8 @@ function fixture() { text: "/cf", entities: [{ type: "bot_command", offset: 0, length: 3 }], }, - }), + }); + }, click: (data: string) => bot.handleUpdate({ update_id: ++updateId, @@ -141,6 +143,32 @@ function fixture() { }; } +test("requires a complete callback and supports multi-digit setup IDs and generations", async () => { + const f = fixture(); + await f.open(12_345); + await f.click(f.button(() => true)); + await f.click(f.button((text) => text.includes("2"))); + await f.click(f.button((text) => text === "24h")); + for (let edits = 0; edits < 6; edits += 1) { + await f.click(f.button((text) => text === "🌐 Public" || text === "🔒 Private")); + } + const create = f.button((text) => text.includes("Create")); + expect(create).toMatch(/^evs:12345:10:\d+$/); + const answers = f.answers.length; + await f.click(`x${create}`); + await f.click(`${create}x`); + expect(f.answers).toHaveLength(answers); + expect(f.submitted).toEqual([]); + + await f.click(create); + expect(f.submitted).toHaveLength(1); + expect(f.submitted[0]).toMatchObject({ + id: "12345", + timeoutSeconds: 86_400, + isPrivate: false, + }); +}); + test("failed edits preserve visible buttons across restart and retire them after delivery", async () => { const f = fixture(); await f.open(); From c62e752f7d36b3c5884e8047ac308f1ba5b56a62 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 22:45:22 -0300 Subject: [PATCH 255/410] test(evm): keep a confirmed join finished with a stale close flag --- src/evm/service.test.ts | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/src/evm/service.test.ts b/src/evm/service.test.ts index 18be78fc..914f0b98 100644 --- a/src/evm/service.test.ts +++ b/src/evm/service.test.ts @@ -631,6 +631,16 @@ describe("EvmBotService.step for submitted transactions", () => { expect(sent).toEqual([]); }); + test("a confirmed join stays finished even if its saved body has a close flag", async () => { + receipt = { status: "success", blockNumber: 90n }; + const join = submitted({ kind: "join", body: json({ game: gameId, refundingPlayer: true }) }); + + await service.step(join); + + expect(stored(join.id)).toMatchObject({ phase: "done", raw, hash }); + expect(sent).toEqual([]); + }); + test("confirmed creations finish and record the game message", async () => { receipt = { status: "success", blockNumber: 90n }; const created = submitted({ kind: "create", body: json({ game: gameId }) }); From ae73e63ad20c7edf5fccb8e8230b1f7bf64c440c Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 22:47:34 -0300 Subject: [PATCH 256/410] test(evm): isolate setup buttons and update replays --- src/evm/setup.test.ts | 66 +++++++++++++++++++++++++++++++++++++++---- 1 file changed, 61 insertions(+), 5 deletions(-) diff --git a/src/evm/setup.test.ts b/src/evm/setup.test.ts index bbb9d53b..cce62551 100644 --- a/src/evm/setup.test.ts +++ b/src/evm/setup.test.ts @@ -9,7 +9,7 @@ afterEach(() => { for (const store of stores.splice(0)) store.db.close(); }); -function fixture() { +function fixture(group = false) { const store = new EvmBotStore(":memory:", "setup-test"); stores.push(store); const submitted: Setup[] = []; @@ -17,9 +17,12 @@ function fixture() { let visible: any; const answers: string[] = []; let sends = 0; + let edits = 0; const sent: string[] = []; let updateId = 1; - const chat = { id: 1, type: "private" as const, first_name: "Test" }; + const chat = group + ? { id: -10001, type: "supergroup" as const, title: "Setup Test Group" } + : { id: 1, type: "private" as const, first_name: "Test" }; const from = { id: 1, is_bot: false, first_name: "Test" }; function createBot() { const bot = new Bot("123:test", { @@ -35,6 +38,7 @@ function fixture() { }); bot.api.config.use(async (_previous, method, payload) => { if (method === "editMessageText") { + edits++; if (mode === "fail") throw new Error("Telegram unavailable"); if (JSON.stringify(visible) === JSON.stringify(payload)) return { @@ -86,6 +90,7 @@ function fixture() { }, visible: () => visible, sends: () => sends, + edits: () => edits, sent, labels: () => visible.reply_markup?.inline_keyboard.flat().map((b: any) => b.text) ?? [], buttonAt: (index: number) => @@ -111,15 +116,27 @@ function fixture() { }, }); }, - click: (data: string) => + click: ( + data: string, + location: { userId?: number; chatId?: number; messageId?: number; inline?: boolean } = {}, + ) => bot.handleUpdate({ update_id: ++updateId, callback_query: { id: String(updateId), chat_instance: "test", - from, + from: { ...from, id: location.userId ?? from.id }, data, - message: { message_id: 100, date: 1, chat, text: "menu" }, + ...(location.inline + ? { inline_message_id: "inline-setup" } + : { + message: { + message_id: location.messageId ?? 100, + date: 1, + chat: { ...chat, id: location.chatId ?? chat.id }, + text: "menu", + }, + }), }, }), reply: (text: string) => @@ -169,6 +186,45 @@ test("requires a complete callback and supports multi-digit setup IDs and genera }); }); +test.each([ + ["other user", { userId: 2 }], + ["other chat", { chatId: -10002 }], + ["other message", { messageId: 101 }], + ["inline message", { inline: true }], +] as const)("rejects a setup button from an %s", async (_case, location) => { + const f = fixture(true); + await toConfirm(f, "2"); + const create = f.button((text) => text === "✅ Create Game"); + const edits = f.edits(); + + await f.click(create, location); + + expect(f.answers.at(-1)).toBe("This setup is unavailable."); + expect(f.edits()).toBe(edits); + expect(f.submitted).toEqual([]); + await f.click(create); + expect(f.submitted).toHaveLength(1); +}); + +test("opening the same update again only retries outstanding menu delivery", async () => { + const f = fixture(); + await toConfirm(f, "2"); + const create = f.button((text) => text === "✅ Create Game"); + const edits = f.edits(); + const sends = f.sends(); + + await f.open(); + await f.click(create); + f.restart(); + await f.open(); + await f.click(create); + + expect(f.sends()).toBe(sends); + expect(f.edits()).toBe(edits); + expect(f.answers.at(-1)).toBe("This setup is unavailable."); + expect(f.submitted).toHaveLength(1); +}); + test("failed edits preserve visible buttons across restart and retire them after delivery", async () => { const f = fixture(); await f.open(); From 174dd64c36a8d6aa4af503cfa9ba0b806217efee Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 22:49:10 -0300 Subject: [PATCH 257/410] test(evm): isolate equivalent encoding and wallet path literals --- src/evm/config.ts | 1 + src/evm/wallet.ts | 1 + 2 files changed, 2 insertions(+) diff --git a/src/evm/config.ts b/src/evm/config.ts index cf558915..ec5682d9 100644 --- a/src/evm/config.ts +++ b/src/evm/config.ts @@ -19,5 +19,6 @@ export const evmBotConfigSchema = z.strictObject({ }); export type EvmBotConfig = z.output; export function loadEvmBotConfig(file: string) { + // Stryker disable next-line StringLiteral: An empty encoding returns a buffer that JSON.parse also decodes as UTF-8. return evmBotConfigSchema.parse(JSON.parse(readFileSync(file, "utf8"))); } diff --git a/src/evm/wallet.ts b/src/evm/wallet.ts index d4635f07..3583e23b 100644 --- a/src/evm/wallet.ts +++ b/src/evm/wallet.ts @@ -6,5 +6,6 @@ import { mnemonicToAccount } from "viem/accounts"; export function evmAccount(mnemonic: string, telegramId: string) { if (!/^[1-9][0-9]*$/.test(telegramId) || BigInt(telegramId) > BigInt(Number.MAX_SAFE_INTEGER)) throw new Error("Invalid Telegram wallet identity"); + // Stryker disable next-line StringLiteral: An empty path uses Viem's same BIP-44 default. Keep wallet restore independent of that default. return mnemonicToAccount(mnemonic, { passphrase: telegramId, path: "m/44'/60'/0'/0/0" }); } From a62d626208c5900b39464a639996cc02d14c76ec Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 22:51:06 -0300 Subject: [PATCH 258/410] test(evm): pin exact stake presets and force reply --- src/evm/setup.test.ts | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) diff --git a/src/evm/setup.test.ts b/src/evm/setup.test.ts index cce62551..fbc4802a 100644 --- a/src/evm/setup.test.ts +++ b/src/evm/setup.test.ts @@ -19,6 +19,7 @@ function fixture(group = false) { let sends = 0; let edits = 0; const sent: string[] = []; + const sentPayloads: unknown[] = []; let updateId = 1; const chat = group ? { id: -10001, type: "supergroup" as const, title: "Setup Test Group" } @@ -53,6 +54,7 @@ function fixture(group = false) { if (method === "sendMessage") { sends++; sent.push((payload as any).text); + sentPayloads.push(payload); } return { ok: true, @@ -92,6 +94,7 @@ function fixture(group = false) { sends: () => sends, edits: () => edits, sent, + sentPayloads, labels: () => visible.reply_markup?.inline_keyboard.flat().map((b: any) => b.text) ?? [], buttonAt: (index: number) => visible.reply_markup.inline_keyboard.flat()[index].callback_data as string, @@ -401,6 +404,39 @@ test("custom amounts below the token minimum are rejected", async () => { expect(f.labels()).toContain("✏️ Custom Amount"); }); +test("renders stake presets from the exact token minimum in the HTML setup menu", async () => { + const f = fixture(); + await f.open(); + + expect(f.sentPayloads[0]).toMatchObject({ parse_mode: "HTML" }); + expect(f.visible()).toMatchObject({ parse_mode: "HTML" }); + expect(f.labels()).toEqual([ + "0.000000000000000001", + "0.000000000000000002", + "0.000000000000000005", + "0.00000000000000001", + "✏️ Custom Amount", + "❌ Cancel", + ]); +}); + +test("the custom stake prompt uses force reply and accepts the exact minimum", async () => { + const f = fixture(); + await f.open(); + await f.click(f.button((text) => text === "✏️ Custom Amount")); + + expect(f.sentPayloads.at(-1)).toMatchObject({ + text: "Reply with the amount in TEST.", + reply_markup: { force_reply: true }, + }); + await f.reply("0.000000000000000001"); + await f.click(f.button((text) => text === "👥 2")); + await f.click(f.button((text) => text === "✅ Create Game")); + + expect(f.submitted).toHaveLength(1); + expect(f.submitted[0]).toMatchObject({ amount: "0.000000000000000001", players: 2 }); +}); + test("an unknown action index is refused", async () => { const f = fixture(); await f.open(); From 9b660521f8f5a239e73c899c62047093f929a794 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 22:52:06 -0300 Subject: [PATCH 259/410] test(evm): pin USD and game action boundaries --- src/evm/bot.test.ts | 86 ++++++++++++++++++++++++++++++++++++++------- 1 file changed, 73 insertions(+), 13 deletions(-) diff --git a/src/evm/bot.test.ts b/src/evm/bot.test.ts index 98904587..d40ea7b1 100644 --- a/src/evm/bot.test.ts +++ b/src/evm/bot.test.ts @@ -699,11 +699,18 @@ describe("EVM game commands", () => { ); }); - test("USD amounts are refused on EVM tokens", async () => { - useEvm(); - await h.text("/cf $5 TEST"); - expect(h.replies().at(-1)).toContain("USD pricing is unavailable"); - }); + test.each(["/cf $5 TEST", "/cf 5 TEST UsD", "/ga 5 uSd TEST 2"])( + "refuses EVM USD pricing in %s before looking up the balance", + async (command) => { + useEvm(); + await h.text(command); + expect(h.replies()).toEqual([ + "USD pricing is unavailable for this token on this network. Enter the amount in token units.", + ]); + expect(h.readContract).not.toHaveBeenCalled(); + expect(h.store.pending()).toEqual([]); + }, + ); test("insufficient balances stop game creation", async () => { useEvm(); @@ -762,7 +769,8 @@ describe("EVM game commands", () => { }); describe("EVM game buttons", () => { - const openGame = (overrides: Record = {}) => ({ + type Game = Awaited>; + const openGame = (overrides: Partial = {}): Game => ({ creator: h.runtime.service.account("2").address, token: tokenAddress, gameType: 0, @@ -772,13 +780,15 @@ describe("EVM game buttons", () => { totalAmount: 10n, minPlayers: 2, maxPlayers: 2, - expiresAt: 5_000n, + expiresAt: 5_000, + lastEntryBlock: 1, + commitment: gameId, participants: [h.runtime.service.account("2").address], ...overrides, }); test("joining an open game queues a join", async () => { - const game = spyOn(h.runtime.service, "game").mockResolvedValue(openGame() as any); + const game = spyOn(h.runtime.service, "game").mockResolvedValue(openGame()); await h.click(gameCallback("j", gameId), { chat: "group" }); expect(h.answers().at(-1)).toBeUndefined(); expect(h.store.pending()[0]).toMatchObject({ kind: "join", chat: -100 }); @@ -786,9 +796,7 @@ describe("EVM game buttons", () => { }); test("private games require an invitation", async () => { - const game = spyOn(h.runtime.service, "game").mockResolvedValue( - openGame({ isPrivate: true }) as any, - ); + const game = spyOn(h.runtime.service, "game").mockResolvedValue(openGame({ isPrivate: true })); await h.click(gameCallback("j", gameId)); expect(h.answers().at(-1)).toContain("Action unavailable"); @@ -802,7 +810,7 @@ describe("EVM game buttons", () => { }); test("unavailable actions and malformed callbacks are refused", async () => { - const game = spyOn(h.runtime.service, "game").mockResolvedValue(openGame() as any); + const game = spyOn(h.runtime.service, "game").mockResolvedValue(openGame()); await h.click(gameCallback("r", gameId)); expect(h.answers().at(-1)).toContain("Action unavailable"); await h.click(gameCallback("z", gameId)); @@ -817,12 +825,64 @@ describe("EVM game buttons", () => { const creator = h.runtime.service.account("1").address; const player = h.runtime.service.account("3").address; const game = spyOn(h.runtime.service, "game").mockResolvedValue( - openGame({ creator, participants: [player], expiresAt: 0n }) as any, + openGame({ creator, participants: [player], expiresAt: 0 }), ); await h.click(gameCallback("c", gameId)); expect(h.store.pending()[0]).toMatchObject({ kind: "close" }); game.mockRestore(); }); + + test("a timed-out participant queues a refund, not a close", async () => { + const participant = h.runtime.service.account("1").address; + const game = spyOn(h.runtime.service, "game").mockResolvedValue( + openGame({ participants: [participant], expiresAt: 1_000 }), + ); + + await h.click(gameCallback("r", gameId), { chat: "group", message: 91 }); + + expect(h.answers()).toEqual([undefined]); + expect(h.store.pending()).toHaveLength(1); + expect(h.store.pending()[0]).toMatchObject({ kind: "refund", chat: -100, message: 91 }); + expect(JSON.parse(h.store.pending()[0]!.body)).toMatchObject({ game: gameId }); + game.mockRestore(); + }); + + test("coinflip cleanup does not let the creator join or refund someone else's ticket", async () => { + const creator = h.runtime.service.account("1").address; + const player = h.runtime.service.account("3").address; + const game = spyOn(h.runtime.service, "game").mockResolvedValue( + openGame({ creator, participants: [player], expiresAt: 1_000 }), + ); + + await h.click(gameCallback("j", gameId)); + await h.click(gameCallback("r", gameId)); + + expect(h.answers()).toEqual([ + "Action unavailable. Check your wallet, invitation or pending transaction.", + "Action unavailable. Check your wallet, invitation or pending transaction.", + ]); + expect(h.store.pending()).toEqual([]); + game.mockRestore(); + }); + + test.each([ + ["from a non-creator", 2, 1_000, [3]], + ["before the refund buffer", 1, 500, [3, 4]], + ] as const)("refuses a close %s", async (_case, creatorId, expiresAt, playerIds) => { + const creator = h.runtime.service.account(String(creatorId)).address; + const participants = playerIds.map((id) => h.runtime.service.account(String(id)).address); + const game = spyOn(h.runtime.service, "game").mockResolvedValue( + openGame({ creator, participants, expiresAt }), + ); + + await h.click(gameCallback("c", gameId)); + + expect(h.answers()).toEqual([ + "Action unavailable. Check your wallet, invitation or pending transaction.", + ]); + expect(h.store.pending()).toEqual([]); + game.mockRestore(); + }); }); describe("EVM refresh loop", () => { From 75cd2f44d61edea78e14a797084d05f81133a61c Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 22:57:59 -0300 Subject: [PATCH 260/410] test(wallet): bound exact retry and confirmation fixtures --- tests/wallet-mutation-bounds.test.ts | 124 +++++++++++++++++++++++++++ 1 file changed, 124 insertions(+) create mode 100644 tests/wallet-mutation-bounds.test.ts diff --git a/tests/wallet-mutation-bounds.test.ts b/tests/wallet-mutation-bounds.test.ts new file mode 100644 index 00000000..d3110df6 --- /dev/null +++ b/tests/wallet-mutation-bounds.test.ts @@ -0,0 +1,124 @@ +import { afterEach, beforeEach, expect, test } from "bun:test"; +import { + Connection, + Keypair, + PublicKey, + SystemProgram, + TransactionMessage, + VersionedTransaction, +} from "#solana"; +import { WalletManager } from "../src/utils/wallet"; +import { stubInstantTimers, withinTestDeadline } from "./helpers/timers"; + +const mnemonic = + "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about"; +const signature = "bounded-wallet-test-signature"; +let timers: ReturnType; +beforeEach(() => { + timers = stubInstantTimers(); +}); +afterEach(() => timers.restore()); + +const walletWith = (rpc: Partial) => + WalletManager.createForTest(mnemonic, { connection: rpc as Connection }); + +test("serialized send stops after the three production attempts and keeps the latest error", async () => { + const signer = await Keypair.generate(); + const message = new TransactionMessage({ + payerKey: signer.publicKey, + recentBlockhash: PublicKey.default.toBase58(), + instructions: [ + SystemProgram.transfer({ + fromPubkey: signer.publicKey, + toPubkey: PublicKey.default, + lamports: 1, + }), + ], + }).compileToV0Message(); + const wire = Buffer.from(new VersionedTransaction(message).serialize()).toString("base64"); + let sends = 0; + const wallet = walletWith({ + sendTransaction: async () => { + sends++; + if (sends > 3) return signature; + throw new Error(`RPC send failed ${sends}`); + }, + getSignatureStatus: async () => ({ context: { slot: 1n }, value: null }), + }); + + await expect( + withinTestDeadline(wallet.signAndSendSerializedTransaction(wire, signer), "serialized send"), + ).rejects.toThrow("Failed to send transaction: RPC send failed 3"); + expect(sends).toBe(3); + expect(timers.delays).toEqual([1_000, 2_000]); +}); + +test("post-timeout status probing stops after three rate-limited reads", async () => { + let reads = 0; + const wallet = walletWith({ + getTransaction: async () => null, + getSignatureStatus: async () => { + reads++; + if (reads > 3) return { context: { slot: 1n }, value: null }; + throw new Error("429 Too Many Requests"); + }, + }); + + const result = withinTestDeadline( + wallet["probeTransactionAfterTimeout"](signature), + "status probe", + ); + await expect(result).resolves.toBe("missing"); + expect(reads).toBe(3); + expect(timers.delays).toEqual([250, 250]); +}); + +test.each(["confirmed", "finalized"] as const)( + "finishes on the first %s status without polling again", + async (confirmationStatus) => { + let reads = 0; + const wallet = walletWith({ + getSignatureStatuses: async () => { + reads++; + if (reads > 1) throw new Error("Unexpected second status lookup"); + return { + context: { slot: 1n }, + value: [{ slot: 1n, confirmations: 2n, err: null, confirmationStatus }], + }; + }, + }); + + await expect( + withinTestDeadline(wallet.confirmTransaction(signature), "confirmed wallet status"), + ).resolves.toBeUndefined(); + expect(reads).toBe(1); + expect(timers.delays).toEqual([]); + }, +); + +test("waits once before using a confirmed post-timeout history result", async () => { + let reads = 0; + let probes = 0; + const wallet = walletWith({ + getSignatureStatuses: async () => { + reads++; + return { context: { slot: 1n }, value: [null] }; + }, + getTransaction: async () => { + probes++; + return null; + }, + getSignatureStatus: async () => ({ + context: { slot: 1n }, + value: { slot: 1n, confirmations: 2n, err: null, confirmationStatus: "confirmed" }, + }), + }); + Object.defineProperty(wallet, "confirmationTimeoutMs", { value: 0 }); + + await expect( + withinTestDeadline(wallet.confirmTransaction(signature), "post-timeout backoff"), + ).resolves.toBeUndefined(); + expect(reads).toBe(1); + expect(probes).toBe(1); + expect(timers.delays).toEqual([2_000]); +}); From 2ca368a79345600d23d39890f322bf18c4529b13 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 23:01:28 -0300 Subject: [PATCH 261/410] fix(wallet): retain bigint confirmation counts in logs --- src/utils/wallet.ts | 12 ++++---- tests/wallet-mutation-bounds.test.ts | 43 +++++++++++++++++++++++++++- 2 files changed, 49 insertions(+), 6 deletions(-) diff --git a/src/utils/wallet.ts b/src/utils/wallet.ts index 2c8e833d..69aa302a 100644 --- a/src/utils/wallet.ts +++ b/src/utils/wallet.ts @@ -327,6 +327,10 @@ type MetadataLoader = { // UTILITY FUNCTIONS // ================================ +function statusConfirmationCount(value: unknown): number | bigint | null { + return typeof value === "bigint" || typeof value === "number" ? value : null; +} + const retryWithBackoff = async ( operation: () => Promise, maxRetries: number = MAX_RETRIES, @@ -2314,7 +2318,7 @@ export class WalletManager { let pollCount = 0; let lastStatusLabel: "no-result" | null = null; let lastConfirmationStatus: string | null = null; - let lastConfirmations: number | null = null; + let lastConfirmations: number | bigint | null = null; let historySearchEnabled = false; let historyEnabledAt: number | null = null; let firstStatusObservedAt: number | null = null; @@ -2470,8 +2474,7 @@ export class WalletManager { if (status) { const currentStatus = status.confirmationStatus || "unknown"; - const currentConfirmations = - typeof status.confirmations === "number" ? status.confirmations : null; + const currentConfirmations = statusConfirmationCount(status.confirmations); if ( currentStatus !== lastConfirmationStatus || @@ -2547,8 +2550,7 @@ export class WalletManager { } const finalStatusLabel = finalStatus.confirmationStatus || "unknown"; - const finalConfirmations = - typeof finalStatus.confirmations === "number" ? finalStatus.confirmations : null; + const finalConfirmations = statusConfirmationCount(finalStatus.confirmations); if (finalStatusLabel === "confirmed" || finalStatusLabel === "finalized") { console.log( diff --git a/tests/wallet-mutation-bounds.test.ts b/tests/wallet-mutation-bounds.test.ts index d3110df6..577dc9ee 100644 --- a/tests/wallet-mutation-bounds.test.ts +++ b/tests/wallet-mutation-bounds.test.ts @@ -1,4 +1,4 @@ -import { afterEach, beforeEach, expect, test } from "bun:test"; +import { afterEach, beforeEach, expect, spyOn, test } from "bun:test"; import { Connection, Keypair, @@ -9,6 +9,7 @@ import { } from "#solana"; import { WalletManager } from "../src/utils/wallet"; import { stubInstantTimers, withinTestDeadline } from "./helpers/timers"; +import { useWalletConfirmationClock } from "./helpers/wallet-confirmation-clock"; const mnemonic = "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about"; @@ -122,3 +123,43 @@ test("waits once before using a confirmed post-timeout history result", async () expect(probes).toBe(1); expect(timers.delays).toEqual([2_000]); }); + +test("reports bigint confirmation counts while polling and on the final status check", async () => { + const pendingCounts = [0n, 2n, 3n]; + const wallet = walletWith({ + getSignatureStatuses: async () => { + const confirmations = pendingCounts.shift(); + if (confirmations === undefined) throw new Error("Unexpected fourth status lookup"); + return { + context: { slot: 1n }, + value: [{ slot: 1n, confirmations, err: null, confirmationStatus: "processed" }], + }; + }, + getTransaction: async () => null, + getSignatureStatus: async () => ({ + context: { slot: 1n }, + value: { slot: 1n, confirmations: null, err: null, confirmationStatus: "finalized" }, + }), + }); + Object.defineProperty(wallet, "confirmationTimeoutMs", { value: 800 }); + const clock = useWalletConfirmationClock(wallet); + const log = spyOn(console, "log").mockImplementation(() => {}); + const error = spyOn(console, "error").mockImplementation(() => {}); + try { + await expect( + withinTestDeadline(wallet.confirmTransaction(signature), "polling confirmation diagnostics"), + ).resolves.toBeUndefined(); + expect(pendingCounts).toEqual([]); + expect( + log.mock.calls.map(([line]) => String(line)).filter((line) => line.startsWith("📊")), + ).toEqual([ + `📊 Transaction ${signature} status update (poll 1, 0ms): processed (0 confirmations)`, + `📊 Transaction ${signature} status update (poll 2, 400ms): processed (2 confirmations)`, + `📊 Final status for ${signature}: processed (3 confirmations) (polls=2, history=not-used, firstStatus=0ms, networkRetries=0)`, + ]); + } finally { + error.mockRestore(); + log.mockRestore(); + clock.restore(); + } +}); From 6c42d9f44d2c58d482b48c00919603eef4f58b14 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 23:02:56 -0300 Subject: [PATCH 262/410] test(evm): verify refresh and notification boundaries --- src/evm/bot.test.ts | 83 +++++++++++++++++++++++++++++++++++++++++---- 1 file changed, 76 insertions(+), 7 deletions(-) diff --git a/src/evm/bot.test.ts b/src/evm/bot.test.ts index d40ea7b1..a0b7634d 100644 --- a/src/evm/bot.test.ts +++ b/src/evm/bot.test.ts @@ -5,6 +5,7 @@ import { tmpdir } from "node:os"; import { join } from "node:path"; import type { Address, Hex } from "viem"; import { registerEvmBot, gameCallback } from "./bot"; +import type { EvmAction } from "./store"; const address = `0x${"11".repeat(20)}` as Address; const tokenAddress = `0x${"22".repeat(20)}` as Address; @@ -907,7 +908,7 @@ describe("EVM refresh loop", () => { expect((step.mock.calls[0] as any[])[0].id).toBe("timer"); }); - const addAction = (overrides: Record) => + const addAction = (overrides: Partial) => h.store.add({ id: crypto.randomUUID(), user: "1", @@ -919,7 +920,7 @@ describe("EVM refresh loop", () => { raw: null, hash: null, ...overrides, - } as any); + }); test("stale unsigned actions fail and every outcome is announced once", async () => { const step = spyOn(h.runtime.service, "step").mockRejectedValue(new Error("rpc")); @@ -928,19 +929,73 @@ describe("EVM refresh loop", () => { addAction({ id: "create", user: "3", kind: "create", phase: "failed" }); addAction({ id: "withdraw-done", user: "4", kind: "withdraw", phase: "done", hash: "0xab" }); addAction({ id: "withdraw-failed", user: "5", kind: "withdraw", phase: "failed" }); + addAction({ id: "join-done", user: "6", kind: "join", phase: "done" }); + addAction({ id: "create-done", user: "7", kind: "create", phase: "done" }); await h.runtime.refresh(); expect(h.store.action("old")!.phase).toBe("failed"); expect(h.store.action("fresh")!.phase).toBe("new"); const edits = h.calls.filter((c) => c.method === "editMessageText").map((c) => c.payload.text); - expect(edits).toContain("Game creation failed. Check your Anvil wallet balance."); - expect(edits).toContain("Withdrawal confirmed on Anvil. Transaction: 0xab"); - expect(edits).toContain("Withdrawal failed. Check your token and ETH balances."); - expect(h.replies()).toContain( + expect(edits.sort()).toEqual([ + "Game creation failed. Check your Anvil wallet balance.", + "Withdrawal confirmed on Anvil. Transaction: 0xab", + "Withdrawal failed. Check your token and ETH balances.", + ]); + expect(h.replies()).toEqual([ "Your Anvil join could not complete. Use /balance to check your wallet and try the game button again.", - ); + ]); expect(h.store.unnotified()).toHaveLength(0); + const telegramCalls = h.calls.length; + await h.runtime.refresh(); + expect(h.calls).toHaveLength(telegramCalls); + step.mockRestore(); + }); + + test("failed unsigned actions expire only after two minutes and signed actions stay pending", async () => { + const now = 1_700_000_000_000; + const clock = spyOn(Date, "now").mockReturnValue(now); + const step = spyOn(h.runtime.service, "step").mockRejectedValue(new Error("RPC offline")); + try { + addAction({ id: "known-boundary", body: JSON.stringify({ createdAt: now - 120_000 }) }); + addAction({ id: "expired", user: "2", body: JSON.stringify({ createdAt: now - 120_001 }) }); + addAction({ + id: "signed", + user: "3", + body: JSON.stringify({ createdAt: now - 120_001 }), + phase: "transaction", + raw: "0x12", + hash: "0x34", + }); + + await h.runtime.refresh(); + + expect(h.store.action("known-boundary")).toMatchObject({ phase: "new" }); + expect(h.store.action("expired")).toMatchObject({ phase: "failed" }); + expect(h.store.action("signed")).toMatchObject({ + phase: "transaction", + raw: "0x12", + hash: "0x34", + }); + } finally { + step.mockRestore(); + clock.mockRestore(); + } + }); + + test("does not run another refresh while one is in flight or after stop", async () => { + addAction({ id: "in-flight" }); + const rpc = Promise.withResolvers(); + const step = spyOn(h.runtime.service, "step").mockReturnValue(rpc.promise); + const first = h.runtime.refresh(); + const duplicate = h.runtime.refresh(); + rpc.resolve(); + await Promise.all([first, duplicate]); + + expect(step).toHaveBeenCalledTimes(1); + h.runtime.stop(); + await h.runtime.refresh(); + expect(step).toHaveBeenCalledTimes(1); step.mockRestore(); }); @@ -958,10 +1013,24 @@ describe("EVM refresh loop", () => { expect(h.store.unnotified()).toHaveLength(0); addAction({ id: "transient", user: "2", phase: "failed" }); + h.failApi( + new GrammyError( + "Rate limited", + { ok: false, error_code: 429, description: "Too Many Requests" }, + "sendMessage", + {}, + ), + ); + await h.runtime.refresh(); + expect(h.store.unnotified().map((row) => row.id)).toEqual(["transient"]); h.failApi(new Error("network")); await h.runtime.refresh(); expect(h.store.unnotified().map((row) => row.id)).toEqual(["transient"]); h.failApi(undefined); + const retryCount = h.replies().length; + await h.runtime.refresh(); + expect(h.replies()).toHaveLength(retryCount + 1); + expect(h.store.unnotified()).toHaveLength(0); }); test("game messages are rendered, deferred when unchanged and show winners", async () => { From b0e2bbe10d47ded3d1526ca16cae661c4cbdf7f4 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 23:04:35 -0300 Subject: [PATCH 263/410] test(evm): check setup edit errors and inert controls --- src/evm/setup.test.ts | 41 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) diff --git a/src/evm/setup.test.ts b/src/evm/setup.test.ts index fbc4802a..288de5c6 100644 --- a/src/evm/setup.test.ts +++ b/src/evm/setup.test.ts @@ -14,6 +14,7 @@ function fixture(group = false) { stores.push(store); const submitted: Setup[] = []; let mode: "ok" | "fail" | "lost-response" = "ok"; + let editError: { error_code: number; description: string } | undefined; let visible: any; const answers: string[] = []; let sends = 0; @@ -40,6 +41,7 @@ function fixture(group = false) { bot.api.config.use(async (_previous, method, payload) => { if (method === "editMessageText") { edits++; + if (editError) return { ok: false, ...editError }; if (mode === "fail") throw new Error("Telegram unavailable"); if (JSON.stringify(visible) === JSON.stringify(payload)) return { @@ -87,6 +89,9 @@ function fixture(group = false) { fail: (value: typeof mode) => { mode = value; }, + failEdit: (error?: typeof editError) => { + editError = error; + }, restart: () => { bot = createBot(); }, @@ -271,6 +276,42 @@ test("lost edit responses recover through either visible generation without dupl } }); +test.each([ + ["other bad request", 400, "Bad Request: message to edit not found"], + ["not modified with the wrong status", 500, "message is not modified"], +] as const)("keeps the old setup available after %s", async (_case, error_code, description) => { + const f = fixture(); + await f.open(); + const amount = f.buttonAt(0); + f.failEdit({ error_code, description }); + + await f.click(amount); + + expect(f.answers).toEqual(["Unable to continue. Check the amount, players and wallet balance."]); + expect(f.buttonAt(0)).toBe(amount); + f.failEdit(); + await f.click(amount); + expect(f.answers.at(-1)).toBe(""); + expect(f.labels()).toContain("👥 2"); +}); + +test("selecting the already active hour does not edit or open another prompt", async () => { + const f = fixture(); + await toConfirm(f, "2"); + const menu = f.visible(); + const edits = f.edits(); + const sends = f.sends(); + + await f.click(f.button((text) => text === "1h")); + + expect(f.visible()).toEqual(menu); + expect(f.edits()).toBe(edits); + expect(f.sends()).toBe(sends); + expect(f.answers.at(-1)).toBe(""); + await f.click(f.button((text) => text === "✅ Create Game")); + expect(f.submitted[0]).toMatchObject({ screen: "confirm", timeoutSeconds: 3_600 }); +}); + test("initial failed menu delivery retries the saved message on update replay", async () => { const f = fixture(); f.fail("fail"); From 9cda1a49f9f620e031bece84ae20edff5371806b Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 23:05:14 -0300 Subject: [PATCH 264/410] test(keyboards): pin smallest stake tiers and amount rows --- tests/keyboards.test.ts | 53 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 53 insertions(+) diff --git a/tests/keyboards.test.ts b/tests/keyboards.test.ts index d79635f5..407bf19c 100644 --- a/tests/keyboards.test.ts +++ b/tests/keyboards.test.ts @@ -7,6 +7,7 @@ import { createConfirmWrapKeyboard, createConfirmUnwrapKeyboard, createTradeConfirmKeyboard, + createAmountMenuKeyboard, createAmountSelectionKeyboard, createPlayerSelectionKeyboard, createGameConfirmKeyboard, @@ -378,6 +379,58 @@ describe("keyboards: amount selection", () => { ]); }); + test("keeps two stake tiers exactly one millionth apart", () => { + expect(getSuggestedStakeAmounts(0, undefined, 250_000)).toEqual([ + { amount: 0.000001, usdTarget: 0.25 }, + { amount: 0.000002, usdTarget: 0.5 }, + { amount: 0.000004, usdTarget: 1 }, + { amount: 0.000008, usdTarget: 2 }, + { amount: 0.000012, usdTarget: 3 }, + { amount: 0.00002, usdTarget: 5 }, + { amount: 0.00003, usdTarget: 7.5 }, + { amount: 0.00004, usdTarget: 10 }, + { amount: 0.00006, usdTarget: 15 }, + { amount: 0.00008, usdTarget: 20 }, + { amount: 0.0001, usdTarget: 25 }, + ]); + }); + + test("drops zero tiers and keeps the first USD label when two tiers round to one amount", () => { + const suggestions = getSuggestedStakeAmounts(20, undefined, 1_000_000); + expect(suggestions.slice(0, 3)).toEqual([ + { amount: 0.000001, usdTarget: 0.5 }, + { amount: 0.000002, usdTarget: 2 }, + { amount: 0.000003, usdTarget: 3 }, + ]); + expect(suggestions.find((s) => s.usdTarget === 0.25 || s.usdTarget === 1)).toBeUndefined(); + }); + + test.each([2, 3, 4])("lays out %i exact stakes without an extra row before custom", (count) => { + const amounts = Array.from({ length: count }, (_, index) => ({ + text: `Stake ${index + 1}`, + callback: `stake-${index + 1}`, + })); + const controls = createAmountMenuKeyboard(amounts, "custom", "cancel").inline_keyboard; + const expected = [ + [ + { text: "Stake 1", callback_data: "stake-1" }, + { text: "Stake 2", callback_data: "stake-2" }, + ], + ]; + if (count === 3) expected.push([{ text: "Stake 3", callback_data: "stake-3" }]); + if (count === 4) + expected.push([ + { text: "Stake 3", callback_data: "stake-3" }, + { text: "Stake 4", callback_data: "stake-4" }, + ]); + expect(controls).toEqual([ + ...expected, + [{ text: "✏️ Custom Amount", callback_data: "custom" }], + [{ text: "❌ Cancel", callback_data: "cancel" }], + [], + ]); + }); + test("minimum bet button renders USD equivalent when price is provided", () => { const kb = createAmountSelectionKeyboard("coinflip", undefined, undefined, 20, { decimals: 2, From 30c9079d64f3c682ea670ee49d82d98b738838d9 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 23:08:08 -0300 Subject: [PATCH 265/410] refactor(keyboards): specialize stake rounding at six decimals --- src/utils/keyboards.ts | 11 ++++------- tests/keyboards.test.ts | 13 +++++++++++++ 2 files changed, 17 insertions(+), 7 deletions(-) diff --git a/src/utils/keyboards.ts b/src/utils/keyboards.ts index 84de820a..18b4c5ab 100644 --- a/src/utils/keyboards.ts +++ b/src/utils/keyboards.ts @@ -153,11 +153,8 @@ export const createTradeConfirmKeyboard = ({ // GAME SETUP KEYBOARDS // ================================ -const roundToPrecision = (value: number, precision: number): number => { - if (!Number.isFinite(value)) return 0; - if (precision <= 0) return Math.round(value); - - const factor = Math.pow(10, precision); +const roundStakeAmount = (value: number): number => { + const factor = 1_000_000; const scaled = value * factor; return Number.isFinite(scaled) ? Math.round(scaled) / factor : 0; }; @@ -237,11 +234,11 @@ export const getSuggestedStakeAmounts = ( const suggestions = hasValidPrice ? USD_STAKE_TARGETS.map((usdTarget) => ({ - amount: roundToPrecision(usdTarget / tokenPriceUSD, 6), + amount: roundStakeAmount(usdTarget / tokenPriceUSD), usdTarget, })) : SUGGESTION_MULTIPLIERS.map((multiplier) => ({ - amount: roundToPrecision(min * multiplier, 6), + amount: roundStakeAmount(min * multiplier), })); const unique: StakeSuggestion[] = []; diff --git a/tests/keyboards.test.ts b/tests/keyboards.test.ts index 407bf19c..2f7849e3 100644 --- a/tests/keyboards.test.ts +++ b/tests/keyboards.test.ts @@ -405,6 +405,19 @@ describe("keyboards: amount selection", () => { expect(suggestions.find((s) => s.usdTarget === 0.25 || s.usdTarget === 1)).toBeUndefined(); }); + test.each([ + ["zero", 0, 0], + ["negative", -5, 0], + ["below half a unit", 0.0000000001, 0.0000000001], + ["invalid", Number.NaN, Number.NaN], + ["infinite", Infinity, Infinity], + ] as const)( + "keeps the existing suggestion fallback when the minimum is %s", + (_case, min, amount) => { + expect(getSuggestedStakeAmounts(min)).toEqual([{ amount }]); + }, + ); + test.each([2, 3, 4])("lays out %i exact stakes without an extra row before custom", (count) => { const amounts = Array.from({ length: count }, (_, index) => ({ text: `Stake ${index + 1}`, From 47474e8bb0745e038d499de55b0d1f56b16e73f1 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 23:08:09 -0300 Subject: [PATCH 266/410] test(faucet): check the exact collector display boundary --- tests/faucet-handler.test.ts | 29 +++++++++++++++++++++++++---- 1 file changed, 25 insertions(+), 4 deletions(-) diff --git a/tests/faucet-handler.test.ts b/tests/faucet-handler.test.ts index 78157c72..36198d0a 100644 --- a/tests/faucet-handler.test.ts +++ b/tests/faucet-handler.test.ts @@ -1050,16 +1050,37 @@ describe("buildFaucetMessage", () => { expect(text).toContain("Remaining: 8/30 TOK"); }); + test("lists exactly twenty collectors without a zero remainder", () => { + const collectors = Array.from({ length: 20 }, (_, index) => ({ + telegramId: String(index + 10), + displayName: index === 0 ? "A&B" : null, + })); + const text = buildFaucetMessage({ faucet, paidClaims: 20, processingClaims: 0, collectors }); + + expect(text.split("\n").find((line) => line.startsWith("Collectors: "))).toBe( + 'Collectors: A&B, ' + + Array.from({ length: 19 }, (_, index) => { + const id = index + 11; + return `User ${id}`; + }).join(", "), + ); + }); + test("does not link collectors without a numeric id", () => { const text = buildFaucetMessage({ faucet, - paidClaims: 1, + paidClaims: 3, processingClaims: 0, - collectors: [{ telegramId: "legacy", displayName: "Old" }], + collectors: [ + { telegramId: "legacy", displayName: "Old" }, + { telegramId: "legacy123", displayName: "Prefix" }, + { telegramId: "123legacy", displayName: "Suffix" }, + ], }); - expect(text).toContain("Collectors: Old"); - expect(text).not.toContain("tg://user?id=legacy"); + expect(text.split("\n")).toContain("Collectors: Old, Prefix, Suffix"); + expect(text).not.toContain('href="tg://user?id=legacy'); + expect(text).not.toContain('href="tg://user?id=123legacy'); }); test("an empty faucet shows nothing remaining", () => { From 7d6fbc1e6c4b3f17f0a9abf30455986eb5eda73f Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 23:11:40 -0300 Subject: [PATCH 267/410] test(settings): verify token routes in the live default menu --- tests/chat-defaults.handler.test.ts | 41 ++++++++++++++++++++++++++++- 1 file changed, 40 insertions(+), 1 deletion(-) diff --git a/tests/chat-defaults.handler.test.ts b/tests/chat-defaults.handler.test.ts index 29cbad0b..fb65967b 100644 --- a/tests/chat-defaults.handler.test.ts +++ b/tests/chat-defaults.handler.test.ts @@ -1356,7 +1356,13 @@ describe("chat defaults menus and inputs", () => { gameDb = GameDatabase.getInstance(); }); - const setup = (options: { admin?: boolean; tokenManager?: any } = {}) => { + const setup = ( + options: { + admin?: boolean; + tokenManager?: any; + network?: Parameters[0]["network"]; + } = {}, + ) => { const mockBot = createMockBot(); const tokenManager = options.tokenManager ?? baseTokenManager(); const replies: string[] = []; @@ -1367,6 +1373,7 @@ describe("chat defaults menus and inputs", () => { bot: mockBot as any, chatDb, gameDb, + network: options.network, getTokenManager: () => tokenManager, getGameManager: () => ({ getUsernameFromTelegramId: async () => null }) as any, wrapCallbackHandler: (handler) => async (ctx) => await handler(ctx, async () => {}), @@ -1688,6 +1695,38 @@ describe("chat defaults menus and inputs", () => { } }); + test.each([ + ["evm", "game_network_token", "Network: Base & Test\n🪙 Token: T<ST>"], + ["solana", "chat_defaults_token", "🪙 Token: DEF\n🏷️ Mint: mint"], + ] as const)( + "routes the live /default menu to the chat's %s token settings", + async (chain, callback, tokenLine) => { + const configKey = "EVM_BOT_CONFIG_FILE"; + const original = process.env[configKey]; + const chats: number[] = []; + const h = setup({ + network: (chatId) => { + chats.push(chatId); + return { chain, name: "Base & Test", token: "T" }; + }, + }); + process.env[configKey] = "test-only-evm-settings"; + try { + await h.module.handleDefaultCommand(h.ctxFor(), ["/default"]); + + expect(new Set(chats)).toEqual(new Set([99])); + expect(h.lastMenu().text).toContain(tokenLine); + expect(h.lastMenu().options).toMatchObject({ parse_mode: "HTML" }); + const keyboard = h.lastMenu().options.reply_markup.inline_keyboard; + expect(keyboard[0][0]).toEqual({ text: "🪙 Default token", callback_data: callback }); + expect(keyboard.at(-1)).toEqual([{ text: "⛓️ Network", callback_data: "game_network" }]); + } finally { + if (original === undefined) delete process.env[configKey]; + else process.env[configKey] = original; + } + }, + ); + test("the join notification menu shows the current cap and the opposite action", async () => { const h = setup(); chatDb.upsertChatGameSettings(99, { From 05b5a2ae5fc1f80049bc22c0bdf1ca92c19f5acc Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 23:12:52 -0300 Subject: [PATCH 268/410] test(telegram): pin standalone diagnostics and friendly text --- tests/outbound-error-guard.test.ts | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/tests/outbound-error-guard.test.ts b/tests/outbound-error-guard.test.ts index b0f608c4..d93bb7cf 100644 --- a/tests/outbound-error-guard.test.ts +++ b/tests/outbound-error-guard.test.ts @@ -21,6 +21,36 @@ describe("outbound Telegram error guard", () => { expect(guardOutboundText(text)).toBe(GENERIC_USER_ERROR_MESSAGE); }); + test.each([ + ["first-line stack frame", "at processReceipt"], + ["indented stack frame", "No confirmation\n at async processReceipt"], + ["cause header spacing", "Caused by : no confirmation"], + ["compiled JavaScript location", "/workspace/generated/bot.cjs:44"], + ["plain Python location", "/workspace/tasks/run.py:28"], + ["nested TSX location", "/workspace/src/menus/wallet.tsx:309:2"], + ["Undici failure code", "UND_ERR_CONNECT_TIMEOUT"], + ["HTTP major version", "HTTP/2 503"], + ["HTTP minor version", "HTTP/1.1 503"], + ["HTTP status spacing", "HTTP status 503"], + ["expanded status code", "status code was 503"], + ["response context", "Unexpected upstream response"], + ["swap service context", "Failed while contacting Jupiter"], + ] as const)("replaces a standalone %s at the outbound boundary", (_case, text) => { + expect(guardOutboundText(text)).toBe(GENERIC_USER_ERROR_MESSAGE); + }); + + test.each([ + ["empty text", ""], + ["whitespace-only text", " \n\t "], + ["normal channel count", "Status: waiting for 601 players"], + ["normal documentation link", "Read https://example.invalid/help/faq"], + ["normal JSON array", ' [{"title":"Round 2"}] '], + ["plain heading", "Next steps before the request concludes"], + ["friendly non-JSON notice", "[Summary: prizes arrive after confirmation]"], + ] as const)("does not replace %s", (_case, text) => { + expect(guardOutboundText(text)).toBe(text); + }); + test("continues searching for a diagnostic after null and primitive values", () => { const text = JSON.stringify([null, false, 2, "plain", { outer: { statusText: "Busy" } }]); expect(guardOutboundText(text)).toBe(GENERIC_USER_ERROR_MESSAGE); From 8da9f13048530479348a00f0d8c08e551cc125a0 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 23:14:03 -0300 Subject: [PATCH 269/410] refactor(telegram): simplify equivalent diagnostic checks --- src/utils/outbound-error-guard.ts | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/utils/outbound-error-guard.ts b/src/utils/outbound-error-guard.ts index cfd7e6a8..18f32e61 100644 --- a/src/utils/outbound-error-guard.ts +++ b/src/utils/outbound-error-guard.ts @@ -5,9 +5,9 @@ export const GENERIC_USER_ERROR_MESSAGE = const EXCEPTION_NAME = /\b(?:Aggregate|Assertion|Eval|Internal|ProtocolHttp|ProtocolResponse|Range|Reference|Syntax|Type|URI|Zod)?Error\b|\bException\b/i; -const STACK_FRAME = /(?:^|\n)\s*(?:at\s+(?:async\s+)?\S+|caused by\s*:)/im; -const SOURCE_LOCATION = - /(?:file:\/\/|\/(?:[^\s/:]+\/)+[^\s/:]+\.(?:[cm]?[jt]sx?|rs|py)):\d+(?::\d+)?/i; +const STACK_FRAME = /^\s*(?:at\s+(?:async\s+)?\S+|caused by\s*:)/im; +// Only the start of a source location is needed. Column numbers are optional. +const SOURCE_LOCATION = /(?:file:\/\/|\/(?:[^\s/:]+\/)+[^\s/:]+\.(?:[cm]?[jt]sx?|rs|py)):\d/i; const VALIDATOR_DIAGNOSTIC = /\b(?:invalid_type|invalid_union|invalid_value|unrecognized_keys|too_small|too_big)\b|"(?:expected|received|code|path|issues)"\s*:/i; const NETWORK_DIAGNOSTIC = @@ -26,8 +26,8 @@ const looksLikeSerializedDiagnostic = (text: string): boolean => { if (!(trimmed.startsWith("{") || trimmed.startsWith("["))) return false; try { + // That opening delimiter ensures valid JSON is an object or an array. const parsed: unknown = JSON.parse(trimmed); - if (!parsed || typeof parsed !== "object") return false; const inspect = (value: unknown, depth = 0): boolean => { if (depth > 5) return false; From 85bfb59fd01eacd35fcd5a256517851e41586f19 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 23:17:45 -0300 Subject: [PATCH 270/410] fix(faucet): avoid duplicate in-flight payout notices --- src/handlers/faucet.ts | 9 +++++++-- tests/faucet-handler.test.ts | 33 +++++++++++++++++++++++++++++++++ 2 files changed, 40 insertions(+), 2 deletions(-) diff --git a/src/handlers/faucet.ts b/src/handlers/faucet.ts index e803bccb..48617472 100644 --- a/src/handlers/faucet.ts +++ b/src/handlers/faucet.ts @@ -180,6 +180,8 @@ const tellClaimant = async (ctx: Context, text: string): Promise => { export const createFaucetModule = (deps: FaucetModuleDeps) => { const now = deps.now ?? Date.now; + const claimOperationKey = (faucetId: number, telegramId: bigint | string): string => + `${faucetId}:${telegramId}`; const activeClaimOperations = new Set(); let reconciliationPromise: Promise | undefined; const answer = @@ -249,6 +251,9 @@ export const createFaucetModule = (deps: FaucetModuleDeps) => { const deliverPendingClaimNotifications = async (): Promise => { for (const claim of deps.database.getPendingNotifications(now())) { + // A live claim can already be awaiting the same Telegram send. + if (activeClaimOperations.has(claimOperationKey(claim.faucet_id, claim.telegram_id))) + continue; await deliverClaimNotification(claim.faucet_id, BigInt(claim.telegram_id)); } }; @@ -263,7 +268,7 @@ export const createFaucetModule = (deps: FaucetModuleDeps) => { ); const affected = new Set(); for (const claim of deps.database.getSubmittedClaims()) { - const claimKey = `${claim.faucet_id}:${claim.telegram_id}`; + const claimKey = claimOperationKey(claim.faucet_id, claim.telegram_id); if (activeClaimOperations.has(claimKey)) continue; const signature = claim.transaction_signature!; let outcome: "confirmed" | "failed" | "unknown"; @@ -463,7 +468,7 @@ export const createFaucetModule = (deps: FaucetModuleDeps) => { } const faucet = reserved.faucet; - const claimKey = `${faucetId}:${claimantId}`; + const claimKey = claimOperationKey(faucetId, claimantId); activeClaimOperations.add(claimKey); try { await answer(ctx); diff --git a/tests/faucet-handler.test.ts b/tests/faucet-handler.test.ts index 36198d0a..8f56d3ca 100644 --- a/tests/faucet-handler.test.ts +++ b/tests/faucet-handler.test.ts @@ -5,6 +5,7 @@ import { FaucetDatabase } from "../src/utils/faucet-database"; import { inferMaxPlayers } from "../src/utils/arg-parsing"; import { resetTestDatabase } from "./helpers/database"; import { telegramRefusal } from "./helpers/telegram-errors"; +import { withinTestDeadline } from "./helpers/timers"; let db: FaucetDatabase; // In the group, a refused /faucet reaches only its creator (id 10). @@ -302,6 +303,38 @@ describe("faucet handler", () => { expect(harness.events.slice(-2)).toEqual(["edit", "dm"]); }); + test("does not send a second notification while a paid claim is finishing", async () => { + const started = Promise.withResolvers(); + const release = Promise.withResolvers(); + let notifications = 0; + const harness = createHarness({ + notify: async () => { + notifications++; + if (notifications === 1) { + started.resolve(); + await release.promise; + } + }, + }); + await harness.module.handleCommand(harness.commandContext("/faucet 1 1")); + const claim = harness.module.handleClaim(harness.callbackContext(20), 1); + try { + await withinTestDeadline(started.promise, "first payout notification"); + expect(db.getClaim(1, 20n)).toMatchObject({ status: "paid", notification_status: "pending" }); + + await harness.module.reconcile(); + + expect(notifications).toBe(1); + expect(db.getClaim(1, 20n)?.notification_status).toBe("pending"); + } finally { + release.resolve(); + await claim; + } + expect(harness.privateMessages).toHaveLength(1); + expect(harness.transferSenders).toEqual([10n]); + expect(db.getClaim(1, 20n)?.notification_status).toBe("sent"); + }); + test("rejects creator claims and copied faucet buttons", async () => { const harness = createHarness(); await harness.module.handleCommand(harness.commandContext("/faucet 1 2")); From ed43eafb978623f1c11ada95d768db2b41f69bbc Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 23:20:05 -0300 Subject: [PATCH 271/410] test(faucet): keep unrelated payout notices deliverable --- tests/faucet-handler.test.ts | 48 ++++++++++++++++++++++++++++++------ 1 file changed, 40 insertions(+), 8 deletions(-) diff --git a/tests/faucet-handler.test.ts b/tests/faucet-handler.test.ts index 8f56d3ca..583208d2 100644 --- a/tests/faucet-handler.test.ts +++ b/tests/faucet-handler.test.ts @@ -303,19 +303,27 @@ describe("faucet handler", () => { expect(harness.events.slice(-2)).toEqual(["edit", "dm"]); }); - test("does not send a second notification while a paid claim is finishing", async () => { + const holdFirstPayoutNotice = () => { const started = Promise.withResolvers(); const release = Promise.withResolvers(); - let notifications = 0; - const harness = createHarness({ - notify: async () => { - notifications++; - if (notifications === 1) { + const attempts: number[] = []; + return { + started, + release, + attempts, + notify: async (chatId: number) => { + attempts.push(chatId); + if (attempts.length === 1) { started.resolve(); await release.promise; } }, - }); + }; + }; + + test("does not send a second notification while a paid claim is finishing", async () => { + const { started, release, attempts, notify } = holdFirstPayoutNotice(); + const harness = createHarness({ notify }); await harness.module.handleCommand(harness.commandContext("/faucet 1 1")); const claim = harness.module.handleClaim(harness.callbackContext(20), 1); try { @@ -324,7 +332,7 @@ describe("faucet handler", () => { await harness.module.reconcile(); - expect(notifications).toBe(1); + expect(attempts).toEqual([20]); expect(db.getClaim(1, 20n)?.notification_status).toBe("pending"); } finally { release.resolve(); @@ -335,6 +343,30 @@ describe("faucet handler", () => { expect(db.getClaim(1, 20n)?.notification_status).toBe("sent"); }); + test("reconciliation still sends a different claimant's pending notification", async () => { + const { started, release, attempts, notify } = holdFirstPayoutNotice(); + const harness = createHarness({ notify }); + await harness.module.handleCommand(harness.commandContext("/faucet 1 2")); + const claim = harness.module.handleClaim(harness.callbackContext(20), 1); + try { + await withinTestDeadline(started.promise, "first claimant's payout notice"); + db.reserveClaim(1, 21n, 1_000); + db.recordClaimSignature(1, 21n, "other-transaction", 1_000); + db.completeClaim(1, 21n, "other-transaction", 1_000); + + await harness.module.reconcile(); + + expect(attempts).toEqual([20, 21]); + expect(db.getClaim(1, 20n)?.notification_status).toBe("pending"); + expect(db.getClaim(1, 21n)?.notification_status).toBe("sent"); + } finally { + release.resolve(); + await claim; + } + expect(harness.privateMessages.map(({ chatId }) => chatId)).toEqual([21, 20]); + expect(harness.transferSenders).toEqual([10n]); + }); + test("rejects creator claims and copied faucet buttons", async () => { const harness = createHarness(); await harness.module.handleCommand(harness.commandContext("/faucet 1 2")); From a7da970f2d2c021a57d2f257d4c88cecf4cf8ce0 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 23:25:59 -0300 Subject: [PATCH 272/410] refactor(wallet): preserve example section spacing --- src/utils/wallet-ui.ts | 4 +--- tests/wallet-ui.test.ts | 25 +++++++++++++++++++++++++ 2 files changed, 26 insertions(+), 3 deletions(-) diff --git a/src/utils/wallet-ui.ts b/src/utils/wallet-ui.ts index 96bfc813..bcaca05b 100644 --- a/src/utils/wallet-ui.ts +++ b/src/utils/wallet-ui.ts @@ -419,9 +419,7 @@ export const showCustomAmountPrompt = async ({ appendSection(lines, instructions); if (examples && examples.length > 0) { - if (lines.length > 0) { - lines.push(""); - } + lines.push(""); if (examplesHeading) { lines.push(examplesHeading); } diff --git a/tests/wallet-ui.test.ts b/tests/wallet-ui.test.ts index 4cdfe189..62facf40 100644 --- a/tests/wallet-ui.test.ts +++ b/tests/wallet-ui.test.ts @@ -363,6 +363,31 @@ test("showCustomAmountPrompt formats send custom amount flow", async () => { expect(session?.chatId).toBe(654); }); +test.each([ + [ + "with a heading", + "Amount", + "Examples:", + "Amount\n\nExamples:\n• 0.5", + ], + ["without a title or heading", "", "", "\n\n• 0.5"], +] as const)("keeps exact example spacing %s", async (_case, title, examplesHeading, expected) => { + const edits: EditCall[] = []; + await showCustomAmountPrompt({ + ctx: createMockContext(edits), + userId: "amount-user", + title, + instructions: [], + examplesHeading, + examples: [" ", 17 as unknown as string, "• 0.5", ""], + footerLines: [], + cancelCallback: "send_select_SOL", + state: { type: "send_custom_amount", token: "SOL" }, + }); + + expect(expectSingleEdit(edits).text).toBe(expected); +}); + test("showCustomAmountPrompt formats sell custom amount flow", async () => { const edits: EditCall[] = []; const ctx = createMockContext(edits, { From e155296e9973399185753960848fbce9d1f6eb7b Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 23:28:58 -0300 Subject: [PATCH 273/410] test(swap): require native mints for wrap quotes --- tests/swap-manager.sol-wsol-quote.test.ts | 53 +++++++++++++++++++++-- 1 file changed, 50 insertions(+), 3 deletions(-) diff --git a/tests/swap-manager.sol-wsol-quote.test.ts b/tests/swap-manager.sol-wsol-quote.test.ts index 4e7020ec..e25c879f 100644 --- a/tests/swap-manager.sol-wsol-quote.test.ts +++ b/tests/swap-manager.sol-wsol-quote.test.ts @@ -5,6 +5,8 @@ import { SwapManager } from "../src/utils/swap-manager"; import { WalletManager } from "../src/utils/wallet"; import { WSOL_MINT } from "../src/utils/token-registry"; +const tokenMint = "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"; + describe("SwapManager.getQuote SOL/WSOL handling", async () => { const connection = new Connection("http://localhost:8899", "confirmed"); const wallet = WalletManager.createForTest( @@ -106,7 +108,7 @@ describe("SwapManager.getQuote SOL/WSOL handling", async () => { test("still requests Jupiter quote for non wrap/unwrap pairs", async () => { const jupiterSpy = vi.spyOn((manager as any).jupiterClient, "getQuote").mockResolvedValue({ inputMint: WSOL_MINT, - outputMint: "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v", + outputMint: tokenMint, inAmount: baseRequest.amount, outAmount: "1000", otherAmountThreshold: "0", @@ -119,18 +121,63 @@ describe("SwapManager.getQuote SOL/WSOL handling", async () => { const quote = await manager.getQuote({ ...baseRequest, inputMint: WSOL_MINT, - outputMint: "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v", + outputMint: tokenMint, inputTicker: "SOL", outputTicker: "USDC", }); expect(quote.provider).toBe("jupiter"); + expect(quote.estimatedRate).toBe(1 / 123_000); + expect(quote.slippage).toBe(1); + expect(quote.inputAmountRaw).toBe("123000000"); expect(jupiterSpy).toHaveBeenCalledTimes(1); const [params] = jupiterSpy.mock.calls[0]!; expect(params).toMatchObject({ inputMint: WSOL_MINT, - outputMint: "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v", + outputMint: tokenMint, amount: baseRequest.amount, }); }); + + test.each([ + ["input", tokenMint, WSOL_MINT], + ["output", WSOL_MINT, tokenMint], + ] as const)( + "requires a SOL mint on the %s even if both ticker labels look native", + async (_side, inputMint, outputMint) => { + const providerQuote = { + inputMint, + outputMint, + inAmount: "200", + outAmount: "50", + otherAmountThreshold: "49", + swapMode: "ExactIn" as const, + slippageBps: 75, + priceImpactPct: "0", + routePlan: [], + }; + const getQuote = vi + .spyOn(manager["jupiterClient"], "getQuote") + .mockResolvedValue(providerQuote); + const quote = await manager.getQuote({ + ...baseRequest, + amount: "200", + inputMint, + outputMint, + inputTicker: "SoL", + outputTicker: "wSoL", + }); + + expect(getQuote).toHaveBeenCalledTimes(1); + expect(quote).toMatchObject({ + provider: "jupiter", + inputMint, + outputMint, + inputAmountRaw: "200", + outputAmount: "50", + estimatedRate: 0.25, + slippage: 0.75, + }); + }, + ); }); From 503b7729e3f4c38c44faf74f1ecdfd790d0deac7 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 23:30:56 -0300 Subject: [PATCH 274/410] test(swap): pin exact sponsored route requirements --- ...wap-manager.execute-jupiter.errors.test.ts | 59 ++++++++++++++++++- 1 file changed, 58 insertions(+), 1 deletion(-) diff --git a/tests/swap-manager.execute-jupiter.errors.test.ts b/tests/swap-manager.execute-jupiter.errors.test.ts index 1650c0cf..432bb833 100644 --- a/tests/swap-manager.execute-jupiter.errors.test.ts +++ b/tests/swap-manager.execute-jupiter.errors.test.ts @@ -1,5 +1,5 @@ import { Buffer } from "buffer"; -import { describe, test, expect } from "bun:test"; +import { describe, expect, spyOn, test } from "bun:test"; import { Connection, Keypair, PublicKey, TransactionMessage, VersionedTransaction } from "#solana"; import { AccountLayout, AccountState, TOKEN_PROGRAM_ID } from "#token"; import type { IntegratorSwapParams } from "../src/utils/integrator-fees"; @@ -182,6 +182,63 @@ describe("SwapManager.ensureAdminCanCoverRoute", () => { expect(integrator.adminRouteLamports).toBe(helperCosts.routeLamports); }); + test.each([ + ["base", 0, 0, 0, 0, 0, 10_000_000], + ["rent-heavy", 2_000_000, 300_000, 10_000, 2_310_000, 577_500, 12_887_500], + ] as const)( + "accepts the exact %s requirement and logs its route costs", + async ( + kind, + rentFeeLamports, + prioritizationFeeLamports, + signatureFeeLamports, + routeLamports, + paddingLamports, + requiredLamports, + ) => { + const manager = buildSwapManagerWithBalance(requiredLamports); + const integrator = { ...baseIntegrator }; + const order = buildBaseOrder({ + rentFeeLamports, + prioritizationFeeLamports, + signatureFeeLamports, + }); + const log = spyOn(console, "log").mockImplementation(() => {}); + try { + await expect( + manager["ensureAdminCanCoverRoute"](integrator, order, PublicKey.default), + ).resolves.toBeUndefined(); + + expect(integrator.adminRouteLamports).toBe(routeLamports); + expect(log.mock.calls).toEqual([ + [ + kind === "base" + ? "Admin payer route check" + : "Admin payer route check (rent-heavy path)", + { + adminBalance: requiredLamports, + requiredLamports, + routeLamports, + paddingLamports, + routeRequestId: "route-rent", + router: "iris", + payerKind: "admin", + }, + ], + ...(kind === "base" + ? [] + : [ + [ + "Route iris needs 2310000 lamports SOL for rent/priority. Admin payer will cover it (adds 577500 lamports padding).", + ], + ]), + ]); + } finally { + log.mockRestore(); + } + }, + ); + test("throws when the admin wallet balance is below the total requirement", async () => { const swapManager = buildSwapManagerWithBalance(5_000_000); const integrator = { ...baseIntegrator, adminRequiredLamports: 8_000_000 }; From 127d5a375b4a48e39b6e90007113677b10a13fe9 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 23:39:13 -0300 Subject: [PATCH 275/410] test(evm): pin giveaway and coinflip player floors --- src/evm/setup.test.ts | 51 ++++++++++++++++++++++++++++++++++++++----- 1 file changed, 45 insertions(+), 6 deletions(-) diff --git a/src/evm/setup.test.ts b/src/evm/setup.test.ts index 288de5c6..66d0d582 100644 --- a/src/evm/setup.test.ts +++ b/src/evm/setup.test.ts @@ -9,7 +9,7 @@ afterEach(() => { for (const store of stores.splice(0)) store.db.close(); }); -function fixture(group = false) { +function fixture(group = false, type: Setup["type"] = "coinflip", minPlayers = 2) { const store = new EvmBotStore(":memory:", "setup-test"); stores.push(store); const submitted: Setup[] = []; @@ -26,6 +26,7 @@ function fixture(group = false) { ? { id: -10001, type: "supergroup" as const, title: "Setup Test Group" } : { id: 1, type: "private" as const, first_name: "Test" }; const from = { id: 1, is_bot: false, first_name: "Test" }; + const command = type === "coinflip" ? "cf" : "ga"; function createBot() { const bot = new Bot("123:test", { botInfo: { @@ -66,7 +67,7 @@ function fixture(group = false) { const open = registerEvmSetup(bot, store, "Anvil", async (_ctx, setup) => { submitted.push(structuredClone(setup)); }); - bot.command("cf", (ctx) => + bot.command(command, (ctx) => open( ctx, { @@ -75,8 +76,8 @@ function fixture(group = false) { decimals: 18, minimumAmount: "1", }, - "coinflip", - { maxPlayers: 2, minPlayers: 2, timeout: 3600, isPrivate: false }, + type, + { maxPlayers: Math.max(2, minPlayers), minPlayers, timeout: 3600, isPrivate: false }, ), ); return bot; @@ -119,7 +120,7 @@ function fixture(group = false) { date: 1, chat, from, - text: "/cf", + text: `/${command}`, entities: [{ type: "bot_command", offset: 0, length: 3 }], }, }); @@ -355,7 +356,14 @@ test("retrying a failed timeout edit applies its delta only once", async () => { expect(f.submitted[0]?.timeoutSeconds).toBe(7200); }); -const CONFIRM = { create: 0, visibility: 10, minPlus50: 14, minMax: 15, back: 16 }; +const CONFIRM = { + create: 0, + visibility: 10, + minMinus50: 11, + minPlus50: 14, + minMax: 15, + back: 16, +}; async function toConfirm(f: ReturnType, players: string) { await f.open(); @@ -403,6 +411,37 @@ test("minimum players can be raised but never above the maximum", async () => { expect(f.submitted[0]).toMatchObject({ players: 10, minPlayers: 10 }); }); +test("a giveaway can lower its minimum to one player", async () => { + const f = fixture(false, "giveaway"); + await toConfirm(f, "5"); + await f.click(f.buttonAt(CONFIRM.minMinus50)); + expect(f.labels()).toContain("Min 1"); + await f.click(f.buttonAt(CONFIRM.create)); + expect(f.submitted[0]).toMatchObject({ type: "giveaway", minPlayers: 1, players: 5 }); +}); + +test("a saved coinflip decrement cannot lower the minimum below two players", async () => { + const f = fixture(false, "coinflip", 3); + await toConfirm(f, "5"); + expect(f.labels()).toContain("Min 3"); + const decrease = f.buttonAt(CONFIRM.minMinus50); + + // Model a durable setup restored with an older menu for the same generation. + const row = f.store.db + .query<{ body: string }, [string]>("SELECT body FROM setups WHERE id=?") + .get("1"); + if (!row) throw new Error("Expected a saved setup"); + const setup = JSON.parse(row.body) as Setup; + f.store.db + .query("UPDATE setups SET body=? WHERE id=?") + .run(JSON.stringify({ ...setup, minPlayers: 2 }), "1"); + f.restart(); + + await f.click(decrease); + await f.click(f.buttonAt(CONFIRM.create)); + expect(f.submitted[0]).toMatchObject({ type: "coinflip", minPlayers: 2, players: 5 }); +}); + test("visibility toggles to private and is submitted", async () => { const f = fixture(); await toConfirm(f, "2"); From 5d10dad85c601f8c67229a08b982cf29e59d1541 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 23:42:03 -0300 Subject: [PATCH 276/410] test(evm): isolate four equivalent setup literals --- src/evm/setup.ts | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/evm/setup.ts b/src/evm/setup.ts index 4764f7a1..4f6902d7 100644 --- a/src/evm/setup.ts +++ b/src/evm/setup.ts @@ -149,6 +149,7 @@ export function registerEvmSetup( await ctx.answerCallbackQuery(); return; } + // Stryker disable next-line StringLiteral: The catch sends the same setup error for every exception. if (!action) throw new Error("Invalid selection"); // A click on the new generation proves that Telegram received its menu. delete s.pendingPreviousGeneration; @@ -225,12 +226,14 @@ export function registerEvmSetup( try { if (s.input === "amount") { const raw = parseTokenAmount(ctx.message.text, s.token.decimals); + // Stryker disable next-line StringLiteral: The catch sends the same invalid-value reply. if (raw < BigInt(s.token.minimumAmount)) throw new Error("minimum"); s.amount = formatTokenAmount(raw, s.token.decimals); s.screen = "players"; } else { const value = parseDecimalInteger(ctx.message.text); if (value === null || value < (s.type === "coinflip" ? 2 : 1) || value > 100) + // Stryker disable next-line StringLiteral: The catch sends the same invalid-value reply. throw new Error("players"); s.players = value; s.minPlayers = Math.min(s.minPlayers, value); @@ -270,6 +273,7 @@ export function registerEvmSetup( timeoutSeconds: defaults.timeout, isPrivate: defaults.isPrivate, screen: "amount", + // Stryker disable next-line ArrayDeclaration: Render rebuilds the actions before saving the setup. actions: [], generation: 0, }; From 1cdb9bae750673967b639929829c91d0f49c914c Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 23:47:05 -0300 Subject: [PATCH 277/410] test(wallet): pin history confirmation diagnostics --- tests/wallet-mutation-bounds.test.ts | 63 +++++++++++++++++++++++++--- 1 file changed, 58 insertions(+), 5 deletions(-) diff --git a/tests/wallet-mutation-bounds.test.ts b/tests/wallet-mutation-bounds.test.ts index 577dc9ee..ef0ca3fa 100644 --- a/tests/wallet-mutation-bounds.test.ts +++ b/tests/wallet-mutation-bounds.test.ts @@ -89,14 +89,67 @@ test.each(["confirmed", "finalized"] as const)( }, }); - await expect( - withinTestDeadline(wallet.confirmTransaction(signature), "confirmed wallet status"), - ).resolves.toBeUndefined(); - expect(reads).toBe(1); - expect(timers.delays).toEqual([]); + const clock = useWalletConfirmationClock(wallet); + const log = spyOn(console, "log").mockImplementation(() => {}); + try { + await expect( + withinTestDeadline(wallet.confirmTransaction(signature), "confirmed wallet status"), + ).resolves.toBeUndefined(); + expect(reads).toBe(1); + expect(clock.delays).toEqual([]); + expect(timers.delays).toEqual([]); + expect(log.mock.calls.at(-1)).toEqual([ + `✅ Transaction ${signature} confirmed in 0ms (1 polls, history=not-used, firstStatus=0ms, networkRetries=0)`, + ]); + } finally { + log.mockRestore(); + clock.restore(); + } }, ); +test("missing status responses remain unknown until the history lookup confirms", async () => { + const context = { slot: 1n }; + const responses = [ + undefined, + { context }, + { context, value: [{ slot: 1n, confirmations: 0n, err: null, confirmationStatus: null }] }, + { + context, + value: [{ slot: 1n, confirmations: 1n, err: null, confirmationStatus: "confirmed" }], + }, + ]; + const history: Array = []; + type ReadStatus = Connection["getSignatureStatuses"]; + const wallet = walletWith({ + getSignatureStatuses: async (_signatures, config) => { + if (responses.length === 0) throw new Error("Unexpected fifth status lookup"); + history.push(config?.searchTransactionHistory); + // Include the incomplete values that a broken provider adapter can return. + return responses.shift() as Awaited>; + }, + }); + Object.defineProperty(wallet, "signaturePollIntervalMs", { value: 4_000 }); + const clock = useWalletConfirmationClock(wallet); + const log = spyOn(console, "log").mockImplementation(() => {}); + try { + await expect( + withinTestDeadline(wallet.confirmTransaction(signature), "wallet history confirmation"), + ).resolves.toBeUndefined(); + expect(history).toEqual([undefined, undefined, true, true]); + expect(clock.delays).toEqual([4_000, 4_000, 4_000]); + expect(log.mock.calls).toContainEqual([ + `📊 Transaction ${signature} status update (poll 3, 8000ms): unknown (0 confirmations)`, + ]); + expect(log.mock.calls.at(-1)).toEqual([ + `✅ Transaction ${signature} confirmed in 12000ms (4 polls, history=enabled@8000ms, firstStatus=8000ms, networkRetries=0)`, + ]); + } finally { + log.mockRestore(); + clock.restore(); + } +}); + test("waits once before using a confirmed post-timeout history result", async () => { let reads = 0; let probes = 0; From 63512ecdb70749e9ca58a595e2f99b3ff655b2cd Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 23:49:41 -0300 Subject: [PATCH 278/410] fix(ci): read complete mutation diffs --- scripts/mutants.test.ts | 43 ++++++++++++++++++++++++++++++++++++++++- scripts/mutants.ts | 18 +++++++++++------ 2 files changed, 54 insertions(+), 7 deletions(-) diff --git a/scripts/mutants.test.ts b/scripts/mutants.test.ts index c1b1c222..7f92602b 100644 --- a/scripts/mutants.test.ts +++ b/scripts/mutants.test.ts @@ -1,5 +1,8 @@ import { describe, expect, test } from "bun:test"; -import { changedRanges, instrumentRanges, inScope, lived, partRanges } from "./mutants"; +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { changedRanges, instrumentRanges, inScope, lived, partRanges, readGit } from "./mutants"; const scope = { roots: ["src"], @@ -47,6 +50,44 @@ describe("mutants", () => { ]); }); + test("reads the last source hunk after more than one MiB of Git output", () => { + const repo = mkdtempSync(join(tmpdir(), "mutants-git-")); + const git = (...args: string[]) => readGit(args, repo); + const commit = (message: string) => + git( + "-c", + "user.name=test", + "-c", + "user.email=test@example.invalid", + "commit", + "-qm", + message, + ); + try { + git("init", "-q"); + mkdirSync(join(repo, "src")); + const source = join(repo, "src", "last.ts"); + writeFileSync(source, "export const value = 1;\n"); + git("add", "."); + commit("baseline"); + + writeFileSync(join(repo, "bulk-fixture.txt"), `${"test fixture\n".repeat(160_000)}é\n`); + writeFileSync(source, "export const value = 2;\n"); + git("add", "."); + commit("large diff"); + + const diff = git("diff", "-U0", "--no-color", "HEAD^", "HEAD"); + expect(Buffer.byteLength(diff, "utf8")).toBeGreaterThan(1_048_576); + expect(diff).toContain("+é\n"); + expect(changedRanges(diff).filter(({ file }) => inScope(file, scope))).toEqual([ + { file: "src/last.ts", from: 1, to: 1 }, + ]); + expect(() => git("rev-parse", "--verify", "missing-fixture-ref")).toThrow("fatal:"); + } finally { + rmSync(repo, { recursive: true, force: true }); + } + }); + test("parts cover every line once, as equal as whole lines allow", () => { const files = [ { file: "src/a.ts", lines: 5 }, diff --git a/scripts/mutants.ts b/scripts/mutants.ts index cc105d2c..6bd039c3 100644 --- a/scripts/mutants.ts +++ b/scripts/mutants.ts @@ -171,10 +171,16 @@ export function lived( return { rows: left.map(([, , row]) => row), total }; } -function git(...args: string[]): string { - const result = spawnSync("git", args, { cwd: ROOT, encoding: "utf8" }); - if (result.status !== 0) throw new Error(`git ${args.join(" ")}: ${result.stderr}`); - return result.stdout; +export function readGit(args: string[], cwd = ROOT): string { + // Git diffs can exceed the default buffer of node:child_process.spawnSync. + const result = Bun.spawnSync(["git", ...args], { cwd, stdout: "pipe", stderr: "pipe" }); + const decode = new TextDecoder("utf-8", { ignoreBOM: true }); + if (!result.success) { + throw new Error( + `git ${args.join(" ")} (exit ${result.exitCode}): ${decode.decode(result.stderr)}`, + ); + } + return decode.decode(result.stdout); } function sourceFiles(scope: Scope): { file: string; lines: number }[] { @@ -199,8 +205,8 @@ function main(argv: string[]): number { const scope: Scope = JSON.parse(readFileSync(join(ROOT, "coverage-scope.json"), "utf8")); let ranges: Range[]; if (argv[0] === "diff" && argv[1]) { - const since = git("merge-base", argv[1], "HEAD").trim(); - ranges = changedRanges(git("diff", "-U0", "--no-color", since, "HEAD")).filter((range) => + const since = readGit(["merge-base", argv[1], "HEAD"]).trim(); + ranges = changedRanges(readGit(["diff", "-U0", "--no-color", since, "HEAD"])).filter((range) => inScope(range.file, scope), ); } else if (argv[0] === "part" && argv[1] && argv[2]) { From 35b4e5d26d57b2262cc2f0e7b2b8a0c12e4e9b9f Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 23:53:36 -0300 Subject: [PATCH 279/410] test(evm): cover setup balance retry and invalid giveaways --- src/evm/bot.test.ts | 46 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) diff --git a/src/evm/bot.test.ts b/src/evm/bot.test.ts index a0b7634d..a830ae26 100644 --- a/src/evm/bot.test.ts +++ b/src/evm/bot.test.ts @@ -720,6 +720,52 @@ describe("EVM game commands", () => { expect(h.replies().at(-1)).toContain("Insufficient TEST"); }); + test("the setup can retry creation when its balance reaches the exact stake", async () => { + const account = h.runtime.service.account("1").address; + h.balances.set(account, 0n); + const button = (label: string): string => { + const menu = h.calls.findLast( + (call) => call.method === "editMessageText" && call.payload.reply_markup, + ); + const data: unknown = menu?.payload.reply_markup.inline_keyboard + .flat() + .find((entry: { text: string }) => entry.text === label)?.callback_data; + if (typeof data !== "string") throw new Error(`Missing setup button ${label}`); + return data; + }; + await h.text("/ecf TEST"); + await h.click(button("0.000000000000000001")); + await h.click(button("👥 2")); + const create = button("✅ Create Game"); + + await h.click(create); + expect(h.answers().at(-1)).toBe( + "Unable to continue. Check the amount, players and wallet balance.", + ); + expect(h.store.pending()).toEqual([]); + + h.balances.set(account, 1n); + await h.click(create); + expect(h.store.pending()).toHaveLength(1); + expect(JSON.parse(h.store.pending()[0]!.body)).toMatchObject({ + token: tokenAddress, + amount: "1", + maxPlayers: 2, + }); + }); + + test.each([ + ["unknown token", "/egiveaway 1 TKN"], + ["too many players", "/egiveaway 1 TEST 101"], + ] as const)("gives the giveaway usage and creates nothing for %s", async (_case, text) => { + await h.text(text); + expect(h.replies()).toEqual([ + "Use /ga AMOUNT [TOKEN] [PLAYERS] [private]. Check the token minimum and your wallet balance.", + ]); + expect(h.store.pending()).toEqual([]); + expect(h.readContract).not.toHaveBeenCalled(); + }); + test("giveaways record players, visibility and the chat default token", async () => { useEvm(); h.store.setToken("1", usdcAddress); From a61ddbcd0770611427d0fbfc41530e40419d6daf Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 29 Nov 2026 23:57:34 -0300 Subject: [PATCH 280/410] test(swap): check which routes can retry without referral --- tests/swap-manager.sol-wsol-quote.test.ts | 59 +++++++++++++++++++++++ 1 file changed, 59 insertions(+) diff --git a/tests/swap-manager.sol-wsol-quote.test.ts b/tests/swap-manager.sol-wsol-quote.test.ts index e25c879f..d3cc884c 100644 --- a/tests/swap-manager.sol-wsol-quote.test.ts +++ b/tests/swap-manager.sol-wsol-quote.test.ts @@ -4,6 +4,7 @@ import { Connection, Keypair } from "#solana"; import { SwapManager } from "../src/utils/swap-manager"; import { WalletManager } from "../src/utils/wallet"; import { WSOL_MINT } from "../src/utils/token-registry"; +import { JupiterReferralUnavailableError } from "../src/utils/jupiter"; const tokenMint = "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"; @@ -180,4 +181,62 @@ describe("SwapManager.getQuote SOL/WSOL handling", async () => { }); }, ); + + test.each([ + ["admin token-to-SOL", tokenMint, WSOL_MINT, "admin", true], + ["admin SOL-to-token", WSOL_MINT, tokenMint, "admin", false], + [ + "admin token-to-token", + tokenMint, + "F3A1baCgv4TF79TSjdMTvpMDtNv8DJvHZwNc9DG8pump", + "admin", + false, + ], + ["user token-to-SOL", tokenMint, WSOL_MINT, "user", false], + ["unsponsored token-to-SOL", tokenMint, WSOL_MINT, undefined, false], + ] as const)( + "checks plain-quote fallback for %s", + async (_case, inputMint, outputMint, payerKind, allowed) => { + const unavailable = new JupiterReferralUnavailableError("Referral quote unavailable"); + const fallback = new Error("Plain quote unavailable"); + const getQuote = vi + .spyOn(manager["jupiterClient"], "getQuote") + .mockRejectedValueOnce(unavailable) + .mockRejectedValue(fallback); + + await expect( + manager.getQuote({ + ...baseRequest, + inputMint, + outputMint, + inputTicker: inputMint === WSOL_MINT ? "SOL" : "USDC", + outputTicker: + outputMint === WSOL_MINT ? "SOL" : outputMint === tokenMint ? "USDC" : "TIMBA", + ...(payerKind + ? { + integrator: { + payerKind, + payer: "PAYER", + closeAuthority: "CLOSE", + referralAccount: "REF", + referralFee: 50, + }, + } + : {}), + }), + ).rejects.toBe(allowed ? fallback : unavailable); + + expect(getQuote).toHaveBeenCalledTimes(allowed ? 2 : 1); + if (allowed) { + expect(getQuote.mock.calls[1]?.[0]).toEqual({ + inputMint, + outputMint, + amount: baseRequest.amount, + taker: user.publicKey.toBase58(), + swapMode: undefined, + slippageBps: undefined, + }); + } + }, + ); }); From 4696b1c3aec6f68fab6426cd7319dbae85c21337 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Mon, 30 Nov 2026 00:02:22 -0300 Subject: [PATCH 281/410] test(database): check recovery lease and cleanup boundaries --- tests/game-database.pending-creation.test.ts | 49 ++++++++++++++++++++ 1 file changed, 49 insertions(+) diff --git a/tests/game-database.pending-creation.test.ts b/tests/game-database.pending-creation.test.ts index 3f9a6e64..9c7a61f9 100644 --- a/tests/game-database.pending-creation.test.ts +++ b/tests/game-database.pending-creation.test.ts @@ -406,6 +406,55 @@ describe("GameDatabase pending game creation lifecycle", () => { expect(db.clearPendingGameCreationIfState("PENDING_1", ["failed"])).toBe(true); expect(db.getPendingGameCreation("PENDING_1")).toBeNull(); }); + + test("caps a recovery error without releasing the current sender's lease", () => { + const game = "PENDING_1"; + const leaseEnds = NOW + 500; + const error = "provider timeout ".repeat(40); + db.savePendingGameCreation({ ...pendingInput(), state: "prepared" }); + expect(db.claimPendingGameCreationSubmission(game, "owner", leaseEnds, NOW)).toEqual({ + acquired: true, + }); + + expect( + db.setPendingGameCreationStateIfCurrent(game, ["submitted"], "unknown", { + submissionLeaseId: "owner", + error, + now: NOW + 1, + nextAttemptAt: NOW + 20, + }), + ).toBe(true); + expect(db.getPendingGameCreation(game)).toMatchObject({ + state: "unknown", + submission_lease_id: "owner", + submission_lease_expires_at: leaseEnds, + last_error: error.slice(0, 500), + next_attempt_at: NOW + 20, + updated_at: NOW + 1, + }); + expect(db.claimPendingGameCreationSubmission(game, "other", leaseEnds + 1, NOW + 2)).toEqual({ + acquired: false, + reason: "in-flight", + state: "unknown", + leaseExpiresAt: leaseEnds, + }); + }); + + test("deletes only the requested row if either terminal state still matches", () => { + const game = "PENDING_1"; + db.savePendingGameCreation({ ...pendingInput(), state: "failed" }); + db.savePendingGameCreation({ + ...pendingInput(), + gameAddress: "OTHER_GAME", + transactionSignature: "OTHER_SIG", + state: "confirmed", + }); + + expect(db.clearPendingGameCreationIfState(game, ["confirmed", "failed"])).toBe(true); + expect(db.clearPendingGameCreationIfState(game, ["confirmed", "failed"])).toBe(false); + expect(db.getPendingGameCreation(game)).toBeNull(); + expect(db.getPendingGameCreation("OTHER_GAME")?.state).toBe("confirmed"); + }); }); describe("replacing a proven-absent game transaction", () => { From c0d506797b43f07e926e4cb67ba270e24cace7e0 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Mon, 30 Nov 2026 00:03:55 -0300 Subject: [PATCH 282/410] test(wallet): cover transaction menu and prompt failures --- tests/wallet-transactions.flows.test.ts | 47 ++++++++++++++++++++++++- 1 file changed, 46 insertions(+), 1 deletion(-) diff --git a/tests/wallet-transactions.flows.test.ts b/tests/wallet-transactions.flows.test.ts index cfa41aff..8395b35a 100644 --- a/tests/wallet-transactions.flows.test.ts +++ b/tests/wallet-transactions.flows.test.ts @@ -20,7 +20,11 @@ import { wallet, } from "./helpers/bot-harness"; import { WSOL_MINT } from "../src/utils/constants"; -import { clearAllInputSessions, storePendingTransaction } from "../src/utils/user-state"; +import { + __test_listInputSessions, + clearAllInputSessions, + storePendingTransaction, +} from "../src/utils/user-state"; useBotHarness(); @@ -625,6 +629,47 @@ describe("input handlers guard their sessions", () => { }); describe("Telegram failures while showing wallet transaction menus", () => { + test.each([ + ["cmd_withdraw", "❌ Error loading send menu"], + ["cmd_wrap", "❌ Error loading wrap menu"], + ["cmd_unwrap", "❌ Error loading unwrap menu"], + ])("%s reports the failed menu without exposing wallet details", async (data, expectedAck) => { + const failure = new Error("private wallet lookup failed"); + stub(wallet, "getKeyPair", async () => { + throw failure; + }); + const errors = spyOn(console, "error").mockImplementation(() => {}); + try { + await press(data, { userId: USER }); + + expect(answers()).toEqual([expectedAck]); + expect(messageCalls()).toEqual([]); + expect(transfers).toEqual([]); + expect(errors.mock.calls).toContainEqual([`Error in ${data}:`, failure]); + } finally { + errors.mockRestore(); + } + }); + + test("does not open a wrap input session when Telegram cannot show the prompt", async () => { + failApiMethod("editMessageText", "Bad Request: chat not found"); + failApiMethod("sendMessage", "Forbidden: bot was blocked by the user", 403); + const errors = spyOn(console, "error").mockImplementation(() => {}); + try { + await press("wrap_custom", { userId: USER }); + + expect(answers()).toEqual(["❌ Error processing custom amount"]); + expect(__test_listInputSessions()).toEqual([]); + expect(transfers).toEqual([]); + expect(errors.mock.calls).toContainEqual([ + "Error in wrap_custom:", + expect.objectContaining({ error_code: 403 }), + ]); + } finally { + errors.mockRestore(); + } + }); + test("unwrap reports failure when the progress message cannot be shown", async () => { const unwraps: unknown[] = []; stub(wallet, "unwrapSol", async (...args: unknown[]) => { From c7752beaf06f7e9a6891698e579e190d17d8e740 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Mon, 30 Nov 2026 00:05:34 -0300 Subject: [PATCH 283/410] test(cache): bound timer cancellation to live handles --- tests/expiring-cache.test.ts | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/tests/expiring-cache.test.ts b/tests/expiring-cache.test.ts index 9b6d4e01..ec767572 100644 --- a/tests/expiring-cache.test.ts +++ b/tests/expiring-cache.test.ts @@ -43,6 +43,29 @@ test("replacing, deleting, and clearing cache entries cancel pending timers", () } }); +test("cancels a deleted entry's timer once and never sends a missing handle to the clock", () => { + vi.useFakeTimers({ now: 1_000 }); + const cancel = spyOn(globalThis, "clearTimeout"); + try { + const cache = createExpiringCache(20); + expect(cache.delete("missing")).toBe(false); + expect(cancel).not.toHaveBeenCalled(); + + cache.setWithTTL("price", 42); + expect(vi.getTimerCount()).toBe(1); + expect(cache.delete("price")).toBe(true); + expect(cache.delete("price")).toBe(false); + cache.clear(); + + expect(cancel).toHaveBeenCalledTimes(1); + expect(cancel.mock.calls[0]?.[0]).toBeDefined(); + expect(vi.getTimerCount()).toBe(0); + } finally { + cancel.mockRestore(); + vi.useRealTimers(); + } +}); + test("a real expiry timer does not keep the process alive", () => { const schedule = spyOn(globalThis, "setTimeout"); const cache = createExpiringCache(60_000); From 1a2f9ca5326802dd36aa405919467acdb197b579 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Mon, 30 Nov 2026 00:08:49 -0300 Subject: [PATCH 284/410] test(game): pin the production player poll interval --- tests/game.production-player-poll.test.ts | 56 +++++++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 tests/game.production-player-poll.test.ts diff --git a/tests/game.production-player-poll.test.ts b/tests/game.production-player-poll.test.ts new file mode 100644 index 00000000..9309c0fa --- /dev/null +++ b/tests/game.production-player-poll.test.ts @@ -0,0 +1,56 @@ +import { expect, test } from "bun:test"; +import { Api, Context } from "grammy"; +import { stubInstantTimers, withinTestDeadline } from "./helpers/timers"; + +// The player retry delay is chosen when the module loads. Keep this file +// isolated so its production import does not change other tests' delay. +const { GameManager } = await (async () => { + const originalEnvironment = process.env.NODE_ENV; + process.env.NODE_ENV = "production"; + try { + return await import("../src/utils/game"); + } finally { + if (originalEnvironment === undefined) delete process.env.NODE_ENV; + else process.env.NODE_ENV = originalEnvironment; + } +})(); + +test("uses four production delays before falling back to the player address", async () => { + const address = "BPFLoader1111111111111111111111111111111111"; + const reads: string[] = []; + const db = { + getPlayerTelegramId(publicKey: string): null { + reads.push(publicKey); + if (reads.length > 5) throw new Error("Unexpected sixth player lookup"); + return null; + }, + }; + const game = Reflect.construct(GameManager, [{}, {}, db]) as ReturnType< + typeof GameManager.getInstance + >; + const ctx = new Context({ update_id: 1 }, new Api("TEST_TOKEN"), { + id: 1, + is_bot: true, + first_name: "Test", + username: "test_bot", + can_join_groups: true, + can_read_all_group_messages: false, + supports_inline_queries: false, + can_connect_to_business: false, + has_main_web_app: false, + has_topics_enabled: false, + allows_users_to_create_topics: false, + can_manage_bots: false, + supports_join_request_queries: false, + }); + const timers = stubInstantTimers(); + try { + expect(await withinTestDeadline(game.getPlayerUsername(ctx, address), "player lookup")).toBe( + "BPFL…1111", + ); + expect(reads).toEqual(Array(5).fill(address)); + expect(timers.delays).toEqual([40, 40, 40, 40]); + } finally { + timers.restore(); + } +}); From f9aa2fd0ab2dc3eb0d75594cf71e4cea39ffdebe Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Mon, 30 Nov 2026 00:11:07 -0300 Subject: [PATCH 285/410] fix(ci): preserve mutation reports for both PR scopes --- scripts/mutants.test.ts | 39 +++++++++++++++++++++++++++++++++++++-- scripts/mutants.ts | 31 ++++++++++++++++++++++--------- 2 files changed, 59 insertions(+), 11 deletions(-) diff --git a/scripts/mutants.test.ts b/scripts/mutants.test.ts index 7f92602b..0466d968 100644 --- a/scripts/mutants.test.ts +++ b/scripts/mutants.test.ts @@ -1,8 +1,16 @@ import { describe, expect, test } from "bun:test"; -import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; -import { changedRanges, instrumentRanges, inScope, lived, partRanges, readGit } from "./mutants"; +import { + changedRanges, + instrumentRanges, + inScope, + lived, + partRanges, + readGit, + writeMutationOutputs, +} from "./mutants"; const scope = { roots: ["src"], @@ -11,6 +19,33 @@ const scope = { }; describe("mutants", () => { + test("keeps each complete report beside its own tally when a second scope is run", () => { + const dir = mkdtempSync(join(tmpdir(), "mutants-outputs-")); + try { + const changed = join(dir, "build", "mutants"); + const trial = join(dir, "build", "mutants-part"); + const changedReport = '{"files":{"src/changed.ts":{"mutants":[]}}}\n'; + const trialReport = '{"files":{"src/trial.ts":{"mutants":[]}}}\n'; + + writeMutationOutputs(changed, ["changed fixture"], "3 of 4", changedReport); + writeMutationOutputs(trial, ["trial fixture"], "1 of 2", trialReport); + + expect(readFileSync(join(changed, "mutation.json"), "utf8")).toBe(changedReport); + expect(readFileSync(join(changed, "lived.txt"), "utf8")).toBe("changed fixture\n"); + expect(readFileSync(join(changed, "tally.txt"), "utf8")).toBe("3 of 4\n"); + expect(readFileSync(join(trial, "mutation.json"), "utf8")).toBe(trialReport); + expect(readFileSync(join(trial, "lived.txt"), "utf8")).toBe("trial fixture\n"); + expect(readFileSync(join(trial, "tally.txt"), "utf8")).toBe("1 of 2\n"); + + writeMutationOutputs(changed, [], "0 of 0", undefined); + expect(existsSync(join(changed, "mutation.json"))).toBe(false); + expect(readFileSync(join(changed, "tally.txt"), "utf8")).toBe("0 of 0\n"); + expect(readFileSync(join(trial, "mutation.json"), "utf8")).toBe(trialReport); + } finally { + rmSync(dir, { recursive: true, force: true }); + } + }); + test("only source the coverage gate counts is mutated", () => { expect(inScope("src/bot.ts", scope)).toBe(true); expect(inScope("src/utils/amount.ts", scope)).toBe(true); diff --git a/scripts/mutants.ts b/scripts/mutants.ts index 6bd039c3..52b04001 100644 --- a/scripts/mutants.ts +++ b/scripts/mutants.ts @@ -7,9 +7,9 @@ * bun run scripts/mutants.ts diff HEAD^1 --out build/mutants * * Only what coverage-scope.json counts as source is changed. Lists what lived by file and line; - * --out also writes it to lived.txt and the tally ("3 of 10") to tally.txt there. Exits 0 once - * it got to its tally, whatever lived; only a broken run fails. Stryker's full report is in - * reports/mutation/. + * --out also saves lived.txt, tally.txt ("3 of 10"), and the full mutation.json there. Exits 0 + * once it got to its tally, whatever lived; only a broken run fails. The latest Stryker report + * is also in reports/mutation/. */ import { spawnSync } from "node:child_process"; import { @@ -199,6 +199,21 @@ function sourceFiles(scope: Scope): { file: string; lines: number }[] { })); } +export function writeMutationOutputs( + out: string, + rows: string[], + tally: string, + report: string | undefined, +): void { + mkdirSync(out, { recursive: true }); + writeFileSync(join(out, "lived.txt"), rows.map((row) => `${row}\n`).join("")); + writeFileSync(join(out, "tally.txt"), `${tally}\n`); + // The setup trial reuses Stryker's default path. Keep each run beside its own tally. + const outputReport = join(out, "mutation.json"); + if (report === undefined) rmSync(outputReport, { force: true }); + else writeFileSync(outputReport, report); +} + function main(argv: string[]): number { const usage = "Usage: bun run scripts/mutants.ts diff BASE | part K N [--out DIR]"; const out = argv.includes("--out") ? argv[argv.indexOf("--out") + 1] : undefined; @@ -217,6 +232,7 @@ function main(argv: string[]): number { } let rows: string[] = []; let total = 0; + let report: string | undefined; if (ranges.length === 0) { console.log("No source lines to mutate."); } else { @@ -235,16 +251,13 @@ function main(argv: string[]): number { console.error(`Stryker stopped (exit ${run.status ?? run.signal}) before its report.`); return 1; } - ({ rows, total } = lived(JSON.parse(readFileSync(REPORT, "utf8")), ranges)); + report = readFileSync(REPORT, "utf8"); + ({ rows, total } = lived(JSON.parse(report), ranges)); } rows.forEach((row) => console.log(row)); const tally = `${total - rows.length} of ${total}`; console.log(`${tally} changes caught by a test.`); - if (out) { - mkdirSync(out, { recursive: true }); - writeFileSync(join(out, "lived.txt"), rows.map((row) => `${row}\n`).join("")); - writeFileSync(join(out, "tally.txt"), `${tally}\n`); - } + if (out) writeMutationOutputs(out, rows, tally, report); return 0; } From 8220e9f89e8695660482be82673accfeff72d5b2 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Mon, 30 Nov 2026 00:15:59 -0300 Subject: [PATCH 286/410] test(game): check definitive errors and the one-second boundary --- ...game.create-failure-classification.test.ts | 42 +++++++++++++++---- tests/game.rate-limit-window.test.ts | 1 + 2 files changed, 36 insertions(+), 7 deletions(-) diff --git a/tests/game.create-failure-classification.test.ts b/tests/game.create-failure-classification.test.ts index eb883a6e..91bb2c38 100644 --- a/tests/game.create-failure-classification.test.ts +++ b/tests/game.create-failure-classification.test.ts @@ -4,6 +4,7 @@ import { GameManager } from "../src/utils/game"; import { PublicKey, Keypair, TransactionInstruction } from "#solana"; import { TOKEN_PROGRAM_ID } from "#token"; import { decodeGameTransaction } from "../src/utils/game-transaction"; +import type { GameDatabase } from "../src/utils/game-database"; const TEST_ORACLE = await Keypair.generate(); @@ -14,8 +15,7 @@ async function signGameTransactionAsOracle(txBase64: string): Promise { } function resetGM() { - // @ts-ignore - GameManager["instance"] = undefined; + GameManager.resetForTest(); } function getGameManager(...args: Parameters): GameManager { @@ -153,7 +153,9 @@ const makeSubmittedCreationHarness = async (sendError: unknown) => { throw sendError; }), }); - const finishPendingGameCreationSubmission = vi.fn(() => true); + const finishPendingGameCreationSubmission = vi.fn< + GameDatabase["finishPendingGameCreationSubmission"] + >(() => true); const db = { savePlayerMapping: () => {}, saveGame: vi.fn(), @@ -208,14 +210,24 @@ describe("GameManager.createGame definitive failure classification", () => { resetGM(); }); + const cyclicTransportCause: { cause?: unknown; logs: unknown[] } = { + logs: [null, 404, "provider disconnected while reading the response"], + }; + cyclicTransportCause.cause = cyclicTransportCause; + const cases: Array<{ name: string; error: unknown; state: "failed" | "unknown" }> = [ { - name: "a plain string cause naming a program failure", + name: "a plain string cause naming a simulation failure", error: Object.assign(new Error("send failed"), { - cause: "Transaction simulation failed: custom program error: 0x1", + cause: "Transaction simulation failed at instruction 1", }), state: "failed", }, + { + name: "only a custom program error in a nested Error", + error: new Error("send failed", { cause: new Error("CUSTOM PROGRAM ERROR: 0x1") }), + state: "failed", + }, { name: "string log lines that report insufficient funds", error: Object.assign(new Error("send failed"), { @@ -223,11 +235,28 @@ describe("GameManager.createGame definitive failure classification", () => { }), state: "failed", }, + ...[ + "insufficient lamports", + "invalid transaction", + "invalid signature", + "transaction failed", + "program failed to complete", + ].map((message) => ({ name: message, error: message, state: "failed" as const })), + { + name: "an RPC diagnostic split between the message and logs", + error: Object.assign(new Error("simulation"), { logs: ["failed at instruction 1"] }), + state: "failed", + }, { name: "a transport error with no definitive marker", error: Object.assign(new Error("socket hang up"), { cause: "connection reset by peer" }), state: "unknown", }, + { + name: "cyclic network diagnostics with no definitive marker", + error: new Error("socket hang up", { cause: cyclicTransportCause }), + state: "unknown", + }, ]; for (const { name, error, state } of cases) { @@ -241,8 +270,7 @@ describe("GameManager.createGame definitive failure classification", () => { await attemptCreate(gm); expect(finishPendingGameCreationSubmission).toHaveBeenCalledTimes(1); - const call = finishPendingGameCreationSubmission.mock.calls[0] as unknown[]; - expect(call[2]).toBe(state); + expect(finishPendingGameCreationSubmission.mock.calls[0]?.[2]).toBe(state); } finally { errorSpy.mockRestore(); } diff --git a/tests/game.rate-limit-window.test.ts b/tests/game.rate-limit-window.test.ts index efe719af..8d8a0f2e 100644 --- a/tests/game.rate-limit-window.test.ts +++ b/tests/game.rate-limit-window.test.ts @@ -15,6 +15,7 @@ describe("formatRateLimitWindow", () => { }); test("reports longer windows as a duration", () => { + expect(formatRateLimitWindow(1_000)).toBe("1s"); expect(formatRateLimitWindow(120_000)).toBe("2m"); }); }); From bec1a24d413b663c002c5d12819b222271e38a31 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Mon, 30 Nov 2026 00:16:54 -0300 Subject: [PATCH 287/410] test(game): isolate the production polling module from Stryker cache --- tests/game.production-player-poll.test.ts | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/tests/game.production-player-poll.test.ts b/tests/game.production-player-poll.test.ts index 9309c0fa..f339aeb8 100644 --- a/tests/game.production-player-poll.test.ts +++ b/tests/game.production-player-poll.test.ts @@ -2,13 +2,16 @@ import { expect, test } from "bun:test"; import { Api, Context } from "grammy"; import { stubInstantTimers, withinTestDeadline } from "./helpers/timers"; -// The player retry delay is chosen when the module loads. Keep this file -// isolated so its production import does not change other tests' delay. +// The player retry delay is chosen when the module loads. The mutation +// runner can already have the default import cached from another test. +await import("../src/utils/game"); const { GameManager } = await (async () => { const originalEnvironment = process.env.NODE_ENV; process.env.NODE_ENV = "production"; try { - return await import("../src/utils/game"); + // A query gives Bun a separate module instance of the same source file. + const productionModule = "../src/utils/game.ts?production-player-poll"; + return (await import(productionModule)) as typeof import("../src/utils/game"); } finally { if (originalEnvironment === undefined) delete process.env.NODE_ENV; else process.env.NODE_ENV = originalEnvironment; From d4afcfa6cc964acac54e5bb443ebfaa3f51fe2b0 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Mon, 30 Nov 2026 00:20:58 -0300 Subject: [PATCH 288/410] test(game): check orphaned giveaway expiry and grace limits --- tests/game-manager.orphaned-scan.test.ts | 64 +++++++++++++++++++++--- 1 file changed, 56 insertions(+), 8 deletions(-) diff --git a/tests/game-manager.orphaned-scan.test.ts b/tests/game-manager.orphaned-scan.test.ts index 92b0f0d2..1f8f2fd5 100644 --- a/tests/game-manager.orphaned-scan.test.ts +++ b/tests/game-manager.orphaned-scan.test.ts @@ -1,16 +1,10 @@ -import { describe, test, expect } from "bun:test"; +import { describe, test, expect, spyOn } from "bun:test"; import { GameManager } from "../src/utils/game"; import { PublicKey } from "#solana"; -function resetGM() { - // reset singleton - // @ts-ignore - GameManager["instance"] = undefined; -} - describe("GameManager orphaned scan helpers", () => { test("findOrphanedGames returns unknown games from chain", async () => { - resetGM(); + GameManager.resetForTest(); const first = new PublicKey("BPFLoader1111111111111111111111111111111111").toBase58(); const second = new PublicKey("BPFLoader2111111111111111111111111111111111").toBase58(); const program = { @@ -30,3 +24,57 @@ describe("GameManager orphaned scan helpers", () => { expect(res[0]!.address).toBe(second); }); }); + +describe("orphaned giveaway cleanup boundaries", () => { + test.each([ + ["at the expiry second", 0, 1, 2, false], + ["below the participant minimum after expiry", 1, 1, 2, true], + ["empty with no minimum after expiry", 1, 0, 0, true], + ["filled at the end of the oracle window", 86_400, 2, 2, false], + ["filled one second after the oracle window", 86_401, 2, 2, true], + ] as const)("processes a giveaway %s", async (_label, afterExpiry, tickets, minimum, cancel) => { + const game = new PublicKey("BPFLoader1111111111111111111111111111111111"); + const knownGame = new PublicKey("BPFLoader2111111111111111111111111111111111"); + const createdAt = 1_700_000_000; + const timeout = 60; + const account = { + gameType: { giveaway: {} }, + createdAt, + timeout, + ticketsCount: tickets, + minTickets: minimum, + maxTickets: 10, + }; + const reads: string[] = []; + const program = { + account: { + game: { + all: async () => [ + { publicKey: knownGame, account }, + { publicKey: game, account }, + ], + fetch: async (address: PublicKey) => { + reads.push(address.toBase58()); + return account; + }, + }, + }, + }; + const db = { gameExists: (address: string) => address === knownGame.toBase58() }; + const manager = Reflect.construct(GameManager, [program, {}, db]) as GameManager; + const clock = spyOn(Date, "now").mockReturnValue((createdAt + timeout + afterExpiry) * 1_000); + const close = spyOn(manager, "cancelGameWithPlayerKeys").mockResolvedValue({ + success: true, + tx: "FAKE_CLOSE", + }); + try { + await manager.scanBlockchainForOrphanedGames(); + + expect(reads).toEqual([game.toBase58()]); + expect(close.mock.calls).toEqual(cancel ? [[game, "giveaway"]] : []); + } finally { + close.mockRestore(); + clock.mockRestore(); + } + }); +}); From c497603168f47799fdd6f07f768107b35d1dc6c3 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Mon, 30 Nov 2026 00:24:36 -0300 Subject: [PATCH 289/410] test(callbacks): reject partial settings and malformed amounts --- tests/chat-defaults.handler.test.ts | 21 +++++++++++++++++++++ tests/game-setup.flows.test.ts | 23 +++++++++++++++++++++++ 2 files changed, 44 insertions(+) diff --git a/tests/chat-defaults.handler.test.ts b/tests/chat-defaults.handler.test.ts index fb65967b..571dc0e9 100644 --- a/tests/chat-defaults.handler.test.ts +++ b/tests/chat-defaults.handler.test.ts @@ -1621,6 +1621,27 @@ describe("chat defaults menus and inputs", () => { ]); }); + test.each([ + "chat_defaults_set_privacy_giveaway_private_stale", + "old_chat_defaults_set_privacy_coinflip_clear", + "old_chat_defaults_set_join_external_off", + "chat_defaults_set_join_external_off_stale", + ])("does not apply a partially matching settings callback %s", async (data) => { + const h = setup(); + chatDb.upsertChatGameSettings(99, { + coinflip_default_privacy: "private", + giveaway_default_privacy: "public", + join_notifications_external: true, + set_by_telegram_id: "456", + }); + const prior = chatDb.getChatGameSettings(99); + + expect(await h.press(data)).toBe(false); + expect(chatDb.getChatGameSettings(99)).toEqual(prior); + expect(h.answers).toEqual([]); + expect(h.menus).toEqual([]); + }); + test("without a usable actor the group command leaves settings intact", async () => { const h = setup(); h.tokenManager.setChatDefaultToken(99, "mint", "AAA", "1"); diff --git a/tests/game-setup.flows.test.ts b/tests/game-setup.flows.test.ts index 16816000..d1d7645a 100644 --- a/tests/game-setup.flows.test.ts +++ b/tests/game-setup.flows.test.ts @@ -128,6 +128,29 @@ const replyTo = (messageId: number, text: string, userId = CREATOR) => sendText(text, { ...group(userId), replyTo: messageId }); describe("interactive game setup", () => { + test("rejects a broken compact amount callback and identifies the route that rejected it", async () => { + const setupId = await openSetup(); + const key = `${CHAT}_${setupId}`; + const original = getGameSetupSession(key); + const brokenCallback = "ga|invalid"; + expect(original).toBeDefined(); + resetCalls(); + const warnings = spyOn(console, "warn").mockImplementation(() => {}); + try { + await press(brokenCallback, { ...group(), messageId: setupId }); + + expect(answers()).toEqual(["❌ Unable to process action"]); + expect(messageCalls()).toEqual([]); + expect(getGameSetupSession(key)).toEqual(original); + expect(createCalls).toEqual([]); + expect(warnings.mock.calls).toContainEqual([ + "amount_compact: unable to resolve creator id from callback", + ]); + } finally { + warnings.mockRestore(); + } + }); + test("amount, players and advanced options lead to a created game", async () => { const setupId = await openSetup(); await clickLabel("5", setupId); From e8a6d418eb27869e4e20bd8b8aff7e4da36dc2f6 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Mon, 30 Nov 2026 00:28:52 -0300 Subject: [PATCH 290/410] test(evm): keep unknown tokens out of the USD route --- src/evm/bot.test.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/src/evm/bot.test.ts b/src/evm/bot.test.ts index a830ae26..37b0a3e8 100644 --- a/src/evm/bot.test.ts +++ b/src/evm/bot.test.ts @@ -756,6 +756,7 @@ describe("EVM game commands", () => { test.each([ ["unknown token", "/egiveaway 1 TKN"], + ["unknown token with a USD amount", "/egiveaway $1 TKN"], ["too many players", "/egiveaway 1 TEST 101"], ] as const)("gives the giveaway usage and creates nothing for %s", async (_case, text) => { await h.text(text); From 8eb2cf47ccb132f1a92406ea1b152692907b8899 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Mon, 30 Nov 2026 00:30:25 -0300 Subject: [PATCH 291/410] test(evm): verify restored setup controls and screen state --- src/evm/setup.test.ts | 51 ++++++++++++++++++++++++++++++++++++++----- 1 file changed, 46 insertions(+), 5 deletions(-) diff --git a/src/evm/setup.test.ts b/src/evm/setup.test.ts index 66d0d582..f697caa2 100644 --- a/src/evm/setup.test.ts +++ b/src/evm/setup.test.ts @@ -373,6 +373,49 @@ async function toConfirm(f: ReturnType, players: string) { expect(f.labels()[0]).toBe("✅ Create Game"); } +function storedSetup(f: ReturnType): Setup { + const row = f.store.db + .query<{ body: string }, [string]>("SELECT body FROM setups WHERE id=?") + .get("1"); + if (!row) throw new Error("Expected a saved setup"); + return JSON.parse(row.body) as Setup; +} + +test.each([ + ["cancel_game_setup_1", "cancelled"], + ["back_to_players_coinflip_1", "players"], + ["custom_players_coinflip_1_1", "prompted"], + ["", "rejected"], +] as const)("restores a saved setup with action %p", async (action, outcome) => { + const f = fixture(); + await toConfirm(f, "2"); + const original = storedSetup(f); + const callback = f.buttonAt(CONFIRM.create); + const updated = { ...original, actions: [action, ...original.actions.slice(1)] }; + f.store.db.query("UPDATE setups SET body=? WHERE id=?").run(JSON.stringify(updated), updated.id); + f.restart(); + + await f.click(callback); + + expect(f.submitted).toEqual([]); + if (outcome === "cancelled") { + expect(f.visible().text).toBe("Game setup cancelled."); + await f.click(callback); + expect(f.answers.at(-1)).toBe("This setup is unavailable."); + } else if (outcome === "players") { + expect(f.labels()).toContain("📊 Custom Players"); + expect(storedSetup(f).screen).toBe("players"); + } else if (outcome === "prompted") { + expect(f.sent.at(-1)).toBe("Reply with the maximum number of players (up to 100)."); + expect(storedSetup(f).input).toBe("players"); + } else { + expect(f.answers.at(-1)).toBe( + "Unable to continue. Check the amount, players and wallet balance.", + ); + expect(storedSetup(f)).toEqual(updated); + } +}); + test("cancel closes the setup and retires its buttons", async () => { const f = fixture(); await f.open(); @@ -427,11 +470,7 @@ test("a saved coinflip decrement cannot lower the minimum below two players", as const decrease = f.buttonAt(CONFIRM.minMinus50); // Model a durable setup restored with an older menu for the same generation. - const row = f.store.db - .query<{ body: string }, [string]>("SELECT body FROM setups WHERE id=?") - .get("1"); - if (!row) throw new Error("Expected a saved setup"); - const setup = JSON.parse(row.body) as Setup; + const setup = storedSetup(f); f.store.db .query("UPDATE setups SET body=? WHERE id=?") .run(JSON.stringify({ ...setup, minPlayers: 2 }), "1"); @@ -468,6 +507,8 @@ test("custom player counts are validated and applied", async () => { await f.reply("7"); expect(f.visible().text).toContain("Network: Anvil"); + expect(storedSetup(f)).toMatchObject({ screen: "confirm", players: 7 }); + f.restart(); await f.click(f.buttonAt(CONFIRM.create)); expect(f.submitted[0]).toMatchObject({ players: 7, minPlayers: 2 }); }); From 7c9c4c3939d074d6a2b9d92b56815eb089dc878b Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Mon, 30 Nov 2026 00:33:45 -0300 Subject: [PATCH 292/410] refactor(evm): remove unreachable direct amount fallbacks --- src/evm/bot.test.ts | 57 +++++++++++++++++++++++++++++++++++++++++++++ src/evm/bot.ts | 9 ++----- 2 files changed, 59 insertions(+), 7 deletions(-) diff --git a/src/evm/bot.test.ts b/src/evm/bot.test.ts index 37b0a3e8..4fd3db9a 100644 --- a/src/evm/bot.test.ts +++ b/src/evm/bot.test.ts @@ -767,6 +767,63 @@ describe("EVM game commands", () => { expect(h.readContract).not.toHaveBeenCalled(); }); + test.each(["/egiveaway", "/egiveaway TEST"])( + "the exact EVM command %s opens setup without reading a balance", + async (command) => { + await h.text(command); + + const menu = h.calls.find((call) => call.method === "editMessageText"); + expect(menu?.payload.text).toContain("Token: TEST (Anvil)"); + expect(h.store.pending()).toEqual([]); + expect(h.readContract).not.toHaveBeenCalled(); + }, + ); + + test.each(["", " TEST"])( + "a direct EVM amount with token suffix %p keeps the first raw unit and player index", + async (tokenSuffix) => { + const amount = "0.000000000000000001"; + const account = h.runtime.service.account("1").address; + h.balances.set(account, 1n); + const createdAt = 1_700_000_000_001; + const clock = spyOn(Date, "now").mockReturnValue(createdAt); + try { + await h.text(`/egiveaway ${amount}${tokenSuffix} 1 public`); + } finally { + clock.mockRestore(); + } + + const actions = h.store.pending(); + expect(actions).toHaveLength(1); + const [pending] = actions; + if (!pending) throw new Error("Expected a single queued giveaway"); + expect(JSON.parse(pending.body)).toEqual({ + token: tokenAddress, + amount: "1", + gameType: 1, + createdAt, + minPlayers: 1, + maxPlayers: 1, + isPrivate: false, + timeout: 3_600, + }); + expect(h.replies()).toEqual(["⏳ Creating game…"]); + }, + ); + + test.each(["0", "-1", "1e2"])( + "the direct EVM route refuses amount %s before reading a balance", + async (amount) => { + await h.text(`/egiveaway ${amount} TEST 1`); + + expect(h.replies()).toEqual([ + "Use /ga AMOUNT [TOKEN] [PLAYERS] [private]. Check the token minimum and your wallet balance.", + ]); + expect(h.store.pending()).toEqual([]); + expect(h.readContract).not.toHaveBeenCalled(); + }, + ); + test("giveaways record players, visibility and the chat default token", async () => { useEvm(); h.store.setToken("1", usdcAddress); diff --git a/src/evm/bot.ts b/src/evm/bot.ts index b84deb21..f8dbbce0 100644 --- a/src/evm/bot.ts +++ b/src/evm/bot.ts @@ -456,12 +456,7 @@ export function registerEvmBot( return; } const inferred = inferMaxPlayers( - [ - command, - amountText ?? "", - ...(symbol ? [symbol] : []), - ...(playersText ? [playersText] : []), - ], + [command, amountText, ...(symbol ? [symbol] : []), ...(playersText ? [playersText] : [])], 1, Boolean(symbol), settings.maxPlayers, @@ -474,7 +469,7 @@ export function registerEvmBot( { type, tokenMint: token.address, - amount: amountText ?? formatTokenAmount(BigInt(token.minimumAmount), token.decimals), + amount: amountText, minPlayers: Math.min(settings.minPlayers, players), maxPlayers: players, timeoutMinutes: settings.timeout / 60, From 8bc6d8e1e9adffe95b5046e346447da2809cb8e7 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Mon, 30 Nov 2026 00:35:09 -0300 Subject: [PATCH 293/410] test(database): check repeat message migration and diagnostics --- tests/game-database.schema.test.ts | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/tests/game-database.schema.test.ts b/tests/game-database.schema.test.ts index ae4e72e1..c62016eb 100644 --- a/tests/game-database.schema.test.ts +++ b/tests/game-database.schema.test.ts @@ -105,6 +105,34 @@ describe("GameDatabase schema upgrades and failure handling", () => { expect(errorSpy).not.toHaveBeenCalled(); }); + test("reopening preserves the migrated target without retrying the old insert", () => { + const db = open(); + db.saveGame("TRACKED_GAME", "111", 5, "coinflip"); + db.saveGameMessage("TRACKED_GAME", 9, 77); + const raw = (db as unknown as RawDb).db; + raw + .query("UPDATE games SET chat_id = ?, message_id = ? WHERE game_address = ?") + .run(77, 8, "TRACKED_GAME"); + + const reopened = open(); + + expect(reopened.getGameMessages("TRACKED_GAME")).toEqual([{ chatId: 77, messageId: 9 }]); + expect(errorSpy).not.toHaveBeenCalled(); + }); + + test("identifies the failed row count when the message table cannot be read", () => { + seedLegacy("CREATE VIEW game_messages AS SELECT * FROM missing_game_messages;"); + + const db = open(); + + expect(errorSpy.mock.calls.map(([message]) => message)).toEqual([ + "[Game DB] Error during counting game messages:", + "Failed to ensure game_messages schema:", + ]); + db.saveGame("AFTER_READ_ERROR", "111", 5, "coinflip"); + expect(db.getGame("AFTER_READ_ERROR")?.creator_telegram_id).toBe("111"); + }); + const brokenViews: Array<[string, string, string]> = [ [ "game_participants", @@ -151,6 +179,7 @@ describe("GameDatabase schema upgrades and failure handling", () => { const messages = errorSpy.mock.calls.map((call) => call[0]); expect(messages).toContain("Failed to ensure games schema:"); + expect(messages).toContain("[Game DB] Error during migrating game messages:"); expect(messages).toContain("Failed to ensure game_messages schema:"); }); }); From ad6f90e0658bae94f7c58f03dcbc6c3fe17801a7 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Mon, 30 Nov 2026 00:44:00 -0300 Subject: [PATCH 294/410] test(lightning): cover zero quotes and paid deposit cards --- tests/lightning-handler.test.ts | 47 +++++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) diff --git a/tests/lightning-handler.test.ts b/tests/lightning-handler.test.ts index 35c319da..d3f327fd 100644 --- a/tests/lightning-handler.test.ts +++ b/tests/lightning-handler.test.ts @@ -447,6 +447,53 @@ describe("deposit cards", () => { ]); }); + test("a completed payout with a zero quote shows the settlement without a USD estimate", () => { + const completed = depositMessage( + card("completed", { + ...providerOrder, + status: "DONE", + to: { ...providerOrder.to, amount: "0", tx: { id: "settled", amount: "0.18" } }, + }), + ); + expect(completed.text).toBe("✅ Deposit received\n\n0.18 SOL arrived in your wallet."); + expect(completed.keyboard.inline_keyboard).toEqual([ + [{ text: "View transaction", url: "https://solscan.io/tx/settled" }], + [ + { text: "← Deposit", callback_data: "wallet_deposit" }, + { text: "← Wallet", callback_data: "main_wallet" }, + ], + ]); + }); + + test("a completed saved deposit without an order shows the stored SOL amount", () => { + const completed = depositMessage(card("completed", null)); + expect(completed.text).toBe("✅ Deposit received\n\n0.24 SOL arrived in your wallet."); + expect(completed.keyboard.inline_keyboard).toEqual([ + [ + { text: "← Deposit", callback_data: "wallet_deposit" }, + { text: "← Wallet", callback_data: "main_wallet" }, + ], + ]); + }); + + test.each(["active", "settling"] as const)( + "a provider exchange in the %s state does not offer a second payment", + (state) => { + const { text, keyboard } = depositMessage( + card(state, { ...providerOrder, status: "EXCHANGE" }), + ); + expect(text).toBe( + "⏳ Deposit processing\n\nPayment received. Waiting for SOL to arrive.\nYou receive: ≈ 0.36 SOL (≈ $30.00)\n\nThis card updates automatically.", + ); + expect(keyboard.inline_keyboard.flat()).toEqual([ + { text: "Open FixedFloat order", url: "https://ff.io/order/TEST01" }, + { text: "🔁 Refresh", callback_data: "ln_status:private-card" }, + { text: "← Deposit", callback_data: "wallet_deposit" }, + { text: "← Wallet", callback_data: "main_wallet" }, + ]); + }, + ); + test.each(["unknown", "creating", "failed", "expired"] as const)( "never displays payment instructions in the %s state", (state) => { From f61fc33c655652b0903d3bd418c72f800694a1da Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Mon, 30 Nov 2026 00:45:08 -0300 Subject: [PATCH 295/410] refactor(lightning): bound deposit prompt cleanup --- src/handlers/lightning.ts | 15 +++++------ src/utils/user-state.ts | 8 ++++++ tests/lightning-handler.test.ts | 46 ++++++++++++++++++++++++++++++++- 3 files changed, 59 insertions(+), 10 deletions(-) diff --git a/src/handlers/lightning.ts b/src/handlers/lightning.ts index ef5e22d2..40131fbe 100644 --- a/src/handlers/lightning.ts +++ b/src/handlers/lightning.ts @@ -16,6 +16,7 @@ import { findInputSession, getInputSession, clearInputSession, + clearInputSessionsWhere, markInputSessionProcessing, clearInputSessionProcessing, } from "../utils/user-state"; @@ -150,16 +151,12 @@ export function registerLightningDeposits( ctx.from && (ctx.callbackQuery || ctx.message?.text?.startsWith("/")) ) { - let pending; - while ( - (pending = findInputSession( - (_key, session) => - session.type === "deposit_usd" && session.initiatorId === String(ctx.from!.id), - )) - ) - clearInputSession(pending.key); + const owner = String(ctx.from.id); + clearInputSessionsWhere( + (_key, session) => session.type === "deposit_usd" && session.initiatorId === owner, + ); const messageId = ctx.callbackQuery?.message?.message_id; - if (messageId) store?.detachMessage(String(ctx.from.id), messageId); + if (messageId) store?.detachMessage(owner, messageId); } await next(); }); diff --git a/src/utils/user-state.ts b/src/utils/user-state.ts index ace3c37c..b0a9e959 100644 --- a/src/utils/user-state.ts +++ b/src/utils/user-state.ts @@ -252,6 +252,14 @@ const listNamespaceEntries = (namespace: string): Array<[string, T]> => { return results; }; +export const clearInputSessionsWhere = ( + predicate: (key: string, session: InputSessionState) => boolean, +): void => { + for (const [key, session] of listNamespaceEntries(INPUT_SESSION_NAMESPACE)) { + if (predicate(key, session)) clearInputSession(key); + } +}; + export const __test_listGameSetupSessions = () => listNamespaceEntries(GAME_SETUP_NAMESPACE); diff --git a/tests/lightning-handler.test.ts b/tests/lightning-handler.test.ts index d3f327fd..a28de472 100644 --- a/tests/lightning-handler.test.ts +++ b/tests/lightning-handler.test.ts @@ -13,7 +13,12 @@ import { } from "../src/handlers/lightning"; import { FixedFloatClient, type FixedFloatOrder } from "../src/services/lightning/fixedfloat"; import { DepositStore, type Deposit } from "../src/services/lightning/store"; -import { clearAllInputSessions } from "../src/utils/user-state"; +import { + clearAllInputSessions, + getInputSession, + markInputSessionProcessing, + setInputSession, +} from "../src/utils/user-state"; import type { WalletManager } from "../src/utils/wallet"; const address = "So11111111111111111111111111111111111111112"; @@ -297,6 +302,45 @@ describe("deposit access", () => { expect(h.text()).toBe("Lightning deposits are temporarily unavailable."); }); }); + + test.each(["private callback", "private command", "group callback"] as const)( + "only private deposit navigation removes the owner's pending quotes via a %s", + async (navigation) => { + await withHarness({}, async (h) => { + const ownerId = String(owner.id); + for (const [key, initiatorId, type] of [ + ["321_40", ownerId, "deposit_usd"], + ["321_41", ownerId, "deposit_usd"], + ["999_42", "999", "deposit_usd"], + ["321_43", ownerId, "wrap_custom_amount"], + ] as const) { + setInputSession(key, { type, initiatorId }); + } + expect(markInputSessionProcessing("321_41", "old-request")).toBe(true); + const otherDeposit = getInputSession("999_42"); + const wrap = getInputSession("321_43"); + + if (navigation === "private command") await h.send("/deposit"); + else + await h.click( + "wallet_lightning", + navigation === "group callback" ? groupChat : privateChat, + ); + + if (navigation === "group callback") { + expect(getInputSession("321_40")).toMatchObject({ type: "deposit_usd" }); + expect(getInputSession("321_41")).toMatchObject({ processingBy: "old-request" }); + expect(h.answers()).toEqual(["Open a private chat with the bot to deposit."]); + } else { + expect(getInputSession("321_40")).toBeUndefined(); + expect(getInputSession("321_41")).toBeUndefined(); + } + expect(getInputSession("999_42")).toEqual(otherDeposit); + expect(getInputSession("321_43")).toEqual(wrap); + expect(h.store!.active(ownerId)).toBeNull(); + }); + }, + ); }); describe("quote failures", () => { From ea92703dcbb68c02c3857f1f0f1c81cbfec88e04 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Mon, 30 Nov 2026 00:50:05 -0300 Subject: [PATCH 296/410] refactor(mentions): bound both directions of UTF-16 scans --- src/utils/user-mention.ts | 5 +++-- tests/user-mention.test.ts | 25 +++++++++++++++++++++++++ 2 files changed, 28 insertions(+), 2 deletions(-) diff --git a/src/utils/user-mention.ts b/src/utils/user-mention.ts index 6660d3e6..532d4b29 100644 --- a/src/utils/user-mention.ts +++ b/src/utils/user-mention.ts @@ -221,7 +221,8 @@ export const findNamedUsers = ( // Someone who cannot be placed goes last and keeps every word. found.push({ person, position: first === -1 ? words.length : first }); if (range) { - for (let index = range.start; index < Math.min(range.end, text.length); index += 1) { + const end = Math.min(range.end, text.length); + for (let index = range.start; index >= range.start && index < end; index += 1) { marked.add(index); } } @@ -231,7 +232,7 @@ export const findNamedUsers = ( spans.forEach((span, position) => { const word = words[position]!; let unmarked = ""; - for (let index = span.start; index < span.end; index += 1) { + for (let index = span.start; index >= span.start && index < span.end; index += 1) { unmarked += marked.has(index) ? " " : text.charAt(index); } const mentioned = unmarked !== word; diff --git a/tests/user-mention.test.ts b/tests/user-mention.test.ts index 8074397d..b6e84d60 100644 --- a/tests/user-mention.test.ts +++ b/tests/user-mention.test.ts @@ -283,6 +283,31 @@ describe("findNamedUsers", () => { }); }); + test("uses Telegram's UTF-16 offsets without consuming the adjacent typed name or token", () => { + const user = { id: 1, is_bot: false, first_name: "Ana", username: "ana" }; + const text = "/cf 5 🧪Ana,@bob USDC @cora"; + + expect(findNamedUsers(command(text, [picked(text, "🧪Ana", user)]))).toEqual({ + users: [{ user, username: "@ana", label: "🧪Ana" }, typed("@bob"), typed("@cora")], + args: ["/cf", "5", "USDC"], + positions: [0, 1, 3], + }); + }); + + test("keeps the original argument when a malformed fractional range marks no character", () => { + const user = { id: 1, is_bot: false, first_name: "Zed" }; + + expect( + findNamedUsers( + command("/cf 5 Zed USDC", [{ type: "text_mention", offset: 6.5, length: 1, user }]), + ), + ).toEqual({ + users: [{ user, username: null, label: "Z" }], + args: ["/cf", "5", "Zed", "USDC"], + positions: [0, 1, 2, 3], + }); + }); + test("names Telegram did not mark, beside a mention in the same word, are typed", () => { const alice = { user: null, username: "@alice", label: "@alice" }; for (const [text, users] of [ From dc77346a696a0f8f8a06b1d716105dd10a7e35c2 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Mon, 30 Nov 2026 00:50:05 -0300 Subject: [PATCH 297/410] test(game): bound the cyclic diagnostics fixture --- ...game.create-failure-classification.test.ts | 36 +++++++++++++------ 1 file changed, 26 insertions(+), 10 deletions(-) diff --git a/tests/game.create-failure-classification.test.ts b/tests/game.create-failure-classification.test.ts index 91bb2c38..c27350dd 100644 --- a/tests/game.create-failure-classification.test.ts +++ b/tests/game.create-failure-classification.test.ts @@ -210,11 +210,6 @@ describe("GameManager.createGame definitive failure classification", () => { resetGM(); }); - const cyclicTransportCause: { cause?: unknown; logs: unknown[] } = { - logs: [null, 404, "provider disconnected while reading the response"], - }; - cyclicTransportCause.cause = cyclicTransportCause; - const cases: Array<{ name: string; error: unknown; state: "failed" | "unknown" }> = [ { name: "a plain string cause naming a simulation failure", @@ -252,11 +247,6 @@ describe("GameManager.createGame definitive failure classification", () => { error: Object.assign(new Error("socket hang up"), { cause: "connection reset by peer" }), state: "unknown", }, - { - name: "cyclic network diagnostics with no definitive marker", - error: new Error("socket hang up", { cause: cyclicTransportCause }), - state: "unknown", - }, ]; for (const { name, error, state } of cases) { @@ -276,6 +266,32 @@ describe("GameManager.createGame definitive failure classification", () => { } }); } + + test("visits a cyclic network cause once and keeps the submission unknown", async () => { + resetGM(); + const errorSpy = spyOn(console, "error").mockImplementation(() => undefined); + let causeReads = 0; + const cyclicCause: { cause: unknown; logs: unknown[] } = { + get cause() { + causeReads += 1; + // Terminate within a few reads if the cycle check is removed. + return causeReads < 4 ? cyclicCause : undefined; + }, + logs: [null, 404, "provider disconnected while reading the response"], + }; + try { + const { gm, finishPendingGameCreationSubmission } = await makeSubmittedCreationHarness( + new Error("socket hang up", { cause: cyclicCause }), + ); + await attemptCreate(gm); + + expect(finishPendingGameCreationSubmission).toHaveBeenCalledTimes(1); + expect(finishPendingGameCreationSubmission.mock.calls[0]?.[2]).toBe("unknown"); + expect(causeReads).toBe(1); + } finally { + errorSpy.mockRestore(); + } + }); }); describe("GameManager.createGame limit check error formatting", () => { From 8055c75337fe7bf844567f4b02e8b176781ba138 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Mon, 30 Nov 2026 00:51:33 -0300 Subject: [PATCH 298/410] refactor(wallet): record first status inside its poll branch --- src/utils/wallet.ts | 9 ++------- tests/wallet-mutation-bounds.test.ts | 30 ++++++++++++++++++++++++++++ 2 files changed, 32 insertions(+), 7 deletions(-) diff --git a/src/utils/wallet.ts b/src/utils/wallet.ts index 69aa302a..e4a5a65c 100644 --- a/src/utils/wallet.ts +++ b/src/utils/wallet.ts @@ -2468,11 +2468,8 @@ export class WalletManager { const now = Date.now(); const elapsedAfterFetch = now - startTime; - if (status && firstStatusObservedAt === null) { - firstStatusObservedAt = elapsedAfterFetch; - } - if (status) { + firstStatusObservedAt ??= elapsedAfterFetch; const currentStatus = status.confirmationStatus || "unknown"; const currentConfirmations = statusConfirmationCount(status.confirmations); @@ -2499,9 +2496,7 @@ export class WalletManager { console.log( `✅ Transaction ${signature} confirmed in ${elapsedAfterFetch}ms (${pollCount} polls, history=${ historyEnabledAt !== null ? `enabled@${historyEnabledAt}ms` : "not-used" - }, firstStatus=${ - firstStatusObservedAt !== null ? `${firstStatusObservedAt}ms` : "none" - }, networkRetries=${networkRetryCount})`, + }, firstStatus=${firstStatusObservedAt}ms, networkRetries=${networkRetryCount})`, ); return; } diff --git a/tests/wallet-mutation-bounds.test.ts b/tests/wallet-mutation-bounds.test.ts index ef0ca3fa..638d093c 100644 --- a/tests/wallet-mutation-bounds.test.ts +++ b/tests/wallet-mutation-bounds.test.ts @@ -108,6 +108,36 @@ test.each(["confirmed", "finalized"] as const)( }, ); +test("keeps the first status at zero milliseconds when a later poll confirms", async () => { + const expectedStatuses = ["processed", "confirmed"] as const; + let reads = 0; + const wallet = walletWith({ + getSignatureStatuses: async () => { + const confirmationStatus = expectedStatuses[reads++]; + if (!confirmationStatus) throw new Error("Unexpected third status lookup"); + return { + context: { slot: 1n }, + value: [{ slot: 1n, confirmations: null, err: null, confirmationStatus }], + }; + }, + }); + const clock = useWalletConfirmationClock(wallet); + const log = spyOn(console, "log").mockImplementation(() => {}); + try { + await expect( + withinTestDeadline(wallet.confirmTransaction(signature), "first observed status timestamp"), + ).resolves.toBeUndefined(); + expect(reads).toBe(2); + expect(clock.delays).toEqual([400]); + expect(log.mock.calls.at(-1)).toEqual([ + `✅ Transaction ${signature} confirmed in 400ms (2 polls, history=not-used, firstStatus=0ms, networkRetries=0)`, + ]); + } finally { + log.mockRestore(); + clock.restore(); + } +}); + test("missing status responses remain unknown until the history lookup confirms", async () => { const context = { slot: 1n }; const responses = [ From 5d5fd87059203cb5652038989aa93381cde67e30 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Mon, 30 Nov 2026 00:54:34 -0300 Subject: [PATCH 299/410] test(wallet): distinguish late confirmation from unknown status --- tests/wallet-mutation-bounds.test.ts | 50 +++++++++++++++++++++++++++- 1 file changed, 49 insertions(+), 1 deletion(-) diff --git a/tests/wallet-mutation-bounds.test.ts b/tests/wallet-mutation-bounds.test.ts index 638d093c..545edf92 100644 --- a/tests/wallet-mutation-bounds.test.ts +++ b/tests/wallet-mutation-bounds.test.ts @@ -7,7 +7,7 @@ import { TransactionMessage, VersionedTransaction, } from "#solana"; -import { WalletManager } from "../src/utils/wallet"; +import { TransactionOutcomeUnknownError, WalletManager } from "../src/utils/wallet"; import { stubInstantTimers, withinTestDeadline } from "./helpers/timers"; import { useWalletConfirmationClock } from "./helpers/wallet-confirmation-clock"; @@ -138,6 +138,54 @@ test("keeps the first status at zero milliseconds when a later poll confirms", a } }); +test.each(["finalized", null] as const)( + "distinguishes the final status %p from an absent status throughout confirmation", + async (finalStatus) => { + const context = { slot: 1n }; + const historyLookups: Array = []; + const wallet = walletWith({ + getSignatureStatuses: async (_signatures, config) => { + historyLookups.push(config?.searchTransactionHistory); + if (historyLookups.length > 2) throw new Error("Unexpected third status lookup"); + const status = + historyLookups.length === 2 && finalStatus + ? { slot: 1n, confirmations: null, err: null, confirmationStatus: finalStatus } + : null; + return { context, value: [status] }; + }, + getTransaction: async () => null, + getSignatureStatus: async () => ({ context, value: null }), + }); + Object.defineProperty(wallet, "confirmationTimeoutMs", { value: 400 }); + const clock = useWalletConfirmationClock(wallet); + const log = spyOn(console, "log").mockImplementation(() => {}); + const error = spyOn(console, "error").mockImplementation(() => {}); + try { + const result = withinTestDeadline( + wallet.confirmTransaction(signature), + "final wallet status", + ); + if (finalStatus) { + await expect(result).resolves.toBeUndefined(); + expect(log.mock.calls.at(-1)).toEqual([ + `✅ Transaction ${signature} confirmed on final check (polls=1, history=not-used, firstStatus=400ms, networkRetries=0)`, + ]); + } else { + await expect(result).rejects.toBeInstanceOf(TransactionOutcomeUnknownError); + expect(error.mock.calls).toContainEqual([ + `⏰ Transaction confirmation timeout for ${signature} after 400ms (1 polls, history=not-used, firstStatus=none, networkRetries=0, postTimeoutProbe=missing)`, + ]); + } + expect(historyLookups).toEqual([undefined, true]); + expect(clock.delays).toEqual([400]); + } finally { + error.mockRestore(); + log.mockRestore(); + clock.restore(); + } + }, +); + test("missing status responses remain unknown until the history lookup confirms", async () => { const context = { slot: 1n }; const responses = [ From 707499ac695f620a786baae62d62072a986237c6 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Mon, 30 Nov 2026 01:04:35 -0300 Subject: [PATCH 300/410] test(database): isolate two equivalent count variants --- src/utils/game-database.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/utils/game-database.ts b/src/utils/game-database.ts index 2dfedd2f..20272dfc 100644 --- a/src/utils/game-database.ts +++ b/src/utils/game-database.ts @@ -1943,8 +1943,10 @@ export class GameDatabase extends BaseDatabase { private ensureGameMessagesSchema(): void { try { const count = + // Stryker disable next-line OptionalChaining: An ungrouped SQLite COUNT returns one row or throws. this.get<{ count: number }>( "SELECT COUNT(*) as count FROM game_messages", + // Stryker disable next-line ArrayDeclaration: The SQLite statement has no parameters and ignores extra bindings. [], "counting game messages", )?.count ?? 0; From f22ee6ad37327299b07ec16a4ecd3e281ea5ded8 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Mon, 30 Nov 2026 01:07:45 -0300 Subject: [PATCH 301/410] test(database): pin the failing schema operation --- tests/game-database.schema.test.ts | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/tests/game-database.schema.test.ts b/tests/game-database.schema.test.ts index c62016eb..0d74ad3d 100644 --- a/tests/game-database.schema.test.ts +++ b/tests/game-database.schema.test.ts @@ -133,7 +133,7 @@ describe("GameDatabase schema upgrades and failure handling", () => { expect(db.getGame("AFTER_READ_ERROR")?.creator_telegram_id).toBe("111"); }); - const brokenViews: Array<[string, string, string]> = [ + const brokenViews: Array<[string, string, string, string?]> = [ [ "game_participants", "CREATE VIEW game_participants AS SELECT game_address, game_address AS telegram_id FROM backing", @@ -153,16 +153,19 @@ describe("GameDatabase schema upgrades and failure handling", () => { "chat_membership_cache", "CREATE VIEW chat_membership_cache AS SELECT game_address AS chat_id FROM backing", "Failed to ensure membership cache schema:", + "[Game DB] Error during creating membership cache index:", ], ]; - for (const [name, createView, message] of brokenViews) { + for (const [name, createView, message, sqlError] of brokenViews) { test(`reports but survives a ${name} object that cannot be migrated`, () => { seedLegacy(`CREATE TABLE backing (game_address TEXT); ${createView};`); const db = open(); - expect(errorSpy.mock.calls.map((call) => call[0])).toContain(message); + const messages = errorSpy.mock.calls.map(([result]) => result); + expect(messages).toContain(message); + if (sqlError) expect(messages).toContain(sqlError); // The rest of the database still works. db.saveGame("G_AFTER", "1", 1, "coinflip"); expect(db.getGame("G_AFTER")?.game_address).toBe("G_AFTER"); @@ -178,6 +181,7 @@ describe("GameDatabase schema upgrades and failure handling", () => { open(); const messages = errorSpy.mock.calls.map((call) => call[0]); + expect(messages).toContain("[Game DB] Error during adding timeout_seconds column to games:"); expect(messages).toContain("Failed to ensure games schema:"); expect(messages).toContain("[Game DB] Error during migrating game messages:"); expect(messages).toContain("Failed to ensure game_messages schema:"); From dcf6949d44547fbf99f64c5b6fc24c7bd10a7aa3 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Mon, 30 Nov 2026 01:17:11 -0300 Subject: [PATCH 302/410] test(media): bound deferred edits and retry checks Check the exact Telegram retry boundary and recovery after a failed edit. The local image was unavailable. Validate both contract versions through the draft PR before counting this batch as verified. --- tests/media.test.ts | 163 ++++++++++++++++++++++++++------------------ 1 file changed, 96 insertions(+), 67 deletions(-) diff --git a/tests/media.test.ts b/tests/media.test.ts index 0f712e2f..385678fd 100644 --- a/tests/media.test.ts +++ b/tests/media.test.ts @@ -1,102 +1,131 @@ -import { describe, expect, test } from "bun:test"; +import { describe, expect, test, vi } from "bun:test"; import { editMediaWithFallback, enqueueMessageMediaEdit } from "../src/utils/media"; +function observe(promise: Promise) { + const outcomes: Array<{ value: T } | { error: unknown }> = []; + void promise.then( + (value) => outcomes.push({ value }), + (error: unknown) => outcomes.push({ error }), + ); + return outcomes; +} + +async function flushEdits(): Promise { + // An edit that never settles must fail the result check instead of hanging the test. + for (let turn = 0; turn < 24; turn += 1) await Promise.resolve(); +} + describe("editMediaWithFallback", () => { test("retries edit when Telegram responds with 429", async () => { - const originalSetTimeout = globalThis.setTimeout; - const delays: number[] = []; - globalThis.setTimeout = ((callback: (...args: any[]) => void, ms?: number) => { - delays.push(ms ?? 0); - callback(); - return 0 as any; - }) as any; - + vi.useFakeTimers(); let attempts = 0; const edit = async () => { attempts += 1; if (attempts < 3) { - const error: any = new Error("Too Many Requests"); - error.error_code = 429; - error.parameters = { retry_after: 2 }; - throw error; + throw Object.assign(new Error("Too Many Requests"), { + error_code: 429, + parameters: { retry_after: 2 }, + }); } return { ok: true }; }; try { - const result = await editMediaWithFallback({ edit }); - expect(result).toEqual({ result: { ok: true }, usedFallback: false, skipped: false }); + const result = observe(editMediaWithFallback({ edit })); + await flushEdits(); + for (const expectedCount of [1, 2]) { + vi.advanceTimersByTime(1_999); + await flushEdits(); + expect(attempts).toBe(expectedCount); + expect(result).toEqual([]); + vi.advanceTimersByTime(1); + await flushEdits(); + } expect(attempts).toBe(3); - expect(delays).toEqual([2000, 2000]); + expect(result).toEqual([ + { value: { result: { ok: true }, usedFallback: false, skipped: false } }, + ]); } finally { - globalThis.setTimeout = originalSetTimeout; + vi.clearAllTimers(); + vi.useRealTimers(); } }); }); -const createDeferred = () => { - let resolve: (value: T) => void = () => {}; - let reject: (error: unknown) => void = () => {}; - const promise = new Promise((res, rej) => { - resolve = res; - reject = rej; - }); - return { promise, resolve, reject }; -}; - describe("enqueueMessageMediaEdit", () => { test("serializes edits and drops superseded pending entries", async () => { const key = "1:2"; const steps: string[] = []; - const firstDeferred = createDeferred(); - - const firstPromise = enqueueMessageMediaEdit(key, async () => { - steps.push("first-start"); - await firstDeferred.promise; - steps.push("first-end"); - return "first"; - }); - - const secondPromise = enqueueMessageMediaEdit(key, async () => { - steps.push("second"); - return "second"; - }); - - const thirdPromise = enqueueMessageMediaEdit(key, async () => { - steps.push("third"); - return "third"; - }); - - const secondResult = await secondPromise; - expect(secondResult).toEqual({ result: null, skipped: true }); + const firstDeferred = Promise.withResolvers(); + + const first = observe( + enqueueMessageMediaEdit(key, async () => { + steps.push("first-start"); + await firstDeferred.promise; + steps.push("first-end"); + return "first"; + }), + ); + + const second = observe( + enqueueMessageMediaEdit(key, async () => { + steps.push("second"); + return "second"; + }), + ); + + const third = observe( + enqueueMessageMediaEdit(key, async () => { + steps.push("third"); + return "third"; + }), + ); - firstDeferred.resolve(); - - const firstResult = await firstPromise; - const thirdResult = await thirdPromise; - - expect(firstResult).toEqual({ result: "first", skipped: false }); - expect(thirdResult).toEqual({ result: "third", skipped: false }); + try { + await flushEdits(); + expect(second).toEqual([{ value: { result: null, skipped: true } }]); + expect(steps).toEqual(["first-start"]); + } finally { + firstDeferred.resolve(); + await flushEdits(); + } + expect(first).toEqual([{ value: { result: "first", skipped: false } }]); + expect(third).toEqual([{ value: { result: "third", skipped: false } }]); expect(steps).toEqual(["first-start", "first-end", "third"]); }); test("runs queued edit when only one pending entry exists", async () => { const key = "3:4"; - const firstDeferred = createDeferred(); - - const firstPromise = enqueueMessageMediaEdit(key, async () => { - await firstDeferred.promise; - return "first"; - }); - - const secondPromise = enqueueMessageMediaEdit(key, async () => "second"); + const firstDeferred = Promise.withResolvers(); + const first = observe( + enqueueMessageMediaEdit(key, async () => { + await firstDeferred.promise; + return "first"; + }), + ); + const second = observe(enqueueMessageMediaEdit(key, async () => "second")); firstDeferred.resolve(); + await flushEdits(); - const firstResult = await firstPromise; - const secondResult = await secondPromise; + expect(first).toEqual([{ value: { result: "first", skipped: false } }]); + expect(second).toEqual([{ value: { result: "second", skipped: false } }]); + }); - expect(firstResult).toEqual({ result: "first", skipped: false }); - expect(secondResult).toEqual({ result: "second", skipped: false }); + test("a failed edit rejects its own caller and leaves the key usable", async () => { + const key = "failed-media"; + const firstDeferred = Promise.withResolvers(); + const failure = new Error("Telegram edit failed"); + const first = observe(enqueueMessageMediaEdit(key, () => firstDeferred.promise)); + const second = observe(enqueueMessageMediaEdit(key, async () => "new card")); + + firstDeferred.reject(failure); + await flushEdits(); + + expect(first).toEqual([{ error: failure }]); + expect(second).toEqual([{ value: { result: "new card", skipped: false } }]); + const reuse = observe(enqueueMessageMediaEdit(key, async () => "next card")); + await flushEdits(); + expect(reuse).toEqual([{ value: { result: "next card", skipped: false } }]); }); }); From 20b2c14e52e9dc13315a34592b53cb575f6b53d7 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Mon, 30 Nov 2026 02:33:15 -0300 Subject: [PATCH 303/410] test(game): check card layout, stats fallbacks, and card recovery calls Remove three dead fallbacks in game stats and card composition. Each one gave the same result for every input. --- src/utils/game.ts | 53 +-- tests/game-manager.card-layout.test.ts | 274 ++++++++++++ tests/game-manager.stats-boundaries.test.ts | 275 ++++++++++++ ...me-manager.update-message-recovery.test.ts | 414 ++++++++++++++++++ 4 files changed, 983 insertions(+), 33 deletions(-) create mode 100644 tests/game-manager.card-layout.test.ts create mode 100644 tests/game-manager.stats-boundaries.test.ts create mode 100644 tests/game-manager.update-message-recovery.test.ts diff --git a/src/utils/game.ts b/src/utils/game.ts index 8882bfe9..c439e588 100644 --- a/src/utils/game.ts +++ b/src/utils/game.ts @@ -2750,8 +2750,7 @@ export class GameManager { providedGameAccount?: any, ) { const baseAmountLamports = coerceLamportValue(amountLamportsInput) ?? 0n; - const providedTotalPot = - providedTotalPotInput !== undefined ? coerceLamportValue(providedTotalPotInput) : null; + const providedTotalPot = coerceLamportValue(providedTotalPotInput); try { const gameAccount = @@ -2778,18 +2777,15 @@ export class GameManager { // Calculate totalPot based on game type let totalPot = providedTotalPot ?? null; if (totalPot === null) { - const chainTotal = coerceLamportValue((gameAccount as any)?.totalAmount); + const chainTotal = coerceLamportValue((gameAccount as any).totalAmount); if (chainTotal !== null && chainTotal > 0n) { totalPot = chainTotal; } else { - const gameType = this.getGameType(gameAccount); - if (gameType === "giveaway") { - // For giveaways, totalPot is just the amount (prize from creator) - totalPot = baseAmountLamports; - } else { - // For coinflips, totalPot = amount * participants - totalPot = baseAmountLamports * BigInt(Math.max(currentTickets, 0)); - } + // A giveaway pot is the creator's prize. A coinflip pot is the amount per participant. + totalPot = + this.getGameType(gameAccount) === "giveaway" + ? baseAmountLamports + : baseAmountLamports * BigInt(Math.max(currentTickets, 0)); } } @@ -2798,7 +2794,7 @@ export class GameManager { const expiresAt = createdAt + timeout; const expirationInfo = await formatExpirationTime(expiresAt, this.wallet, "\n⏰ "); const tokenMint = ((gameAccount as any)?.tokenMint as PublicKey | undefined)?.toBase58(); - const participantAddresses = Array.isArray((gameAccount as any)?.participants) + const participantAddresses = Array.isArray((gameAccount as any).participants) ? (gameAccount as any).participants.flatMap((participant: unknown) => { try { return [new PublicKey(participant as any).toBase58()]; @@ -2843,8 +2839,7 @@ export class GameManager { providedTotalPotInput?: number | bigint, ) { const baseAmountLamports = coerceLamportValue(amountLamportsInput) ?? 0n; - const providedTotalPot = - providedTotalPotInput !== undefined ? coerceLamportValue(providedTotalPotInput) : null; + const providedTotalPot = coerceLamportValue(providedTotalPotInput); const gameAddress = gamePda.toBase58(); const gameData = this.gameDb.getGame(gameAddress); @@ -2853,19 +2848,15 @@ export class GameManager { const currentTickets = Math.max(participants.length, participantAddresses.length); const parsedMax = Number(gameData?.max_players); - const maxTickets = - Number.isFinite(parsedMax) && parsedMax > 0 ? parsedMax : Math.max(currentTickets, 0); + // currentTickets is a length, so these fallbacks are finite and not negative. + const maxTickets = Number.isFinite(parsedMax) && parsedMax > 0 ? parsedMax : currentTickets; const parsedMin = Number(gameData?.min_players); - let minTickets = + const minTickets = Number.isFinite(parsedMin) && parsedMin > 0 ? parsedMin : Math.min(currentTickets, maxTickets); - if (!Number.isFinite(minTickets) || minTickets <= 0) { - minTickets = Math.min(maxTickets, Math.max(currentTickets, 0)); - } - // Get game type from database to calculate totalPot correctly let totalPot = providedTotalPot ?? null; if (totalPot === null) { @@ -2876,15 +2867,11 @@ export class GameManager { if (storedTotal !== null && storedTotal > 0n) { totalPot = storedTotal; } else { - const gameType = gameData?.game_type || "coinflip"; // default to coinflip if not found - - if (gameType === "giveaway") { - // For giveaways, totalPot is just the amount (prize from creator) - totalPot = baseAmountLamports; - } else { - // For coinflips, totalPot = amount * participants - totalPot = baseAmountLamports * BigInt(Math.max(currentTickets, 0)); - } + // Any game that is not a giveaway, including a missing type, uses the coinflip pot. + totalPot = + gameData?.game_type === "giveaway" + ? baseAmountLamports + : baseAmountLamports * BigInt(currentTickets); } } @@ -3257,8 +3244,8 @@ export class GameManager { const statusSection = !isCompleted ? `\nStatus: ${statusText}${expirationInfo}` : ""; const composeMessage = (names: ParticipantDisplay[], omittedCount: number): string => { - const participantsSection = names.length > 0 ? buildParticipantsList(names) : ""; - let message = baseBeforeParticipants + participantsSection; + // An empty list renders as an empty string. + let message = baseBeforeParticipants + buildParticipantsList(names); // The prize line and the player list both end in a newline, and the // winner line brings its own spacing. if (isCompleted && message.endsWith("\n")) { @@ -3277,7 +3264,7 @@ export class GameManager { Math.max(0, totalParticipants - participantDisplayNames.length), ); - if (messageText.length > TELEGRAM_MESSAGE_CHAR_LIMIT && participantDisplayNames.length > 0) { + if (messageText.length > TELEGRAM_MESSAGE_CHAR_LIMIT) { for (const offset of participantDisplayNames.keys()) { const keep = participantDisplayNames.length - offset - 1; const omitted = Math.max(0, totalParticipants - keep); diff --git a/tests/game-manager.card-layout.test.ts b/tests/game-manager.card-layout.test.ts new file mode 100644 index 00000000..bfa1b1db --- /dev/null +++ b/tests/game-manager.card-layout.test.ts @@ -0,0 +1,274 @@ +import { afterEach, beforeEach, describe, expect, spyOn, test } from "bun:test"; +import { PublicKey } from "#solana"; +import { GameManager } from "../src/utils/game"; +import { formatAmount } from "../src/utils/format-amount"; +import { + makeDbStub, + makeProgramStub, + makeWalletStub, + resetGameManager, +} from "./helpers/game-manager"; + +const GAME = new PublicKey("BPFLoader1111111111111111111111111111111111"); +const ADDRESS = GAME.toBase58(); +const LIMIT = 4096; +const KEYBOARD = [ + [ + { text: "🎮 Join", callback_data: `join_${ADDRESS}` }, + { text: "🔁 Refresh", callback_data: `refresh_${ADDRESS}` }, + ], +]; + +type Render = { + tickets: number; + status?: "Active" | "Completed"; + players?: string[]; + names?: Record; + creator?: string; + account?: Record; + db?: Record; + lookupFails?: boolean; +}; + +let warn: ReturnType; +let error: ReturnType; +beforeEach(() => { + warn = spyOn(console, "warn").mockImplementation(() => {}); + error = spyOn(console, "error").mockImplementation(() => {}); +}); +afterEach(() => { + warn.mockRestore(); + error.mockRestore(); +}); + +async function render(options: Render) { + resetGameManager(); + const status = options.status ?? "Active"; + const players = options.players ?? Array.from({ length: options.tickets }, (_, i) => `${i + 1}`); + const lookups: unknown[] = []; + const gm = GameManager.getInstance( + makeProgramStub({ + ticketsCount: options.tickets, + maxTickets: 300, + minTickets: 2, + totalAmount: 0, + createdAt: 1_000_000, + timeout: 60, + gameType: { coinflip: {} }, + ...options.account, + }), + makeWalletStub({ + blockTime: 1_000_030, + tokenFormatter: (amount, decimals) => + formatAmount(amount, decimals, { maxFractionDigits: 6, trim: true }), + }), + makeDbStub({ + participants: players, + gameOverride: { max_players: 300, min_players: 2 }, + extra: options.db, + }), + ); + const ctx: any = { + chat: { id: 1, type: "supergroup" }, + api: { + getChatMember: async (_chat: number, id: unknown) => { + lookups.push(id); + if (options.lookupFails) throw new Error("synthetic member lookup failure"); + const name = options.names?.[String(id)]; + return { user: name ? { first_name: name } : { username: `user${id}` } }; + }, + }, + }; + const result = await gm.formatGameMessage( + ctx, + GAME, + "coinflip", + 1_000_000_000, + options.creator ?? "@creator", + status, + "TOK", + status === "Completed" ? "WinnerPub" : undefined, + ); + return { ...result, lookups }; +} + +const header = (tickets: number, prize: number) => + `🪙 Coinflip 🔎 • 1 TOK\nCreator: @creator • ${tickets}/300 players\nPrize pool: ${prize} TOK\n`; + +describe("game card layout", () => { + test("an active card lists its players before the status", async () => { + const card = await render({ tickets: 3 }); + expect(card.messageText).toBe( + header(3, 3) + + "\n1. @user1\n2. @user2\n3. @user3\n" + + "\nStatus: ▰▱▱▱▱▱▱▱▱▱ Ready, 297 spots left\n⏰ Expires in: 30s", + ); + expect(card.keyboard).toEqual(KEYBOARD); + expect(warn).not.toHaveBeenCalled(); + expect(error).not.toHaveBeenCalled(); + }); + + test("a completed card drops the status and keeps one blank line before the winner", async () => { + const card = await render({ tickets: 3, status: "Completed" }); + expect(card.messageText).toBe( + header(3, 3) + + "\n1. @user1\n2. @user2\n3. @user3" + + '\n\nWinner: Winn…rPub', + ); + expect(card.keyboard).toEqual([]); + }); + + test("an active card without tickets lists nobody, even with stored players", async () => { + const card = await render({ tickets: 0, players: ["5"] }); + expect(card.messageText).toBe( + header(0, 0) + "\nStatus: ▱▱▱▱▱▱▱▱▱▱ Needs 2 more players to start\n⏰ Expires in: 30s", + ); + expect(card.lookups).toEqual([]); + }); + + test("a player whose name cannot be read is shown by the start of the Telegram ID", async () => { + const card = await render({ tickets: 1, players: ["1234567890"], lookupFails: true }); + expect(card.messageText).toContain("\n1. Player 123456...\n"); + }); + + test("a stored player row without an ID is shown as unknown", async () => { + const card = await render({ + tickets: 1, + db: { getGameParticipantsPreview: () => [null] }, + }); + expect(card.messageText).toContain("\n1. Player unknown...\n"); + }); + + test("an unmapped wallet is shown by its address without a name lookup", async () => { + const wallet = new PublicKey("Vote111111111111111111111111111111111111111").toBase58(); + const card = await render({ tickets: 1, account: { participants: [wallet] } }); + expect(card.messageText).toContain(`\n1. `); + expect(card.lookups).toEqual([]); + expect(warn).not.toHaveBeenCalled(); + }); + + test("a failed player list read is logged and the card only counts the players", async () => { + const failure = new Error("synthetic preview failure"); + const card = await render({ + tickets: 2, + db: { + getGameParticipantsPreview: () => { + throw failure; + }, + }, + }); + expect(card.messageText).toBe( + header(2, 2) + "\n… and 2 more\nStatus: ▰▱▱▱▱▱▱▱▱▱ Ready, 298 spots left\n⏰ Expires in: 30s", + ); + expect(error).toHaveBeenCalledWith("Error getting player list:", failure); + }); + + test("Telegram names are read for 100 players but not for 101", async () => { + const hundred = await render({ tickets: 100 }); + expect(hundred.lookups).toHaveLength(100); + const more = await render({ + tickets: 101, + db: { getPlayerDisplayName: (id: string) => `Stored ${id}` }, + }); + expect(more.lookups).toEqual([]); + expect(more.messageText).toContain("\n1. Stored 1\n"); + }); + + test("the preview reads at most 250 wallets and counts the rest", async () => { + const wallets = Array.from({ length: 251 }, (_, i) => { + const bytes = new Uint8Array(32); + bytes[0] = 1 + (i % 250); + bytes[1] = 1 + Math.floor(i / 250); + return new PublicKey(bytes).toBase58(); + }); + const read: string[] = []; + const card = await render({ + tickets: 251, + account: { participants: wallets }, + db: { + getPlayerTelegramId: (wallet: string) => { + read.push(wallet); + return null; + }, + }, + }); + // Only the preview is mapped to players; the card length limit then counts the rest. + expect(read).toEqual(wallets.slice(0, 250)); + expect(card.messageText).toContain("\n37. "); + expect(card.messageText).toContain("\n… and 214 more\nStatus:"); + }); + + test("a missing challenge reader is not an error, and a failed one is logged", async () => { + await render({ tickets: 1 }); + expect(warn).not.toHaveBeenCalled(); + const failure = new Error("synthetic challenge failure"); + await render({ + tickets: 1, + db: { + getGameChallenge: () => { + throw failure; + }, + }, + }); + expect(warn).toHaveBeenCalledWith(`Failed to read challenge for ${ADDRESS}:`, failure); + }); +}); + +describe("game card length limit", () => { + // Five players named by Telegram ID. Only the last name changes length. + const ids = ["1", "2", "3", "4", "5"]; + const named = (lastLength: number, short = 10) => + Object.fromEntries( + ids.map((id, index) => [ + id, + (index === ids.length - 1 ? "z" : "a").repeat( + index === ids.length - 1 ? lastLength : short, + ), + ]), + ); + const lengthWith = async (lastLength: number) => + (await render({ tickets: 5, names: named(lastLength) })).messageText.length; + + test("a card of exactly the limit keeps every player", async () => { + const base = await lengthWith(1); + const exact = await render({ tickets: 5, names: named(1 + LIMIT - base) }); + expect(exact.messageText).toHaveLength(LIMIT); + expect(exact.messageText).toContain("\n5. zzz"); + expect(exact.messageText.endsWith("Expires in: 30s")).toBe(true); + }); + + test("one character over the limit drops the last player and counts it", async () => { + const base = await lengthWith(1); + const over = await render({ tickets: 5, names: named(2 + LIMIT - base) }); + expect(over.messageText).not.toContain("\n5. "); + expect(over.messageText).toContain("\n4. aaaaaaaaaa\n\n… and 1 more\nStatus:"); + expect(over.messageText.endsWith("Expires in: 30s")).toBe(true); + }); + + test("a shortened card of exactly the limit keeps the remaining players", async () => { + // The last name alone is over the limit, so the card drops it and counts it. + const reference = await render({ tickets: 5, names: named(5000) }); + expect(reference.messageText).toContain("\n4. aaaaaaaaaa\n\n… and 1 more\n"); + // Pad the first name until the shortened card is exactly the limit. + const names = named(5000); + names["1"] = "a".repeat(10 + LIMIT - reference.messageText.length); + const exact = await render({ tickets: 5, names }); + expect(exact.messageText).toHaveLength(LIMIT); + expect(exact.messageText).toContain("\n4. aaaaaaaaaa\n\n… and 1 more\n"); + expect(exact.messageText.endsWith("Expires in: 30s")).toBe(true); + }); + + test("a header longer than the limit counts every player and is cut with an ellipsis", async () => { + const short = await render({ tickets: 3, creator: "@c" }); + const listLength = "\n1. @user1\n2. @user2\n3. @user3\n".length; + // The card without its list is 30 characters over the limit. + const creator = + "@c" + + "x".repeat(LIMIT + 30 - (short.messageText.length - listLength) - "\n… and 3 more".length); + const card = await render({ tickets: 3, creator }); + expect(card.messageText).toHaveLength(LIMIT); + expect(card.messageText.endsWith("…")).toBe(true); + expect(card.messageText).toContain("\n… and 3 more\nStatus:"); + expect(card.messageText).not.toContain("1. @user1"); + }); +}); diff --git a/tests/game-manager.stats-boundaries.test.ts b/tests/game-manager.stats-boundaries.test.ts new file mode 100644 index 00000000..e3a826d8 --- /dev/null +++ b/tests/game-manager.stats-boundaries.test.ts @@ -0,0 +1,275 @@ +import { afterEach, beforeEach, describe, expect, spyOn, test } from "bun:test"; +import { PublicKey } from "#solana"; +import { GameManager } from "../src/utils/game"; + +const GAME = new PublicKey("BPFLoader1111111111111111111111111111111111"); +const KEY_A = new PublicKey("BPFLoader2111111111111111111111111111111111").toBase58(); +const KEY_B = new PublicKey("Vote111111111111111111111111111111111111111").toBase58(); +const KEY_C = new PublicKey("Stake11111111111111111111111111111111111111").toBase58(); + +let warn: ReturnType; +beforeEach(() => { + GameManager.resetForTest(); + warn = spyOn(console, "warn").mockImplementation(() => {}); +}); +afterEach(() => { + warn.mockRestore(); +}); + +const unavailable = (amount: bigint) => ({ + currentTickets: 0, + maxTickets: 0, + minTickets: 0, + totalPot: amount, + expirationInfo: "", + tokenMint: undefined, + participantAddresses: [], + stateUnavailable: true, +}); + +function completedManager( + game: Record | null, + players: string[], + addresses?: string[], +) { + const db: Record = { + getGame: () => game, + getGameParticipants: () => players, + }; + if (addresses) db["getGameParticipantAddresses"] = () => addresses; + return GameManager.getInstance({} as any, {} as any, db as any); +} + +describe("completed game stats", () => { + const cases: Array<{ + name: string; + game: Record | null; + players?: string[]; + addresses?: string[]; + pot?: number | bigint; + expected: Record; + }> = [ + { + name: "stored limits and a coinflip pot from three players", + game: { max_players: "5", min_players: "2", game_type: "coinflip", token_mint: "MINT" }, + players: ["1", "2", "3"], + expected: { + currentTickets: 3, + maxTickets: 5, + minTickets: 2, + totalPot: 30n, + tokenMint: "MINT", + }, + }, + { + name: "invalid limits fall back to the player count", + game: { max_players: "abc", min_players: 0, game_type: "coinflip" }, + players: ["1", "2", "3"], + expected: { currentTickets: 3, maxTickets: 3, minTickets: 3, totalPot: 30n }, + }, + { + name: "negative limits fall back to the player count", + game: { max_players: -4, min_players: -1 }, + players: ["1", "2"], + expected: { currentTickets: 2, maxTickets: 2, minTickets: 2, totalPot: 20n }, + }, + { + name: "a missing minimum uses the smaller of players and maximum", + game: { max_players: 6 }, + players: ["1", "2"], + expected: { currentTickets: 2, maxTickets: 6, minTickets: 2, totalPot: 20n }, + }, + { + name: "a missing minimum cannot exceed a stored maximum", + game: { max_players: 2 }, + players: ["1", "2", "3", "4"], + expected: { currentTickets: 4, maxTickets: 2, minTickets: 2, totalPot: 40n }, + }, + { + name: "participant addresses count when players are not mapped", + game: { game_type: "coinflip" }, + players: ["1"], + addresses: [KEY_A, KEY_B, KEY_C], + expected: { + currentTickets: 3, + maxTickets: 3, + minTickets: 3, + totalPot: 30n, + participantAddresses: [KEY_A, KEY_B, KEY_C], + }, + }, + { + name: "a database without participant addresses has none", + game: { game_type: "coinflip" }, + players: [], + expected: { + currentTickets: 0, + maxTickets: 0, + minTickets: 0, + totalPot: 0n, + participantAddresses: [], + }, + }, + { + name: "a missing game row is a coinflip without a token", + game: null, + players: ["1", "2"], + expected: { + currentTickets: 2, + maxTickets: 2, + minTickets: 2, + totalPot: 20n, + tokenMint: undefined, + }, + }, + { + name: "an empty game type and token use the defaults", + game: { game_type: "", token_mint: "" }, + players: ["1"], + expected: { totalPot: 10n, tokenMint: undefined }, + }, + { + name: "a giveaway pot is the prize amount", + game: { game_type: "giveaway" }, + players: ["1", "2", "3"], + expected: { totalPot: 10n }, + }, + { + name: "a stored pot wins over the player count", + game: { totalPot: "75", total_amount: "99", game_type: "coinflip" }, + players: ["1", "2"], + expected: { totalPot: 75n }, + }, + { + name: "a legacy stored pot is used when the current one is missing", + game: { total_amount: 99, game_type: "giveaway" }, + players: ["1"], + expected: { totalPot: 99n }, + }, + { + name: "a stored zero pot falls back to the player count", + game: { totalPot: 0, game_type: "coinflip" }, + players: ["1", "2"], + expected: { totalPot: 20n }, + }, + { + name: "a provided pot wins over the stored pot and the player count", + game: { totalPot: 75, game_type: "coinflip" }, + players: ["1", "2"], + pot: 5, + expected: { totalPot: 5n }, + }, + { + name: "a provided zero pot is kept", + game: { game_type: "coinflip" }, + players: ["1", "2"], + pot: 0n, + expected: { totalPot: 0n }, + }, + ]; + + for (const { name, game, players = [], addresses, pot, expected } of cases) { + test(name, async () => { + const gm = completedManager(game, players, addresses); + const stats = await (gm as any).getCompletedGameStats(GAME, 10n, pot); + expect(stats).toEqual({ + currentTickets: stats.currentTickets, + maxTickets: stats.maxTickets, + minTickets: stats.minTickets, + totalPot: stats.totalPot, + expirationInfo: "", + tokenMint: stats.tokenMint, + participantAddresses: stats.participantAddresses, + }); + expect(stats).toMatchObject(expected); + if (!("participantAddresses" in expected)) { + expect(stats.participantAddresses).toEqual(addresses ?? []); + } + }); + } +}); + +describe("active game stats", () => { + const account = (extra: Record = {}) => ({ + ticketsCount: 2, + maxTickets: 4, + minTickets: 2, + createdAt: 1_000, + timeout: 60, + gameType: { coinflip: {} }, + ...extra, + }); + + function activeManager(program: any = {}, saved: any[][] = []) { + return GameManager.getInstance( + program, + { getBlockchainTime: async () => 1_000 } as any, + { saveGameParticipantAddresses: (...args: any[]) => saved.push(args) } as any, + ); + } + + const pots: Array<[string, Record, number | bigint | undefined, bigint]> = [ + ["the chain total wins", { totalAmount: 50 }, undefined, 50n], + ["a zero chain total uses the coinflip player count", { totalAmount: 0 }, undefined, 20n], + ["a missing chain total uses the coinflip player count", {}, undefined, 20n], + ["a negative ticket count gives an empty coinflip pot", { ticketsCount: -3 }, undefined, 0n], + ["a giveaway pot is the prize amount", { gameType: { giveaway: {} } }, undefined, 10n], + ["a provided pot wins over the chain total", { totalAmount: 50 }, 7, 7n], + ["a provided zero pot is kept", { totalAmount: 50 }, 0n, 0n], + ]; + for (const [name, extra, pot, expected] of pots) { + test(`pot: ${name}`, async () => { + const gm = activeManager(); + const stats = await (gm as any).getActiveGameStats(GAME, 10n, pot, account(extra)); + expect(stats.totalPot).toBe(expected); + expect(warn).not.toHaveBeenCalled(); + }); + } + + test("only the participants inside the ticket count are saved", async () => { + const saved: any[][] = []; + const gm = activeManager({}, saved); + const stats = await (gm as any).getActiveGameStats( + GAME, + 10n, + undefined, + account({ ticketsCount: 2, participants: [KEY_A, KEY_B, KEY_C] }), + ); + expect(stats.participantAddresses).toEqual([KEY_A, KEY_B, KEY_C]); + expect(saved).toEqual([[GAME.toBase58(), [KEY_A, KEY_B]]]); + }); + + test("an account without a participant list has no participants", async () => { + const saved: any[][] = []; + const gm = activeManager({}, saved); + const stats = await (gm as any).getActiveGameStats(GAME, 10n, undefined, account()); + expect(stats.participantAddresses).toEqual([]); + expect(saved).toEqual([[GAME.toBase58(), []]]); + }); + + test("a closed account is unavailable without a lookup warning", async () => { + const gm = activeManager({ account: { game: { fetchNullable: async () => null } } }); + const stats = await (gm as any).getActiveGameStats(GAME, 10n); + expect(stats).toEqual(unavailable(10n)); + expect(warn).not.toHaveBeenCalled(); + }); + + test("a failed lookup is unavailable and names the game in its warning", async () => { + const failure = new Error("rpc unavailable"); + const gm = activeManager({ + account: { + game: { + fetch: async () => { + throw failure; + }, + }, + }, + }); + const stats = await (gm as any).getActiveGameStats(GAME, 10n); + expect(stats).toEqual(unavailable(10n)); + expect(warn).toHaveBeenCalledWith( + `Warning: Could not fetch game account for ${GAME.toBase58()}:`, + failure, + ); + }); +}); diff --git a/tests/game-manager.update-message-recovery.test.ts b/tests/game-manager.update-message-recovery.test.ts new file mode 100644 index 00000000..934f78a7 --- /dev/null +++ b/tests/game-manager.update-message-recovery.test.ts @@ -0,0 +1,414 @@ +import { afterEach, beforeEach, describe, expect, spyOn, test } from "bun:test"; +import { PublicKey } from "#solana"; +import { + makeDbStub, + makeProgramStub, + makeWalletStub, + resetGameManager, +} from "./helpers/game-manager"; +import { withinTestDeadline } from "./helpers/timers"; +import { GameManager } from "../src/utils/game"; +import { ChatDatabase } from "../src/utils/chat-database"; +import { CHAT_MEDIA_DISABLED_SENTINEL } from "../src/utils/constants"; +import { resetTestDatabase } from "./helpers/database"; + +// Each Telegram method answers from its own script, one entry per call. +// An entry made with fail() throws; any other entry is returned. When a +// script runs out, the method succeeds with a default Telegram reply. +type Failure = { fail: unknown }; +const fail = (error: unknown): Failure => ({ fail: error }); +const isFailure = (entry: unknown): entry is Failure => + typeof entry === "object" && entry !== null && "fail" in entry; + +type Method = "caption" | "media" | "text" | "retire" | "send" | "video" | "delete"; + +const recoverable = { description: "Bad Request: wrong file identifier/HTTP URL specified" }; +const noCaption = { description: "Bad Request: there is no caption in the message to edit" }; +const noText = { description: "Bad Request: there is no text in the message to edit" }; +const editGone = { description: "Bad Request: message to edit not found" }; +const notModified = { description: "Bad Request: message is not modified" }; +const refused = new Error("synthetic Telegram refusal"); + +const CHAT = 1; +const ORIGINAL = 46; +const REPLACEMENT = 777; +const EMPTY_KEYBOARD = { reply_markup: { inline_keyboard: [] } }; + +function scriptedCtx(script: Partial> = {}) { + const calls: any[][] = []; + const answer = async (method: Method, args: any[], fallback: unknown) => { + calls.push([method, ...args]); + const queue = script[method]; + const entry = queue && queue.length > 0 ? queue.shift() : fallback; + if (isFailure(entry)) throw entry.fail; + return entry; + }; + const sent = (chatId: number) => ({ message_id: REPLACEMENT, chat: { id: chatId } }); + const ctx: any = { + chat: { id: CHAT, type: "supergroup" }, + api: { + getChatMember: async (_chat: number, id: number) => ({ + user: { username: `user${id}` }, + status: "member", + }), + editMessageCaption: (...args: any[]) => answer("caption", args, { message_id: ORIGINAL }), + editMessageMedia: (...args: any[]) => answer("media", args, { message_id: ORIGINAL }), + editMessageText: (...args: any[]) => answer("text", args, { message_id: ORIGINAL }), + editMessageReplyMarkup: (...args: any[]) => answer("retire", args, true), + deleteMessage: (...args: any[]) => answer("delete", args, true), + sendMessage: (...args: any[]) => answer("send", args, sent(args[0])), + sendVideo: (...args: any[]) => answer("video", args, sent(args[0])), + }, + }; + const call = (index: number): any[] => { + const entry = calls[index]; + if (!entry) throw new Error(`Telegram call ${index} was not made`); + return entry; + }; + return { ctx, calls, call, names: () => calls.map((entry) => entry[0]) }; +} + +function managerFor( + status: "Active" | "Completed", + address: string, + options: { usesVideo?: boolean; saveGameMessage?: (...args: any[]) => void } = {}, +) { + resetGameManager(); + const completed = status === "Completed"; + const gameAccount = { + ticketsCount: completed ? 2 : 1, + maxTickets: 2, + minTickets: 1, + totalAmount: 0, + createdAt: 1_000_000, + timeout: 60, + gameType: { coinflip: {} }, + }; + const saved: any[] = []; + const gm = GameManager.getInstance( + makeProgramStub(gameAccount), + makeWalletStub({ tokenFormatter: (n, d) => (Number(n) / Math.pow(10, d)).toFixed(0) }), + makeDbStub({ + gameOverride: { game_type: "coinflip" }, + extra: { + getPlayerTelegramId: () => null, + saveGameMessage: + options.saveGameMessage ?? + ((...args: any[]) => { + saved.push(args); + }), + }, + }), + ); + const messages = new Map(); + const card: any = { chatId: CHAT, messageId: ORIGINAL }; + if (options.usesVideo !== undefined) card.usesVideo = options.usesVideo; + messages.set(CHAT, card); + (gm as any).activeGameMessages.set(address, messages); + const update = (ctx: any) => + withinTestDeadline( + gm.updateGameMessage( + ctx, + address, + "coinflip", + 1_000_000_000, + "@creator", + status, + "TOK", + completed ? "SomeWinner" : undefined, + ), + "updateGameMessage", + ); + return { gm, saved, update, card: () => gm.getActiveGameMessages(address)?.get(CHAT) }; +} + +let address = 0; +const nextAddress = () => { + address += 1; + return new PublicKey(new Uint8Array(32).fill(address)).toBase58(); +}; + +let warn: ReturnType; +let error: ReturnType; +beforeEach(() => { + warn = spyOn(console, "warn").mockImplementation(() => {}); + error = spyOn(console, "error").mockImplementation(() => {}); +}); +afterEach(() => { + warn.mockRestore(); + error.mockRestore(); +}); +const warnings = (): string[] => warn.mock.calls.map((call: unknown[]) => String(call[0])); + +describe("game card edit arguments", () => { + test("an active video card edits its caption with the card text and controls", async () => { + const game = managerFor("Active", nextAddress()); + const telegram = scriptedCtx(); + await game.update(telegram.ctx); + + expect(telegram.names()).toEqual(["caption"]); + const [, chatId, messageId, options] = telegram.call(0); + expect([chatId, messageId]).toEqual([CHAT, ORIGINAL]); + expect(Object.keys(options).sort()).toEqual(["caption", "parse_mode", "reply_markup"]); + expect(options.parse_mode).toBe("HTML"); + expect(options.caption.length).toBeGreaterThan(0); + expect(options.reply_markup.inline_keyboard.length).toBeGreaterThan(0); + // A card with no recorded media flag is known to be media after the edit. + expect(game.card()?.usesVideo).toBe(true); + expect(warnings()).toEqual([]); + }); + + test("a completed video card replaces its media with the winner video", async () => { + const game = managerFor("Completed", nextAddress()); + const telegram = scriptedCtx(); + await game.update(telegram.ctx); + + expect(telegram.names()).toEqual(["media"]); + const [, chatId, messageId, media, extra] = telegram.call(0); + expect([chatId, messageId]).toEqual([CHAT, ORIGINAL]); + expect(media.type).toBe("video"); + expect(media.media.length).toBeGreaterThan(0); + expect(media.parse_mode).toBe("HTML"); + expect(media.caption.length).toBeGreaterThan(0); + expect(Object.keys(extra)).toEqual(["reply_markup"]); + expect(game.card()?.usesVideo).toBe(true); + }); + + test("a text card falls back to a caption edit with the same text and controls", async () => { + const game = managerFor("Active", nextAddress(), { usesVideo: false }); + const telegram = scriptedCtx({ text: [fail(noText)] }); + await game.update(telegram.ctx); + + expect(telegram.names()).toEqual(["text", "caption"]); + const [, , , text, textOptions] = telegram.call(0); + expect(textOptions.parse_mode).toBe("HTML"); + expect(textOptions.reply_markup.inline_keyboard.length).toBeGreaterThan(0); + expect(telegram.call(1)).toEqual([ + "caption", + CHAT, + ORIGINAL, + { caption: text, parse_mode: "HTML", reply_markup: textOptions.reply_markup }, + ]); + // The caption worked, so the card is media from now on. + expect(game.card()?.usesVideo).toBe(true); + expect(warnings()).toContain("Falling back to text after game text update (1) failure:"); + }); +}); + +describe("game card recovery after a failed media edit", () => { + test("an active card that is no longer media is replaced once, without restoring old controls", async () => { + const game = managerFor("Active", nextAddress()); + const telegram = scriptedCtx({ + caption: [fail(noCaption), fail(noCaption)], + text: [fail(noText)], + }); + await game.update(telegram.ctx); + + expect(telegram.names()).toEqual(["caption", "text", "caption", "retire", "send"]); + const [, , , captionOptions] = telegram.call(0); + const text = captionOptions.caption; + const keyboard = captionOptions.reply_markup; + expect(telegram.call(1)).toEqual([ + "text", + CHAT, + ORIGINAL, + text, + { parse_mode: "HTML", reply_markup: keyboard }, + ]); + // The second caption attempt is the media recovery, with the same content. + expect(telegram.call(2)).toEqual(["caption", CHAT, ORIGINAL, captionOptions]); + expect(telegram.call(3)).toEqual(["retire", CHAT, ORIGINAL, EMPTY_KEYBOARD]); + expect(telegram.call(4).slice(0, 3)).toEqual(["send", CHAT, text]); + expect(telegram.call(4)[3].reply_markup).toBe(keyboard); + expect(game.saved).toEqual([[expect.any(String), REPLACEMENT, CHAT]]); + expect(game.card()).toEqual({ chatId: CHAT, messageId: REPLACEMENT, usesVideo: false }); + expect(warnings()).toEqual(["Falling back to text after game media update (1) failure:"]); + }); + + test("an unchanged caption during recovery keeps the card as media", async () => { + const game = managerFor("Completed", nextAddress(), { usesVideo: true }); + const telegram = scriptedCtx({ + media: [fail(recoverable)], + text: [fail(noText)], + caption: [fail(notModified)], + }); + await game.update(telegram.ctx); + + expect(telegram.names()).toEqual(["media", "text", "caption"]); + const [, , , media, extra] = telegram.call(0); + expect(telegram.call(2)).toEqual([ + "caption", + CHAT, + ORIGINAL, + { caption: media.caption, parse_mode: "HTML", reply_markup: extra.reply_markup }, + ]); + expect(game.card()).toEqual({ chatId: CHAT, messageId: ORIGINAL, usesVideo: true }); + expect(warnings()).toEqual(["Falling back to text after game media update (1) failure:"]); + }); + + test("a refused caption during recovery stops before the old card is retired", async () => { + const game = managerFor("Completed", nextAddress(), { usesVideo: true }); + const telegram = scriptedCtx({ + media: [fail(recoverable)], + text: [fail(noText)], + caption: [fail(refused)], + }); + await game.update(telegram.ctx); + + expect(telegram.names()).toEqual(["media", "text", "caption"]); + expect(game.saved).toEqual([]); + expect(game.card()).toEqual({ chatId: CHAT, messageId: ORIGINAL, usesVideo: true }); + const unexpected = warn.mock.calls.find((call: unknown[]) => + String(call[0]).startsWith("Unexpected error in media edit path"), + ); + expect(unexpected?.[1]).toBe(refused); + }); + + test("an old card that is already gone is not given its controls back", async () => { + const game = managerFor("Active", nextAddress()); + const telegram = scriptedCtx({ + caption: [fail(noCaption), fail(noCaption)], + text: [fail(noText)], + retire: [fail(editGone)], + send: [fail(refused)], + }); + await game.update(telegram.ctx); + + expect(telegram.names()).toEqual(["caption", "text", "caption", "retire", "send"]); + expect(game.saved).toEqual([]); + expect(game.card()?.messageId).toBe(ORIGINAL); + }); + + test("a cleared card without controls is not given an empty keyboard", async () => { + const game = managerFor("Completed", nextAddress(), { usesVideo: true }); + const telegram = scriptedCtx({ + media: [fail(recoverable)], + text: [fail(noText)], + caption: [fail(noCaption)], + send: [fail(refused)], + }); + await game.update(telegram.ctx); + + const [, , , , extra] = telegram.call(0); + expect(extra.reply_markup).toBeUndefined(); + expect(telegram.names()).toEqual(["media", "text", "caption", "retire", "send"]); + expect(game.card()?.messageId).toBe(ORIGINAL); + }); + + test("an old card gets its controls back when the replacement cannot be sent", async () => { + const game = managerFor("Active", nextAddress()); + const telegram = scriptedCtx({ + caption: [fail(noCaption), fail(noCaption)], + text: [fail(noText)], + send: [fail(refused)], + }); + await game.update(telegram.ctx); + + const keyboard = telegram.call(0)[3].reply_markup; + expect(telegram.names()).toEqual(["caption", "text", "caption", "retire", "send", "retire"]); + expect(telegram.call(5)).toEqual(["retire", CHAT, ORIGINAL, { reply_markup: keyboard }]); + expect(game.card()?.messageId).toBe(ORIGINAL); + expect(warnings()).not.toContain(`Failed to restore game keyboard ${CHAT}:${ORIGINAL}:`); + }); + + test("a failed keyboard restore is reported with the card that keeps no controls", async () => { + const game = managerFor("Active", nextAddress()); + const telegram = scriptedCtx({ + caption: [fail(noCaption), fail(noCaption)], + text: [fail(noText)], + send: [fail(refused)], + retire: [true, fail(refused)], + }); + await game.update(telegram.ctx); + + expect(telegram.names()).toEqual(["caption", "text", "caption", "retire", "send", "retire"]); + const restore = warn.mock.calls.find( + (call: unknown[]) => call[0] === `Failed to restore game keyboard ${CHAT}:${ORIGINAL}:`, + ); + expect(restore?.[1]).toBe(refused); + }); +}); + +describe("game card recreation after the card is deleted", () => { + test("each deleted card is recreated again after the previous recreation finished", async () => { + const game = managerFor("Completed", nextAddress(), { usesVideo: true }); + const telegram = scriptedCtx({ media: [fail(editGone), fail(editGone)] }); + await game.update(telegram.ctx); + // The recreated card is tracked; put the deleted one back to delete it again. + (game.gm as any).activeGameMessages + .get([...(game.gm as any).activeGameMessages.keys()][0]) + .set(CHAT, { chatId: CHAT, messageId: ORIGINAL, usesVideo: true }); + await game.update(telegram.ctx); + + expect(telegram.names()).toEqual(["media", "video", "media", "video"]); + expect(game.saved).toEqual([ + [expect.any(String), REPLACEMENT, CHAT], + [expect.any(String), REPLACEMENT, CHAT], + ]); + expect(warnings().filter((text: string) => text.startsWith("Unexpected error"))).toEqual([]); + }); +}); + +describe("game card edits for a chat with media turned off", () => { + const chatSettings = () => { + resetTestDatabase("chat-settings.sqlite"); + ChatDatabase.resetForTesting(); + ChatDatabase.getInstance().upsertChatGameSettings(CHAT, { + coinflip_video_id: CHAT_MEDIA_DISABLED_SENTINEL, + coinflip_media_type: null, + set_by_telegram_id: "admin", + }); + }; + afterEach(() => { + resetTestDatabase("chat-settings.sqlite"); + ChatDatabase.resetForTesting(); + }); + + test("a video card is replaced as text without a second caption attempt", async () => { + chatSettings(); + const game = managerFor("Active", nextAddress(), { usesVideo: true }); + const telegram = scriptedCtx({ caption: [fail(noCaption)], text: [fail(noText)] }); + await game.update(telegram.ctx); + + expect(telegram.names()).toEqual(["caption", "text", "retire", "send"]); + const [, , , captionOptions] = telegram.call(0); + expect(Object.keys(captionOptions).sort()).toEqual(["caption", "parse_mode", "reply_markup"]); + expect(captionOptions.parse_mode).toBe("HTML"); + expect(game.card()).toEqual({ chatId: CHAT, messageId: REPLACEMENT, usesVideo: false }); + expect(warnings()).toEqual(["Falling back to text after game caption update (1) failure:"]); + }); + + test("a card without a media flag is marked as media after its caption edit", async () => { + chatSettings(); + const game = managerFor("Active", nextAddress()); + const telegram = scriptedCtx(); + await game.update(telegram.ctx); + + expect(telegram.names()).toEqual(["caption"]); + expect(game.card()).toEqual({ chatId: CHAT, messageId: ORIGINAL, usesVideo: true }); + }); + + test("an unchanged caption leaves the card flag as it was", async () => { + chatSettings(); + const game = managerFor("Active", nextAddress()); + const telegram = scriptedCtx({ caption: [fail(notModified)] }); + await game.update(telegram.ctx); + + expect(telegram.names()).toEqual(["caption"]); + expect(game.card()).toEqual({ chatId: CHAT, messageId: ORIGINAL }); + }); + + test("a refused caption is reported once and does not recreate the card", async () => { + chatSettings(); + const game = managerFor("Active", nextAddress()); + const telegram = scriptedCtx({ caption: [fail(refused)] }); + await game.update(telegram.ctx); + + expect(telegram.names()).toEqual(["caption"]); + const unexpected = warn.mock.calls.filter((call: unknown[]) => + String(call[0]).startsWith("Unexpected error in caption edit path"), + ); + expect(unexpected).toHaveLength(1); + expect(unexpected[0][1]).toBe(refused); + }); +}); From 30ff9d27c8f1c0e35cb26fc9f42c0e16ef8fea8c Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Mon, 30 Nov 2026 02:34:58 -0300 Subject: [PATCH 304/410] test(game): check creation timing fallbacks and pre-confirmation errors Remove a debug log without behavior in the creation path and an optional call on the required database. --- src/utils/game.ts | 8 +---- tests/game.create-game.test.ts | 61 ++++++++++++++++++++++++++++++++++ 2 files changed, 62 insertions(+), 7 deletions(-) diff --git a/src/utils/game.ts b/src/utils/game.ts index c439e588..27350ab8 100644 --- a/src/utils/game.ts +++ b/src/utils/game.ts @@ -5101,7 +5101,7 @@ export class GameManager { const authoritativeExpiresAtMs = hasAuthoritativeTiming ? (createdAtSeconds + timeoutSeconds) * 1_000 : undefined; - const setPendingChainTiming = (this.gameDb as any)?.setPendingGameCreationChainTiming; + const setPendingChainTiming = (this.gameDb as any).setPendingGameCreationChainTiming; if ( hasAuthoritativeTiming && typeof setPendingChainTiming === "function" && @@ -5141,12 +5141,6 @@ export class GameManager { lastVerifiedAt: Date.now(), }); autoJoinResult = { success: true }; - } else { - debugLog( - `🎁 ${ - gameType.charAt(0).toUpperCase() + gameType.slice(1) - } game ${gamePda.toBase58()} created - creator not auto-joined`, - ); } if (parsedAmount.priceLookup) { diff --git a/tests/game.create-game.test.ts b/tests/game.create-game.test.ts index aeaabe07..d100075a 100644 --- a/tests/game.create-game.test.ts +++ b/tests/game.create-game.test.ts @@ -588,6 +588,67 @@ describe("createGame confirmed-account verification", () => { expect(saveArgs.slice(-2)).toEqual([1_700_000_060_000, 1_700_000_000_000]); }); + test.each([ + ["a missing creation time", { createdAt: undefined, timeout: 60 }], + ["a zero creation time", { createdAt: 0, timeout: 60 }], + ["a negative creation time", { createdAt: -5, timeout: 60 }], + ["an unreadable creation time", { createdAt: "soon", timeout: 60 }], + ["a missing timeout", { createdAt: 1_700_000_000, timeout: undefined }], + ])("keeps the requested timing when the account has %s", async (_label, account) => { + const setPendingGameCreationChainTiming = vi.fn(); + const db = durableDb({ setPendingGameCreationChainTiming }); + const { gm } = await setup({ db, account }); + const result = await create(gm); + expect(result.success).toBe(true); + expect(setPendingGameCreationChainTiming).not.toHaveBeenCalled(); + const saveArgs = db.saveGame.mock.calls[0] as unknown[]; + expect(saveArgs.slice(-2)).toEqual([undefined, undefined]); + }); + + test("saves the chain timing when the database has no pending timing writer", async () => { + const db = durableDb(); + const { gm } = await setup({ db, account: { createdAt: 1_700_000_000, timeout: 60 } }); + const result = await create(gm); + expect(result.success).toBe(true); + const saveArgs = db.saveGame.mock.calls[0] as unknown[]; + expect(saveArgs.slice(-2)).toEqual([1_700_000_060_000, 1_700_000_000_000]); + }); + + test("a failed hydration keeps the pending creation confirmed with its error", async () => { + const setPendingGameCreationState = vi.fn(); + const db = durableDb({ setPendingGameCreationState }); + const { gm } = await setup({ db, account: { maxTickets: 9 } }); + const result = await create(gm); + expect(result.success).toBe(false); + expect(setPendingGameCreationState.mock.calls.at(-1)).toEqual([ + FIXED_PDA.toBase58(), + "confirmed", + expect.objectContaining({ + error: "Confirmed game account does not match the requested configuration", + }), + ]); + }); + + test("a failure before confirmation returns a user error and logs the game type", async () => { + const failure = new Error("synthetic metadata failure"); + const db = durableDb(); + const { gm } = await setup({ + db, + wallet: { + getTokenMetadata: async () => { + throw failure; + }, + }, + }); + const result = await create(gm, { gameType: "giveaway" }); + expect(Object.keys(result).sort()).toEqual(["error", "success"]); + expect(result.success).toBe(false); + expect(typeof result.error).toBe("string"); + expect(result.error.length).toBeGreaterThan(0); + expect(errorSpy).toHaveBeenCalledWith("Error in creating giveaway game:", failure); + expect(db.saveGame).not.toHaveBeenCalled(); + }); + test("remembers the price used for the stake against the new game", async () => { const mint = (await Keypair.generate()).publicKey.toBase58(); const { gm } = await setup(); From 3c31f9ec63fb7b3b82c8346d59902995df0df57d Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Mon, 30 Nov 2026 02:36:55 -0300 Subject: [PATCH 305/410] test(mutants): ignore mutants inside debug trace calls debugLog prints only with TIMBA_DEBUG=true. Its arguments have no side effects, so a changed argument cannot change behavior. --- scripts/stryker-ignorers.mjs | 24 ++++++++++++++++ scripts/stryker-ignorers.test.ts | 47 ++++++++++++++++++++++++++++++++ stryker.conf.mjs | 4 ++- 3 files changed, 74 insertions(+), 1 deletion(-) create mode 100644 scripts/stryker-ignorers.mjs create mode 100644 scripts/stryker-ignorers.test.ts diff --git a/scripts/stryker-ignorers.mjs b/scripts/stryker-ignorers.mjs new file mode 100644 index 00000000..c4e2a1ba --- /dev/null +++ b/scripts/stryker-ignorers.mjs @@ -0,0 +1,24 @@ +// @ts-check +// Stryker ignorers: mutants inside these nodes cannot change what the bot does. + +/** Names of trace helpers that print only when debug logging is turned on. */ +export const DEBUG_TRACE_FUNCTIONS = new Set(["debugLog"]); + +/** @type {import("@stryker-mutator/api/ignore").Ignorer} */ +export const debugTraceIgnorer = { + shouldIgnore(path) { + /** @type {any} */ + const node = /** @type {any} */ (path).node; + if ( + node?.type === "CallExpression" && + node.callee?.type === "Identifier" && + DEBUG_TRACE_FUNCTIONS.has(node.callee.name) + ) { + return "Debug trace text. It prints only with TIMBA_DEBUG=true and its arguments have no side effects."; + } + return undefined; + }, +}; + +// The same object that declareValuePlugin(PluginKind.Ignore, ...) from @stryker-mutator/api builds. +export const strykerPlugins = [{ kind: "Ignore", name: "debug-trace", value: debugTraceIgnorer }]; diff --git a/scripts/stryker-ignorers.test.ts b/scripts/stryker-ignorers.test.ts new file mode 100644 index 00000000..050750bb --- /dev/null +++ b/scripts/stryker-ignorers.test.ts @@ -0,0 +1,47 @@ +import { describe, expect, test } from "bun:test"; +import { debugTraceIgnorer, strykerPlugins } from "./stryker-ignorers.mjs"; + +// The smallest Babel NodePath shapes the ignorer reads. +const identifier = (name: string) => ({ type: "Identifier", name }); +const call = (callee: unknown) => ({ node: { type: "CallExpression", callee, arguments: [] } }); +const paths = { + "debugLog(`joined ${name}`, 1)": call(identifier("debugLog")), + "console.warn(`joined ${name}`)": call({ + type: "MemberExpression", + object: identifier("console"), + property: identifier("warn"), + }), + "logger.debugLog(`joined`)": call({ + type: "MemberExpression", + object: identifier("logger"), + property: identifier("debugLog"), + }), + "notifyPlayer(`joined`)": call(identifier("notifyPlayer")), + debugLog: { node: identifier("debugLog") }, +}; +const callPath = (source: keyof typeof paths) => paths[source]; + +describe("Stryker debug trace ignorer", () => { + test("ignores a call to the debug trace helper with a reason", () => { + const reason = debugTraceIgnorer.shouldIgnore(callPath("debugLog(`joined ${name}`, 1)") as any); + expect(reason).toContain("TIMBA_DEBUG=true"); + }); + + test.each([ + ["a console warning", "console.warn(`joined ${name}`)"], + ["a method named debugLog", "logger.debugLog(`joined`)"], + ["another function", "notifyPlayer(`joined`)"], + ["a reference that is not a call", "debugLog"], + ] as const)("keeps mutants in %s", (_label, source) => { + expect(debugTraceIgnorer.shouldIgnore(callPath(source) as any)).toBeUndefined(); + }); + + test("registers the ignorer under the name used in the Stryker config", async () => { + const config = (await import("../stryker.conf.mjs")).default as any; + expect(config.ignorers).toEqual(["debug-trace"]); + expect(config.appendPlugins).toContain("./scripts/stryker-ignorers.mjs"); + expect(strykerPlugins.map((plugin: any) => [plugin.kind, plugin.name])).toEqual([ + ["Ignore", "debug-trace"], + ]); + }); +}); diff --git a/stryker.conf.mjs b/stryker.conf.mjs index 55ead026..cc5f928a 100644 --- a/stryker.conf.mjs +++ b/stryker.conf.mjs @@ -3,7 +3,9 @@ // change. Run it through scripts/mutants.ts, which picks the lines to change. /** @type {import('@stryker-mutator/api/core').PartialStrykerOptions} */ export default { - appendPlugins: ["@hughescr/stryker-bun-runner"], + appendPlugins: ["@hughescr/stryker-bun-runner", "./scripts/stryker-ignorers.mjs"], + // Skip mutants that only change debug trace text (see scripts/stryker-ignorers.mjs). + ignorers: ["debug-trace"], testRunner: "bun", // The same isolation `bun run test` uses. // timeout bounds only the dry run, the whole suite once with coverage (about a minute in CI). From 0d0ee18e849ae97d0539847cc7421e5bf8df0271 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Mon, 30 Nov 2026 02:40:22 -0300 Subject: [PATCH 306/410] test(game): check unjoin key choice, fee checks, and creator fallback --- src/utils/game.ts | 30 +++----- tests/game.cleanup.test.ts | 151 +++++++++++++++++++++++++++++++++++++ 2 files changed, 163 insertions(+), 18 deletions(-) diff --git a/src/utils/game.ts b/src/utils/game.ts index 27350ab8..9243efe7 100644 --- a/src/utils/game.ts +++ b/src/utils/game.ts @@ -8724,31 +8724,22 @@ export class GameManager { const gameAddress = gamePda.toBase58(); const logContext = "unjoin " + gameAddress; + // A PublicKey and key-like values convert with toBase58. Strings and other + // values convert with toString. A missing or failing conversion is no mint. const resolvePublicKeyString = (value: any): string | null => { if (!value) { return null; } - if (value instanceof PublicKey) { + try { return value.toBase58(); + } catch { + // Not key-like: use its text form. } - if (typeof value === "string") { - return value; - } - if (typeof value.toBase58 === "function") { - try { - return value.toBase58(); - } catch (_) { - // fall through - } - } - if (typeof value.toString === "function") { - try { - return value.toString(); - } catch (_) { - return null; - } + try { + return value.toString(); + } catch { + return null; } - return null; }; const tokenMintStr = resolvePublicKeyString(gameAccount?.tokenMint); @@ -8783,6 +8774,7 @@ export class GameManager { try { return await this.wallet.getKeyPair(BigInt(telegramId)); + // Stryker disable next-line BlockStatement: an empty catch returns undefined, which every caller treats as no key. } catch (_) { return null; } @@ -8912,9 +8904,11 @@ export class GameManager { gameAccount, creatorTelegramId, gameType, + // Stryker disable StringLiteral: operator log text, not shown to players attemptLog: "🎁 Closing expired " + gameType + " " + address + " with cleanup", successPrefix: "✅ Successfully closed expired " + gameType, failurePrefix: "❌ Failed to close expired " + gameType, + // Stryker restore StringLiteral }); return result.success; } diff --git a/tests/game.cleanup.test.ts b/tests/game.cleanup.test.ts index 60f51098..bbb7e7bf 100644 --- a/tests/game.cleanup.test.ts +++ b/tests/game.cleanup.test.ts @@ -576,6 +576,157 @@ describe("unjoinPlayers edge paths", () => { expect(warned("Creator fallback lacks SOL for unjoin: creator broke")).toBe(true); }); + const warnings = () => warnSpy.mock.calls.map((call: unknown[]) => String(call[0])); + + test("passes the token decimals to the fee check only when they are a number", async () => { + const decimals: unknown[] = []; + for (const value of [6, "6", undefined]) { + const { gm, prepareCalls } = setup({ + wallet: { getTokenMetadata: async () => ({ decimals: value }) }, + }); + await gm.unjoinPlayers(pda, { tokenMint: WSOL_MINT }, [player("1", PLAYER)]); + decimals.push(prepareCalls[0].tokenDecimals); + } + expect(decimals).toEqual([6, 0, 0]); + }); + + test("skips the fee check and still unjoins when the game has no token mint", async () => { + for (const account of [{}, undefined]) { + const creatorKey = await Keypair.generate(); + const { gm, prepareCalls, unjoinCalls } = setup({ + wallet: { + getKeyPair: async (id: bigint) => { + if (id === 1n) return creatorKey; + throw new Error("no key"); + }, + }, + }); + const count = await gm.unjoinPlayers(pda, account, [player("2", PLAYER)], "1"); + expect(count).toBe(1); + expect(prepareCalls).toEqual([]); + expect(unjoinCalls.map((call) => call[1])).toEqual([creatorKey]); + } + }); + + test("a blank Telegram ID has no signing key", async () => { + const requested: bigint[] = []; + const { gm, unjoinCalls } = setup({ + wallet: { + getKeyPair: async (id: bigint) => { + requested.push(id); + return Keypair.generate(); + }, + }, + }); + const count = await gm.unjoinPlayers(pda, { tokenMint: WSOL_MINT }, [player("", PLAYER)], ""); + expect(count).toBe(0); + expect(requested).toEqual([]); + expect(unjoinCalls).toEqual([]); + }); + + test("a successful player unjoin uses the player key once, with the database check skipped", async () => { + const creatorKey = await Keypair.generate(); + const playerKey = await Keypair.generate(); + const { gm, unjoinCalls } = setup({ + wallet: { getKeyPair: async (id: bigint) => (id === 1n ? creatorKey : playerKey) }, + }); + const count = await gm.unjoinPlayers(pda, { tokenMint: WSOL_MINT }, [player("2", PLAYER)], "1"); + expect(count).toBe(1); + expect(unjoinCalls).toEqual([ + [pda, playerKey, new PublicKey(PLAYER), "2", { skipDbCheck: true }], + ]); + expect(warnings()).toEqual([]); + }); + + test("a player without fee balance is unjoined by the creator instead", async () => { + const creatorKey = await Keypair.generate(); + const playerKey = await Keypair.generate(); + const { gm, unjoinCalls, prepareCalls } = setup({ + wallet: { getKeyPair: async (id: bigint) => (id === 1n ? creatorKey : playerKey) }, + prepare: async (args) => + args.telegramId === "2" ? { success: false, reason: "no sol." } : { success: true }, + }); + const count = await gm.unjoinPlayers(pda, { tokenMint: WSOL_MINT }, [player("2", PLAYER)], "1"); + expect(count).toBe(1); + expect(prepareCalls.map((call) => call.telegramId)).toEqual(["2", "1"]); + expect(unjoinCalls).toEqual([ + [pda, creatorKey, new PublicKey(PLAYER), "2", { skipDbCheck: true }], + ]); + expect(warnings()).toEqual([ + `⚠️ Player ${PLAYER} lacks SOL for unjoin: no sol. Falling back to creator authority.`, + ]); + }); + + test("a creator without fee balance still tries with its own key", async () => { + const creatorKey = await Keypair.generate(); + const { gm, unjoinCalls } = setup({ + wallet: { getKeyPair: async () => creatorKey }, + prepare: async () => ({ success: false, reason: "no sol." }), + }); + const count = await gm.unjoinPlayers( + pda, + { tokenMint: WSOL_MINT }, + [player("1", CREATOR, true)], + "1", + ); + expect(count).toBe(1); + expect(unjoinCalls.map((call) => call[1])).toEqual([creatorKey]); + expect(warnings()).toEqual([ + `⚠️ Player ${CREATOR} lacks SOL for unjoin: no sol. Attempting with remaining balance.`, + ]); + }); + + test("a creator whose own unjoin fails is not retried with the same authority", async () => { + const creatorKey = await Keypair.generate(); + const { gm, unjoinCalls } = setup({ + wallet: { getKeyPair: async () => creatorKey }, + unjoin: async () => { + throw new Error("rpc rejected"); + }, + }); + const count = await gm.unjoinPlayers( + pda, + { tokenMint: WSOL_MINT }, + [player("1", CREATOR, true)], + "1", + ); + expect(count).toBe(0); + expect(unjoinCalls).toHaveLength(1); + }); + + test("the creator fallback warns about its fee balance only when the check fails", async () => { + const creatorKey = await Keypair.generate(); + const { gm, unjoinCalls } = setup({ + wallet: { + getKeyPair: async (id: bigint) => { + if (id === 1n) return creatorKey; + throw new Error("no key"); + }, + }, + }); + const count = await gm.unjoinPlayers(pda, { tokenMint: WSOL_MINT }, [player("2", PLAYER)], "1"); + expect(count).toBe(1); + expect(unjoinCalls).toEqual([ + [pda, creatorKey, new PublicKey(PLAYER), "2", { skipDbCheck: true }], + ]); + expect(warnings()).toEqual([]); + + const failing = setup({ + wallet: { + getKeyPair: async (id: bigint) => { + if (id === 1n) return creatorKey; + throw new Error("no key"); + }, + }, + prepare: async () => ({ success: false, reason: "empty." }), + }); + warnSpy.mockClear(); + await failing.gm.unjoinPlayers(pda, { tokenMint: WSOL_MINT }, [player("2", PLAYER)], "1"); + expect(warnings()).toEqual([ + "⚠️ Creator fallback lacks SOL for unjoin: empty. Attempting with current balance.", + ]); + }); + test("does not count a player when both the player and creator unjoin fail", async () => { const { gm, unjoinCalls } = setup({ unjoin: async () => { From 1dd9aacad44bcc45c3f613030246a541a29e2813 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Mon, 30 Nov 2026 02:44:57 -0300 Subject: [PATCH 307/410] test(game): check completion state reads, recovery schedule, and username cache keys --- src/utils/game.ts | 12 +- tests/game.completion-state.test.ts | 340 ++++++++++++++++++++++++++++ 2 files changed, 346 insertions(+), 6 deletions(-) create mode 100644 tests/game.completion-state.test.ts diff --git a/src/utils/game.ts b/src/utils/game.ts index 9243efe7..a8582a64 100644 --- a/src/utils/game.ts +++ b/src/utils/game.ts @@ -854,13 +854,13 @@ export class GameManager { return; } - const recordGameCompletionFinance = (this.gameDb as any)?.recordGameCompletionFinance; + const recordGameCompletionFinance = (this.gameDb as any).recordGameCompletionFinance; if (typeof recordGameCompletionFinance !== "function") { return; } try { - const currentGame = (this.gameDb as any)?.getGame?.(gameAddress); + const currentGame = (this.gameDb as any).getGame?.(gameAddress); if ( currentGame?.completion_signature && currentGame.completion_signature !== winnerSignature @@ -934,7 +934,7 @@ export class GameManager { return null; } - const persistedStatus = String(gameData?.status ?? "active").toLowerCase(); + const persistedStatus = String(gameData?.status).toLowerCase(); const isTerminal = persistedStatus === "completed" || !!gameData?.winner_address; if (!isTerminal && requestedStatus.toLowerCase() !== "completed") { return null; @@ -942,7 +942,7 @@ export class GameManager { const completionMetadata = this.gameMessageCompletionMetadata.get(gameAddress); const persistedTotalPot = - isTerminal && typeof gameData?.total_amount === "number" ? gameData.total_amount : undefined; + isTerminal && typeof gameData.total_amount === "number" ? gameData.total_amount : undefined; return { status: "Completed", @@ -990,7 +990,7 @@ export class GameManager { const timer = setTimeout(async () => { this.unavailableStateRecoveryTimers.delete(recoveryKey); - const getGame = (this.gameDb as any)?.getGame; + const getGame = (this.gameDb as any).getGame; if (typeof getGame !== "function") { return; } @@ -1020,7 +1020,7 @@ export class GameManager { } catch { return; } - const persistedStatus = String(persisted?.status ?? "active").toLowerCase(); + const persistedStatus = String(persisted?.status).toLowerCase(); if (persistedStatus !== "completed" && !persisted?.winner_address) { this.scheduleUnavailableStateRecovery(ctx, gameAddress, gameType, attempt + 1); } diff --git a/tests/game.completion-state.test.ts b/tests/game.completion-state.test.ts new file mode 100644 index 00000000..85ce1f9c --- /dev/null +++ b/tests/game.completion-state.test.ts @@ -0,0 +1,340 @@ +import { afterEach, beforeEach, describe, expect, spyOn, test } from "bun:test"; +import { GameManager } from "../src/utils/game"; +import { TELEGRAM_USERNAME_CACHE_TTL_MS } from "../src/utils/constants"; + +const GAME = "BPFLoader1111111111111111111111111111111111"; + +const makeManager = (gameDb: any = {}, program: any = { account: { game: {} } }) => + GameManager.getInstance(program, {} as any, gameDb) as any; + +let warn: ReturnType; +beforeEach(() => { + GameManager.resetForTest(); + warn = spyOn(console, "warn").mockImplementation(() => undefined); +}); +afterEach(() => { + warn.mockRestore(); + GameManager.resetForTest(); +}); + +describe("completion signature save", () => { + const recorder = (extra: Record = {}) => { + const recorded: unknown[][] = []; + const reads: string[] = []; + const db = { + getGame: (address: string) => { + reads.push(address); + return null; + }, + recordGameCompletionFinance(this: unknown, ...args: unknown[]) { + recorded.push([this === db, ...args]); + }, + ...extra, + }; + return { db, recorded, reads }; + }; + + test.each([[undefined], [""]])("a missing signature (%p) reads and saves nothing", (sig) => { + const { db, recorded, reads } = recorder(); + makeManager(db).persistCompletionSignature(GAME, 1, { + status: "Completed", + winnerSignature: sig, + }); + expect(reads).toEqual([]); + expect(recorded).toEqual([]); + }); + + // The update at generation 1 saves "sig" unless a newer update holds another signature. + const newer: Array<[string, number, string | undefined, boolean]> = [ + ["a newer different signature blocks the save", 2, "other", false], + ["an update of the same generation does not block the save", 1, "other", true], + ["an older update does not block the save", 0, "other", true], + ["a newer update without a signature does not block the save", 2, undefined, true], + ["a newer update with the same signature does not block the save", 2, "sig", true], + ]; + for (const source of ["latest request", "completion metadata"] as const) { + test.each(newer)(`${source}: %s`, (_name, generation, winnerSignature, saved) => { + const { db, recorded } = recorder(); + const gm = makeManager(db); + const entry = { status: "Completed", generation, winnerSignature }; + if (source === "latest request") gm.latestGameMessageUpdateRequests.set(GAME, entry); + else gm.gameMessageCompletionMetadata.set(GAME, entry); + gm.persistCompletionSignature(GAME, 1, { status: "Completed", winnerSignature: "sig" }); + expect(recorded).toEqual(saved ? [[true, GAME, { signature: "sig" }]] : []); + }); + } + + test("a database without the finance writer is skipped without a read or warning", () => { + const reads: string[] = []; + const gm = makeManager({ getGame: (address: string) => reads.push(address) }); + gm.persistCompletionSignature(GAME, 1, { status: "Completed", winnerSignature: "sig" }); + expect(reads).toEqual([]); + expect(warn).not.toHaveBeenCalled(); + }); + + test("a database without a game reader still saves the signature", () => { + const { db, recorded } = recorder({ getGame: undefined }); + makeManager(db).persistCompletionSignature(GAME, 1, { + status: "Completed", + winnerSignature: "sig", + }); + expect(recorded).toEqual([[true, GAME, { signature: "sig" }]]); + expect(warn).not.toHaveBeenCalled(); + }); + + test("an empty stored signature does not block the save", () => { + const { db, recorded } = recorder({ getGame: () => ({ completion_signature: "" }) }); + makeManager(db).persistCompletionSignature(GAME, 1, { + status: "Completed", + winnerSignature: "sig", + }); + expect(recorded).toEqual([[true, GAME, { signature: "sig" }]]); + }); +}); + +describe("older completion update check", () => { + // Generation 1 is the older update. Generation 2 is the newest generation. + const supersededBy = (latest: Record, request: Record) => { + const gm = makeManager(); + gm.nextGameMessageUpdateGeneration(GAME); + gm.nextGameMessageUpdateGeneration(GAME); + gm.latestGameMessageUpdateRequests.set(GAME, { generation: 2, ...latest }); + return gm.isSupersededActiveGameMessageUpdate(GAME, { status: "Completed", ...request }, 1); + }; + + const cases: Array<[string, Record, Record, boolean]> = [ + ["a different winner", { winnerAddress: "w2" }, { winnerAddress: "w1" }, true], + ["the same winner", { winnerAddress: "w2" }, { winnerAddress: "w2" }, false], + ["no newer winner", {}, { winnerAddress: "w1" }, false], + ["a different pot", { totalPot: 5 }, { totalPot: 4 }, true], + ["the same pot", { totalPot: 5 }, { totalPot: 5 }, false], + ["no newer pot", {}, { totalPot: 4 }, false], + ["a different signature", { winnerSignature: "s2" }, { winnerSignature: "s1" }, true], + ["the same signature", { winnerSignature: "s2" }, { winnerSignature: "s2" }, false], + ["no newer signature", {}, { winnerSignature: "s1" }, false], + ]; + test.each(cases)("a newer completion with %s", (_name, latest, request, expected) => { + expect(supersededBy({ status: "Completed", ...latest }, request)).toBe(expected); + expect(supersededBy({ status: "COMPLETED", ...latest }, request)).toBe(expected); + }); + + test("a newer active request never supersedes an older completion", () => { + expect(supersededBy({ status: "Active", winnerAddress: "w2" }, { winnerAddress: "w1" })).toBe( + false, + ); + }); + + test("a remembered request of the same generation does not supersede the update", () => { + const gm = makeManager(); + gm.nextGameMessageUpdateGeneration(GAME); + gm.nextGameMessageUpdateGeneration(GAME); + gm.latestGameMessageUpdateRequests.set(GAME, { + generation: 1, + status: "Completed", + winnerAddress: "w2", + }); + expect( + gm.isSupersededActiveGameMessageUpdate(GAME, { status: "Completed", winnerAddress: "w1" }, 1), + ).toBe(false); + }); +}); + +describe("persisted terminal state", () => { + const terminal = (game: unknown, requested = "Active", metadata?: Record) => { + const gm = makeManager({ getGame: () => game }); + if (metadata) gm.gameMessageCompletionMetadata.set(GAME, { generation: 1, ...metadata }); + return gm.getPersistedTerminalUpdate(GAME, requested, "arg-w", 9, "arg-s"); + }; + const fromArgs = { + status: "Completed", + winnerAddress: "arg-w", + totalPot: 9, + winnerSignature: "arg-s", + }; + + test.each([ + ["no game row", null], + ["an active row", { status: "active" }], + ["a row without a status", {}], + ])("%s is not terminal for an active request", (_name, game) => { + expect(terminal(game)).toBeNull(); + }); + + test.each([ + ["a completed status", { status: "completed" }], + ["an upper case completed status", { status: "COMPLETED" }], + ["a winner without a completed status", { status: "active", winner_address: "db-w" }], + ])("%s is terminal for an active request", (_name, game) => { + expect(terminal(game)?.status).toBe("Completed"); + }); + + test.each([["Completed"], ["COMPLETED"], ["completed"]])( + "a %s request without a stored game uses its own fields", + (requested) => { + expect(terminal(null, requested)).toEqual(fromArgs); + }, + ); + + test("stored fields win over completion metadata and request fields", () => { + expect( + terminal( + { + status: "completed", + winner_address: "db-w", + total_amount: 0, + completion_signature: "db-s", + }, + "Active", + { winnerAddress: "meta-w", totalPot: 7, winnerSignature: "meta-s" }, + ), + ).toEqual({ status: "Completed", winnerAddress: "db-w", totalPot: 0, winnerSignature: "db-s" }); + }); + + test("completion metadata wins over request fields", () => { + expect( + terminal({ status: "completed" }, "Active", { + winnerAddress: "meta-w", + totalPot: 7, + winnerSignature: "meta-s", + }), + ).toEqual({ + status: "Completed", + winnerAddress: "meta-w", + totalPot: 7, + winnerSignature: "meta-s", + }); + }); + + test("a stored pot counts only for a terminal row with a numeric amount", () => { + expect(terminal({ status: "completed", total_amount: "5" })?.totalPot).toBe(9); + expect(terminal({ status: "active", total_amount: 5 }, "Completed")?.totalPot).toBe(9); + expect(terminal({ status: "completed", total_amount: 5 })?.totalPot).toBe(5); + }); +}); + +describe("recovery account read", () => { + test.each([ + ["an account", { id: 1 }, { id: 1 }], + ["a missing account", undefined, null], + ])("a nullable read of %s", async (_name, account, expected) => { + const gm = makeManager({}, { account: { game: { fetchNullable: async () => account } } }); + expect(await gm.fetchGameAccountForRecovery(GAME)).toEqual(expected); + }); +}); + +describe("unavailable state recovery schedule", () => { + type Scheduled = { callback: () => Promise; delay: number; unrefs: number }; + let scheduled: Scheduled[]; + let original: typeof setTimeout; + let withUnref: boolean; + beforeEach(() => { + scheduled = []; + withUnref = true; + original = globalThis.setTimeout; + globalThis.setTimeout = ((callback: () => Promise, delay?: number) => { + const entry: Scheduled = { callback, delay: delay ?? 0, unrefs: 0 }; + scheduled.push(entry); + return withUnref ? { unref: () => (entry.unrefs += 1) } : {}; + }) as unknown as typeof setTimeout; + }); + afterEach(() => { + globalThis.setTimeout = original; + }); + + const ctx = { chat: { id: 77 } }; + + test.each([ + ["a chat without an ID", {}, 0], + ["a string chat ID", { chat: { id: "77" } }, 0], + ["the last attempt", ctx, 3], + ])("%s is not scheduled", (_name, context, attempt) => { + const gm = makeManager({ getGame: () => ({}) }); + gm.scheduleUnavailableStateRecovery(context, GAME, "coinflip", attempt); + expect(scheduled).toEqual([]); + expect(gm.unavailableStateRecoveryTimers.size).toBe(0); + }); + + test("each attempt uses its delay, is keyed by game and chat, and does not hold the process", () => { + const delays: number[] = []; + for (const attempt of [0, 1, 2]) { + GameManager.resetForTest(); + const gm = makeManager({ getGame: () => ({}) }); + gm.scheduleUnavailableStateRecovery(ctx, GAME, "coinflip", attempt); + expect([...gm.unavailableStateRecoveryTimers.keys()]).toEqual([`${GAME}:77`]); + delays.push(scheduled.at(-1)!.delay); + } + expect(delays).toEqual([1_000, 5_000, 15_000]); + expect(scheduled.map((entry) => entry.unrefs)).toEqual([1, 1, 1]); + }); + + test("a timer without unref is still scheduled", () => { + withUnref = false; + const gm = makeManager({ getGame: () => ({}) }); + gm.scheduleUnavailableStateRecovery(ctx, GAME, "coinflip"); + expect(scheduled).toHaveLength(1); + expect(gm.unavailableStateRecoveryTimers.size).toBe(1); + }); + + const afterRefresh = async (stored: unknown, refreshFails = false) => { + let reads = 0; + const gm = makeManager( + { getGame: () => (reads++ === 0 ? { status: "active" } : stored) }, + { account: { game: { fetchNullable: async () => ({}) } } }, + ); + spyOn(gm, "updateGameMessageFromData").mockImplementation(async () => { + if (refreshFails) throw new Error("synthetic refresh failure"); + }); + gm.scheduleUnavailableStateRecovery(ctx, GAME, "coinflip"); + await scheduled[0]!.callback(); + return scheduled.slice(1).map((entry) => entry.delay); + }; + + test.each([ + ["an active game", { status: "active" }, [5_000]], + ["a game without a status", {}, [5_000]], + ["a missing game", null, [5_000]], + ["a completed game", { status: "Completed" }, []], + ["a game with a winner", { status: "active", winner_address: "w" }, []], + ])("after a refresh, %s is checked again only while it is open", async (_n, stored, next) => { + expect(await afterRefresh(stored)).toEqual(next); + }); + + test("a failed refresh is logged and tried again after the next delay", async () => { + expect(await afterRefresh({ status: "completed" }, true)).toEqual([5_000]); + expect(warn).toHaveBeenCalledWith( + `Game state recovery attempt failed for ${GAME}:`, + expect.any(Error), + ); + }); +}); + +describe("username cache keys", () => { + test.each([ + ["the chat ID", { chat: { id: 5 }, from: { id: 6 } }, "5:t"], + ["a zero chat ID", { chat: { id: 0 }, from: { id: 6 } }, "0:t"], + ["the sender ID without a chat", { from: { id: 6 } }, "6:t"], + ["the global scope without a chat or sender", {}, "global:t"], + ])("a key uses %s", (_name, ctx, key) => { + expect(makeManager().buildUsernameCacheKey(ctx, "t")).toBe(key); + }); + + test("a tracked name key moves to the end without a copy", () => { + const gm = makeManager(); + for (const key of ["a", "b", "a"]) gm.setCachedUsername(key, "@n"); + expect(gm.usernameCacheKeys).toEqual(["b", "a"]); + for (const key of ["x", "y", "x"]) gm.setCachedTelegramIdForUsername(key, "1"); + expect(gm.usernameToIdCacheKeys).toEqual(["y", "x"]); + }); + + test("a failed name lookup is kept for at most 30 seconds", () => { + const gm = makeManager(); + const ttl = spyOn(gm.usernameCache, "setWithTTL"); + gm.setCachedUsername("a", null); + gm.setCachedUsername("b", "@n"); + expect(ttl.mock.calls).toEqual([ + ["a", null, Math.min(TELEGRAM_USERNAME_CACHE_TTL_MS, 30_000)], + ["b", "@n", TELEGRAM_USERNAME_CACHE_TTL_MS], + ]); + expect(TELEGRAM_USERNAME_CACHE_TTL_MS).toBeGreaterThan(30_000); + }); +}); From 9234157d04288155d2f49ff188a971488ae70b09 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Mon, 30 Nov 2026 02:47:28 -0300 Subject: [PATCH 308/410] test(mutants): ignore text literals in console log arguments --- scripts/stryker-ignorers.mjs | 86 ++++++++++++++++++- scripts/stryker-ignorers.test.ts | 138 ++++++++++++++++++++++++++++++- stryker.conf.mjs | 4 +- 3 files changed, 220 insertions(+), 8 deletions(-) diff --git a/scripts/stryker-ignorers.mjs b/scripts/stryker-ignorers.mjs index c4e2a1ba..b924d77d 100644 --- a/scripts/stryker-ignorers.mjs +++ b/scripts/stryker-ignorers.mjs @@ -20,5 +20,87 @@ export const debugTraceIgnorer = { }, }; -// The same object that declareValuePlugin(PluginKind.Ignore, ...) from @stryker-mutator/api builds. -export const strykerPlugins = [{ kind: "Ignore", name: "debug-trace", value: debugTraceIgnorer }]; +/** Console methods whose text goes only to the operator log. */ +export const CONSOLE_LOG_METHODS = new Set(["log", "info", "warn", "error", "debug"]); + +/** Methods that no Stryker mutator changes. They only convert a key or value to text. */ +const PLAIN_TEXT_METHODS = new Set(["toBase58", "toString"]); + +/** + * True for a plain, non-optional `a.b` read of a plain value. + * @param {any} node + * @returns {boolean} + */ +const isPlainMember = (node) => + node?.type === "MemberExpression" && + !node.computed && + !node.optional && + node.property?.type === "Identifier" && + isPlainValue(node.object); + +/** + * True for a value that has no mutants of its own: a name, `this`, a plain `a.b` + * read, or `a.toBase58()` / `a.toString()` without arguments. A template literal + * made only of these can be ignored as a whole. + * @param {any} node + * @returns {boolean} + */ +const isPlainValue = (node) => + node?.type === "Identifier" || + node?.type === "ThisExpression" || + isPlainMember(node) || + (node?.type === "CallExpression" && + !node.optional && + node.arguments.length === 0 && + isPlainMember(node.callee) && + PLAIN_TEXT_METHODS.has(node.callee.property.name)); + +/** + * @param {any} node + * @returns {boolean} + */ +const isConsoleLogCall = (node) => + node?.type === "CallExpression" && + node.callee?.type === "MemberExpression" && + !node.callee.computed && + node.callee.object?.type === "Identifier" && + node.callee.object.name === "console" && + node.callee.property?.type === "Identifier" && + CONSOLE_LOG_METHODS.has(node.callee.property.name); + +/** + * Ignores only text literals in console arguments. Other mutants in the same call, + * such as a changed condition or a missing optional read, are still tested. + * @type {import("@stryker-mutator/api/ignore").Ignorer} + */ +export const consoleTextIgnorer = { + shouldIgnore(path) { + /** @type {any} */ + let current = path; + const node = current?.node; + const isText = + node?.type === "StringLiteral" || + (node?.type === "TemplateLiteral" && node.expressions.every(isPlainValue)); + if (!isText) { + return undefined; + } + // Walk up through string joins and template parts to the call argument. + while ( + current.parentPath?.node?.type === "TemplateLiteral" || + (current.parentPath?.node?.type === "BinaryExpression" && + current.parentPath.node.operator === "+") + ) { + current = current.parentPath; + } + if (current.listKey === "arguments" && isConsoleLogCall(current.parentPath?.node)) { + return "Operator log text. Console output does not change what the bot does or shows to players."; + } + return undefined; + }, +}; + +// The same objects that declareValuePlugin(PluginKind.Ignore, ...) from @stryker-mutator/api builds. +export const strykerPlugins = [ + { kind: "Ignore", name: "debug-trace", value: debugTraceIgnorer }, + { kind: "Ignore", name: "console-text", value: consoleTextIgnorer }, +]; diff --git a/scripts/stryker-ignorers.test.ts b/scripts/stryker-ignorers.test.ts index 050750bb..4364d9ee 100644 --- a/scripts/stryker-ignorers.test.ts +++ b/scripts/stryker-ignorers.test.ts @@ -1,5 +1,5 @@ import { describe, expect, test } from "bun:test"; -import { debugTraceIgnorer, strykerPlugins } from "./stryker-ignorers.mjs"; +import { consoleTextIgnorer, debugTraceIgnorer, strykerPlugins } from "./stryker-ignorers.mjs"; // The smallest Babel NodePath shapes the ignorer reads. const identifier = (name: string) => ({ type: "Identifier", name }); @@ -38,10 +38,140 @@ describe("Stryker debug trace ignorer", () => { test("registers the ignorer under the name used in the Stryker config", async () => { const config = (await import("../stryker.conf.mjs")).default as any; - expect(config.ignorers).toEqual(["debug-trace"]); + expect(config.ignorers).toEqual(["debug-trace", "console-text"]); expect(config.appendPlugins).toContain("./scripts/stryker-ignorers.mjs"); - expect(strykerPlugins.map((plugin: any) => [plugin.kind, plugin.name])).toEqual([ - ["Ignore", "debug-trace"], + expect(strykerPlugins.map((plugin: any) => [plugin.kind, plugin.name, plugin.value])).toEqual([ + ["Ignore", "debug-trace", debugTraceIgnorer], + ["Ignore", "console-text", consoleTextIgnorer], ]); }); }); + +// Small Babel node builders. A node marked with `target` is the one the ignorer sees. +type Node = { type: string; target?: boolean; [key: string]: unknown }; +const id = (name: string): Node => ({ type: "Identifier", name }); +const str = (value: string, target = false): Node => ({ type: "StringLiteral", value, target }); +const tpl = (expressions: Node[], target = false): Node => ({ + type: "TemplateLiteral", + quasis: [], + expressions, + target, +}); +const member = (object: Node, property: string, flags: Record = {}): Node => ({ + type: "MemberExpression", + object, + property: id(property), + computed: false, + optional: false, + ...flags, +}); +const callOf = (callee: Node, args: Node[] = [], optional = false): Node => ({ + type: "CallExpression", + callee, + arguments: args, + optional, +}); +const plus = (left: Node, right: Node, operator = "+"): Node => ({ + type: "BinaryExpression", + operator, + left, + right, +}); +const consoleCall = (method: string, args: Node[]) => callOf(member(id("console"), method), args); + +// Builds the NodePath of the target node, with parentPath and listKey like Babel. +function pathOf(root: Node) { + const visit = (node: Node, parentPath: unknown, listKey?: string): unknown => { + const path = { node, parentPath, listKey }; + if (node.target) return path; + for (const [key, value] of Object.entries(node)) { + const children = Array.isArray(value) ? value : [value]; + for (const child of children) { + if (child && typeof child === "object" && "type" in child) { + const found = visit(child as Node, path, Array.isArray(value) ? key : undefined); + if (found) return found; + } + } + } + return undefined; + }; + const found = visit(root, undefined); + if (!found) throw new Error("no target node"); + return found as any; +} + +describe("Stryker console text ignorer", () => { + const ignored = (root: Node) => consoleTextIgnorer.shouldIgnore(pathOf(root)); + + test.each([ + ["a string argument", consoleCall("warn", [str("text", true), id("error")])], + ["each console method", consoleCall("debug", [str("text", true)])], + [ + "a string in a joined argument", + consoleCall("error", [plus(plus(str("a", true), id("x")), str("b"))]), + ], + [ + "a template of names", + consoleCall("log", [tpl([id("address"), member(id("game"), "id")], true)]), + ], + [ + "a template with this", + consoleCall("info", [tpl([member({ type: "ThisExpression" }, "name")], true)]), + ], + [ + "a template with a key conversion", + consoleCall("warn", [tpl([callOf(member(id("pda"), "toBase58"))], true)]), + ], + [ + "a string inside a template part", + consoleCall("warn", [tpl([plus(str("a", true), id("b"))])]), + ], + ])("ignores %s", (_name, root) => { + expect(ignored(root)).toBe( + "Operator log text. Console output does not change what the bot does or shows to players.", + ); + }); + + test.each([ + [ + "a template with an optional read", + consoleCall("warn", [tpl([member(id("a"), "b", { optional: true })], true)]), + ], + [ + "a template with a computed read", + consoleCall("warn", [tpl([member(id("a"), "b", { computed: true })], true)]), + ], + [ + "a template with another method", + consoleCall("warn", [tpl([callOf(member(id("s"), "trim"))], true)]), + ], + [ + "a template with an argument call", + consoleCall("warn", [tpl([callOf(member(id("a"), "toString"), [id("radix")])], true)]), + ], + [ + "a template with an optional call", + consoleCall("warn", [tpl([callOf(member(id("a"), "toString"), [], true)], true)]), + ], + ["a template with a sum", consoleCall("warn", [tpl([plus(id("a"), id("b"))], true)])], + [ + "a string compared inside the argument", + consoleCall("warn", [plus(str("a", true), id("b"), "===")]), + ], + [ + "a string passed to a nested call", + consoleCall("warn", [callOf(id("format"), [str("a", true)])]), + ], + ["a string as the callee object", callOf(member(str("a", true), "warn"))], + ["another logger", callOf(member(id("logger"), "warn"), [str("a", true)])], + ["a console method that is not a log", consoleCall("table", [str("a", true)])], + [ + "a computed console method", + callOf(member(id("console"), "warn", { computed: true }), [str("a", true)]), + ], + ["a user message", callOf(member(id("ctx"), "reply"), [str("a", true)])], + ["a node that is not text", consoleCall("warn", [{ ...id("error"), target: true }])], + ])("keeps mutants in %s", (_name, root) => { + expect(ignored(root)).toBeUndefined(); + }); +}); diff --git a/stryker.conf.mjs b/stryker.conf.mjs index cc5f928a..82ff746e 100644 --- a/stryker.conf.mjs +++ b/stryker.conf.mjs @@ -4,8 +4,8 @@ /** @type {import('@stryker-mutator/api/core').PartialStrykerOptions} */ export default { appendPlugins: ["@hughescr/stryker-bun-runner", "./scripts/stryker-ignorers.mjs"], - // Skip mutants that only change debug trace text (see scripts/stryker-ignorers.mjs). - ignorers: ["debug-trace"], + // Skip mutants that only change debug trace or console log text (see scripts/stryker-ignorers.mjs). + ignorers: ["debug-trace", "console-text"], testRunner: "bun", // The same isolation `bun run test` uses. // timeout bounds only the dry run, the whole suite once with coverage (about a minute in CI). From e2b7cf8736e4f0cd1ebc63844dd0f10d379e60f6 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Mon, 30 Nov 2026 02:50:26 -0300 Subject: [PATCH 309/410] test(game): check expired giveaway timing and coinflip creator lookup --- src/utils/game.ts | 7 +- ...game-manager.expired-cleanup-paths.test.ts | 249 ++++++++++++++++++ 2 files changed, 252 insertions(+), 4 deletions(-) create mode 100644 tests/game-manager.expired-cleanup-paths.test.ts diff --git a/src/utils/game.ts b/src/utils/game.ts index a8582a64..0b3687c3 100644 --- a/src/utils/game.ts +++ b/src/utils/game.ts @@ -8488,6 +8488,7 @@ export class GameManager { return gameAccount.creator instanceof PublicKey ? gameAccount.creator : new PublicKey(gameAccount.creator); + // Stryker disable next-line BlockStatement: undefined and null are both no creator key here. } catch (_) { return null; } @@ -8498,10 +8499,8 @@ export class GameManager { } if (!creatorTelegramId && typeof this.gameDb.getCreatorInfo === "function") { - const info = this.gameDb.getCreatorInfo(address); - if (info?.telegramId) { - creatorTelegramId = info.telegramId; - } + // A missing or empty ID stays falsy, so the check below still stops the cancel. + creatorTelegramId = this.gameDb.getCreatorInfo(address)?.telegramId ?? null; } if (!creatorTelegramId) { diff --git a/tests/game-manager.expired-cleanup-paths.test.ts b/tests/game-manager.expired-cleanup-paths.test.ts new file mode 100644 index 00000000..b4e34160 --- /dev/null +++ b/tests/game-manager.expired-cleanup-paths.test.ts @@ -0,0 +1,249 @@ +import { afterEach, beforeEach, describe, expect, spyOn, test } from "bun:test"; +import { PublicKey } from "#solana"; +import { GameManager } from "../src/utils/game"; + +const GAME = new PublicKey("BPFLoader1111111111111111111111111111111111"); +const ADDRESS = GAME.toBase58(); +const CREATOR = new PublicKey("Vote111111111111111111111111111111111111111"); + +let warn: ReturnType; +beforeEach(() => { + GameManager.resetForTest(); + warn = spyOn(console, "warn").mockImplementation(() => undefined); +}); +afterEach(() => { + warn.mockRestore(); + GameManager.resetForTest(); +}); + +const manager = (db: Record = {}) => + GameManager.getInstance({ account: { game: {} } } as any, {} as any, db as any) as any; + +describe("display amount and game type", () => { + test.each([ + ["a giveaway prize", { giveaway: {} }, 7, 3, 7], + ["a giveaway without a prize total", { giveaway: {} }, 0, 3, 3], + ["a giveaway with a negative total", { giveaway: {} }, -1, 3, 3], + ["a giveaway with a broken total", { giveaway: {} }, "x", 3, 3], + ["a coinflip ticket", { coinflip: {} }, 7, 3, 3], + ["a broken ticket amount", { coinflip: {} }, 7, "x", 0], + ])("%s", (_name, gameType, totalAmount, ticketAmount, expected) => { + expect(manager().getDisplayAmountFromAccount({ gameType, totalAmount, ticketAmount })).toBe( + expected, + ); + }); + + test.each([ + ["a missing account", undefined, "game"], + ["a text game type", { gameType: "coinflip" }, "game"], + ["an empty game type", { gameType: {} }, "unknown"], + ["an unnamed game type", { gameType: { "": {} } }, "game"], + ["a named game type", { gameType: { giveaway: {} } }, "giveaway"], + ])("the game type of %s", (_name, account, expected) => { + expect(manager().getGameType(account)).toBe(expected); + }); +}); + +describe("expired giveaway timing", () => { + const giveaway = async (account: Record, bufferElapsed: boolean) => { + const gm = manager(); + const cancels: unknown[][] = []; + gm.cancelGameWithPlayerKeys = async (...args: unknown[]) => { + cancels.push(args); + return { success: true }; + }; + gm.isGameExpiredWithBuffer = () => bufferElapsed; + const handled = await gm.handleExpiredGiveaway( + GAME, + { gameType: { giveaway: {} }, ...account }, + ADDRESS, + ); + return { handled, cancels }; + }; + + test.each([ + ["no tickets", { ticketsCount: 0, minTickets: 2 }], + ["fewer tickets than the minimum", { ticketsCount: 1, minTickets: 2 }], + ["no ticket count", { minTickets: 2 }], + ])("%s closes before the oracle buffer", async (_name, account) => { + expect(await giveaway(account, false)).toEqual({ + handled: true, + cancels: [[GAME, "giveaway"]], + }); + }); + + test.each([ + ["exactly the minimum", { ticketsCount: 2, minTickets: 2 }], + ["a negative count without a minimum", { ticketsCount: -1, minTickets: 0 }], + ["tickets without a minimum", { ticketsCount: 1 }], + ])("%s waits for the oracle buffer", async (_name, account) => { + expect(await giveaway(account, false)).toEqual({ handled: false, cancels: [] }); + expect(await giveaway(account, true)).toEqual({ + handled: true, + cancels: [[GAME, "giveaway"]], + }); + }); +}); + +describe("expired coinflip checks", () => { + type Keys = Record; + const coinflip = async ( + keys: Keys, + account: Record = {}, + db: Record = {}, + ) => { + const removed: unknown[][] = []; + const gm = manager({ + getGameParticipants: () => [], + removeGameParticipant: (...args: unknown[]) => removed.push(args), + ...db, + }); + const cancels: unknown[][] = []; + const cleanups: string[] = []; + gm.reconcilePendingParticipants = async () => undefined; + gm.analyzePlayerKeys = () => ({ available: [], total: 0, ...keys }); + gm.cancelGameWithCreator = async (...args: unknown[]) => { + cancels.push(args.slice(2)); + return true; + }; + gm.executeCompleteCleanup = async () => cleanups.push("complete"); + gm.executePartialCleanup = async () => cleanups.push("partial"); + const handled = await gm.handleExpiredCoinflip( + GAME, + { ticketsCount: 2, creator: CREATOR.toBase58(), ...account }, + ADDRESS, + ); + return { + handled, + cancels, + cleanups, + removed, + warnings: warn.mock.calls.map((call: unknown[]) => call[0]), + }; + }; + + test("matching counts give no warning and use the cleanup the keys allow", async () => { + const full = await coinflip( + { + onChainTickets: 2, + onChainParticipants: 2, + dbParticipantCount: 2, + canCompleteCleanup: true, + }, + {}, + ); + expect(full.cleanups).toEqual(["complete"]); + expect(full.warnings).toEqual([]); + const partial = await coinflip( + { unmatchedParticipants: [] }, + { participants: ["a", "b"] }, + { + getGameParticipants: () => ["1", "2"], + }, + ); + expect(partial.cleanups).toEqual(["partial"]); + expect(partial.warnings).toEqual([]); + }); + + test("the analyzed participant count wins over the account list", async () => { + const result = await coinflip( + { onChainTickets: 3, onChainParticipants: 3, dbParticipantCount: 3 }, + { participants: ["a"] }, + ); + expect(result.warnings).toEqual([]); + }); + + test("each count mismatch and unmapped participant is reported", async () => { + const result = await coinflip( + { + onChainTickets: 3, + onChainParticipants: 2, + dbParticipantCount: 1, + unmatchedParticipants: ["x"], + }, + {}, + ); + expect(result.warnings).toEqual([ + `⚠️ Participant mismatch for ${ADDRESS}: on-chain tickets 3, participant list length 2`, + `⚠️ Database mismatch for ${ADDRESS}: on-chain tickets 3, local participants 1`, + `⚠️ Unable to map 1 participant(s) for ${ADDRESS}`, + ]); + }); + + const emptyGame = (db: Record, keys: Keys = {}) => + coinflip({ onChainTickets: 0, onChainParticipants: 0, dbParticipantCount: 0, ...keys }, {}, db); + + test("an empty game without stale rows cancels with the analyzed creator", async () => { + const result = await emptyGame( + { getCreatorInfo: () => ({ telegramId: "other" }) }, + { creator: { telegramId: "42" } }, + ); + expect(result.cancels).toEqual([["42", ADDRESS, "coinflip"]]); + expect(result.removed).toEqual([]); + expect(result.warnings).toEqual([]); + }); + + test("an empty game removes each stale local participant before the cancel", async () => { + const result = await emptyGame({ + getGameParticipants: () => ["1", "2"], + getCreatorTelegramId: () => "42", + }); + expect(result.removed).toEqual([ + [ADDRESS, "1"], + [ADDRESS, "2"], + ]); + expect(result.cancels).toEqual([["42", ADDRESS, "coinflip"]]); + }); + + test.each([ + ["the creator lookup", { getCreatorTelegramId: () => "41" }, "41"], + [ + "the creator wallet", + { getPlayerTelegramId: (key: string) => (key === CREATOR.toBase58() ? "43" : null) }, + "43", + ], + ["the stored creator row", { getCreatorInfo: () => ({ telegramId: "44" }) }, "44"], + [ + "the first source that has an ID", + { getCreatorTelegramId: () => "41", getCreatorInfo: () => ({ telegramId: "44" }) }, + "41", + ], + ] as Array<[string, Record, string]>)( + "an empty game finds the creator from %s", + async (_name, db, expected) => { + const result = await emptyGame(db); + expect(result.cancels).toEqual([[expected, ADDRESS, "coinflip"]]); + }, + ); + + test.each([ + ["no creator source", {}], + ["a missing creator row", { getCreatorInfo: () => null }], + ["a creator row without an ID", { getCreatorInfo: () => ({ telegramId: null }) }], + ["a creator row with an empty ID", { getCreatorInfo: () => ({ telegramId: "" }) }], + ] as Array<[string, Record]>)( + "an empty game with %s is not cancelled", + async (_name, db) => { + const result = await emptyGame(db); + expect(result.handled).toBe(false); + expect(result.cancels).toEqual([]); + expect(result.warnings).toEqual([ + `⚠️ Cannot cancel ${ADDRESS}: creator Telegram ID is missing from local data`, + ]); + }, + ); + + test("an empty game with a broken creator key uses the stored creator row", async () => { + const reads: string[] = []; + const result = await coinflip( + { onChainTickets: 0, onChainParticipants: 0, dbParticipantCount: 0 }, + { creator: "not a key" }, + { + getPlayerTelegramId: (key: string) => reads.push(key), + getCreatorInfo: () => ({ telegramId: "44" }), + }, + ); + expect(reads).toEqual([]); + expect(result.cancels).toEqual([["44", ADDRESS, "coinflip"]]); + }); +}); From 82a7313008f63cc8e8a7a5f6228d22dde6959c2a Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Mon, 30 Nov 2026 02:54:52 -0300 Subject: [PATCH 310/410] test(game): check each confirmed game setting before hydration --- tests/game.create-game.test.ts | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/tests/game.create-game.test.ts b/tests/game.create-game.test.ts index d100075a..a46c2a6e 100644 --- a/tests/game.create-game.test.ts +++ b/tests/game.create-game.test.ts @@ -541,6 +541,15 @@ describe("createGame confirmed-account verification", () => { mismatch("Confirmed game account does not match the requested configuration", { maxTickets: 9, }), + mismatch("Confirmed game account does not match the requested configuration", { + gameType: { giveaway: {} }, + }), + mismatch("Confirmed game account does not match the requested configuration", { + ticketAmount: AMOUNT + 1, + }), + mismatch("Confirmed game account does not match the requested configuration", { + minTickets: 3, + }), mismatch("Confirmed game timeout does not match the requested configuration", { timeout: 61, }), @@ -569,6 +578,18 @@ describe("createGame confirmed-account verification", () => { ); }); + test.each([ + ["no timeout or visibility", { timeout: null, isPrivate: null }], + ["the requested timeout and visibility", { timeout: 60, isPrivate: false }], + ["limits stored as text", { maxTickets: "2", minTickets: "2", timeout: "60" }], + ])("accepts a confirmed account with %s", async (_label, account) => { + const db = durableDb(); + const { gm } = await setup({ db, account }); + const result = await create(gm); + expect(result.success).toBe(true); + expect(db.saveGame).toHaveBeenCalledTimes(1); + }); + test("stores the on-chain creation timing and forwards it to the pending record", async () => { const setPendingGameCreationChainTiming = vi.fn(); const db = durableDb({ setPendingGameCreationChainTiming }); From 46b606af99aeb6518a8f5535efa4be4584098595 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Mon, 30 Nov 2026 02:57:52 -0300 Subject: [PATCH 311/410] test(game): check player key analysis and complete cleanup --- src/utils/game.ts | 13 +- tests/game-manager.player-keys.test.ts | 195 +++++++++++++++++++++++++ 2 files changed, 201 insertions(+), 7 deletions(-) create mode 100644 tests/game-manager.player-keys.test.ts diff --git a/src/utils/game.ts b/src/utils/game.ts index 0b3687c3..423cf84f 100644 --- a/src/utils/game.ts +++ b/src/utils/game.ts @@ -8541,6 +8541,7 @@ export class GameManager { gameAccount.creator instanceof PublicKey ? gameAccount.creator : new PublicKey(gameAccount.creator); + // Stryker disable next-line BlockStatement: an unset key and null are both read as no creator key. } catch (_) { creatorPubkey = null; } @@ -8576,6 +8577,7 @@ export class GameManager { for (const telegramId of participantTelegramIds) { try { const playerPubkeyStr = this.gameDb.getPlayerPublicKey(telegramId); + // Stryker disable next-line ConditionalExpression,BlockStatement: a missing key also fails the parse below, and the catch marks it unavailable too. if (!playerPubkeyStr) { unavailable.push(telegramId); continue; @@ -8604,11 +8606,7 @@ export class GameManager { unavailable.push(creatorPubkey.toBase58()); } - if (unmatchedParticipants.length > 0) { - for (const participant of unmatchedParticipants) { - unavailable.push(participant); - } - } + unavailable.push(...unmatchedParticipants); const totalParticipants = Math.max( participantTelegramIds.size, @@ -8647,12 +8645,13 @@ export class GameManager { " players, then cancel", ); - // Unjoin ALL players including creator for coinflip games + // Unjoin ALL players including creator for coinflip games. This strategy + // runs only when the analysis found the creator key. const unjoinedCount = await this.unjoinPlayers( gamePda, gameAccount, playerKeyInfo.available, - playerKeyInfo.creator?.telegramId, + playerKeyInfo.creator.telegramId, ); // Only proceed if all players were successfully unjoined diff --git a/tests/game-manager.player-keys.test.ts b/tests/game-manager.player-keys.test.ts new file mode 100644 index 00000000..5d8e2756 --- /dev/null +++ b/tests/game-manager.player-keys.test.ts @@ -0,0 +1,195 @@ +import { afterEach, beforeEach, describe, expect, spyOn, test } from "bun:test"; +import { PublicKey } from "#solana"; +import { GameManager } from "../src/utils/game"; + +const GAME = new PublicKey("BPFLoader1111111111111111111111111111111111"); +const ADDRESS = GAME.toBase58(); +const CREATOR = new PublicKey("Vote111111111111111111111111111111111111111"); +const PLAYER = new PublicKey("Stake11111111111111111111111111111111111111"); + +let warn: ReturnType; +beforeEach(() => { + GameManager.resetForTest(); + warn = spyOn(console, "warn").mockImplementation(() => undefined); +}); +afterEach(() => { + warn.mockRestore(); + GameManager.resetForTest(); +}); + +type Setup = { + players?: string[]; + keys?: Record; + creatorId?: () => string | null; + unmatched?: string[]; + db?: Record; +}; + +function analyze(account: Record, options: Setup = {}) { + const db: Record = { + getPlayerTelegramId: options.creatorId ?? (() => null), + getPlayerPublicKey: (id: string) => options.keys?.[id] ?? null, + ...options.db, + }; + const gm = GameManager.getInstance({ account: { game: {} } } as any, {} as any, db as any) as any; + gm.getGamePlayers = () => options.players ?? []; + gm.recoverParticipantsFromChain = () => ({ + recovered: [], + unmatchedParticipants: options.unmatched ?? [], + }); + const info = gm.analyzePlayerKeys(GAME, account, ADDRESS); + return { info, warnings: warn.mock.calls.map((call: unknown[]) => call) }; +} + +describe("player key analysis", () => { + test("a creator with a key and a mapped player can be cleaned up completely", () => { + const { info, warnings } = analyze( + { creator: CREATOR, ticketsCount: 2 }, + { + players: ["2"], + keys: { "1": CREATOR.toBase58(), "2": PLAYER.toBase58() }, + creatorId: () => "1", + }, + ); + expect(info.available).toEqual([ + { pubkey: PLAYER, telegramId: "2", isCreator: false }, + { pubkey: CREATOR, telegramId: "1", isCreator: true }, + ]); + expect(info.creator).toEqual({ pubkey: CREATOR, telegramId: "1", isCreator: true }); + expect(info.nonCreators).toEqual([{ pubkey: PLAYER, telegramId: "2", isCreator: false }]); + expect(info.unavailable).toEqual([]); + expect(info.canCompleteCleanup).toBe(true); + expect(info).toMatchObject({ total: 2, onChainTickets: 2, dbParticipantCount: 1 }); + expect(warnings).toEqual([]); + }); + + test("a creator without a stored key is added with the account key but blocks a complete cleanup", () => { + const { info } = analyze( + { creator: CREATOR.toBase58(), ticketsCount: 1 }, + { creatorId: () => "1" }, + ); + expect(info.available).toEqual([{ pubkey: CREATOR, telegramId: "1", isCreator: true }]); + expect(info.unavailable).toEqual(["1"]); + expect(info.canCompleteCleanup).toBe(false); + }); + + test("an unknown creator is unavailable and blocks a complete cleanup", () => { + const { info, warnings } = analyze( + { creator: CREATOR, ticketsCount: 3 }, + { players: ["2"], keys: { "2": PLAYER.toBase58() } }, + ); + expect(info.available).toEqual([{ pubkey: PLAYER, telegramId: "2", isCreator: false }]); + expect(info.creator).toBeUndefined(); + expect(info.unavailable).toEqual([CREATOR.toBase58()]); + expect(info.canCompleteCleanup).toBe(false); + expect(info.total).toBe(3); + expect(warnings).toEqual([ + ["⚠️ Unable to resolve creator Telegram ID for orphaned game " + ADDRESS], + ]); + }); + + test("a database without the wallet reader leaves the creator unknown", () => { + const { info, warnings } = analyze( + { creator: CREATOR }, + { db: { getPlayerTelegramId: undefined } }, + ); + expect(info.unavailable).toEqual([CREATOR.toBase58()]); + expect(warnings).toEqual([ + ["⚠️ Unable to resolve creator Telegram ID for orphaned game " + ADDRESS], + ]); + }); + + test("a failed creator lookup is logged with its error", () => { + const failure = new Error("synthetic lookup failure"); + const { info, warnings } = analyze( + { creator: CREATOR }, + { + creatorId: () => { + throw failure; + }, + }, + ); + expect(info.unavailable).toEqual([CREATOR.toBase58()]); + expect(warnings).toEqual([ + ["⚠️ Failed to look up creator Telegram ID for " + ADDRESS + ":", failure], + ]); + }); + + test("a broken creator key has no creator, and players are not marked as creator", () => { + const reads: string[] = []; + const { info, warnings } = analyze( + { creator: "not a key", ticketsCount: 0 }, + { + players: ["2"], + keys: { "2": PLAYER.toBase58() }, + creatorId: () => { + reads.push("read"); + return "1"; + }, + }, + ); + expect(reads).toEqual([]); + expect(info.available).toEqual([{ pubkey: PLAYER, telegramId: "2", isCreator: false }]); + expect(info.unavailable).toEqual([]); + expect(info.canCompleteCleanup).toBe(false); + expect(info.total).toBe(1); + expect(warnings).toEqual([]); + }); + + test("players without a valid key and unmatched wallets are unavailable", () => { + const { info } = analyze( + { creator: CREATOR, participants: ["a", "b", "c", "d"], ticketsCount: 2 }, + { + players: ["2", "3", "4"], + keys: { "1": CREATOR.toBase58(), "3": "not a key", "4": "" }, + creatorId: () => "1", + unmatched: ["walletA", "walletB"], + }, + ); + expect(info.unavailable).toEqual(["2", "3", "4", "walletA", "walletB"]); + expect(info.unmatchedParticipants).toEqual(["walletA", "walletB"]); + expect(info.canCompleteCleanup).toBe(false); + expect(info).toMatchObject({ total: 4, onChainParticipants: 4, onChainTickets: 2 }); + }); + + test("a missing ticket count is zero", () => { + expect(analyze({ creator: CREATOR }, { creatorId: () => "1" }).info.onChainTickets).toBe(0); + }); +}); + +describe("complete cleanup", () => { + const cleanup = async (unjoined: number) => { + const gm = GameManager.getInstance( + { account: { game: {} } } as any, + {} as any, + {} as any, + ) as any; + const unjoinCalls: unknown[][] = []; + const cancels: unknown[][] = []; + gm.unjoinPlayers = async (...args: unknown[]) => { + unjoinCalls.push(args); + return unjoined; + }; + gm.cancelGameWithCreator = async (...args: unknown[]) => { + cancels.push(args); + return true; + }; + const account = { creator: CREATOR }; + const info = { available: ["p1", "p2"], creator: { telegramId: "777" } }; + const ok = await gm.executeCompleteCleanup(GAME, account, info, ADDRESS); + return { ok, unjoinCalls, cancels, account }; + }; + + test("cancels with the creator after every player left", async () => { + const { ok, unjoinCalls, cancels, account } = await cleanup(2); + expect(ok).toBe(true); + expect(unjoinCalls).toEqual([[GAME, account, ["p1", "p2"], "777"]]); + expect(cancels).toEqual([[GAME, account, "777", ADDRESS, "coinflip"]]); + }); + + test("does not cancel while a player is still in the game", async () => { + const { ok, cancels } = await cleanup(1); + expect(ok).toBe(false); + expect(cancels).toEqual([]); + }); +}); From db63458f976b90301732aa0cb0702e61fdce9da8 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Mon, 30 Nov 2026 03:02:56 -0300 Subject: [PATCH 312/410] test(game): check join attempts, resends, and the completion request --- src/utils/game.ts | 13 +- tests/game-manager.join-attempts.test.ts | 280 +++++++++++++++++++++++ 2 files changed, 286 insertions(+), 7 deletions(-) create mode 100644 tests/game-manager.join-attempts.test.ts diff --git a/src/utils/game.ts b/src/utils/game.ts index 423cf84f..c285ea67 100644 --- a/src/utils/game.ts +++ b/src/utils/game.ts @@ -5601,7 +5601,6 @@ export class GameManager { } const playerPubkey = playerKp.publicKey.toBase58(); let joinTx: string | undefined; - let joinConfirmed = false; if (gameAccount.isPrivate) { const result = await this.joinPrivateGame(gamePda, playerKp, chatId || 0, telegramId); @@ -5617,12 +5616,12 @@ export class GameManager { joinSignature: joinTx ?? null, lastVerifiedAt: null, }); - joinConfirmed = true; } else { const maxAttempts = 2; - for (let attempt = 0; attempt < maxAttempts && !joinConfirmed; attempt++) { + // Each attempt ends with a break or a throw, and the last attempt never retries. + // Stryker disable next-line EqualityOperator,ConditionalExpression: so the loop bound is never what stops it. + for (let attempt = 0; attempt < maxAttempts; attempt++) { let setupInstructions: TransactionInstruction[] = []; - let joinInstructions: TransactionInstruction[] = []; try { const { accounts: joinAccounts, setupInstructions: setupIxs } = await this.buildJoinAccounts( @@ -5637,7 +5636,7 @@ export class GameManager { .joinGame() .accounts(joinAccounts as any) .instruction(); - joinInstructions = [...setupInstructions, joinInstruction]; + const joinInstructions = [...setupInstructions, joinInstruction]; joinTx = await this.wallet.sendTransaction(joinInstructions, [playerKp], { priorityFee: true, @@ -5673,7 +5672,7 @@ export class GameManager { return refreshedSignature ?? joinTx; }, ); - joinConfirmed = true; + break; } catch (joinError: any) { const message = joinError?.message ?? ""; const normalized = message.toLowerCase(); @@ -5689,11 +5688,11 @@ export class GameManager { if (isTimeout && !isLastAttempt) { const alreadyJoined = await this.isPlayerInGame(gamePda, playerKp.publicKey).catch( + // Stryker disable next-line ArrowFunction: undefined and false both mean not joined. () => false, ); if (alreadyJoined) { - joinConfirmed = true; break; } diff --git a/tests/game-manager.join-attempts.test.ts b/tests/game-manager.join-attempts.test.ts new file mode 100644 index 00000000..99748742 --- /dev/null +++ b/tests/game-manager.join-attempts.test.ts @@ -0,0 +1,280 @@ +import { afterEach, beforeEach, describe, expect, spyOn, test } from "bun:test"; +import { Keypair, PublicKey } from "#solana"; +import { GameManager } from "../src/utils/game"; + +const GAME = new PublicKey("BPFLoader1111111111111111111111111111111111"); +const ADDRESS = GAME.toBase58(); +const MINT = "So11111111111111111111111111111111111111112"; +const SETUP_IX = { setup: true }; +const JOIN_IX = { join: true }; + +let warn: ReturnType; +let error: ReturnType; +beforeEach(() => { + GameManager.resetForTest(); + warn = spyOn(console, "warn").mockImplementation(() => undefined); + error = spyOn(console, "error").mockImplementation(() => undefined); +}); +afterEach(() => { + warn.mockRestore(); + error.mockRestore(); + GameManager.resetForTest(); +}); + +type Options = { + // Each confirm call runs the next step. A step may call the resend callback. + confirm?: Array<(resend: () => Promise) => Promise>; + build?: () => Promise<{ accounts: object; setupInstructions: unknown[] }>; + alreadyJoined?: () => Promise; + resend?: () => Promise; + after?: Record | (() => Promise); + oracle?: Record; +}; + +async function join(options: Options = {}) { + const player = await Keypair.generate(); + const before = { + isPrivate: false, + ticketsCount: 0, + maxTickets: 2, + gameType: { coinflip: {} }, + ticketAmount: 500_000, + tokenMint: new PublicKey(MINT), + }; + let reads = 0; + const after = options.after ?? { ...before, ticketsCount: 1 }; + const sends: unknown[][] = []; + const resends: unknown[][] = []; + const saved: unknown[][] = []; + const program = { + programId: GAME, + account: { + game: { + fetchNullable: async () => before, + fetch: async () => { + reads += 1; + return typeof after === "function" ? after() : after; + }, + }, + }, + methods: { joinGame: () => ({ accounts: () => ({ instruction: async () => JOIN_IX }) }) }, + }; + const wallet = { + getKeyPair: () => player, + getTokenMetadata: async () => ({ decimals: 9 }), + getTokenBalance: async () => 5_000_000_000, + getBalance: async () => 5_000_000_000, + sendTransaction: async (...args: unknown[]) => { + sends.push(args); + return `SIG${sends.length}`; + }, + }; + const db = { + getGame: () => ({ status: "active", token_mint: MINT, token_ticker: "TOK" }), + savePlayerMapping: () => {}, + saveGameParticipant: (...args: unknown[]) => saved.push(args), + removeGameParticipant: () => {}, + getGameParticipants: () => [], + getPlayerTelegramId: () => null, + }; + const gm = GameManager.getInstance(program as any, wallet as any, db as any) as any; + gm.swapManager = { performJustInTimeSolSwap: async () => ({ swapped: false }) }; + gm.buildJoinAccounts = + options.build ?? (async () => ({ accounts: {}, setupInstructions: [SETUP_IX] })); + const steps = [...(options.confirm ?? [async () => "CONFIRMED"])]; + let confirmFailed = false; + gm.confirmTransactionWithRecovery = async ( + _sig: string, + _pda: PublicKey, + _label: string, + _player: PublicKey, + resend: () => Promise, + ) => { + const step = steps.shift(); + if (!step) throw new Error("unexpected confirm"); + try { + return await step(resend); + } catch (failure) { + confirmFailed = true; + throw failure; + } + }; + gm.sendInstructionsWithFallback = async (...args: unknown[]) => { + resends.push(args); + return options.resend ? options.resend() : "RESENT"; + }; + // The checks before the join always see a new player. + gm.isPlayerInGame = async () => + confirmFailed && options.alreadyJoined ? options.alreadyJoined() : false; + const verified: unknown[] = []; + gm.verifyParticipantJoin = async (...args: unknown[]) => { + verified.push(args[3]); + return true; + }; + const completions: string[] = []; + gm.oracleClient = options.oracle ?? { + requestGameCompletion: async (address: string) => completions.push(address), + }; + const result = await gm.joinGame(ADDRESS, 7n); + const pending = (signature: unknown) => [ + ADDRESS, + "7", + player.publicKey.toBase58(), + { status: "pending", joinSignature: signature, lastVerifiedAt: null }, + ]; + return { result, player, sends, resends, saved, verified, completions, reads, pending }; +} + +const timeout = () => async () => { + throw new Error("Transaction not confirmed in time"); +}; + +describe("join attempts", () => { + test("one confirmed attempt sends the setup and join instructions signed by the player", async () => { + const run = await join(); + expect(run.result.success).toBe(true); + expect(run.sends).toEqual([[[SETUP_IX, JOIN_IX], [run.player], { priorityFee: true }]]); + expect(run.saved).toEqual([run.pending("SIG1")]); + expect(run.verified).toEqual([{ joinSignature: "CONFIRMED" }]); + }); + + test("a resend during confirmation saves and confirms the new signature", async () => { + const run = await join({ confirm: [async (resend) => resend()] }); + expect(run.resends).toEqual([[[SETUP_IX, JOIN_IX], [run.player], "Player join transaction"]]); + expect(run.saved).toEqual([run.pending("SIG1"), run.pending("RESENT")]); + expect(run.verified).toEqual([{ joinSignature: "RESENT" }]); + }); + + test("a resend without a signature keeps the sent signature", async () => { + const run = await join({ + confirm: [async (resend) => resend()], + resend: async () => undefined, + }); + expect(run.saved).toEqual([run.pending("SIG1"), run.pending(null)]); + expect(run.verified).toEqual([{ joinSignature: "SIG1" }]); + }); + + test("a first timeout retries once and warns", async () => { + const run = await join({ confirm: [timeout(), async () => "SECOND"] }); + expect(run.result.success).toBe(true); + expect(run.sends).toHaveLength(2); + expect(run.verified).toEqual([{ joinSignature: "SECOND" }]); + expect(warn).toHaveBeenCalledWith( + `⚠️ Player join attempt 1 for ${ADDRESS} timed out; retrying with a fresh blockhash.`, + ); + }); + + test.each([ + ["the player is already in the game", async () => true, []], + ["the membership check fails", async () => Promise.reject(new Error("rpc down")), [1]], + ])("after a first timeout, %s", async (_name, alreadyJoined, retried) => { + const run = await join({ confirm: [timeout(), async () => "SECOND"], alreadyJoined }); + expect(run.result.success).toBe(true); + expect(run.sends.slice(1).map(() => 1)).toEqual(retried); + }); + + test("a second timeout fails the join without a third send", async () => { + const run = await join({ confirm: [timeout(), timeout()] }); + expect(run.result.success).toBe(false); + expect(run.sends).toHaveLength(2); + expect(run.verified).toEqual([]); + }); + + test("an error that is not a timeout fails without a retry", async () => { + const failure = new Error("custom program error"); + const run = await join({ + confirm: [ + async () => { + throw failure; + }, + ], + }); + expect(run.result.success).toBe(false); + expect(run.sends).toHaveLength(1); + expect(error).toHaveBeenCalledWith(`Error joining game ${ADDRESS}:`, failure); + }); + + test("a token account failure with setup instructions gets a token account error", async () => { + const failure = new Error("AccountNotInitialized"); + const run = await join({ + confirm: [ + async () => { + throw failure; + }, + ], + }); + expect(run.result.success).toBe(false); + const logged = error.mock.calls.find( + (call: unknown[]) => call[0] === `Error joining game ${ADDRESS}:`, + ); + expect((logged?.[1] as Error).message).toBe( + "Failed to initialize your token account for this game. Please try again or ensure you have enough SOL for fees.", + ); + expect((logged?.[1] as Error).cause).toBe(failure); + }); + + test.each([ + ["no setup instructions", async () => ({ accounts: {}, setupInstructions: [] })], + [ + "a failed account build", + async () => { + throw new Error("uninitialized vault"); + }, + ], + ])("a token account failure with %s is passed on unchanged", async (_name, build) => { + const run = await join({ + build, + confirm: [ + async () => { + throw new Error("uninitialized vault"); + }, + ], + }); + expect(run.result.success).toBe(false); + const logged = error.mock.calls.find( + (call: unknown[]) => call[0] === `Error joining game ${ADDRESS}:`, + ); + expect((logged?.[1] as Error).message).toBe("uninitialized vault"); + }); + + test("a thrown value without a message is passed on unchanged", async () => { + const run = await join({ build: async () => Promise.reject(null) }); + expect(run.result.success).toBe(false); + expect(error).toHaveBeenCalledWith(`Error joining game ${ADDRESS}:`, null); + }); +}); + +describe("join completion request", () => { + test.each([ + ["the last seat", { ticketsCount: 2, maxTickets: 2 }, [ADDRESS]], + ["more tickets than seats", { ticketsCount: 3, maxTickets: 2 }, [ADDRESS]], + ["an open seat", { ticketsCount: 1, maxTickets: 2 }, []], + ["no seat limit", { ticketsCount: 0, maxTickets: 0 }, []], + ["no counts", {}, []], + ])("a join that fills %s", async (_name, after, expected) => { + const run = await join({ after }); + expect(run.completions).toEqual(expected); + expect(run.result).toEqual({ + success: true, + gameAccount: after, + ticketsCount: Number((after as any).ticketsCount ?? 0), + maxTickets: Number((after as any).maxTickets ?? 0), + }); + }); + + test("an oracle without completion requests is skipped without a warning", async () => { + const run = await join({ after: { ticketsCount: 2, maxTickets: 2 }, oracle: {} }); + expect(run.result.success).toBe(true); + expect(warn).not.toHaveBeenCalled(); + }); + + test("a failed account read after the join is logged and still succeeds", async () => { + const failure = new Error("synthetic read failure"); + const run = await join({ after: async () => Promise.reject(failure) }); + expect(run.result).toEqual({ success: true }); + expect(warn).toHaveBeenCalledWith( + `Failed to request oracle completion for ${ADDRESS}:`, + failure, + ); + }); +}); From fe5924dc23851e8d32a69ff91b3b938e3a4ae10c Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Mon, 30 Nov 2026 03:06:04 -0300 Subject: [PATCH 313/410] test(game): check batch account reads and active game list defaults --- src/utils/game.ts | 6 +- tests/game-manager.active-list.test.ts | 159 +++++++++++++++++++++++++ 2 files changed, 163 insertions(+), 2 deletions(-) create mode 100644 tests/game-manager.active-list.test.ts diff --git a/src/utils/game.ts b/src/utils/game.ts index c285ea67..cac0ffed 100644 --- a/src/utils/game.ts +++ b/src/utils/game.ts @@ -6771,7 +6771,8 @@ export class GameManager { private async fetchGameAccountsBatch(addresses: string[]): Promise> { const accounts = new Map(); const accountApi = this.program.account.game; - if (addresses.length === 0 || typeof accountApi?.fetchMultiple !== "function") { + // An empty list ends below, after the address check finds nothing to read. + if (typeof accountApi?.fetchMultiple !== "function") { return accounts; } @@ -6876,7 +6877,8 @@ export class GameManager { }; } catch (error) { console.warn( - `Failed to format active game ${gameData?.game_address ?? "unknown"}:`, + // Rows without an address return before anything can throw. + `Failed to format active game ${gameData.game_address}:`, error, ); return null; diff --git a/tests/game-manager.active-list.test.ts b/tests/game-manager.active-list.test.ts new file mode 100644 index 00000000..bd0d0ee5 --- /dev/null +++ b/tests/game-manager.active-list.test.ts @@ -0,0 +1,159 @@ +import { afterEach, beforeEach, describe, expect, spyOn, test } from "bun:test"; +import { PublicKey } from "#solana"; +import { GameManager } from "../src/utils/game"; +import { DEFAULT_TOKEN_TICKER } from "../src/utils/constants"; + +const A = new PublicKey("BPFLoader1111111111111111111111111111111111").toBase58(); +const B = new PublicKey("Vote111111111111111111111111111111111111111").toBase58(); + +let warn: ReturnType; +let error: ReturnType; +beforeEach(() => { + GameManager.resetForTest(); + warn = spyOn(console, "warn").mockImplementation(() => undefined); + error = spyOn(console, "error").mockImplementation(() => undefined); +}); +afterEach(() => { + warn.mockRestore(); + error.mockRestore(); + GameManager.resetForTest(); +}); + +const manager = (game: unknown) => + GameManager.getInstance({ account: { game } } as any, {} as any, {} as any) as any; + +describe("batch game account read", () => { + test("reads each valid address once and keeps only the answers it got", async () => { + const reads: string[][] = []; + const gm = manager({ + fetchMultiple: async (keys: PublicKey[]) => { + reads.push(keys.map((key) => key.toBase58())); + return [{ id: "a" }, null]; + }, + }); + const map = await gm.fetchGameAccountsBatch([A, "not a key", B, A, "x"]); + expect(reads).toEqual([[A, B]]); + expect([...map.entries()]).toEqual([ + [A, { id: "a" }], + [B, null], + ]); + }); + + test("an answer without an entry is left out for a single lookup", async () => { + const gm = manager({ fetchMultiple: async () => [undefined, { id: "b" }] }); + const map = await gm.fetchGameAccountsBatch([A, B]); + expect([...map.entries()]).toEqual([[B, { id: "b" }]]); + }); + + test.each([ + ["no addresses", { fetchMultiple: async () => [{}] }, []], + ["only invalid addresses", { fetchMultiple: async () => [{}] }, ["bad"]], + ["no batch reader", {}, [A]], + ["no account reader", undefined, [A]], + ])("%s reads nothing", async (_name, game, addresses) => { + const gm = manager(game); + expect((await gm.fetchGameAccountsBatch(addresses)).size).toBe(0); + expect(warn).not.toHaveBeenCalled(); + }); + + test("a failed batch read is logged and leaves every game to a single lookup", async () => { + const failure = new Error("synthetic batch failure"); + const gm = manager({ + fetchMultiple: async () => { + throw failure; + }, + }); + expect((await gm.fetchGameAccountsBatch([A])).size).toBe(0); + expect(warn).toHaveBeenCalledWith( + "Batch game account lookup failed; falling back to single lookups:", + failure, + ); + }); +}); + +describe("active game list", () => { + type Row = Record | null; + const list = async (rows: Row[], game: Record = {}) => { + const gm = manager({ fetchNullable: async () => ({ ticketsCount: 1 }), ...game }); + const formatCalls: unknown[][] = []; + gm.getGameCreatorUsername = async () => "@creator"; + gm.formatGameMessage = async (...args: unknown[]) => { + formatCalls.push(args.slice(2)); + return { messageText: "card", keyboard: [["k"]] }; + }; + const result = await gm.formatActiveGamesList({}, rows); + return { result, formatCalls }; + }; + + test("rows without an address are skipped before any account read", async () => { + const batch: string[][] = []; + const { result, formatCalls } = await list([null, {}, { game_address: "" }], { + fetchMultiple: async (keys: PublicKey[]) => batch.push(keys.map(String)), + }); + expect(result).toEqual([]); + expect(formatCalls).toEqual([]); + expect(batch).toEqual([]); + }); + + test("missing row fields use the game, zero amount, active status, and token defaults", async () => { + const account = { ticketsCount: 2, maxTickets: 4, minTickets: 2 }; + const { result, formatCalls } = await list([{ game_address: A, game_account: account }]); + expect(formatCalls).toEqual([ + [ + "game", + 0, + "@creator", + "active", + DEFAULT_TOKEN_TICKER, + undefined, + undefined, + undefined, + { suppressMentions: true, gameAccount: account }, + ], + ]); + expect(result).toEqual([ + { + messageText: "card", + keyboard: [["k"]], + gameAddress: A, + currentTickets: 2, + maxTickets: 4, + minTickets: 2, + }, + ]); + }); + + test("row fields are passed to the card, and the token mint stands in for a ticker", async () => { + const account = { ticketsCount: 1 }; + const row = { + game_address: A, + game_account: account, + game_type: "giveaway", + amount: "5", + status: "completed", + token_mint: "MINT", + winner_address: "W", + }; + const { formatCalls } = await list([row, { ...row, token_ticker: "TOK" }]); + expect(formatCalls.map((call) => call.slice(0, 6))).toEqual([ + ["giveaway", 5, "@creator", "completed", "MINT", "W"], + ["giveaway", 5, "@creator", "completed", "TOK", "W"], + ]); + }); + + test("a broken amount is zero", async () => { + const { formatCalls } = await list([{ game_address: A, game_account: {}, amount: "x" }]); + expect(formatCalls[0]?.[1]).toBe(0); + }); + + test("a card that fails is logged with its address and left out", async () => { + const gm = manager({}); + const failure = new Error("synthetic card failure"); + gm.getGameCreatorUsername = async () => { + throw failure; + }; + const rows = await gm.formatActiveGamesList({}, [{ game_address: A, game_account: {} }]); + expect(rows).toEqual([]); + expect(warn).toHaveBeenCalledWith(`Failed to format active game ${A}:`, failure); + }); +}); From 0233c4ebacab12407e488eb2321099bb951e6c19 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Mon, 30 Nov 2026 03:09:23 -0300 Subject: [PATCH 314/410] test(game): check Telegram name lookups and the creator name fallback --- src/utils/game.ts | 3 +- tests/game-manager.username-lookup.test.ts | 178 +++++++++++++++++++++ 2 files changed, 180 insertions(+), 1 deletion(-) create mode 100644 tests/game-manager.username-lookup.test.ts diff --git a/src/utils/game.ts b/src/utils/game.ts index cac0ffed..36111dbf 100644 --- a/src/utils/game.ts +++ b/src/utils/game.ts @@ -2637,8 +2637,9 @@ export class GameManager { this.setCachedUsername(cacheKey, resolved); return resolved; } catch (fetchError) { + // The fallback is already a remembered hint: either it came from the + // hints or it was remembered when it was read from the database above. if (fallbackCandidate) { - this.rememberTelegramUsername(trimmedId, fallbackCandidate); this.setCachedUsername(cacheKey, fallbackCandidate); return fallbackCandidate; } diff --git a/tests/game-manager.username-lookup.test.ts b/tests/game-manager.username-lookup.test.ts new file mode 100644 index 00000000..a8afccee --- /dev/null +++ b/tests/game-manager.username-lookup.test.ts @@ -0,0 +1,178 @@ +import { afterEach, beforeEach, describe, expect, spyOn, test } from "bun:test"; +import { GameManager } from "../src/utils/game"; +import { makeDbStub, makeProgramStub, makeWalletStub } from "./helpers/game-manager"; + +let warn: ReturnType; +beforeEach(() => { + GameManager.resetForTest(); + warn = spyOn(console, "warn").mockImplementation(() => undefined); +}); +afterEach(() => { + warn.mockRestore(); + GameManager.resetForTest(); +}); + +type Member = Record | (() => never); + +function setup(member: Member = {}, db: Record = {}) { + const lookups: unknown[][] = []; + const deleted: string[] = []; + const mapped: unknown[][] = []; + const gm = GameManager.getInstance( + makeProgramStub(), + makeWalletStub(), + makeDbStub({ + extra: { + deleteUsernameMappingsForTelegramId: (id: string) => deleted.push(id), + saveUsernameMapping: (...args: unknown[]) => mapped.push(args), + ...db, + }, + }), + ) as any; + const ctxFor = (chatId: unknown) => ({ + chat: chatId === undefined ? undefined : { id: chatId }, + api: { + getChatMember: async (...args: unknown[]) => { + lookups.push(args); + if (typeof member === "function") member(); + return { user: member }; + }, + }, + }); + return { gm, ctx: ctxFor(1), ctxFor, lookups, deleted, mapped }; +} + +describe("Telegram name lookup", () => { + test.each([["12a"], ["a12"], ["abc"], [""]])("the invalid ID %p is not looked up", async (id) => { + const { gm, ctx, lookups } = setup({ username: "bob" }); + expect(await gm.getUsernameFromTelegramId(ctx, id)).toBeNull(); + expect(lookups).toEqual([]); + expect(warn).toHaveBeenCalledTimes(1); + }); + + test.each([[null], [undefined]])("a chat ID of %p is not looked up", async (chatId) => { + const { gm, ctxFor, lookups } = setup({ username: "bob" }); + expect(await gm.getUsernameFromTelegramId(ctxFor(chatId), "5")).toBeNull(); + expect(lookups).toEqual([]); + }); + + test("a chat ID of zero is looked up with the numeric player ID", async () => { + const { gm, ctxFor, lookups } = setup({ username: "bob" }); + expect(await gm.getUsernameFromTelegramId(ctxFor(0), " 5 ")).toBe("@bob"); + expect(lookups).toEqual([[0, 5]]); + }); + + test.each([ + ["a trimmed handle", { username: " bob " }, "@bob"], + [ + "the full name without a handle", + { username: " ", first_name: " Ann ", last_name: " Lee " }, + "Ann Lee", + ], + ["the first name alone", { first_name: "Ann" }, "Ann"], + ["the last name alone", { first_name: 5, last_name: "Lee" }, "Lee"], + ["nothing without names", { username: 7, first_name: " " }, null], + ])("a member resolves to %s", async (_name, member, expected) => { + const { gm, ctx } = setup(member); + expect(await gm.getUsernameFromTelegramId(ctx, "5")).toBe(expected); + }); + + test("a handle is saved as a mapping and keeps the old mappings", async () => { + const { gm, ctx, deleted, mapped } = setup({ username: "Bob" }); + await gm.getUsernameFromTelegramId(ctx, "5"); + expect(mapped).toEqual([["bob", "5", "@Bob"]]); + expect(deleted).toEqual([]); + }); + + test("a member without a handle clears old mappings and is only a hint", async () => { + const { gm, ctx, ctxFor, deleted, mapped } = setup({ first_name: "Ann" }); + await gm.getUsernameFromTelegramId(ctx, "5"); + expect(deleted).toEqual(["5"]); + expect(mapped).toEqual([]); + // Another chat reads the hint without a network lookup. + expect(await gm.getUsernameFromTelegramId(ctxFor(2), "5", { allowNetworkLookup: false })).toBe( + "Ann", + ); + }); + + test("a member without any name is not remembered", async () => { + const { gm, ctx, ctxFor } = setup({}); + await gm.getUsernameFromTelegramId(ctx, "5"); + expect(warn).not.toHaveBeenCalled(); + expect( + await gm.getUsernameFromTelegramId(ctxFor(2), "5", { allowNetworkLookup: false }), + ).toBeNull(); + }); + + test("a remembered hint wins over the stored name when the lookup fails", async () => { + const { gm, ctx, ctxFor, lookups } = setup( + () => { + throw new Error("synthetic lookup failure"); + }, + { getPlayerDisplayName: () => "Stored" }, + ); + gm.primeUsernameCache(ctx, "5", "Hint", false); + // Another chat has no cached name, so it looks up and falls back to the hint. + expect(await gm.getUsernameFromTelegramId(ctxFor(9), "5")).toBe("Hint"); + expect(lookups).toHaveLength(1); + }); + + test("a failed lookup falls back to the stored name and caches it", async () => { + const { gm, ctx, lookups } = setup( + () => { + throw new Error("synthetic lookup failure"); + }, + { getPlayerDisplayName: () => "Stored" }, + ); + expect(await gm.getUsernameFromTelegramId(ctx, "5")).toBe("Stored"); + expect(await gm.getUsernameFromTelegramId(ctx, "5")).toBe("Stored"); + expect(lookups).toHaveLength(1); + }); + + test("a failed lookup without a fallback is logged and returns nothing", async () => { + const failure = new Error("synthetic lookup failure"); + const { gm, ctx } = setup(() => { + throw failure; + }); + expect(await gm.getUsernameFromTelegramId(ctx, "5")).toBeNull(); + expect(warn).toHaveBeenCalledWith("Error getting username for Telegram ID 5:", failure); + }); +}); + +describe("game creator name", () => { + const KEY = "BPFLoader1111111111111111111111111111111111"; + const creator = async (info: unknown, member: Member = { username: "bob" }) => { + const { gm, ctx, lookups } = setup(member, { getCreatorInfo: () => info }); + return { name: await gm.getGameCreatorUsername(ctx, "GAME"), lookups }; + }; + + test("a creator with a padded Telegram ID uses the Telegram name", async () => { + expect(await creator({ telegramId: " 5 ", publicKey: KEY })).toEqual({ + name: "@bob", + lookups: [[1, 5]], + }); + }); + + test.each([["12a"], ["a12"], [""]])( + "a creator ID of %p is not looked up and shows the short address", + async (telegramId) => { + expect(await creator({ telegramId, publicKey: KEY })).toEqual({ + name: "BPFL…1111", + lookups: [], + }); + // The ID is rejected here, not by the name lookup, which would log a warning. + expect(warn).not.toHaveBeenCalled(); + }, + ); + + test("a creator without a Telegram name shows the short address", async () => { + expect((await creator({ telegramId: "5", publicKey: KEY }, {})).name).toBe("BPFL…1111"); + }); + + test.each([ + ["no creator row", null], + ["a creator without a name or key", { telegramId: "5", publicKey: null }], + ])("%s is unknown", async (_name, info) => { + expect((await creator(info, {})).name).toBe("Unknown"); + }); +}); From 540fc34835854edb35cb3985880c5632b1a63c34 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Mon, 30 Nov 2026 03:10:50 -0300 Subject: [PATCH 315/410] test(game): check the game creation request lookup --- tests/game-manager.creation-request.test.ts | 40 +++++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 tests/game-manager.creation-request.test.ts diff --git a/tests/game-manager.creation-request.test.ts b/tests/game-manager.creation-request.test.ts new file mode 100644 index 00000000..7bf02437 --- /dev/null +++ b/tests/game-manager.creation-request.test.ts @@ -0,0 +1,40 @@ +import { afterEach, beforeEach, describe, expect, test } from "bun:test"; +import { GameManager } from "../src/utils/game"; + +beforeEach(() => GameManager.resetForTest()); +afterEach(() => GameManager.resetForTest()); + +describe("game creation request check", () => { + const check = (chatId: number | undefined, messageId: number | undefined, stored: unknown) => { + const reads: unknown[][] = []; + const db = + stored === "no reader" + ? {} + : { + hasGameCreationRequest: (...args: unknown[]) => { + reads.push(args); + return stored; + }, + }; + const gm = GameManager.getInstance({} as any, {} as any, db as any); + return { found: gm.hasGameCreationRequest(12n, chatId, messageId), reads }; + }; + + test.each([ + ["no chat", undefined, 5], + ["no message", 1, undefined], + ])("a request without %s is not read", (_name, chatId, messageId) => { + expect(check(chatId, messageId, true)).toEqual({ found: false, reads: [] }); + }); + + test.each([ + ["a stored request", true, true], + ["no stored request", false, false], + ["an empty answer", undefined, false], + ["a database without the reader", "no reader", false], + ])("chat and message zero with %s", (_name, stored, found) => { + const result = check(0, 0, stored); + expect(result.found).toBe(found); + expect(result.reads).toEqual(stored === "no reader" ? [] : [["12", 0, 0]]); + }); +}); From 729b07354f7a191ee98a4011e5c72a1d89e8b2ff Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Mon, 30 Nov 2026 03:13:17 -0300 Subject: [PATCH 316/410] test(game): check games header amounts, net sign, and win rate --- src/utils/game.ts | 4 ++-- tests/game.history.test.ts | 28 ++++++++++++++++++++++++++++ 2 files changed, 30 insertions(+), 2 deletions(-) diff --git a/src/utils/game.ts b/src/utils/game.ts index 36111dbf..847a5f60 100644 --- a/src/utils/game.ts +++ b/src/utils/game.ts @@ -6575,8 +6575,8 @@ export class GameManager { const losses = result.lost.games.length; const totalGames = wins + losses; const winRate = totalGames > 0 ? (wins / totalGames) * 100 : 0; - const winRateStr = - winRate > 0 ? (Number.isInteger(winRate) ? winRate.toFixed(0) : winRate.toFixed(1)) : "0"; + // A zero rate is an integer, so it prints as "0". + const winRateStr = Number.isInteger(winRate) ? winRate.toFixed(0) : winRate.toFixed(1); // Remove the $ from netStr since we'll add it with the sign const summaryLine = `Net: ${netSign}$${netStr.replace("$", "")} (Won ${wonUsd} • Lost ${lostUsd})`; diff --git a/tests/game.history.test.ts b/tests/game.history.test.ts index c229e671..9849db4c 100644 --- a/tests/game.history.test.ts +++ b/tests/game.history.test.ts @@ -424,6 +424,34 @@ describe("formatGamesHeader and formatGamesMessage", () => { expect(header).toContain("Net: -$24k"); }); + test.each([ + [999.99, 0, "Net: +$999.99 (Won $999.99 • Lost $0.00)"], + [1000, 0, "Net: +$1.0k (Won $1.0k • Lost $0.00)"], + [9999, 0, "Net: +$10.0k (Won $10.0k • Lost $0.00)"], + [10_000, 0, "Net: +$10k (Won $10k • Lost $0.00)"], + [5, 5, "Net: +$0.00 (Won $5.00 • Lost $5.00)"], + [0, 5.5, "Net: -$5.50 (Won $0.00 • Lost $5.50)"], + ])("won $%p and lost $%p give the summary line", (won, lost, line) => { + const header = gm.formatGamesHeader("@bob", result([], [], [], { won, lost })); + expect(header.split("\n")[1]).toBe(line); + }); + + test.each([ + [0, 0, "0 wins • 0 losses • 0% WR"], + [1, 1, "1 wins • 1 losses • 50% WR"], + [2, 1, "2 wins • 1 losses • 66.7% WR"], + [0, 3, "0 wins • 3 losses • 0% WR"], + ])("%p wins and %p losses give the record line", (wins, losses, line) => { + const games = (count: number) => Array.from({ length: count }, () => entry()); + const header = gm.formatGamesHeader("A", result(games(wins), games(losses), [])); + expect(header.split("\n")).toEqual([ + "🎲 Games: A<b> [30D]", + "Net: +$0.00 (Won $0.00 • Lost $0.00)", + line, + "────────", + ]); + }); + test("formats won, lost and cancelled tabs with their own titles", () => { const res = result( [entry({ category: "won" })], From 96ed686ddd62e0614d3528d254da46da415b5b4f Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Mon, 30 Nov 2026 03:26:17 -0300 Subject: [PATCH 317/410] test(game): check private join attempts, history quotes, and zero stat limits Kill the game.ts survivors that the changed-code mutation run found on e2b7cf8. Rewrite dead guards and mark equivalent mutants with reasons. --- src/utils/game.ts | 36 +++-- ...game-manager.join-private-attempts.test.ts | 150 ++++++++++++++++++ tests/game-manager.stats-boundaries.test.ts | 6 + tests/game.history.test.ts | 31 +++- 4 files changed, 209 insertions(+), 14 deletions(-) create mode 100644 tests/game-manager.join-private-attempts.test.ts diff --git a/src/utils/game.ts b/src/utils/game.ts index 847a5f60..b4208055 100644 --- a/src/utils/game.ts +++ b/src/utils/game.ts @@ -1072,8 +1072,9 @@ export class GameManager { private trimUsernameCacheKeys(keys: string[], cache: { delete(key: string): boolean }): void { const overflow = Math.max(0, keys.length - this.usernameCacheMaxEntries); + // Keys are never empty: username keys are checked, and name keys hold a ":". for (const oldestKey of keys.splice(0, overflow)) { - if (oldestKey) cache.delete(oldestKey); + cache.delete(oldestKey); } } @@ -3691,6 +3692,9 @@ export class GameManager { const redrawAsTerminal = async (terminal: TerminalGameMessageUpdate): Promise => { // An update may switch once from active to terminal. A terminal redraw must not restart. + // A terminal redraw has the status Completed, and only a status that is not Completed + // redirects. So this guard and the flag below keep the one-pass bound for later changes. + // Stryker disable next-line ConditionalExpression: no current path reaches it with the flag set. if (isTerminalRedraw) return; await this.updateGameMessageInternal( ctx, @@ -3706,6 +3710,7 @@ export class GameManager { updateGeneration, request, undefined, + // Stryker disable next-line BooleanLiteral: no current path reaches it with the flag set. true, ); }; @@ -6133,7 +6138,6 @@ export class GameManager { for (const attempt of attempts) { let setupInstructions: TransactionInstruction[] = []; - let joinInstructions: TransactionInstruction[] = []; try { if (attempt > 0) { gameAccount = await loadGameAccount(); @@ -6158,7 +6162,7 @@ export class GameManager { .joinGame() .accounts(joinAccounts as any) .instruction(); - joinInstructions = [...setupInstructions, joinInstruction]; + const joinInstructions = [...setupInstructions, joinInstruction]; lastSignature = await this.wallet.sendTransaction(joinInstructions, [playerKp, adminKp], { priorityFee: true, @@ -6184,6 +6188,7 @@ export class GameManager { return { success: true, tx: lastSignature }; } catch (joinError: any) { + // Stryker disable next-line StringLiteral: any text without the words checked below takes the same path. const message = joinError?.message ?? ""; if (isMissingAccountError(joinError)) { @@ -6194,7 +6199,7 @@ export class GameManager { } const normalized = message.toLowerCase(); - const needsAtaCreation = (setupInstructions ?? []).length > 0; + const needsAtaCreation = setupInstructions.length > 0; const isAtaInitFailure = needsAtaCreation && (normalized.includes("associated token account") || @@ -6208,6 +6213,7 @@ export class GameManager { if ((isTimeout || isExpiration) && !isLastAttempt) { const alreadyJoined = await this.isPlayerInGame(gamePda, playerKp.publicKey).catch( + // Stryker disable next-line ArrowFunction: undefined and false both mean not joined. () => false, ); @@ -6457,6 +6463,7 @@ export class GameManager { let decimals = 9; try { const meta = await this.wallet.getTokenMetadata(tokenMint); + // Stryker disable next-line OptionalChaining: missing metadata throws into the catch, which keeps the same default. decimals = meta?.decimals ?? decimals; } catch { // Keep the default units if metadata is unavailable. @@ -6466,8 +6473,12 @@ export class GameManager { const lookup = await getUsdPrice({ tokenMint: tokenMint === "SOL" ? WSOL_MINT : tokenMint, }); - const price = lookup?.price; - return typeof price === "number" && Number.isFinite(price) && price > 0 + // Number.isFinite is false for every value that is not a number, and a missing price is 0. + // Stryker disable next-line OptionalChaining: a missing lookup throws into the catch, which also returns null. + const price = lookup?.price ?? 0; + // A zero price adds zero to a total, the same as no quote. + // Stryker disable next-line EqualityOperator: so the boundary at zero cannot change a total. + return Number.isFinite(price) && price > 0 ? { price, divisor: Math.pow(10, decimals) } : null; } catch { @@ -7075,7 +7086,7 @@ export class GameManager { options: { allowExpired?: boolean } = {}, ): Promise { const allowExpired = options.allowExpired === true; - const getGame = (this.gameDb as any)?.getGame; + const getGame = (this.gameDb as any).getGame; if (!allowExpired && typeof getGame === "function") { const existing = getGame.call(this.gameDb, gameAddress); if (existing) return existing; @@ -7102,7 +7113,7 @@ export class GameManager { if (!tokenMint) return null; let tokenTicker = DEFAULT_TOKEN_TICKER; - const getTokenMetadata = (this.wallet as any)?.getTokenMetadata; + const getTokenMetadata = (this.wallet as any).getTokenMetadata; if (typeof getTokenMetadata === "function") { try { const metadata = await getTokenMetadata.call(this.wallet, tokenMint); @@ -7116,7 +7127,7 @@ export class GameManager { typeof gameAccount.creator?.toBase58 === "function" ? gameAccount.creator.toBase58() : String(gameAccount.creator ?? ""); - const getPlayerTelegramId = (this.gameDb as any)?.getPlayerTelegramId; + const getPlayerTelegramId = (this.gameDb as any).getPlayerTelegramId; const creatorTelegramId = (creatorPubkey && typeof getPlayerTelegramId === "function" ? getPlayerTelegramId.call(this.gameDb, creatorPubkey) @@ -7124,7 +7135,7 @@ export class GameManager { if (creatorPubkey && creatorTelegramId) { try { - const savePlayerMapping = (this.gameDb as any)?.savePlayerMapping; + const savePlayerMapping = (this.gameDb as any).savePlayerMapping; if (typeof savePlayerMapping === "function") { savePlayerMapping.call(this.gameDb, creatorPubkey, creatorTelegramId); } @@ -7155,7 +7166,7 @@ export class GameManager { }; try { - const saveGame = (this.gameDb as any)?.saveGame; + const saveGame = (this.gameDb as any).saveGame; if (typeof saveGame === "function") { saveGame.call( this.gameDb, @@ -7175,7 +7186,7 @@ export class GameManager { } if (hasTiming) { - const setGameChainTiming = (this.gameDb as any)?.setGameChainTiming; + const setGameChainTiming = (this.gameDb as any).setGameChainTiming; if (typeof setGameChainTiming === "function") { setGameChainTiming.call(this.gameDb, gameAddress, createdAtMs, expiresAtMs); } @@ -8737,6 +8748,7 @@ export class GameManager { } try { return value.toString(); + // Stryker disable next-line BlockStatement: every use reads an undefined mint like null. } catch { return null; } diff --git a/tests/game-manager.join-private-attempts.test.ts b/tests/game-manager.join-private-attempts.test.ts new file mode 100644 index 00000000..0f6ce430 --- /dev/null +++ b/tests/game-manager.join-private-attempts.test.ts @@ -0,0 +1,150 @@ +import { afterEach, beforeEach, describe, expect, spyOn, test } from "bun:test"; +import { Keypair, PublicKey } from "#solana"; +import { GameManager } from "../src/utils/game"; + +const GAME = new PublicKey("BPFLoader1111111111111111111111111111111111"); +const ADDRESS = GAME.toBase58(); +const SETUP_IX = { setup: true }; +const JOIN_IX = { join: true }; + +let warn: ReturnType; +let error: ReturnType; +beforeEach(() => { + GameManager.resetForTest(); + warn = spyOn(console, "warn").mockImplementation(() => undefined); + error = spyOn(console, "error").mockImplementation(() => undefined); +}); +afterEach(() => { + warn.mockRestore(); + error.mockRestore(); + GameManager.resetForTest(); +}); + +type Options = { + // Each confirm call runs the next step. A step may call the resend callback. + confirm?: Array<(resend: () => Promise) => Promise>; + build?: () => Promise<{ accounts: object; setupInstructions?: unknown[] }>; + alreadyJoined?: () => Promise; +}; + +async function joinPrivate(options: Options = {}) { + const player = await Keypair.generate(); + const admin = await Keypair.generate(); + const sends: unknown[][] = []; + const resends: unknown[][] = []; + const labels: unknown[] = []; + const friendly: unknown[] = []; + const program = { + account: { game: { fetchNullable: async () => ({ ticketsCount: 0 }) } }, + methods: { joinGame: () => ({ accounts: () => ({ instruction: async () => JOIN_IX }) }) }, + }; + const wallet = { + sendTransaction: async (...args: unknown[]) => { + sends.push(args); + return `SIG${sends.length}`; + }, + getFriendlyErrorMessage: (failure: unknown) => { + friendly.push(failure); + return "friendly"; + }, + }; + const db = { getGame: () => ({ token_mint: "MINT" }) }; + const gm = GameManager.getInstance(program as any, wallet as any, db as any) as any; + gm.oracleClient = { + authorizePlayer: async () => ({ authorized: true, operatorKeypair: admin }), + }; + gm.buildJoinAccounts = + options.build ?? (async () => ({ accounts: {}, setupInstructions: [SETUP_IX] })); + const steps = [...(options.confirm ?? [async () => "CONFIRMED"])]; + gm.confirmTransactionWithRecovery = async ( + _sig: string, + _pda: PublicKey, + label: string, + _player: PublicKey, + resend: () => Promise, + ) => { + labels.push(label); + const step = steps.shift(); + if (!step) throw new Error("unexpected confirm"); + return step(resend); + }; + gm.sendInstructionsWithFallback = async (...args: unknown[]) => { + resends.push(args); + return "RESENT"; + }; + gm.isPlayerInGame = options.alreadyJoined ?? (async () => false); + const result = await gm.joinPrivateGame(GAME, player, 99, 7n); + return { result, player, admin, sends, resends, labels, friendly }; +} + +const timeout = () => async () => { + throw new Error("Transaction not confirmed in time"); +}; +const fails = (failure: unknown) => async () => { + throw failure; +}; + +describe("private join attempts", () => { + test("one confirmed attempt is signed by the player and the operator", async () => { + const run = await joinPrivate(); + expect(run.result).toEqual({ success: true, tx: "CONFIRMED" }); + expect(run.sends).toEqual([ + [[SETUP_IX, JOIN_IX], [run.player, run.admin], { priorityFee: true }], + ]); + // The operation type picks the "player is recorded" probe. + expect(run.labels).toEqual(["Player join"]); + }); + + test("a resend during confirmation sends the full instruction set", async () => { + const run = await joinPrivate({ confirm: [async (resend) => resend()] }); + expect(run.result).toEqual({ success: true, tx: "RESENT" }); + expect(run.resends).toEqual([ + [[SETUP_IX, JOIN_IX], [run.player, run.admin], "Player join transaction"], + ]); + }); + + test("a first timeout retries once with the attempt number in its warning", async () => { + const run = await joinPrivate({ confirm: [timeout(), async () => "SECOND"] }); + expect(run.result).toEqual({ success: true, tx: "SECOND" }); + expect(run.sends).toHaveLength(2); + expect(warn).toHaveBeenCalledWith( + `⚠️ Player join attempt 1 for ${ADDRESS} timed out or expired; retrying with a fresh blockhash.`, + ); + }); + + test.each([ + ["an associated token account error", "Associated token account missing"], + ["an uninitialized account error", "Error: AccountNotInitialized"], + ["an uninitialized vault error", "vault is uninitialized"], + ])("%s with setup instructions gets the token account error", async (_name, text) => { + const failure = new Error(text); + const run = await joinPrivate({ confirm: [fails(failure)] }); + expect(run.result).toEqual({ success: false, error: "friendly" }); + const passed = run.friendly[0] as Error; + expect(passed.message).toBe( + "Failed to initialize your token account for this game. Please try again or ensure you have enough SOL for fees.", + ); + expect(passed.cause).toBe(failure); + }); + + test("another error with setup instructions is passed on unchanged", async () => { + const failure = new Error("custom program error"); + const run = await joinPrivate({ confirm: [fails(failure)] }); + expect(run.friendly).toEqual([failure]); + expect(run.sends).toHaveLength(1); + }); + + test.each([ + ["no setup instructions", async () => ({ accounts: {}, setupInstructions: [] })], + ["a failed account build", fails(new Error("uninitialized vault"))], + ])("a token account error with %s is passed on unchanged", async (_name, build) => { + const run = await joinPrivate({ build, confirm: [fails(new Error("uninitialized vault"))] }); + expect((run.friendly[0] as Error).message).toBe("uninitialized vault"); + }); + + test("a thrown value without a message is passed on unchanged", async () => { + const run = await joinPrivate({ build: fails(null) }); + expect(run.friendly).toEqual([null]); + expect(error).toHaveBeenCalledWith("Error joining private game:", null); + }); +}); diff --git a/tests/game-manager.stats-boundaries.test.ts b/tests/game-manager.stats-boundaries.test.ts index e3a826d8..f7df61eb 100644 --- a/tests/game-manager.stats-boundaries.test.ts +++ b/tests/game-manager.stats-boundaries.test.ts @@ -67,6 +67,12 @@ describe("completed game stats", () => { players: ["1", "2", "3"], expected: { currentTickets: 3, maxTickets: 3, minTickets: 3, totalPot: 30n }, }, + { + name: "zero limits fall back to the player count", + game: { max_players: 0, min_players: 0, game_type: "coinflip" }, + players: ["1", "2"], + expected: { currentTickets: 2, maxTickets: 2, minTickets: 2, totalPot: 20n }, + }, { name: "negative limits fall back to the player count", game: { max_players: -4, min_players: -1 }, diff --git a/tests/game.history.test.ts b/tests/game.history.test.ts index 9849db4c..4962b485 100644 --- a/tests/game.history.test.ts +++ b/tests/game.history.test.ts @@ -321,6 +321,7 @@ describe("getUserGamesHistory fallbacks", () => { BROKEN: 5_000_000_000, EMPTY: 0, FAILS: 1_000_000_000, + NEGATIVE: 1_000_000, }, lostAmountByToken: { ZERO_DEC: 4, @@ -335,6 +336,7 @@ describe("getUserGamesHistory fallbacks", () => { if (tokenMint === "FAILS") throw new Error("price api down"); if (tokenMint === WSOL_MINT) return { price: 100 }; if (tokenMint === "BROKEN") return { price: 0 }; + if (tokenMint === "NEGATIVE") return { price: -2 }; return { price: 2 }; }) as any); @@ -344,9 +346,34 @@ describe("getUserGamesHistory fallbacks", () => { expect(result.won.totalUsd).toBeCloseTo(3 * 2 + 2000 * 100, 6); // ZERO_DEC: 4 * 2 = 8, NO_DEC falls back to 9 decimals: 2 * 2 = 4 expect(result.lost.totalUsd).toBeCloseTo(8 + 4, 6); + // Each mint is asked once, a failed quote is not asked again, and zero or + // negative amounts are not asked at all. const askedMints = priceSpy.mock.calls.map((call: any[]) => call[0].tokenMint); - expect(askedMints).toContain(WSOL_MINT); - expect(askedMints).not.toContain("SOL"); + expect(askedMints).toEqual([ + "USDC_MINT", + WSOL_MINT, + "BROKEN", + "FAILS", + "NEGATIVE", + "ZERO_DEC", + "NO_DEC", + ]); + }); + + test("a ticker keeps the decimals of its first game", async () => { + const { gm } = await build({ + games: [ + baseGame({ game_address: "A", token_mint: "NINE_MINT" }), + baseGame({ game_address: "B", token_mint: "" }), + ], + wallet: { getTokenMetadata: async () => ({ decimals: 9 }) }, + }); + + const result = await gm.getUserGamesHistory(CTX, 12345n); + + expect(result.primaryTicker).toBe("TIMBA"); + expect(result.primaryDecimals).toBe(9); + expect(result.lost.games.map((g) => g.tokenDecimals)).toEqual([9, 6]); }); test("values equal wins and losses for the same mint with one shared quote", async () => { From 17f754da0cd04724b5216d4dcfc11d16690edc99 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Mon, 30 Nov 2026 04:12:00 -0300 Subject: [PATCH 318/410] fix(media): surface a 429 whose delay is too large to represent getRetryAfterSeconds returns null for a delay that cannot be represented, so the media retry waited one second instead. Tell a missing delay apart from a delay that is too large. --- src/utils/media.ts | 14 ++++++++++--- src/utils/telegram-errors.ts | 14 +++++++++++++ tests/media.retry.test.ts | 39 +++++++++++++++++++++++++++++++++++ tests/telegram-errors.test.ts | 15 ++++++++++++++ 4 files changed, 79 insertions(+), 3 deletions(-) diff --git a/src/utils/media.ts b/src/utils/media.ts index cf6dd45e..83795bd5 100644 --- a/src/utils/media.ts +++ b/src/utils/media.ts @@ -2,7 +2,12 @@ * Utility helpers for dealing with Telegram media operations. */ -import { getErrorDescription, getRetryAfterSeconds, isMessageNotModified } from "./telegram-errors"; +import { + getErrorDescription, + getRetryAfterSeconds, + hasRetryAfterHint, + isMessageNotModified, +} from "./telegram-errors"; import { MAX_TIMER_DELAY_MS } from "./retry-delay"; const isTooManyRequestsError = (error: any): boolean => { @@ -93,8 +98,11 @@ export const awaitTelegramRetry = async ( throw error; } - const delayMs = (getRetryAfterSeconds(error) ?? 1) * 1_000; - // Do not retry early when the provider's delay exceeds the native timer range. + // Without a delay, wait one second. Do not retry early when the provider's delay is + // too large to represent or exceeds the native timer range. + const retryAfterSeconds = getRetryAfterSeconds(error); + if (retryAfterSeconds === null && hasRetryAfterHint(error)) throw error; + const delayMs = (retryAfterSeconds ?? 1) * 1_000; if (delayMs > MAX_TIMER_DELAY_MS) throw error; await sleep(delayMs); } diff --git a/src/utils/telegram-errors.ts b/src/utils/telegram-errors.ts index cbf336c8..5c90c607 100644 --- a/src/utils/telegram-errors.ts +++ b/src/utils/telegram-errors.ts @@ -109,6 +109,20 @@ export const getRetryAfterSeconds = (error: unknown): number | null => { return retrySecondsToMilliseconds(seconds) === null ? null : seconds; }; +/** True when the error gives a retry delay, including one too large to represent. */ +export const hasRetryAfterHint = (error: unknown): boolean => { + if (!error || typeof error !== "object") { + return false; + } + + const response = error as RetryAfterFields; + return ( + isFiniteNumber(response.parameters?.retry_after) || + isFiniteNumber(response.retry_after) || + /retry after \d/i.test(getErrorString(error)) + ); +}; + export const shouldFallbackToReply = (error: unknown): boolean => isMessageMissing(error) || isEditProhibited(error) || diff --git a/tests/media.retry.test.ts b/tests/media.retry.test.ts index a0146734..f2eca20b 100644 --- a/tests/media.retry.test.ts +++ b/tests/media.retry.test.ts @@ -283,6 +283,45 @@ describe("media retry helpers", () => { } }); + test.each([ + [ + "the parameters", + Object.assign(new Error("Too Many Requests"), { + error_code: 429, + parameters: { retry_after: 1e308 }, + }), + ], + [ + "the description text", + Object.assign(new Error(`Too Many Requests: retry after ${"9".repeat(35)}`), { + error_code: 429, + }), + ], + ])( + "awaitTelegramRetry surfaces a 429 whose delay in %s is too large to represent", + async (_name, error) => { + const delays: number[] = []; + globalThis.setTimeout = ((callback: () => void, ms?: number) => { + delays.push(ms ?? 0); + callback(); + return 0 as any; + }) as any; + let attempts = 0; + try { + await expect( + awaitTelegramRetry(async () => { + attempts += 1; + throw error; + }), + ).rejects.toBe(error); + expect(attempts).toBe(1); + expect(delays).toEqual([]); + } finally { + globalThis.setTimeout = originalSetTimeout; + } + }, + ); + test("isRecoverableMediaError ignores unchanged messages and empty errors", () => { expect(isRecoverableMediaError(null)).toBe(false); expect(isRecoverableMediaError({})).toBe(false); diff --git a/tests/telegram-errors.test.ts b/tests/telegram-errors.test.ts index 6cb9c1af..cdc6ee66 100644 --- a/tests/telegram-errors.test.ts +++ b/tests/telegram-errors.test.ts @@ -2,6 +2,7 @@ import { describe, expect, test } from "bun:test"; import { getErrorDescription, getRetryAfterSeconds, + hasRetryAfterHint, isBotNotAdmin, isChatInaccessible, isDuplicateContent, @@ -157,6 +158,20 @@ describe("telegram error helpers", () => { expect(getRetryAfterSeconds("retry after 9")).toBeNull(); }); + test.each([ + ["a delay in the parameters", { parameters: { retry_after: 1e308 } }, true], + ["a top-level delay", { retry_after: 0 }, true], + ["a delay in the description", { description: `retry after ${"9".repeat(35)}` }, true], + ["a delay in the message", new Error("Too Many Requests: Retry After 3"), true], + ["a delay that is not a number", { parameters: { retry_after: "5" }, retry_after: NaN }, false], + ["null parameters", { parameters: null, description: "Too Many Requests" }, false], + ["no delay", { description: "Too Many Requests: retry later" }, false], + ["a text error", "retry after 9", false], + ["no error", null, false], + ])("hasRetryAfterHint with %s", (_name, error, expected) => { + expect(hasRetryAfterHint(error)).toBe(expected); + }); + test("rejects Retry-After hints that cannot be represented in milliseconds", () => { expect(getRetryAfterSeconds({ parameters: { retry_after: 1e308 } })).toBeNull(); expect( From 2a38b4f6d03da22d76537ce2e5ad548cd6d07a9c Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Mon, 30 Nov 2026 04:12:01 -0300 Subject: [PATCH 319/410] fix(game): replace disables that hid killable mutants Remove the join loop bound and the unreachable terminal redraw guard, warn on a stored wallet key that does not parse, clamp history quotes at zero, and remember the name lookup fallback again after a failed lookup. --- src/utils/game.ts | 35 +++++++++------------- tests/game-manager.player-keys.test.ts | 6 +++- tests/game-manager.username-lookup.test.ts | 18 +++++++++++ 3 files changed, 37 insertions(+), 22 deletions(-) diff --git a/src/utils/game.ts b/src/utils/game.ts index b4208055..91dd0602 100644 --- a/src/utils/game.ts +++ b/src/utils/game.ts @@ -2638,9 +2638,9 @@ export class GameManager { this.setCachedUsername(cacheKey, resolved); return resolved; } catch (fetchError) { - // The fallback is already a remembered hint: either it came from the - // hints or it was remembered when it was read from the database above. if (fallbackCandidate) { + // Remember it again: the hints may have been cleared during the lookup. + this.rememberTelegramUsername(trimmedId, fallbackCandidate); this.setCachedUsername(cacheKey, fallbackCandidate); return fallbackCandidate; } @@ -3638,7 +3638,6 @@ export class GameManager { updateGeneration?: number, updateRequest?: GameMessageUpdateRequest, updateOptions?: GameMessageUpdateOptions, - isTerminalRedraw = false, ): Promise { const request = updateRequest ?? { status, @@ -3691,11 +3690,8 @@ export class GameManager { if (!messageMap || messageMap.size === 0) return; const redrawAsTerminal = async (terminal: TerminalGameMessageUpdate): Promise => { - // An update may switch once from active to terminal. A terminal redraw must not restart. - // A terminal redraw has the status Completed, and only a status that is not Completed - // redirects. So this guard and the flag below keep the one-pass bound for later changes. - // Stryker disable next-line ConditionalExpression: no current path reaches it with the flag set. - if (isTerminalRedraw) return; + // An update may switch once from active to terminal. The redraw has the status + // Completed, and only a status that is not Completed redirects, so it cannot restart. await this.updateGameMessageInternal( ctx, gameAddress, @@ -3709,9 +3705,6 @@ export class GameManager { terminal.winnerSignature, updateGeneration, request, - undefined, - // Stryker disable next-line BooleanLiteral: no current path reaches it with the flag set. - true, ); }; @@ -5624,9 +5617,9 @@ export class GameManager { }); } else { const maxAttempts = 2; - // Each attempt ends with a break or a throw, and the last attempt never retries. - // Stryker disable next-line EqualityOperator,ConditionalExpression: so the loop bound is never what stops it. - for (let attempt = 0; attempt < maxAttempts; attempt++) { + // Each attempt ends with a break, a continue, or a throw. Only the retry check + // below decides if another attempt runs, and the last attempt never retries. + for (let attempt = 0; ; attempt++) { let setupInstructions: TransactionInstruction[] = []; try { const { accounts: joinAccounts, setupInstructions: setupIxs } = @@ -6473,13 +6466,12 @@ export class GameManager { const lookup = await getUsdPrice({ tokenMint: tokenMint === "SOL" ? WSOL_MINT : tokenMint, }); - // Number.isFinite is false for every value that is not a number, and a missing price is 0. - // Stryker disable next-line OptionalChaining: a missing lookup throws into the catch, which also returns null. + // A missing lookup has no price. Number.isFinite is false for every value that is + // not a number. A zero or negative price adds nothing to a total. + // Stryker disable next-line OptionalChaining: a missing lookup throws into the catch, and a null quote also adds nothing. const price = lookup?.price ?? 0; - // A zero price adds zero to a total, the same as no quote. - // Stryker disable next-line EqualityOperator: so the boundary at zero cannot change a total. - return Number.isFinite(price) && price > 0 - ? { price, divisor: Math.pow(10, decimals) } + return Number.isFinite(price) + ? { price: Math.max(price, 0), divisor: Math.pow(10, decimals) } : null; } catch { return null; @@ -8590,7 +8582,6 @@ export class GameManager { for (const telegramId of participantTelegramIds) { try { const playerPubkeyStr = this.gameDb.getPlayerPublicKey(telegramId); - // Stryker disable next-line ConditionalExpression,BlockStatement: a missing key also fails the parse below, and the catch marks it unavailable too. if (!playerPubkeyStr) { unavailable.push(telegramId); continue; @@ -8605,6 +8596,8 @@ export class GameManager { isCreator, }); } catch (error) { + // A player without a key is normal. A stored key that does not parse is bad data. + console.warn(`⚠️ Stored wallet key for player ${telegramId} is not valid:`, error); unavailable.push(telegramId); } } diff --git a/tests/game-manager.player-keys.test.ts b/tests/game-manager.player-keys.test.ts index 5d8e2756..0164cf06 100644 --- a/tests/game-manager.player-keys.test.ts +++ b/tests/game-manager.player-keys.test.ts @@ -137,7 +137,7 @@ describe("player key analysis", () => { }); test("players without a valid key and unmatched wallets are unavailable", () => { - const { info } = analyze( + const { info, warnings } = analyze( { creator: CREATOR, participants: ["a", "b", "c", "d"], ticketsCount: 2 }, { players: ["2", "3", "4"], @@ -147,6 +147,10 @@ describe("player key analysis", () => { }, ); expect(info.unavailable).toEqual(["2", "3", "4", "walletA", "walletB"]); + // Only the stored key that does not parse is reported. A missing or empty key is normal. + expect(warnings).toEqual([ + ["⚠️ Stored wallet key for player 3 is not valid:", expect.any(Error)], + ]); expect(info.unmatchedParticipants).toEqual(["walletA", "walletB"]); expect(info.canCompleteCleanup).toBe(false); expect(info).toMatchObject({ total: 4, onChainParticipants: 4, onChainTickets: 2 }); diff --git a/tests/game-manager.username-lookup.test.ts b/tests/game-manager.username-lookup.test.ts index a8afccee..61844c08 100644 --- a/tests/game-manager.username-lookup.test.ts +++ b/tests/game-manager.username-lookup.test.ts @@ -117,6 +117,24 @@ describe("Telegram name lookup", () => { expect(lookups).toHaveLength(1); }); + test("a failed lookup remembers the fallback again when the hints were cleared meanwhile", async () => { + let fail: (reason: Error) => void = () => undefined; + const pending = new Promise((_resolve, reject) => { + fail = reject; + }); + const { gm, ctx, ctxFor } = setup(); + ctx.api.getChatMember = async () => pending; + gm.primeUsernameCache(ctxFor(3), "5", "Hint", false); + const lookup = gm.getUsernameFromTelegramId(ctx, "5"); + // Another lookup found no handle and cleared the hints while this one waits. + gm.clearTelegramUsernames("5"); + fail(new Error("synthetic lookup failure")); + expect(await lookup).toBe("Hint"); + expect(await gm.getUsernameFromTelegramId(ctxFor(2), "5", { allowNetworkLookup: false })).toBe( + "Hint", + ); + }); + test("a failed lookup falls back to the stored name and caches it", async () => { const { gm, ctx, lookups } = setup( () => { From 92ac26cf10532f66053a8859b24e71c92866b7e3 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Mon, 30 Nov 2026 04:18:53 -0300 Subject: [PATCH 320/410] fix(ci): check debug trace arguments and watch the ignorers in the mutation job The debug trace ignorer now ignores a call only when every argument is text or a plain value. Text in other trace calls is ignored by the log text rule. The mutation workflow now runs on ignorer changes and includes them in the setup trial. --- .github/workflows/mutants.yml | 4 +- scripts/stryker-ignorers.mjs | 66 ++++++++++++++------ scripts/stryker-ignorers.test.ts | 101 ++++++++++++++++++++++--------- 3 files changed, 124 insertions(+), 47 deletions(-) diff --git a/.github/workflows/mutants.yml b/.github/workflows/mutants.yml index 6d05158a..09145b8c 100644 --- a/.github/workflows/mutants.yml +++ b/.github/workflows/mutants.yml @@ -12,6 +12,8 @@ on: - src/** - coverage-scope.json - stryker.conf.mjs + - scripts/stryker-ignorers.mjs + - scripts/stryker-ignorers.test.ts - scripts/mutants.ts - scripts/mutants.test.ts - scripts/mutants-post.sh @@ -68,7 +70,7 @@ jobs: run: bun run scripts/mutants.ts diff HEAD^1 --out build/mutants - name: Try one part of everything run: | - if git diff --quiet HEAD^1 -- stryker.conf.mjs scripts/mutants.ts .github/workflows/mutants.yml; then + if git diff --quiet HEAD^1 -- stryker.conf.mjs scripts/stryker-ignorers.mjs scripts/mutants.ts .github/workflows/mutants.yml; then echo "The setup didn't change." else bun run scripts/mutants.ts part 0 64 --out build/mutants-part diff --git a/scripts/stryker-ignorers.mjs b/scripts/stryker-ignorers.mjs index b924d77d..a60c39bf 100644 --- a/scripts/stryker-ignorers.mjs +++ b/scripts/stryker-ignorers.mjs @@ -4,22 +4,6 @@ /** Names of trace helpers that print only when debug logging is turned on. */ export const DEBUG_TRACE_FUNCTIONS = new Set(["debugLog"]); -/** @type {import("@stryker-mutator/api/ignore").Ignorer} */ -export const debugTraceIgnorer = { - shouldIgnore(path) { - /** @type {any} */ - const node = /** @type {any} */ (path).node; - if ( - node?.type === "CallExpression" && - node.callee?.type === "Identifier" && - DEBUG_TRACE_FUNCTIONS.has(node.callee.name) - ) { - return "Debug trace text. It prints only with TIMBA_DEBUG=true and its arguments have no side effects."; - } - return undefined; - }, -}; - /** Console methods whose text goes only to the operator log. */ export const CONSOLE_LOG_METHODS = new Set(["log", "info", "warn", "error", "debug"]); @@ -69,7 +53,50 @@ const isConsoleLogCall = (node) => CONSOLE_LOG_METHODS.has(node.callee.property.name); /** - * Ignores only text literals in console arguments. Other mutants in the same call, + * True for a debug trace call: `debugLog(...)`. + * @param {any} node + * @returns {boolean} + */ +const isDebugTraceCall = (node) => + node?.type === "CallExpression" && + node.callee?.type === "Identifier" && + DEBUG_TRACE_FUNCTIONS.has(node.callee.name); + +/** + * True for an argument that is only text: a string, a number, a plain value, a + * template literal of plain values, or a `+` join of these. + * @param {any} node + * @returns {boolean} + */ +const isPlainText = (node) => + node?.type === "StringLiteral" || + node?.type === "NumericLiteral" || + (node?.type === "TemplateLiteral" && node.expressions.every(isPlainValue)) || + (node?.type === "BinaryExpression" && + node.operator === "+" && + isPlainText(node.left) && + isPlainText(node.right)) || + isPlainValue(node); + +/** + * Ignores a whole debug trace call only when every argument is text or a plain + * value, so the call has no side effects. Text in other trace calls is still + * ignored by the log text ignorer, and their other mutants are tested. + * @type {import("@stryker-mutator/api/ignore").Ignorer} + */ +export const debugTraceIgnorer = { + shouldIgnore(path) { + /** @type {any} */ + const node = /** @type {any} */ (path).node; + if (isDebugTraceCall(node) && node.arguments.every(isPlainText)) { + return "Debug trace text. It prints only with TIMBA_DEBUG=true, and every argument is text or a plain value."; + } + return undefined; + }, +}; + +/** + * Ignores only text literals in console and debug trace arguments. Other mutants in the same call, * such as a changed condition or a missing optional read, are still tested. * @type {import("@stryker-mutator/api/ignore").Ignorer} */ @@ -92,8 +119,9 @@ export const consoleTextIgnorer = { ) { current = current.parentPath; } - if (current.listKey === "arguments" && isConsoleLogCall(current.parentPath?.node)) { - return "Operator log text. Console output does not change what the bot does or shows to players."; + const call = current.parentPath?.node; + if (current.listKey === "arguments" && (isConsoleLogCall(call) || isDebugTraceCall(call))) { + return "Operator log text. Log output does not change what the bot does or shows to players."; } return undefined; }, diff --git a/scripts/stryker-ignorers.test.ts b/scripts/stryker-ignorers.test.ts index 4364d9ee..78be5d66 100644 --- a/scripts/stryker-ignorers.test.ts +++ b/scripts/stryker-ignorers.test.ts @@ -1,4 +1,6 @@ import { describe, expect, test } from "bun:test"; +import { readFileSync } from "node:fs"; +import { join } from "node:path"; import { consoleTextIgnorer, debugTraceIgnorer, strykerPlugins } from "./stryker-ignorers.mjs"; // The smallest Babel NodePath shapes the ignorer reads. @@ -21,32 +23,6 @@ const paths = { }; const callPath = (source: keyof typeof paths) => paths[source]; -describe("Stryker debug trace ignorer", () => { - test("ignores a call to the debug trace helper with a reason", () => { - const reason = debugTraceIgnorer.shouldIgnore(callPath("debugLog(`joined ${name}`, 1)") as any); - expect(reason).toContain("TIMBA_DEBUG=true"); - }); - - test.each([ - ["a console warning", "console.warn(`joined ${name}`)"], - ["a method named debugLog", "logger.debugLog(`joined`)"], - ["another function", "notifyPlayer(`joined`)"], - ["a reference that is not a call", "debugLog"], - ] as const)("keeps mutants in %s", (_label, source) => { - expect(debugTraceIgnorer.shouldIgnore(callPath(source) as any)).toBeUndefined(); - }); - - test("registers the ignorer under the name used in the Stryker config", async () => { - const config = (await import("../stryker.conf.mjs")).default as any; - expect(config.ignorers).toEqual(["debug-trace", "console-text"]); - expect(config.appendPlugins).toContain("./scripts/stryker-ignorers.mjs"); - expect(strykerPlugins.map((plugin: any) => [plugin.kind, plugin.name, plugin.value])).toEqual([ - ["Ignore", "debug-trace", debugTraceIgnorer], - ["Ignore", "console-text", consoleTextIgnorer], - ]); - }); -}); - // Small Babel node builders. A node marked with `target` is the one the ignorer sees. type Node = { type: string; target?: boolean; [key: string]: unknown }; const id = (name: string): Node => ({ type: "Identifier", name }); @@ -100,6 +76,73 @@ function pathOf(root: Node) { return found as any; } +describe("Stryker debug trace ignorer", () => { + test("ignores a call to the debug trace helper with a reason", () => { + const reason = debugTraceIgnorer.shouldIgnore(callPath("debugLog(`joined ${name}`, 1)") as any); + expect(reason).toContain("TIMBA_DEBUG=true"); + }); + + test.each([ + ["a console warning", "console.warn(`joined ${name}`)"], + ["a method named debugLog", "logger.debugLog(`joined`)"], + ["another function", "notifyPlayer(`joined`)"], + ["a reference that is not a call", "debugLog"], + ] as const)("keeps mutants in %s", (_label, source) => { + expect(debugTraceIgnorer.shouldIgnore(callPath(source) as any)).toBeUndefined(); + }); + + // The whole call is ignored only when every argument is text, so no argument can + // change state. + const debugCall = (args: Node[]) => ({ node: callOf(id("debugLog"), args) }); + test.each([ + ["no arguments", []], + ["a string and a number", [str("joined"), { type: "NumericLiteral", value: 1 }]], + ["a template of names", [tpl([id("name"), member(id("game"), "id")])]], + ["a joined string", [plus(plus(str("a"), id("x")), callOf(member(id("pda"), "toBase58")))]], + ["a plain value", [member({ type: "ThisExpression" }, "name")]], + ])("ignores a debug trace with %s", (_name, args) => { + expect(debugTraceIgnorer.shouldIgnore(debugCall(args as Node[]) as any)).toBe( + "Debug trace text. It prints only with TIMBA_DEBUG=true, and every argument is text or a plain value.", + ); + }); + + test.each([ + ["a call with an argument", [str("a"), callOf(member(id("cache"), "take"), [id("id")])]], + ["another method in a template", [tpl([callOf(member(id("wallet"), "format"))])]], + ["an optional read", [member(id("a"), "b", { optional: true })]], + ["a sum that is not text", [plus(id("a"), id("b"), "-")]], + ["an object", [{ type: "ObjectExpression", properties: [] }]], + [ + "a choice", + [{ type: "ConditionalExpression", test: id("a"), consequent: str("b"), alternate: str("c") }], + ], + ])("keeps mutants in a debug trace with %s", (_name, args) => { + expect(debugTraceIgnorer.shouldIgnore(debugCall(args as Node[]) as any)).toBeUndefined(); + }); + + test("a change to the ignorers runs the mutation job and the setup trial", () => { + const workflow = readFileSync( + join(import.meta.dir, "..", ".github", "workflows", "mutants.yml"), + "utf8", + ); + const paths = workflow.slice(workflow.indexOf("paths:"), workflow.indexOf("schedule:")); + expect(paths).toContain("- scripts/stryker-ignorers.mjs\n"); + expect(paths).toContain("- scripts/stryker-ignorers.test.ts\n"); + const trial = workflow.split("\n").find((line) => line.includes("git diff --quiet HEAD^1")); + expect(trial).toContain(" scripts/stryker-ignorers.mjs "); + }); + + test("registers the ignorer under the name used in the Stryker config", async () => { + const config = (await import("../stryker.conf.mjs")).default as any; + expect(config.ignorers).toEqual(["debug-trace", "console-text"]); + expect(config.appendPlugins).toContain("./scripts/stryker-ignorers.mjs"); + expect(strykerPlugins.map((plugin: any) => [plugin.kind, plugin.name, plugin.value])).toEqual([ + ["Ignore", "debug-trace", debugTraceIgnorer], + ["Ignore", "console-text", consoleTextIgnorer], + ]); + }); +}); + describe("Stryker console text ignorer", () => { const ignored = (root: Node) => consoleTextIgnorer.shouldIgnore(pathOf(root)); @@ -126,9 +169,13 @@ describe("Stryker console text ignorer", () => { "a string inside a template part", consoleCall("warn", [tpl([plus(str("a", true), id("b"))])]), ], + [ + "a string in a debug trace with another argument", + callOf(id("debugLog"), [str("a", true), callOf(member(id("cache"), "take"), [id("id")])]), + ], ])("ignores %s", (_name, root) => { expect(ignored(root)).toBe( - "Operator log text. Console output does not change what the bot does or shows to players.", + "Operator log text. Log output does not change what the bot does or shows to players.", ); }); From 344d5f0cf6c1a91220289cbb35fb71b35d8f14bd Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Mon, 30 Nov 2026 04:23:17 -0300 Subject: [PATCH 321/410] fix(capital): reject an RPC account list whose length does not match the request The total used to reduce over the returned accounts, so a short answer skipped the missing required targets and reported too little capital. --- src/services/contract-capital.ts | 15 ++++++++++----- tests/contract-capital.test.ts | 29 ++++++++++++++++++++++++++++- 2 files changed, 38 insertions(+), 6 deletions(-) diff --git a/src/services/contract-capital.ts b/src/services/contract-capital.ts index 428df4a3..16d99a27 100644 --- a/src/services/contract-capital.ts +++ b/src/services/contract-capital.ts @@ -75,11 +75,16 @@ export async function getContractCapitalLamports( VERIFICATION_COMMITMENT, ); - return accounts.reduce((total, account, index) => { - const expected = targets[index]; - if (!expected) { - throw new Error(`Unable to verify contract account ${index}`); - } + // A short or long answer cannot verify every target, and a missing required one + // would make the total too low. + if (accounts.length !== targets.length) { + throw new Error( + `Unable to verify contract accounts: asked for ${targets.length}, got ${accounts.length}`, + ); + } + + return targets.reduce((total, expected, index) => { + const account = accounts[index]; if (!account && !expected.required) { return total; } diff --git a/tests/contract-capital.test.ts b/tests/contract-capital.test.ts index aea5b8d7..8e07c41e 100644 --- a/tests/contract-capital.test.ts +++ b/tests/contract-capital.test.ts @@ -162,6 +162,33 @@ describe("contract capital verification failures", () => { ); }); + test("rejects an RPC response with fewer accounts than requested", async () => { + const { programId, programDataBytes } = await setup(); + const getAccountInfo = mock(async () => ({ + owner: LOADER, + data: programDataBytes, + lamports: 1n, + executable: true, + rentEpoch: 0n, + space: 36n, + })); + // The answer leaves out the last target, the required oracle account. + const getMultipleAccountsInfo = mock(async (addresses) => + addresses.slice(0, -1).map(() => ({ + owner: LOADER, + data: programDataBytes, + lamports: 1n, + executable: true, + rentEpoch: 0n, + space: 36n, + })), + ); + + await expect( + getContractCapitalLamports({ getAccountInfo, getMultipleAccountsInfo }, { programId }, []), + ).rejects.toThrow("Unable to verify contract accounts: asked for 3, got 2"); + }); + test("rejects a required account that does not exist", async () => { const { programId, programDataBytes } = await setup(); const tokenMint = (await Keypair.generate()).publicKey; @@ -239,7 +266,7 @@ describe("contract capital verification failures", () => { }; await expect(getContractCapitalLamports(connection as any, { programId }, [])).rejects.toThrow( - "Unable to verify contract account 3", + "Unable to verify contract accounts: asked for 3, got 4", ); }); }); From 83cd859c26099c07d5e99fadccaf254b2331176a Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Mon, 30 Nov 2026 04:23:18 -0300 Subject: [PATCH 322/410] test: check non-finite alert sizes without a minimum and the 16-digit sats limit --- tests/buy-alerts.publisher.test.ts | 17 +++++++++++++++++ tests/lightning-deposits.test.ts | 4 +++- 2 files changed, 20 insertions(+), 1 deletion(-) diff --git a/tests/buy-alerts.publisher.test.ts b/tests/buy-alerts.publisher.test.ts index d7a81721..9abb718e 100644 --- a/tests/buy-alerts.publisher.test.ts +++ b/tests/buy-alerts.publisher.test.ts @@ -455,6 +455,23 @@ test("allows the exact lamport minimum but rejects missing and non-finite SOL si expect(posted).toHaveLength(1); }); +test("posts a non-finite SOL size when the chat has no minimum", async () => { + const chatDb = ChatDatabase.getInstance(); + chatDb.upsertChatBuyAlerts(-1, { enabled: true, min_sol_lamports: null }); + const publisher = createBuyAlertPublisher({ + chatDb, + tokenManager, + fetchPairStats: async () => null, + sendHtml: async () => undefined, + }); + for (const [index, solAmount] of [NaN, Infinity, null].entries()) { + expect(await publisher.publish(event({ signature: `open-${index}`, solAmount }))).toEqual({ + posted: 1, + skipped: [], + }); + } +}); + test.each([ ["Raydium CLMM", "DEX: ⚡ Raydium AMM SOL"], [null, "DEX: 💊 Pump.fun SOL"], diff --git a/tests/lightning-deposits.test.ts b/tests/lightning-deposits.test.ts index 68c3ffd8..dae76f94 100644 --- a/tests/lightning-deposits.test.ts +++ b/tests/lightning-deposits.test.ts @@ -33,8 +33,10 @@ describe("Lightning deposits", () => { test("formats sats without floating point rounding", () => { expect(satsToBtc("1")).toBe("0.00000001"); expect(satsToBtc("10000")).toBe("0.00010000"); + // Sixteen digits are accepted up to the 21 million BTC supply limit. + expect(satsToBtc("1000000000000000")).toBe("10000000.00000000"); expect(satsToBtc("2100000000000000")).toBe("21000000.00000000"); - for (const invalid of ["0", "-1", "1.2", "1e8", " 1", "2100000000000001"]) + for (const invalid of ["0", "-1", "1.2", "1e8", " 1", "2100000000000001", "10000000000000000"]) expect(() => satsToBtc(invalid)).toThrow(); }); From e6a9b58284468c6b2b12e3c6edb2f57e82e16f5e Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Mon, 30 Nov 2026 04:27:39 -0300 Subject: [PATCH 323/410] test(lightning): check stale quote cancel per state and settlement edge values create no longer repeats the quote expiry test that admit and cancelQuote already do. hasSettlementTransfer skips falsy instructions with one check. --- src/services/lightning/service.ts | 15 ++++++--------- tests/lightning-deposits.test.ts | 16 +++++++++++++++- tests/lightning.service-client.test.ts | 19 +++++++++++++++++++ 3 files changed, 40 insertions(+), 10 deletions(-) diff --git a/src/services/lightning/service.ts b/src/services/lightning/service.ts index b7df024b..c23e4ef2 100644 --- a/src/services/lightning/service.ts +++ b/src/services/lightning/service.ts @@ -6,12 +6,7 @@ import { invoiceMatchesSats, type FixedFloatOrder, } from "./fixedfloat"; -import { - DEPOSIT_POLL_INTERVAL_MS, - DEPOSIT_QUOTE_TTL_MS, - DepositStore, - type Deposit, -} from "./store"; +import { DEPOSIT_POLL_INTERVAL_MS, DepositStore, type Deposit } from "./store"; export class LightningDeposits { private polling = false; @@ -52,8 +47,9 @@ export class LightningDeposits { const deposit = this.store.get(id); if (!deposit || deposit.owner !== owner) throw new Error("Deposit not found."); if (!this.store.admit(id, owner)) { - if (deposit.state === "quoted" && deposit.created < Date.now() - DEPOSIT_QUOTE_TTL_MS) - this.store.cancelQuote(id, owner); + // admit refuses a quoted row only after it expires, and cancelQuote changes only a + // quoted row, so a deposit in any other state stays as it is. + this.store.cancelQuote(id, owner); return this.store.get(id)!; } try { @@ -142,7 +138,8 @@ export function hasSettlementTransfer(tx: unknown, destination: string, expected ]; let received = 0n; for (const raw of instructions) { - if (typeof raw !== "object" || raw === null) continue; + // Any other primitive has none of the fields below, so the next check skips it. + if (!raw) continue; const ix = raw as { program?: string; programId?: { toString(): string }; diff --git a/tests/lightning-deposits.test.ts b/tests/lightning-deposits.test.ts index dae76f94..91d4ded3 100644 --- a/tests/lightning-deposits.test.ts +++ b/tests/lightning-deposits.test.ts @@ -388,7 +388,21 @@ test("only counts parsed native transfers with positive whole lamports", () => { expect(hasSettlementTransfer(null, destination, 7n)).toBe(false); expect(hasSettlementTransfer(inner([valid]), destination, 0n)).toBe(false); expect(hasSettlementTransfer(inner([valid]), destination, 7n)).toBe(true); - expect(hasSettlementTransfer(inner([null, {}, valid]), destination, 7n)).toBe(true); + expect( + hasSettlementTransfer( + inner([null, undefined, 0, "", 7, "7", true, {}, valid]), + destination, + 7n, + ), + ).toBe(true); + // A number above the safe integer limit is not exact, so it never counts. + expect( + hasSettlementTransfer( + inner([{ ...valid, parsed: { type: "transfer", info: { destination, lamports: 2 ** 60 } } }]), + destination, + 1n, + ), + ).toBe(false); expect( hasSettlementTransfer( inner([ diff --git a/tests/lightning.service-client.test.ts b/tests/lightning.service-client.test.ts index 721a85dd..018ed436 100644 --- a/tests/lightning.service-client.test.ts +++ b/tests/lightning.service-client.test.ts @@ -91,6 +91,25 @@ describe("LightningDeposits.create", () => { expect(db.get(deposit.id)?.state).toBe("expired"); }); + test.each(["creating", "unknown", "active", "failed", "expired"] as const)( + "a %s deposit is not changed or sent to the provider again", + async (state) => { + const db = store(); + let created = 0; + const service = serviceWith(db, { + create: async () => { + created++; + return order(); + }, + }); + const deposit = await service.quote("1", destination, "10000"); + db.update(deposit.id, state); + + expect((await service.create(deposit.id, "1")).state).toBe(state); + expect(created).toBe(0); + }, + ); + test("an invoice for the wrong amount is kept for recovery but never activated", async () => { const db = store(); const service = serviceWith(db, { From 7705c5923bac3ea34dfc9a03692cd0fdf310e854 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Mon, 30 Nov 2026 04:28:39 -0300 Subject: [PATCH 324/410] test(wallet): check the stale fallback cache and its generation guard --- tests/wallet-menu.cache.test.ts | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/tests/wallet-menu.cache.test.ts b/tests/wallet-menu.cache.test.ts index 2b1f482b..c38dae0b 100644 --- a/tests/wallet-menu.cache.test.ts +++ b/tests/wallet-menu.cache.test.ts @@ -233,6 +233,36 @@ describe("wallet menu cache guards", () => { expect(module.__test_getWalletSnapshotCacheKeys()).toEqual([]); }); + test("a stale fallback is cached for the TTL and is not read again", async () => { + const { wallet, state } = createStubWallet({ fail: true, staleNative: 42 }); + const module = createModule(wallet); + module.__test_clearWalletSnapshotCache(); + + const first = await module.getCachedWalletData(14n); + const second = await module.getCachedWalletData(14n); + + expect(first).toMatchObject({ solBalance: 42, nativeSolBalance: 42, tokenBalances: [] }); + expect(second).toBe(first); + expect(module.__test_getWalletSnapshotCacheKeys()).toEqual(["14:rpc"]); + ensureBalanceCalled(state, 1); + }); + + test("a clear during a failed fetch keeps the stale fallback out of the cache", async () => { + let moduleRef: ReturnType | null = null; + const { wallet, state } = createStubWallet({ + fail: true, + staleNative: 42, + beforeBalance: () => moduleRef?.clearWalletCache(15n), + }); + const module = createModule(wallet); + moduleRef = module; + module.__test_clearWalletSnapshotCache(); + + expect(await module.getCachedWalletData(15n)).toMatchObject({ solBalance: 42 }); + expect(module.__test_getWalletSnapshotCacheKeys()).toEqual([]); + ensureBalanceCalled(state, 1); + }); + test("TTL expiration triggers new RPC", async () => { const { wallet, state } = createStubWallet(); const module = createModule(wallet); From 0768139dc28cdd9a7309f1f04facbb8bc71eed08 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Mon, 30 Nov 2026 04:35:02 -0300 Subject: [PATCH 325/410] test(fees): check SOL value limits, missing quotes, and referral claim reads The SOL value no longer repeats the price guard that validation already applies. A referral claim without meta now skips the ledger loop, which records nothing in both forms. --- src/services/fee-sweeper.ts | 14 +++-- tests/fee-sweeper.paths.test.ts | 68 +++++++++++++++++---- tests/fee-sweeper.referral-decimals.test.ts | 29 +++++++++ tests/fee-sweeper.test.ts | 16 +++++ 4 files changed, 108 insertions(+), 19 deletions(-) diff --git a/src/services/fee-sweeper.ts b/src/services/fee-sweeper.ts index 01bdee38..7a686d82 100644 --- a/src/services/fee-sweeper.ts +++ b/src/services/fee-sweeper.ts @@ -195,10 +195,10 @@ const getSolBalanceUsdValue = async ( connection.getBalance(owner).then(Number), priceResolver({ tokenMint: WSOL_MINT }), ]); - const solPrice = solPriceData?.price ?? 0; - const usdValue = - lamports > 0 && solPrice > 0 ? finiteUsdValue(lamports / LAMPORTS_PER_SOL, solPrice) : 0; - return { lamports, usdValue, solPrice, solPriceData }; + // The caller uses usdValue only after validateSolPriceData accepts a positive finite price, + // and an RPC balance is never negative. + const usdValue = finiteUsdValue(lamports / LAMPORTS_PER_SOL, solPriceData?.price); + return { lamports, usdValue, solPriceData }; }; const shouldSkipTokenToSolSweeps = async (options: { @@ -541,10 +541,12 @@ async function runReferralSweep( commitment: "confirmed", maxSupportedTransactionVersion: 0, }); - if (confirmed) { + // A delta needs the token balances in meta, so a claim without meta records nothing. + if (confirmed?.meta) { for (const tokenAccount of allTokenAccounts) { const address = tokenAccount.pubkey.toBase58(); const delta = referralDeltaFromTransaction(confirmed, address); + // Stryker disable next-line EqualityOperator: referralDeltaFromTransaction returns null for a zero delta, so >= and > match. if (!delta || delta.delta >= 0n) continue; TransactionHistory.getInstance().recordFinanceEvent({ eventId: `jupiter:${sig}:${address}:claimed`, @@ -555,7 +557,7 @@ async function runReferralSweep( account: address, mint: delta.mint, amountRaw: (-delta.delta).toString(), - networkFeeLamports: String(confirmed.meta?.fee ?? 0), + networkFeeLamports: String(confirmed.meta.fee ?? 0), timestamp: Number(confirmed.blockTime ?? Math.floor(Date.now() / 1000)) * 1_000, slot: Number(confirmed.slot), }); diff --git a/tests/fee-sweeper.paths.test.ts b/tests/fee-sweeper.paths.test.ts index d69c2665..fe8289f9 100644 --- a/tests/fee-sweeper.paths.test.ts +++ b/tests/fee-sweeper.paths.test.ts @@ -162,7 +162,7 @@ describe("SOL price validation before swaps", () => { __test_clearPriceServiceCache(); }); - const run = async (solPrice: Record | null) => { + const run = async (solPrice: Record | null, lamports = 0) => { const admin = await Keypair.generate(); const swaps: unknown[] = []; await __test_sweepTokensToSol( @@ -171,7 +171,7 @@ describe("SOL price validation before swaps", () => { getTokenMetadata: async () => ({ decimals: 6 }), formatSolBalance: String, } as any, - { getBalance: async () => 0 } as any, + { getBalance: async () => lamports } as any, [{ mint: (await Keypair.generate()).publicKey.toBase58(), ticker: "AAA" }], () => ({ @@ -189,6 +189,21 @@ describe("SOL price validation before swaps", () => { return swaps.length; }; + test.each([ + [149_999_999, 1], + [150_000_000, 0], + [Number.MAX_SAFE_INTEGER, 0], + ])( + "a SOL balance of %p lamports at $100 gives %p swaps against the $15 limit", + async (lamports, swaps) => { + expect(await run({ price: 100, resolvedAt: Date.now() }, lamports)).toBe(swaps); + }, + ); + + test("a SOL value too large to represent counts as zero and does not block swaps", async () => { + expect(await run({ price: Number.MAX_VALUE, resolvedAt: Date.now() }, 1e18)).toBe(1); + }); + test("accepts a price timestamped in seconds", async () => { expect(await run({ price: 100, timestamp: Math.floor(Date.now() / 1000) })).toBe(1); }); @@ -432,13 +447,15 @@ describe("referral claims", () => { const sent: Uint8Array[] = []; const connection = { getParsedAccountInfo: async () => ({ value: { data: { program: "spl-token" } } }), - getLatestBlockhash: async () => ({ blockhash: "11111111111111111111111111111111" }), + getLatestBlockhash: async (_commitment?: string) => ({ + blockhash: "11111111111111111111111111111111", + }), sendRawTransaction: async (raw: Uint8Array) => { sent.push(raw); return `claim-${sent.length}`; }, confirmTransaction: async () => ({ value: { err: null } }), - getTransaction: async () => options.confirmed ?? null, + getTransaction: async (_signature?: string, _options?: unknown) => options.confirmed ?? null, }; const provider = { getReferralTokenAccountsV2: async () => ({ @@ -602,22 +619,47 @@ describe("referral claims", () => { expect(logged(warnSpy, "Unable to record referral claim claim-1")).toBe(true); }); - test("an unconfirmed claim records nothing", async () => { - const s = await claimSetup({ transactions: [fakeTx()] }); + test.each([ + ["an unconfirmed claim", null], + ["a claim without meta", { slot: 1, blockTime: 1, meta: null, transaction: { message: {} } }], + ])("%s records nothing and logs no ledger error", async (_label, confirmed) => { + const s = await claimSetup({ transactions: [fakeTx()], confirmed }); const record = spyOn(TransactionHistory.getInstance(), "recordFinanceEvent"); try { - await __test_runReferralSweep( - s.connection as any, - s.payer, - referral, - price(1), - () => s.provider as any, - ); + expect( + await __test_runReferralSweep( + s.connection as unknown as SweepInputs[0], + s.payer, + referral, + price(1), + () => s.provider as unknown as ReturnType>, + ), + ).toBe(1); expect(record).not.toHaveBeenCalled(); + expect(warnSpy.mock.calls).toEqual([]); } finally { record.mockRestore(); } }); + + test("reads the blockhash and the claim at confirmed commitment", async () => { + const s = await claimSetup({ transactions: [fakeTx()] }); + const blockhash = spyOn(s.connection, "getLatestBlockhash"); + const transaction = spyOn(s.connection, "getTransaction"); + + await __test_runReferralSweep( + s.connection as unknown as SweepInputs[0], + s.payer, + referral, + price(1), + () => s.provider as unknown as ReturnType>, + ); + + expect(blockhash.mock.calls).toEqual([["confirmed"]]); + expect(transaction.mock.calls).toEqual([ + ["claim-1", { commitment: "confirmed", maxSupportedTransactionVersion: 0 }], + ]); + }); }); describe("sweepFees orchestration", () => { diff --git a/tests/fee-sweeper.referral-decimals.test.ts b/tests/fee-sweeper.referral-decimals.test.ts index 84ec64ad..db656e51 100644 --- a/tests/fee-sweeper.referral-decimals.test.ts +++ b/tests/fee-sweeper.referral-decimals.test.ts @@ -105,6 +105,35 @@ describe("referral sweep uses on-chain mint decimals", () => { expect(logged("Skipping referral claim: total value ≈ $0.01")).toBe(true); }); + test.each([ + ["no quote", null], + ["a zero quote", 0], + ] as const)("skips %s without reading that mint's decimals", async (_label, otherPrice) => { + const s = await setup(0, 5n); + const otherMint = (await Keypair.generate()).publicKey; + const otherAccount = (await Keypair.generate()).publicKey; + const provider = { + ...s.provider, + getReferralTokenAccountsV2: async () => ({ + tokenAccounts: [ + { pubkey: otherAccount, account: { mint: otherMint, amount: 10n } }, + { pubkey: s.accountKey, account: { mint: s.mint, amount: 5n } }, + ], + token2022Accounts: [], + }), + }; + await s.sweep(async ({ tokenMint }) => { + if (tokenMint === s.mint.toBase58()) { + return { price: 1, identifier: tokenMint, resolvedAt: Date.now() }; + } + return otherPrice === null + ? null + : { price: otherPrice, identifier: "other", resolvedAt: Date.now() }; + }, provider); + expect(s.requestedMints).toEqual([s.mint.toBase58()]); + expect(s.claimCalls).toHaveLength(1); + }); + test("ignores a negative quote without reducing another mint below the claim threshold", async () => { const s = await setup(0, 5n); const invalidMint = (await Keypair.generate()).publicKey; diff --git a/tests/fee-sweeper.test.ts b/tests/fee-sweeper.test.ts index 24d997fe..c2b49b30 100644 --- a/tests/fee-sweeper.test.ts +++ b/tests/fee-sweeper.test.ts @@ -183,6 +183,22 @@ describe("WSOL unwrap helper", async () => { expect(unwrapCalls).toEqual([6_000_000_000]); }); + test("skips the unwrap when the WSOL price lookup returns nothing", async () => { + type UnwrapInputs = Parameters; + const unwrapCalls: number[] = []; + + await __test_unwrapWsolBalance( + buildWallet((lamports) => unwrapCalls.push(lamports)) as unknown as UnwrapInputs[0], + {} as UnwrapInputs[1], + owner.publicKey, + payer, + async () => null, + async () => 6_000_000_000n, + ); + + expect(unwrapCalls).toEqual([]); + }); + test("skips unwrap when lamports exceed safe integer range", async () => { const unwrapCalls: number[] = []; const balanceFetcher = async () => BigInt(Number.MAX_SAFE_INTEGER) + 100n; From 58c60a6815cbcd19f67c209a4c6028e03ff644f0 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Mon, 30 Nov 2026 04:39:25 -0300 Subject: [PATCH 326/410] fix(positions): rebuild fills when a mint returns after a rebuild without it The cache stored the union of the old and new known mints even after it rebuilt the fills with only the new ones. A mint that came back then looked known, so its buys stayed missing until the cache expired. Fills are now stored with the exact mints they were built with. --- src/services/positions.ts | 33 ++++----- tests/positions.test.ts | 150 +++++++++++++++++++++++++++++++++++++- 2 files changed, 161 insertions(+), 22 deletions(-) diff --git a/src/services/positions.ts b/src/services/positions.ts index 1118c281..4132fe95 100644 --- a/src/services/positions.ts +++ b/src/services/positions.ts @@ -150,10 +150,7 @@ export function rawAmountToNumber(raw: string | undefined, decimals: number): nu } export function quoteAmountToSol(quoteMint: string, quoteAmount: number): number { - if (!Number.isFinite(quoteAmount) || quoteAmount <= 0 || quoteMint !== WSOL_MINT) { - return 0; - } - return quoteAmount; + return quoteMint === WSOL_MINT && Number.isFinite(quoteAmount) ? Math.max(quoteAmount, 0) : 0; } export function fillsFromSwaps( @@ -695,16 +692,19 @@ async function resolvePositionWork( const now = Date.now(); const cacheFresh = Boolean(cached && cached.expiresAt > now); - let fills = cached?.fills; - if ( - !cacheFresh || - !cached || - cached.swapFingerprint !== swapFingerprint || - !fills || - knownMintsGrew(cached.fillKnownMints, fillKnownMints) - ) { - fills = buildFillsForHoldings(swaps, args.knownTokens, holdings); - } + // Reuse fills only when they were built from the same swaps and at least these mints. + const reusable = + cacheFresh && + cached?.swapFingerprint === swapFingerprint && + !knownMintsGrew(cached.fillKnownMints, fillKnownMints) + ? cached + : undefined; + // Fills stay paired with the mints they were built with: a rebuild knows only the current ones. + const fillWork = reusable ?? { + fills: buildFillsForHoldings(swaps, args.knownTokens, holdings), + fillKnownMints, + }; + const { fills } = fillWork; const neededPrices = collectPositionPriceMints(fills, holdings); @@ -724,10 +724,7 @@ async function resolvePositionWork( expiresAt: now + POSITION_SNAPSHOT_TTL_MS, fills, swapFingerprint, - fillKnownMints: - cacheFresh && cached - ? new Set([...cached.fillKnownMints, ...fillKnownMints]) - : fillKnownMints, + fillKnownMints: fillWork.fillKnownMints, pricesUsd, pricedMints, }; diff --git a/tests/positions.test.ts b/tests/positions.test.ts index 9a334fda..c303ca0c 100644 --- a/tests/positions.test.ts +++ b/tests/positions.test.ts @@ -1,5 +1,5 @@ import { expect, spyOn, test } from "bun:test"; -import { WSOL_MINT } from "../src/utils/constants"; +import { WALLET_RPC_CACHE_TTL_MS, WSOL_MINT } from "../src/utils/constants"; import { USDC_MINT, USDT_MINT, @@ -862,9 +862,12 @@ test("quoteAmountToSol only counts native SOL", () => { expect(quoteAmountToSol(WSOL_MINT, 0.42)).toBeCloseTo(0.42, 8); }); -test.each([0, -1, Infinity, NaN])("ignores invalid or empty SOL cost %p", (amount) => { - expect(quoteAmountToSol(WSOL_MINT, amount)).toBe(0); -}); +test.each([0, -0, -1, Number.MIN_VALUE * -1, Infinity, -Infinity, NaN])( + "ignores invalid or empty SOL cost %p", + (amount) => { + expect(quoteAmountToSol(WSOL_MINT, amount)).toBe(0); + }, +); test("format helpers match the wallet PNL style", () => { expect(formatSignedPercent(0.184)).toBe("+18.4%"); @@ -1466,3 +1469,142 @@ test("newly known token metadata rebuilds cached fills", async () => { expect(after.map((position) => position.mint)).toEqual([UNKNOWN_MINT]); clearPositionSnapshot(); }); + +test("rebuilt fills forget a mint that left, so its return rebuilds them again", async () => { + clearPositionSnapshot(); + const newBuy = swap({ + signature: "buy-new", + output_mint: UNKNOWN_MINT, + output_ticker: "NEW", + amount_in: "1000000000", + amount_out: "1000", + }); + const timbaBuy = swap({ signature: "buy-timba", timestamp: 2 }); + let swaps = [newBuy]; + const newHolding = { mint: UNKNOWN_MINT, ticker: "NEW", balance: 10, decimals: 2 }; + const timbaHolding = { mint: TIMBA, ticker: "TIMBA", balance: 123, decimals: 6 }; + let holdings = [newHolding]; + const loader = { + walletAddress: "wallet-known-left", + getSwaps: () => swaps, + getHoldings: async () => holdings, + fetchPricesUSD: async (mints: string[]) => + Object.fromEntries(mints.map((mint) => [mint, mint === WSOL_MINT ? 100 : 1])), + }; + const mints = async () => + (await loadTokenPositionsForWallet(loader)).map((position) => position.mint).sort(); + + try { + expect(await mints()).toEqual([UNKNOWN_MINT]); + // A new swap rebuilds the fills while NEW is not held, so its decimals are unknown. + swaps = [newBuy, timbaBuy]; + holdings = [timbaHolding]; + expect(await mints()).toEqual([TIMBA]); + // NEW comes back with no new swap. The fills must be rebuilt to include it. + holdings = [timbaHolding, newHolding]; + expect(await mints()).toEqual([UNKNOWN_MINT, TIMBA].sort()); + } finally { + clearPositionSnapshot(); + } +}); + +test("reused fills keep the mints they were built with", async () => { + clearPositionSnapshot(); + const first = swap({ signature: "first", timestamp: 1 }); + const last = swap({ signature: "last", timestamp: 3 }); + const middle = (amountOut: string) => + swap({ signature: "middle", timestamp: 2, amount_out: amountOut }); + let swaps = [first, middle("123000000"), last]; + const timba = { mint: TIMBA, ticker: "TIMBA", balance: 1_000, decimals: 6 }; + const other = { mint: UNKNOWN_MINT, ticker: "NEW", balance: 1, decimals: 2 }; + let holdings = [timba, other]; + const clock = spyOn(Date, "now").mockReturnValue(1_800_000_000_000); + const loader = { + walletAddress: "wallet-fill-mints", + getSwaps: () => swaps, + getHoldings: async () => holdings, + fetchPricesUSD: async (mints: string[]) => + Object.fromEntries(mints.map((mint) => [mint, mint === WSOL_MINT ? 100 : 1])), + }; + const tracked = async () => + (await loadTokenPositionsForWallet(loader)).find((position) => position.mint === TIMBA) + ?.trackedBalance; + + try { + expect(await tracked()).toBe(369); + holdings = [timba]; + expect(await tracked()).toBe(369); + // NEW was known when the fills were built, so its return is not new and the fills stay. + swaps = [first, middle("246000000"), last]; + holdings = [timba, other]; + expect(await tracked()).toBe(369); + } finally { + clock.mockRestore(); + clearPositionSnapshot(); + } +}); + +test("cached fills are reused only while fresh and for the same swaps", async () => { + clearPositionSnapshot(); + const first = swap({ signature: "first", timestamp: 1 }); + const last = swap({ signature: "last", timestamp: 3 }); + const middle = (amountOut: string) => + swap({ signature: "middle", timestamp: 2, amount_out: amountOut }); + let swaps = [first, middle("123000000"), last]; + let now = 1_800_000_000_000; + const clock = spyOn(Date, "now").mockImplementation(() => now); + const loader = { + walletAddress: "wallet-fill-reuse", + getSwaps: () => swaps, + getHoldings: async () => [{ mint: TIMBA, ticker: "TIMBA", balance: 1_000, decimals: 6 }], + fetchPricesUSD: async (mints: string[]) => + Object.fromEntries(mints.map((mint) => [mint, mint === WSOL_MINT ? 100 : 1])), + }; + const tracked = async () => (await loadTokenPositionsForWallet(loader))[0]?.trackedBalance; + + try { + expect(await tracked()).toBe(369); + // The same length, first and last swap give the same fingerprint, so fresh fills are kept. + swaps = [first, middle("246000000"), last]; + expect(await tracked()).toBe(369); + // A new swap changes the fingerprint. + swaps = [...swaps, swap({ signature: "fourth", timestamp: 4 })]; + expect(await tracked()).toBe(615); + // An expired cache rebuilds the fills even with the same fingerprint. + swaps = [first, middle("123000000"), last, swap({ signature: "fourth", timestamp: 4 })]; + expect(await tracked()).toBe(615); + now += WALLET_RPC_CACHE_TTL_MS + 1; + expect(await tracked()).toBe(492); + } finally { + clock.mockRestore(); + clearPositionSnapshot(); + } +}); + +test.each([ + ["overflows to infinity", 1e300, 1e10], + ["rounds to zero", 5e-324, 0.5], +])("a USD cost that %s gives no USD entry or profit", (_label, quoteAmount, solPrice) => { + const [position] = buildTokenPositions({ + fills: [ + { + mint: TIMBA, + ticker: "TIMBA", + side: "buy", + tokenAmount: 1, + quoteMint: WSOL_MINT, + quoteAmount, + timestamp: 1, + }, + ], + holdings: [{ mint: TIMBA, ticker: "TIMBA", balance: 1, decimals: 6 }], + pricesUsd: { [WSOL_MINT]: solPrice, [TIMBA]: 2 }, + }); + + expect(position).toMatchObject({ + avgEntrySol: quoteAmount, + avgEntryUsd: null, + pnlPercent: null, + unrealizedUsd: null, + }); +}); From f5ba3f710afda884a5941804487e11ff78484d61 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Mon, 30 Nov 2026 04:42:26 -0300 Subject: [PATCH 327/410] test(lightning): check custom amount reply locks and prompt sessions --- src/handlers/lightning.ts | 1 + tests/lightning-handler.test.ts | 40 +++++++++++++++++++++++++++++++++ 2 files changed, 41 insertions(+) diff --git a/src/handlers/lightning.ts b/src/handlers/lightning.ts index 40131fbe..680b3d83 100644 --- a/src/handlers/lightning.ts +++ b/src/handlers/lightning.ts @@ -156,6 +156,7 @@ export function registerLightningDeposits( (_key, session) => session.type === "deposit_usd" && session.initiatorId === owner, ); const messageId = ctx.callbackQuery?.message?.message_id; + // Stryker disable next-line ConditionalExpression: with no id, detachMessage binds NULL, which matches no row. if (messageId) store?.detachMessage(owner, messageId); } await next(); diff --git a/tests/lightning-handler.test.ts b/tests/lightning-handler.test.ts index a28de472..77832255 100644 --- a/tests/lightning-handler.test.ts +++ b/tests/lightning-handler.test.ts @@ -383,6 +383,46 @@ describe("quote failures", () => { }); }); +describe("custom amount replies", () => { + const promptKey = `${privateChat.id}_10`; + + test("an accepted amount closes its prompt session", async () => { + await withHarness({}, async (h) => { + await h.click("ln_custom"); + expect(getInputSession(promptKey)).toMatchObject({ type: "deposit_usd" }); + await h.send("25"); + expect(h.store?.active(String(owner.id))?.sats).toBe("25000"); + expect(getInputSession(promptKey)).toBeUndefined(); + }); + }); + + test("a reply while another reply is processing is ignored", async () => { + await withHarness({}, async (h) => { + await h.click("ln_custom"); + expect(markInputSessionProcessing(promptKey, "other-reply")).toBe(true); + await h.send("25"); + expect(h.store?.active(String(owner.id))).toBeNull(); + expect(getInputSession(promptKey)).toMatchObject({ processingBy: "other-reply" }); + }); + }); + + test("a rejected amount whose prompt moved keeps the old prompt open and unlocked", async () => { + await withHarness({}, async (h) => { + await h.click("ln_custom"); + h.calls.length = 0; + h.failNext("editMessageText", () => new Error("message to edit not found")); + h.failNext("editMessageCaption", () => new Error("message to edit not found")); + await h.send("5"); + const movedPrompt = h.calls.findLast((call) => call.method === "sendMessage"); + expect(movedPrompt?.payload.text).toContain("Reply with an amount in USD."); + const oldSession = getInputSession(promptKey); + expect(oldSession).toMatchObject({ type: "deposit_usd" }); + expect(oldSession).not.toHaveProperty("processing"); + expect(oldSession).not.toHaveProperty("processingBy"); + }); + }); +}); + describe("deposit cards", () => { const expiration = Date.UTC(2026, 10, 28, 12, 34); const providerOrder: FixedFloatOrder = { From 704b4bd8e98a83f6b5775bd23ba62c437e79c39d Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Mon, 30 Nov 2026 04:45:29 -0300 Subject: [PATCH 328/410] refactor(amount): take token decimals from one trade parameter Every caller passes the same mint decimals as decimals and tokenBalance.decimals, so a trade now reads only decimals. The token balance snapshot holds only the raw balance, and the unused TokenBalanceLike type is gone. --- src/bot.ts | 8 +++---- src/handlers/wallet-transactions.ts | 19 ++++++++--------- src/types/wallet.ts | 4 ---- src/utils/amount.ts | 14 ++++--------- tests/amount.boundary.test.ts | 2 +- tests/amount.trade-evaluation.test.ts | 30 +++++++++++++-------------- 6 files changed, 32 insertions(+), 45 deletions(-) delete mode 100644 src/types/wallet.ts diff --git a/src/bot.ts b/src/bot.ts index e57450f8..223a22d3 100644 --- a/src/bot.ts +++ b/src/bot.ts @@ -186,7 +186,7 @@ import { getContractCapitalLamports } from "./services/contract-capital"; import { TransactionHistory } from "./utils/transaction-history"; import { getConfirmedTransactionFeeLamports } from "./utils/transaction-fee"; import { generateTransactionId } from "./utils/transaction-id"; -import type { TokenBalanceLike } from "./types/wallet"; +import type { TradeTokenBalanceSnapshot } from "./utils/amount"; import { refreshDynamicFeeBudgets } from "./utils/fee-budget-refresh"; import { SlidingWindowRateLimiter } from "./utils/rate-limiter"; import { sweepFees } from "./services/fee-sweeper"; @@ -1055,7 +1055,7 @@ type ResolvedTradeAsset = { ticker: string; mint: string; decimals: number; - tokenBalance?: TokenBalanceLike; + tokenBalance?: TradeTokenBalanceSnapshot; applySolFeeBuffer?: boolean; metadata?: Record; }; @@ -5935,9 +5935,7 @@ const showSwapQuoteAndConfirmation = async ( ticker: fromToken, mint: inputMint, decimals, - tokenBalance: balanceEntry - ? { balance: balanceEntry.balance, decimals: balanceEntry.decimals } - : undefined, + tokenBalance: balanceEntry ? { balance: balanceEntry.balance } : undefined, applySolFeeBuffer: fromToken === "SOL", }; }, diff --git a/src/handlers/wallet-transactions.ts b/src/handlers/wallet-transactions.ts index b9619c0d..83f9ce3b 100644 --- a/src/handlers/wallet-transactions.ts +++ b/src/handlers/wallet-transactions.ts @@ -31,7 +31,11 @@ import { getTelegramId, getTelegramIdString, } from "../utils/context-helpers"; -import { presentTradeAmount, parseDecimalAmount } from "../utils/amount"; +import { + presentTradeAmount, + parseDecimalAmount, + type TradeTokenBalanceSnapshot, +} from "../utils/amount"; import { escapeHtml } from "../utils/format-amount"; import { formatUserFriendlyError } from "../utils/errors"; import { buildTransactionLinkMessage, NetworkDetector } from "../utils/network-detector"; @@ -50,7 +54,6 @@ import type { RegisterCallbackPrefixHandler, WrapCallbackHandler, } from "../utils/callback-registry"; -import type { TokenBalanceLike } from "../types/wallet"; import { generateTransactionId } from "../utils/transaction-id"; type PresentSpendAmountParams = { @@ -58,7 +61,7 @@ type PresentSpendAmountParams = { assetTicker: string; decimals: number; solBalance: number; - tokenBalance?: TokenBalanceLike; + tokenBalance?: TradeTokenBalanceSnapshot; formatSol: (lamports: number) => string; formatToken: (amount: number, decimals: number) => string; applySolFeeBuffer?: boolean; @@ -75,7 +78,7 @@ type SendAmountPromptParams = { rawAmount: string; decimals: number; solBalance: number; - tokenBalance?: TokenBalanceLike; + tokenBalance?: TradeTokenBalanceSnapshot; exampleAddress?: string; formatSol: (lamports: number) => string; formatToken: (amount: number, decimals: number) => string; @@ -458,9 +461,7 @@ export const createWalletTransactionsModule = ( rawAmount: amount, decimals: isSol ? 9 : selectedToken!.decimals, solBalance, - tokenBalance: selectedToken - ? { balance: selectedToken.balance, decimals: selectedToken.decimals } - : undefined, + tokenBalance: selectedToken ? { balance: selectedToken.balance } : undefined, exampleAddress, formatSol: (lamports) => wallet.formatSolBalance(lamports), formatToken: (value, decimals) => wallet.formatTokenBalance(value, decimals), @@ -1064,9 +1065,7 @@ export const createWalletTransactionsModule = ( rawAmount: amountChoice, decimals: isSol ? 9 : selectedToken!.decimals, solBalance, - tokenBalance: selectedToken - ? { balance: selectedToken.balance, decimals: selectedToken.decimals } - : undefined, + tokenBalance: selectedToken ? { balance: selectedToken.balance } : undefined, exampleAddress, formatSol: (lamports) => wallet.formatSolBalance(lamports), formatToken: (value, decimals) => wallet.formatTokenBalance(value, decimals), diff --git a/src/types/wallet.ts b/src/types/wallet.ts deleted file mode 100644 index 78771942..00000000 --- a/src/types/wallet.ts +++ /dev/null @@ -1,4 +0,0 @@ -export type TokenBalanceLike = { - balance: number; - decimals: number; -}; diff --git a/src/utils/amount.ts b/src/utils/amount.ts index 53768709..601402df 100644 --- a/src/utils/amount.ts +++ b/src/utils/amount.ts @@ -78,9 +78,9 @@ export const parseTradeAmountInput = (amount: string): TradeAmountParseResult => return { kind: "absolute", normalized: trimmed }; }; +/** The raw token balance. Its decimals are the trade's own `decimals`, so one value sets both. */ export interface TradeTokenBalanceSnapshot { balance: number; - decimals: number; } export interface EvaluateTradeAmountParams { @@ -158,8 +158,7 @@ export const evaluateTradeAmount = ({ return formatSol ? formatSol(rawAmount) : undefined; } - const { decimals: tokenDecimals } = getTokenSnapshot(); - return formatToken ? formatToken(rawAmount, tokenDecimals) : undefined; + return formatToken ? formatToken(rawAmount, decimals) : undefined; }; if (parsed.kind === "max") { @@ -227,7 +226,7 @@ export const evaluateTradeAmount = ({ throw new Error("Percentage results in zero amount"); } - const formatted = formatAmount(rawAmount, tokenSnapshot.decimals); + const formatted = formatAmount(rawAmount, decimals); const displayOverride = formatDisplayAmount(rawAmount); const displayAmount = displayOverride ?? formatted; @@ -280,14 +279,9 @@ export const presentTradeAmount = ( params: EvaluateTradeAmountParams, ): PresentedTradeAmountResult => { const evaluation = evaluateTradeAmount(params); - const decimals = - params.assetTicker !== "SOL" && params.tokenBalance - ? params.tokenBalance.decimals - : params.decimals; - const displayAmount = evaluation.displayAmount || - (evaluation.kind === "max" ? "max" : formatAmount(evaluation.rawAmount, decimals)); + (evaluation.kind === "max" ? "max" : formatAmount(evaluation.rawAmount, params.decimals)); return { kind: evaluation.kind, diff --git a/tests/amount.boundary.test.ts b/tests/amount.boundary.test.ts index 9b47d18b..2f7781df 100644 --- a/tests/amount.boundary.test.ts +++ b/tests/amount.boundary.test.ts @@ -12,7 +12,7 @@ test("presentSpendAmount rejects inputs exceeding Number.MAX_SAFE_INTEGER", () = assetTicker: "TOK", decimals: 0, solBalance: 0, - tokenBalance: { balance: Number.MAX_SAFE_INTEGER, decimals: 0 }, + tokenBalance: { balance: Number.MAX_SAFE_INTEGER }, formatSol: () => "", formatToken: () => "", applySolFeeBuffer: false, diff --git a/tests/amount.trade-evaluation.test.ts b/tests/amount.trade-evaluation.test.ts index c9af6d6f..18598c66 100644 --- a/tests/amount.trade-evaluation.test.ts +++ b/tests/amount.trade-evaluation.test.ts @@ -1,7 +1,7 @@ import { describe, expect, test } from "bun:test"; import { evaluateTradeAmount, presentTradeAmount } from "../src/utils/amount"; -const token = (balance: number, decimals = 6) => ({ balance, decimals }); +const token = (balance: number) => ({ balance }); describe("evaluateTradeAmount SOL balance boundaries", () => { const sol = { assetTicker: "SOL", decimals: 9, solBalance: 100_000_000 }; @@ -97,7 +97,7 @@ describe("evaluateTradeAmount token edge cases", () => { assetTicker: "TOK", decimals: 2, solBalance: 0, - tokenBalance: token(123, 2), + tokenBalance: token(123), }), ).toEqual({ kind: "absolute", @@ -114,7 +114,7 @@ describe("evaluateTradeAmount token edge cases", () => { assetTicker: "TOK", decimals: 2, solBalance: 0, - tokenBalance: token(123, 2), + tokenBalance: token(123), }), ).toThrow("Insufficient token balance"); }); @@ -131,7 +131,7 @@ describe("evaluateTradeAmount token edge cases", () => { assetTicker: "BONK", decimals: 5, solBalance: 0, - tokenBalance: token(0, 5), + tokenBalance: token(0), }), ).toThrow("No BONK balance found"); }); @@ -143,7 +143,7 @@ describe("evaluateTradeAmount token edge cases", () => { assetTicker: "BONK", decimals: 5, solBalance: 0, - tokenBalance: token(0.5, 5), + tokenBalance: token(0.5), }), ).toThrow("No BONK balance found"); }); @@ -155,7 +155,7 @@ describe("evaluateTradeAmount token edge cases", () => { assetTicker: "BONK", decimals: 0, solBalance: 0, - tokenBalance: token(9, 0), + tokenBalance: token(9), }), ).toThrow("Percentage results in zero amount"); }); @@ -167,7 +167,7 @@ describe("evaluateTradeAmount token edge cases", () => { assetTicker: "BONK", decimals: 2, solBalance: 0, - tokenBalance: token(1_001, 2), + tokenBalance: token(1_001), }), ).toEqual({ kind: "percentage", rawAmount: 500, displayAmount: "5", normalizedAmount: "5" }); }); @@ -181,7 +181,7 @@ describe("presentTradeAmount display fallbacks", () => { assetTicker: "BONK", decimals: 5, solBalance: 0, - tokenBalance: token(123_456, 5), + tokenBalance: token(123_456), }), ).toEqual({ kind: "max", rawAmount: 123_456, normalizedAmount: "max", displayAmount: "max" }); }); @@ -202,25 +202,25 @@ describe("presentTradeAmount display fallbacks", () => { }); }); - test("uses the token's own decimals for the fallback display", () => { + test("formats the fallback display with the trade decimals", () => { expect( presentTradeAmount({ amount: "1.5", assetTicker: "USDC", decimals: 6, solBalance: 0, - tokenBalance: token(5_000_000, 0), + tokenBalance: token(5_000_000), }).displayAmount, - ).toBe("1500000"); + ).toBe("1.5"); expect( presentTradeAmount({ amount: "1.5", assetTicker: "TOK", - decimals: 3, + decimals: 2, solBalance: 0, - tokenBalance: token(5_000, 2), + tokenBalance: token(5_000), }).displayAmount, - ).toBe("15"); + ).toBe("1.5"); }); test("uses the exact amount if a display callback produces an empty string", () => { @@ -251,7 +251,7 @@ describe("presentTradeAmount display fallbacks", () => { assetTicker: "USDC", decimals: 6, solBalance: 0, - tokenBalance: token(5_000_000, 6), + tokenBalance: token(5_000_000), formatToken: (raw, decimals) => `${raw}/${decimals}`, }).displayAmount, ).toBe("2000000/6"); From 3d79f306e6c7eb9186e85c1d3b02b1f581050bb8 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Mon, 30 Nov 2026 04:48:33 -0300 Subject: [PATCH 329/410] test: report test guards that the code under test catches The clock and console guards now record a trip and fail the test at restore or in afterEach. The recovery timer stub fails at once on an unknown long delay. The test deadline ends 1.5 s before Bun's timeout. The parser test again checks a log field that is not an array. --- tests/errors.parser.test.ts | 10 ++++ tests/helpers/timers.ts | 66 +++++++++++++++++++--- tests/helpers/wallet-confirmation-clock.ts | 12 +++- tests/transaction-runner.test.ts | 11 +++- 4 files changed, 88 insertions(+), 11 deletions(-) diff --git a/tests/errors.parser.test.ts b/tests/errors.parser.test.ts index 7b631456..d28cf6d5 100644 --- a/tests/errors.parser.test.ts +++ b/tests/errors.parser.test.ts @@ -58,6 +58,16 @@ describe("collectErrorLogs", () => { expect(await collectErrorLogs(error)).toEqual(["a", "b", "c", "d"]); }); + test("skips a log field that is not an array", async () => { + const error = { + logs: ["a", 1, "b"], + logMessages: ["c"], + transactionLogs: "not an array", + }; + + expect(await collectErrorLogs(error)).toEqual(["a", "b", "c"]); + }); + test("walks data, error and cause chains without looping on cycles", async () => { let rootReads = 0; const shared = { logs: ["cause"] }; diff --git a/tests/helpers/timers.ts b/tests/helpers/timers.ts index b6e4e8bf..05f573cc 100644 --- a/tests/helpers/timers.ts +++ b/tests/helpers/timers.ts @@ -3,12 +3,17 @@ import { afterEach, beforeEach, spyOn } from "bun:test"; const scheduleDeadline = globalThis.setTimeout; const cancelDeadline = globalThis.clearTimeout; -/** Use the normal test deadline even when a mutation removes a simulated timer. */ +/** Bun's default per-test timeout. */ +const BUN_TEST_TIMEOUT_MS = 5_000; +/** End first, so the "did not settle" message shows instead of Bun's generic timeout. */ +const TEST_DEADLINE_MS = BUN_TEST_TIMEOUT_MS - 1_500; + +/** Fail with a named action even when a mutation removes a simulated timer. */ export async function withinTestDeadline(result: Promise, action: string): Promise { const timeout = Promise.withResolvers(); const timer = scheduleDeadline( - () => timeout.reject(new Error(`${action} did not settle`)), - 5_000, + () => timeout.reject(new Error(`${action} did not settle within ${TEST_DEADLINE_MS} ms`)), + TEST_DEADLINE_MS, ); try { return await Promise.race([result, timeout.promise]); @@ -40,21 +45,64 @@ export const stubInstantTimers = (shouldStub?: (delayMs: number) => boolean) => }; }; -/** Keep recovery fixtures bounded even when they use the production backoff. */ +/** The production recovery backoff. These delays run at once. */ +const RECOVERY_DELAYS_MS = new Set([2_000, 4_000, 8_000, 12_000, 16_000, 20_000]); +/** Timers that the code under test starts but that a test never waits for. */ +const BACKGROUND_DELAYS_MS = new Set([ + 3_000, // creation rebroadcast interval, cleared when the creation settles + 30_000, // expiring cache entry + 60_000, // expiring cache entry +]); +/** A shorter delay is a test's own small wait, so it uses the real clock. */ +const LONG_DELAY_MS = 1_000; + +/** + * Keep recovery fixtures bounded even when they use the production backoff. + * Any other long delay throws at once and fails the test in afterEach, because a + * real wait would only end at Bun's test timeout, with no hint of the cause. + */ export function useInstantRecoveryBackoff() { - const recoveryDelays = new Set([2_000, 4_000, 8_000, 12_000, 16_000, 20_000]); let timers: ReturnType; + let unexpected: number[] = []; beforeEach(() => { - timers = stubInstantTimers((delayMs) => recoveryDelays.has(delayMs)); + unexpected = []; + timers = stubInstantTimers((delayMs) => { + if (RECOVERY_DELAYS_MS.has(delayMs)) return true; + if (delayMs >= LONG_DELAY_MS && !BACKGROUND_DELAYS_MS.has(delayMs)) { + unexpected.push(delayMs); + throw new Error(`Unexpected ${delayMs} ms timer in a recovery test`); + } + return false; + }); + }); + afterEach(() => { + timers.restore(); + if (unexpected.length > 0) { + throw new Error( + `Unexpected timer delays ${unexpected.join(", ")} ms: add them to the recovery or background delays in tests/helpers/timers.ts`, + ); + } }); - afterEach(() => timers.restore()); } export function mockDateNowWithReadLimit(readNow: () => number, maxReads = 1_000) { let reads = 0; - return spyOn(Date, "now").mockImplementation(() => { + let tripped = false; + const spy = spyOn(Date, "now").mockImplementation(() => { reads += 1; - if (reads > maxReads) throw new Error("Polling exceeded the fake clock read limit"); + if (reads > maxReads) { + // The code under test may catch this error, so mockRestore() reports it too. + tripped = true; + throw new Error("Polling exceeded the fake clock read limit"); + } return readNow(); }); + return { + mockRestore: () => { + spy.mockRestore(); + if (tripped) { + throw new Error(`The fake clock passed ${maxReads} Date.now reads: polling did not stop`); + } + }, + }; } diff --git a/tests/helpers/wallet-confirmation-clock.ts b/tests/helpers/wallet-confirmation-clock.ts index f28ebcb1..cb0fb737 100644 --- a/tests/helpers/wallet-confirmation-clock.ts +++ b/tests/helpers/wallet-confirmation-clock.ts @@ -6,10 +6,15 @@ export function useWalletConfirmationClock(wallet: WalletManager) { const start = 1_700_000_000_000; let now = start; let reads = 0; + let tripped = false; const delays: number[] = []; const nowSpy = spyOn(Date, "now").mockImplementation(() => { reads += 1; - if (reads > 500) throw new Error("Confirmation polling did not finish within the clock budget"); + if (reads > 500) { + // The code under test may catch this error and retry, so restore() reports it too. + tripped = true; + throw new Error("Confirmation polling did not finish within the clock budget"); + } return now; }); const originalSleep = Object.getOwnPropertyDescriptor(wallet, "sleep"); @@ -28,6 +33,11 @@ export function useWalletConfirmationClock(wallet: WalletManager) { nowSpy.mockRestore(); if (originalSleep) Object.defineProperty(wallet, "sleep", originalSleep); else Reflect.deleteProperty(wallet, "sleep"); + if (tripped) { + throw new Error( + "The wallet confirmation clock passed 500 Date.now reads: confirmation polling did not stop", + ); + } }, }; } diff --git a/tests/transaction-runner.test.ts b/tests/transaction-runner.test.ts index 9e343cde..9ec9d43f 100644 --- a/tests/transaction-runner.test.ts +++ b/tests/transaction-runner.test.ts @@ -47,18 +47,27 @@ const timeout = () => new Error("Transaction confirmation timeout"); let warnSpy: ReturnType; let errorSpy: Mock; +let errorLimitTripped = false; beforeEach(() => { warnSpy = spyOn(console, "warn").mockImplementation(() => {}); let errors = 0; + errorLimitTripped = false; errorSpy = spyOn(console, "error").mockImplementation(() => { // A mutant can decrement the resubmission index in a loop of caught errors. // Stop it synchronously so it cannot starve the runner's timeout timer. - if (++errors > 6) throw new Error("Unexpected seventh recovery error"); + if (++errors > 6) { + // The runner may catch this error as a network error, so afterEach reports it too. + errorLimitTripped = true; + throw new Error("Unexpected seventh recovery error"); + } }); }); afterEach(() => { warnSpy.mockRestore(); errorSpy.mockRestore(); + if (errorLimitTripped) { + throw new Error("console.error ran more than 6 times: the recovery loop did not stop"); + } }); describe("getConfirmationRetryDelays", () => { From c84c07ceac2a2dd290e3b4845c514d0a2debc97b Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Mon, 30 Nov 2026 04:54:18 -0300 Subject: [PATCH 330/410] refactor(game): read optional database and wallet methods without any casts --- src/utils/game.ts | 62 +++++++++++++++++++++----------------- tests/game.hydrate.test.ts | 32 ++++++++++++++++++++ 2 files changed, 66 insertions(+), 28 deletions(-) diff --git a/src/utils/game.ts b/src/utils/game.ts index 91dd0602..593064bc 100644 --- a/src/utils/game.ts +++ b/src/utils/game.ts @@ -603,6 +603,16 @@ export class GameManager { private feeBudget: FeeBudgetProvider, ) {} + /** Test doubles can leave out database methods, so optional calls look them up first. */ + private get optionalGameDb(): Partial { + return this.gameDb; + } + + /** Test doubles can leave out wallet methods, so optional calls look them up first. */ + private get optionalWallet(): Partial { + return this.wallet; + } + private getInFlightCreations(telegramId: string): number { return this.inFlightGameCreations.get(telegramId) ?? 0; } @@ -854,13 +864,13 @@ export class GameManager { return; } - const recordGameCompletionFinance = (this.gameDb as any).recordGameCompletionFinance; + const recordGameCompletionFinance = this.optionalGameDb.recordGameCompletionFinance; if (typeof recordGameCompletionFinance !== "function") { return; } try { - const currentGame = (this.gameDb as any).getGame?.(gameAddress); + const currentGame = this.optionalGameDb.getGame?.(gameAddress); if ( currentGame?.completion_signature && currentGame.completion_signature !== winnerSignature @@ -990,7 +1000,7 @@ export class GameManager { const timer = setTimeout(async () => { this.unavailableStateRecoveryTimers.delete(recoveryKey); - const getGame = (this.gameDb as any).getGame; + const getGame = this.optionalGameDb.getGame; if (typeof getGame !== "function") { return; } @@ -2779,7 +2789,7 @@ export class GameManager { // Calculate totalPot based on game type let totalPot = providedTotalPot ?? null; if (totalPot === null) { - const chainTotal = coerceLamportValue((gameAccount as any).totalAmount); + const chainTotal = coerceLamportValue(gameAccount.totalAmount); if (chainTotal !== null && chainTotal > 0n) { totalPot = chainTotal; } else { @@ -2796,8 +2806,8 @@ export class GameManager { const expiresAt = createdAt + timeout; const expirationInfo = await formatExpirationTime(expiresAt, this.wallet, "\n⏰ "); const tokenMint = ((gameAccount as any)?.tokenMint as PublicKey | undefined)?.toBase58(); - const participantAddresses = Array.isArray((gameAccount as any).participants) - ? (gameAccount as any).participants.flatMap((participant: unknown) => { + const participantAddresses = Array.isArray(gameAccount.participants) + ? gameAccount.participants.flatMap((participant: unknown) => { try { return [new PublicKey(participant as any).toBase58()]; } catch { @@ -5094,23 +5104,19 @@ export class GameManager { createdAtSeconds > 0 && Number.isFinite(timeoutSeconds) && timeoutSeconds > 0; - const authoritativeCreatedAtMs = hasAuthoritativeTiming - ? createdAtSeconds * 1_000 - : undefined; - const authoritativeExpiresAtMs = hasAuthoritativeTiming - ? (createdAtSeconds + timeoutSeconds) * 1_000 + const authoritativeTiming = hasAuthoritativeTiming + ? { + createdAtMs: createdAtSeconds * 1_000, + expiresAtMs: (createdAtSeconds + timeoutSeconds) * 1_000, + } : undefined; - const setPendingChainTiming = (this.gameDb as any).setPendingGameCreationChainTiming; - if ( - hasAuthoritativeTiming && - typeof setPendingChainTiming === "function" && - pendingCreation - ) { + const setPendingChainTiming = this.optionalGameDb.setPendingGameCreationChainTiming; + if (authoritativeTiming && typeof setPendingChainTiming === "function" && pendingCreation) { setPendingChainTiming.call( this.gameDb, pendingCreation.gameAddress, - authoritativeCreatedAtMs, - authoritativeExpiresAtMs, + authoritativeTiming.createdAtMs, + authoritativeTiming.expiresAtMs, Date.now(), ); } @@ -5127,8 +5133,8 @@ export class GameManager { minTickets, chatId, timeout, - authoritativeExpiresAtMs, - authoritativeCreatedAtMs, + authoritativeTiming?.expiresAtMs, + authoritativeTiming?.createdAtMs, ); // Auto-join logic based on game type @@ -7078,7 +7084,7 @@ export class GameManager { options: { allowExpired?: boolean } = {}, ): Promise { const allowExpired = options.allowExpired === true; - const getGame = (this.gameDb as any).getGame; + const getGame = this.optionalGameDb.getGame; if (!allowExpired && typeof getGame === "function") { const existing = getGame.call(this.gameDb, gameAddress); if (existing) return existing; @@ -7105,7 +7111,7 @@ export class GameManager { if (!tokenMint) return null; let tokenTicker = DEFAULT_TOKEN_TICKER; - const getTokenMetadata = (this.wallet as any).getTokenMetadata; + const getTokenMetadata = this.optionalWallet.getTokenMetadata; if (typeof getTokenMetadata === "function") { try { const metadata = await getTokenMetadata.call(this.wallet, tokenMint); @@ -7119,7 +7125,7 @@ export class GameManager { typeof gameAccount.creator?.toBase58 === "function" ? gameAccount.creator.toBase58() : String(gameAccount.creator ?? ""); - const getPlayerTelegramId = (this.gameDb as any).getPlayerTelegramId; + const getPlayerTelegramId = this.optionalGameDb.getPlayerTelegramId; const creatorTelegramId = (creatorPubkey && typeof getPlayerTelegramId === "function" ? getPlayerTelegramId.call(this.gameDb, creatorPubkey) @@ -7127,7 +7133,7 @@ export class GameManager { if (creatorPubkey && creatorTelegramId) { try { - const savePlayerMapping = (this.gameDb as any).savePlayerMapping; + const savePlayerMapping = this.optionalGameDb.savePlayerMapping; if (typeof savePlayerMapping === "function") { savePlayerMapping.call(this.gameDb, creatorPubkey, creatorTelegramId); } @@ -7158,7 +7164,7 @@ export class GameManager { }; try { - const saveGame = (this.gameDb as any).saveGame; + const saveGame = this.optionalGameDb.saveGame; if (typeof saveGame === "function") { saveGame.call( this.gameDb, @@ -7177,8 +7183,8 @@ export class GameManager { ); } - if (hasTiming) { - const setGameChainTiming = (this.gameDb as any).setGameChainTiming; + if (expiresAtMs !== undefined) { + const setGameChainTiming = this.optionalGameDb.setGameChainTiming; if (typeof setGameChainTiming === "function") { setGameChainTiming.call(this.gameDb, gameAddress, createdAtMs, expiresAtMs); } diff --git a/tests/game.hydrate.test.ts b/tests/game.hydrate.test.ts index aa947d29..5501353a 100644 --- a/tests/game.hydrate.test.ts +++ b/tests/game.hydrate.test.ts @@ -183,6 +183,38 @@ describe("hydrateGameDataFromChain fallbacks", () => { }); expect(await gm.ensureGameDataFromChain(GAME)).toBeNull(); }); + + test("stores the chain timing when the account has a start time and a timeout", async () => { + const timings: unknown[][] = []; + const { gm, now } = makeManager({ + db: { + saveGame: () => {}, + setGameChainTiming: (...args: unknown[]) => timings.push(args), + }, + }); + + await gm.ensureGameDataFromChain(GAME); + + expect(timings).toEqual([[GAME, now * 1000, (now + 3600) * 1000]]); + }); + + test.each([ + ["no start time", { createdAt: 0, timeout: 3600 }], + ["no timeout", { createdAt: 1_700_000_000, timeout: 0 }], + ])("does not store chain timing for an account with %s", async (_label, timing) => { + const timings: unknown[][] = []; + const { gm } = makeManager({ + account: { tokenMint: MINT, creator: CREATOR, ticketAmount: 250, ...timing }, + db: { + saveGame: () => {}, + setGameChainTiming: (...args: unknown[]) => timings.push(args), + }, + }); + + await gm.ensureGameDataFromChain(GAME); + + expect(timings).toEqual([]); + }); }); describe("getPendingGameCreationMessages", () => { From 09c94b07c618f0f8e366d8be67d20f929350c8f3 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Mon, 30 Nov 2026 04:55:59 -0300 Subject: [PATCH 331/410] refactor(jupiter): take the fallback token without a non-null assertion --- src/utils/jupiter.ts | 7 ++++--- tests/jupiter.client-errors.test.ts | 2 ++ 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/src/utils/jupiter.ts b/src/utils/jupiter.ts index 77a607e2..28ad775e 100644 --- a/src/utils/jupiter.ts +++ b/src/utils/jupiter.ts @@ -916,11 +916,12 @@ export async function fetchJupiterTokenMetadata( } const parsed = z.array(jupiterTokenMetadataSchema).safeParse(await response.json()); - if (!parsed.success || parsed.data.length === 0) { + const entries = parsed.data ?? []; + const [firstEntry] = entries; + if (!firstEntry) { return null; } - const entries = parsed.data; const exactId = entries.find((item) => item.id.trim() === trimmedQuery); // Mint addresses are case-sensitive. Text search can still use fuzzy results. if (!exactId && isCanonicalMintQuery(trimmedQuery)) return null; @@ -929,7 +930,7 @@ export async function fetchJupiterTokenMetadata( exactId ?? entries.find((item) => item.id.trim().toLowerCase() === normalizedQuery) ?? entries.find((item) => item.symbol.trim().toLowerCase() === normalizedQuery) ?? - entries[0]!; + firstEntry; return { id: candidate.id, diff --git a/tests/jupiter.client-errors.test.ts b/tests/jupiter.client-errors.test.ts index b0c2fdc7..f5cf5835 100644 --- a/tests/jupiter.client-errors.test.ts +++ b/tests/jupiter.client-errors.test.ts @@ -339,5 +339,7 @@ describe("fetchJupiterTokenMetadata", () => { expect( await fetchJupiterTokenMetadata("SOL", async () => Response.json([{ id: mint }])), ).toBeNull(); + // These answers are expected, so they return null without the error log. + expect(errorSpy).not.toHaveBeenCalled(); }); }); From 2cf01394dbde6ee25008e831ea60ce39e7b7e0fe Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Mon, 30 Nov 2026 05:10:56 -0300 Subject: [PATCH 332/410] test: build fakes with typed members instead of any casts --- scripts/stryker-ignorers.test.ts | 29 ++++-- src/evm/bot.test.ts | 16 ++-- src/evm/service.test.ts | 22 +++-- tests/buy-alerts.pool-trades.test.ts | 7 +- tests/fee-sweeper.paths.test.ts | 17 ++-- tests/game-manager.active-list.test.ts | 21 ++-- tests/game-manager.creation-request.test.ts | 3 +- ...game-manager.expired-cleanup-paths.test.ts | 41 +++++--- tests/game-manager.join-attempts.test.ts | 63 ++++++++---- tests/game-manager.join-lifecycle.test.ts | 2 +- ...game-manager.join-private-attempts.test.ts | 42 +++++--- tests/game-manager.player-keys.test.ts | 34 ++++--- tests/game-manager.public-page.test.ts | 5 +- tests/game-manager.stats-boundaries.test.ts | 38 ++++---- tests/game-manager.unjoin-errors.test.ts | 20 ++-- ...me-manager.update-message-recovery.test.ts | 13 ++- tests/game-manager.update-message.test.ts | 32 +++---- tests/game-manager.username-lookup.test.ts | 23 +++-- tests/game.completion-state.test.ts | 96 +++++++++++-------- tests/helpers/fakes.ts | 43 +++++++++ tests/lightning-handler.test.ts | 2 +- tests/media.retry.test.ts | 4 +- tests/program-event-parser.test.ts | 11 ++- tests/swap-manager.token-account-wait.test.ts | 12 ++- tests/swap-service.edge-cases.test.ts | 33 ++++--- tests/wallet-handler.edge.test.ts | 11 ++- tests/wallet-ui.handler.test.ts | 10 +- tests/wallet.transactions.test.ts | 16 ++-- 28 files changed, 417 insertions(+), 249 deletions(-) create mode 100644 tests/helpers/fakes.ts diff --git a/scripts/stryker-ignorers.test.ts b/scripts/stryker-ignorers.test.ts index 78be5d66..4e9b7f47 100644 --- a/scripts/stryker-ignorers.test.ts +++ b/scripts/stryker-ignorers.test.ts @@ -1,8 +1,13 @@ import { describe, expect, test } from "bun:test"; import { readFileSync } from "node:fs"; import { join } from "node:path"; +import type { Ignorer } from "@stryker-mutator/api/ignore"; +import { fake, type FakeMembers } from "../tests/helpers/fakes"; import { consoleTextIgnorer, debugTraceIgnorer, strykerPlugins } from "./stryker-ignorers.mjs"; +// The Babel NodePath that an ignorer gets. The tests build only the fields the ignorer reads. +type IgnorerPath = Parameters[0]; + // The smallest Babel NodePath shapes the ignorer reads. const identifier = (name: string) => ({ type: "Identifier", name }); const call = (callee: unknown) => ({ node: { type: "CallExpression", callee, arguments: [] } }); @@ -21,7 +26,7 @@ const paths = { "notifyPlayer(`joined`)": call(identifier("notifyPlayer")), debugLog: { node: identifier("debugLog") }, }; -const callPath = (source: keyof typeof paths) => paths[source]; +const callPath = (source: keyof typeof paths) => fake(paths[source]); // Small Babel node builders. A node marked with `target` is the one the ignorer sees. type Node = { type: string; target?: boolean; [key: string]: unknown }; @@ -57,7 +62,11 @@ const consoleCall = (method: string, args: Node[]) => callOf(member(id("console" // Builds the NodePath of the target node, with parentPath and listKey like Babel. function pathOf(root: Node) { - const visit = (node: Node, parentPath: unknown, listKey?: string): unknown => { + const visit = ( + node: Node, + parentPath: unknown, + listKey?: string, + ): FakeMembers | undefined => { const path = { node, parentPath, listKey }; if (node.target) return path; for (const [key, value] of Object.entries(node)) { @@ -73,12 +82,12 @@ function pathOf(root: Node) { }; const found = visit(root, undefined); if (!found) throw new Error("no target node"); - return found as any; + return fake(found); } describe("Stryker debug trace ignorer", () => { test("ignores a call to the debug trace helper with a reason", () => { - const reason = debugTraceIgnorer.shouldIgnore(callPath("debugLog(`joined ${name}`, 1)") as any); + const reason = debugTraceIgnorer.shouldIgnore(callPath("debugLog(`joined ${name}`, 1)")); expect(reason).toContain("TIMBA_DEBUG=true"); }); @@ -88,12 +97,12 @@ describe("Stryker debug trace ignorer", () => { ["another function", "notifyPlayer(`joined`)"], ["a reference that is not a call", "debugLog"], ] as const)("keeps mutants in %s", (_label, source) => { - expect(debugTraceIgnorer.shouldIgnore(callPath(source) as any)).toBeUndefined(); + expect(debugTraceIgnorer.shouldIgnore(callPath(source))).toBeUndefined(); }); // The whole call is ignored only when every argument is text, so no argument can // change state. - const debugCall = (args: Node[]) => ({ node: callOf(id("debugLog"), args) }); + const debugCall = (args: Node[]) => fake({ node: callOf(id("debugLog"), args) }); test.each([ ["no arguments", []], ["a string and a number", [str("joined"), { type: "NumericLiteral", value: 1 }]], @@ -101,7 +110,7 @@ describe("Stryker debug trace ignorer", () => { ["a joined string", [plus(plus(str("a"), id("x")), callOf(member(id("pda"), "toBase58")))]], ["a plain value", [member({ type: "ThisExpression" }, "name")]], ])("ignores a debug trace with %s", (_name, args) => { - expect(debugTraceIgnorer.shouldIgnore(debugCall(args as Node[]) as any)).toBe( + expect(debugTraceIgnorer.shouldIgnore(debugCall(args as Node[]))).toBe( "Debug trace text. It prints only with TIMBA_DEBUG=true, and every argument is text or a plain value.", ); }); @@ -117,7 +126,7 @@ describe("Stryker debug trace ignorer", () => { [{ type: "ConditionalExpression", test: id("a"), consequent: str("b"), alternate: str("c") }], ], ])("keeps mutants in a debug trace with %s", (_name, args) => { - expect(debugTraceIgnorer.shouldIgnore(debugCall(args as Node[]) as any)).toBeUndefined(); + expect(debugTraceIgnorer.shouldIgnore(debugCall(args as Node[]))).toBeUndefined(); }); test("a change to the ignorers runs the mutation job and the setup trial", () => { @@ -133,10 +142,10 @@ describe("Stryker debug trace ignorer", () => { }); test("registers the ignorer under the name used in the Stryker config", async () => { - const config = (await import("../stryker.conf.mjs")).default as any; + const config = (await import("../stryker.conf.mjs")).default; expect(config.ignorers).toEqual(["debug-trace", "console-text"]); expect(config.appendPlugins).toContain("./scripts/stryker-ignorers.mjs"); - expect(strykerPlugins.map((plugin: any) => [plugin.kind, plugin.name, plugin.value])).toEqual([ + expect(strykerPlugins.map((plugin) => [plugin.kind, plugin.name, plugin.value])).toEqual([ ["Ignore", "debug-trace", debugTraceIgnorer], ["Ignore", "console-text", consoleTextIgnorer], ]); diff --git a/src/evm/bot.test.ts b/src/evm/bot.test.ts index 4fd3db9a..7dd87357 100644 --- a/src/evm/bot.test.ts +++ b/src/evm/bot.test.ts @@ -6,6 +6,7 @@ import { join } from "node:path"; import type { Address, Hex } from "viem"; import { registerEvmBot, gameCallback } from "./bot"; import type { EvmAction } from "./store"; +import { itemAt } from "../../tests/helpers/fakes"; const address = `0x${"11".repeat(20)}` as Address; const tokenAddress = `0x${"22".repeat(20)}` as Address; @@ -336,7 +337,7 @@ describe("EVM token choice between networks", () => { const { keyboard } = await askChoice(); await h.click(keyboard[1].callback_data); expect(h.store.pending()).toHaveLength(1); - expect(JSON.parse(h.store.pending()[0]!.body).token).toBe(usdcAddress); + expect(JSON.parse(itemAt(h.store.pending(), 0).body).token).toBe(usdcAddress); await h.click(keyboard[0].callback_data); expect(h.solanaDispatched).toEqual([]); @@ -688,7 +689,10 @@ describe("EVM game commands", () => { from: { id: 5150, is_bot: false, first_name: "Ana" }, }, }); - expect(JSON.parse(h.store.pending()[0]!.body)).toMatchObject({ gameType: 1, maxPlayers: 5 }); + expect(JSON.parse(itemAt(h.store.pending(), 0).body)).toMatchObject({ + gameType: 1, + maxPlayers: 5, + }); }); test("a wallet with a pending transaction cannot start another game", async () => { @@ -747,7 +751,7 @@ describe("EVM game commands", () => { h.balances.set(account, 1n); await h.click(create); expect(h.store.pending()).toHaveLength(1); - expect(JSON.parse(h.store.pending()[0]!.body)).toMatchObject({ + expect(JSON.parse(itemAt(h.store.pending(), 0).body)).toMatchObject({ token: tokenAddress, amount: "1", maxPlayers: 2, @@ -828,7 +832,7 @@ describe("EVM game commands", () => { useEvm(); h.store.setToken("1", usdcAddress); await h.text("/ga 2 5 public"); - const body = JSON.parse(h.store.pending()[0]!.body); + const body = JSON.parse(itemAt(h.store.pending(), 0).body); expect(body).toMatchObject({ token: usdcAddress, amount: "2000000", @@ -907,7 +911,7 @@ describe("EVM game buttons", () => { h.store.invite(gameId, "1", JSON.stringify({ deadline: "1300", signature: "0x12" })); await h.click(gameCallback("j", gameId)); - expect(JSON.parse(h.store.pending()[0]!.body).invitation).toEqual({ + expect(JSON.parse(itemAt(h.store.pending(), 0).body).invitation).toEqual({ deadline: "1300", signature: "0x12", }); @@ -948,7 +952,7 @@ describe("EVM game buttons", () => { expect(h.answers()).toEqual([undefined]); expect(h.store.pending()).toHaveLength(1); expect(h.store.pending()[0]).toMatchObject({ kind: "refund", chat: -100, message: 91 }); - expect(JSON.parse(h.store.pending()[0]!.body)).toMatchObject({ game: gameId }); + expect(JSON.parse(itemAt(h.store.pending(), 0).body)).toMatchObject({ game: gameId }); game.mockRestore(); }); diff --git a/src/evm/service.test.ts b/src/evm/service.test.ts index 914f0b98..70d71865 100644 --- a/src/evm/service.test.ts +++ b/src/evm/service.test.ts @@ -13,6 +13,7 @@ import { creationTypedData, gameIdFor, timbaAbi } from "@timbagame/protocol/evm/ import { EvmBotService } from "./service"; import { EvmBotStore, json, type EvmAction } from "./store"; import { evmBotConfigSchema } from "./config"; +import { itemAt } from "../../tests/helpers/fakes"; const mnemonic = "test test test test test test test test test test test junk"; const operator = mnemonicToAccount(mnemonic, { path: "m/44'/60'/0'/0/7" }); @@ -71,10 +72,15 @@ const addAction = (overrides: Partial = {}) => { const stored = (id: string) => store.action(id)!; const lastSentCall = () => { - const raw = sent.at(-1)!; + const raw = itemAt(sent, -1); const tx = parseTransaction(raw); return { raw, tx }; }; +const lastSentData = () => { + const { data } = lastSentCall().tx; + if (!data) throw new Error("The last sent transaction has no call data"); + return data; +}; beforeEach(() => { store = new EvmBotStore(":memory:", "test"); @@ -171,7 +177,7 @@ describe("EvmBotService oracle and metadata", () => { ["POST", "Bearer api-token"], ]); expect(oracleCalls[1]!.body).toEqual({ value: "1" }); - expect(oracleCalls[0]!.body).toBeUndefined(); + expect(itemAt(oracleCalls, 0).body).toBeUndefined(); oracleHandler = () => ({ status: 500, body: {} }); await expect(service.oracle("/evm/config")).rejects.toThrow("EVM oracle request failed"); @@ -358,7 +364,7 @@ describe("EvmBotService.step for new actions", () => { reads.allowance = () => 10n; await service.step(row); - const decoded = decodeFunctionData({ abi: timbaAbi, data: lastSentCall().tx.data! }); + const decoded = decodeFunctionData({ abi: timbaAbi, data: lastSentData() }); expect(decoded.functionName).toBe("createGame"); expect(decoded.args?.[2]).toBe(false); expect(oracleCalls).toHaveLength(1); @@ -460,7 +466,7 @@ describe("EvmBotService.step for new actions", () => { const row = stored(joined.id); expect(row.phase).toBe("transaction"); expect(JSON.parse(row.body).token).toBe(token); - const decoded = decodeFunctionData({ abi: timbaAbi, data: lastSentCall().tx.data! }); + const decoded = decodeFunctionData({ abi: timbaAbi, data: lastSentData() }); expect(decoded.functionName).toBe("joinGame"); expect(decoded.args).toEqual([gameId, 1300n, "0xabcd"]); }); @@ -473,7 +479,7 @@ describe("EvmBotService.step for new actions", () => { const row = stored(joined.id); expect(row.phase).toBe("approval"); expect(JSON.parse(row.body).approvalAmount).toBe("0"); - expect(decodeFunctionData({ abi: erc20Abi, data: lastSentCall().tx.data! }).args).toEqual([ + expect(decodeFunctionData({ abi: erc20Abi, data: lastSentData() }).args).toEqual([ config.address, 0n, ]); @@ -489,7 +495,7 @@ describe("EvmBotService.step for new actions", () => { test("refund and close build the matching game transactions", async () => { const refund = addAction({ kind: "refund", body: json({ game: gameId }) }); await service.step(refund); - expect(decodeFunctionData({ abi: timbaAbi, data: lastSentCall().tx.data! }).functionName).toBe( + expect(decodeFunctionData({ abi: timbaAbi, data: lastSentData() }).functionName).toBe( "refundPlayer", ); @@ -501,7 +507,7 @@ describe("EvmBotService.step for new actions", () => { body: json({ game: gameId }), }); await service.step(closeWithPlayer); - const decoded = decodeFunctionData({ abi: timbaAbi, data: lastSentCall().tx.data! }); + const decoded = decodeFunctionData({ abi: timbaAbi, data: lastSentData() }); expect(decoded.functionName).toBe("refundPlayer"); expect(decoded.args?.[1]).toBe(player); expect(JSON.parse(stored(closeWithPlayer.id).body).refundingPlayer).toBe(true); @@ -509,7 +515,7 @@ describe("EvmBotService.step for new actions", () => { reads.getGame = () => ({ status: 0, gameType: 1, participants: [player] }); const close = addAction({ user: "103", kind: "close", body: json({ game: gameId }) }); await service.step(close); - expect(decodeFunctionData({ abi: timbaAbi, data: lastSentCall().tx.data! }).functionName).toBe( + expect(decodeFunctionData({ abi: timbaAbi, data: lastSentData() }).functionName).toBe( "closeGame", ); }); diff --git a/tests/buy-alerts.pool-trades.test.ts b/tests/buy-alerts.pool-trades.test.ts index 056ecba2..c29735c8 100644 --- a/tests/buy-alerts.pool-trades.test.ts +++ b/tests/buy-alerts.pool-trades.test.ts @@ -8,6 +8,7 @@ import { } from "../src/services/buy-alerts/pool-trades"; import { WSOL_MINT } from "../src/utils/constants"; import type { BuyEvent } from "../src/services/buy-alerts/types"; +import { itemAt } from "./helpers/fakes"; const mint = "F3A1baCgv4TF79TSjdMTvpMDtNv8DJvHZwNc9DG8pump"; @@ -657,9 +658,9 @@ describe("pool trade poller defaults", () => { expect(calls[0]!.url).toBe( "https://api.geckoterminal.com/api/v2/networks/solana/pools/pair%2Fwith%20space/trades", ); - expect(calls[0]!.init.headers).toEqual({ accept: "application/json" }); - expect(calls[0]!.init.signal).toBe(deadline.signal); - expect(calls[0]!.init.method).toBe("GET"); + expect(itemAt(calls, 0).init.headers).toEqual({ accept: "application/json" }); + expect(itemAt(calls, 0).init.signal).toBe(deadline.signal); + expect(itemAt(calls, 0).init.method).toBe("GET"); expect(timeout).toHaveBeenCalledWith(5000); // The first snapshot only primes the pool. expect(received).toEqual([]); diff --git a/tests/fee-sweeper.paths.test.ts b/tests/fee-sweeper.paths.test.ts index fe8289f9..ebda3764 100644 --- a/tests/fee-sweeper.paths.test.ts +++ b/tests/fee-sweeper.paths.test.ts @@ -1,5 +1,5 @@ import { afterEach, beforeEach, describe, expect, mock, spyOn, test } from "bun:test"; -import { Keypair, PublicKey } from "#solana"; +import { Keypair, PublicKey, type Connection } from "#solana"; import { TOKEN_2022_PROGRAM_ID, TOKEN_PROGRAM_ID } from "#token"; import { TokenPolicySchema } from "@timbagame/protocol/oracle"; import { @@ -18,6 +18,8 @@ import { contractCapabilities } from "../src/utils/contract-idl"; import { OracleClient } from "../src/utils/oracle"; import { getSupportedTokens } from "../src/utils/token-registry"; import { TransactionHistory, type FinanceEventRecord } from "../src/utils/transaction-history"; +import { fake } from "./helpers/fakes"; +import type { WalletManager } from "../src/utils/wallet"; const price = (value: number, extra: Record = {}) => (async () => ({ price: value, identifier: "x", resolvedAt: Date.now(), ...extra })) as any; @@ -166,12 +168,12 @@ describe("SOL price validation before swaps", () => { const admin = await Keypair.generate(); const swaps: unknown[] = []; await __test_sweepTokensToSol( - { + fake({ getOperatorKeypair: async () => admin, getTokenMetadata: async () => ({ decimals: 6 }), formatSolBalance: String, - } as any, - { getBalance: async () => lamports } as any, + }), + fake({ getBalance: async () => lamports }), [{ mint: (await Keypair.generate()).publicKey.toBase58(), ticker: "AAA" }], () => ({ @@ -377,8 +379,11 @@ describe("WSOL unwrap with the default balance reader", () => { const payer = await Keypair.generate(); const unwrapSolWithKeypair = mock(async () => ({ signature: "sig", remainingLamports: 0 })); await __test_unwrapWsolBalance( - { getTokenMetadata: async () => ({ decimals: 9 }), unwrapSolWithKeypair } as any, - {} as any, + fake({ + getTokenMetadata: async () => ({ decimals: 9 }), + unwrapSolWithKeypair, + }), + fake(), payer.publicKey, payer, price(Infinity), diff --git a/tests/game-manager.active-list.test.ts b/tests/game-manager.active-list.test.ts index bd0d0ee5..d3d738b5 100644 --- a/tests/game-manager.active-list.test.ts +++ b/tests/game-manager.active-list.test.ts @@ -1,6 +1,8 @@ import { afterEach, beforeEach, describe, expect, spyOn, test } from "bun:test"; import { PublicKey } from "#solana"; +import type { Context } from "grammy"; import { GameManager } from "../src/utils/game"; +import { fake, makeTestGameManager } from "./helpers/fakes"; import { DEFAULT_TOKEN_TICKER } from "../src/utils/constants"; const A = new PublicKey("BPFLoader1111111111111111111111111111111111").toBase58(); @@ -19,8 +21,9 @@ afterEach(() => { GameManager.resetForTest(); }); -const manager = (game: unknown) => - GameManager.getInstance({ account: { game } } as any, {} as any, {} as any) as any; +// The list builder and the batch read are private. Typed bracket access calls them, so a +// changed signature breaks the build. +const manager = (game: unknown) => makeTestGameManager({ program: { account: { game } } }); describe("batch game account read", () => { test("reads each valid address once and keeps only the answers it got", async () => { @@ -31,7 +34,7 @@ describe("batch game account read", () => { return [{ id: "a" }, null]; }, }); - const map = await gm.fetchGameAccountsBatch([A, "not a key", B, A, "x"]); + const map = await gm["fetchGameAccountsBatch"]([A, "not a key", B, A, "x"]); expect(reads).toEqual([[A, B]]); expect([...map.entries()]).toEqual([ [A, { id: "a" }], @@ -41,7 +44,7 @@ describe("batch game account read", () => { test("an answer without an entry is left out for a single lookup", async () => { const gm = manager({ fetchMultiple: async () => [undefined, { id: "b" }] }); - const map = await gm.fetchGameAccountsBatch([A, B]); + const map = await gm["fetchGameAccountsBatch"]([A, B]); expect([...map.entries()]).toEqual([[B, { id: "b" }]]); }); @@ -52,7 +55,7 @@ describe("batch game account read", () => { ["no account reader", undefined, [A]], ])("%s reads nothing", async (_name, game, addresses) => { const gm = manager(game); - expect((await gm.fetchGameAccountsBatch(addresses)).size).toBe(0); + expect((await gm["fetchGameAccountsBatch"](addresses)).size).toBe(0); expect(warn).not.toHaveBeenCalled(); }); @@ -63,7 +66,7 @@ describe("batch game account read", () => { throw failure; }, }); - expect((await gm.fetchGameAccountsBatch([A])).size).toBe(0); + expect((await gm["fetchGameAccountsBatch"]([A])).size).toBe(0); expect(warn).toHaveBeenCalledWith( "Batch game account lookup failed; falling back to single lookups:", failure, @@ -81,7 +84,7 @@ describe("active game list", () => { formatCalls.push(args.slice(2)); return { messageText: "card", keyboard: [["k"]] }; }; - const result = await gm.formatActiveGamesList({}, rows); + const result = await gm["formatActiveGamesList"](fake({}), rows); return { result, formatCalls }; }; @@ -152,7 +155,9 @@ describe("active game list", () => { gm.getGameCreatorUsername = async () => { throw failure; }; - const rows = await gm.formatActiveGamesList({}, [{ game_address: A, game_account: {} }]); + const rows = await gm["formatActiveGamesList"](fake({}), [ + { game_address: A, game_account: {} }, + ]); expect(rows).toEqual([]); expect(warn).toHaveBeenCalledWith(`Failed to format active game ${A}:`, failure); }); diff --git a/tests/game-manager.creation-request.test.ts b/tests/game-manager.creation-request.test.ts index 7bf02437..ae6849a2 100644 --- a/tests/game-manager.creation-request.test.ts +++ b/tests/game-manager.creation-request.test.ts @@ -1,5 +1,6 @@ import { afterEach, beforeEach, describe, expect, test } from "bun:test"; import { GameManager } from "../src/utils/game"; +import { makeTestGameManager } from "./helpers/fakes"; beforeEach(() => GameManager.resetForTest()); afterEach(() => GameManager.resetForTest()); @@ -16,7 +17,7 @@ describe("game creation request check", () => { return stored; }, }; - const gm = GameManager.getInstance({} as any, {} as any, db as any); + const gm = makeTestGameManager({ db }); return { found: gm.hasGameCreationRequest(12n, chatId, messageId), reads }; }; diff --git a/tests/game-manager.expired-cleanup-paths.test.ts b/tests/game-manager.expired-cleanup-paths.test.ts index b4e34160..83eada69 100644 --- a/tests/game-manager.expired-cleanup-paths.test.ts +++ b/tests/game-manager.expired-cleanup-paths.test.ts @@ -1,6 +1,8 @@ import { afterEach, beforeEach, describe, expect, spyOn, test } from "bun:test"; import { PublicKey } from "#solana"; import { GameManager } from "../src/utils/game"; +import type { GameDatabase } from "../src/utils/game-database"; +import { fake, makeTestGameManager, type FakeMembers } from "./helpers/fakes"; const GAME = new PublicKey("BPFLoader1111111111111111111111111111111111"); const ADDRESS = GAME.toBase58(); @@ -16,8 +18,10 @@ afterEach(() => { GameManager.resetForTest(); }); -const manager = (db: Record = {}) => - GameManager.getInstance({ account: { game: {} } } as any, {} as any, db as any) as any; +// These tests stub private steps of the expired-game cleanup to reach each branch. +// GameManager has no public way to inject those steps, so typed bracket access sets them. +const manager = (db: FakeMembers = {}) => + makeTestGameManager({ program: { account: { game: {} } }, db }); describe("display amount and game type", () => { test.each([ @@ -28,7 +32,7 @@ describe("display amount and game type", () => { ["a coinflip ticket", { coinflip: {} }, 7, 3, 3], ["a broken ticket amount", { coinflip: {} }, 7, "x", 0], ])("%s", (_name, gameType, totalAmount, ticketAmount, expected) => { - expect(manager().getDisplayAmountFromAccount({ gameType, totalAmount, ticketAmount })).toBe( + expect(manager()["getDisplayAmountFromAccount"]({ gameType, totalAmount, ticketAmount })).toBe( expected, ); }); @@ -40,7 +44,7 @@ describe("display amount and game type", () => { ["an unnamed game type", { gameType: { "": {} } }, "game"], ["a named game type", { gameType: { giveaway: {} } }, "giveaway"], ])("the game type of %s", (_name, account, expected) => { - expect(manager().getGameType(account)).toBe(expected); + expect(manager()["getGameType"](account)).toBe(expected); }); }); @@ -52,8 +56,8 @@ describe("expired giveaway timing", () => { cancels.push(args); return { success: true }; }; - gm.isGameExpiredWithBuffer = () => bufferElapsed; - const handled = await gm.handleExpiredGiveaway( + gm["isGameExpiredWithBuffer"] = () => bufferElapsed; + const handled = await gm["handleExpiredGiveaway"]( GAME, { gameType: { giveaway: {} }, ...account }, ADDRESS, @@ -86,11 +90,11 @@ describe("expired giveaway timing", () => { }); describe("expired coinflip checks", () => { - type Keys = Record; + type Keys = FakeMembers>; const coinflip = async ( keys: Keys, account: Record = {}, - db: Record = {}, + db: FakeMembers = {}, ) => { const removed: unknown[][] = []; const gm = manager({ @@ -100,15 +104,22 @@ describe("expired coinflip checks", () => { }); const cancels: unknown[][] = []; const cleanups: string[] = []; - gm.reconcilePendingParticipants = async () => undefined; - gm.analyzePlayerKeys = () => ({ available: [], total: 0, ...keys }); - gm.cancelGameWithCreator = async (...args: unknown[]) => { + gm["reconcilePendingParticipants"] = async () => undefined; + gm["analyzePlayerKeys"] = () => + fake>({ available: [], total: 0, ...keys }); + gm["cancelGameWithCreator"] = async (...args: unknown[]) => { cancels.push(args.slice(2)); return true; }; - gm.executeCompleteCleanup = async () => cleanups.push("complete"); - gm.executePartialCleanup = async () => cleanups.push("partial"); - const handled = await gm.handleExpiredCoinflip( + gm["executeCompleteCleanup"] = async () => { + cleanups.push("complete"); + return true; + }; + gm["executePartialCleanup"] = async () => { + cleanups.push("partial"); + return true; + }; + const handled = await gm["handleExpiredCoinflip"]( GAME, { ticketsCount: 2, creator: CREATOR.toBase58(), ...account }, ADDRESS, @@ -170,7 +181,7 @@ describe("expired coinflip checks", () => { ]); }); - const emptyGame = (db: Record, keys: Keys = {}) => + const emptyGame = (db: FakeMembers, keys: Keys = {}) => coinflip({ onChainTickets: 0, onChainParticipants: 0, dbParticipantCount: 0, ...keys }, {}, db); test("an empty game without stale rows cancels with the analyzed creator", async () => { diff --git a/tests/game-manager.join-attempts.test.ts b/tests/game-manager.join-attempts.test.ts index 99748742..9b5597e5 100644 --- a/tests/game-manager.join-attempts.test.ts +++ b/tests/game-manager.join-attempts.test.ts @@ -1,6 +1,9 @@ import { afterEach, beforeEach, describe, expect, spyOn, test } from "bun:test"; import { Keypair, PublicKey } from "#solana"; import { GameManager } from "../src/utils/game"; +import type { OracleClient } from "../src/utils/oracle"; +import type { SwapManager } from "../src/utils/swap-manager"; +import { fake, makeTestGameManager, type FakeMembers } from "./helpers/fakes"; const GAME = new PublicKey("BPFLoader1111111111111111111111111111111111"); const ADDRESS = GAME.toBase58(); @@ -24,13 +27,15 @@ afterEach(() => { type Options = { // Each confirm call runs the next step. A step may call the resend callback. confirm?: Array<(resend: () => Promise) => Promise>; - build?: () => Promise<{ accounts: object; setupInstructions: unknown[] }>; + build?: () => Promise; alreadyJoined?: () => Promise; resend?: () => Promise; after?: Record | (() => Promise); - oracle?: Record; + oracle?: FakeMembers; }; +type JoinAccounts = Awaited>; + async function join(options: Options = {}) { const player = await Keypair.generate(); const before = { @@ -68,6 +73,11 @@ async function join(options: Options = {}) { sends.push(args); return `SIG${sends.length}`; }, + // The resend path. A wallet that answers without a signature is a real case. + sendAndConfirmWithResubmits: async (...args: unknown[]) => { + resends.push(args); + return options.resend ? options.resend() : "RESENT"; + }, }; const db = { getGame: () => ({ status: "active", token_mint: MINT, token_ticker: "TOK" }), @@ -77,13 +87,18 @@ async function join(options: Options = {}) { getGameParticipants: () => [], getPlayerTelegramId: () => null, }; - const gm = GameManager.getInstance(program as any, wallet as any, db as any) as any; - gm.swapManager = { performJustInTimeSolSwap: async () => ({ swapped: false }) }; - gm.buildJoinAccounts = - options.build ?? (async () => ({ accounts: {}, setupInstructions: [SETUP_IX] })); + // The tests stub private join steps to reach each retry branch. GameManager has no + // public way to inject them, so typed bracket access sets them. + const gm = makeTestGameManager({ program, wallet, db }); + gm["swapManager"] = fake({ + performJustInTimeSolSwap: async () => ({ swapped: false }), + }); + gm["buildJoinAccounts"] = + options.build ?? + (async () => fake({ accounts: {}, setupInstructions: [SETUP_IX] })); const steps = [...(options.confirm ?? [async () => "CONFIRMED"])]; let confirmFailed = false; - gm.confirmTransactionWithRecovery = async ( + gm["confirmTransactionWithRecovery"] = async ( _sig: string, _pda: PublicKey, _label: string, @@ -99,22 +114,20 @@ async function join(options: Options = {}) { throw failure; } }; - gm.sendInstructionsWithFallback = async (...args: unknown[]) => { - resends.push(args); - return options.resend ? options.resend() : "RESENT"; - }; // The checks before the join always see a new player. - gm.isPlayerInGame = async () => + gm["isPlayerInGame"] = async () => confirmFailed && options.alreadyJoined ? options.alreadyJoined() : false; const verified: unknown[] = []; - gm.verifyParticipantJoin = async (...args: unknown[]) => { + gm["verifyParticipantJoin"] = async (...args: unknown[]) => { verified.push(args[3]); return true; }; const completions: string[] = []; - gm.oracleClient = options.oracle ?? { - requestGameCompletion: async (address: string) => completions.push(address), - }; + gm["oracleClient"] = fake( + options.oracle ?? { + requestGameCompletion: async (address: string) => completions.push(address), + }, + ); const result = await gm.joinGame(ADDRESS, 7n); const pending = (signature: unknown) => [ ADDRESS, @@ -140,7 +153,17 @@ describe("join attempts", () => { test("a resend during confirmation saves and confirms the new signature", async () => { const run = await join({ confirm: [async (resend) => resend()] }); - expect(run.resends).toEqual([[[SETUP_IX, JOIN_IX], [run.player], "Player join transaction"]]); + expect(run.resends).toEqual([ + [ + [SETUP_IX, JOIN_IX], + [run.player], + { + operationLabel: "Player join transaction", + skipConfirmation: undefined, + priorityFee: true, + }, + ], + ]); expect(run.saved).toEqual([run.pending("SIG1"), run.pending("RESENT")]); expect(run.verified).toEqual([{ joinSignature: "RESENT" }]); }); @@ -245,7 +268,7 @@ describe("join attempts", () => { }); describe("join completion request", () => { - test.each([ + test.each<[string, { ticketsCount?: number; maxTickets?: number }, string[]]>([ ["the last seat", { ticketsCount: 2, maxTickets: 2 }, [ADDRESS]], ["more tickets than seats", { ticketsCount: 3, maxTickets: 2 }, [ADDRESS]], ["an open seat", { ticketsCount: 1, maxTickets: 2 }, []], @@ -257,8 +280,8 @@ describe("join completion request", () => { expect(run.result).toEqual({ success: true, gameAccount: after, - ticketsCount: Number((after as any).ticketsCount ?? 0), - maxTickets: Number((after as any).maxTickets ?? 0), + ticketsCount: after.ticketsCount ?? 0, + maxTickets: after.maxTickets ?? 0, }); }); diff --git a/tests/game-manager.join-lifecycle.test.ts b/tests/game-manager.join-lifecycle.test.ts index 7cf13fa1..4979105a 100644 --- a/tests/game-manager.join-lifecycle.test.ts +++ b/tests/game-manager.join-lifecycle.test.ts @@ -362,7 +362,7 @@ describe("GameManager join lifecycle", () => { } as any; const gm = GameManager.getInstance({ account: { game } } as any, {} as any, gameDb); let reads = 0; - (gm as any).isPlayerInGame = async () => { + gm["isPlayerInGame"] = async () => { reads += 1; if (reads > 1) throw new Error("Unexpected second membership check"); return false; diff --git a/tests/game-manager.join-private-attempts.test.ts b/tests/game-manager.join-private-attempts.test.ts index 0f6ce430..27e73692 100644 --- a/tests/game-manager.join-private-attempts.test.ts +++ b/tests/game-manager.join-private-attempts.test.ts @@ -1,6 +1,8 @@ import { afterEach, beforeEach, describe, expect, spyOn, test } from "bun:test"; import { Keypair, PublicKey } from "#solana"; import { GameManager } from "../src/utils/game"; +import type { OracleClient } from "../src/utils/oracle"; +import { fake, makeTestGameManager } from "./helpers/fakes"; const GAME = new PublicKey("BPFLoader1111111111111111111111111111111111"); const ADDRESS = GAME.toBase58(); @@ -20,10 +22,12 @@ afterEach(() => { GameManager.resetForTest(); }); +type JoinAccounts = Awaited>; + type Options = { // Each confirm call runs the next step. A step may call the resend callback. confirm?: Array<(resend: () => Promise) => Promise>; - build?: () => Promise<{ accounts: object; setupInstructions?: unknown[] }>; + build?: () => Promise; alreadyJoined?: () => Promise; }; @@ -47,16 +51,24 @@ async function joinPrivate(options: Options = {}) { friendly.push(failure); return "friendly"; }, + // The resend path. + sendAndConfirmWithResubmits: async (...args: unknown[]) => { + resends.push(args); + return "RESENT"; + }, }; const db = { getGame: () => ({ token_mint: "MINT" }) }; - const gm = GameManager.getInstance(program as any, wallet as any, db as any) as any; - gm.oracleClient = { + // The tests stub private join steps to reach each retry branch. GameManager has no + // public way to inject them, so typed bracket access sets them. + const gm = makeTestGameManager({ program, wallet, db }); + gm["oracleClient"] = fake({ authorizePlayer: async () => ({ authorized: true, operatorKeypair: admin }), - }; - gm.buildJoinAccounts = - options.build ?? (async () => ({ accounts: {}, setupInstructions: [SETUP_IX] })); + }); + gm["buildJoinAccounts"] = + options.build ?? + (async () => fake({ accounts: {}, setupInstructions: [SETUP_IX] })); const steps = [...(options.confirm ?? [async () => "CONFIRMED"])]; - gm.confirmTransactionWithRecovery = async ( + gm["confirmTransactionWithRecovery"] = async ( _sig: string, _pda: PublicKey, label: string, @@ -68,11 +80,7 @@ async function joinPrivate(options: Options = {}) { if (!step) throw new Error("unexpected confirm"); return step(resend); }; - gm.sendInstructionsWithFallback = async (...args: unknown[]) => { - resends.push(args); - return "RESENT"; - }; - gm.isPlayerInGame = options.alreadyJoined ?? (async () => false); + gm["isPlayerInGame"] = options.alreadyJoined ?? (async () => false); const result = await gm.joinPrivateGame(GAME, player, 99, 7n); return { result, player, admin, sends, resends, labels, friendly }; } @@ -99,7 +107,15 @@ describe("private join attempts", () => { const run = await joinPrivate({ confirm: [async (resend) => resend()] }); expect(run.result).toEqual({ success: true, tx: "RESENT" }); expect(run.resends).toEqual([ - [[SETUP_IX, JOIN_IX], [run.player, run.admin], "Player join transaction"], + [ + [SETUP_IX, JOIN_IX], + [run.player, run.admin], + { + operationLabel: "Player join transaction", + skipConfirmation: undefined, + priorityFee: true, + }, + ], ]); }); diff --git a/tests/game-manager.player-keys.test.ts b/tests/game-manager.player-keys.test.ts index 0164cf06..1992b13e 100644 --- a/tests/game-manager.player-keys.test.ts +++ b/tests/game-manager.player-keys.test.ts @@ -1,6 +1,8 @@ import { afterEach, beforeEach, describe, expect, spyOn, test } from "bun:test"; import { PublicKey } from "#solana"; import { GameManager } from "../src/utils/game"; +import type { GameDatabase } from "../src/utils/game-database"; +import { fake, makeTestGameManager, type FakeMembers } from "./helpers/fakes"; const GAME = new PublicKey("BPFLoader1111111111111111111111111111111111"); const ADDRESS = GAME.toBase58(); @@ -22,22 +24,25 @@ type Setup = { keys?: Record; creatorId?: () => string | null; unmatched?: string[]; - db?: Record; + db?: FakeMembers; }; +// These tests stub private steps of the key check and the cleanup to reach each branch. +// GameManager has no public way to inject those steps, so typed bracket access sets them. + function analyze(account: Record, options: Setup = {}) { - const db: Record = { + const db: FakeMembers = { getPlayerTelegramId: options.creatorId ?? (() => null), getPlayerPublicKey: (id: string) => options.keys?.[id] ?? null, ...options.db, }; - const gm = GameManager.getInstance({ account: { game: {} } } as any, {} as any, db as any) as any; - gm.getGamePlayers = () => options.players ?? []; - gm.recoverParticipantsFromChain = () => ({ + const gm = makeTestGameManager({ program: { account: { game: {} } }, db }); + gm["getGamePlayers"] = () => options.players ?? []; + gm["recoverParticipantsFromChain"] = () => ({ recovered: [], unmatchedParticipants: options.unmatched ?? [], }); - const info = gm.analyzePlayerKeys(GAME, account, ADDRESS); + const info = gm["analyzePlayerKeys"](GAME, account, ADDRESS); return { info, warnings: warn.mock.calls.map((call: unknown[]) => call) }; } @@ -163,24 +168,23 @@ describe("player key analysis", () => { describe("complete cleanup", () => { const cleanup = async (unjoined: number) => { - const gm = GameManager.getInstance( - { account: { game: {} } } as any, - {} as any, - {} as any, - ) as any; + const gm = makeTestGameManager({ program: { account: { game: {} } } }); const unjoinCalls: unknown[][] = []; const cancels: unknown[][] = []; - gm.unjoinPlayers = async (...args: unknown[]) => { + gm["unjoinPlayers"] = async (...args: unknown[]) => { unjoinCalls.push(args); return unjoined; }; - gm.cancelGameWithCreator = async (...args: unknown[]) => { + gm["cancelGameWithCreator"] = async (...args: unknown[]) => { cancels.push(args); return true; }; const account = { creator: CREATOR }; - const info = { available: ["p1", "p2"], creator: { telegramId: "777" } }; - const ok = await gm.executeCompleteCleanup(GAME, account, info, ADDRESS); + const info = fake>({ + available: ["p1", "p2"], + creator: { telegramId: "777" }, + }); + const ok = await gm["executeCompleteCleanup"](GAME, account, info, ADDRESS); return { ok, unjoinCalls, cancels, account }; }; diff --git a/tests/game-manager.public-page.test.ts b/tests/game-manager.public-page.test.ts index d23ac564..fc5cc7ab 100644 --- a/tests/game-manager.public-page.test.ts +++ b/tests/game-manager.public-page.test.ts @@ -2,6 +2,7 @@ import { afterEach, describe, expect, spyOn, test, vi } from "bun:test"; import { Keypair, PublicKey } from "#solana"; import type { Context } from "grammy"; import { GameManager } from "../src/utils/game"; +import { fake } from "./helpers/fakes"; const now = () => Math.floor(Date.now() / 1000); @@ -347,7 +348,7 @@ describe("GameManager active list batching", () => { stubFormatting(manager); const warn = spyOn(console, "warn").mockImplementation(() => {}); - const games = await manager.getUserActiveGames({} as any, 7n); + const games = await manager.getUserActiveGames(fake({}), 7n); expect(fetchNullable).toHaveBeenCalledTimes(1); expect(games).toHaveLength(1); expect(warn.mock.calls).toEqual([ @@ -376,7 +377,7 @@ describe("GameManager active list batching", () => { stubFormatting(manager); const warn = spyOn(console, "warn").mockImplementation(() => {}); - const games = await manager.getUserActiveGames({} as any, 7n); + const games = await manager.getUserActiveGames(fake({}), 7n); expect(fetchNullable.mock.calls.map(([key]) => key.toBase58())).toEqual([omittedAddress]); expect(games.map((row) => row.gameAddress)).toEqual([omittedAddress]); expect(warn.mock.calls).toEqual([ diff --git a/tests/game-manager.stats-boundaries.test.ts b/tests/game-manager.stats-boundaries.test.ts index f7df61eb..4b188e75 100644 --- a/tests/game-manager.stats-boundaries.test.ts +++ b/tests/game-manager.stats-boundaries.test.ts @@ -1,6 +1,12 @@ import { afterEach, beforeEach, describe, expect, spyOn, test } from "bun:test"; import { PublicKey } from "#solana"; import { GameManager } from "../src/utils/game"; +import type { GameDatabase } from "../src/utils/game-database"; +import type { TimbaProgram } from "../src/utils/timba-program"; +import { makeTestGameManager, type FakeMembers } from "./helpers/fakes"; + +// No public call returns these stats: formatGameMessage only shows them as message text. +// Typed bracket access calls the private builders, so a changed signature breaks the build. const GAME = new PublicKey("BPFLoader1111111111111111111111111111111111"); const KEY_A = new PublicKey("BPFLoader2111111111111111111111111111111111").toBase58(); @@ -32,12 +38,12 @@ function completedManager( players: string[], addresses?: string[], ) { - const db: Record = { + const db: FakeMembers = { getGame: () => game, getGameParticipants: () => players, }; - if (addresses) db["getGameParticipantAddresses"] = () => addresses; - return GameManager.getInstance({} as any, {} as any, db as any); + if (addresses) db.getGameParticipantAddresses = () => addresses; + return makeTestGameManager({ db }); } describe("completed game stats", () => { @@ -177,7 +183,7 @@ describe("completed game stats", () => { for (const { name, game, players = [], addresses, pot, expected } of cases) { test(name, async () => { const gm = completedManager(game, players, addresses); - const stats = await (gm as any).getCompletedGameStats(GAME, 10n, pot); + const stats = await gm["getCompletedGameStats"](GAME, 10n, pot); expect(stats).toEqual({ currentTickets: stats.currentTickets, maxTickets: stats.maxTickets, @@ -206,12 +212,12 @@ describe("active game stats", () => { ...extra, }); - function activeManager(program: any = {}, saved: any[][] = []) { - return GameManager.getInstance( + function activeManager(program: FakeMembers = {}, saved: unknown[][] = []) { + return makeTestGameManager({ program, - { getBlockchainTime: async () => 1_000 } as any, - { saveGameParticipantAddresses: (...args: any[]) => saved.push(args) } as any, - ); + wallet: { getBlockchainTime: async () => 1_000 }, + db: { saveGameParticipantAddresses: (...args: unknown[]) => saved.push(args) }, + }); } const pots: Array<[string, Record, number | bigint | undefined, bigint]> = [ @@ -226,16 +232,16 @@ describe("active game stats", () => { for (const [name, extra, pot, expected] of pots) { test(`pot: ${name}`, async () => { const gm = activeManager(); - const stats = await (gm as any).getActiveGameStats(GAME, 10n, pot, account(extra)); + const stats = await gm["getActiveGameStats"](GAME, 10n, pot, account(extra)); expect(stats.totalPot).toBe(expected); expect(warn).not.toHaveBeenCalled(); }); } test("only the participants inside the ticket count are saved", async () => { - const saved: any[][] = []; + const saved: unknown[][] = []; const gm = activeManager({}, saved); - const stats = await (gm as any).getActiveGameStats( + const stats = await gm["getActiveGameStats"]( GAME, 10n, undefined, @@ -246,16 +252,16 @@ describe("active game stats", () => { }); test("an account without a participant list has no participants", async () => { - const saved: any[][] = []; + const saved: unknown[][] = []; const gm = activeManager({}, saved); - const stats = await (gm as any).getActiveGameStats(GAME, 10n, undefined, account()); + const stats = await gm["getActiveGameStats"](GAME, 10n, undefined, account()); expect(stats.participantAddresses).toEqual([]); expect(saved).toEqual([[GAME.toBase58(), []]]); }); test("a closed account is unavailable without a lookup warning", async () => { const gm = activeManager({ account: { game: { fetchNullable: async () => null } } }); - const stats = await (gm as any).getActiveGameStats(GAME, 10n); + const stats = await gm["getActiveGameStats"](GAME, 10n); expect(stats).toEqual(unavailable(10n)); expect(warn).not.toHaveBeenCalled(); }); @@ -271,7 +277,7 @@ describe("active game stats", () => { }, }, }); - const stats = await (gm as any).getActiveGameStats(GAME, 10n); + const stats = await gm["getActiveGameStats"](GAME, 10n); expect(stats).toEqual(unavailable(10n)); expect(warn).toHaveBeenCalledWith( `Warning: Could not fetch game account for ${GAME.toBase58()}:`, diff --git a/tests/game-manager.unjoin-errors.test.ts b/tests/game-manager.unjoin-errors.test.ts index ae91fdfa..a8e8b281 100644 --- a/tests/game-manager.unjoin-errors.test.ts +++ b/tests/game-manager.unjoin-errors.test.ts @@ -203,7 +203,7 @@ describe("GameManager unjoin errors", () => { (gm as any).recoverParticipantsFromChain = () => {}; (gm as any).buildUnjoinAccounts = async () => ({}); (gm as any).sendInstructionsWithFallback = async () => "SIG"; - return { gm: gm as any, gamePda, player, removed, confirmations }; + return { gm, program, gamePda, player, removed, confirmations }; }; test("an RPC error while checking the game keeps the local record and throws", async () => { @@ -212,7 +212,7 @@ describe("GameManager unjoin errors", () => { }); await expect( - gm.unjoinPlayerFromGame(gamePda, player, player.publicKey, "123"), + gm["unjoinPlayerFromGame"](gamePda, player, player.publicKey, "123"), ).rejects.toThrow(/rpc down/); expect(confirmations).toEqual(["SIG", "SIG", "SIG"]); expect(removed).toEqual([]); @@ -221,23 +221,25 @@ describe("GameManager unjoin errors", () => { test("a game that is really gone counts as the player removed", async () => { const { gm, gamePda, player, removed, confirmations } = await setup(async () => null); - await gm.unjoinPlayerFromGame(gamePda, player, player.publicKey, "123"); + await gm["unjoinPlayerFromGame"](gamePda, player, player.publicKey, "123"); expect(confirmations).toEqual(["SIG", "SIG", "SIG"]); expect(removed).toEqual([[gamePda.toBase58(), "123"]]); }); test("without fetchNullable, a missing-account error from fetch counts as removed", async () => { - const { gm, gamePda, player, removed, confirmations } = await setup(async () => null); + const { gm, program, gamePda, player, removed, confirmations } = await setup( + async () => null, + ); let reads = 0; - gm.program.account.game.fetchNullable = undefined; - gm.program.account.game.fetch = async () => { + program.account.game.fetchNullable = undefined; + program.account.game.fetch = async () => { // The first read loads the account to build the unjoin; the probe's read finds it closed. if (reads++ === 0) return { creator: player.publicKey, participants: [] }; throw new Error("Account does not exist or has no data"); }; - await gm.unjoinPlayerFromGame(gamePda, player, player.publicKey, "123"); + await gm["unjoinPlayerFromGame"](gamePda, player, player.publicKey, "123"); expect(confirmations).toEqual(["SIG", "SIG", "SIG"]); expect(removed).toEqual([[gamePda.toBase58(), "123"]]); @@ -248,7 +250,7 @@ describe("GameManager unjoin errors", () => { participants: [], })); - await gm.unjoinPlayerFromGame(gamePda, player, player.publicKey, "123"); + await gm["unjoinPlayerFromGame"](gamePda, player, player.publicKey, "123"); expect(confirmations).toEqual(["SIG", "SIG", "SIG"]); expect(removed).toEqual([[gamePda.toBase58(), "123"]]); @@ -260,7 +262,7 @@ describe("GameManager unjoin errors", () => { })); await expect( - gm.unjoinPlayerFromGame(gamePda, player, player.publicKey, "123"), + gm["unjoinPlayerFromGame"](gamePda, player, player.publicKey, "123"), ).rejects.toThrow(/still pending|timeout/i); expect(confirmations).toEqual(["SIG", "SIG", "SIG"]); expect(removed).toEqual([]); diff --git a/tests/game-manager.update-message-recovery.test.ts b/tests/game-manager.update-message-recovery.test.ts index 934f78a7..dbd62e95 100644 --- a/tests/game-manager.update-message-recovery.test.ts +++ b/tests/game-manager.update-message-recovery.test.ts @@ -104,7 +104,9 @@ function managerFor( const card: any = { chatId: CHAT, messageId: ORIGINAL }; if (options.usesVideo !== undefined) card.usesVideo = options.usesVideo; messages.set(CHAT, card); - (gm as any).activeGameMessages.set(address, messages); + // The database restore always sets `usesVideo` to true, and a public send adds extra + // Telegram calls to each script. Typed bracket access seeds the exact card instead. + gm["activeGameMessages"].set(address, messages); const update = (ctx: any) => withinTestDeadline( gm.updateGameMessage( @@ -119,7 +121,8 @@ function managerFor( ), "updateGameMessage", ); - return { gm, saved, update, card: () => gm.getActiveGameMessages(address)?.get(CHAT) }; + const cards = () => gm.getActiveGameMessages(address); + return { gm, saved, update, cards, card: () => cards()?.get(CHAT) }; } let address = 0; @@ -335,9 +338,9 @@ describe("game card recreation after the card is deleted", () => { const telegram = scriptedCtx({ media: [fail(editGone), fail(editGone)] }); await game.update(telegram.ctx); // The recreated card is tracked; put the deleted one back to delete it again. - (game.gm as any).activeGameMessages - .get([...(game.gm as any).activeGameMessages.keys()][0]) - .set(CHAT, { chatId: CHAT, messageId: ORIGINAL, usesVideo: true }); + const cards = game.cards(); + if (!cards) throw new Error("The recreated card is not tracked"); + cards.set(CHAT, { chatId: CHAT, messageId: ORIGINAL, usesVideo: true }); await game.update(telegram.ctx); expect(telegram.names()).toEqual(["media", "video", "media", "video"]); diff --git a/tests/game-manager.update-message.test.ts b/tests/game-manager.update-message.test.ts index 8eb5ea60..aa3f611a 100644 --- a/tests/game-manager.update-message.test.ts +++ b/tests/game-manager.update-message.test.ts @@ -122,7 +122,7 @@ describe("GameManager.updateGameMessage routing", () => { msgMap.set(1, { chatId: 1, messageId: 42, usesVideo: true }); (gm as any).activeGameMessages.set(addr, msgMap); await gm.updateGameMessage( - ctx as any, + ctx, addr, "coinflip", 1_000_000_000, @@ -161,7 +161,7 @@ describe("GameManager.updateGameMessage routing", () => { (gm as any).activeGameMessages.set(addr, msgMap); await withinTestDeadline( gm.updateGameMessage( - ctx as any, + ctx, addr, "coinflip", 1_000_000_000, @@ -202,7 +202,7 @@ describe("GameManager.updateGameMessage routing", () => { msgMap.set(1, { chatId: 1, messageId: 44, usesVideo: false }); (gm as any).activeGameMessages.set(addr, msgMap); await gm.updateGameMessage( - ctx as any, + ctx, addr, "giveaway", 1_000_000_000, @@ -238,7 +238,7 @@ describe("GameManager.updateGameMessage routing", () => { msgMap.set(1, { chatId: 1, messageId: 45, usesVideo: false }); (gm as any).activeGameMessages.set(addr, msgMap); await gm.updateGameMessage( - ctx as any, + ctx, addr, "coinflip", 1_000_000_000, @@ -288,7 +288,7 @@ describe("GameManager.updateGameMessage routing", () => { (gm as any).activeGameMessages.set(addr, msgMap); await gm.updateGameMessage( - ctx as any, + ctx, addr, "coinflip", 1_000_000_000, @@ -334,7 +334,7 @@ describe("GameManager.updateGameMessage routing", () => { (gm as any).activeGameMessages.set(addr, msgMap); await withinTestDeadline( gm.updateGameMessage( - ctx as any, + ctx, addr, "coinflip", 1_000_000_000, @@ -382,7 +382,7 @@ describe("GameManager.updateGameMessage routing", () => { (gm as any).activeGameMessages.set(addr, msgMap); await withinTestDeadline( gm.updateGameMessage( - ctx as any, + ctx, addr, "coinflip", 1_000_000_000, @@ -434,7 +434,7 @@ describe("GameManager.updateGameMessage routing", () => { (gm as any).activeGameMessages.set(addr, msgMap); await withinTestDeadline( gm.updateGameMessage( - ctx as any, + ctx, addr, "coinflip", 1_000_000_000, @@ -487,7 +487,7 @@ describe("GameManager.updateGameMessage routing", () => { (gm as any).activeGameMessages.set(addr, msgMap); await withinTestDeadline( gm.updateGameMessage( - ctx as any, + ctx, addr, "coinflip", 1_000_000_000, @@ -567,7 +567,7 @@ describe("GameManager.updateGameMessage routing", () => { msgMap.set(1, { chatId: 1, messageId: 46, usesVideo: true }); (gm as any).activeGameMessages.set(addr, msgMap); await gm.updateGameMessage( - ctx as any, + ctx, addr, "coinflip", 1_000_000_000, @@ -634,7 +634,7 @@ describe("GameManager.updateGameMessage routing", () => { (gm as any).activeGameMessages.set(addr, msgMap); await gm.updateGameMessage( - ctx as any, + ctx, addr, "coinflip", 1_000_000_000, @@ -692,7 +692,7 @@ describe("GameManager.updateGameMessage routing", () => { await Promise.all([ gm.updateGameMessage( - ctx as any, + ctx, addr, "coinflip", 1_000_000_000, @@ -701,7 +701,7 @@ describe("GameManager.updateGameMessage routing", () => { "TOK", ), gm.updateGameMessage( - ctx as any, + ctx, addr, "coinflip", 1_000_000_000, @@ -765,7 +765,7 @@ describe("GameManager.updateGameMessage routing", () => { (gm as any).activeGameMessages.set(addr, msgMap); await gm.updateGameMessage( - ctx as any, + ctx, addr, "coinflip", 1_000_000_000, @@ -836,7 +836,7 @@ describe("GameManager.updateGameMessage routing", () => { (gm as any).activeGameMessages.set(addr, msgMap); await gm.updateGameMessage( - ctx as any, + ctx, addr, "coinflip", 1_000_000_000, @@ -903,7 +903,7 @@ describe("GameManager.updateGameMessage routing", () => { (gm as any).activeGameMessages.set(addr, msgMap); await gm.updateGameMessage( - ctx as any, + ctx, addr, "giveaway", 1_000_000_000, diff --git a/tests/game-manager.username-lookup.test.ts b/tests/game-manager.username-lookup.test.ts index 61844c08..c7b4a213 100644 --- a/tests/game-manager.username-lookup.test.ts +++ b/tests/game-manager.username-lookup.test.ts @@ -1,5 +1,7 @@ import { afterEach, beforeEach, describe, expect, spyOn, test } from "bun:test"; +import type { Context } from "grammy"; import { GameManager } from "../src/utils/game"; +import { fake } from "./helpers/fakes"; import { makeDbStub, makeProgramStub, makeWalletStub } from "./helpers/game-manager"; let warn: ReturnType; @@ -28,17 +30,18 @@ function setup(member: Member = {}, db: Record = {}) { ...db, }, }), - ) as any; - const ctxFor = (chatId: unknown) => ({ - chat: chatId === undefined ? undefined : { id: chatId }, - api: { - getChatMember: async (...args: unknown[]) => { - lookups.push(args); - if (typeof member === "function") member(); - return { user: member }; + ); + const ctxFor = (chatId: unknown) => + fake({ + chat: chatId === undefined ? undefined : { id: chatId }, + api: { + getChatMember: async (...args: unknown[]) => { + lookups.push(args); + if (typeof member === "function") member(); + return { user: member }; + }, }, - }, - }); + }); return { gm, ctx: ctxFor(1), ctxFor, lookups, deleted, mapped }; } diff --git a/tests/game.completion-state.test.ts b/tests/game.completion-state.test.ts index 85ce1f9c..b5e26fb2 100644 --- a/tests/game.completion-state.test.ts +++ b/tests/game.completion-state.test.ts @@ -1,11 +1,21 @@ import { afterEach, beforeEach, describe, expect, spyOn, test } from "bun:test"; +import type { Context } from "grammy"; import { GameManager } from "../src/utils/game"; +import type { GameDatabase } from "../src/utils/game-database"; +import type { TimbaProgram } from "../src/utils/timba-program"; +import { fake, itemAt, makeTestGameManager, type FakeMembers } from "./helpers/fakes"; + +type UpdateRequest = Parameters[1]; import { TELEGRAM_USERNAME_CACHE_TTL_MS } from "../src/utils/constants"; const GAME = "BPFLoader1111111111111111111111111111111111"; -const makeManager = (gameDb: any = {}, program: any = { account: { game: {} } }) => - GameManager.getInstance(program, {} as any, gameDb) as any; +// These tests check private ordering and cache rules one case at a time. Typed bracket +// access reaches them, so a renamed member or a changed signature breaks the build. +const makeManager = ( + db: FakeMembers = {}, + program: FakeMembers = { account: { game: {} } }, +) => makeTestGameManager({ program, db }); let warn: ReturnType; beforeEach(() => { @@ -36,7 +46,7 @@ describe("completion signature save", () => { test.each([[undefined], [""]])("a missing signature (%p) reads and saves nothing", (sig) => { const { db, recorded, reads } = recorder(); - makeManager(db).persistCompletionSignature(GAME, 1, { + makeManager(db)["persistCompletionSignature"](GAME, 1, { status: "Completed", winnerSignature: sig, }); @@ -57,9 +67,9 @@ describe("completion signature save", () => { const { db, recorded } = recorder(); const gm = makeManager(db); const entry = { status: "Completed", generation, winnerSignature }; - if (source === "latest request") gm.latestGameMessageUpdateRequests.set(GAME, entry); - else gm.gameMessageCompletionMetadata.set(GAME, entry); - gm.persistCompletionSignature(GAME, 1, { status: "Completed", winnerSignature: "sig" }); + if (source === "latest request") gm["latestGameMessageUpdateRequests"].set(GAME, entry); + else gm["gameMessageCompletionMetadata"].set(GAME, entry); + gm["persistCompletionSignature"](GAME, 1, { status: "Completed", winnerSignature: "sig" }); expect(recorded).toEqual(saved ? [[true, GAME, { signature: "sig" }]] : []); }); } @@ -67,14 +77,14 @@ describe("completion signature save", () => { test("a database without the finance writer is skipped without a read or warning", () => { const reads: string[] = []; const gm = makeManager({ getGame: (address: string) => reads.push(address) }); - gm.persistCompletionSignature(GAME, 1, { status: "Completed", winnerSignature: "sig" }); + gm["persistCompletionSignature"](GAME, 1, { status: "Completed", winnerSignature: "sig" }); expect(reads).toEqual([]); expect(warn).not.toHaveBeenCalled(); }); test("a database without a game reader still saves the signature", () => { const { db, recorded } = recorder({ getGame: undefined }); - makeManager(db).persistCompletionSignature(GAME, 1, { + makeManager(db)["persistCompletionSignature"](GAME, 1, { status: "Completed", winnerSignature: "sig", }); @@ -84,7 +94,7 @@ describe("completion signature save", () => { test("an empty stored signature does not block the save", () => { const { db, recorded } = recorder({ getGame: () => ({ completion_signature: "" }) }); - makeManager(db).persistCompletionSignature(GAME, 1, { + makeManager(db)["persistCompletionSignature"](GAME, 1, { status: "Completed", winnerSignature: "sig", }); @@ -94,15 +104,15 @@ describe("completion signature save", () => { describe("older completion update check", () => { // Generation 1 is the older update. Generation 2 is the newest generation. - const supersededBy = (latest: Record, request: Record) => { + const supersededBy = (latest: UpdateRequest, request: Partial) => { const gm = makeManager(); - gm.nextGameMessageUpdateGeneration(GAME); - gm.nextGameMessageUpdateGeneration(GAME); - gm.latestGameMessageUpdateRequests.set(GAME, { generation: 2, ...latest }); - return gm.isSupersededActiveGameMessageUpdate(GAME, { status: "Completed", ...request }, 1); + gm["nextGameMessageUpdateGeneration"](GAME); + gm["nextGameMessageUpdateGeneration"](GAME); + gm["latestGameMessageUpdateRequests"].set(GAME, { generation: 2, ...latest }); + return gm["isSupersededActiveGameMessageUpdate"](GAME, { status: "Completed", ...request }, 1); }; - const cases: Array<[string, Record, Record, boolean]> = [ + const cases: Array<[string, Partial, Partial, boolean]> = [ ["a different winner", { winnerAddress: "w2" }, { winnerAddress: "w1" }, true], ["the same winner", { winnerAddress: "w2" }, { winnerAddress: "w2" }, false], ["no newer winner", {}, { winnerAddress: "w1" }, false], @@ -126,27 +136,29 @@ describe("older completion update check", () => { test("a remembered request of the same generation does not supersede the update", () => { const gm = makeManager(); - gm.nextGameMessageUpdateGeneration(GAME); - gm.nextGameMessageUpdateGeneration(GAME); - gm.latestGameMessageUpdateRequests.set(GAME, { + gm["nextGameMessageUpdateGeneration"](GAME); + gm["nextGameMessageUpdateGeneration"](GAME); + gm["latestGameMessageUpdateRequests"].set(GAME, { generation: 1, status: "Completed", winnerAddress: "w2", }); expect( - gm.isSupersededActiveGameMessageUpdate(GAME, { status: "Completed", winnerAddress: "w1" }, 1), + gm["isSupersededActiveGameMessageUpdate"](GAME, { status: "Completed", winnerAddress: "w1" }, 1), ).toBe(false); }); }); describe("persisted terminal state", () => { - const terminal = (game: unknown, requested = "Active", metadata?: Record) => { + const terminal = (game: unknown, requested = "Active", metadata?: Partial) => { const gm = makeManager({ getGame: () => game }); - if (metadata) gm.gameMessageCompletionMetadata.set(GAME, { generation: 1, ...metadata }); - return gm.getPersistedTerminalUpdate(GAME, requested, "arg-w", 9, "arg-s"); + if (metadata) { + gm["gameMessageCompletionMetadata"].set(GAME, { generation: 1, status: "Completed", ...metadata }); + } + return gm["getPersistedTerminalUpdate"](GAME, requested, "arg-w", 9, "arg-s"); }; const fromArgs = { - status: "Completed", + status: "Completed" as const, winnerAddress: "arg-w", totalPot: 9, winnerSignature: "arg-s", @@ -218,7 +230,7 @@ describe("recovery account read", () => { ["a missing account", undefined, null], ])("a nullable read of %s", async (_name, account, expected) => { const gm = makeManager({}, { account: { game: { fetchNullable: async () => account } } }); - expect(await gm.fetchGameAccountForRecovery(GAME)).toEqual(expected); + expect(await gm["fetchGameAccountForRecovery"](GAME)).toEqual(expected); }); }); @@ -241,7 +253,7 @@ describe("unavailable state recovery schedule", () => { globalThis.setTimeout = original; }); - const ctx = { chat: { id: 77 } }; + const ctx = fake({ chat: { id: 77 } }); test.each([ ["a chat without an ID", {}, 0], @@ -249,9 +261,9 @@ describe("unavailable state recovery schedule", () => { ["the last attempt", ctx, 3], ])("%s is not scheduled", (_name, context, attempt) => { const gm = makeManager({ getGame: () => ({}) }); - gm.scheduleUnavailableStateRecovery(context, GAME, "coinflip", attempt); + gm["scheduleUnavailableStateRecovery"](fake(context), GAME, "coinflip", attempt); expect(scheduled).toEqual([]); - expect(gm.unavailableStateRecoveryTimers.size).toBe(0); + expect(gm["unavailableStateRecoveryTimers"].size).toBe(0); }); test("each attempt uses its delay, is keyed by game and chat, and does not hold the process", () => { @@ -259,9 +271,9 @@ describe("unavailable state recovery schedule", () => { for (const attempt of [0, 1, 2]) { GameManager.resetForTest(); const gm = makeManager({ getGame: () => ({}) }); - gm.scheduleUnavailableStateRecovery(ctx, GAME, "coinflip", attempt); - expect([...gm.unavailableStateRecoveryTimers.keys()]).toEqual([`${GAME}:77`]); - delays.push(scheduled.at(-1)!.delay); + gm["scheduleUnavailableStateRecovery"](ctx, GAME, "coinflip", attempt); + expect([...gm["unavailableStateRecoveryTimers"].keys()]).toEqual([`${GAME}:77`]); + delays.push(itemAt(scheduled, -1).delay); } expect(delays).toEqual([1_000, 5_000, 15_000]); expect(scheduled.map((entry) => entry.unrefs)).toEqual([1, 1, 1]); @@ -270,9 +282,9 @@ describe("unavailable state recovery schedule", () => { test("a timer without unref is still scheduled", () => { withUnref = false; const gm = makeManager({ getGame: () => ({}) }); - gm.scheduleUnavailableStateRecovery(ctx, GAME, "coinflip"); + gm["scheduleUnavailableStateRecovery"](ctx, GAME, "coinflip"); expect(scheduled).toHaveLength(1); - expect(gm.unavailableStateRecoveryTimers.size).toBe(1); + expect(gm["unavailableStateRecoveryTimers"].size).toBe(1); }); const afterRefresh = async (stored: unknown, refreshFails = false) => { @@ -284,8 +296,8 @@ describe("unavailable state recovery schedule", () => { spyOn(gm, "updateGameMessageFromData").mockImplementation(async () => { if (refreshFails) throw new Error("synthetic refresh failure"); }); - gm.scheduleUnavailableStateRecovery(ctx, GAME, "coinflip"); - await scheduled[0]!.callback(); + gm["scheduleUnavailableStateRecovery"](ctx, GAME, "coinflip"); + await itemAt(scheduled, 0).callback(); return scheduled.slice(1).map((entry) => entry.delay); }; @@ -315,22 +327,22 @@ describe("username cache keys", () => { ["the sender ID without a chat", { from: { id: 6 } }, "6:t"], ["the global scope without a chat or sender", {}, "global:t"], ])("a key uses %s", (_name, ctx, key) => { - expect(makeManager().buildUsernameCacheKey(ctx, "t")).toBe(key); + expect(makeManager()["buildUsernameCacheKey"](fake(ctx), "t")).toBe(key); }); test("a tracked name key moves to the end without a copy", () => { const gm = makeManager(); - for (const key of ["a", "b", "a"]) gm.setCachedUsername(key, "@n"); - expect(gm.usernameCacheKeys).toEqual(["b", "a"]); - for (const key of ["x", "y", "x"]) gm.setCachedTelegramIdForUsername(key, "1"); - expect(gm.usernameToIdCacheKeys).toEqual(["y", "x"]); + for (const key of ["a", "b", "a"]) gm["setCachedUsername"](key, "@n"); + expect(gm["usernameCacheKeys"]).toEqual(["b", "a"]); + for (const key of ["x", "y", "x"]) gm["setCachedTelegramIdForUsername"](key, "1"); + expect(gm["usernameToIdCacheKeys"]).toEqual(["y", "x"]); }); test("a failed name lookup is kept for at most 30 seconds", () => { const gm = makeManager(); - const ttl = spyOn(gm.usernameCache, "setWithTTL"); - gm.setCachedUsername("a", null); - gm.setCachedUsername("b", "@n"); + const ttl = spyOn(gm["usernameCache"], "setWithTTL"); + gm["setCachedUsername"]("a", null); + gm["setCachedUsername"]("b", "@n"); expect(ttl.mock.calls).toEqual([ ["a", null, Math.min(TELEGRAM_USERNAME_CACHE_TTL_MS, 30_000)], ["b", "@n", TELEGRAM_USERNAME_CACHE_TTL_MS], diff --git a/tests/helpers/fakes.ts b/tests/helpers/fakes.ts new file mode 100644 index 00000000..de0d3e79 --- /dev/null +++ b/tests/helpers/fakes.ts @@ -0,0 +1,43 @@ +import { GameManager } from "../../src/utils/game"; +import type { TimbaProgram } from "../../src/utils/timba-program"; +import type { WalletManager } from "../../src/utils/wallet"; +import type { GameDatabase } from "../../src/utils/game-database"; + +/** + * The members that a test fake sets. Each key must be a real member of `T`, so a renamed + * member breaks the test at compile time. The values stay loose because a fake returns + * only the fields that the test reads. + */ +export type FakeMembers = { [K in keyof T]?: unknown }; + +/** + * Builds a fake `T` from the members a test needs. This is the one place where a partial + * object stands in for a full dependency. + */ +export function fake(members: FakeMembers = {}): T { + return members as unknown as T; +} + +export type GameManagerFakes = { + program?: FakeMembers; + wallet?: FakeMembers; + db?: FakeMembers; +}; + +/** Returns the GameManager singleton built from typed fakes. */ +export function makeTestGameManager(fakes: GameManagerFakes = {}): GameManager { + return GameManager.getInstance( + fake(fakes.program), + fake(fakes.wallet), + fake(fakes.db), + ); +} + +/** Returns the item at `index` (negative counts from the end), or fails the test. */ +export function itemAt(items: readonly T[], index: number): T { + const item = items.at(index); + if (item === undefined) { + throw new Error(`Expected an item at index ${index}, but the list has ${items.length} items`); + } + return item; +} diff --git a/tests/lightning-handler.test.ts b/tests/lightning-handler.test.ts index 77832255..38dbb60e 100644 --- a/tests/lightning-handler.test.ts +++ b/tests/lightning-handler.test.ts @@ -337,7 +337,7 @@ describe("deposit access", () => { } expect(getInputSession("999_42")).toEqual(otherDeposit); expect(getInputSession("321_43")).toEqual(wrap); - expect(h.store!.active(ownerId)).toBeNull(); + expect(h.store?.active(ownerId)).toBeNull(); }); }, ); diff --git a/tests/media.retry.test.ts b/tests/media.retry.test.ts index f2eca20b..a04eda6a 100644 --- a/tests/media.retry.test.ts +++ b/tests/media.retry.test.ts @@ -304,8 +304,8 @@ describe("media retry helpers", () => { globalThis.setTimeout = ((callback: () => void, ms?: number) => { delays.push(ms ?? 0); callback(); - return 0 as any; - }) as any; + return 0; + }) as unknown as typeof setTimeout; let attempts = 0; try { await expect( diff --git a/tests/program-event-parser.test.ts b/tests/program-event-parser.test.ts index fe1c40d3..d4c84d4a 100644 --- a/tests/program-event-parser.test.ts +++ b/tests/program-event-parser.test.ts @@ -8,6 +8,7 @@ import { parseProgramEventLogs, parseProgramEventsFromTransaction, } from "../src/utils/program-event-parser"; +import { itemAt } from "./helpers/fakes"; const GAME = new PublicKey("11111111111111111111111111111112"); const PLAYER = new PublicKey("So11111111111111111111111111111111111111112"); @@ -249,8 +250,8 @@ describe("parseProgramEventLogs", () => { expect(events).toHaveLength(1); expect(events[0]!.name).toBe("PlayerRefunded"); - expect(events[0]!.data["movedParticipant"]).toBeNull(); - expect(events[0]!.data["totalAmount"]).toBe(42n); + expect(itemAt(events, 0).data["movedParticipant"]).toBeNull(); + expect(itemAt(events, 0).data["totalAmount"]).toBe(42n); }); test("still surfaces fee events when a prior log would have thrown under the current IDL", () => { @@ -289,8 +290,8 @@ describe("parseProgramEventLogs", () => { ]); expect(events.map((e) => e.name)).toEqual(["GameCompleted"]); - expect(events[0]!.data["feeAmount"]).toBe(3n); - expect(events[0]!.data["winner"]).toEqual(PLAYER); - expect(events[0]!.data).not.toHaveProperty("gameType"); + expect(itemAt(events, 0).data["feeAmount"]).toBe(3n); + expect(itemAt(events, 0).data["winner"]).toEqual(PLAYER); + expect(itemAt(events, 0).data).not.toHaveProperty("gameType"); }); }); diff --git a/tests/swap-manager.token-account-wait.test.ts b/tests/swap-manager.token-account-wait.test.ts index 3dfd5914..f9665263 100644 --- a/tests/swap-manager.token-account-wait.test.ts +++ b/tests/swap-manager.token-account-wait.test.ts @@ -2,6 +2,8 @@ import { describe, expect, test, vi } from "bun:test"; import { Keypair, PublicKey } from "#solana"; import { SwapManager } from "../src/utils/swap-manager"; import { mockDateNowWithReadLimit } from "./helpers/timers"; +import type { SwapQuote, SwapRequest } from "../src/utils/swap/types"; +import { fake } from "./helpers/fakes"; const WSOL = "So11111111111111111111111111111111111111112"; @@ -128,19 +130,19 @@ describe("SwapManager token-account setup wait", () => { const user = await Keypair.generate(); await expect( sm.executeJupiterSwap( - { + fake({ inputMint: WSOL, outputMint: created.toBase58(), amount: "1", userKeypair: user, - } as any, - { + }), + fake({ inputMint: WSOL, outputMint: created.toBase58(), inputAmountRaw: "1", - providerQuote: {} as any, + providerQuote: {}, providerQuoteTimestamp: 0, - } as any, + }), ), ).rejects.toThrow("quote expired"); diff --git a/tests/swap-service.edge-cases.test.ts b/tests/swap-service.edge-cases.test.ts index 0de78f0b..c6ad00fe 100644 --- a/tests/swap-service.edge-cases.test.ts +++ b/tests/swap-service.edge-cases.test.ts @@ -2,19 +2,22 @@ import { afterEach, beforeEach, describe, expect, spyOn, test } from "bun:test"; import { Keypair } from "#solana"; import { SwapService, type SwapBackend } from "../src/utils/swap/service"; import { TransactionHistory } from "../src/utils/transaction-history"; +import { fake } from "./helpers/fakes"; +import type { WalletManager } from "../src/utils/wallet"; const formatSol = (lamports: number) => `${lamports / 1e9}`; -const makeWallet = (balance: number, fee: number | bigint | null = 5_000) => ({ - getConnection: () => ({ - rpcEndpoint: "http://test-swap-service", - getBalance: async () => balance, - getAccountInfo: async () => null, - getMinimumBalanceForRentExemption: async () => 2_039_280, - getTransaction: async () => (fee === null ? null : { meta: { fee } }), - }), - formatSolBalance: formatSol, -}); +const makeWallet = (balance: number, fee: number | bigint | null = 5_000) => + fake({ + getConnection: () => ({ + rpcEndpoint: "http://test-swap-service", + getBalance: async () => balance, + getAccountInfo: async () => null, + getMinimumBalanceForRentExemption: async () => 2_039_280, + getTransaction: async () => (fee === null ? null : { meta: { fee } }), + }), + formatSolBalance: formatSol, + }); const makeBackend = (signature = "sig-test") => { const executed: unknown[] = []; @@ -59,7 +62,7 @@ describe("SwapService", () => { test("treats an amount beyond the safe integer range as exceeding the balance", async () => { const { backend } = makeBackend(); - const service = new SwapService(makeWallet(1_000_000) as any, backend); + const service = new SwapService(makeWallet(1_000_000), backend); const user = await Keypair.generate(); const hugeAmount = (BigInt(Number.MAX_SAFE_INTEGER) * 4n).toString(); @@ -74,7 +77,7 @@ describe("SwapService", () => { test("clamps the reported deficit when the shortfall exceeds the safe integer range", async () => { const { backend } = makeBackend(); const maxSafe = Number.MAX_SAFE_INTEGER; - const service = new SwapService(makeWallet(maxSafe) as any, backend); + const service = new SwapService(makeWallet(maxSafe), backend); const user = await Keypair.generate(); const hugeAmount = (BigInt(maxSafe) * 4n).toString(); @@ -88,7 +91,7 @@ describe("SwapService", () => { test("records sponsor cost from the confirmed fee and omits an absent reimbursement", async () => { const { backend, executed } = makeBackend("sig-sponsor"); - const service = new SwapService(makeWallet(10_000_000, 7_500n) as any, backend); + const service = new SwapService(makeWallet(10_000_000, 7_500n), backend); const user = await Keypair.generate(); const quote = adminQuote({ providerQuote: { signatureFeeLamports: 5_000, prioritizationFeeLamports: 1_000 }, @@ -107,7 +110,7 @@ describe("SwapService", () => { test("estimates sponsor cost from the quote when the confirmed fee is unavailable", async () => { const { backend } = makeBackend("sig-estimated"); - const service = new SwapService(makeWallet(10_000_000, null) as any, backend); + const service = new SwapService(makeWallet(10_000_000, null), backend); const user = await Keypair.generate(); await service.execute( @@ -126,7 +129,7 @@ describe("SwapService", () => { test("still returns the signature when recording swap statistics fails", async () => { const { backend } = makeBackend("sig-recorded-badly"); - const service = new SwapService(makeWallet(10_000_000) as any, backend); + const service = new SwapService(makeWallet(10_000_000), backend); const user = await Keypair.generate(); const failure = new Error("history db locked"); recordSpy.mockImplementation(() => { diff --git a/tests/wallet-handler.edge.test.ts b/tests/wallet-handler.edge.test.ts index ff03a6ce..74fc9411 100644 --- a/tests/wallet-handler.edge.test.ts +++ b/tests/wallet-handler.edge.test.ts @@ -3,6 +3,7 @@ import { InlineKeyboard } from "grammy"; import { onBalance, onMainWallet, onWalletSettings, showWalletUI } from "../src/handlers/wallet"; import { MISSING_TELEGRAM_ID_MESSAGE } from "../src/utils/context-helpers"; import { RateLimitExceededError } from "../src/utils/rate-limiter"; +import { itemAt } from "./helpers/fakes"; const ADDRESS = "WALLETADDR11111111111111111111111111111111"; const NOW = 9_000_000; @@ -287,7 +288,10 @@ describe("background refresh targets", () => { await showWalletUI(ctx, cachedDeps(3e9)); await ctx.__walletBackgroundRefresh; - const edit = calls.find(([kind]) => kind === "apiEditCaption")!; + const edit = itemAt( + calls.filter(([kind]) => kind === "apiEditCaption"), + 0, + ); expect(edit.slice(1, 3)).toEqual([1, 700]); expect(edit[3].caption).toContain("SOL=3"); }); @@ -307,7 +311,10 @@ describe("background refresh targets", () => { await showWalletUI(ctx, cachedDeps(3e9)); await ctx.__walletBackgroundRefresh; - const edit = calls.find(([kind]) => kind === "apiEditCaption")!; + const edit = itemAt( + calls.filter(([kind]) => kind === "apiEditCaption"), + 0, + ); expect(edit.slice(1, 3)).toEqual([1, 33]); }, ); diff --git a/tests/wallet-ui.handler.test.ts b/tests/wallet-ui.handler.test.ts index 1f1ec9af..4c5e44de 100644 --- a/tests/wallet-ui.handler.test.ts +++ b/tests/wallet-ui.handler.test.ts @@ -100,7 +100,7 @@ describe("wallet handler showWalletUI", () => { capturedLines = lines; return "CAPTION"; }, - createWalletKeyboard: () => ({ rows: [] }) as any, + createWalletKeyboard: () => new InlineKeyboard(), WINNER_VIDEO_ID: "VID", }; await showWalletUI(ctx, deps); @@ -151,7 +151,7 @@ describe("wallet handler showWalletUI", () => { capturedLines = lines; return "CAPTION"; }, - createWalletKeyboard: () => ({ rows: [] }) as any, + createWalletKeyboard: () => new InlineKeyboard(), WINNER_VIDEO_ID: "VID", }; @@ -192,7 +192,7 @@ describe("wallet handler showWalletUI", () => { return record; }, buildWalletCaption: () => "CAPTION", - createWalletKeyboard: () => ({ rows: [] }) as any, + createWalletKeyboard: () => new InlineKeyboard(), WINNER_VIDEO_ID: "VID", }; await showWalletUI(ctx, deps); @@ -229,7 +229,7 @@ describe("wallet handler showWalletUI", () => { return record; }, buildWalletCaption: () => "CAPTION", - createWalletKeyboard: () => ({ rows: [] }) as any, + createWalletKeyboard: () => new InlineKeyboard(), WINNER_VIDEO_ID: "VID", }; @@ -308,7 +308,7 @@ describe("wallet handler showWalletUI", () => { getCachedWalletData: async () => ({ solBalance: 0n, tokenBalances: [] }), fetchPricesUSD: async () => ({}), buildWalletCaption: () => "CAPTION", - createWalletKeyboard: () => ({ rows: [] }) as any, + createWalletKeyboard: () => new InlineKeyboard(), WINNER_VIDEO_ID: "VID", }; diff --git a/tests/wallet.transactions.test.ts b/tests/wallet.transactions.test.ts index bd4f5804..9f225e97 100644 --- a/tests/wallet.transactions.test.ts +++ b/tests/wallet.transactions.test.ts @@ -633,7 +633,7 @@ describe("confirmTransaction polling", () => { const signature = "SIG_GRACE"; const clock = useWalletConfirmationClock(wallet); elapsed = clock.elapsed; - (wallet as any).pendingSignatures.set(signature, { + wallet["pendingSignatures"].set(signature, { blockhash: "BH", lastValidBlockHeight: 100, recordedAt: Date.now(), @@ -643,7 +643,7 @@ describe("confirmTransaction polling", () => { "expired before confirmation (last valid block height 100, current 103)", ); expect(heights).toEqual([1_200, 2_400]); - expect((wallet as any).pendingSignatures.has(signature)).toBe(false); + expect(wallet["pendingSignatures"].has(signature)).toBe(false); } finally { clock.restore(); } @@ -660,7 +660,7 @@ describe("confirmTransaction polling", () => { }); fastProbe(wallet); (wallet as any).postTimeoutProbeBackoffMs = 5; - (wallet as any).pendingSignatures.set("SIG_HEIGHT", { + wallet["pendingSignatures"].set("SIG_HEIGHT", { blockhash: "BH", lastValidBlockHeight: 10, recordedAt: Date.now(), @@ -676,7 +676,7 @@ describe("confirmTransaction polling", () => { ), ).toBe(true); expect(instantTimers.delays).toContain(5); // the post-timeout backoff - expect((wallet as any).pendingSignatures.has("SIG_HEIGHT")).toBe(false); + expect(wallet["pendingSignatures"].has("SIG_HEIGHT")).toBe(false); } finally { clock.restore(); } @@ -751,7 +751,7 @@ describe("confirmTransaction polling", () => { getTransaction: readConfirmed, }); elapsed = clock.elapsed; - (wallet as any).pendingSignatures.set(signature, { + wallet["pendingSignatures"].set(signature, { blockhash: "BH", lastValidBlockHeight: 100, recordedAt: Date.now(), @@ -774,7 +774,7 @@ describe("confirmTransaction polling", () => { getBlockHeight: async () => (elapsed() >= CONFIRMATION_TIMEOUT_MS ? 200 : 50), }); elapsed = clock.elapsed; - (wallet as any).pendingSignatures.set("SIG_LATE_EXPIRED", { + wallet["pendingSignatures"].set("SIG_LATE_EXPIRED", { blockhash: "BH", lastValidBlockHeight: 100, recordedAt: Date.now(), @@ -806,7 +806,7 @@ describe("confirmTransaction polling", () => { getTransaction: history, }); elapsed = clock.elapsed; - (wallet as any).pendingSignatures.set(signature, { + wallet["pendingSignatures"].set(signature, { blockhash: "BH", lastValidBlockHeight: 100, recordedAt: Date.now(), @@ -1157,7 +1157,7 @@ describe("game transaction submission", () => { await expect(wallet.sendFullySignedGameTransaction(tx, blockhash)).rejects.toThrow( `RPC returned an unexpected game transaction signature: expected ${signature}, received SomeOtherSignature`, ); - expect((wallet as any).pendingSignatures.has(signature)).toBe(false); + expect(wallet["pendingSignatures"].has(signature)).toBe(false); }); }); From 244d8b7af242273ff1811db57f3649e81673f18e Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Mon, 30 Nov 2026 05:18:55 -0300 Subject: [PATCH 333/410] refactor(game-setup): share the setup balance and minimum lookup The custom amount and back-to-amounts handlers had the same balance and minimum lookup. Move it to resolveSetupBalance and resolveSetupMinimum. Add tests for the custom amount prompt, the legacy players prompt and typed setup input, and mark the equivalent null player check. --- src/handlers/game-callbacks.ts | 78 +++-- tests/game-callbacks.prompt-target.test.ts | 329 ++++++++++++++++++++- 2 files changed, 352 insertions(+), 55 deletions(-) diff --git a/src/handlers/game-callbacks.ts b/src/handlers/game-callbacks.ts index 8d0bb120..c46347c8 100644 --- a/src/handlers/game-callbacks.ts +++ b/src/handlers/game-callbacks.ts @@ -234,6 +234,35 @@ export const createGameCallbacksModule = (deps: GameCallbacksModuleDeps): GameCa const getGameManager = () => deps.getGameManager(); const isFromDM = (ctx: Context): boolean => ctx.chat?.type === "private"; + /** + * Returns the stored positive balance, or reads the wallet balance in token units. + * A failed read is logged and gives 0, so the setup can continue. + */ + const resolveSetupBalance = async ( + creatorContext: Pick, + telegramId: bigint, + ): Promise => { + const { session, tokenContext } = creatorContext; + const storedBalance = session?.userBalance ?? 0; + if (storedBalance > 0) return storedBalance; + try { + const tokenBalance = await deps.wallet.getTokenBalance(telegramId, tokenContext.tokenMint); + return tokenBalance / Math.pow(10, tokenContext.tokenDecimals); + } catch (error) { + console.error("Error getting balance:", error); + return 0; + } + }; + + /** Returns the stored contract minimum, or the token policy minimum when none is stored. */ + const resolveSetupMinimum = async ( + tokenContext: CreatorCallbackContext["tokenContext"], + ): Promise => + tokenContext.contractMinimum !== undefined + ? tokenContext.contractMinimum + : (await deps.getTokenPolicyMinimumAmount(tokenContext.tokenMint, tokenContext.tokenDecimals)) + .formatted; + const resolveTokenPriceUSDForSetup = async (input: { tokenMint: string; sessionPrice?: number; @@ -693,6 +722,7 @@ export const createGameCallbacksModule = (deps: GameCallbacksModuleDeps): GameCa `🔍 Custom players input: "${inputText}" -> ${players} (gameType: ${userSession.gameType}, min: ${minPlayers}, max: ${maxPlayers})`, ); + // Stryker disable next-line ConditionalExpression: null is below every player minimum, so the range check also rejects it. if (players === null || players < minPlayers || players > maxPlayers) { await retryAtPrompt( `❌ Invalid number of players. Please enter a number between ${minPlayers} and ${maxPlayers}.`, @@ -1748,27 +1778,8 @@ export const createGameCallbacksModule = (deps: GameCallbacksModuleDeps): GameCa // withCreatorSessionContext already refused callbacks without a sender id. const telegramId = requireTelegramId(ctx, "type amount prompt"); - let userBalance = - session?.userBalance && session.userBalance > 0 ? session.userBalance : 0; - if (userBalance <= 0) { - try { - const tokenBalance = await deps.wallet.getTokenBalance( - telegramId, - tokenContext.tokenMint, - ); - userBalance = tokenBalance / Math.pow(10, tokenContext.tokenDecimals); - } catch (error) { - console.error("Error getting balance:", error); - } - } - - const { formatted: contractMin } = - tokenContext.contractMinimum !== undefined - ? { formatted: tokenContext.contractMinimum } - : await deps.getTokenPolicyMinimumAmount( - tokenContext.tokenMint, - tokenContext.tokenDecimals, - ); + const userBalance = await resolveSetupBalance({ session, tokenContext }, telegramId); + const contractMin = await resolveSetupMinimum(tokenContext); const response = await presentCustomAmountPrompt({ ctx, @@ -1902,8 +1913,8 @@ export const createGameCallbacksModule = (deps: GameCallbacksModuleDeps): GameCa .row(), }); + // storeSetupPromptSession keeps the stored setup fields on both paths. storeSetupPromptSession(ctx, creatorContext, response, { - ...(creatorContext.session ?? {}), waitingFor: "players_input", gameType, amount, @@ -1962,27 +1973,8 @@ export const createGameCallbacksModule = (deps: GameCallbacksModuleDeps): GameCa // before any wallet, contract, price, or Telegram request. clearSession(); - let userBalance = - session?.userBalance && session.userBalance > 0 ? session.userBalance : 0; - if (userBalance <= 0) { - try { - const tokenBalance = await deps.wallet.getTokenBalance( - telegramId, - tokenContext.tokenMint, - ); - userBalance = tokenBalance / Math.pow(10, tokenContext.tokenDecimals); - } catch (error) { - console.error("Error getting balance:", error); - } - } - - const { formatted: contractMin } = - tokenContext.contractMinimum !== undefined - ? { formatted: tokenContext.contractMinimum } - : await deps.getTokenPolicyMinimumAmount( - tokenContext.tokenMint, - tokenContext.tokenDecimals, - ); + const userBalance = await resolveSetupBalance({ session, tokenContext }, telegramId); + const contractMin = await resolveSetupMinimum(tokenContext); const tokenPriceUSD = await deps.fetchTokenPriceUSD({ tokenMint: tokenContext.tokenMint, diff --git a/tests/game-callbacks.prompt-target.test.ts b/tests/game-callbacks.prompt-target.test.ts index 520b53b3..9696a4d3 100644 --- a/tests/game-callbacks.prompt-target.test.ts +++ b/tests/game-callbacks.prompt-target.test.ts @@ -1,14 +1,19 @@ -import { afterEach, beforeEach, expect, mock, spyOn, test } from "bun:test"; -import type { Bot, Context } from "grammy"; +import { afterEach, beforeEach, describe, expect, mock, spyOn, test } from "bun:test"; +import { InlineKeyboard, type Bot, type Context } from "grammy"; import { createGameCallbacksModule } from "../src/handlers/game-callbacks"; import { GAME_SETUP_COPY, createGameSetupModule } from "../src/handlers/game-setup"; import { encodeCustomPlayersPayload } from "../src/utils/callback-data"; +import { DEFAULT_GAME_TIMEOUT } from "../src/utils/constants"; import { getTelegramId, getTelegramIdString, safeAnswerCallbackQuery, } from "../src/utils/context-helpers"; -import { createAmountSelectionKeyboard, getSuggestedStakeAmounts } from "../src/utils/keyboards"; +import { + createAmountSelectionKeyboard, + createPlayerSelectionKeyboard, + getSuggestedStakeAmounts, +} from "../src/utils/keyboards"; import { clearAllGameSetupSessions, clearGameSetupSession, @@ -36,7 +41,18 @@ afterEach(() => { clearAllGameSetupSessions(); }); -function makeHandlers() { +type HandlerOptions = { + tokenBalance?: () => Promise; + policyMinimum?: number; +}; + +type InvokeOptions = { + // Leave out ctx.chat, as for a callback that Telegram sends without a chat. + withoutChat?: boolean; + replyResult?: () => Promise; +}; + +function makeHandlers(options: HandlerOptions = {}) { type Dependencies = Parameters[0]; const registered: Array<{ pattern: RegExp | string; handle: (ctx: Context) => Promise }> = []; @@ -46,9 +62,16 @@ function makeHandlers() { registered.push({ pattern, handle }); }, } as unknown as Bot; - const wallet = { getTokenBalance: async () => 3_000_000 } as unknown as Dependencies["wallet"]; + const wallet = { + getTokenBalance: options.tokenBalance ?? (async () => 3_000_000), + } as unknown as Dependencies["wallet"]; const getDefaultTokenMetadata = async () => ({ decimals: 6 }); - const getTokenPolicyMinimumAmount = async () => ({ formatted: 1, raw: 1_000_000, decimals: 6 }); + const policyMinimum = options.policyMinimum ?? 1; + const getTokenPolicyMinimumAmount = async () => ({ + formatted: policyMinimum, + raw: policyMinimum * 1_000_000, + decimals: 6, + }); const fetchTokenPriceUSD = async () => null; const setup = createGameSetupModule({ wallet, @@ -89,12 +112,11 @@ function makeHandlers() { gameSetupCopy: GAME_SETUP_COPY, }); callbacks.registerHandlers(); - const invoke = async (data: string, useReply: boolean) => { + const invoke = async (data: string, useReply: boolean, extra: InvokeOptions = {}) => { const answerCallbackQuery = mock(async (_text?: string) => {}); - const reply = mock(async (_text: string, _options?: unknown) => ({ - message_id: SENT, - chat: { id: CHAT }, - })); + const reply = mock(async (_text: string, _options?: unknown): Promise => + extra.replyResult ? extra.replyResult() : { message_id: SENT, chat: { id: CHAT } }, + ); const editMessageText = mock(async (_text: string, _options?: unknown) => { if (useReply) throw new Error("fixture edit unavailable"); return true; @@ -105,7 +127,7 @@ function makeHandlers() { if (!match) continue; const ctx = { from: { id: Number(CREATOR) }, - chat: { id: CHAT, type: "supergroup" }, + ...(extra.withoutChat ? {} : { chat: { id: CHAT, type: "supergroup" } }), match, callbackQuery: { id: "fixture-callback", @@ -345,3 +367,286 @@ test.each([ }); }, ); + +describe("custom amount prompt", () => { + const amountData = `custom_amount_coinflip_${CREATOR}`; + + test("keeps a stored positive balance without a wallet read", async () => { + seedSession(); + let reads = 0; + const { invoke } = makeHandlers({ + tokenBalance: async () => { + reads += 1; + return 3_000_000; + }, + }); + await invoke(amountData, false); + expect(reads).toBe(0); + expect(getGameSetupSession(oldKey)).toMatchObject({ + waitingFor: "amount_input", + userBalance: 10, + }); + }); + + test.each([ + ["no stored balance", undefined], + ["a zero balance", 0], + ["a negative balance", -5], + ])("reads the wallet balance in token units for %s", async (_label, userBalance) => { + seedSession(); + upsertGameSetupSession(oldKey, { userBalance }); + const { invoke } = makeHandlers(); + await invoke(amountData, false); + // 3_000_000 raw units with 6 decimals. + expect(getGameSetupSession(oldKey)).toMatchObject({ + waitingFor: "amount_input", + userBalance: 3, + }); + }); + + test("logs a failed wallet read and keeps a zero balance", async () => { + seedSession(); + upsertGameSetupSession(oldKey, { userBalance: 0 }); + const failure = new Error("balance unavailable"); + const error = spyOn(console, "error").mockImplementation(() => {}); + spies.push(error); + const { invoke } = makeHandlers({ + tokenBalance: async () => { + throw failure; + }, + }); + const { answerCallbackQuery } = await invoke(amountData, false); + expect(error.mock.calls).toEqual([["Error getting balance:", failure]]); + expect(answerCallbackQuery.mock.calls).toEqual([["Type your amount..."]]); + expect(getGameSetupSession(oldKey)).toMatchObject({ + waitingFor: "amount_input", + userBalance: 0, + }); + }); + + test("uses the stored contract minimum before the token policy", async () => { + seedSession(); + const { invoke } = makeHandlers({ policyMinimum: 5 }); + await invoke(amountData, false); + expect(getGameSetupSession(oldKey)).toMatchObject({ contractMinimum: 1 }); + }); + + test("reads the token policy minimum when no minimum is stored", async () => { + const { invoke } = makeHandlers({ policyMinimum: 5 }); + await invoke(amountData, false); + expect(getGameSetupSession(oldKey)).toMatchObject({ + waitingFor: "amount_input", + contractMinimum: 5, + }); + }); + + test("a callback without a chat keeps the prompt on the callback message", async () => { + seedSession(); + const { invoke } = makeHandlers(); + // The edit fails and the reply returns no message, so the prompt target is the callback. + const { answerCallbackQuery } = await invoke(amountData, true, { + withoutChat: true, + replyResult: async () => ({}), + }); + expect(answerCallbackQuery.mock.calls).toEqual([["Type your amount..."]]); + expect(getGameSetupSession(`0_${OLD}`)).toMatchObject({ + waitingFor: "amount_input", + chatId: 0, + messageId: OLD, + }); + }); + + test("a reply in another chat stores the prompt under that chat", async () => { + seedSession(); + const { invoke } = makeHandlers(); + await invoke(amountData, true, { + replyResult: async () => ({ message_id: SENT, chat: { id: -200 } }), + }); + expect(getGameSetupSession(oldKey)).toBeUndefined(); + expect(getGameSetupSession(sentKey)).toBeUndefined(); + expect(getGameSetupSession(`-200_${SENT}`)).toMatchObject({ + waitingFor: "amount_input", + chatId: -200, + messageId: SENT, + }); + }); + + test("a failed prompt is logged and answered with an error", async () => { + seedSession(); + const failure = new Error("reply refused"); + const error = spyOn(console, "error").mockImplementation(() => {}); + spies.push(error); + const { invoke } = makeHandlers(); + const { answerCallbackQuery } = await invoke(amountData, true, { + replyResult: async () => { + throw failure; + }, + }); + expect(error.mock.calls).toEqual([ + ["Error in creator-protected custom_amount callback:", failure], + ]); + expect(answerCallbackQuery.mock.calls).toEqual([["❌ Error setting up text input"]]); + }); +}); + +describe("legacy custom players prompt", () => { + test("a giveaway without a stored setup shows its range, keyboard and defaults", async () => { + const { invoke } = makeHandlers(); + const { answerCallbackQuery, editMessageText } = await invoke( + `custom_players_giveaway_1.23456_${CREATOR}`, + false, + ); + expect(answerCallbackQuery.mock.calls).toEqual([["Type the number of players..."]]); + expect(editMessageText.mock.calls).toEqual([ + [ + "👥 Type Custom Players - Giveaway\n\nAmount: 1.23456 " + + `${getGameSetupSession(oldKey)?.tokenTicker}\n\n` + + "Please type the number of players for this game.\n\nRange: 1-20 players", + { + parse_mode: "HTML", + link_preview_options: { is_disabled: true }, + reply_markup: new InlineKeyboard() + .text("❌ Cancel", `cancel_game_setup_${CREATOR}`) + .row(), + }, + ], + ]); + expect(getGameSetupSession(oldKey)).toMatchObject({ + waitingFor: "players_input", + gameType: "giveaway", + userBalance: 0, + amount: "1.23456", + maxPlayersLimit: 20, + timeoutSeconds: DEFAULT_GAME_TIMEOUT, + isPrivate: false, + }); + }); + + test("a coinflip keeps the stored private flag and starts at two players", async () => { + seedSession(); + upsertGameSetupSession(oldKey, { isPrivate: true }); + const { invoke } = makeHandlers(); + const { editMessageText } = await invoke(`custom_players_coinflip_2_${CREATOR}`, false); + expect(editMessageText.mock.calls[0]?.[0]).toContain("Range: 2-20 players"); + expect(getGameSetupSession(oldKey)).toMatchObject({ isPrivate: true, timeoutSeconds: 4_500 }); + }); + + test("a failed prompt is logged and answered with an error", async () => { + seedSession(); + const failure = new Error("reply refused"); + const error = spyOn(console, "error").mockImplementation(() => {}); + spies.push(error); + const { invoke } = makeHandlers(); + const { answerCallbackQuery } = await invoke(`custom_players_coinflip_2_${CREATOR}`, true, { + replyResult: async () => { + throw failure; + }, + }); + expect(error.mock.calls).toEqual([ + ["Error in creator-protected custom_players callback:", failure], + ]); + expect(answerCallbackQuery.mock.calls).toEqual([["❌ Error setting up players input"]]); + }); +}); + +describe("typed setup input", () => { + const typeInto = async ( + text: string, + replyResult: () => Promise = async () => ({ message_id: SENT, chat: { id: CHAT } }), + editFails = true, + ) => { + const { callbacks } = makeHandlers(); + const editMessageText = mock( + async (_chat: number, _id: number, _text: string, _options: unknown) => { + if (editFails) throw new Error("fixture edit failed"); + return true; + }, + ); + const reply = mock(async (_text: string, _options: unknown) => replyResult()); + const next = mock(async () => {}); + const ctx = { + from: { id: Number(CREATOR) }, + chat: { id: CHAT, type: "supergroup" }, + message: { text, reply_to_message: { message_id: OLD } }, + api: { editMessageText }, + reply, + } as unknown as Context; + await callbacks.__test_handleGameSetupTextInput(ctx, next); + return { editMessageText, reply, next }; + }; + + test("an accepted amount shows the player choice with its keyboard", async () => { + seedSession(); + upsertGameSetupSession(oldKey, { waitingFor: "amount_input", maxPlayersLimit: 20 }); + const { editMessageText } = await typeInto("3", undefined, false); + expect(editMessageText.mock.calls).toEqual([ + [ + CHAT, + OLD, + expect.stringContaining("Choose Maximum Players"), + { + parse_mode: "HTML", + reply_markup: createPlayerSelectionKeyboard("coinflip", "3", CREATOR), + }, + ], + ]); + }); + + test("the largest allowed player count is accepted", async () => { + seedSession(); + upsertGameSetupSession(oldKey, { waitingFor: "players_input", maxPlayersLimit: 20 }); + const { editMessageText } = await typeInto("20", undefined, false); + expect(editMessageText.mock.calls[0]?.[2]).toContain("Confirm Coinflip"); + expect(getGameSetupSession(oldKey)).toMatchObject({ waitingFor: "setup", players: 20 }); + }); + + test("a message without a chat uses chat 0 for the stored setup", async () => { + upsertGameSetupSession(`0_${OLD}`, { + waitingFor: "players_input", + creatorId: CREATOR, + gameType: "coinflip", + amount: "2", + maxPlayersLimit: 20, + }); + const { callbacks } = makeHandlers(); + const editMessageText = mock( + async (_chat: number, _id: number, _text: string, _options: unknown) => true, + ); + const ctx = { + from: { id: Number(CREATOR) }, + message: { text: "21", reply_to_message: { message_id: OLD } }, + api: { editMessageText }, + } as unknown as Context; + await callbacks.__test_handleGameSetupTextInput( + ctx, + mock(async () => {}), + ); + expect(editMessageText.mock.calls).toEqual([ + [ + 0, + OLD, + "❌ Invalid number of players. Please enter a number between 2 and 20.", + { parse_mode: "HTML" }, + ], + ]); + }); + + test("a setup without a stored target uses the reply target and keeps it after an empty reply", async () => { + seedSession(); + upsertGameSetupSession(oldKey, { + waitingFor: "players_input", + maxPlayersLimit: 20, + chatId: undefined, + messageId: undefined, + }); + const error = "❌ Invalid number of players. Please enter a number between 2 and 20."; + const { editMessageText, reply } = await typeInto("21", async () => undefined); + expect(editMessageText.mock.calls).toEqual([[CHAT, OLD, error, { parse_mode: "HTML" }]]); + expect(reply.mock.calls).toEqual([[error, { parse_mode: "HTML" }]]); + expect(getGameSetupSession(oldKey)).toMatchObject({ + waitingFor: "players_input", + chatId: CHAT, + messageId: OLD, + }); + }); +}); From 81c74791c5401ddcc3211c5bfb7e24fe6fa5264c Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Mon, 30 Nov 2026 05:24:31 -0300 Subject: [PATCH 334/410] refactor(buy-alerts): drop the baseline pool maps from the trade poller The baseline pool set always held the pools that had no complete snapshot yet, so it repeated the primed set. The poller now applies the watch start filter to every unprimed pool. Discovery returns poll targets with the trimmed pair address, which removes two non-null assertions. Add edge tests for late pools, failed first reads, handlers that remove mints, the request slot limits and the timer unref. --- src/services/buy-alerts/pool-trades.ts | 104 +++------- .../buy-alerts.pool-trades-edge-cases.test.ts | 178 +++++++++++++++++- 2 files changed, 205 insertions(+), 77 deletions(-) diff --git a/src/services/buy-alerts/pool-trades.ts b/src/services/buy-alerts/pool-trades.ts index d7c44a26..ebc6259b 100644 --- a/src/services/buy-alerts/pool-trades.ts +++ b/src/services/buy-alerts/pool-trades.ts @@ -128,6 +128,7 @@ export function parseGeckoPoolTrade( const trader = (attrs.tx_from_address ?? "").trim(); const tokenAmount = parseFiniteNumber(attrs.to_token_amount); const fromAmount = parseFiniteNumber(attrs.from_token_amount); + // Stryker disable next-line ConditionalExpression: null <= 0 is true, so the amount check also rejects null. TypeScript needs the null check. if (!signature || !trader || tokenAmount == null || tokenAmount <= 0) { return null; } @@ -184,7 +185,7 @@ export type PoolTradePoller = BuyFeed & { }; type MintWatch = { since: number }; -type PollTarget = { mint: string; pair: PairStats; watch: MintWatch }; +type PollTarget = { mint: string; pairAddress: string; pair: PairStats; watch: MintWatch }; export function createPoolTradePoller(options: PoolTradePollerOptions = {}): PoolTradePoller { const fetchPoolStats = @@ -231,8 +232,6 @@ export function createPoolTradePoller(options: PoolTradePollerOptions = {}): Poo const handlers = new Set<(event: BuyEvent) => void>(); const seen = new Map>>(); const primed = new Map>(); - const discoveredPools = new Map>(); - const baselinePools = new Map>(); const watches = new Map(); const stillWatching = (mint: string, watch: MintWatch) => watches.get(mint) === watch; let poolQueue: Array<{ mint: string; pairAddress: string }> = []; @@ -296,35 +295,27 @@ export function createPoolTradePoller(options: PoolTradePollerOptions = {}): Poo ); }; - const pollPool = async ( - mint: string, - pair: PairStats, - watch: MintWatch, - firstPassCutoffMs: number | null, - ): Promise => { - // Only targets with a non-empty pair address are queued (see the target filter). - const pairAddress = pair.pairAddress!.trim(); - + const pollPool = async ({ mint, pairAddress, pair, watch }: PollTarget): Promise => { let payload: unknown; try { - if (!(await waitForTradeSlot())) return false; + if (!(await waitForTradeSlot())) return; if (!stillWatching(mint, watch)) { - return false; + return; } payload = await fetchTrades(pairAddress); } catch (error) { deferAfterTradeFailure(error); reportError(error); - return false; + return; } - if (!stillWatching(mint, watch)) return false; + if (!stillWatching(mint, watch)) return; const parsed = geckoTradesResponseSchema.safeParse(payload); if (!parsed.success) { const error = new Error("GeckoTerminal trades response was malformed"); deferAfterTradeFailure(error); reportError(error); - return false; + return; } consecutiveTradeFailures = 0; healthySince ??= now(); @@ -333,6 +324,7 @@ export function createPoolTradePoller(options: PoolTradePollerOptions = {}): Poo const mintSeen = seen.get(mint) ?? new Map>(); const known = mintSeen.get(pairAddress) ?? new Set(); const mintPrimed = primed.get(mint) ?? new Set(); + // Until a pool has one complete snapshot, skip trades from before the watch started. const isFirstPass = !mintPrimed.has(pairAddress); // GeckoTerminal returns newest trades first. Process the snapshot oldest-first @@ -343,13 +335,11 @@ export function createPoolTradePoller(options: PoolTradePollerOptions = {}): Poo if (!event) continue; if (!rememberSignature(known, event.signature)) continue; const tradeTimestamp = Date.parse(trade.attributes.block_timestamp ?? ""); - const occurredAfterWatchStarted = - firstPassCutoffMs != null && - Number.isFinite(tradeTimestamp) && - tradeTimestamp >= firstPassCutoffMs; - if (!isFirstPass || firstPassCutoffMs == null || occurredAfterWatchStarted) { + // An undated trade parses to NaN, and NaN >= since is false. + const occurredAfterWatchStarted = tradeTimestamp >= watch.since; + if (!isFirstPass || occurredAfterWatchStarted) { emit(event); - if (!stillWatching(mint, watch)) return false; + if (!stillWatching(mint, watch)) return; } } @@ -357,46 +347,24 @@ export function createPoolTradePoller(options: PoolTradePollerOptions = {}): Poo seen.set(mint, mintSeen); mintPrimed.add(pairAddress); primed.set(mint, mintPrimed); - return true; }; - const discoverMintPools = async (mint: string, watch: MintWatch): Promise => { + const discoverMintPools = async (mint: string, watch: MintWatch): Promise => { let pools: PairStats[]; try { pools = await fetchPoolStats(mint); } catch (error) { reportError(error); - // Stryker disable next-line ArrayDeclaration: The injected string has no pair address and the queue discards it. return []; } - if (!stillWatching(mint, watch)) return []; - const uniquePools = new Map(); - for (const pool of pools) { - const pairAddress = pool.pairAddress?.trim(); - if (pairAddress && !uniquePools.has(pairAddress)) { - uniquePools.set(pairAddress, pool); + const targets = new Map(); + for (const pair of pools) { + const pairAddress = pair.pairAddress?.trim(); + if (pairAddress && !targets.has(pairAddress)) { + targets.set(pairAddress, { mint, pairAddress, pair, watch }); } } - const poolsToPoll = Array.from(uniquePools.values()); - if (poolsToPoll.length === 0) { - // Stryker disable next-line ArrayDeclaration: The injected string has no pair address and the queue discards it. - return []; - } - - let knownPools = discoveredPools.get(mint); - if (!knownPools) { - knownPools = new Set(uniquePools.keys()); - discoveredPools.set(mint, knownPools); - baselinePools.set(mint, new Set(knownPools)); - } else { - for (const pairAddress of uniquePools.keys()) { - if (!knownPools.has(pairAddress)) { - knownPools.add(pairAddress); - baselinePools.get(mint)?.add(pairAddress); - } - } - } - return poolsToPoll; + return Array.from(targets.values()); }; let pollChain = Promise.resolve(); @@ -407,22 +375,18 @@ export function createPoolTradePoller(options: PoolTradePollerOptions = {}): Poo const refreshPoolQueue = (targets: PollTarget[]): Map => { const targetByKey = new Map(); for (const target of targets) { + // A watch that restarted during discovery has newer targets. if (!stillWatching(target.mint, target.watch)) continue; - const pairAddress = target.pair.pairAddress?.trim(); - if (!pairAddress) continue; - targetByKey.set(targetKey(target.mint, pairAddress), target); + targetByKey.set(targetKey(target.mint, target.pairAddress), target); } poolQueue = poolQueue.filter(({ mint, pairAddress }) => targetByKey.has(targetKey(mint, pairAddress)), ); const queued = new Set(poolQueue.map(({ mint, pairAddress }) => targetKey(mint, pairAddress))); - for (const { mint, pair } of targetByKey.values()) { - const pairAddress = pair.pairAddress!.trim(); - const key = targetKey(mint, pairAddress); + for (const [key, { mint, pairAddress }] of targetByKey) { if (!queued.has(key)) { poolQueue.push({ mint, pairAddress }); - queued.add(key); } } return targetByKey; @@ -431,13 +395,12 @@ export function createPoolTradePoller(options: PoolTradePollerOptions = {}): Poo const pollNow = async () => { queuedPolls += 1; const run = async () => { - if (mints.length === 0) return; const targetsByMint = await Promise.all( mints.map(async (mint) => { const watch = watches.get(mint); + // Stryker disable next-line ConditionalExpression,ArrayDeclaration: setMints stores a watch for every mint, so this check only narrows the type. if (!watch) return []; - const pools = await discoverMintPools(mint, watch); - return pools.map((pair) => ({ mint, pair, watch })); + return discoverMintPools(mint, watch); }), ); const targetByKey = refreshPoolQueue(targetsByMint.flat()); @@ -448,17 +411,10 @@ export function createPoolTradePoller(options: PoolTradePollerOptions = {}): Poo if (!queuedTarget) break; const key = targetKey(queuedTarget.mint, queuedTarget.pairAddress); const target = targetByKey.get(key); - if (!target || !stillWatching(target.mint, target.watch)) continue; + // Stryker disable next-line ConditionalExpression: refreshPoolQueue queues only pools with a target and setMints only removes entries, so this check only narrows the type. + if (!target) continue; poolQueue.push(queuedTarget); - - const { mint, pair, watch } = target; - const pairAddress = queuedTarget.pairAddress; - const isBaselinePool = baselinePools.get(mint)?.has(pairAddress) ?? false; - const firstPassCutoffMs = isBaselinePool ? watch.since : null; - const succeeded = await pollPool(mint, pair, watch, firstPassCutoffMs); - if (succeeded) { - baselinePools.get(mint)?.delete(pairAddress); - } + await pollPool(target); } }; const next = pollChain.then(run, run); @@ -503,8 +459,6 @@ export function createPoolTradePoller(options: PoolTradePollerOptions = {}): Poo if (!nextSet.has(mint)) { seen.delete(mint); primed.delete(mint); - discoveredPools.delete(mint); - baselinePools.delete(mint); watches.delete(mint); } } @@ -529,8 +483,6 @@ export function createPoolTradePoller(options: PoolTradePollerOptions = {}): Poo stopTimer(); seen.clear(); primed.clear(); - discoveredPools.clear(); - baselinePools.clear(); watches.clear(); poolQueue = []; nextTradeFetchAt = 0; diff --git a/tests/buy-alerts.pool-trades-edge-cases.test.ts b/tests/buy-alerts.pool-trades-edge-cases.test.ts index 96e931f8..fb22dbd7 100644 --- a/tests/buy-alerts.pool-trades-edge-cases.test.ts +++ b/tests/buy-alerts.pool-trades-edge-cases.test.ts @@ -1,4 +1,4 @@ -import { afterEach, describe, expect, spyOn, test, vi } from "bun:test"; +import { afterEach, describe, expect, mock, spyOn, test, vi } from "bun:test"; import { GeckoRateLimitError, createPoolTradePoller, @@ -7,6 +7,7 @@ import { type PoolTradePoller, } from "../src/services/buy-alerts/pool-trades"; import { WSOL_MINT } from "../src/utils/constants"; +import { MAX_TIMER_DELAY_MS } from "../src/utils/retry-delay"; import type { BuyEvent, PairStats } from "../src/services/buy-alerts/types"; const mint = "F3A1baCgv4TF79TSjdMTvpMDtNv8DJvHZwNc9DG8pump"; @@ -239,10 +240,16 @@ describe("pool trade poller", () => { test("does not poll an obsolete pool discovered after restarting a mint watch", async () => { const firstDiscovery = Promise.withResolvers(); const requestedPools: string[] = []; + const waits: number[] = []; let discoveries = 0; const poller = track( createPoolTradePoller({ ...base, + // An obsolete pool must not take a request slot either. + minRequestIntervalMs: 1_000, + wait: async (delay) => { + waits.push(delay); + }, fetchPoolStats: async () => ++discoveries === 1 ? firstDiscovery.promise : [pool("current")], fetchTrades: async (pair) => { @@ -261,6 +268,7 @@ describe("pool trade poller", () => { firstDiscovery.resolve([pool("obsolete")]); await finished; expect(requestedPools).toEqual(["current"]); + expect(waits).toEqual([]); } finally { firstDiscovery.resolve([]); poller.stop(); @@ -516,4 +524,172 @@ describe("pool trade poller", () => { await poller.pollNow(); expect(emitted).toEqual(["fresh"]); }); + + test("a pool found after the first discovery also skips trades from before the watch started", async () => { + const start = Date.parse("2026-09-03T20:00:00Z"); + let pools = [pool("pair-a")]; + const observed: string[] = []; + const poller = track( + createPoolTradePoller({ + ...base, + now: () => start, + fetchPoolStats: async () => pools, + fetchTrades: async (pair) => ({ + data: [trade(`${pair}-after`, start + 1), trade(`${pair}-before`, start - 1)], + }), + }), + ); + poller.onTrade(({ signature }) => observed.push(signature)); + poller.setMints([mint]); + await poller.pollNow(); + expect(observed).toEqual(["pair-a-after"]); + + pools = [pool("pair-a"), pool("pair-b")]; + await poller.pollNow(); + expect(observed).toEqual(["pair-a-after", "pair-b-after"]); + }); + + test("a pool keeps the watch start filter until one read succeeds, then emits every new trade", async () => { + const start = Date.parse("2026-09-03T20:00:00Z"); + let reads = 0; + let batch = [trade("after", start + 1), trade("before", start - 1)]; + const observed: string[] = []; + const poller = track( + createPoolTradePoller({ + ...base, + now: () => start, + onError: () => {}, + fetchPoolStats: async () => [pool("pair-a")], + fetchTrades: async () => { + reads += 1; + if (reads === 1) throw new Error("trades offline"); + return { data: batch }; + }, + }), + ); + poller.onTrade(({ signature }) => observed.push(signature)); + poller.setMints([mint]); // The first read fails. + await poller.pollNow(); + expect(observed).toEqual(["after"]); + + // A late-indexed trade with an old timestamp is new after the first complete snapshot. + batch = [trade("late-indexed", start - 10), trade("undated"), ...batch]; + await poller.pollNow(); + // Snapshots arrive newest first and are emitted oldest first. + expect(observed).toEqual(["after", "undated", "late-indexed"]); + }); + + test("stops a snapshot when a trade handler removes the mint", async () => { + const observed: string[] = []; + const poller: PoolTradePoller = track( + createPoolTradePoller({ + ...base, + fetchPoolStats: async () => [pool("pair-a")], + fetchTrades: async () => ({ data: [trade("second", 2), trade("first", 1)] }), + }), + ); + poller.onTrade(({ signature }) => { + observed.push(signature); + poller.setMints([]); + }); + poller.setMints([mint]); + await poller.pollNow(); + expect(observed).toEqual(["first"]); + }); + + test("ends the cycle when a trade handler removes every mint", async () => { + const fetched: string[] = []; + const errors: unknown[] = []; + const poller: PoolTradePoller = track( + createPoolTradePoller({ + ...base, + poolsPerCycle: 2, + onError: (error) => errors.push(error), + fetchPoolStats: async () => [pool("pair-a"), pool("pair-b")], + fetchTrades: async (pair) => { + fetched.push(pair); + return { data: [trade(`${pair}-buy`, 1)] }; + }, + }), + ); + poller.onTrade(() => poller.setMints([])); + poller.setMints([mint]); // Starts the cycle that the handler ends. + await poller.pollNow(); + expect(fetched).toEqual(["pair-a"]); + expect(errors).toEqual([]); + }); + + test("does not wait for a request slot without a request interval, even if the clock goes back", async () => { + let now = 10_000; + let fetches = 0; + const waits: number[] = []; + const poller = track( + createPoolTradePoller({ + ...base, + now: () => now, + fetchPoolStats: async () => [pool("pair-a")], + fetchTrades: async () => { + fetches += 1; + return { data: [] }; + }, + wait: async (delay) => { + waits.push(delay); + }, + }), + ); + poller.setMints([mint]); + await poller.pollNow(); + now = 5_000; + await poller.pollNow(); + expect(fetches).toBe(3); + expect(waits).toEqual([]); + }); + + test("waits for a request slot exactly at the longest timer delay", async () => { + let fetches = 0; + const waits: number[] = []; + const poller = track( + createPoolTradePoller({ + ...base, + intervalMs: MAX_TIMER_DELAY_MS, + minRequestIntervalMs: MAX_TIMER_DELAY_MS, + fetchPoolStats: async () => [pool("pair-a")], + fetchTrades: async () => { + fetches += 1; + return { data: [] }; + }, + wait: async (delay) => { + waits.push(delay); + }, + }), + ); + poller.setMints([mint]); + await poller.pollNow(); + expect(fetches).toBe(2); + expect(waits).toEqual([MAX_TIMER_DELAY_MS]); + }); + + test("the interval timer does not keep the process alive", () => { + const unref = mock(() => {}); + const fakeTimer = { unref }; + const intervalSpy = spyOn(globalThis, "setInterval").mockImplementation( + (() => fakeTimer) as unknown as typeof setInterval, + ); + const clearSpy = spyOn(globalThis, "clearInterval").mockImplementation(() => {}); + try { + const poller = track( + createPoolTradePoller({ + ...base, + fetchPoolStats: async () => [], + }), + ); + poller.setMints([mint]); + expect(unref).toHaveBeenCalledTimes(1); + poller.stop(); + expect(clearSpy).toHaveBeenCalledWith(fakeTimer); + } finally { + intervalSpy.mockRestore(); + clearSpy.mockRestore(); + } + }); }); From 93e16feaf34412019154079935cf3cd26429894e Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Mon, 30 Nov 2026 05:26:03 -0300 Subject: [PATCH 335/410] test(callback-data): check malformed deltas, amounts and long callbacks Mark the three equivalent part checks with the reason. --- src/utils/callback-data.ts | 4 ++++ tests/callback-data.test.ts | 45 +++++++++++++++++++++++++++++++++++++ 2 files changed, 49 insertions(+) diff --git a/src/utils/callback-data.ts b/src/utils/callback-data.ts index 97c7909d..c289e2d4 100644 --- a/src/utils/callback-data.ts +++ b/src/utils/callback-data.ts @@ -54,6 +54,7 @@ const encodeSigned = (value: number): string | null => { const decodeUnsigned = (value: string | undefined): number | null => { const parsed = decodeSigned(value); + // Stryker disable next-line ConditionalExpression: null < 0 is false, so null is returned on both paths. TypeScript needs the null check. return parsed === null || parsed < 0 ? null : parsed; }; @@ -83,6 +84,7 @@ const encodeAmount = (amount: string): string | null => { }; const decodeAmount = (encoded: string | undefined): string | null => { + // Stryker disable next-line StringLiteral: parseCallbackParts checks the part count, so every part is defined. const raw = encoded ?? ""; const separator = raw.indexOf(AMOUNT_SEPARATOR); if (separator < 1) return null; @@ -105,7 +107,9 @@ const encodeCreatorId = (creatorId?: string): string | null => { }; const decodeCreatorId = (encoded: string | undefined): string | null => { + // Stryker disable next-line OptionalChaining: parseCallbackParts checks the part count, so every part is defined. const mode = encoded?.charAt(0); + // Stryker disable next-line OptionalChaining,StringLiteral: parseCallbackParts checks the part count, so every part is defined. const value = encoded?.slice(1) ?? ""; if (mode === "n") { diff --git a/tests/callback-data.test.ts b/tests/callback-data.test.ts index aa722cea..0c4ee7cf 100644 --- a/tests/callback-data.test.ts +++ b/tests/callback-data.test.ts @@ -207,3 +207,48 @@ test("keeps decimal amounts exact through callback encoding", () => { { seed: 451 }, ); }); + +test.each(["+5", " 5", "5+", "5!", ""])( + "refuses the signed delta %p, which is not plain base 36", + (delta) => { + expect(callback.decodeTimeoutChangePayload(`ct|c|0:5|3|${delta}|n1`)).toBeNull(); + }, +); + +test("decodes a negative base 36 delta", () => { + expect(callback.decodeTimeoutChangePayload("ct|c|0:5|3|-z|n1")).toEqual({ + gameType: "coinflip", + amount: "5", + players: 3, + deltaMinutes: -35, + creatorId: "1", + }); +}); + +test.each([ + ["15", "an amount without a scale separator"], + ["74:1", "a scale above the mint decimal limit"], + ["!:1", "a scale that is not base 36"], +])("refuses the encoded amount %p (%s)", (amount) => { + expect(callback.decodeTimeoutChangePayload(`ct|c|${amount}|3|1|n1`)).toBeNull(); +}); + +test("accepts the highest scale", () => { + expect(callback.decodeTimeoutChangePayload("ct|c|73:1|3|1|n1")?.amount).toBe( + "0." + "0".repeat(254) + "1", + ); +}); + +test("drops every trailing zero before it encodes an amount", () => { + const payload = { gameType: "coinflip" as const, players: 3, deltaMinutes: 1, creatorId: "1" }; + expect(callback.encodeTimeoutChangePayload({ ...payload, amount: "1.500" })).toBe( + "ct|c|1:f|3|1|n1", + ); +}); + +test("refuses callback data over the Telegram limit even when the fields are valid", () => { + const data = `ct|c|0:5|3|1|n${"1".repeat(60)}`; + expect(data.length).toBeGreaterThan(callback.CALLBACK_DATA_LIMIT); + expect(callback.decodeTimeoutChangePayload(data)).toBeNull(); + expect(callback.decodeTimeoutChangePayload(data.slice(0, 64))).not.toBeNull(); +}); From 83b85385833e9a5d27c762e1f94a0bc72c98bafb Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Mon, 30 Nov 2026 05:27:48 -0300 Subject: [PATCH 336/410] refactor(rpc): name failed methods with String and drop a repeated endpoint check String(prop) names strings and symbols the same way as the old branch. The single-endpoint check repeated the last-endpoint check. Add tests for two failed write endpoints, symbol methods, missing loggers, the read attempt limit and null JSON entries. --- src/utils/rpc-endpoints.ts | 7 +- tests/rpc-endpoints.error-paths.test.ts | 105 ++++++++++++++++++++++++ 2 files changed, 109 insertions(+), 3 deletions(-) diff --git a/src/utils/rpc-endpoints.ts b/src/utils/rpc-endpoints.ts index d5f89b6f..d9d8922f 100644 --- a/src/utils/rpc-endpoints.ts +++ b/src/utils/rpc-endpoints.ts @@ -284,9 +284,10 @@ export class RpcEndpointManager { return awaited; } catch (error) { lastError = error; - const methodName = typeof prop === "symbol" ? prop.toString() : prop; + // String() also names a symbol, which a template literal would reject. + const methodName = String(prop); const endpoint = this.endpoints[index]; - + // Stryker disable next-line StringLiteral: index is always inside the endpoint list. const safeEndpoint = endpoint ? redactRpcEndpoint(endpoint) : "unknown endpoint"; if (isRead && isRetryableRpcError(error) && offset === total - 1) break; @@ -297,7 +298,7 @@ export class RpcEndpointManager { this.logger?.warn?.(`RPC call ${methodName} rejected by ${safeEndpoint}: ${message}`); throw error; } - if (total === 1 || offset === total - 1) { + if (offset === total - 1) { this.logger?.error?.( `RPC call ${methodName} failed on ${safeEndpoint} without fallback:`, error, diff --git a/tests/rpc-endpoints.error-paths.test.ts b/tests/rpc-endpoints.error-paths.test.ts index 494b8a6b..3e44db31 100644 --- a/tests/rpc-endpoints.error-paths.test.ts +++ b/tests/rpc-endpoints.error-paths.test.ts @@ -218,6 +218,107 @@ describe("RpcEndpointManager call handling", () => { ]); }); + type WriteConnection = { sendRawTransaction: (transaction: Uint8Array) => Promise }; + const writeConnection = (manager: RpcEndpointManager) => + manager.getConnection() as unknown as WriteConnection; + + test("warns for each failed write endpoint and logs the last one without fallback", async () => { + const warnings: unknown[][] = []; + const errors: unknown[][] = []; + const failures = new Map([ + ["https://rpc-a", resetError("first reset")], + ["https://rpc-b", resetError("second reset")], + ]); + const manager = new RpcEndpointManager([...failures.keys()], { + connectionFactory: (endpoint) => + asConnection({ + sendRawTransaction: async () => { + throw failures.get(endpoint); + }, + }), + logger: { + warn: (...args: unknown[]) => warnings.push(args), + error: (...args: unknown[]) => errors.push(args), + }, + }); + + await expect(writeConnection(manager).sendRawTransaction(new Uint8Array(1))).rejects.toBe( + failures.get("https://rpc-b"), + ); + expect(warnings).toEqual([ + ["RPC call sendRawTransaction failed on https://rpc-a; trying next endpoint (1/2)."], + ]); + expect(errors).toEqual([ + [ + "RPC call sendRawTransaction failed on https://rpc-b without fallback:", + failures.get("https://rpc-b"), + ], + ]); + }); + + test("names a symbol method in failover warnings", async () => { + const method = Symbol("rpc-test"); + const warnings: unknown[][] = []; + const manager = new RpcEndpointManager(["https://rpc-a", "https://rpc-b"], { + connectionFactory: (endpoint) => + asConnection({ + [method]: async () => { + if (endpoint === "https://rpc-a") throw resetError(); + return "second"; + }, + }), + logger: { warn: (...args: unknown[]) => warnings.push(args) }, + }); + const connection = manager.getConnection() as unknown as Record Promise>; + + expect(await connection[method]?.()).toBe("second"); + expect(warnings).toEqual([ + ["RPC call Symbol(rpc-test) failed on https://rpc-a; trying next endpoint (1/2)."], + ]); + }); + + test.each([ + ["no logger", undefined], + ["a logger without warn or error", {}], + ])("rethrows the provider error with %s", async (_label, logger) => { + const rejected = new Error("invalid transaction"); + const reset = resetError(); + const manager = (failure: Error) => + new RpcEndpointManager(["https://rpc-only"], { + logger, + connectionFactory: () => + asConnection({ + sendRawTransaction: async () => { + throw failure; + }, + }), + }); + + await expect( + writeConnection(manager(rejected)).sendRawTransaction(new Uint8Array(1)), + ).rejects.toBe(rejected); + await expect( + writeConnection(manager(reset)).sendRawTransaction(new Uint8Array(1)), + ).rejects.toBe(reset); + }); + + test("limits one read attempt to the time left before the read deadline", async () => { + const timeoutSpy = spyOn(globalThis, "setTimeout"); + try { + const manager = new RpcEndpointManager(["https://rpc-only"], { + readTimeoutMs: 400, + connectionFactory: () => asConnection({ getSlot: async () => 7n }), + }); + expect(await manager.getConnection().getSlot()).toBe(7n); + const delays = timeoutSpy.mock.calls.map(([, delay]) => delay); + expect(delays).toHaveLength(1); + expect(delays[0]).toBeGreaterThan(300); + expect(delays[0]).toBeLessThanOrEqual(400); + } finally { + timeoutSpy.mockRestore(); + } + }); + test("does not start a read at the exact deadline", async () => { const getSlot = mock(async () => 7n); const manager = new RpcEndpointManager(["https://rpc-only"], { @@ -460,6 +561,10 @@ describe("parseRpcEndpointList edge cases", () => { expect(parseRpcEndpointList('["", "https://a", " "]')).toEqual(["https://a"]); }); + test("skips null JSON array entries", () => { + expect(parseRpcEndpointList('[null, "https://a"]')).toEqual(["https://a"]); + }); + test("uses the fallback when every entry is blank", () => { expect(parseRpcEndpointList('[""]', { fallback: DEFAULT_MAINNET_ENDPOINT })).toEqual([ DEFAULT_MAINNET_ENDPOINT, From e03ff373ce4918229ca75f0400967054c3e67882 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Mon, 30 Nov 2026 05:37:45 -0300 Subject: [PATCH 337/410] test(wallet): check program hints, fee estimates and confirmation logs Remove two checks that could not change the result: the undefined key check in the keypair cache trim, and the delete of an expired missing-mint marker that is always replaced. Add tests for cached program hints, the missing-mint marker without a clock, number and bigint fee estimates, failures that must not resubmit, a null status error, the confirmation count in logs and the network retry count. --- src/utils/wallet.ts | 5 +- tests/wallet-mutation-bounds.test.ts | 74 ++++++++++++++++++++++++ tests/wallet.balances-edge-cases.test.ts | 44 ++++++++++++++ tests/wallet.resubmit.test.ts | 28 +++++++++ tests/wallet.transactions.test.ts | 6 ++ 5 files changed, 155 insertions(+), 2 deletions(-) diff --git a/src/utils/wallet.ts b/src/utils/wallet.ts index e4a5a65c..2d480bb1 100644 --- a/src/utils/wallet.ts +++ b/src/utils/wallet.ts @@ -186,7 +186,7 @@ class KeypairCache { private trim(): void { for (const oldestKey of this.cache.keys()) { - if (!(this.cache.size > this.capacity) || oldestKey === undefined) { + if (!(this.cache.size > this.capacity)) { break; } this.cache.delete(oldestKey); @@ -691,8 +691,8 @@ export class WalletManager { const cached = this.mintProgramCache.get(cacheKey); if (cached) { if ("programId" in cached) return cached; + // An expired entry is replaced below with a new detection or a new missing marker. if ((this.timeNow?.() ?? Date.now()) < cached.missingUntil) return null; - this.mintProgramCache.delete(cacheKey); } const detection = await detectTokenProgram(this.connection, mintKey); @@ -2530,6 +2530,7 @@ export class WalletManager { console.warn( `⚠️ Final status lookup unavailable for ${signature}, checking transaction history`, ); + // Stryker disable next-line ObjectLiteral: the checks below treat undefined like null and false. return { status: null, available: false }; }, ); diff --git a/tests/wallet-mutation-bounds.test.ts b/tests/wallet-mutation-bounds.test.ts index 545edf92..cee39438 100644 --- a/tests/wallet-mutation-bounds.test.ts +++ b/tests/wallet-mutation-bounds.test.ts @@ -8,6 +8,7 @@ import { VersionedTransaction, } from "#solana"; import { TransactionOutcomeUnknownError, WalletManager } from "../src/utils/wallet"; +import { fake } from "./helpers/fakes"; import { stubInstantTimers, withinTestDeadline } from "./helpers/timers"; import { useWalletConfirmationClock } from "./helpers/wallet-confirmation-clock"; @@ -294,3 +295,76 @@ test("reports bigint confirmation counts while polling and on the final status c clock.restore(); } }); + +test("leaves the confirmation count out of the log when the status has none", async () => { + const statuses = [ + { slot: 1n, err: null, confirmationStatus: "processed" }, + { slot: 1n, confirmations: 3n, err: null, confirmationStatus: "confirmed" }, + ]; + let reads = 0; + const wallet = walletWith({ + getSignatureStatuses: async () => { + const status = statuses[reads++]; + if (!status) throw new Error("Unexpected third status lookup"); + return fake>>({ + context: { slot: 1n }, + value: [status], + }); + }, + }); + const clock = useWalletConfirmationClock(wallet); + const log = spyOn(console, "log").mockImplementation(() => {}); + try { + await expect( + withinTestDeadline(wallet.confirmTransaction(signature), "status without confirmations"), + ).resolves.toBeUndefined(); + expect(log.mock.calls.filter(([line]) => String(line).includes("status update"))).toEqual([ + [`📊 Transaction ${signature} status update (poll 1, 0ms): processed`], + [`📊 Transaction ${signature} status update (poll 2, 400ms): confirmed (3 confirmations)`], + ]); + } finally { + log.mockRestore(); + clock.restore(); + } +}); + +test("rethrows a status lookup that rejects without an error object", async () => { + const wallet = walletWith({ + getSignatureStatuses: async () => { + throw null; + }, + }); + const clock = useWalletConfirmationClock(wallet); + const error = spyOn(console, "error").mockImplementation(() => {}); + try { + await expect( + withinTestDeadline(wallet.confirmTransaction(signature), "null status error"), + ).rejects.toBeNull(); + } finally { + error.mockRestore(); + clock.restore(); + } +}); + +test.each([4_321, 4_321n])("uses the RPC fee estimate %p", async (fee) => { + const payer = await Keypair.generate(); + const wallet = walletWith({ + getLatestBlockhash: async () => + fake>>({ + blockhash: PublicKey.default.toBase58(), + lastValidBlockHeight: 100n, + }), + getFeeForMessage: async () => + fake>>({ + context: { slot: 1n }, + value: fee, + }), + }); + const instruction = SystemProgram.transfer({ + fromPubkey: payer.publicKey, + toPubkey: PublicKey.default, + lamports: 1, + }); + + expect(await wallet["estimateFee"](payer.publicKey, [instruction])).toBe(4_321); +}); diff --git a/tests/wallet.balances-edge-cases.test.ts b/tests/wallet.balances-edge-cases.test.ts index 7d1ddb8e..8316c656 100644 --- a/tests/wallet.balances-edge-cases.test.ts +++ b/tests/wallet.balances-edge-cases.test.ts @@ -11,6 +11,7 @@ import { type WalletTokenBalance, type WalletTokenCensus, } from "../src/utils/wallet"; +import { fake, itemAt } from "./helpers/fakes"; import { stubInstantTimers } from "./helpers/timers"; const MNEMONIC = process.env.MNEMONIC!; @@ -648,6 +649,49 @@ describe("getAllWalletTokenBalances edge cases", () => { }); }); +describe("token program hints", () => { + test("a fresh cached snapshot copies only detected token programs to the known tokens", async () => { + const wallet = walletWith({}); + const mints = fixtureMints(3).map((mint) => mint.toBase58()); + const detected = itemAt(mints, 0); + const missing = itemAt(mints, 1); + const snapshot = fake({ + mint: detected, + ticker: "DET", + balance: 1, + decimals: 6, + decimalBalance: 1, + }); + wallet.setCachedWalletTokenBalances(TELEGRAM_ID, [snapshot]); + wallet["mintProgramCache"].set(detected, { + programId: TOKEN_2022_PROGRAM_ID, + isToken2022: true, + }); + wallet["mintProgramCache"].set(missing, { missingUntil: Date.now() + 60_000 }); + // The third mint has no cache entry. + const tokens = mints.map((mint) => knownToken(mint, "TOK")); + + expect(await wallet.getAllWalletTokenBalances(TELEGRAM_ID, tokens)).toEqual([snapshot]); + expect(tokens.map((token) => token.token_program_id)).toEqual([ + TOKEN_2022_PROGRAM_ID.toBase58(), + TOKEN_PROGRAM_ID.toBase58(), + TOKEN_PROGRAM_ID.toBase58(), + ]); + }); + + test("a missing mint marker answers without a clock dependency or an RPC read", async () => { + const wallet = walletWith({ + getAccountInfo: async () => { + throw new Error("The missing marker must answer first"); + }, + }); + const mint = itemAt(fixtureMints(1), 0); + wallet["mintProgramCache"].set(mint.toBase58(), { missingUntil: Date.now() + 60_000 }); + + expect(await wallet["resolveTokenProgram"](mint)).toBeNull(); + }); +}); + describe("processParsedTokenAccount", () => { test("ignores zero balances and tokens that cannot be registered", async () => { const wallet = walletWith({}); diff --git a/tests/wallet.resubmit.test.ts b/tests/wallet.resubmit.test.ts index 7542567d..960a0af1 100644 --- a/tests/wallet.resubmit.test.ts +++ b/tests/wallet.resubmit.test.ts @@ -30,6 +30,34 @@ class ResubmitConnection implements Partial { } describe("WalletManager sendAndConfirmWithResubmits", () => { + test("does not resubmit after a failure that is not a confirmation timeout", async () => { + const connection = new ResubmitConnection(); + const wallet = WalletManager.createForTest(MNEMONIC, { + connection: connection as unknown as Connection, + }); + const failure = new Error("Transaction failed: insufficient funds"); + const confirm = spyOn(wallet, "confirmTransaction").mockRejectedValue(failure); + const log = spyOn(console, "log").mockImplementation(() => {}); + try { + const instruction = new TransactionInstruction({ + programId: PublicKey.default, + keys: [], + data: Buffer.alloc(0), + }); + await expect( + wallet.sendAndConfirmWithResubmits([instruction], [await Keypair.generate()], { + operationLabel: "Test claim", + maxResubmits: 2, + }), + ).rejects.toBe(failure); + expect(connection.sendCalls).toBe(1); + expect(confirm).toHaveBeenCalledTimes(1); + } finally { + confirm.mockRestore(); + log.mockRestore(); + } + }); + test.each([0, 1, 2] as const)( "reports the confirmed signature after %i resubmits", async (retries) => { diff --git a/tests/wallet.transactions.test.ts b/tests/wallet.transactions.test.ts index 9f225e97..8673472a 100644 --- a/tests/wallet.transactions.test.ts +++ b/tests/wallet.transactions.test.ts @@ -820,6 +820,12 @@ describe("confirmTransaction polling", () => { expect(messages(warnSpy)).toContain( `⚠️ Final status lookup unavailable for ${signature}, checking transaction history`, ); + // The failed final lookup counts as one network retry. + expect( + messages(errorSpy).filter((line) => + line.startsWith("⏰ Transaction confirmation timeout"), + ), + ).toEqual([expect.stringContaining(", networkRetries=1, postTimeoutProbe=")]); } finally { history.mockRestore(); clock.restore(); From 140c95b18edf2ae46fc4c6dd7be288a1336e8071 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Mon, 30 Nov 2026 05:39:05 -0300 Subject: [PATCH 338/410] refactor(rate-limit): drop checks that retry parsing already makes retrySecondsToMilliseconds rejects NaN and Infinity, Number.isFinite rejects non-numbers, and splice ignores a negative count. Add tests for the safe deadline limit, the maximum wait boundary, the rounded error text and malformed retry parameters. --- src/utils/telegram-rate-limiter.ts | 9 ++--- tests/telegram-rate-limiter.test.ts | 52 +++++++++++++++++++++++++++++ 2 files changed, 57 insertions(+), 4 deletions(-) diff --git a/src/utils/telegram-rate-limiter.ts b/src/utils/telegram-rate-limiter.ts index 36be80fd..e0cf135f 100644 --- a/src/utils/telegram-rate-limiter.ts +++ b/src/utils/telegram-rate-limiter.ts @@ -70,8 +70,8 @@ export class CallbackAnswerQueue { */ enqueue(callbackQueryId: string, text?: string, showAlert?: boolean): void { // Drop oldest if queue is full - const overflow = this.queue.length + 1 - this.maxSize; - if (overflow > 0) this.queue.splice(0, overflow); + // splice treats a negative count as 0. + this.queue.splice(0, this.queue.length + 1 - this.maxSize); this.queue.push({ callbackQueryId, @@ -208,7 +208,7 @@ export class TelegramRateLimiter { * Record a rate limit error and set the blocked period. */ recordRateLimit(retryAfterSeconds: number, chatId?: number): void { - if (!Number.isFinite(retryAfterSeconds)) return; + // retrySecondsToMilliseconds also rejects NaN and Infinity. const retryAfterMs = retrySecondsToMilliseconds(Math.max(0, retryAfterSeconds)); if (retryAfterMs === null) return; const blockedUntil = Date.now() + retryAfterMs; @@ -427,7 +427,7 @@ export const extractRetryAfter = (error: unknown): number | null => { const params = (error as any).parameters; const seconds = params?.retry_after; if ( - typeof seconds === "number" && + // Number.isFinite is false for every non-number. Number.isFinite(seconds) && retrySecondsToMilliseconds(Math.max(0, seconds)) !== null ) { @@ -437,6 +437,7 @@ export const extractRetryAfter = (error: unknown): number | null => { // Try to parse from message const match = error.message.match(/retry after (\d+)/i); + // Stryker disable next-line StringLiteral: parseInt returns NaN for any text without leading digits. const seconds = Number.parseInt(match?.[1] ?? "", 10); return retrySecondsToMilliseconds(seconds) === null ? null : seconds; }; diff --git a/tests/telegram-rate-limiter.test.ts b/tests/telegram-rate-limiter.test.ts index f1182401..cba79813 100644 --- a/tests/telegram-rate-limiter.test.ts +++ b/tests/telegram-rate-limiter.test.ts @@ -491,3 +491,55 @@ describe("Singleton getters", () => { expect(queue1).toBe(queue2); }); }); + +describe("rate limit boundaries", () => { + const NOW = 1_000_000; + + test("ignores a retry delay that would pass the largest safe deadline", () => { + const now = spyOn(Date, "now").mockReturnValue(NOW); + try { + const limiter = new TelegramRateLimiter(); + // The delay is a safe integer in milliseconds, but adding the current time is not. + limiter.recordRateLimit(9_007_199_254_740, 5); + expect(limiter.getWaitTimeMs(5)).toBe(0); + limiter.recordRateLimit(9_007_199_253, 6); + expect(limiter.getWaitTimeMs(6)).toBe(9_007_199_253_000); + } finally { + now.mockRestore(); + } + }); + + test("waits when the remaining limit equals the maximum wait", async () => { + const now = spyOn(Date, "now").mockReturnValue(NOW); + try { + const limiter = new TelegramRateLimiter(); + limiter.recordRateLimit(0.02, 7); + await expect(limiter.throttle(7, async () => "sent", { maxWait: 20 })).resolves.toBe("sent"); + } finally { + now.mockRestore(); + } + }); + + test("rounds both durations up to seconds when the limit exceeds the maximum wait", async () => { + const now = spyOn(Date, "now").mockReturnValue(NOW); + try { + const limiter = new TelegramRateLimiter(); + limiter.recordRateLimit(2.5, 8); + await expect(limiter.throttle(8, async () => "sent", { maxWait: 1_500 })).rejects.toThrow( + "Rate limited for 3s, exceeds max wait of 2s", + ); + } finally { + now.mockRestore(); + } + }); + + test("uses the message hint when the parameters are missing", () => { + const error = Object.assign(new Error("retry after 4"), { parameters: undefined }); + expect(extractRetryAfter(error)).toBe(4); + }); + + test("ignores a retry_after parameter that is not a number", () => { + const error = Object.assign(new Error("Rate limited"), { parameters: { retry_after: "5" } }); + expect(extractRetryAfter(error)).toBeNull(); + }); +}); From aa6cd339a650287182c976ad12f4bc8859ca61dc Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Mon, 30 Nov 2026 05:39:05 -0300 Subject: [PATCH 339/410] test(prices): check the request method, API key, deadline cleanup and batch filters pickUsdPrice already returns null or a positive finite price, so the batch loop now checks only for a missing price. --- src/utils/prices.ts | 4 +- tests/prices.aggregate.test.ts | 93 +++++++++++++++++++++++++++++++++- 2 files changed, 95 insertions(+), 2 deletions(-) diff --git a/src/utils/prices.ts b/src/utils/prices.ts index 82f6ae39..05099d00 100644 --- a/src/utils/prices.ts +++ b/src/utils/prices.ts @@ -109,6 +109,7 @@ async function fetchJupiterEntries( }; // Use one deadline for both headers and body, even when a transport ignores abort. return await Promise.race([deadline, request()]); + // Stryker disable next-line BlockStatement: both callers treat undefined like null. } catch { return null; } finally { @@ -208,7 +209,8 @@ export async function getPricesUSD( for (const mint of batch) { const price = fetched[mint]; - if (!price || !Number.isFinite(price) || price <= 0) continue; + // pickUsdPrice returns null or a positive finite price. + if (!price) continue; priceCache.setWithTTL(mint, { value: price }); } } diff --git a/tests/prices.aggregate.test.ts b/tests/prices.aggregate.test.ts index 759d7c9d..1723ebc9 100644 --- a/tests/prices.aggregate.test.ts +++ b/tests/prices.aggregate.test.ts @@ -1,4 +1,4 @@ -import { test, expect } from "bun:test"; +import { afterEach, beforeEach, describe, expect, spyOn, test } from "bun:test"; import { getPricesUSD, getPriceUSD, __test_resetPriceCache } from "../src/utils/prices"; import { WSOL_MINT } from "../src/utils/token-registry"; @@ -56,3 +56,94 @@ test("duplicate mint requests share a single Jupiter request and hydrate cache", } } }); + +describe("Jupiter price requests", () => { + const USDC = "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"; + type FetchCall = { url: string; init: RequestInit | undefined }; + const recordingFetch = ( + calls: FetchCall[], + respond: (ids: string[]) => Response | Promise, + ) => + (async (input: RequestInfo | URL, init?: RequestInit) => { + const url = String(input); + calls.push({ url, init }); + return respond((new URL(url).searchParams.get("ids") ?? "").split(",")); + }) as unknown as typeof fetch; + const priceResponse = (prices: Record) => + new Response( + JSON.stringify({ + data: Object.fromEntries(Object.entries(prices).map(([id, price]) => [id, { price }])), + }), + { status: 200 }, + ); + const savedEnv = { ...process.env }; + + beforeEach(() => { + process.env["PRICES_ENABLED"] = "true"; + Reflect.deleteProperty(process.env, "JUPITER_API_KEY"); + __test_resetPriceCache(); + }); + afterEach(() => { + for (const key of ["PRICES_ENABLED", "JUPITER_API_KEY"]) { + if (savedEnv[key] === undefined) Reflect.deleteProperty(process.env, key); + else process.env[key] = savedEnv[key]; + } + __test_resetPriceCache(); + }); + + test.each([ + ["with", "test-key", { "x-api-key": "test-key" }], + ["without", undefined, undefined], + ])("sends a GET request %s the Jupiter API key header", async (_label, apiKey, headers) => { + if (apiKey) process.env["JUPITER_API_KEY"] = apiKey; + const calls: FetchCall[] = []; + const price = await getPriceUSD( + USDC, + recordingFetch(calls, () => priceResponse({ [USDC]: 1 })), + ); + expect(price).toBe(1); + expect(calls).toHaveLength(1); + expect(calls[0]?.init?.method).toBe("GET"); + expect(calls[0]?.init?.headers).toEqual(headers); + }); + + test("clears the request deadline when the request fails", async () => { + const timeoutSpy = spyOn(globalThis, "setTimeout"); + const clearSpy = spyOn(globalThis, "clearTimeout"); + try { + const price = await getPriceUSD(USDC, (async () => { + throw new Error("offline"); + }) as unknown as typeof fetch); + expect(price).toBe(0); + // The deadline timer starts before the price cache schedules its own expiry. + const deadline = timeoutSpy.mock.results[0]?.value as + ReturnType | undefined; + expect(deadline).toBeDefined(); + expect(clearSpy.mock.calls.map(([timer]) => timer)).toContain(deadline); + } finally { + timeoutSpy.mockRestore(); + clearSpy.mockRestore(); + } + }); + + test("batches only valid mint addresses", async () => { + const calls: FetchCall[] = []; + const prices = await getPricesUSD( + ["not-a-mint", " ", USDC], + recordingFetch(calls, () => priceResponse({ [USDC]: 2 })), + ); + expect(prices).toEqual({ "not-a-mint": 0, " ": 0, [USDC]: 2 }); + expect(calls.map(({ url }) => new URL(url).searchParams.get("ids"))).toEqual([USDC]); + }); + + test("does not cache a batch entry without a usable price", async () => { + const calls: FetchCall[] = []; + const prices = await getPricesUSD( + [USDC], + recordingFetch(calls, () => priceResponse({ [USDC]: 0 })), + ); + expect(prices).toEqual({ [USDC]: 0 }); + // The single-mint lookup asks again because the batch cached nothing. + expect(calls).toHaveLength(2); + }); +}); From 636d7d648bd1320a64ff214229252923113eb83e Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Mon, 30 Nov 2026 05:45:29 -0300 Subject: [PATCH 340/410] test(jupiter): check token search matching and a zero fee Mark the type-narrowing fee check and the mint parse catch block as equivalent with the reason. --- src/utils/jupiter.ts | 2 ++ tests/jupiter.client-errors.test.ts | 33 +++++++++++++++++++++++++++++ tests/jupiter.utils.test.ts | 1 + 3 files changed, 36 insertions(+) diff --git a/src/utils/jupiter.ts b/src/utils/jupiter.ts index 28ad775e..b339908f 100644 --- a/src/utils/jupiter.ts +++ b/src/utils/jupiter.ts @@ -232,6 +232,7 @@ export const resolveAppliedFeeBps = ( data: Pick, ): number | null => { const feeBps = data.platformFee?.feeBps ?? data.feeBps; + // Stryker disable next-line ConditionalExpression: Number.isSafeInteger is false for non-numbers. TypeScript needs typeof before the comparison. return typeof feeBps === "number" && Number.isSafeInteger(feeBps) && feeBps >= 0 ? feeBps : null; }; @@ -882,6 +883,7 @@ export interface JupiterTokenMetadata { const isCanonicalMintQuery = (query: string): boolean => { try { return new PublicKey(query).toBase58() === query; + // Stryker disable next-line BlockStatement: the caller treats undefined like false. } catch { return false; } diff --git a/tests/jupiter.client-errors.test.ts b/tests/jupiter.client-errors.test.ts index f5cf5835..84387b4f 100644 --- a/tests/jupiter.client-errors.test.ts +++ b/tests/jupiter.client-errors.test.ts @@ -331,6 +331,39 @@ describe("fetchJupiterTokenMetadata", () => { expect(await fetchJupiterTokenMetadata("text search", fetchImpl)).toMatchObject(other); }); + test("matches a mint id that the search returns with surrounding spaces", async () => { + const padded = { ...exact, id: ` ${mint} ` }; + expect( + await fetchJupiterTokenMetadata(mint, async () => Response.json([padded])), + ).toMatchObject({ symbol: "EXACT" }); + }); + + test("prefers a text id match, ignoring case and spaces, over a symbol match", async () => { + const symbolMatch = { id: "zzz", symbol: "ABC", decimals: 1 }; + const idMatch = { id: " AbC ", symbol: "QQQ", decimals: 2 }; + expect( + await fetchJupiterTokenMetadata("abc", async () => Response.json([symbolMatch, idMatch])), + ).toMatchObject({ symbol: "QQQ" }); + }); + + test("matches a symbol that the search returns with surrounding spaces", async () => { + const first = { id: "zzz", symbol: "QQQ", decimals: 1 }; + const padded = { id: "yyy", symbol: " ABC ", decimals: 2 }; + expect( + await fetchJupiterTokenMetadata("abc", async () => Response.json([first, padded])), + ).toMatchObject({ id: "yyy" }); + }); + + test("returns null for a missing query from an untyped caller", async () => { + let calls = 0; + const fetchImpl = async () => { + calls += 1; + return Response.json([exact]); + }; + expect(await fetchJupiterTokenMetadata(undefined as unknown as string, fetchImpl)).toBeNull(); + expect(calls).toBe(0); + }); + test("ignores HTTP failures, empty results, and missing fields without throwing", async () => { expect( await fetchJupiterTokenMetadata("SOL", async () => new Response("busy", { status: 503 })), diff --git a/tests/jupiter.utils.test.ts b/tests/jupiter.utils.test.ts index c8933c40..24f6bf05 100644 --- a/tests/jupiter.utils.test.ts +++ b/tests/jupiter.utils.test.ts @@ -415,6 +415,7 @@ describe("resolveAppliedFeeBps", () => { 50, ); expect(resolveAppliedFeeBps({})).toBe(null); + expect(resolveAppliedFeeBps({ feeBps: 0 })).toBe(0); }); test.each([12.5, -1, NaN, Infinity, Number.MAX_SAFE_INTEGER + 1])( From 0edeb391870a3ffbad03969bede76963813385ea Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Mon, 30 Nov 2026 05:51:24 -0300 Subject: [PATCH 341/410] style(tests): format two game message tests with Prettier --- tests/game-manager.update-message.test.ts | 110 +++------------------- tests/game.completion-state.test.ts | 12 ++- 2 files changed, 21 insertions(+), 101 deletions(-) diff --git a/tests/game-manager.update-message.test.ts b/tests/game-manager.update-message.test.ts index aa3f611a..bd8ae6f4 100644 --- a/tests/game-manager.update-message.test.ts +++ b/tests/game-manager.update-message.test.ts @@ -121,15 +121,7 @@ describe("GameManager.updateGameMessage routing", () => { const msgMap = new Map(); msgMap.set(1, { chatId: 1, messageId: 42, usesVideo: true }); (gm as any).activeGameMessages.set(addr, msgMap); - await gm.updateGameMessage( - ctx, - addr, - "coinflip", - 1_000_000_000, - "@creator", - "Active", - "TOK", - ); + await gm.updateGameMessage(ctx, addr, "coinflip", 1_000_000_000, "@creator", "Active", "TOK"); const calls = (ctx as any).__calls; expect(calls[0][0]).toBe("caption"); const active = gm.getActiveGameMessages(addr)?.get(1); @@ -201,15 +193,7 @@ describe("GameManager.updateGameMessage routing", () => { const msgMap = new Map(); msgMap.set(1, { chatId: 1, messageId: 44, usesVideo: false }); (gm as any).activeGameMessages.set(addr, msgMap); - await gm.updateGameMessage( - ctx, - addr, - "giveaway", - 1_000_000_000, - "@creator", - "Active", - "TOK", - ); + await gm.updateGameMessage(ctx, addr, "giveaway", 1_000_000_000, "@creator", "Active", "TOK"); const calls = (ctx as any).__calls; expect(calls[0][0]).toBe("text"); }); @@ -237,15 +221,7 @@ describe("GameManager.updateGameMessage routing", () => { const msgMap = new Map(); msgMap.set(1, { chatId: 1, messageId: 45, usesVideo: false }); (gm as any).activeGameMessages.set(addr, msgMap); - await gm.updateGameMessage( - ctx, - addr, - "coinflip", - 1_000_000_000, - "@creator", - "Active", - "TOK", - ); + await gm.updateGameMessage(ctx, addr, "coinflip", 1_000_000_000, "@creator", "Active", "TOK"); const calls = (ctx as any).__calls; expect(calls[0][0]).toBe("text"); const active = gm.getActiveGameMessages(addr)?.get(1); @@ -287,15 +263,7 @@ describe("GameManager.updateGameMessage routing", () => { msgMap.set(chatId, { chatId, messageId: 49, usesVideo: true }); (gm as any).activeGameMessages.set(addr, msgMap); - await gm.updateGameMessage( - ctx, - addr, - "coinflip", - 1_000_000_000, - "@creator", - "Active", - "TOK", - ); + await gm.updateGameMessage(ctx, addr, "coinflip", 1_000_000_000, "@creator", "Active", "TOK"); const calls = (ctx as any).__calls; expect(calls.map((call: any[]) => call[0])).toEqual(["caption", "text"]); @@ -566,15 +534,7 @@ describe("GameManager.updateGameMessage routing", () => { const msgMap = new Map(); msgMap.set(1, { chatId: 1, messageId: 46, usesVideo: true }); (gm as any).activeGameMessages.set(addr, msgMap); - await gm.updateGameMessage( - ctx, - addr, - "coinflip", - 1_000_000_000, - "@creator", - "Active", - "TOK", - ); + await gm.updateGameMessage(ctx, addr, "coinflip", 1_000_000_000, "@creator", "Active", "TOK"); const calls = (ctx as any).__calls; const sendIndex = calls.findIndex((c: any[]) => c[0] === "send"); expect(sendIndex).toBeGreaterThan(-1); @@ -633,15 +593,7 @@ describe("GameManager.updateGameMessage routing", () => { msgMap.set(1, { chatId: 1, messageId: 47, usesVideo: false }); (gm as any).activeGameMessages.set(addr, msgMap); - await gm.updateGameMessage( - ctx, - addr, - "coinflip", - 1_000_000_000, - "@creator", - "Active", - "TOK", - ); + await gm.updateGameMessage(ctx, addr, "coinflip", 1_000_000_000, "@creator", "Active", "TOK"); const calls = (ctx as any).__calls; const sendCall = calls.find((call: any[]) => call[0] === "send"); @@ -691,24 +643,8 @@ describe("GameManager.updateGameMessage routing", () => { (gm as any).activeGameMessages.set(addr, msgMap); await Promise.all([ - gm.updateGameMessage( - ctx, - addr, - "coinflip", - 1_000_000_000, - "@creator", - "Active", - "TOK", - ), - gm.updateGameMessage( - ctx, - addr, - "coinflip", - 1_000_000_000, - "@creator", - "Active", - "TOK", - ), + gm.updateGameMessage(ctx, addr, "coinflip", 1_000_000_000, "@creator", "Active", "TOK"), + gm.updateGameMessage(ctx, addr, "coinflip", 1_000_000_000, "@creator", "Active", "TOK"), ]); expect((database as any).__savedMessages).toHaveLength(1); @@ -764,15 +700,7 @@ describe("GameManager.updateGameMessage routing", () => { msgMap.set(1, { chatId: 1, messageId: 47, usesVideo: false }); (gm as any).activeGameMessages.set(addr, msgMap); - await gm.updateGameMessage( - ctx, - addr, - "coinflip", - 1_000_000_000, - "@creator", - "Active", - "TOK", - ); + await gm.updateGameMessage(ctx, addr, "coinflip", 1_000_000_000, "@creator", "Active", "TOK"); // Should have attempted video first (text edit failed, then recreate with video) const videoCalls = calls.filter((call: any[]) => call[0] === "video"); @@ -835,15 +763,7 @@ describe("GameManager.updateGameMessage routing", () => { msgMap.set(1, { chatId: 1, messageId: 47, usesVideo: false }); (gm as any).activeGameMessages.set(addr, msgMap); - await gm.updateGameMessage( - ctx, - addr, - "coinflip", - 1_000_000_000, - "@creator", - "Active", - "TOK", - ); + await gm.updateGameMessage(ctx, addr, "coinflip", 1_000_000_000, "@creator", "Active", "TOK"); // Find the send call and check it includes reply_to_message_id const sendCall = calls.find((call: any[]) => call[0] === "send"); @@ -902,15 +822,7 @@ describe("GameManager.updateGameMessage routing", () => { msgMap.set(1, { chatId: 1, messageId: 47, usesVideo: false }); (gm as any).activeGameMessages.set(addr, msgMap); - await gm.updateGameMessage( - ctx, - addr, - "giveaway", - 1_000_000_000, - "@creator", - "Active", - "TOK", - ); + await gm.updateGameMessage(ctx, addr, "giveaway", 1_000_000_000, "@creator", "Active", "TOK"); // Should have tried to recreate the message (either video or text depending on config) // In test env, video IDs may not be configured, so we just verify the message was recreated diff --git a/tests/game.completion-state.test.ts b/tests/game.completion-state.test.ts index b5e26fb2..221f8344 100644 --- a/tests/game.completion-state.test.ts +++ b/tests/game.completion-state.test.ts @@ -144,7 +144,11 @@ describe("older completion update check", () => { winnerAddress: "w2", }); expect( - gm["isSupersededActiveGameMessageUpdate"](GAME, { status: "Completed", winnerAddress: "w1" }, 1), + gm["isSupersededActiveGameMessageUpdate"]( + GAME, + { status: "Completed", winnerAddress: "w1" }, + 1, + ), ).toBe(false); }); }); @@ -153,7 +157,11 @@ describe("persisted terminal state", () => { const terminal = (game: unknown, requested = "Active", metadata?: Partial) => { const gm = makeManager({ getGame: () => game }); if (metadata) { - gm["gameMessageCompletionMetadata"].set(GAME, { generation: 1, status: "Completed", ...metadata }); + gm["gameMessageCompletionMetadata"].set(GAME, { + generation: 1, + status: "Completed", + ...metadata, + }); } return gm["getPersistedTerminalUpdate"](GAME, requested, "arg-w", 9, "arg-s"); }; From fb42acfa6ec57650f41ac46f2f38eaa3463121ef Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Mon, 30 Nov 2026 06:02:03 -0300 Subject: [PATCH 342/410] test(recovery): check the exact binary search probes and the slot list checks The restart jump now has a test that reads the exact probe slots for five slot lists, so an extra read after the search range is empty fails. Two text slot cases check that a slot from RPC must be a number. The slot checks are rewritten without two equivalent mutants and keep the same result for every list. Number.isSafeInteger is true only for a number, so the typeof check added nothing. The order check now compares each slot with the one before it through slice(1), so no index guard is needed. The maxProbes bound stays: a correct search never reaches it, so its own mutants are equivalent and are listed in the PR body. --- src/utils/game-creation-recovery.ts | 11 ++++--- ...ame-creation-recovery.proof-guards.test.ts | 32 +++++++++++++++++++ 2 files changed, 38 insertions(+), 5 deletions(-) diff --git a/src/utils/game-creation-recovery.ts b/src/utils/game-creation-recovery.ts index f3325ac0..daffd7e2 100644 --- a/src/utils/game-creation-recovery.ts +++ b/src/utils/game-creation-recovery.ts @@ -36,7 +36,8 @@ export type CreationProofProgress = { }; function isFinalizedSlot(value: unknown): value is number { - return typeof value === "number" && Number.isSafeInteger(value) && value >= 0; + // Number.isSafeInteger is true only for a number, so Number(value) is the value itself. + return Number.isSafeInteger(value) && Number(value) >= 0; } export async function proveExpiredCreationAbsent( @@ -109,10 +110,10 @@ export async function proveExpiredCreationAbsent( if ( !Array.isArray(slots) || !slots.length || - slots.some( - (value: unknown, index: number) => - !isFinalizedSlot(value) || value > slot || (index > 0 && value <= slots[index - 1]), - ) + !slots.every(isFinalizedSlot) || + slots.some((value: number) => value > slot) || + // Each slot must be above the one before it. + slots.slice(1).some((value: number, index: number) => value <= slots[index]) ) return false; let low = 0; diff --git a/tests/game-creation-recovery.proof-guards.test.ts b/tests/game-creation-recovery.proof-guards.test.ts index 2be35c11..f3f229df 100644 --- a/tests/game-creation-recovery.proof-guards.test.ts +++ b/tests/game-creation-recovery.proof-guards.test.ts @@ -60,6 +60,8 @@ describe("restart jump to the expiry anchor", () => { ["containing a non-integer slot", [1_000.5]], ["containing a negative slot", [-1]], ["containing a slot after the tip", [1_000, 2_000]], + ["containing a text slot", ["1000"]], + ["containing a text slot after a valid one", [1_000, "1001"]], ["not strictly increasing", [1_000, 1_000]], ["decreasing", [1_001, 1_000]], ] as const) @@ -88,6 +90,36 @@ describe("restart jump to the expiry anchor", () => { ).toEqual([1, 1, 0]); }); + // Height equals slot, and expiry is height 13, so slot 14 is the first block after expiry. + // A binary search over n slots reads at most ceil(log2(n + 1)) blocks and stops as soon + // as its range is empty, even when the bound would allow another read. + test.each<[string, number[], number[], boolean]>([ + ["one slot after expiry", [14], [14], true], + ["two slots after expiry", [14, 15], [14], true], + ["four slots after expiry", [14, 15, 16, 17], [15, 14], true], + ["seven slots around expiry", [10, 11, 12, 13, 14, 15, 16], [13, 15, 14], true], + ["four slots before expiry", [10, 11, 12, 13], [11, 12, 13], false], + ])( + "binary search over %s reads exactly the probe slots", + async (_name, slots, probes, proven) => { + const log: Array<[string, unknown]> = []; + const recorded = + (name: string): RecoveryRpc => + async (method, params) => { + if (method === "getBlock") log.push([name, params[0]]); + return rpcFor(blocks, 1_014, { getBlocks: slots })(method, params); + }; + expect( + await proveExpiredCreationAbsent(input, recorded("primary"), recorded("witness")), + ).toBe(proven); + const witnessRead = log.findIndex(([name]) => name === "witness"); + // The first primary read is the tip. The search probes follow it. + const searchReads = log.slice(1, witnessRead < 0 ? undefined : witnessRead); + expect(searchReads).toEqual(probes.map((slot) => ["primary", slot])); + if (proven) expect(log[witnessRead]).toEqual(["witness", 14]); + }, + ); + test("does not request a restart jump at the exact distance boundary", async () => { const rpc = mock(rpcFor(chain(10, 77), 77)); expect(await proveExpiredCreationAbsent(input, rpc, rpc)).toBe(true); From 22e9dfe5e649d71fffad6cb39474d28171b77a6a Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Mon, 30 Nov 2026 06:04:37 -0300 Subject: [PATCH 343/410] fix(jupiter): check the fee rate without a disable that hid killable mutants The ConditionalExpression disable on resolveAppliedFeeBps also hid the ternary true and false mutants, which a valid fee or a missing fee kills. The check now reads Number.isSafeInteger(feeBps) && Number(feeBps) >= 0. Number.isSafeInteger is true only for a number, so Number(feeBps) is the value itself and the result is the same for every input. A new test passes a fee rate that JSON gives as text. --- src/utils/jupiter.ts | 6 +++--- tests/jupiter.utils.test.ts | 7 +++++++ 2 files changed, 10 insertions(+), 3 deletions(-) diff --git a/src/utils/jupiter.ts b/src/utils/jupiter.ts index b339908f..e96362f3 100644 --- a/src/utils/jupiter.ts +++ b/src/utils/jupiter.ts @@ -231,9 +231,9 @@ const extractJupiterErrorMessage = (errorText: string): string => { export const resolveAppliedFeeBps = ( data: Pick, ): number | null => { - const feeBps = data.platformFee?.feeBps ?? data.feeBps; - // Stryker disable next-line ConditionalExpression: Number.isSafeInteger is false for non-numbers. TypeScript needs typeof before the comparison. - return typeof feeBps === "number" && Number.isSafeInteger(feeBps) && feeBps >= 0 ? feeBps : null; + const feeBps: unknown = data.platformFee?.feeBps ?? data.feeBps; + // Number.isSafeInteger is true only for a number, so Number(feeBps) is the value itself. + return Number.isSafeInteger(feeBps) && Number(feeBps) >= 0 ? Number(feeBps) : null; }; export interface JupiterExecuteResponse { diff --git a/tests/jupiter.utils.test.ts b/tests/jupiter.utils.test.ts index 24f6bf05..7be4bfe9 100644 --- a/tests/jupiter.utils.test.ts +++ b/tests/jupiter.utils.test.ts @@ -427,6 +427,13 @@ describe("resolveAppliedFeeBps", () => { }, ); + test("does not use a fee rate that JSON gives as text", () => { + expect(resolveAppliedFeeBps(JSON.parse('{"feeBps":"50"}'))).toBeNull(); + expect( + resolveAppliedFeeBps(JSON.parse('{"platformFee":{"feeBps":"50","amount":"1"}}')), + ).toBeNull(); + }); + test("does not mistake gasless recoup in total feeBps for the referral fee", async () => { const request = { inputMint: "So11111111111111111111111111111111111111112", From babdd99d7f42e9d7a4d576cc83ab534edccf0b0b Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Mon, 30 Nov 2026 06:04:37 -0300 Subject: [PATCH 344/410] fix(game): keep a zero history quote out of the totals and name key read errors readQuote again returns no quote for a zero price. With Math.max(price, 0), an amount without a finite unit value times a zero price gave NaN instead of 0. A new test checks it, and the positive-price tests kill the <= mutant. The OptionalChaining disable reason is again true: a missing lookup throws into the catch, which also returns null. The player key warning also fires when the database read fails, so its text now says the key could not be read or is not valid. --- src/utils/game.ts | 14 ++++++++------ tests/game-manager.player-keys.test.ts | 2 +- tests/game.history.test.ts | 9 +++++++++ 3 files changed, 18 insertions(+), 7 deletions(-) diff --git a/src/utils/game.ts b/src/utils/game.ts index 593064bc..790f821b 100644 --- a/src/utils/game.ts +++ b/src/utils/game.ts @@ -6473,11 +6473,12 @@ export class GameManager { tokenMint: tokenMint === "SOL" ? WSOL_MINT : tokenMint, }); // A missing lookup has no price. Number.isFinite is false for every value that is - // not a number. A zero or negative price adds nothing to a total. - // Stryker disable next-line OptionalChaining: a missing lookup throws into the catch, and a null quote also adds nothing. + // not a number. A zero price gives no quote, so an amount without a finite unit + // value cannot turn the total into NaN. + // Stryker disable next-line OptionalChaining: a missing lookup throws into the catch, which also returns null. const price = lookup?.price ?? 0; - return Number.isFinite(price) - ? { price: Math.max(price, 0), divisor: Math.pow(10, decimals) } + return Number.isFinite(price) && price > 0 + ? { price, divisor: Math.pow(10, decimals) } : null; } catch { return null; @@ -8602,8 +8603,9 @@ export class GameManager { isCreator, }); } catch (error) { - // A player without a key is normal. A stored key that does not parse is bad data. - console.warn(`⚠️ Stored wallet key for player ${telegramId} is not valid:`, error); + // A player without a key is normal. A key read error or a stored key that does not + // parse is not. + console.warn(`⚠️ Could not read a valid wallet key for player ${telegramId}:`, error); unavailable.push(telegramId); } } diff --git a/tests/game-manager.player-keys.test.ts b/tests/game-manager.player-keys.test.ts index 1992b13e..02ef01d3 100644 --- a/tests/game-manager.player-keys.test.ts +++ b/tests/game-manager.player-keys.test.ts @@ -154,7 +154,7 @@ describe("player key analysis", () => { expect(info.unavailable).toEqual(["2", "3", "4", "walletA", "walletB"]); // Only the stored key that does not parse is reported. A missing or empty key is normal. expect(warnings).toEqual([ - ["⚠️ Stored wallet key for player 3 is not valid:", expect.any(Error)], + ["⚠️ Could not read a valid wallet key for player 3:", expect.any(Error)], ]); expect(info.unmatchedParticipants).toEqual(["walletA", "walletB"]); expect(info.canCompleteCleanup).toBe(false); diff --git a/tests/game.history.test.ts b/tests/game.history.test.ts index 4962b485..2dae59f4 100644 --- a/tests/game.history.test.ts +++ b/tests/game.history.test.ts @@ -403,6 +403,15 @@ describe("getUserGamesHistory fallbacks", () => { expect(result.won.totalUsd).toBe(0); expect(result.lost.totalUsd).toBe(0); }); + test("a zero quote adds nothing, even for an amount without a finite unit value", async () => { + const mint = "COIN_MINT"; + // Infinity times a zero price is NaN, so a zero price must give no quote at all. + const { gm } = await build({ games: [], stats: { wonAmountByToken: { [mint]: Infinity } } }); + priceSpy.mockResolvedValue({ price: 0, identifier: mint, resolvedAt: 0 }); + + const result = await gm.getUserGamesHistory(CTX, 12345n); + expect(result.won.totalUsd).toBe(0); + }); }); describe("formatGamesHeader and formatGamesMessage", () => { From 4392c152492aa2962f3a55f9dd246388f5507d0a Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Mon, 30 Nov 2026 06:05:06 -0300 Subject: [PATCH 345/410] fix(rate-limit): ignore a retry delay that is not a finite number again 140c95b removed the Number.isFinite check in recordRateLimit as redundant, but it was not: Math.max(0, -Infinity), null, false and [] give 0, which recorded a 0 ms block and cleared an existing one, and "5" or true recorded a block that the old code ignored. The only caller passes a finite number, so production did not reach it, but the method is public. The check is back, with tests for -Infinity and untyped JSON values. --- src/utils/telegram-rate-limiter.ts | 4 +++- tests/telegram-rate-limiter.test.ts | 7 ++++++- 2 files changed, 9 insertions(+), 2 deletions(-) diff --git a/src/utils/telegram-rate-limiter.ts b/src/utils/telegram-rate-limiter.ts index e0cf135f..9cc35ada 100644 --- a/src/utils/telegram-rate-limiter.ts +++ b/src/utils/telegram-rate-limiter.ts @@ -208,7 +208,9 @@ export class TelegramRateLimiter { * Record a rate limit error and set the blocked period. */ recordRateLimit(retryAfterSeconds: number, chatId?: number): void { - // retrySecondsToMilliseconds also rejects NaN and Infinity. + // Math.max(0, x) turns -Infinity, null, false and [] into 0, which would clear an + // existing block, so reject every value that is not a finite number first. + if (!Number.isFinite(retryAfterSeconds)) return; const retryAfterMs = retrySecondsToMilliseconds(Math.max(0, retryAfterSeconds)); if (retryAfterMs === null) return; const blockedUntil = Date.now() + retryAfterMs; diff --git a/tests/telegram-rate-limiter.test.ts b/tests/telegram-rate-limiter.test.ts index cba79813..cffe1204 100644 --- a/tests/telegram-rate-limiter.test.ts +++ b/tests/telegram-rate-limiter.test.ts @@ -79,7 +79,12 @@ describe("TelegramRateLimiter", () => { const clock = spyOn(Date, "now").mockReturnValue(1_000); try { limiter.recordRateLimit(5, 123); - for (const invalid of [Infinity, NaN, 1e308]) { + for (const invalid of [Infinity, -Infinity, NaN, 1e308]) { + limiter.recordRateLimit(invalid, 123); + expect(limiter.getWaitTimeMs(123)).toBe(5_000); + } + // Untyped values from a provider error, as JSON gives them. + for (const invalid of JSON.parse('[null, false, [], "5", true]')) { limiter.recordRateLimit(invalid, 123); expect(limiter.getWaitTimeMs(123)).toBe(5_000); } From 38c67cc8681caa81972d8bb173705d978f8ab87a Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Mon, 30 Nov 2026 06:06:26 -0300 Subject: [PATCH 346/410] test(lightning): check that a private click detaches the deposit card The ConditionalExpression disable on the detach check also hid its false mutant, which never detaches a card. A new test clicks another menu on the card message and expects the card to be detached. The true mutant is equivalent (detachMessage with no id binds NULL, which matches no row) and stays a listed survivor without a disable. --- src/handlers/lightning.ts | 3 ++- tests/lightning-handler.test.ts | 12 ++++++++++++ 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/src/handlers/lightning.ts b/src/handlers/lightning.ts index 680b3d83..15eccbde 100644 --- a/src/handlers/lightning.ts +++ b/src/handlers/lightning.ts @@ -156,7 +156,8 @@ export function registerLightningDeposits( (_key, session) => session.type === "deposit_usd" && session.initiatorId === owner, ); const messageId = ctx.callbackQuery?.message?.message_id; - // Stryker disable next-line ConditionalExpression: with no id, detachMessage binds NULL, which matches no row. + // With no id, detachMessage would bind NULL, which matches no row, so the test only + // saves a query. Its true mutant is equivalent and stays a listed survivor. if (messageId) store?.detachMessage(owner, messageId); } await next(); diff --git a/tests/lightning-handler.test.ts b/tests/lightning-handler.test.ts index 38dbb60e..16ead87a 100644 --- a/tests/lightning-handler.test.ts +++ b/tests/lightning-handler.test.ts @@ -763,6 +763,18 @@ describe("status polling", () => { }); }); + test("a private click on the card message detaches the card, so polling does not edit it", async () => { + await withHarness({}, async (h) => { + const deposit = await activeDeposit(h); + const store = h.store; + if (!store) throw new Error("the harness has no deposit store"); + expect(store.get(deposit.id)?.messageId).toBe(10); + // A button of another menu on the same message replaces the card. + await h.click("unrelated_menu"); + expect(store.get(deposit.id)?.messageId).toBeNull(); + }); + }); + test("a card that moved elsewhere is not edited", async () => { await withHarness({}, async (h) => { const deposit = await activeDeposit(h); From 82a4152489be1c6fd1fceee8ae1b6b92264ad201 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Mon, 30 Nov 2026 06:06:26 -0300 Subject: [PATCH 347/410] test(callback-data): refuse a negative count in an unsigned field The ConditionalExpression disable in decodeUnsigned also hid the true and false mutants of the whole test and of parsed < 0, which accept -1 as a player count. A new test decodes -1 in each unsigned confirm field. The false mutant of parsed === null is equivalent (null < 0 is false) and stays a listed survivor without a disable. --- src/utils/callback-data.ts | 3 ++- tests/callback-data.test.ts | 11 +++++++++++ 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/src/utils/callback-data.ts b/src/utils/callback-data.ts index c289e2d4..62ed1ad1 100644 --- a/src/utils/callback-data.ts +++ b/src/utils/callback-data.ts @@ -54,7 +54,8 @@ const encodeSigned = (value: number): string | null => { const decodeUnsigned = (value: string | undefined): number | null => { const parsed = decodeSigned(value); - // Stryker disable next-line ConditionalExpression: null < 0 is false, so null is returned on both paths. TypeScript needs the null check. + // TypeScript needs the null check. Its false mutant is equivalent (null < 0 is false, so + // null is returned on both paths) and stays a listed survivor. return parsed === null || parsed < 0 ? null : parsed; }; diff --git a/tests/callback-data.test.ts b/tests/callback-data.test.ts index 0c4ee7cf..e69e9961 100644 --- a/tests/callback-data.test.ts +++ b/tests/callback-data.test.ts @@ -252,3 +252,14 @@ test("refuses callback data over the Telegram limit even when the fields are val expect(callback.decodeTimeoutChangePayload(data)).toBeNull(); expect(callback.decodeTimeoutChangePayload(data.slice(0, 64))).not.toBeNull(); }); + +test("refuses a negative count in an unsigned field", () => { + const payload = callback.encodeGameConfirmPayload(confirm); + if (!payload) throw new Error("Expected a valid fixture"); + // Players, timeout and minimum players are unsigned. "-1" is -1 in base 36. + for (const index of [3, 4, 5]) { + const parts = payload.split("|"); + parts[index] = "-1"; + expect(callback.decodeGameConfirmPayload(parts.join("|"))).toBeNull(); + } +}); From 9b7aa379c4605f9a0f4a08e0e810cfca57bde1f3 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Mon, 30 Nov 2026 06:07:36 -0300 Subject: [PATCH 348/410] fix(recovery): keep the slot list untyped so the build passes slots.every(isFinalizedSlot) narrowed the RPC slot list to number[], and with noUncheckedIndexedAccess an index read became number | undefined. The type check now uses slots.some(value => !isFinalizedSlot(value)), which gives the same result and does not narrow. --- src/utils/game-creation-recovery.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/utils/game-creation-recovery.ts b/src/utils/game-creation-recovery.ts index daffd7e2..69a728b9 100644 --- a/src/utils/game-creation-recovery.ts +++ b/src/utils/game-creation-recovery.ts @@ -110,7 +110,7 @@ export async function proveExpiredCreationAbsent( if ( !Array.isArray(slots) || !slots.length || - !slots.every(isFinalizedSlot) || + slots.some((value: unknown) => !isFinalizedSlot(value)) || slots.some((value: number) => value > slot) || // Each slot must be above the one before it. slots.slice(1).some((value: number, index: number) => value <= slots[index]) From 5ea4ba72868a94fbfbe57aaac966c8f9a57b576b Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Mon, 30 Nov 2026 06:11:17 -0300 Subject: [PATCH 349/410] test(game): give the new card tests typed Telegram fakes instead of any --- tests/game-manager.card-layout.test.ts | 10 +- ...me-manager.update-message-recovery.test.ts | 97 ++++++++++++------- 2 files changed, 66 insertions(+), 41 deletions(-) diff --git a/tests/game-manager.card-layout.test.ts b/tests/game-manager.card-layout.test.ts index bfa1b1db..2f1b2f68 100644 --- a/tests/game-manager.card-layout.test.ts +++ b/tests/game-manager.card-layout.test.ts @@ -1,4 +1,5 @@ import { afterEach, beforeEach, describe, expect, spyOn, test } from "bun:test"; +import type { Api, Context } from "grammy"; import { PublicKey } from "#solana"; import { GameManager } from "../src/utils/game"; import { formatAmount } from "../src/utils/format-amount"; @@ -8,6 +9,7 @@ import { makeWalletStub, resetGameManager, } from "./helpers/game-manager"; +import { fake } from "./helpers/fakes"; const GAME = new PublicKey("BPFLoader1111111111111111111111111111111111"); const ADDRESS = GAME.toBase58(); @@ -68,17 +70,17 @@ async function render(options: Render) { extra: options.db, }), ); - const ctx: any = { + const ctx = fake({ chat: { id: 1, type: "supergroup" }, - api: { + api: fake({ getChatMember: async (_chat: number, id: unknown) => { lookups.push(id); if (options.lookupFails) throw new Error("synthetic member lookup failure"); const name = options.names?.[String(id)]; return { user: name ? { first_name: name } : { username: `user${id}` } }; }, - }, - }; + }), + }); const result = await gm.formatGameMessage( ctx, GAME, diff --git a/tests/game-manager.update-message-recovery.test.ts b/tests/game-manager.update-message-recovery.test.ts index dbd62e95..3abe7839 100644 --- a/tests/game-manager.update-message-recovery.test.ts +++ b/tests/game-manager.update-message-recovery.test.ts @@ -1,4 +1,5 @@ import { afterEach, beforeEach, describe, expect, spyOn, test } from "bun:test"; +import type { Api, Context } from "grammy"; import { PublicKey } from "#solana"; import { makeDbStub, @@ -11,6 +12,8 @@ import { GameManager } from "../src/utils/game"; import { ChatDatabase } from "../src/utils/chat-database"; import { CHAT_MEDIA_DISABLED_SENTINEL } from "../src/utils/constants"; import { resetTestDatabase } from "./helpers/database"; +import { fake } from "./helpers/fakes"; +import type { GameMessage } from "../src/types"; // Each Telegram method answers from its own script, one entry per call. // An entry made with fail() throws; any other entry is returned. When a @@ -34,44 +37,60 @@ const ORIGINAL = 46; const REPLACEMENT = 777; const EMPTY_KEYBOARD = { reply_markup: { inline_keyboard: [] } }; +// The fields of a Telegram options or media object that these tests read. +type Payload = { + caption?: string; + parse_mode?: string; + type?: string; + media?: string; + reply_markup?: { inline_keyboard: unknown[] }; +}; +const isPayload = (value: unknown): value is Payload => typeof value === "object" && value !== null; + function scriptedCtx(script: Partial> = {}) { - const calls: any[][] = []; - const answer = async (method: Method, args: any[], fallback: unknown) => { + const calls: [Method, ...unknown[]][] = []; + const answer = async (method: Method, args: unknown[], fallback: unknown) => { calls.push([method, ...args]); const queue = script[method]; const entry = queue && queue.length > 0 ? queue.shift() : fallback; if (isFailure(entry)) throw entry.fail; return entry; }; - const sent = (chatId: number) => ({ message_id: REPLACEMENT, chat: { id: chatId } }); - const ctx: any = { + const sent = (chatId: unknown) => ({ message_id: REPLACEMENT, chat: { id: chatId } }); + const ctx = fake({ chat: { id: CHAT, type: "supergroup" }, - api: { + api: fake({ getChatMember: async (_chat: number, id: number) => ({ user: { username: `user${id}` }, status: "member", }), - editMessageCaption: (...args: any[]) => answer("caption", args, { message_id: ORIGINAL }), - editMessageMedia: (...args: any[]) => answer("media", args, { message_id: ORIGINAL }), - editMessageText: (...args: any[]) => answer("text", args, { message_id: ORIGINAL }), - editMessageReplyMarkup: (...args: any[]) => answer("retire", args, true), - deleteMessage: (...args: any[]) => answer("delete", args, true), - sendMessage: (...args: any[]) => answer("send", args, sent(args[0])), - sendVideo: (...args: any[]) => answer("video", args, sent(args[0])), - }, - }; - const call = (index: number): any[] => { + editMessageCaption: (...args: unknown[]) => answer("caption", args, { message_id: ORIGINAL }), + editMessageMedia: (...args: unknown[]) => answer("media", args, { message_id: ORIGINAL }), + editMessageText: (...args: unknown[]) => answer("text", args, { message_id: ORIGINAL }), + editMessageReplyMarkup: (...args: unknown[]) => answer("retire", args, true), + deleteMessage: (...args: unknown[]) => answer("delete", args, true), + sendMessage: (...args: unknown[]) => answer("send", args, sent(args[0])), + sendVideo: (...args: unknown[]) => answer("video", args, sent(args[0])), + }), + }); + const call = (index: number): [Method, ...unknown[]] => { const entry = calls[index]; if (!entry) throw new Error(`Telegram call ${index} was not made`); return entry; }; - return { ctx, calls, call, names: () => calls.map((entry) => entry[0]) }; + // The options or media object at `position` in call `index` (the method name is position 0). + const payload = (index: number, position: number): Payload => { + const value = call(index)[position]; + if (!isPayload(value)) throw new Error(`Telegram call ${index} has no object at ${position}`); + return value; + }; + return { ctx, calls, call, payload, names: () => calls.map((entry) => entry[0]) }; } function managerFor( status: "Active" | "Completed", address: string, - options: { usesVideo?: boolean; saveGameMessage?: (...args: any[]) => void } = {}, + options: { usesVideo?: boolean; saveGameMessage?: (...args: unknown[]) => void } = {}, ) { resetGameManager(); const completed = status === "Completed"; @@ -84,7 +103,7 @@ function managerFor( timeout: 60, gameType: { coinflip: {} }, }; - const saved: any[] = []; + const saved: unknown[][] = []; const gm = GameManager.getInstance( makeProgramStub(gameAccount), makeWalletStub({ tokenFormatter: (n, d) => (Number(n) / Math.pow(10, d)).toFixed(0) }), @@ -94,20 +113,20 @@ function managerFor( getPlayerTelegramId: () => null, saveGameMessage: options.saveGameMessage ?? - ((...args: any[]) => { + ((...args: unknown[]) => { saved.push(args); }), }, }), ); - const messages = new Map(); - const card: any = { chatId: CHAT, messageId: ORIGINAL }; + const messages = new Map(); + const card: GameMessage = { chatId: CHAT, messageId: ORIGINAL }; if (options.usesVideo !== undefined) card.usesVideo = options.usesVideo; messages.set(CHAT, card); // The database restore always sets `usesVideo` to true, and a public send adds extra // Telegram calls to each script. Typed bracket access seeds the exact card instead. gm["activeGameMessages"].set(address, messages); - const update = (ctx: any) => + const update = (ctx: Context) => withinTestDeadline( gm.updateGameMessage( ctx, @@ -150,12 +169,13 @@ describe("game card edit arguments", () => { await game.update(telegram.ctx); expect(telegram.names()).toEqual(["caption"]); - const [, chatId, messageId, options] = telegram.call(0); + const [, chatId, messageId] = telegram.call(0); + const options = telegram.payload(0, 3); expect([chatId, messageId]).toEqual([CHAT, ORIGINAL]); expect(Object.keys(options).sort()).toEqual(["caption", "parse_mode", "reply_markup"]); expect(options.parse_mode).toBe("HTML"); - expect(options.caption.length).toBeGreaterThan(0); - expect(options.reply_markup.inline_keyboard.length).toBeGreaterThan(0); + expect(options.caption?.length).toBeGreaterThan(0); + expect(options.reply_markup?.inline_keyboard.length).toBeGreaterThan(0); // A card with no recorded media flag is known to be media after the edit. expect(game.card()?.usesVideo).toBe(true); expect(warnings()).toEqual([]); @@ -167,12 +187,14 @@ describe("game card edit arguments", () => { await game.update(telegram.ctx); expect(telegram.names()).toEqual(["media"]); - const [, chatId, messageId, media, extra] = telegram.call(0); + const [, chatId, messageId] = telegram.call(0); + const media = telegram.payload(0, 3); + const extra = telegram.payload(0, 4); expect([chatId, messageId]).toEqual([CHAT, ORIGINAL]); expect(media.type).toBe("video"); - expect(media.media.length).toBeGreaterThan(0); + expect(media.media?.length).toBeGreaterThan(0); expect(media.parse_mode).toBe("HTML"); - expect(media.caption.length).toBeGreaterThan(0); + expect(media.caption?.length).toBeGreaterThan(0); expect(Object.keys(extra)).toEqual(["reply_markup"]); expect(game.card()?.usesVideo).toBe(true); }); @@ -183,9 +205,10 @@ describe("game card edit arguments", () => { await game.update(telegram.ctx); expect(telegram.names()).toEqual(["text", "caption"]); - const [, , , text, textOptions] = telegram.call(0); + const [, , , text] = telegram.call(0); + const textOptions = telegram.payload(0, 4); expect(textOptions.parse_mode).toBe("HTML"); - expect(textOptions.reply_markup.inline_keyboard.length).toBeGreaterThan(0); + expect(textOptions.reply_markup?.inline_keyboard.length).toBeGreaterThan(0); expect(telegram.call(1)).toEqual([ "caption", CHAT, @@ -208,7 +231,7 @@ describe("game card recovery after a failed media edit", () => { await game.update(telegram.ctx); expect(telegram.names()).toEqual(["caption", "text", "caption", "retire", "send"]); - const [, , , captionOptions] = telegram.call(0); + const captionOptions = telegram.payload(0, 3); const text = captionOptions.caption; const keyboard = captionOptions.reply_markup; expect(telegram.call(1)).toEqual([ @@ -222,7 +245,7 @@ describe("game card recovery after a failed media edit", () => { expect(telegram.call(2)).toEqual(["caption", CHAT, ORIGINAL, captionOptions]); expect(telegram.call(3)).toEqual(["retire", CHAT, ORIGINAL, EMPTY_KEYBOARD]); expect(telegram.call(4).slice(0, 3)).toEqual(["send", CHAT, text]); - expect(telegram.call(4)[3].reply_markup).toBe(keyboard); + expect(telegram.payload(4, 3).reply_markup).toBe(keyboard); expect(game.saved).toEqual([[expect.any(String), REPLACEMENT, CHAT]]); expect(game.card()).toEqual({ chatId: CHAT, messageId: REPLACEMENT, usesVideo: false }); expect(warnings()).toEqual(["Falling back to text after game media update (1) failure:"]); @@ -238,7 +261,8 @@ describe("game card recovery after a failed media edit", () => { await game.update(telegram.ctx); expect(telegram.names()).toEqual(["media", "text", "caption"]); - const [, , , media, extra] = telegram.call(0); + const media = telegram.payload(0, 3); + const extra = telegram.payload(0, 4); expect(telegram.call(2)).toEqual([ "caption", CHAT, @@ -292,8 +316,7 @@ describe("game card recovery after a failed media edit", () => { }); await game.update(telegram.ctx); - const [, , , , extra] = telegram.call(0); - expect(extra.reply_markup).toBeUndefined(); + expect(telegram.payload(0, 4).reply_markup).toBeUndefined(); expect(telegram.names()).toEqual(["media", "text", "caption", "retire", "send"]); expect(game.card()?.messageId).toBe(ORIGINAL); }); @@ -307,7 +330,7 @@ describe("game card recovery after a failed media edit", () => { }); await game.update(telegram.ctx); - const keyboard = telegram.call(0)[3].reply_markup; + const keyboard = telegram.payload(0, 3).reply_markup; expect(telegram.names()).toEqual(["caption", "text", "caption", "retire", "send", "retire"]); expect(telegram.call(5)).toEqual(["retire", CHAT, ORIGINAL, { reply_markup: keyboard }]); expect(game.card()?.messageId).toBe(ORIGINAL); @@ -374,7 +397,7 @@ describe("game card edits for a chat with media turned off", () => { await game.update(telegram.ctx); expect(telegram.names()).toEqual(["caption", "text", "retire", "send"]); - const [, , , captionOptions] = telegram.call(0); + const captionOptions = telegram.payload(0, 3); expect(Object.keys(captionOptions).sort()).toEqual(["caption", "parse_mode", "reply_markup"]); expect(captionOptions.parse_mode).toBe("HTML"); expect(game.card()).toEqual({ chatId: CHAT, messageId: REPLACEMENT, usesVideo: false }); From 0a005f0573eb7783b4660728d087fe837e302c74 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Mon, 30 Nov 2026 06:17:22 -0300 Subject: [PATCH 350/410] test(swap): check the examples label in the custom token prompt --- src/utils/swap/prompts.ts | 1 - tests/swap-prompts.test.ts | 2 ++ 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/src/utils/swap/prompts.ts b/src/utils/swap/prompts.ts index abec3b1d..94060c84 100644 --- a/src/utils/swap/prompts.ts +++ b/src/utils/swap/prompts.ts @@ -11,7 +11,6 @@ export const buildCustomTokenPrompt = (fromToken: string): string => { "", "Reply to this message with the token mint address or symbol.", "", - // Stryker disable next-line StringLiteral: Cosmetic label only. The reply instructions and both usable examples are tested. "Examples:", "• EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v (USDC)", "• BONK", diff --git a/tests/swap-prompts.test.ts b/tests/swap-prompts.test.ts index fae22c6b..e50f7e0a 100644 --- a/tests/swap-prompts.test.ts +++ b/tests/swap-prompts.test.ts @@ -16,6 +16,8 @@ test("keeps the selected input, reply instructions and both supported example in expect(paragraphs.every((paragraph) => paragraph.trim().length > 0)).toBe(true); expect(paragraphs[1]).toContain("SOL"); expect(paragraphs[2]).toMatch(/reply.+mint address or symbol/i); + // The examples start with their label line. + expect(paragraphs[3]?.split("\n")[0]).toBe("Examples:"); const examples = Array.from( (paragraphs[3] ?? "").matchAll(/([^<]+)<\/code>/g), (match) => match[1], From 42351da6df11cc4ca05549c0ae87e7a6c3f36418 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Mon, 30 Nov 2026 06:00:58 -0300 Subject: [PATCH 351/410] test(rate-limit): check that consume prunes expired buckets once per window The throttled prune in consume only bounds memory, so no public call showed it. The new test reads the private bucket map and checks that an expired bucket stays inside the throttle and goes one window after the last prune. It kills the nine surviving mutants in pruneExpiredBuckets and in the consume prune call. --- tests/rate-limiter.windows.test.ts | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/tests/rate-limiter.windows.test.ts b/tests/rate-limiter.windows.test.ts index 2c3ad34f..d72e65f4 100644 --- a/tests/rate-limiter.windows.test.ts +++ b/tests/rate-limiter.windows.test.ts @@ -92,6 +92,29 @@ describe("SlidingWindowRateLimiter edge cases", () => { now = 1_500; expect(limiter.getActiveEntries()).toBe(0); }); + + test("consume prunes expired buckets at most once per window", () => { + let now = 10_000; + const limiter = new SlidingWindowRateLimiter(1_000, () => now); + // The throttled prune only bounds memory. getActiveEntries forces a prune, so no public + // call shows the map size before that. Typed bracket access reads the private map. + const stored = () => [...limiter["buckets"].keys()].sort(); + + limiter.consume("a", 5); + now = 10_600; + limiter.consume("b", 5); + expect(stored()).toEqual(["a", "b"]); + + // The prune pass at 10_600 started the throttle, so "a" stays after it expires at 11_000. + now = 11_000; + limiter.consume("c", 5); + expect(stored()).toEqual(["a", "b", "c"]); + + // One full window after the last prune, the next consume drops "a" and "b". + now = 11_600; + limiter.consume("d", 5); + expect(stored()).toEqual(["c", "d"]); + }); }); test.each([ From afecce9e1ddff5adba1a30d56a01cde1b05f28fb Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Mon, 30 Nov 2026 06:03:19 -0300 Subject: [PATCH 352/410] refactor(game): keep the unjoin mint text conversion free of an equivalent mutant The Stryker disable comment before the catch in resolvePublicKeyString did not apply, because Stryker reads only leading comments and this one trailed the return. The empty-catch mutant returned undefined instead of null, and every use only checks the mint for truthiness. The text conversion now assigns inside the try and returns the variable, so a failing toString still gives null and the catch has nothing to empty. --- src/utils/game.ts | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/src/utils/game.ts b/src/utils/game.ts index 790f821b..9a845334 100644 --- a/src/utils/game.ts +++ b/src/utils/game.ts @@ -8747,12 +8747,13 @@ export class GameManager { } catch { // Not key-like: use its text form. } + let text: string | null = null; try { - return value.toString(); - // Stryker disable next-line BlockStatement: every use reads an undefined mint like null. + text = value.toString(); } catch { - return null; + // No text form: no mint. } + return text; }; const tokenMintStr = resolvePublicKeyString(gameAccount?.tokenMint); From 99c69cdda7704e5901b8a1e906c9e118fee90730 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Mon, 30 Nov 2026 06:04:30 -0300 Subject: [PATCH 353/410] test(game): check the join recovery label and a quiet hydrate without chain timing The join tests now record the confirm call and check that a direct join passes "Player join", which selects the probe that looks for the player in the game. A new hydrate test checks that a database without setGameChainTiming saves the game and logs no warning. --- tests/game-manager.join-attempts.test.ts | 27 +++++++++++++++++++----- tests/game.hydrate.test.ts | 11 ++++++++++ 2 files changed, 33 insertions(+), 5 deletions(-) diff --git a/tests/game-manager.join-attempts.test.ts b/tests/game-manager.join-attempts.test.ts index 9b5597e5..8612ca58 100644 --- a/tests/game-manager.join-attempts.test.ts +++ b/tests/game-manager.join-attempts.test.ts @@ -98,13 +98,15 @@ async function join(options: Options = {}) { (async () => fake({ accounts: {}, setupInstructions: [SETUP_IX] })); const steps = [...(options.confirm ?? [async () => "CONFIRMED"])]; let confirmFailed = false; + const confirms: string[][] = []; gm["confirmTransactionWithRecovery"] = async ( - _sig: string, - _pda: PublicKey, - _label: string, - _player: PublicKey, + sig: string, + pda: PublicKey, + label: string, + joiner: PublicKey, resend: () => Promise, ) => { + confirms.push([sig, pda.toBase58(), label, joiner.toBase58()]); const step = steps.shift(); if (!step) throw new Error("unexpected confirm"); try { @@ -135,7 +137,18 @@ async function join(options: Options = {}) { player.publicKey.toBase58(), { status: "pending", joinSignature: signature, lastVerifiedAt: null }, ]; - return { result, player, sends, resends, saved, verified, completions, reads, pending }; + return { + result, + player, + sends, + resends, + saved, + verified, + completions, + reads, + pending, + confirms, + }; } const timeout = () => async () => { @@ -149,6 +162,10 @@ describe("join attempts", () => { expect(run.sends).toEqual([[[SETUP_IX, JOIN_IX], [run.player], { priorityFee: true }]]); expect(run.saved).toEqual([run.pending("SIG1")]); expect(run.verified).toEqual([{ joinSignature: "CONFIRMED" }]); + // "Player join" makes the recovery check that the player is recorded in the game. + expect(run.confirms).toEqual([ + ["SIG1", ADDRESS, "Player join", run.player.publicKey.toBase58()], + ]); }); test("a resend during confirmation saves and confirms the new signature", async () => { diff --git a/tests/game.hydrate.test.ts b/tests/game.hydrate.test.ts index 5501353a..6669d345 100644 --- a/tests/game.hydrate.test.ts +++ b/tests/game.hydrate.test.ts @@ -198,6 +198,17 @@ describe("hydrateGameDataFromChain fallbacks", () => { expect(timings).toEqual([[GAME, now * 1000, (now + 3600) * 1000]]); }); + test("skips the chain timing quietly when the database cannot store it", async () => { + const saved: unknown[][] = []; + const { gm } = makeManager({ db: { saveGame: (...args: unknown[]) => saved.push(args) } }); + + const result = await gm.ensureGameDataFromChain(GAME); + + expect(result?.game_address).toBe(GAME); + expect(saved).toHaveLength(1); + expect(warnSpy).not.toHaveBeenCalled(); + }); + test.each([ ["no start time", { createdAt: 0, timeout: 3600 }], ["no timeout", { createdAt: 1_700_000_000, timeout: 0 }], From ca9dcfb97d728d6b6b0138bc57c3dfd854c964bd Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Mon, 30 Nov 2026 06:04:30 -0300 Subject: [PATCH 354/410] test(game): exclude the equivalent empty-message default in the join retry The default text for a join error without a message only feeds the keyword checks for timeouts and token account failures. Any text without those words, such as the Stryker marker, takes the same throw path, so the StringLiteral mutant on that line is equivalent. --- src/utils/game.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/src/utils/game.ts b/src/utils/game.ts index 9a845334..32734bd5 100644 --- a/src/utils/game.ts +++ b/src/utils/game.ts @@ -5679,6 +5679,7 @@ export class GameManager { ); break; } catch (joinError: any) { + // Stryker disable next-line StringLiteral: any text without the words checked below takes the same path. const message = joinError?.message ?? ""; const normalized = message.toLowerCase(); const needsAtaCreation = setupInstructions.length > 0; From 2f29d2277479982c73760808a21b115aac6e5869 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Mon, 30 Nov 2026 06:07:28 -0300 Subject: [PATCH 355/410] refactor(telegram): drop equivalent parts of the outbound diagnostic checks The stack frame regex had an optional async group and a one-or-more name, but test() only needs "at", spaces and one non-space, which "async" already starts with. The source location regex repeated the folder group, but any deeper path ends with one "/dir/file.ext" part that matches alone. The structured scan now skips primitives with Object(value) !== value, which also covers null, so the old typeof check that let strings recurse into harmless index keys is gone. New tests check a frame without a location and a word that ends in "at". Every weapon-regex mutant of both new regexes is killed. --- src/utils/outbound-error-guard.ts | 11 +++++++---- tests/outbound-error-guard.test.ts | 2 ++ 2 files changed, 9 insertions(+), 4 deletions(-) diff --git a/src/utils/outbound-error-guard.ts b/src/utils/outbound-error-guard.ts index 18f32e61..4568bd40 100644 --- a/src/utils/outbound-error-guard.ts +++ b/src/utils/outbound-error-guard.ts @@ -5,9 +5,11 @@ export const GENERIC_USER_ERROR_MESSAGE = const EXCEPTION_NAME = /\b(?:Aggregate|Assertion|Eval|Internal|ProtocolHttp|ProtocolResponse|Range|Reference|Syntax|Type|URI|Zod)?Error\b|\bException\b/i; -const STACK_FRAME = /^\s*(?:at\s+(?:async\s+)?\S+|caused by\s*:)/im; -// Only the start of a source location is needed. Column numbers are optional. -const SOURCE_LOCATION = /(?:file:\/\/|\/(?:[^\s/:]+\/)+[^\s/:]+\.(?:[cm]?[jt]sx?|rs|py)):\d/i; +// "at async name" also starts with "at" and a non-space, so the frame check needs no async case. +const STACK_FRAME = /^\s*(?:at\s+\S|caused by\s*:)/im; +// Only the start of a source location is needed. Column numbers are optional. A deeper path +// always ends with one "/dir/file.ext" part, so the check needs only the last folder. +const SOURCE_LOCATION = /(?:file:\/\/|\/[^\s/:]+\/[^\s/:]+\.(?:[cm]?[jt]sx?|rs|py)):\d/i; const VALIDATOR_DIAGNOSTIC = /\b(?:invalid_type|invalid_union|invalid_value|unrecognized_keys|too_small|too_big)\b|"(?:expected|received|code|path|issues)"\s*:/i; const NETWORK_DIAGNOSTIC = @@ -31,7 +33,8 @@ const looksLikeSerializedDiagnostic = (text: string): boolean => { const inspect = (value: unknown, depth = 0): boolean => { if (depth > 5) return false; - if (!value || typeof value !== "object") return false; + // Primitives, null included, have no keys to inspect. + if (Object(value) !== value) return false; if (Array.isArray(value)) return value.some((entry) => inspect(entry, depth + 1)); const record = value as Record; diff --git a/tests/outbound-error-guard.test.ts b/tests/outbound-error-guard.test.ts index d93bb7cf..7eebcccf 100644 --- a/tests/outbound-error-guard.test.ts +++ b/tests/outbound-error-guard.test.ts @@ -24,6 +24,7 @@ describe("outbound Telegram error guard", () => { test.each([ ["first-line stack frame", "at processReceipt"], ["indented stack frame", "No confirmation\n at async processReceipt"], + ["stack frame without a location", "Payment stalled\n at settle"], ["cause header spacing", "Caused by : no confirmation"], ["compiled JavaScript location", "/workspace/generated/bot.cjs:44"], ["plain Python location", "/workspace/tasks/run.py:28"], @@ -46,6 +47,7 @@ describe("outbound Telegram error guard", () => { ["normal documentation link", "Read https://example.invalid/help/faq"], ["normal JSON array", ' [{"title":"Round 2"}] '], ["plain heading", "Next steps before the request concludes"], + ["word that ends in at", "Great job, see you at noon"], ["friendly non-JSON notice", "[Summary: prizes arrive after confirmation]"], ] as const)("does not replace %s", (_case, text) => { expect(guardOutboundText(text)).toBe(text); From 8cdb6c2677d5c1bf023607c3880ec11466a22882 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Mon, 30 Nov 2026 06:09:40 -0300 Subject: [PATCH 356/410] test(fees): check that an unusable RPC fee scales the fallback base fee The old fee cases used a multiplier of 1 and no extra fee, so the scaled fallback equaled the plain fallback that getOrCompute uses for an unusable budget. With a multiplier of 2 and an extra fee of 5, a zero or unsafe RPC fee must give 37 * 2 + 5. This kills six surviving mutants of the fee check in estimateFee. --- tests/fee-budget.behavior.test.ts | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/tests/fee-budget.behavior.test.ts b/tests/fee-budget.behavior.test.ts index 6e4c1787..ceab0628 100644 --- a/tests/fee-budget.behavior.test.ts +++ b/tests/fee-budget.behavior.test.ts @@ -219,6 +219,25 @@ test.each([ expect(await manager.getSingleTransactionLamports()).toBe(expected); }); +test.each([ + [0n, 79], + [100n, 205], + [9_007_199_254_740_993n, 79], +] as const)( + "scales the fallback base fee, not the RPC fee, when the RPC returns %p", + async (fee, expected) => { + // A multiplier and an extra fee make the scaled fallback (37 * 2 + 5) differ from the + // plain fallback that an unusable budget gets. + const { connection } = connectionFor(fee); + const manager = FeeBudgetManager.createForTest(connection, { + fallbackSingleTxLamports: 37, + singleTxMultiplier: 2, + singleTxExtraLamports: 5, + }); + expect(await manager.getSingleTransactionLamports()).toBe(expected); + }, +); + test("falls back if a valid base fee overflows when the safety multiplier is applied", async () => { const { connection } = connectionFor(9_007_199_254_740_991n); const manager = FeeBudgetManager.createForTest(connection, { From 1f89936ad149aa8a922891c45c98a07a07e2679e Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Mon, 30 Nov 2026 06:09:40 -0300 Subject: [PATCH 357/410] refactor(fees): drop the null check that the safe integer check already makes estimateFee turned a missing fee into null and then checked lamports !== null. Number(null) is 0, which the positive check rejects, so the fee now goes through Number directly and the separate null check is gone. Every other value goes through the same Number call as before. --- src/utils/fee-budget.ts | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/utils/fee-budget.ts b/src/utils/fee-budget.ts index 75465b99..20c500c6 100644 --- a/src/utils/fee-budget.ts +++ b/src/utils/fee-budget.ts @@ -359,9 +359,10 @@ export class FeeBudgetManager implements FeeBudgetProvider { }).compileToV0Message(); const fee = await this.connection.getFeeForMessage(message); const rawLamports = typeof fee === "number" ? fee : (fee?.value ?? null); - const lamports = rawLamports === null ? null : Number(rawLamports); + // Number(null) is 0, which the positive check rejects like a missing fee. + const lamports = Number(rawLamports); - if (lamports !== null && Number.isSafeInteger(lamports) && lamports > 0) { + if (Number.isSafeInteger(lamports) && lamports > 0) { return lamports; } } catch (error) { From 0968def62088d12d9741d76971cf95a6f8eaca68 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Mon, 30 Nov 2026 06:13:44 -0300 Subject: [PATCH 358/410] refactor(mentions): mark mention ranges without index loops findNamedUsers marked every UTF-16 unit of each mention in a set with a for loop and then rebuilt each word with a second loop. Both loops had an index >= start guard that was always true, so its mutant was equivalent, and the other loop-test mutants ran forever until Stryker timed them out. The function now keeps the mention ranges and maps the units of each word from slice and split. A range with a fractional or infinite start covered no whole unit before, so it is not kept now. Stryker on the changed lines with the mention and challenge tests: 70 mutants, none of the new lines survive. --- src/utils/user-mention.ts | 23 +++++++++++++---------- 1 file changed, 13 insertions(+), 10 deletions(-) diff --git a/src/utils/user-mention.ts b/src/utils/user-mention.ts index 532d4b29..ecdd5f11 100644 --- a/src/utils/user-mention.ts +++ b/src/utils/user-mention.ts @@ -207,7 +207,11 @@ export const findNamedUsers = ( end: match.index + match[0].length, })); const found: { person: NamedPerson; position: number }[] = []; - const marked = new Set(); + // The UTF-16 units that Telegram's entities cover. A range with a fractional or + // infinite start covers no whole unit, so it is not kept. + const markedRanges = new Set(); + const isMarked = (index: number) => + markedRanges.values().some((range) => index >= range.start && index < range.end); for (const entity of entities) { const person = entity && typeof entity.type === "string" ? entityPerson(entity, text) : null; @@ -220,21 +224,20 @@ export const findNamedUsers = ( : -1; // Someone who cannot be placed goes last and keeps every word. found.push({ person, position: first === -1 ? words.length : first }); - if (range) { - const end = Math.min(range.end, text.length); - for (let index = range.start; index >= range.start && index < end; index += 1) { - marked.add(index); - } + if (range && Number.isInteger(range.start)) { + markedRanges.add(range); } } const removed = new Set(); spans.forEach((span, position) => { const word = words[position]!; - let unmarked = ""; - for (let index = span.start; index >= span.start && index < span.end; index += 1) { - unmarked += marked.has(index) ? " " : text.charAt(index); - } + // split("") gives UTF-16 units, the same units as Telegram's offsets. + const unmarked = text + .slice(span.start, span.end) + .split("") + .map((unit, offset) => (isMarked(span.start + offset) ? " " : unit)) + .join(""); const mentioned = unmarked !== word; if (position === 0 || (!mentioned && !isTypedName(word, position))) { return; From 5f4fca9e5dc34c608deebc6b7d4b44af2a332b6a Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Mon, 30 Nov 2026 06:15:49 -0300 Subject: [PATCH 359/410] test(game-db): check a first-ticket unjoin, a repeated completion and cleanup error logs An unjoin from ticket 0 with a moved player must put that player in ticket 0, which the old test at ticket 1 could not tell from a plain removal. A second completeGame without a pot keeps the stored pot. Each failing cleanup delete must name its own step in the error log. These kill five surviving mutants in recordGameParticipantUnjoined and cleanupOldGames. --- tests/game-database.test.ts | 50 +++++++++++++++++++++++++++++++++++++ 1 file changed, 50 insertions(+) diff --git a/tests/game-database.test.ts b/tests/game-database.test.ts index 8d9a9409..e2b522c0 100644 --- a/tests/game-database.test.ts +++ b/tests/game-database.test.ts @@ -153,6 +153,31 @@ test("GameDatabase: CRUD for games, mappings, participants, and slot updates", ( expect(db.getGameParticipants("gameA")).toEqual(["tg_creator"]); }); +test("an unjoin from the first ticket puts the moved player in that ticket", () => { + const db = GameDatabase.getInstance(); + db.saveGame("swap-game", "tg_creator", 1000, "coinflip"); + db.recordGameParticipantJoined("swap-game", "pub_a", 0, 1); + db.recordGameParticipantJoined("swap-game", "pub_b", 1, 2); + db.recordGameParticipantJoined("swap-game", "pub_c", 2, 3); + + // The program moves the last ticket into the freed slot, so the order changes. + db.recordGameParticipantUnjoined("swap-game", "pub_a", 0, 2, "pub_c"); + + expect(db.getGameParticipantAddresses("swap-game")).toEqual(["pub_c", "pub_b"]); +}); + +test("completing a game again without a pot keeps the stored pot", () => { + const db = GameDatabase.getInstance(); + const now = Date.now(); + db.saveGame("repeat-finance", "creator", 100, "coinflip", "mint", "TOK"); + db.completeGame("repeat-finance", "winner", now - 100, 2_000); + db.completeGame("repeat-finance", "winner", now - 50); + + expect(db.getCompletedGameFinance(now - 1_000, now + 1)).toEqual([ + expect.objectContaining({ games: 1, estimatedTotalAmountRaw: "2000" }), + ]); +}); + test("getCompletedGameFinance groups completed pots and excludes cancellations", () => { const db = GameDatabase.getInstance(); const now = Date.now(); @@ -1368,6 +1393,31 @@ test("cleanupOldGames keeps a game and its linked rows if deleting the game fail } }); +test.each([ + ["game_participants", "deleting old game participants"], + ["game_challenges", "deleting old game challenges"], + ["games", "deleting old games"], +] as const)("cleanupOldGames names the failed delete from %s in its error log", (table, step) => { + const db = GameDatabase.getInstance(); + const raw = (db as unknown as { db: Database }).db; + const game = "old-logged-game"; + db.saveGame(game, "creator", 100, "coinflip"); + db.saveGameParticipant(game, "42", "player-wallet"); + db.saveGameChallenge(game, [RIVAL]); + raw.prepare("UPDATE games SET created_at = ? WHERE game_address = ?").run(1_000, game); + raw.exec(`CREATE TEMP TRIGGER fail_test_cleanup BEFORE DELETE ON ${table} + BEGIN SELECT RAISE(ABORT, 'cleanup step failed'); END`); + const error = spyOn(console, "error").mockImplementation(() => {}); + + try { + expect(() => db.cleanupOldGames()).toThrow("cleanup step failed"); + expect(error.mock.calls.map((call) => call[0])).toEqual([`[Game DB] Error during ${step}:`]); + } finally { + error.mockRestore(); + raw.exec("DROP TRIGGER IF EXISTS fail_test_cleanup"); + } +}); + test("cleanupOldGames leaves games at the production thirty-day boundary", () => { const db = GameDatabase.getInstance(); const raw = (db as unknown as { db: Database }).db; From ed19213b0459c2f2883409ede30bf9164db10668 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Mon, 30 Nov 2026 06:15:49 -0300 Subject: [PATCH 360/410] refactor(game-db): drop the typeof check that Number.isFinite already makes Number.isFinite is false for every value that is not a number, so typeof completedAt === "number" never changed the result and its mutant was equivalent. Number(completedAt) keeps the type checker happy and returns a finite number unchanged, -0 included. --- src/utils/game-database.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/utils/game-database.ts b/src/utils/game-database.ts index 20272dfc..6638aad4 100644 --- a/src/utils/game-database.ts +++ b/src/utils/game-database.ts @@ -501,8 +501,8 @@ export class GameDatabase extends BaseDatabase { completedAt?: number, totalPot?: number, ): void { - const timestamp = - typeof completedAt === "number" && Number.isFinite(completedAt) ? completedAt : Date.now(); + // Number.isFinite is false for every non-number, and Number keeps a finite number as is. + const timestamp = Number.isFinite(completedAt) ? Number(completedAt) : Date.now(); const params: Array = [winnerAddress, timestamp, "completed"]; let sql = "UPDATE games SET winner_address = ?, completed_at = ?, status = ?"; From f852ba5df11090fd66a6b3d7ae05014ef18fabdf Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Mon, 30 Nov 2026 06:19:40 -0300 Subject: [PATCH 361/410] test(challenges): check reply refusals for another picked user and bare @ mentions A reply that picks a different user from the mention list must be refused, and a bare @ mention must never match a replied user whose username is missing, empty or only an @. These kill the surviving mutants of the id check and the empty-username check in namesUser. --- tests/game-challenge.test.ts | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/tests/game-challenge.test.ts b/tests/game-challenge.test.ts index 9535a226..d4a0119b 100644 --- a/tests/game-challenge.test.ts +++ b/tests/game-challenge.test.ts @@ -285,6 +285,38 @@ describe("namedReplyRefusal", () => { ).toBe("To challenge someone, reply to their message or name them without replying."); }); + test("a reply picking someone else from the mention list is refused", () => { + const rival = { id: 5150, is_bot: false, first_name: "Ana" }; + const bo = { id: 6262, is_bot: false, first_name: "Bo" }; + expect( + namedReplyRefusal( + { + text: "/cf 5 Bo", + entities: [{ type: "text_mention", offset: 6, length: 2, user: bo }], + ...reply({ from: rival }), + }, + CREATOR, + ), + ).toBe("To challenge someone, reply to their message or name them without replying."); + }); + + test.each([ + ["no username", {}], + ["an empty username", { username: "" }], + ["a bare @ username", { username: " @ " }], + ])("a bare @ mention never names a replied user with %s", (_case, username) => { + expect( + namedReplyRefusal( + { + text: "/cf 5 @", + entities: [{ type: "mention", offset: 6, length: 1 }], + ...reply({ from: { id: 5150, is_bot: false, first_name: "Ana", ...username } }), + }, + CREATOR, + ), + ).toBe("To challenge someone, reply to their message or name them without replying."); + }); + test("a reply without a name is not refused", () => { expect( namedReplyRefusal( From 6765cea516196fdc84f344b7a1188fddd07088f1 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Mon, 30 Nov 2026 06:19:40 -0300 Subject: [PATCH 362/410] refactor(mentions): type that a name without a picked user has a username findNamedUser and findNamedUsers only make a name without a picked user from a mention slice or a typed word, so its username is always a non-empty string. NamedIdentity now says so as a union. resolveNamedUser drops its non-null assertion, and namesUser and nameKey drop the ?? "" defaults that could never apply and left equivalent StringLiteral mutants. namesUser returns false for a replied user without a username before normalizing, which gives the same result as normalizing an empty string. The test helper for named users takes the same union. --- src/utils/game-challenge.ts | 18 ++++++++++-------- src/utils/user-mention.ts | 31 ++++++++++++++++++++++--------- tests/user-mention.test.ts | 10 ++++++++-- 3 files changed, 40 insertions(+), 19 deletions(-) diff --git a/src/utils/game-challenge.ts b/src/utils/game-challenge.ts index e8c52b03..b5f0d0da 100644 --- a/src/utils/game-challenge.ts +++ b/src/utils/game-challenge.ts @@ -9,7 +9,7 @@ import { normalizeUsername, resolveNamedUser, usernameVerificationFailedMessage, - type NamedUser, + type NamedIdentity, type NamedUsers, type UsernameDirectory, } from "./user-mention"; @@ -57,10 +57,12 @@ const CHALLENGE_BOT_MESSAGE = "You can't challenge a bot."; export const CHALLENGE_REPLY_OR_NAME_MESSAGE = "To challenge someone, reply to their message or name them without replying."; -const namesUser = (named: Pick, user: User): boolean => { +const namesUser = (named: NamedIdentity, user: User): boolean => { if (named.user) return named.user.id === user.id; - const username = normalizeUsername(user.username ?? ""); - return username !== "" && username === normalizeUsername(named.username ?? ""); + // Telegram leaves the username out for someone without one. + if (user.username == null) return false; + const username = normalizeUsername(user.username); + return username !== "" && username === normalizeUsername(named.username); }; /** @@ -95,7 +97,7 @@ export type NamedChallenge = { challenge: ChallengedPlayer } | { refusal: string */ export const resolveNamedChallenge = async ( ctx: Context, - named: Pick, + named: NamedIdentity, creatorTelegramId: bigint, directory: UsernameDirectory, several = false, @@ -151,9 +153,9 @@ const tooManyChallengedMessage = (maxChallenged: number): string => `You can challenge up to ${maxChallenged} ${maxChallenged === 1 ? "person" : "people"} at once.`; // Someone picked from Telegram's list and the same username typed are one person. -const nameKey = (named: Pick): string => { - if (named.user && !named.user.username) return `id ${named.user.id}`; - return `@${normalizeUsername(named.user?.username ?? named.username ?? "")}`; +const nameKey = (named: NamedIdentity): string => { + if (!named.user) return `@${normalizeUsername(named.username)}`; + return named.user.username ? `@${normalizeUsername(named.user.username)}` : `id ${named.user.id}`; }; /** diff --git a/src/utils/user-mention.ts b/src/utils/user-mention.ts index ecdd5f11..a273ccc1 100644 --- a/src/utils/user-mention.ts +++ b/src/utils/user-mention.ts @@ -2,12 +2,26 @@ import type { Context } from "grammy"; import type { Message, User } from "grammy/types"; import { escapeHtml } from "./format-amount"; +/** + * Who a name points at. Someone picked from the mention list comes with their + * user; anyone else is named by the @username marked or typed, so they always + * have one. + */ +export type NamedIdentity = + | { + /** Sent by Telegram when they were picked from the mention list. */ + user: User; + /** The picked user's @username, or the marked one. */ + username: string | null; + } + | { + user: null; + /** The @username marked or typed; it is looked up. */ + username: string; + }; + /** Someone a command names instead of replying to one of their messages. */ -export type NamedUser = { - /** Sent by Telegram when they were picked from the mention list. */ - user: User | null; - /** The picked user's @username, else the one marked or typed; looked up when no one was picked. */ - username: string | null; +export type NamedUser = NamedIdentity & { /** The mention's text, or the picked user's first name. */ label: string | null; /** The command's words without the ones that name them. */ @@ -81,7 +95,7 @@ const entityText = (entity: LooseEntity, text: string): string | null => : null; /** Someone a command names, without the command's words. */ -type NamedPerson = Pick; +type NamedPerson = NamedIdentity & { label: string | null }; /** Who a mention entity names, or null for any other entity. */ const entityPerson = (entity: LooseEntity, text: string): NamedPerson | null => { @@ -267,7 +281,7 @@ export const findNamedUsers = ( */ export const resolveNamedUser = async ( ctx: Context, - named: Pick, + named: NamedIdentity, senderId: bigint, directory: UsernameDirectory, ): Promise => { @@ -275,8 +289,7 @@ export const resolveNamedUser = async ( if (named.user) { resolvedId = String(named.user.id); } else { - // Whoever is named without a picked user always has a username. - const username = named.username!; + const username = named.username; let found: string | null | undefined; try { found = directory.findTelegramIdByUsername(username); diff --git a/tests/user-mention.test.ts b/tests/user-mention.test.ts index b6e84d60..ba1f1b10 100644 --- a/tests/user-mention.test.ts +++ b/tests/user-mention.test.ts @@ -5,6 +5,7 @@ import { findNamedUsers, replaceCommandWord, resolveNamedUser, + type NamedIdentity, type NamedUser, } from "../src/utils/user-mention"; @@ -563,7 +564,7 @@ describe("findNamedUsers", () => { ); }); }); -const named = (overrides: Partial = {}): NamedUser => ({ +const named = (overrides: NamedIdentity | { username?: string } = {}): NamedUser => ({ user: null, username: "@rival", label: "@rival", @@ -794,7 +795,12 @@ describe("resolveNamedUser", () => { }); const user = { id: 5150, is_bot: false, first_name: "Rival" }; expect( - await resolveNamedUser(context(error).ctx, named({ user }), SENDER, directory()), + await resolveNamedUser( + context(error).ctx, + named({ user, username: "@rival" }), + SENDER, + directory(), + ), ).toMatchObject({ kind: "user", telegramId: 5150n, From f2250eeaf58af2710d192f2830511da5e65dc09f Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Mon, 30 Nov 2026 06:23:01 -0300 Subject: [PATCH 363/410] refactor(tokens): drop the dead chat default branch in the game token check isTokenSupportedForGames read the chat's default token only to compare it with the mint, and both the matching branch and the fall-through returned SUPPORTED_TOKEN_MINTS.has(normalizedMint). The branch and the chat read are gone, and a Stryker disable that hid the equivalent mutants with them. The options parameter stays so the caller does not change. Equivalence: for every mint the result is SUPPORTED_TOKEN_MINTS.has(normalizedMint) after the same earlier checks, as before. The only difference is on a failing chat read (a database error, or a stored token_mint that is not a string so trim throws): the old check threw, the new one does not read the chat and answers from the static list. --- src/utils/token-manager.ts | 14 ++------------ 1 file changed, 2 insertions(+), 12 deletions(-) diff --git a/src/utils/token-manager.ts b/src/utils/token-manager.ts index 826ef088..d416fab8 100644 --- a/src/utils/token-manager.ts +++ b/src/utils/token-manager.ts @@ -123,7 +123,8 @@ export class TokenManager { private isTokenSupportedForGames( tokenMint: string, isSol?: boolean, - options?: { chatId?: number }, + // A chat's default token gets no special support, so the chat is not read. + _options?: { chatId?: number }, ): boolean { if (isSol) { return true; @@ -139,21 +140,10 @@ export class TokenManager { return false; } - const chatDefaultMint = options?.chatId - ? this.chatDb.getChatDefaultToken(options.chatId)?.token_mint - : null; - - const normalizedChatMint = chatDefaultMint?.trim(); - if (normalizedMint === WSOL_MINT || normalizedMint === normalizedDefaultMint) { return true; } - // Stryker disable next-line BlockStatement,ConditionalExpression,EqualityOperator: Both branches return the same static mint membership check. - if (normalizedMint === normalizedChatMint) { - return SUPPORTED_TOKEN_MINTS.has(normalizedMint); - } - return SUPPORTED_TOKEN_MINTS.has(normalizedMint); } From 188bf1d238372eccc65b75cf1b3faf2a86272954 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Mon, 30 Nov 2026 06:23:03 -0300 Subject: [PATCH 364/410] refactor(tokens): remove equivalent mutants in the native SOL and price parsing checks MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Only a candidate that upper-cases to "SOL" resolves to the native SOL builtin, so it is three characters from {s, S, ſ}{o, O}{l, L}. On those, candidate.toLowerCase() === "sol" is true exactly when the old /^[sS][oO][lL]$/ test is, and the two anchor-dropping regex mutants are gone. The price split now has its own line. The destructuring defaults next to it are equivalent (split always returns the coefficient, and Number reads "" and "0" as 0), so that line gets an exact StringLiteral exclusion, and the integer part takes no default because split always returns it. --- src/utils/token-manager.ts | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/src/utils/token-manager.ts b/src/utils/token-manager.ts index d416fab8..4fa31956 100644 --- a/src/utils/token-manager.ts +++ b/src/utils/token-manager.ts @@ -406,8 +406,10 @@ export class TokenManager { isSol = false; // An explicit token replaces the default's native SOL status. // Native SOL requires the ASCII ticker, not a wrapped mint or a Unicode case alias. + // Only a candidate that upper-cases to "SOL" is native here, and of those only the + // long s ("ſ") does not lower-case to ASCII. const requestedNativeSolByTicker = - resolvedToken.isNativeSol && /^[sS][oO][lL]$/.test(candidate); + resolvedToken.isNativeSol && candidate.toLowerCase() === "sol"; if (requestedNativeSolByTicker) { requestedNativeSol = true; @@ -566,8 +568,11 @@ export class TokenManager { } // Preserve the decimal quote and floor only when converting to whole token units. - const [coefficient = "", exponent = "0"] = price.toString().split("e"); - const [integer = "", fraction = ""] = coefficient.split("."); + const priceParts = price.toString().split("e"); + // Stryker disable next-line StringLiteral: split always returns the coefficient, and Number reads a missing exponent as 0 from "" or "0". + const [coefficient = "", exponent = "0"] = priceParts; + // split always returns the integer part, so it is never undefined here. + const [integer, fraction = ""] = coefficient.split("."); const priceDigits = BigInt(integer + fraction); const priceExponent = Number(exponent) - fraction.length; const priceNumerator = priceDigits * 10n ** BigInt(Math.max(0, priceExponent)); From 4401d6b4d17135c8a23488c6bf350cd71f03565b Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Mon, 30 Nov 2026 06:25:29 -0300 Subject: [PATCH 365/410] test(cache): check that fired and cleared timers are forgotten and that unref is optional A fired timer must leave the timer map, so replacing its entry does not cancel it again. clear() must empty the timer map, so a later set does not cancel a stale handle. A timer handle without unref must not break setWithTTL. These kill the expiring-cache mutants that drop timers.delete, drop timers.clear, and always call unref. --- tests/expiring-cache.test.ts | 44 ++++++++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) diff --git a/tests/expiring-cache.test.ts b/tests/expiring-cache.test.ts index ec767572..92d3b0ee 100644 --- a/tests/expiring-cache.test.ts +++ b/tests/expiring-cache.test.ts @@ -162,3 +162,47 @@ describe("ExpiringCache", () => { expect(cache.peek("key")).toBe(1); }); }); + +test("a fired timer is forgotten, and a cleared one is never cancelled again", () => { + vi.useFakeTimers({ now: 1_000 }); + const cancel = spyOn(globalThis, "clearTimeout"); + try { + const cache = createExpiringCache(20); + cache.setWithTTL("fired", 1); + vi.advanceTimersByTime(20); + cache.setWithTTL("fired", 2); + expect(cancel).not.toHaveBeenCalled(); + + cache.setWithTTL("cleared", 3); + cache.clear(); + expect(cancel).toHaveBeenCalledTimes(2); + cache.setWithTTL("cleared", 4); + expect(cache.delete("fired")).toBe(false); + expect(cancel).toHaveBeenCalledTimes(2); + cache.clear(); + } finally { + cancel.mockRestore(); + vi.useRealTimers(); + } +}); + +test("works with a clock whose timer handle has no unref method", () => { + const realSetTimeout = globalThis.setTimeout; + const handles: ReturnType[] = []; + const schedule = spyOn(globalThis, "setTimeout").mockImplementation(() => { + const timer = realSetTimeout(() => undefined, 60_000); + // Some runtimes give a timer handle without unref, like a browser's number id. + Object.defineProperty(timer, "unref", { value: undefined }); + handles.push(timer); + return timer; + }); + try { + const cache = createExpiringCache(60_000); + expect(() => cache.setWithTTL("key", 1)).not.toThrow(); + expect(cache.get("key")).toBe(1); + expect(handles).toHaveLength(1); + } finally { + schedule.mockRestore(); + for (const timer of handles) clearTimeout(timer); + } +}); From 289d2b00f5338b61e5924c7edf848f41b5543a77 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Mon, 30 Nov 2026 06:27:09 -0300 Subject: [PATCH 366/410] fix(errors): read each nested error field once when collecting logs collectErrorLogs checked data, error and cause with one read and pushed a second read. A getter that changes between reads (for example a cause that is given once) passed the check and then lost its logs. Each field is now read once, and the value it read is followed. An empty or unreadable value goes to the nested call, which returns no logs for it, so the old truthiness check is gone with its three equivalent mutants. The new test reads one-shot getters and fails on the old code. Stryker on the new lines: 11 mutants, all killed. --- src/utils/errors/parser.ts | 30 ++++++++++++++---------------- tests/errors.parser.test.ts | 20 ++++++++++++++++++++ 2 files changed, 34 insertions(+), 16 deletions(-) diff --git a/src/utils/errors/parser.ts b/src/utils/errors/parser.ts index 78fa72a7..8f32c7e1 100644 --- a/src/utils/errors/parser.ts +++ b/src/utils/errors/parser.ts @@ -86,22 +86,20 @@ export const collectErrorLogs = async ( } } - const nestedCandidates: unknown[] = []; - try { - if (candidate["data"]) nestedCandidates.push(candidate["data"]); - } catch (nestedError) { - console.debug("Failed to read data from error", nestedError); - } - try { - if (candidate["error"]) nestedCandidates.push(candidate["error"]); - } catch (nestedError) { - console.debug("Failed to read nested error", nestedError); - } - try { - if (candidate["cause"]) nestedCandidates.push(candidate["cause"]); - } catch (nestedError) { - console.debug("Failed to read error cause", nestedError); - } + // Read each field once. An empty or unreadable value gives no logs in the nested call below. + const readNested = (key: string, failure: string): unknown => { + try { + return candidate[key]; + } catch (nestedError) { + console.debug(failure, nestedError); + return undefined; + } + }; + const nestedCandidates = [ + readNested("data", "Failed to read data from error"), + readNested("error", "Failed to read nested error"), + readNested("cause", "Failed to read error cause"), + ]; for (const nested of nestedCandidates) { try { diff --git a/tests/errors.parser.test.ts b/tests/errors.parser.test.ts index d28cf6d5..07375c3c 100644 --- a/tests/errors.parser.test.ts +++ b/tests/errors.parser.test.ts @@ -170,6 +170,26 @@ describe("collectErrorLogs", () => { expect(readFields).toEqual(["data", "error", "cause"]); }); + test("reads each nested field once and follows the value it read", async () => { + const readFields: string[] = []; + const once = (key: string, value: { logs: string[] }) => () => { + readFields.push(key); + // A getter that gives its value only once, like a consumed cause. + return readFields.filter((field) => field === key).length === 1 ? value : undefined; + }; + const error = Object.defineProperties( + {}, + { + data: { get: once("data", { logs: ["from data"] }) }, + error: { get: once("error", { logs: ["from error"] }) }, + cause: { get: once("cause", { logs: ["from cause"] }) }, + }, + ); + + expect(await collectErrorLogs(error)).toEqual(["from data", "from error", "from cause"]); + expect(readFields).toEqual(["data", "error", "cause"]); + }); + test.each([ ["data", "Failed to read data from error"], ["error", "Failed to read nested error"], From 58f49204ccc8726351d21d8a4c1ff72376e6f241 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Mon, 30 Nov 2026 06:27:55 -0300 Subject: [PATCH 367/410] test(errors): check that an Error's name does not pick the friendly reply parseTransactionError matches on error.message for Error instances, not on String(error), which adds the name. An Error named SlippageGuardError with an unrelated message must get the default reply. This kills the formatter mutants that turn the message check off. --- tests/errors.test.ts | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/tests/errors.test.ts b/tests/errors.test.ts index 69379806..b0411195 100644 --- a/tests/errors.test.ts +++ b/tests/errors.test.ts @@ -143,6 +143,14 @@ test("parseTransactionError handles transaction timeout without signature", asyn expect(message).not.toContain("/checktx"); }); +test("parseTransactionError reads an Error's message, not its name", async () => { + const error = new Error("quote request rejected"); + error.name = "SlippageGuardError"; + const message = await parseTransactionError(error); + expect(message).toContain("Something went wrong"); + expect(message).not.toContain("slippage"); +}); + test("parseTransactionError handles Jupiter no route errors", async () => { const error = new Error("Jupiter error: no route found"); const message = await parseTransactionError(error); From 39ff932080d8967275cf79d3b3cc536b01b72bc9 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Mon, 30 Nov 2026 06:28:21 -0300 Subject: [PATCH 368/410] test(context): check categorizeError with an empty message and a code of another type An Error with an empty message is described by String(error), which gives "Error". A code that is a boolean or an object is dropped. These cases kill the categorizeError mutants that keep an empty message and that keep any code. --- tests/context-helpers.edge.test.ts | 3 +++ 1 file changed, 3 insertions(+) diff --git a/tests/context-helpers.edge.test.ts b/tests/context-helpers.edge.test.ts index a30c9d00..54e8b7bd 100644 --- a/tests/context-helpers.edge.test.ts +++ b/tests/context-helpers.edge.test.ts @@ -239,6 +239,9 @@ test.each([ ["null prototype", Object.create(null), "Unknown error", undefined], ["non-callable toString", { toString: 42 }, "Unknown error", undefined], ["malformed Error message", Object.assign(new Error(), { message: 42 }), "Error: 42", undefined], + ["empty Error message", new Error(""), "Error", undefined], + ["boolean code", { message: "oops", code: true }, "oops", undefined], + ["structured code", { message: "oops", code: { status: 503 } }, "oops", undefined], ] as const)( "still answers the callback when the error has a %s", async (_label, error, message, code) => { From 40fab9f810f16e37ddc865b901716fc83d5b2862 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Mon, 30 Nov 2026 06:29:44 -0300 Subject: [PATCH 369/410] refactor(prices): key the price cache by "" when a request has no mint rememberPriceLookup stored only when the normalized mint was not null, and getCachedPriceLookup returned null early for a null mint. The early return was equivalent to a cache miss, so its mutants survived. A cacheKey helper now maps a missing mint to "", the store skips that empty key, and the read always asks the cache. Proof: normalize returns null or a non-empty string, so the key is "" exactly when it was null before, and the store runs exactly when it ran before. Nothing is stored under "", and a cache get has no side effect on a missing key, so the read of "" returns null as the early return did. Stryker on lines 21-53 with token-price-cache: 34 mutants, all killed. --- src/utils/price-service.ts | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/src/utils/price-service.ts b/src/utils/price-service.ts index 82482526..8eb02d33 100644 --- a/src/utils/price-service.ts +++ b/src/utils/price-service.ts @@ -18,6 +18,9 @@ const normalize = (value?: string | null): string | null => { return trimmed; }; +// A request without a mint maps to "", and nothing is ever stored under "". +const cacheKey = (mint?: string | null): string => normalize(mint) ?? ""; + const isHintFresh = (hint: CachedPriceLookup): boolean => { const now = Date.now(); return now - hint.resolvedAt <= TOKEN_PRICE_CACHE_TTL_MS; @@ -39,15 +42,14 @@ export function rememberPriceLookup( resolvedAt: (lookup as CachedPriceLookup).resolvedAt ?? Date.now(), }; - const key = normalize(request.tokenMint); - if (key !== null) priceCache.setWithTTL(key, entry); + const key = cacheKey(request.tokenMint); + if (key) priceCache.setWithTTL(key, entry); return entry; } export function getCachedPriceLookup(request: PriceLookupRequest): CachedPriceLookup | null { - const key = normalize(request.tokenMint); - return key === null ? null : (priceCache.get(key) ?? null); + return priceCache.get(cacheKey(request.tokenMint)) ?? null; } const maybeUseHint = ( From f155dce576e6ef226066ac1f803a9621431f939c Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Mon, 30 Nov 2026 06:31:00 -0300 Subject: [PATCH 370/410] refactor(telegram): drop two equivalent checks in getRetryAfterSeconds The top-level retry_after fallback no longer checks typeof number: the only reader is isFiniteNumber, which is false for every non-number, so passing the raw value gives the same result. The field is now read once instead of once for the check and once for the value. The description fallback no longer returns early on no match: Number(undefined) is NaN, and retrySecondsToMilliseconds(NaN) is null, which is what the early return gave. For a match, the capture is ASCII digits only, so Number and parseInt agree on every value that retrySecondsToMilliseconds accepts (under 14 digits, read exactly by both); longer values are rejected by both. Stryker on lines 88-109 with telegram-errors: 29 mutants, all killed. --- src/utils/telegram-errors.ts | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/src/utils/telegram-errors.ts b/src/utils/telegram-errors.ts index 5c90c607..644ec39e 100644 --- a/src/utils/telegram-errors.ts +++ b/src/utils/telegram-errors.ts @@ -95,7 +95,7 @@ export const getRetryAfterSeconds = (error: unknown): number | null => { const retryAfter = (parameters && typeof parameters.retry_after === "number" ? parameters.retry_after - : undefined) ?? (typeof response.retry_after === "number" ? response.retry_after : undefined); + : undefined) ?? response.retry_after; if (isFiniteNumber(retryAfter)) { const seconds = Math.max(0, retryAfter); @@ -103,9 +103,8 @@ export const getRetryAfterSeconds = (error: unknown): number | null => { } const description = getErrorString(error); - const capturedSeconds = description.match(/retry after (\d+)/i)?.[1]; - if (capturedSeconds === undefined) return null; - const seconds = Number.parseInt(capturedSeconds, 10); + // No match gives Number(undefined), which is NaN and has no delay below. + const seconds = Number(description.match(/retry after (\d+)/i)?.[1]); return retrySecondsToMilliseconds(seconds) === null ? null : seconds; }; From fba0b08c1ec5353105c270e19dcdcc13b9dc3dc0 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Mon, 30 Nov 2026 06:31:37 -0300 Subject: [PATCH 371/410] test(retry): check which retry delays become safe deadlines retrySecondsToMilliseconds had no direct test, so its negative-delay check survived: callers clamp the value first. The new test covers zero, a fraction, the largest safe delay, negative and tiny negative delays, NaN, an unsafe delay and Infinity, plus the 32-bit timer limit. --- tests/retry-delay.test.ts | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 tests/retry-delay.test.ts diff --git a/tests/retry-delay.test.ts b/tests/retry-delay.test.ts new file mode 100644 index 00000000..2a41ab11 --- /dev/null +++ b/tests/retry-delay.test.ts @@ -0,0 +1,19 @@ +import { expect, test } from "bun:test"; +import { MAX_TIMER_DELAY_MS, retrySecondsToMilliseconds } from "../src/utils/retry-delay"; + +test.each([ + ["zero", 0, 0], + ["a fraction", 1.25, 1_250], + ["the largest safe delay", 9_007_199_254_740, 9_007_199_254_740_000], + ["a negative delay", -1, null], + ["a tiny negative delay", -0.0005, null], + ["NaN", Number.NaN, null], + ["an unsafe delay", 9_007_199_254_741, null], + ["Infinity", Number.POSITIVE_INFINITY, null], +])("turns %s into milliseconds only when it is a safe deadline", (_label, seconds, expected) => { + expect(retrySecondsToMilliseconds(seconds)).toBe(expected); +}); + +test("the timer limit is the largest delay a 32-bit signed timer accepts", () => { + expect(MAX_TIMER_DELAY_MS).toBe(2_147_483_647); +}); From 704fd03dafae42f1e70f158cd262d73a813f7e27 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Mon, 30 Nov 2026 06:32:06 -0300 Subject: [PATCH 372/410] test(tokens): rethrow a non-text RPC failure even when it prints as a miss isMissingMintAccount reads only text. A thrown object whose toString says "Account not found" is not a mint miss and must be rethrown. This kills the mutant that runs the miss pattern on any thrown value. --- tests/token-programs.test.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/tests/token-programs.test.ts b/tests/token-programs.test.ts index f57c7fa3..4fc881d9 100644 --- a/tests/token-programs.test.ts +++ b/tests/token-programs.test.ts @@ -138,6 +138,7 @@ describe("detectTokenProgram", () => { ["missing RPC method", new SolanaJSONRPCError({ code: -32601, message: "Method not found" })], ["missing RPC endpoint", "Endpoint NOT FOUND"], ["untyped provider failure", { status: 404 }], + ["non-text failure that prints as a miss", { toString: () => "Account not found" }], ] as const)("reports %s rather than calling the mint absent", async (_name, failure) => { const mint = TOKEN_PROGRAM_ID; const connection = new Connection("http://localhost:8899"); From effbcfbc50383502f87eaa639fa300bd3399721e Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Mon, 30 Nov 2026 06:32:33 -0300 Subject: [PATCH 373/410] refactor(tokens): narrow mint decimals with Number.isInteger alone isMintDecimals checked typeof value === "number" before Number.isInteger(value). Number.isInteger does not convert its argument and is true only for a number, so the typeof check never changed the result and its mutant survived. A small type guard around Number.isInteger now gives TypeScript the number type. Proof: for every value, Number.isInteger(v) is true exactly when typeof v is "number" and v is an integer, so both versions agree. New direct test covers the bounds, -0, fractions, NaN, Infinity, a numeric string, a bigint, null, undefined, a boolean and an object with valueOf. Stryker on the file: 13 mutants, all killed. --- src/utils/token-decimals.ts | 5 ++++- tests/token-decimals.test.ts | 22 ++++++++++++++++++++++ 2 files changed, 26 insertions(+), 1 deletion(-) create mode 100644 tests/token-decimals.test.ts diff --git a/src/utils/token-decimals.ts b/src/utils/token-decimals.ts index 8430a03c..a747d9bc 100644 --- a/src/utils/token-decimals.ts +++ b/src/utils/token-decimals.ts @@ -1,5 +1,8 @@ /** SPL mints store decimal precision in a single unsigned byte. */ export const MAX_MINT_DECIMALS = 255; +// Number.isInteger never converts its argument, so it is true only for a number. +const isInteger = (value: unknown): value is number => Number.isInteger(value); + export const isMintDecimals = (value: unknown): value is number => - typeof value === "number" && Number.isInteger(value) && value >= 0 && value <= MAX_MINT_DECIMALS; + isInteger(value) && value >= 0 && value <= MAX_MINT_DECIMALS; diff --git a/tests/token-decimals.test.ts b/tests/token-decimals.test.ts new file mode 100644 index 00000000..7e58244d --- /dev/null +++ b/tests/token-decimals.test.ts @@ -0,0 +1,22 @@ +import { expect, test } from "bun:test"; +import { isMintDecimals, MAX_MINT_DECIMALS } from "../src/utils/token-decimals"; + +test.each([0, 6, 9, MAX_MINT_DECIMALS, -0])("accepts %p as mint decimals", (value) => { + expect(isMintDecimals(value)).toBe(true); +}); + +test.each([ + -1, + MAX_MINT_DECIMALS + 1, + 1.5, + Number.NaN, + Number.POSITIVE_INFINITY, + "6", + 6n, + null, + undefined, + true, + { valueOf: () => 6 }, +])("refuses %p as mint decimals", (value) => { + expect(isMintDecimals(value)).toBe(false); +}); From e5fd8629f067aa4d71ade92cd13e8d45c16da4da Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Mon, 30 Nov 2026 06:32:56 -0300 Subject: [PATCH 374/410] test(history): store a nonzero block height given at insert The block height test inserted only 0, which a mutant that turns every height into a falsy value also stores. A record inserted with height 321 must keep it. --- tests/transaction-history.paths.test.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/tests/transaction-history.paths.test.ts b/tests/transaction-history.paths.test.ts index 54dc4a7a..a21ab3b1 100644 --- a/tests/transaction-history.paths.test.ts +++ b/tests/transaction-history.paths.test.ts @@ -256,6 +256,7 @@ describe("TransactionHistory error handling", () => { test("keeps block height zero distinct from an unknown height on insert and update", () => { const db = TransactionHistory.getInstance(); + db.addTransaction(record("high-at-insert", { block_height: 321 })); db.addTransaction(record("known-at-insert", { block_height: 0 })); db.addTransaction(record("known-at-update", { status: "PENDING" })); db.addTransaction(record("still-unknown")); @@ -273,6 +274,7 @@ describe("TransactionHistory error handling", () => { .all(), ); expect(rows).toEqual([ + { signature: "high-at-insert", status: "SUCCESS", block_height: 321 }, { signature: "known-at-insert", status: "SUCCESS", block_height: 0 }, { signature: "known-at-update", status: "SUCCESS", block_height: 0 }, { signature: "still-unknown", status: "SUCCESS", block_height: null }, From a0d1ef974d02d599f732e395e3d4f198d9aa8e5f Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Mon, 30 Nov 2026 06:33:30 -0300 Subject: [PATCH 375/410] test(concurrency): keep one result slot per item given mapWithConcurrency sizes its results by the input length at call time. If a mapper removes items, the missing items stay as holes and the length does not shrink. This kills the mutant that starts from an empty array. --- tests/concurrency.test.ts | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/tests/concurrency.test.ts b/tests/concurrency.test.ts index 1422fa3e..6e70a1a3 100644 --- a/tests/concurrency.test.ts +++ b/tests/concurrency.test.ts @@ -34,3 +34,15 @@ test("starts only two jobs and keeps input order when another job finishes first slow.resolve("A"); await expect(pending).resolves.toEqual(["A", "B", "C"]); }); + +test("keeps one result slot per item given, even when the mapper removes items", async () => { + const items = ["a", "b", "c"]; + const results = await mapWithConcurrency(items, 1, async (item) => { + if (item === "a") items.pop(); + return item.toUpperCase(); + }); + + expect(results).toHaveLength(3); + expect(results.slice(0, 2)).toEqual(["A", "B"]); + expect(2 in results).toBe(false); +}); From 1b80244af46623c1d522c9e3a58fd23eb3e528d5 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Mon, 30 Nov 2026 06:34:00 -0300 Subject: [PATCH 376/410] test(menu): log why an explicit text edit failed When the explicit target's text edit fails, respondWithMenu logs the reason and goes on to the callback message. The new test checks that log line and the edit of the callback message. This kills the mutants that drop the log call or empty its handler. --- tests/menu-response.test.ts | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/tests/menu-response.test.ts b/tests/menu-response.test.ts index 800ed7ad..dc2f3b36 100644 --- a/tests/menu-response.test.ts +++ b/tests/menu-response.test.ts @@ -446,6 +446,35 @@ describe("respondWithMenu", () => { } }); + test("explicit text edit errors log why before the next target is tried", async () => { + const textError = Object.assign(new Error("forbidden"), { + description: "Bad Request: message can't be edited", + }); + const ctx = makeCtx({ + api: { + editMessageText: async () => { + throw textError; + }, + }, + }); + const warnSpy = spyOn(console, "warn").mockImplementation(() => {}); + try { + const result = await respondWithMenu(ctx, basePayload, { + targetChatId: 777, + targetMessageId: 888, + logLabel: "menu", + }); + + expect(result).toEqual({ messageId: 99, chatId: 42, respondedWithReply: false }); + expect(warnSpy).toHaveBeenCalledWith( + "menu: editMessageText failed for explicit target, replying instead:", + textError, + ); + } finally { + warnSpy.mockRestore(); + } + }); + test("explicit caption edits fall through to text edits when the message has no caption", async () => { const captionError: any = new Error("no caption"); captionError.description = "Bad Request: there is no caption in the message to edit"; From 9ef71d32cd89266cab932d3e487567bef8013bcf Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Mon, 30 Nov 2026 06:36:01 -0300 Subject: [PATCH 377/410] refactor(wallet): drop dead row checks in the quick amount and keyboard trim helpers buildQuickAmountRows pushed a row only when it was not empty. The offset comes from buttons.keys(), so it is below buttons.length, and normalizedColumns is at least 1, so slice(offset, offset + normalizedColumns) always has at least one entry (slice keeps holes, so this holds for sparse arrays too). The check is gone with its two equivalent mutants. trimTrailingEmptyRows used findLastIndex with (row?.length ?? 0) to treat a hole as an empty row. It now walks the rows with forEach, which skips holes, and keeps the last index whose row has buttons. For every InlineKeyboardButton[][] value, sparse or not, both find the same last row with buttons (or -1), so splice keeps the same rows. The optional chain and its equivalent mutant are gone. Stryker on both ranges with the three wallet-ui test files: 15 mutants, all killed. --- src/utils/wallet-ui.ts | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/src/utils/wallet-ui.ts b/src/utils/wallet-ui.ts index bcaca05b..14f64c32 100644 --- a/src/utils/wallet-ui.ts +++ b/src/utils/wallet-ui.ts @@ -634,8 +634,8 @@ export const buildQuickAmountRows = ( for (const offset of buttons.keys()) { if (offset % normalizedColumns !== 0) continue; - const row = buttons.slice(offset, offset + normalizedColumns); - if (row.length > 0) rows.push(row); + // offset is below buttons.length and normalizedColumns is at least 1, so the row is never empty. + rows.push(buttons.slice(offset, offset + normalizedColumns)); } return rows; @@ -832,7 +832,11 @@ const buildWrapKeyboard = ( const trimTrailingEmptyRows = (keyboard: InlineKeyboard): InlineKeyboard => { const rows = keyboard.inline_keyboard; - const lastButtonRow = rows.findLastIndex((row) => (row?.length ?? 0) !== 0); + let lastButtonRow = -1; + // forEach skips holes, so every row it gives is an array. + rows.forEach((row, index) => { + if (row.length !== 0) lastButtonRow = index; + }); rows.splice(lastButtonRow + 1); return keyboard; }; From dbbc222769e0b2b2e920e255b314beec74f3f3ea Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Mon, 30 Nov 2026 06:36:45 -0300 Subject: [PATCH 378/410] test(user-state): check prompt order by write time and a late clear of a gone prompt A Map keeps the first insert position when a key is set again, so findInputSession must compare timestamps, not take the last match. The new test sets a prompt again after another one and expects it to win. A late reply that clears a prompt with its locker id must not throw when the prompt is already gone. These kill the user-state mutants that drop the timestamp check and the optional chain. --- tests/user-state.find-input-session.test.ts | 18 ++++++++++++++++++ tests/user-state.util.test.ts | 7 +++++++ 2 files changed, 25 insertions(+) diff --git a/tests/user-state.find-input-session.test.ts b/tests/user-state.find-input-session.test.ts index b4a0c01f..95fcc0a3 100644 --- a/tests/user-state.find-input-session.test.ts +++ b/tests/user-state.find-input-session.test.ts @@ -73,3 +73,21 @@ test("selects the last matching prompt on a clock tie without inspecting other n clock.mockRestore(); } }); + +test("a prompt that is set again is newer than one set between the two writes", () => { + const clock = spyOn(Date, "now").mockReturnValue(20_000); + try { + setInputSession("first", { type: "send", messageId: 1 }); + clock.mockReturnValue(20_010); + setInputSession("second", { type: "send", messageId: 2 }); + clock.mockReturnValue(20_020); + setInputSession("first", { type: "send", messageId: 3 }); + + expect(findInputSession((_key, session) => session.type === "send")).toEqual({ + key: "first", + session: { type: "send", messageId: 3 }, + }); + } finally { + clock.mockRestore(); + } +}); diff --git a/tests/user-state.util.test.ts b/tests/user-state.util.test.ts index d5ccb98b..53f21531 100644 --- a/tests/user-state.util.test.ts +++ b/tests/user-state.util.test.ts @@ -198,3 +198,10 @@ test("an old reply cannot release the lock on a replacement prompt", () => { clearInputSession(key); } }); + +test("a late reply may try to clear a prompt that is already gone", () => { + const key = "finished-prompt"; + expect(getInputSession(key)).toBeUndefined(); + expect(() => clearInputSession(key, "late-reply")).not.toThrow(); + expect(getInputSession(key)).toBeUndefined(); +}); From acbc1e194f87a2194a3fc4401910e74ea6736071 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Mon, 30 Nov 2026 06:37:43 -0300 Subject: [PATCH 379/410] refactor(tokens): stop stripping null padding the metadata decoder already removed deserializeMetadata reads name and symbol with the umi string() serializer, whose default utf8 decoder returns removeNullCharacters(value) (umi-serializers-encodings 1.6.0, both the ESM and CJS builds). So the strings never hold U+0000, and replace(/\0/g, "") never changed them; its two replacement-string mutants survived for that reason. Only trim() is left. The existing test "prefers on-chain Metaplex metadata and strips null padding" serializes " \0USDC\0 " and still expects "USDC", so it fails if a future decoder stops removing the padding. --- src/utils/token-metadata.ts | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/utils/token-metadata.ts b/src/utils/token-metadata.ts index 5493f774..0159da07 100644 --- a/src/utils/token-metadata.ts +++ b/src/utils/token-metadata.ts @@ -51,8 +51,9 @@ async function tryMetaplexMetadata( return null; } const metadata = deserializeMetadata(metadataAccount as any); - const symbol = metadata.symbol.replace(/\0/g, "").trim(); - const name = metadata.name.replace(/\0/g, "").trim(); + // The umi string decoder already removes the null padding, so only spaces remain to trim. + const symbol = metadata.symbol.trim(); + const name = metadata.name.trim(); if (symbol && symbol !== "UNKNOWN") { return { From 84bae4a11aa4619439f7458c61990ee3186dc566 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Mon, 30 Nov 2026 06:39:16 -0300 Subject: [PATCH 380/410] test: fix the types of the new timer and RPC failure fakes tsc refused the setTimeout mock in expiring-cache (a plain function lacks __promisify__) and inferred a circular type for the toString fake in token-programs. The timer fake is now a Proxy around the real setTimeout, as in other tests, and toString has an explicit string return type. Both tests still kill their mutants (checked by hand), and tsc is clean. --- tests/expiring-cache.test.ts | 18 +++++++++++------- tests/token-programs.test.ts | 2 +- 2 files changed, 12 insertions(+), 8 deletions(-) diff --git a/tests/expiring-cache.test.ts b/tests/expiring-cache.test.ts index 92d3b0ee..8eb4ca0e 100644 --- a/tests/expiring-cache.test.ts +++ b/tests/expiring-cache.test.ts @@ -189,13 +189,17 @@ test("a fired timer is forgotten, and a cleared one is never cancelled again", ( test("works with a clock whose timer handle has no unref method", () => { const realSetTimeout = globalThis.setTimeout; const handles: ReturnType[] = []; - const schedule = spyOn(globalThis, "setTimeout").mockImplementation(() => { - const timer = realSetTimeout(() => undefined, 60_000); - // Some runtimes give a timer handle without unref, like a browser's number id. - Object.defineProperty(timer, "unref", { value: undefined }); - handles.push(timer); - return timer; - }); + const schedule = spyOn(globalThis, "setTimeout").mockImplementation( + new Proxy(realSetTimeout, { + apply: (target, receiver, args) => { + const timer: ReturnType = Reflect.apply(target, receiver, args); + // Some runtimes give a timer handle without unref, like a browser's number id. + Object.defineProperty(timer, "unref", { value: undefined }); + handles.push(timer); + return timer; + }, + }), + ); try { const cache = createExpiringCache(60_000); expect(() => cache.setWithTTL("key", 1)).not.toThrow(); diff --git a/tests/token-programs.test.ts b/tests/token-programs.test.ts index 4fc881d9..3aeb5eae 100644 --- a/tests/token-programs.test.ts +++ b/tests/token-programs.test.ts @@ -138,7 +138,7 @@ describe("detectTokenProgram", () => { ["missing RPC method", new SolanaJSONRPCError({ code: -32601, message: "Method not found" })], ["missing RPC endpoint", "Endpoint NOT FOUND"], ["untyped provider failure", { status: 404 }], - ["non-text failure that prints as a miss", { toString: () => "Account not found" }], + ["non-text failure that prints as a miss", { toString: (): string => "Account not found" }], ] as const)("reports %s rather than calling the mint absent", async (_name, failure) => { const mint = TOKEN_PROGRAM_ID; const connection = new Connection("http://localhost:8899"); From de36f7a0789cd05e2b5d36a54205a04f063e1b5a Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Mon, 30 Nov 2026 06:43:51 -0300 Subject: [PATCH 381/410] refactor: keep failed key, mint and price reads in a variable instead of a catch return Five catch blocks returned null or false after a try that returned the result. Their Stryker disable comments trailed the return, so Stryker never read them, and the empty-catch mutants of jupiter.ts and prices.ts survived in CI. Each function now starts a variable at the old catch value, assigns it in the try, and returns it after the catch. Every input gives the same result: a throw leaves the starting value, and a success assigns the same value as before. The disables are gone, and the catches have nothing to empty. --- src/utils/game.ts | 30 ++++++++++++++++-------------- src/utils/jupiter.ts | 7 ++++--- src/utils/prices.ts | 7 ++++--- 3 files changed, 24 insertions(+), 20 deletions(-) diff --git a/src/utils/game.ts b/src/utils/game.ts index 32734bd5..8de05509 100644 --- a/src/utils/game.ts +++ b/src/utils/game.ts @@ -8497,14 +8497,16 @@ export class GameManager { const creatorPubkey = playerKeyInfo.creator?.pubkey ?? (() => { + let creatorKey: PublicKey | null = null; try { - return gameAccount.creator instanceof PublicKey - ? gameAccount.creator - : new PublicKey(gameAccount.creator); - // Stryker disable next-line BlockStatement: undefined and null are both no creator key here. - } catch (_) { - return null; + creatorKey = + gameAccount.creator instanceof PublicKey + ? gameAccount.creator + : new PublicKey(gameAccount.creator); + } catch { + // Not a valid key: no creator key. } + return creatorKey; })(); if (!creatorTelegramId && creatorPubkey) { @@ -8546,7 +8548,7 @@ export class GameManager { const dbParticipants = this.getGamePlayers(gameAddress); const participantTelegramIds = new Set(dbParticipants); const onChainTickets = Number(gameAccount.ticketsCount ?? 0); - let creatorPubkey: PublicKey | null; + let creatorPubkey: PublicKey | null = null; let creatorTelegramId: string | null = null; try { @@ -8554,9 +8556,8 @@ export class GameManager { gameAccount.creator instanceof PublicKey ? gameAccount.creator : new PublicKey(gameAccount.creator); - // Stryker disable next-line BlockStatement: an unset key and null are both read as no creator key. - } catch (_) { - creatorPubkey = null; + } catch { + // Not a valid key: no creator key. } if (creatorPubkey) { @@ -8787,12 +8788,13 @@ export class GameManager { return null; } + let keyPair: Keypair | null = null; try { - return await this.wallet.getKeyPair(BigInt(telegramId)); - // Stryker disable next-line BlockStatement: an empty catch returns undefined, which every caller treats as no key. - } catch (_) { - return null; + keyPair = await this.wallet.getKeyPair(BigInt(telegramId)); + } catch { + // No readable key for this player. } + return keyPair; }; const creatorAuthority = await tryGetKeyPair(creatorTelegramId); diff --git a/src/utils/jupiter.ts b/src/utils/jupiter.ts index e96362f3..b7389b93 100644 --- a/src/utils/jupiter.ts +++ b/src/utils/jupiter.ts @@ -881,12 +881,13 @@ export interface JupiterTokenMetadata { } const isCanonicalMintQuery = (query: string): boolean => { + let canonical = false; try { - return new PublicKey(query).toBase58() === query; - // Stryker disable next-line BlockStatement: the caller treats undefined like false. + canonical = new PublicKey(query).toBase58() === query; } catch { - return false; + // Not a public key: not a canonical mint. } + return canonical; }; export async function fetchJupiterTokenMetadata( diff --git a/src/utils/prices.ts b/src/utils/prices.ts index 05099d00..312176cb 100644 --- a/src/utils/prices.ts +++ b/src/utils/prices.ts @@ -88,6 +88,7 @@ async function fetchJupiterEntries( ): Promise | null> { const controller = new AbortController(); let timer: ReturnType | undefined; + let entries: ReturnType | null = null; try { const url = new URL(JUPITER_PRICE_URL); url.searchParams.set("ids", ids); @@ -108,13 +109,13 @@ async function fetchJupiterEntries( return response.ok ? getPriceEntries(await response.json()) : null; }; // Use one deadline for both headers and body, even when a transport ignores abort. - return await Promise.race([deadline, request()]); - // Stryker disable next-line BlockStatement: both callers treat undefined like null. + entries = await Promise.race([deadline, request()]); } catch { - return null; + // A failed request gives no entries. } finally { clearTimeout(timer); } + return entries; } async function fetchBatchFromJupiter( From 0430a5653067b2aa9059bf494d40c6b47cd7c14b Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Mon, 30 Nov 2026 06:13:54 -0300 Subject: [PATCH 382/410] fix(swap): read the source balance by the resolved mint only The percentage swap looked up the wallet balance by mint or by ticker. Two tokens can share a ticker, so a "50%" swap could take the balance and decimals of another mint with the same ticker. Now the lookup uses the resolved input mint only. The new test has two BONK tokens with different mints and decimals. It fails with the old lookup. It also kills the ObjectLiteral mutant on the tokenBalance snapshot. --- src/bot.ts | 5 ++--- tests/bot-swap.flows.test.ts | 25 +++++++++++++++++++++++++ 2 files changed, 27 insertions(+), 3 deletions(-) diff --git a/src/bot.ts b/src/bot.ts index 223a22d3..7aaa5eac 100644 --- a/src/bot.ts +++ b/src/bot.ts @@ -5922,9 +5922,8 @@ const showSwapQuoteAndConfirmation = async ( const balanceEntry = fromToken === "SOL" ? undefined - : tokenBalances.find( - (token) => token.mint === overrides.fromMint || token.ticker === fromToken, - ); + : // Match the resolved mint only. Two tokens can share a ticker. + tokenBalances.find((token) => token.mint === inputMint); const decimals = overrides.fromDecimals ?? (fromToken === "SOL" diff --git a/tests/bot-swap.flows.test.ts b/tests/bot-swap.flows.test.ts index 97ec4753..36563072 100644 --- a/tests/bot-swap.flows.test.ts +++ b/tests/bot-swap.flows.test.ts @@ -184,6 +184,31 @@ describe("quoting and confirming a swap", () => { expect(answers().at(-1)).toBe("✅ Swap submitted"); }); + test("a percentage uses the balance of the resolved mint, not another token with the same ticker", async () => { + stub(wallet, "getAllWalletTokenBalances", async () => [ + { + mint: "FakeBonk1111111111111111111111111111111111", + ticker: "BONK", + balance: 9_000_000_000, + decimals: 9, + rawBalance: "9000000000", + }, + { mint: BONK, ticker: "BONK", balance: 1_000_000, decimals: 5, rawBalance: "1000000" }, + ]); + prepareSwap.mockImplementation(async () => + quote({ inputMint: BONK, outputMint: WSOL_MINT, inputAmountRaw: "500000", inputDecimals: 5 }), + ); + + await at("swap_amount_BONK_SOL_50%"); + + expect(prepareSwap).toHaveBeenCalledTimes(1); + expect(prepareSwap.mock.calls[0]?.[0]).toMatchObject({ + inputMint: BONK, + amount: "500000", + inputDecimals: 5, + }); + }); + test("a failed execution explains the error", async () => { execute.mockImplementation(async () => { throw new Error("Jupiter error: no route found"); From 771b13b40255e462200e6e43d15a4768c518e4a9 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Mon, 30 Nov 2026 06:14:01 -0300 Subject: [PATCH 383/410] refactor(bot): read metadata decimals without optional chaining wallet.getTokenMetadata is typed to resolve to an object, and every return path returns an object (resolver result, resolveTokenMetadata result or cache entry) or throws. So metadata?.decimals and metadata.decimals always read the same value. This removes an equivalent OptionalChaining mutant. --- src/bot.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/bot.ts b/src/bot.ts index 7aaa5eac..5ebd4731 100644 --- a/src/bot.ts +++ b/src/bot.ts @@ -428,8 +428,9 @@ const getCachedTokenMetadata = async (mint: string) => { const fetchPromise = (async () => { try { + // getTokenMetadata always resolves to an object or throws. const metadata = await wallet.getTokenMetadata(normalizedMint); - if (!isMintDecimals(metadata?.decimals)) { + if (!isMintDecimals(metadata.decimals)) { throw new Error("Token metadata missing decimals"); } const entry: CachedTokenMetadata = { From b89813c77acbb953f63a1e3232d29700a60ddbda Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Mon, 30 Nov 2026 06:14:01 -0300 Subject: [PATCH 384/410] test(bot): exclude the no-op lock release in the input finally blocks The text and media input handlers run clearInputSession(sessionKey, lockerId) on every try and catch path. That call deletes the session while this locker owns it, and setInputSession strips the lock fields from a new session. So when finally runs, no session is locked by lockerId and clearInputSessionProcessing does nothing. The CallExpression mutant that removes it cannot be told apart. --- src/bot.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/bot.ts b/src/bot.ts index 5ebd4731..1982e103 100644 --- a/src/bot.ts +++ b/src/bot.ts @@ -6112,6 +6112,7 @@ bot.on("message:text", async (ctx, next) => { }); } } finally { + // Stryker disable next-line CallExpression: every try and catch path above already ran clearInputSession(sessionKey, lockerId), which deletes the session while this locker owns it, and setInputSession strips the lock fields, so no session locked by lockerId is left here. clearInputSessionProcessing(sessionKey, lockerId); } }); @@ -6201,6 +6202,7 @@ const handleMediaForChatDefaults = async ( parse_mode: "HTML", }); } finally { + // Stryker disable next-line CallExpression: every try and catch path above already ran clearInputSession(sessionKey, lockerId), which deletes the session while this locker owns it, and setInputSession strips the lock fields, so no session locked by lockerId is left here. clearInputSessionProcessing(sessionKey, lockerId); } }; From 732647d17838f86fbed0f81d25ea9838d376f086 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Mon, 30 Nov 2026 06:15:01 -0300 Subject: [PATCH 385/410] test(bot): flush pending events for a game without a legacy record The target lookup reads the legacy game record with optional chaining. The new test returns no record for that lookup and expects no warning, the flush log line and one notification to the live message. It kills the OptionalChaining mutant on gameRecord?.chat_id and the mutant that removes the flush log. --- tests/pending-player-events.test.ts | 35 +++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) diff --git a/tests/pending-player-events.test.ts b/tests/pending-player-events.test.ts index 89564ab3..0ee1bf10 100644 --- a/tests/pending-player-events.test.ts +++ b/tests/pending-player-events.test.ts @@ -2,6 +2,7 @@ import { beforeEach, afterEach, describe, expect, spyOn, test } from "bun:test"; import { Keypair, PublicKey } from "#solana"; import BN from "bn.js"; import { ChatDatabase } from "../src/utils/chat-database"; +import { fake } from "./helpers/fakes"; import { stubInstantTimers } from "./helpers/timers"; process.env.TELEGRAM_TOKEN = process.env.TELEGRAM_TOKEN ?? "TEST_TELEGRAM_TOKEN"; @@ -112,6 +113,40 @@ describe("Pending player events", async () => { } }); + test("a game without a legacy record still notifies the live message", async () => { + enableJoinAnnouncementsForTest(); + const gameAddress = baseGameKey.toBase58(); + let lookups = 0; + botModule.__test_setGameDatabase( + fake>({ + getGameLastSlotWithTimestamp: () => ({ lastSlot: null, timestamp: null }), + getCreatorInfo: () => ({ telegramId: null, publicKey: null }), + // The target lookup runs first and finds no legacy record. The announcement reads the + // game again later. + getGame: () => (++lookups === 1 ? null : { game_type: "coinflip", chat_id: 77 }), + getGameMessages: () => [], + }), + ); + const warn = spyOn(console, "warn").mockImplementation(() => {}); + const log = spyOn(console, "log").mockImplementation(() => {}); + try { + botModule.__test_enqueuePendingPlayerEvent(gameAddress, { + event: makePlayerEvent(new PublicKey("So11111111111111111111111111111111111111112"), 3, 12), + eventName: "PlayerJoined", + receivedAt: Date.now(), + }); + await botModule.__test_flushPendingPlayerEvents(gameAddress, "notify"); + expect(warn.mock.calls).toEqual([]); + expect(log).toHaveBeenCalledWith(`📬 Flushing 1 pending player event(s) for ${gameAddress}`); + expect(sendCalls).toHaveLength(1); + expect(sendCalls[0]?.chatId).toBe(77); + expect(sendCalls[0]?.options?.reply_to_message_id).toBe(301); + } finally { + warn.mockRestore(); + log.mockRestore(); + } + }); + test.each([ [ "all sources", From dea6f2860c93861ecbe70745c2ac5f4e8aaec00d Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Mon, 30 Nov 2026 06:15:22 -0300 Subject: [PATCH 386/410] test(bot): render after one timer when the debounce is the largest delay A debounce of exactly MAX_TIMER_DELAY_MS fits in one timer. The test runs only the pending timer and expects one render. The mutant that also splits this delay (>= instead of >) chains a second timer, so the render does not happen. This kills that EqualityOperator mutant. --- tests/game-message-debounce.test.ts | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/tests/game-message-debounce.test.ts b/tests/game-message-debounce.test.ts index 401ca6e6..c3528a76 100644 --- a/tests/game-message-debounce.test.ts +++ b/tests/game-message-debounce.test.ts @@ -8,6 +8,7 @@ import { resetCalls, useBotHarness, } from "./helpers/bot-harness"; +import { MAX_TIMER_DELAY_MS } from "../src/utils/retry-delay"; useBotHarness(); @@ -119,6 +120,25 @@ describe("debounced game message updates", () => { }, ); + test("a debounce of exactly the largest timer delay renders after one timer", async () => { + botModule.__test_setGameMessageUpdateDebounceMs(MAX_TIMER_DELAY_MS); + vi.useFakeTimers(); + try { + await botModule.__test_processPlayerEvent(await joinEvent(), "PlayerRefunded", [target]); + expect(updates).not.toHaveBeenCalled(); + + // Run only the timer that is pending now. A second, chained timer would not run. + vi.runOnlyPendingTimers(); + for (let step = 0; step < 8; step += 1) await Promise.resolve(); + + expect(updates).toHaveBeenCalledTimes(1); + } finally { + botModule.__test_clearPendingGameMessageUpdates(); + vi.clearAllTimers(); + vi.useRealTimers(); + } + }); + test("an active game refreshes with the latest pot", async () => { await botModule.__test_processPlayerEvent((await joinEvent()) as any, "PlayerRefunded", [ target, From 87df8af9f0d779a06726904895cbd0a8aead5617 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Mon, 30 Nov 2026 06:16:51 -0300 Subject: [PATCH 387/410] refactor(evm): build the player inference args with one filter The args list used two conditional spreads. When no player count was typed, the ArrayDeclaration mutant put "Stryker was here" in the players slot, and inferMaxPlayers ignores a non-numeric value there, so the mutant was equivalent. The list now drops undefined parts with a filter. The command args never hold an empty string (they are filtered with Boolean), so this keeps the same list for every input. A new test types a coinflip with players and no token. With the other tests it kills every mutant of the new filter. --- src/evm/bot.test.ts | 8 ++++++++ src/evm/bot.ts | 5 ++++- 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/src/evm/bot.test.ts b/src/evm/bot.test.ts index 7dd87357..4739f127 100644 --- a/src/evm/bot.test.ts +++ b/src/evm/bot.test.ts @@ -842,6 +842,14 @@ describe("EVM game commands", () => { }); }); + test("a coinflip without a token reads the player count right after the amount", async () => { + useEvm(); + h.store.setToken("1", usdcAddress); + await h.text("/cf 2 7"); + const body = JSON.parse(itemAt(h.store.pending(), 0).body); + expect(body).toMatchObject({ token: usdcAddress, gameType: 0, maxPlayers: 7 }); + }); + test("accepts two-digit giveaway limits while an unrelated wallet is busy", async () => { useEvm(); h.store.add({ diff --git a/src/evm/bot.ts b/src/evm/bot.ts index f8dbbce0..14cb6101 100644 --- a/src/evm/bot.ts +++ b/src/evm/bot.ts @@ -456,7 +456,10 @@ export function registerEvmBot( return; } const inferred = inferMaxPlayers( - [command, amountText, ...(symbol ? [symbol] : []), ...(playersText ? [playersText] : [])], + // args never holds an empty string, so dropping undefined drops exactly the missing parts. + [command, amountText, symbol, playersText].filter( + (arg): arg is string => arg !== undefined, + ), 1, Boolean(symbol), settings.maxPlayers, From 24eed286006675f4131058012a7ffcd7e2757ebe Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Mon, 30 Nov 2026 06:17:35 -0300 Subject: [PATCH 388/410] refactor(evm): reject a non-integer player reply through the range check The typed player count check started with value === null. Since null < 1 is true, the ConditionalExpression mutant that drops this test was equivalent. A reply that is not an integer now becomes 0, which is below the minimum for every game type, so the range check alone rejects it. The accepted and rejected inputs stay the same. New tests type each limit for coinflip and giveaway: 1 and 0 are rejected, 2, 1 and 100 are accepted. They kill the coinflip, <= and >= mutants on this line, and the && mutant of the new fallback. --- src/evm/setup.test.ts | 26 ++++++++++++++++++++++++++ src/evm/setup.ts | 5 +++-- 2 files changed, 29 insertions(+), 2 deletions(-) diff --git a/src/evm/setup.test.ts b/src/evm/setup.test.ts index f697caa2..a91a3ae6 100644 --- a/src/evm/setup.test.ts +++ b/src/evm/setup.test.ts @@ -513,6 +513,32 @@ test("custom player counts are validated and applied", async () => { expect(f.submitted[0]).toMatchObject({ players: 7, minPlayers: 2 }); }); +test.each([ + ["coinflip", "1", null], + ["coinflip", "2", 2], + ["coinflip", "100", 100], + ["giveaway", "0", null], + ["giveaway", "1", 1], + ["giveaway", "100", 100], +] as const)( + "a %s accepts a typed player count of %p only inside its limits", + async (type, typed, players) => { + const f = fixture(false, type, 1); + await f.open(); + await f.click(f.button(() => true)); + await f.click(f.button((text) => text.includes("Custom Players"))); + + await f.reply(typed); + + if (players === null) { + expect(f.sent.at(-1)).toBe("Invalid value. Reply to the prompt again."); + expect(storedSetup(f).input).toBe("players"); + } else { + expect(storedSetup(f)).toMatchObject({ screen: "confirm", players }); + } + }, +); + test("custom amounts below the token minimum are rejected", async () => { const f = fixture(); await f.open(); diff --git a/src/evm/setup.ts b/src/evm/setup.ts index 4f6902d7..9ba8abb6 100644 --- a/src/evm/setup.ts +++ b/src/evm/setup.ts @@ -231,8 +231,9 @@ export function registerEvmSetup( s.amount = formatTokenAmount(raw, s.token.decimals); s.screen = "players"; } else { - const value = parseDecimalInteger(ctx.message.text); - if (value === null || value < (s.type === "coinflip" ? 2 : 1) || value > 100) + // A reply that is not an integer becomes 0, which every game type rejects. + const value = parseDecimalInteger(ctx.message.text) ?? 0; + if (value < (s.type === "coinflip" ? 2 : 1) || value > 100) // Stryker disable next-line StringLiteral: The catch sends the same invalid-value reply. throw new Error("players"); s.players = value; From 581b19c828dc358729746c15553ab16d7defa2a0 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Mon, 30 Nov 2026 06:18:11 -0300 Subject: [PATCH 389/410] test(admin-status): cover probe error text, HTTP latency and a null body New probe tests check an empty error message ("error"), the 80 character cut, redaction of a plain http:// URL, the latency of an HTTP failure with an injected clock, and a JSON body of null. They kill the StringLiteral, MethodExpression and Regex mutants in describeProbeError, the ArithmeticOperator mutant in the HTTP failure branch, and the two OptionalChaining mutants on the payload. --- tests/admin-status.test.ts | 51 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) diff --git a/tests/admin-status.test.ts b/tests/admin-status.test.ts index 7c79c265..b15da581 100644 --- a/tests/admin-status.test.ts +++ b/tests/admin-status.test.ts @@ -121,6 +121,57 @@ describe("rpc probe", () => { expect(result).toMatchObject({ ok: false, error: "unexpected response" }); }); + test("an empty error message is reported as a plain error", async () => { + const result = await probeRpcEndpoint("https://rpc.example", { + fetchFn: mockProbeFetch(async () => { + throw new Error(""); + }), + }); + expect(result).toMatchObject({ ok: false, error: "error" }); + }); + + test("a long error message is cut to 80 characters", async () => { + const result = await probeRpcEndpoint("https://rpc.example", { + fetchFn: mockProbeFetch(async () => { + throw new Error("x".repeat(100)); + }), + }); + expect(result).toMatchObject({ ok: false, error: "x".repeat(80) }); + }); + + test("redacts a plain HTTP endpoint from remote errors", async () => { + const result = await probeRpcEndpoint("https://rpc.example", { + fetchFn: mockProbeFetch(async () => { + throw new Error("Unable to connect to http://rpc.example/?token=fixture-only"); + }), + }); + expect(result).toMatchObject({ ok: false, error: "Unable to connect to [url]" }); + }); + + test("an HTTP failure reports the time the request took", async () => { + let clock = 1_000; + const result = await probeRpcEndpoint("https://rpc.example", { + now: () => clock, + fetchFn: mockProbeFetch(async () => { + clock += 25; + return jsonResponse({}, 503); + }), + }); + expect(result).toEqual({ + endpoint: "https://rpc.example", + ok: false, + latencyMs: 25, + error: "HTTP 503", + }); + }); + + test("a null JSON body is an unexpected response", async () => { + const result = await probeRpcEndpoint("https://rpc.example", { + fetchFn: mockProbeFetch(async () => new Response("null")), + }); + expect(result).toMatchObject({ ok: false, error: "unexpected response" }); + }); + test("accepts slot zero and measures through the RPC response body", async () => { let clock = 100; const result = await probeRpcEndpoint("https://rpc.example", { From 1e0072535dfce5778d5f5c3dbe528b705a4e3233 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Mon, 30 Nov 2026 06:19:01 -0300 Subject: [PATCH 390/410] refactor(chat-defaults): let clampChatPlayers handle a null player count clampChatPlayers already returns null for a null candidate (Number.isFinite(null ?? NaN) is false). So the parsed === null guard before it gave the same result on every path, and its ConditionalExpression mutant was equivalent. The guard is removed. --- src/handlers/chat-defaults.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/handlers/chat-defaults.ts b/src/handlers/chat-defaults.ts index 435fe79e..578c513d 100644 --- a/src/handlers/chat-defaults.ts +++ b/src/handlers/chat-defaults.ts @@ -520,7 +520,8 @@ const handlePlayersUpdate = async ( } const parsed = parseDecimalInteger(input); - const clamped = parsed === null ? null : clampChatPlayers(parsed, target, maxLimit); + // clampChatPlayers returns null for a null candidate. + const clamped = clampChatPlayers(parsed, target, maxLimit); if (clamped === null) { await deps.replyErrorToMessage( ctx, From 0ed0f49c7f2e3418608979246f63fb5d7fdf17e9 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Mon, 30 Nov 2026 06:19:45 -0300 Subject: [PATCH 391/410] test(chat-defaults): check prompt sessions without a chat and input results A join-rate prompt whose update and reply carry no chat id must not open an input session. This kills the ConditionalExpression mutant on chatId != null. The join-rate tests now also check that handleSettingsInput reports the invalid-rate and expired-session replies as handled, which kills the BooleanLiteral mutant on the invalid-rate return. --- tests/chat-defaults.handler.test.ts | 33 +++++++++++++++++++++++++++-- 1 file changed, 31 insertions(+), 2 deletions(-) diff --git a/tests/chat-defaults.handler.test.ts b/tests/chat-defaults.handler.test.ts index 571dc0e9..af031012 100644 --- a/tests/chat-defaults.handler.test.ts +++ b/tests/chat-defaults.handler.test.ts @@ -1845,13 +1845,15 @@ describe("chat defaults menus and inputs", () => { await h.press("chat_defaults_set_join_rate_custom"); expect(h.lastMenu().text).toBe("Enter a custom rate limit (0-30 per minute):"); const session = promptSession()!; - await h.module.handleSettingsInput(h.ctxFor(), session, "31"); + expect(await h.module.handleSettingsInput(h.ctxFor(), session, "31")).toBe(true); expect(h.replies.at(-1)).toBe("❌ Invalid rate. Please enter a number between 0 and 30."); await h.module.handleSettingsInput(h.ctxFor(), session, "0"); expect(h.replies.at(-1)).toBe("✅ Rate limit set to disabled"); await h.module.handleSettingsInput(h.ctxFor(), session, "12"); expect(h.replies.at(-1)).toBe("✅ Rate limit set to 12/min"); - await h.module.handleSettingsInput(h.ctxFor(), { ...session, chatId: "x" } as any, "3"); + expect( + await h.module.handleSettingsInput(h.ctxFor(), { ...session, chatId: "x" } as any, "3"), + ).toBe(true); expect(h.replies.at(-1)).toBe("❌ Session expired. Please try again."); await h.press("chat_defaults_clear_join_notifications"); @@ -1861,6 +1863,33 @@ describe("chat defaults menus and inputs", () => { }); }); + test("a join-rate prompt without a known chat opens no input session", async () => { + const h = setup(); + const callback = "chat_defaults_set_join_rate_custom"; + const ctx = h.ctxFor(callback); + // Neither the update nor the sent reply carries a chat id. + ctx.chat = { type: "supergroup" }; + ctx.callbackQuery.message = { message_id: 11 }; + ctx.editMessageText = async () => { + throw new Error("message cannot be edited"); + }; + ctx.reply = async (text: string) => { + h.menus.push({ text, options: undefined }); + return { message_id: 50 }; + }; + + const warn = spyOn(console, "warn").mockImplementation(() => {}); + try { + expect(await h.mockBot.dispatch(callback, ctx)).toBe(true); + } finally { + warn.mockRestore(); + } + + expect(h.lastMenu().text).toBe("Enter a custom rate limit (0-30 per minute):"); + expect(getInputSession("null_50")).toBeUndefined(); + expect(getInputSession("99_50")).toBeUndefined(); + }); + test.each([ { label: "an editable menu", edited: true, delivered: true, id: 11 }, { label: "a fallback reply", edited: false, delivered: true, id: 50 }, From 13ffbd67d8c8302e69b454ca2b4bc374cdcd3aa3 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Mon, 30 Nov 2026 06:20:13 -0300 Subject: [PATCH 392/410] test(faucet): check the stored error of a claim with a bad balance A claim that fails because the wallet returned an invalid raw balance stores that message in last_error. The test now checks it, which kills the StringLiteral mutant on the error text. --- tests/faucet-handler.test.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/tests/faucet-handler.test.ts b/tests/faucet-handler.test.ts index 583208d2..5c6b69dc 100644 --- a/tests/faucet-handler.test.ts +++ b/tests/faucet-handler.test.ts @@ -601,6 +601,7 @@ describe("faucet handler", () => { expect(harness.transferSenders).toEqual([]); expect(db.getFaucet(1)?.status).toBe("active"); expect(db.getClaim(1, 20n)?.status).toBe("failed"); + expect(db.getClaim(1, 20n)?.last_error).toBe("Wallet returned an invalid raw balance"); expect(harness.replies.at(-1)?.text).toContain("Could not verify the faucet balance"); }, ); From 14cbdc75182f8f2924322e178fb45b438ee9d542 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Mon, 30 Nov 2026 06:21:57 -0300 Subject: [PATCH 393/410] test(game-callbacks): cover prompt targets, the cancel button and back to amounts New prompt-target tests: - a custom amount callback without a message stores the prompt under the sent reply (kills the OptionalChaining mutant on message_id); - a callback without a chat stores an edited prompt under the message chat, not chat 0 (kills chatId === originalChatId -> true); - a sender id that only the setup module sees makes requireTelegramId throw, and the logged error names "type amount prompt" (kills the StringLiteral mutant on that label); - back to amounts uses the stored balance and minimum for the keyboard without a wallet read (kills the ObjectLiteral mutant on { session, tokenContext }). The compact players test now also checks the cancel button text and callback data (kills two StringLiteral mutants). --- tests/game-callbacks.prompt-target.test.ts | 86 ++++++++++++++++++++-- 1 file changed, 81 insertions(+), 5 deletions(-) diff --git a/tests/game-callbacks.prompt-target.test.ts b/tests/game-callbacks.prompt-target.test.ts index 9696a4d3..984777a2 100644 --- a/tests/game-callbacks.prompt-target.test.ts +++ b/tests/game-callbacks.prompt-target.test.ts @@ -44,11 +44,19 @@ afterEach(() => { type HandlerOptions = { tokenBalance?: () => Promise; policyMinimum?: number; + // A sender id that the setup module reads, whatever ctx.from holds. + setupSenderId?: string; }; type InvokeOptions = { // Leave out ctx.chat, as for a callback that Telegram sends without a chat. withoutChat?: boolean; + // Leave out the callback message, as for a callback on an inline message. + withoutMessage?: boolean; + // Leave out ctx.from. + withoutSender?: boolean; + // Runs while the edit of the callback message is in flight. + onEdit?: () => void; replyResult?: () => Promise; }; @@ -85,8 +93,12 @@ function makeHandlers(options: HandlerOptions = {}) { upsertGameSetupSession, clearGameSetupSession, safeAnswerCallbackQuery, - getTelegramId, - getTelegramIdString, + getTelegramId: + options.setupSenderId === undefined + ? getTelegramId + : () => BigInt(options.setupSenderId ?? "0"), + getTelegramIdString: + options.setupSenderId === undefined ? getTelegramIdString : () => options.setupSenderId, }); const callbacks = createGameCallbacksModule({ bot, @@ -118,6 +130,7 @@ function makeHandlers(options: HandlerOptions = {}) { extra.replyResult ? extra.replyResult() : { message_id: SENT, chat: { id: CHAT } }, ); const editMessageText = mock(async (_text: string, _options?: unknown) => { + extra.onEdit?.(); if (useReply) throw new Error("fixture edit unavailable"); return true; }); @@ -126,13 +139,13 @@ function makeHandlers(options: HandlerOptions = {}) { typeof pattern === "string" ? (pattern === data ? [data] : null) : data.match(pattern); if (!match) continue; const ctx = { - from: { id: Number(CREATOR) }, + ...(extra.withoutSender ? {} : { from: { id: Number(CREATOR) } }), ...(extra.withoutChat ? {} : { chat: { id: CHAT, type: "supergroup" } }), match, callbackQuery: { id: "fixture-callback", data, - message: { message_id: OLD, chat: { id: CHAT } }, + ...(extra.withoutMessage ? {} : { message: { message_id: OLD, chat: { id: CHAT } } }), }, answerCallbackQuery, reply, @@ -241,7 +254,10 @@ test("keeps the existing custom players card and its precise text when it can be expect(editMessageText.mock.calls).toEqual([ [ "👥 Type Custom Players - Coinflip\n\nAmount: 2 TKN\n\nPlease type the number of players for this game.\n\nRange: 2-20 players", - expect.objectContaining({ parse_mode: "HTML" }), + expect.objectContaining({ + parse_mode: "HTML", + reply_markup: new InlineKeyboard().text("❌ Cancel", `cancel_game_setup_${CREATOR}`).row(), + }), ], ]); expect(getGameSetupSession(oldKey)).toMatchObject({ @@ -456,6 +472,48 @@ describe("custom amount prompt", () => { }); }); + test("a callback without a message stores the prompt under the sent reply", async () => { + const { invoke } = makeHandlers(); + const { answerCallbackQuery, editMessageText } = await invoke(amountData, false, { + withoutMessage: true, + }); + expect(editMessageText).not.toHaveBeenCalled(); + expect(answerCallbackQuery.mock.calls).toEqual([["Type your amount..."]]); + expect(getGameSetupSession(sentKey)).toMatchObject({ + waitingFor: "amount_input", + chatId: CHAT, + messageId: SENT, + }); + }); + + test("a callback without a chat stores an edited prompt under the message chat", async () => { + const { invoke } = makeHandlers(); + await invoke(amountData, false, { withoutChat: true }); + expect(getGameSetupSession(`0_${OLD}`)).toBeUndefined(); + expect(getGameSetupSession(oldKey)).toMatchObject({ + waitingFor: "amount_input", + chatId: CHAT, + messageId: OLD, + }); + }); + + test("a prompt whose sender id is missing names the prompt in the logged error", async () => { + seedSession(); + const error = spyOn(console, "error").mockImplementation(() => {}); + spies.push(error); + const { invoke } = makeHandlers({ setupSenderId: CREATOR }); + const { answerCallbackQuery } = await invoke(amountData, false, { withoutSender: true }); + expect(error.mock.calls).toEqual([ + [ + "Error in creator-protected custom_amount callback:", + expect.objectContaining({ + message: "Missing Telegram user id for type amount prompt", + }), + ], + ]); + expect(answerCallbackQuery.mock.calls).toEqual([["❌ Error setting up text input"]]); + }); + test("a reply in another chat stores the prompt under that chat", async () => { seedSession(); const { invoke } = makeHandlers(); @@ -489,6 +547,24 @@ describe("custom amount prompt", () => { }); }); +describe("back to amounts", () => { + test("uses the stored balance and minimum for the amount keyboard", async () => { + seedSession(); + const error = spyOn(console, "error").mockImplementation(() => {}); + spies.push(error); + const { invoke } = makeHandlers(); + const { editMessageText } = await invoke(`back_to_amounts_coinflip_${CREATOR}`, false); + expect(error.mock.calls).toEqual([]); + expect(editMessageText.mock.calls[0]?.[1]).toMatchObject({ + reply_markup: createAmountSelectionKeyboard("coinflip", 10, CREATOR, 1, { + decimals: 6, + tokenPriceUSD: undefined, + }), + }); + expect(getGameSetupSession(oldKey)).toBeUndefined(); + }); +}); + describe("legacy custom players prompt", () => { test("a giveaway without a stored setup shows its range, keyboard and defaults", async () => { const { invoke } = makeHandlers(); From f2639049d74cff3673171d8a7c71723964e80e35 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Mon, 30 Nov 2026 06:22:12 -0300 Subject: [PATCH 394/410] refactor(game-callbacks): store the setup snapshot again in the compact players prompt Commit 244d8b7 dropped ...(creatorContext.session ?? {}) from this storeSetupPromptSession call. On the same-message path the old code wrote the fields read at the start of the handler. The new code wrote only the prompt fields and merged them with the stored state at write time. The two differ when the stored setup changes or expires while the prompt edit is in flight. This restores the old form and removes the comment that claimed both paths were the same. The new test clears the stored setup during the edit and expects the fields read before the edit. It fails without the spread and with the && mutant of ??. Both forms bring back a setup that was cancelled during the edit. That race is older than this change and is not fixed here. --- src/handlers/game-callbacks.ts | 2 +- tests/game-callbacks.prompt-target.test.ts | 17 +++++++++++++++++ 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/src/handlers/game-callbacks.ts b/src/handlers/game-callbacks.ts index c46347c8..d1d692f8 100644 --- a/src/handlers/game-callbacks.ts +++ b/src/handlers/game-callbacks.ts @@ -1913,8 +1913,8 @@ export const createGameCallbacksModule = (deps: GameCallbacksModuleDeps): GameCa .row(), }); - // storeSetupPromptSession keeps the stored setup fields on both paths. storeSetupPromptSession(ctx, creatorContext, response, { + ...(creatorContext.session ?? {}), waitingFor: "players_input", gameType, amount, diff --git a/tests/game-callbacks.prompt-target.test.ts b/tests/game-callbacks.prompt-target.test.ts index 984777a2..cbf8b689 100644 --- a/tests/game-callbacks.prompt-target.test.ts +++ b/tests/game-callbacks.prompt-target.test.ts @@ -272,6 +272,23 @@ test("keeps the existing custom players card and its precise text when it can be expect(getGameSetupSession(sentKey)).toBeUndefined(); }); +test("a compact player prompt keeps the setup fields it read when the stored setup is cleared during the edit", async () => { + seedSession(); + const { invoke } = makeHandlers(); + // Another update clears the setup while the prompt edit is in flight. The prompt still + // stores every field it read before the edit. + await invoke(compactPlayers(), false, { onEdit: () => clearGameSetupSession(oldKey) }); + expect(getGameSetupSession(oldKey)).toMatchObject({ + waitingFor: "players_input", + chatId: CHAT, + messageId: OLD, + userBalance: 10, + timeoutSeconds: 4_500, + minPlayers: 2, + maxPlayersLimit: 20, + }); +}); + test("updates a compact player prompt on the original message without a stored session", async () => { const { invoke } = makeHandlers(); const { reply, editMessageText } = await invoke(compactPlayers(), false); From d883c18af2c120f7df39d54dbdc1561dd99f1f56 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Mon, 30 Nov 2026 06:23:27 -0300 Subject: [PATCH 395/410] test(game-callbacks): kill the typed player range mutants instead of disabling them The Stryker disable on the typed player range check hid killable ConditionalExpression mutants: a check that is always true rejects a valid count, one that is always false accepts 0 or 999, and dropping players < minPlayers accepts 1. The disable is removed. New tests type "1" (rejected) and "2" (accepted) for a coinflip. With the existing 20 and 21 tests they kill every variant except players === null -> false, which is equivalent because null < minPlayers is true. --- src/handlers/game-callbacks.ts | 1 - tests/game-callbacks.prompt-target.test.ts | 21 +++++++++++++++++++++ 2 files changed, 21 insertions(+), 1 deletion(-) diff --git a/src/handlers/game-callbacks.ts b/src/handlers/game-callbacks.ts index d1d692f8..4f1cdc8f 100644 --- a/src/handlers/game-callbacks.ts +++ b/src/handlers/game-callbacks.ts @@ -722,7 +722,6 @@ export const createGameCallbacksModule = (deps: GameCallbacksModuleDeps): GameCa `🔍 Custom players input: "${inputText}" -> ${players} (gameType: ${userSession.gameType}, min: ${minPlayers}, max: ${maxPlayers})`, ); - // Stryker disable next-line ConditionalExpression: null is below every player minimum, so the range check also rejects it. if (players === null || players < minPlayers || players > maxPlayers) { await retryAtPrompt( `❌ Invalid number of players. Please enter a number between ${minPlayers} and ${maxPlayers}.`, diff --git a/tests/game-callbacks.prompt-target.test.ts b/tests/game-callbacks.prompt-target.test.ts index cbf8b689..7bc6115a 100644 --- a/tests/game-callbacks.prompt-target.test.ts +++ b/tests/game-callbacks.prompt-target.test.ts @@ -693,6 +693,27 @@ describe("typed setup input", () => { expect(getGameSetupSession(oldKey)).toMatchObject({ waitingFor: "setup", players: 20 }); }); + test.each([ + ["1", null], + ["2", 2], + ] as const)( + "a coinflip checks the typed player count %p against two players", + async (text, players) => { + seedSession(); + upsertGameSetupSession(oldKey, { waitingFor: "players_input", maxPlayersLimit: 20 }); + const { editMessageText } = await typeInto(text, undefined, false); + if (players === null) { + expect(editMessageText.mock.calls[0]?.[2]).toBe( + "❌ Invalid number of players. Please enter a number between 2 and 20.", + ); + expect(getGameSetupSession(oldKey)).toMatchObject({ waitingFor: "players_input" }); + } else { + expect(editMessageText.mock.calls[0]?.[2]).toContain("Confirm Coinflip"); + expect(getGameSetupSession(oldKey)).toMatchObject({ waitingFor: "setup", players }); + } + }, + ); + test("a message without a chat uses chat 0 for the stored setup", async () => { upsertGameSetupSession(`0_${OLD}`, { waitingFor: "players_input", From 1e371a037c0336652b53827bc41b6e47771c1cd0 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Mon, 30 Nov 2026 06:23:51 -0300 Subject: [PATCH 396/410] test(game-callbacks): check the exact custom amount prompt payload The custom amount prompt test now checks the edited text, the HTML parse mode and the cancel keyboard. This kills the ObjectLiteral mutant on the respondWithMenu payload and the StringLiteral mutant on "HTML" in presentCustomAmountPrompt. --- tests/game-callbacks.prompt-target.test.ts | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/tests/game-callbacks.prompt-target.test.ts b/tests/game-callbacks.prompt-target.test.ts index 7bc6115a..c5c80843 100644 --- a/tests/game-callbacks.prompt-target.test.ts +++ b/tests/game-callbacks.prompt-target.test.ts @@ -413,8 +413,20 @@ describe("custom amount prompt", () => { return 3_000_000; }, }); - await invoke(amountData, false); + const { editMessageText } = await invoke(amountData, false); expect(reads).toBe(0); + expect(editMessageText.mock.calls).toEqual([ + [ + "✏️ Type Custom Amount - Coinflip\n\nPlease type the amount you want to use.\n\nMin: 1 TKN", + { + parse_mode: "HTML", + link_preview_options: { is_disabled: true }, + reply_markup: new InlineKeyboard() + .text("❌ Cancel", `cancel_game_setup_${CREATOR}`) + .row(), + }, + ], + ]); expect(getGameSetupSession(oldKey)).toMatchObject({ waitingFor: "amount_input", userBalance: 10, From d84670f44a3e5766195c40e732752e40158ab300 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Mon, 30 Nov 2026 06:24:43 -0300 Subject: [PATCH 397/410] test(wallet): cover token percentage sends and a repeated wrap prefix New send tests choose 50% of a token balance, once with the quick button and once typed into the custom amount prompt. Both expect half of the raw balance. They kill the ObjectLiteral mutants on the tokenBalance snapshot in both send paths. A wrap confirmation whose data repeats the prefix is now rejected, which kills the Regex mutant without ^. The wrap handler is registered with bot.callbackQuery(/^confirm_wrap_/), so ctx.callbackQuery and its data are always set there. The OptionalChaining and StringLiteral mutants on that read are excluded. --- src/handlers/wallet-transactions.ts | 1 + tests/wallet-transactions.flows.test.ts | 16 ++++++++++++++++ 2 files changed, 17 insertions(+) diff --git a/src/handlers/wallet-transactions.ts b/src/handlers/wallet-transactions.ts index 83f9ce3b..f8be3ae4 100644 --- a/src/handlers/wallet-transactions.ts +++ b/src/handlers/wallet-transactions.ts @@ -906,6 +906,7 @@ export const createWalletTransactionsModule = ( bot.callbackQuery(/^confirm_wrap_/, async (ctx) => { try { + // Stryker disable next-line OptionalChaining,StringLiteral: bot.callbackQuery(/^confirm_wrap_/) runs this handler only for a callback query whose data matches, so ctx.callbackQuery and its data are always set. const match = /^confirm_wrap_(\d+)$/.exec(ctx.callbackQuery?.data ?? ""); const lamportsToWrap = Number(match?.[1]); diff --git a/tests/wallet-transactions.flows.test.ts b/tests/wallet-transactions.flows.test.ts index 8395b35a..f344b1a5 100644 --- a/tests/wallet-transactions.flows.test.ts +++ b/tests/wallet-transactions.flows.test.ts @@ -228,6 +228,21 @@ describe("send flow", () => { expect(lastText()).toContain("Error processing input"); }); + test("a quick percentage of a token sends that share of its balance", async () => { + await press(`send_amount_${TOKEN_MINT}_50%`, { userId: USER }); + await replyToPrompt(recipient); + await press(confirmButton("confirm_send_"), { userId: USER }); + expect(transfers.find((entry) => entry.kind === "token")?.args[2]).toBe(1_250_000); + }); + + test("a typed percentage of a token sends that share of its balance", async () => { + await press(`send_amount_${TOKEN_MINT}_CUSTOM`, { userId: USER }); + await replyToPrompt("50%"); + await replyToPrompt(recipient); + await press(confirmButton("confirm_send_"), { userId: USER }); + expect(transfers.find((entry) => entry.kind === "token")?.args[2]).toBe(1_250_000); + }); + test("MAX token sends use the full balance", async () => { await press(`send_amount_${TOKEN_MINT}_MAX`, { userId: USER }); await replyToPrompt(recipient); @@ -344,6 +359,7 @@ describe("wrap and unwrap flows", () => { ["an unsafe integer", "9007199254740993"], ["a negative value", "-1"], ["zero", "0"], + ["a repeated prefix", "confirm_wrap_100"], ])("rejects a wrap confirmation with %s before moving funds", async (_label, amount) => { const wraps: unknown[][] = []; stub(wallet, "wrapSol", async (...args: unknown[]) => { From d2a06d6f081ea3328258b12d266b439599fddd5c Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Mon, 30 Nov 2026 06:25:05 -0300 Subject: [PATCH 398/410] refactor(buy-alerts): return early for missing DexScreener pairs selectSolanaPairs looped over pairs ?? []. Its ArrayDeclaration mutant looped over a string instead, and every character was skipped because it has no chainId, so the mutant was equivalent. The function now returns [] when pairs is null or undefined and then loops over pairs. The result is the same for every input, and the existing selectSolanaPairs(null) test kills every mutant of the new guard. --- src/services/buy-alerts/dexscreener.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/services/buy-alerts/dexscreener.ts b/src/services/buy-alerts/dexscreener.ts index ec094507..b99ec7fe 100644 --- a/src/services/buy-alerts/dexscreener.ts +++ b/src/services/buy-alerts/dexscreener.ts @@ -83,9 +83,10 @@ export function selectSolanaPairs( pairs: Array> | null | undefined, mint?: string, ): PairStats[] { + if (pairs == null) return []; const target = mint?.trim(); const ranked: Array<{ pair: z.infer; base: boolean; quote: boolean }> = []; - for (const pair of pairs ?? []) { + for (const pair of pairs) { if (pair.chainId?.toLowerCase() !== "solana") continue; const base = !target || pair.baseToken?.address?.trim() === target; const quote = Boolean(target) && pair.quoteToken?.address?.trim() === target; From de7646c8b36e2015bae7002654bf0a7cbe43f70b Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Mon, 30 Nov 2026 06:25:38 -0300 Subject: [PATCH 399/410] test(buy-alerts): kill the trade filter mutants instead of disabling them The Stryker disable on the GeckoTerminal trade filter hid killable ConditionalExpression mutants: a filter that is always true drops every trade, and one that is always false keeps a zero amount. The disable is removed. New cases expect null for a zero token amount, a blank transaction hash and a missing trader. They kill every variant except tokenAmount == null -> false, which is equivalent because null <= 0 is true. --- src/services/buy-alerts/pool-trades.ts | 1 - tests/buy-alerts.pool-trades.test.ts | 10 ++++++++++ 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/src/services/buy-alerts/pool-trades.ts b/src/services/buy-alerts/pool-trades.ts index ebc6259b..6f963566 100644 --- a/src/services/buy-alerts/pool-trades.ts +++ b/src/services/buy-alerts/pool-trades.ts @@ -128,7 +128,6 @@ export function parseGeckoPoolTrade( const trader = (attrs.tx_from_address ?? "").trim(); const tokenAmount = parseFiniteNumber(attrs.to_token_amount); const fromAmount = parseFiniteNumber(attrs.from_token_amount); - // Stryker disable next-line ConditionalExpression: null <= 0 is true, so the amount check also rejects null. TypeScript needs the null check. if (!signature || !trader || tokenAmount == null || tokenAmount <= 0) { return null; } diff --git a/tests/buy-alerts.pool-trades.test.ts b/tests/buy-alerts.pool-trades.test.ts index c29735c8..799179bd 100644 --- a/tests/buy-alerts.pool-trades.test.ts +++ b/tests/buy-alerts.pool-trades.test.ts @@ -47,6 +47,16 @@ test("parseGeckoPoolTrade skips trades whose output is another mint", () => { ).toBeNull(); }); +test.each([ + ["a zero token amount", { to_token_amount: "0" }], + ["a blank transaction hash", { tx_hash: " " }], + ["no trader", { tx_from_address: undefined }], +])("parseGeckoPoolTrade skips a trade with %s", (_label, change) => { + expect( + parseGeckoPoolTrade(mint, { attributes: { ...geckoBuy.attributes, ...change } }), + ).toBeNull(); +}); + test("parseRetryAfterMs accepts seconds and HTTP dates", () => { const now = Date.parse("2026-09-03T20:00:00.000Z"); expect(parseRetryAfterMs("30", now)).toBe(30_000); From 5d14b2efe18b7a580cfc5c832407de690de87579 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Mon, 30 Nov 2026 06:38:57 -0300 Subject: [PATCH 400/410] test(buy-alerts): cover poller backoff, unparsed trades and stop New pool trade poller tests: - each malformed trades response doubles the wait before the next request, and the reported error names the malformed response (kills the StringLiteral mutant and the removed deferAfterTradeFailure call); - a snapshot with a trade that does not parse still emits the newer buy (kills if (!event) -> false); - a response that arrives after stop() emits nothing (kills the removed watches.clear() call). The two Stryker disables in pollNow hid killable "-> true" mutants that drop every pool. The ConditionalExpression part is removed from both; the existing emit tests kill those variants. The "-> false" variants stay as documented survivors: setMints stores a watch for every mint, and refreshPoolQueue queues only pools with a target. The ArrayDeclaration disable stays, because that empty list is never returned. The trade time now parses String(block_timestamp) instead of block_timestamp ?? "". A missing value gives "undefined", which parses to NaN like "", so the result is the same and the equivalent StringLiteral mutant is gone. --- src/services/buy-alerts/pool-trades.ts | 7 +- tests/buy-alerts.pool-trades.test.ts | 106 +++++++++++++++++++++++++ 2 files changed, 109 insertions(+), 4 deletions(-) diff --git a/src/services/buy-alerts/pool-trades.ts b/src/services/buy-alerts/pool-trades.ts index 6f963566..d466fd1d 100644 --- a/src/services/buy-alerts/pool-trades.ts +++ b/src/services/buy-alerts/pool-trades.ts @@ -333,8 +333,8 @@ export function createPoolTradePoller(options: PoolTradePollerOptions = {}): Poo const event = parseGeckoPoolTrade(mint, trade, pair.dexId, pair.quoteSymbol); if (!event) continue; if (!rememberSignature(known, event.signature)) continue; - const tradeTimestamp = Date.parse(trade.attributes.block_timestamp ?? ""); - // An undated trade parses to NaN, and NaN >= since is false. + // An undated trade parses "undefined" to NaN, and NaN >= since is false. + const tradeTimestamp = Date.parse(String(trade.attributes.block_timestamp)); const occurredAfterWatchStarted = tradeTimestamp >= watch.since; if (!isFirstPass || occurredAfterWatchStarted) { emit(event); @@ -397,7 +397,7 @@ export function createPoolTradePoller(options: PoolTradePollerOptions = {}): Poo const targetsByMint = await Promise.all( mints.map(async (mint) => { const watch = watches.get(mint); - // Stryker disable next-line ConditionalExpression,ArrayDeclaration: setMints stores a watch for every mint, so this check only narrows the type. + // Stryker disable next-line ArrayDeclaration: setMints stores a watch for every mint, so this empty list is never returned. if (!watch) return []; return discoverMintPools(mint, watch); }), @@ -410,7 +410,6 @@ export function createPoolTradePoller(options: PoolTradePollerOptions = {}): Poo if (!queuedTarget) break; const key = targetKey(queuedTarget.mint, queuedTarget.pairAddress); const target = targetByKey.get(key); - // Stryker disable next-line ConditionalExpression: refreshPoolQueue queues only pools with a target and setMints only removes entries, so this check only narrows the type. if (!target) continue; poolQueue.push(queuedTarget); await pollPool(target); diff --git a/tests/buy-alerts.pool-trades.test.ts b/tests/buy-alerts.pool-trades.test.ts index 799179bd..37c784ab 100644 --- a/tests/buy-alerts.pool-trades.test.ts +++ b/tests/buy-alerts.pool-trades.test.ts @@ -218,6 +218,112 @@ test("pool trade poller seeds existing trades then emits only new buys", async ( poller.stop(); }); +const singlePool = (pairAddress: string) => async () => ({ + priceUsd: 1, + marketCapUsd: 1, + priceChangeH24: 1, + url: null, + dexId: "raydium", + quoteSymbol: "SOL", + pairAddress, + tokenName: "TOKEN", +}); + +test("pool trade poller skips a trade it cannot parse and keeps the rest of the snapshot", async () => { + const received: string[] = []; + let payload: { data: unknown[] } = { data: [geckoBuy] }; + const poller = createPoolTradePoller({ + intervalMs: 60_000, + minRequestIntervalMs: 0, + fetchPairStats: singlePool("pair-unparsed"), + fetchTrades: async () => payload, + }); + poller.onTrade((event) => received.push(event.signature)); + poller.setMints([mint]); + await poller.pollNow(); + + // Newest first: a new buy, then a sell that does not parse as a buy of this mint. + payload = { + data: [ + { attributes: { ...geckoBuy.attributes, tx_hash: "buy-after-sell" } }, + { attributes: { ...geckoBuy.attributes, tx_hash: "sell", to_token_address: WSOL_MINT } }, + ], + }; + await poller.pollNow(); + + expect(received).toEqual(["buy-after-sell"]); + poller.stop(); +}); + +test("pool trade poller backs off after each malformed trades response", async () => { + const errors: unknown[] = []; + const delays: number[] = []; + let now = 0; + const poller = createPoolTradePoller({ + intervalMs: 60_000, + minRequestIntervalMs: 1_000, + fetchPairStats: singlePool("pair-malformed"), + fetchTrades: async () => ({ malformed: true }), + onError: (error) => errors.push(error), + now: () => now, + wait: async (delayMs) => { + delays.push(delayMs); + now += delayMs; + }, + }); + + // setMints starts one poll, and the test adds three more. + poller.setMints([mint]); + await poller.pollNow(); + await poller.pollNow(); + await poller.pollNow(); + + // Each failure doubles the wait before the next request. + expect(delays).toEqual([1_000, 2_000, 4_000]); + expect(errors.map((error) => (error instanceof Error ? error.message : error))).toEqual( + Array(4).fill("GeckoTerminal trades response was malformed"), + ); + poller.stop(); +}); + +test("pool trade poller drops a response that arrives after stop", async () => { + const received: string[] = []; + let release: (payload: unknown) => void = () => {}; + let fetches = 0; + const poller = createPoolTradePoller({ + intervalMs: 60_000, + minRequestIntervalMs: 0, + fetchPairStats: singlePool("pair-stopped"), + fetchTrades: () => { + fetches += 1; + return new Promise((resolve) => { + release = resolve; + }); + }, + }); + poller.onTrade((event) => received.push(event.signature)); + poller.setMints([mint]); + const poll = poller.pollNow(); + for (let step = 0; step < 50 && fetches === 0; step += 1) await Promise.resolve(); + expect(fetches).toBe(1); + + poller.stop(); + release({ + data: [ + { + attributes: { + ...geckoBuy.attributes, + tx_hash: "after-stop", + block_timestamp: "2100-01-01T00:00:00Z", + }, + }, + ], + }); + await poll; + + expect(received).toEqual([]); +}); + test("rememberSignature evicts the oldest hashes once the per-mint cap is hit", () => { const known = new Set(); expect(rememberSignature(known, "a", 2)).toBe(true); From 9fb6edb246a26ce006fbcc2b64a4e50d18aaa23c Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Mon, 30 Nov 2026 06:39:15 -0300 Subject: [PATCH 401/410] test(buy-alerts): exclude the null check on the minimum buy row belowMinimum runs only inside the publish filter chain, after matchesMint read an enabled row for the same chat. The chain is synchronous, so the row is still there and the OptionalChaining mutant cannot be told apart. --- src/services/buy-alerts/publisher.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/src/services/buy-alerts/publisher.ts b/src/services/buy-alerts/publisher.ts index 8da9e1f9..fff7de3a 100644 --- a/src/services/buy-alerts/publisher.ts +++ b/src/services/buy-alerts/publisher.ts @@ -105,6 +105,7 @@ export function createBuyAlertPublisher(deps: BuyAlertPublisherDeps) { }; const belowMinimum = (chatId: number, solAmount: number | null): boolean => { + // Stryker disable next-line OptionalChaining: publish calls this only after matchesMint read an enabled row for this chat in the same synchronous filter chain, so the row is never null here. const minLamports = deps.chatDb.getChatBuyAlerts(chatId)?.min_sol_lamports ?? 0; if (minLamports <= 0) { return false; From 0ab700d74c1819263437af63be144caf033c7a61 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Mon, 30 Nov 2026 06:39:27 -0300 Subject: [PATCH 402/410] test(buy-alerts): cover a removed alert row and the exact lamport minimum A chat that is still in the enabled list but has no alert row any more is skipped without an error. This kills the OptionalChaining mutant on config?.enabled. A 0.1 SOL buy against a 100_000_000 lamport minimum is posted, because adding 1e-9 to 1e8 does not change the double. This kills the <= mutant of the dust check. --- tests/buy-alerts.publisher.test.ts | 42 ++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) diff --git a/tests/buy-alerts.publisher.test.ts b/tests/buy-alerts.publisher.test.ts index 9abb718e..6bb6db5d 100644 --- a/tests/buy-alerts.publisher.test.ts +++ b/tests/buy-alerts.publisher.test.ts @@ -430,6 +430,48 @@ test("publisher skips chats whose alerts were disabled after being listed", asyn expect(sent).toEqual([]); }); +test("publisher skips a listed chat whose alert settings are gone", async () => { + const chatDb = ChatDatabase.getInstance(); + chatDb.upsertChatBuyAlerts(-13, { enabled: true }); + const enabledSnapshot = chatDb.getEnabledChatBuyAlerts(); + + const sent: number[] = []; + const publisher = createBuyAlertPublisher({ + chatDb: { + getEnabledChatBuyAlerts: () => enabledSnapshot, + // The chat was removed after the list was read. + getChatBuyAlerts: () => null, + }, + tokenManager, + sendHtml: async (chatId) => { + sent.push(chatId); + }, + fetchPairStats: async () => null, + }); + + expect(await publisher.publish(event({ signature: "removed-race" }))).toEqual({ + posted: 0, + skipped: [], + }); + expect(sent).toEqual([]); +}); + +test("a buy that rounds to exactly the lamport minimum is posted", async () => { + const chatDb = ChatDatabase.getInstance(); + chatDb.upsertChatBuyAlerts(-1, { enabled: true, min_sol_lamports: 100_000_000 }); + const publisher = createBuyAlertPublisher({ + chatDb, + tokenManager, + fetchPairStats: async () => null, + sendHtml: async () => {}, + }); + // 0.1 SOL is 100_000_000 lamports, and adding 1e-9 does not change that double. + expect(await publisher.publish(event({ signature: "exact-tenth", solAmount: 0.1 }))).toEqual({ + posted: 1, + skipped: [], + }); +}); + test("allows the exact lamport minimum but rejects missing and non-finite SOL sizes", async () => { const chatDb = ChatDatabase.getInstance(); chatDb.upsertChatBuyAlerts(-1, { enabled: true, min_sol_lamports: 1 }); From b1d3d166834fe8698b5334659c5e2c16544e14b6 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Mon, 30 Nov 2026 06:40:03 -0300 Subject: [PATCH 403/410] refactor(fee-sweeper): reject a missing price timestamp with one finite check The price check used null for a missing timestamp and then tested timestamp === null || !Number.isFinite(timestamp). Number.isFinite(null) is false, so the null test was redundant and its ConditionalExpression mutant was equivalent. A missing timestamp is now NaN, and the finite check alone rejects it with the same reason. --- src/services/fee-sweeper.ts | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/services/fee-sweeper.ts b/src/services/fee-sweeper.ts index 7a686d82..136881c4 100644 --- a/src/services/fee-sweeper.ts +++ b/src/services/fee-sweeper.ts @@ -149,9 +149,10 @@ const validateSolPriceData = ( ? priceData.resolvedAt : typeof priceData?.timestamp === "number" ? priceData.timestamp - : null; + : Number.NaN; - if (timestamp === null || !Number.isFinite(timestamp)) { + // A missing timestamp is NaN here, so one finite check rejects it. + if (!Number.isFinite(timestamp)) { return { isValid: false, reason: "missing timestamp" }; } From 644aa71b33fa272f692cdbf6f6b8396ac38114a3 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Mon, 30 Nov 2026 06:40:03 -0300 Subject: [PATCH 404/410] test(fee-sweeper): check the claim log and kill the claimed-delta mutant The Stryker disable on the claimed-delta check hid a killable mutant: with < instead of >=, an outgoing delta (for example -7) is skipped and an incoming one is recorded. The existing "records only an outgoing delta" tests kill it, so the disable is removed. The > variant stays as a documented survivor, because referralDeltaFromTransaction returns null for a zero delta. The claim order test now checks the "Referral claim 2/4" and "4/4" log lines, which kills the StringLiteral and ArithmeticOperator mutants in that log. --- src/services/fee-sweeper.ts | 1 - tests/fee-sweeper.paths.test.ts | 3 +++ 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/src/services/fee-sweeper.ts b/src/services/fee-sweeper.ts index 136881c4..dee2e1ca 100644 --- a/src/services/fee-sweeper.ts +++ b/src/services/fee-sweeper.ts @@ -547,7 +547,6 @@ async function runReferralSweep( for (const tokenAccount of allTokenAccounts) { const address = tokenAccount.pubkey.toBase58(); const delta = referralDeltaFromTransaction(confirmed, address); - // Stryker disable next-line EqualityOperator: referralDeltaFromTransaction returns null for a zero delta, so >= and > match. if (!delta || delta.delta >= 0n) continue; TransactionHistory.getInstance().recordFinanceEvent({ eventId: `jupiter:${sig}:${address}:claimed`, diff --git a/tests/fee-sweeper.paths.test.ts b/tests/fee-sweeper.paths.test.ts index ebda3764..356737d0 100644 --- a/tests/fee-sweeper.paths.test.ts +++ b/tests/fee-sweeper.paths.test.ts @@ -523,6 +523,9 @@ describe("referral claims", () => { ), ).toBe(2); expect(s.sent.map((raw) => Array.from(raw))).toEqual([[8], [9]]); + // The log counts claims by their position in the provider list. + expect(logSpy).toHaveBeenCalledWith(" ✅ Referral claim 2/4: claim-1"); + expect(logSpy).toHaveBeenCalledWith(" ✅ Referral claim 4/4: claim-2"); expect(first.sign).toHaveBeenCalledTimes(1); expect(second.sign).toHaveBeenCalledTimes(1); }); From 40576f25a44bd99a5642e2b3c7e8d063beab5770 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Mon, 30 Nov 2026 06:41:04 -0300 Subject: [PATCH 405/410] refactor(finance-report): price a raw amount with one NaN-safe range check priceRawAmount rejected price === null, a non-finite price and a negative price before it multiplied. The null test and the finite test were both redundant, so their ConditionalExpression and LogicalOperator mutants were equivalent. A missing price now becomes NaN, and !(unitPrice >= 0) rejects NaN and every negative price, including -Infinity. A +Infinity price gives a value that is not finite (Infinity or NaN), which the existing last check turns into null. -0 still returns 0. Every mutant of the new lines is killed by the finance report tests. --- src/services/finance-report.ts | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/src/services/finance-report.ts b/src/services/finance-report.ts index 5c5eb5b4..50144f77 100644 --- a/src/services/finance-report.ts +++ b/src/services/finance-report.ts @@ -101,9 +101,12 @@ const priceRawAmount = ( decimals: number, price: number | null, ): number | null => { - if (price === null || !Number.isFinite(price) || price < 0) return null; - if (price === 0) return 0; - const value = (Number(rawAmount) / 10 ** decimals) * price; + // A missing price becomes NaN. NaN and negative prices fail this check. An infinite + // price gives a value that is not finite, which the last check turns into null. + const unitPrice = price ?? Number.NaN; + if (!(unitPrice >= 0)) return null; + if (unitPrice === 0) return 0; + const value = (Number(rawAmount) / 10 ** decimals) * unitPrice; return Number.isFinite(value) ? value : null; }; From ba557c5f5765f363827921ba1b14292e7eb7388a Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Mon, 30 Nov 2026 06:41:40 -0300 Subject: [PATCH 406/410] test(lightning): exclude two equivalent FixedFloat mutants - invoiceMatchesSats: the group ([munp]?) always takes part in a match, so match[2] is never undefined and the "" fallback is never used. - FixedFloatClient.requests: call() filters the list by r.at > now - 60_000 before it reads it. A placeholder [] has Array.prototype.at there, which compares false, so the new Array([]) mutant is dropped before any read. --- src/services/lightning/fixedfloat.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/services/lightning/fixedfloat.ts b/src/services/lightning/fixedfloat.ts index b71ab05d..c8f9e003 100644 --- a/src/services/lightning/fixedfloat.ts +++ b/src/services/lightning/fixedfloat.ts @@ -90,6 +90,7 @@ export function invoiceMatchesSats(invoice: string, sats: string): boolean { const match = invoice.toLowerCase().match(/^lnbc([1-9]\d*)([munp]?)1/); if (!match?.[1]) return false; const units = BigInt(match[1]); + // Stryker disable next-line StringLiteral: the group ([munp]?) always takes part in a match, so match[2] is always a string. const unit = match[2] ?? ""; const scale: Record = { "": 100_000_000_000n, @@ -104,6 +105,7 @@ export function invoiceMatchesSats(invoice: string, sats: string): boolean { } export class FixedFloatClient { + // Stryker disable next-line ArrayDeclaration: call() first keeps only entries whose at is later than a minute ago. A placeholder [] has Array.prototype.at there, which compares false, so it is dropped before it is read. private requests = new Array<{ at: number; weight: number }>(); constructor( private readonly config: { key: string; secret: string; refcode: string }, From aea0124ab44f869bb933c33700a564626657f76c Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Mon, 30 Nov 2026 06:42:52 -0300 Subject: [PATCH 407/410] test(lightning): reject sats strings with trailing junk satsToBtc("12x") and satsToBtc("1.2") must throw DepositInputError. This kills the Regex mutant that drops the $ anchor of the sats pattern in fixedfloat.ts. --- tests/lightning-deposits.test.ts | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/tests/lightning-deposits.test.ts b/tests/lightning-deposits.test.ts index 91d4ded3..d51e9263 100644 --- a/tests/lightning-deposits.test.ts +++ b/tests/lightning-deposits.test.ts @@ -1,6 +1,7 @@ import { describe, mock, spyOn, test, expect } from "bun:test"; import { createHmac } from "node:crypto"; import { + DepositInputError, FixedFloatClient, FixedFloatError, satsToBtc, @@ -38,6 +39,9 @@ describe("Lightning deposits", () => { expect(satsToBtc("2100000000000000")).toBe("21000000.00000000"); for (const invalid of ["0", "-1", "1.2", "1e8", " 1", "2100000000000001", "10000000000000000"]) expect(() => satsToBtc(invalid)).toThrow(); + // Trailing text is a user input error, not a BigInt parse failure. + for (const invalid of ["12x", "1.2"]) + expect(() => satsToBtc(invalid)).toThrow(DepositInputError); }); test("an existing quote avoids repeat provider calls and invalid sats never reach the provider", async () => { From dc8eb4d938ffe0258cd2acf476f30006077154b5 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Mon, 30 Nov 2026 06:44:40 -0300 Subject: [PATCH 408/410] refactor(positions): drop two null checks that no input can fail - buildTokenPositions: a missing SOL price now gives NaN, not null, so the marked USD cost is NaN and Number.isFinite rejects it. The old markedUsd !== null check had no effect, because Number.isFinite(null) is false. - resolvePositionWork: cacheFresh is now cached !== undefined && cached.expiresAt > now. TypeScript narrows cached through cacheFresh, so the later cached?. and "cacheFresh && cached" checks go away. Map values are objects, so the old Boolean() test gave the same result. --- src/services/positions.ts | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/src/services/positions.ts b/src/services/positions.ts index 4132fe95..68fe4588 100644 --- a/src/services/positions.ts +++ b/src/services/positions.ts @@ -424,18 +424,18 @@ export function buildTokenPositions(args: { const { qty, costSol, costUsdc, costUsdt, buyCount, sellCount } = lot; const costUsd = costUsdc + costUsdt; - // A USD average must include all costs. A missing SOL price is not zero cost. + // A USD average must include all costs. A missing SOL price is not zero cost: + // NaN marks it, so the marked cost is NaN and fails the finite check below. const solCostUsd = costSol > 0 ? solPriceUsd > 0 && Number.isFinite(solPriceUsd) ? costSol * solPriceUsd - : null + : Number.NaN : 0; - const markedUsd = solCostUsd === null ? null : costUsd + solCostUsd; + const markedUsd = costUsd + solCostUsd; const avgEntrySol = costSol > 0 ? costSol / qty : null; const priceUsd = args.pricesUsd[holding.mint] ?? 0; - const avgEntryUsd = - markedUsd !== null && Number.isFinite(markedUsd) && markedUsd > 0 ? markedUsd / qty : null; + const avgEntryUsd = Number.isFinite(markedUsd) && markedUsd > 0 ? markedUsd / qty : null; const pnlPercent = avgEntryUsd != null && avgEntryUsd > 0 && priceUsd > 0 ? (priceUsd - avgEntryUsd) / avgEntryUsd @@ -690,12 +690,12 @@ async function resolvePositionWork( const fillKnownMints = collectKnownMints(args.knownTokens, holdings); const cached = positionWorkCache.get(args.walletAddress); const now = Date.now(); - const cacheFresh = Boolean(cached && cached.expiresAt > now); + const cacheFresh = cached !== undefined && cached.expiresAt > now; // Reuse fills only when they were built from the same swaps and at least these mints. const reusable = cacheFresh && - cached?.swapFingerprint === swapFingerprint && + cached.swapFingerprint === swapFingerprint && !knownMintsGrew(cached.fillKnownMints, fillKnownMints) ? cached : undefined; @@ -708,8 +708,8 @@ async function resolvePositionWork( const neededPrices = collectPositionPriceMints(fills, holdings); - const pricesUsd = { ...(cacheFresh && cached ? cached.pricesUsd : {}) }; - const pricedMints = new Set(cacheFresh && cached ? cached.pricedMints : []); + const pricesUsd = { ...(cacheFresh ? cached.pricesUsd : {}) }; + const pricedMints = new Set(cacheFresh ? cached.pricedMints : []); const missingPrices = neededPrices.filter((mint) => !pricedMints.has(mint)); if (missingPrices.length > 0) { mergePricedMints( From 296d37269b03d0aa99d6dd14b0190774674c990b Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Mon, 30 Nov 2026 07:04:57 -0300 Subject: [PATCH 409/410] test: check the positive integer clamp warning and build an unfresh price set from null The changed-code job on dc8eb4d left two survivors that are not equivalent or need no mutant: removing the parsePositiveInteger clamp warning passed every test, and the empty list for an unfresh position cache could hold a placeholder. A test now expects the clamp warning, and the price set is built from null, which gives the same empty set as an empty list. --- src/services/positions.ts | 3 ++- tests/constants.dynamic.test.ts | 4 ++++ 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/src/services/positions.ts b/src/services/positions.ts index 68fe4588..a888dc4d 100644 --- a/src/services/positions.ts +++ b/src/services/positions.ts @@ -709,7 +709,8 @@ async function resolvePositionWork( const neededPrices = collectPositionPriceMints(fills, holdings); const pricesUsd = { ...(cacheFresh ? cached.pricesUsd : {}) }; - const pricedMints = new Set(cacheFresh ? cached.pricedMints : []); + // A Set built from null is empty, like one built from an empty list. + const pricedMints = new Set(cacheFresh ? cached.pricedMints : null); const missingPrices = neededPrices.filter((mint) => !pricedMints.has(mint)); if (missingPrices.length > 0) { mergePricedMints( diff --git a/tests/constants.dynamic.test.ts b/tests/constants.dynamic.test.ts index b66f2a9d..49790ebd 100644 --- a/tests/constants.dynamic.test.ts +++ b/tests/constants.dynamic.test.ts @@ -199,6 +199,10 @@ describe("environment number parsers", () => { expect(warn.mock.calls[0]?.[0]).toBe( `[Config] ${key} must be >= 0. Received -1, clamping to 0.`, ); + expect(parsePositiveInteger(key, 2.7)).toBe(2); + expect(warn.mock.calls[1]?.[0]).toBe( + `[Config] ${key} must be > 0. Received -1, clamping to 2.`, + ); } finally { delete process.env[key]; warn.mockRestore(); From aeae0028ee047e73f9995a76386bdb62137551e5 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Mon, 30 Nov 2026 07:47:42 -0300 Subject: [PATCH 410/410] refactor(tokens): drop the unused chat option of the game token check The check stopped reading the chat in f2250ee, so the options parameter had no reader. The two chat defaults tests that reach the expired-session reply now delete chatId from a typed copy of the session, with no cast. --- src/utils/token-manager.ts | 13 +++---------- tests/chat-defaults.handler.test.ts | 10 ++++++---- 2 files changed, 9 insertions(+), 14 deletions(-) diff --git a/src/utils/token-manager.ts b/src/utils/token-manager.ts index 4fa31956..0e99610f 100644 --- a/src/utils/token-manager.ts +++ b/src/utils/token-manager.ts @@ -120,12 +120,8 @@ export class TokenManager { return integer; } - private isTokenSupportedForGames( - tokenMint: string, - isSol?: boolean, - // A chat's default token gets no special support, so the chat is not read. - _options?: { chatId?: number }, - ): boolean { + // A chat's default token gets no special support, so the chat is not an input. + private isTokenSupportedForGames(tokenMint: string, isSol?: boolean): boolean { if (isSol) { return true; } @@ -447,10 +443,7 @@ export class TokenManager { } } - if ( - context === "game" && - !this.isTokenSupportedForGames(resolvedTokenMint, isSol, { chatId }) - ) { + if (context === "game" && !this.isTokenSupportedForGames(resolvedTokenMint, isSol)) { return { success: false, error: "unsupported_token", diff --git a/tests/chat-defaults.handler.test.ts b/tests/chat-defaults.handler.test.ts index af031012..64dc8ad4 100644 --- a/tests/chat-defaults.handler.test.ts +++ b/tests/chat-defaults.handler.test.ts @@ -1823,7 +1823,9 @@ describe("chat defaults menus and inputs", () => { expect(chatDb.getChatBuyAlerts(99)?.min_sol_lamports).toBe(250_000_000); expect(h.replies.at(-1)).toBe("✅ Min buy set to 0.25 SOL"); - await h.module.handleSettingsInput(h.ctxFor(), { ...session, chatId: undefined } as any, "1"); + const withoutChat = { ...session }; + delete withoutChat.chatId; + await h.module.handleSettingsInput(h.ctxFor(), withoutChat, "1"); expect(h.replies.at(-1)).toBe("❌ Session expired. Please try again."); }); @@ -1851,9 +1853,9 @@ describe("chat defaults menus and inputs", () => { expect(h.replies.at(-1)).toBe("✅ Rate limit set to disabled"); await h.module.handleSettingsInput(h.ctxFor(), session, "12"); expect(h.replies.at(-1)).toBe("✅ Rate limit set to 12/min"); - expect( - await h.module.handleSettingsInput(h.ctxFor(), { ...session, chatId: "x" } as any, "3"), - ).toBe(true); + const withoutChat = { ...session }; + delete withoutChat.chatId; + expect(await h.module.handleSettingsInput(h.ctxFor(), withoutChat, "3")).toBe(true); expect(h.replies.at(-1)).toBe("❌ Session expired. Please try again."); await h.press("chat_defaults_clear_join_notifications");