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