Skip to content

Commit b6b460a

Browse files
Shawclaude
andcommitted
chore(cloud-shared): biome autoformat across crypto payments + RPC modules
Pure formatting — no behavior change. Targeted at: - direct-wallet-payments.ts (createPayment, verifyEvm*, processBroadcastBatch) - bnb-price-oracle.ts - evm-rpc.ts - direct-wallet-payments.integration.test.ts Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
1 parent 284cbd9 commit b6b460a

4 files changed

Lines changed: 41 additions & 84 deletions

File tree

packages/cloud-shared/src/lib/config/evm-rpc.ts

Lines changed: 1 addition & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -65,13 +65,7 @@ function builtinPublicRpc(network: EvmPayoutNetwork): string {
6565
*/
6666
export function resolveEvmRpc(network: EvmPayoutNetwork): {
6767
url: string;
68-
source:
69-
| "crypto_direct"
70-
| "explicit"
71-
| "x402"
72-
| "alchemy"
73-
| "infura"
74-
| "public_default";
68+
source: "crypto_direct" | "explicit" | "x402" | "alchemy" | "infura" | "public_default";
7569
} {
7670
const key = NETWORK_KEY[network];
7771

packages/cloud-shared/src/lib/services/__tests__/direct-wallet-payments.integration.test.ts

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -645,9 +645,7 @@ describe.skipIf(!process.env.DATABASE_URL || !pgliteAvailable)(
645645
await service.processBroadcastBatch(env);
646646
const row1 = await dbWrite.query.cryptoPayments.findFirst();
647647
expect(row1?.status).toBe("broadcast");
648-
const attempts1 = Number(
649-
(row1?.metadata as Record<string, unknown>).verify_attempts ?? 0,
650-
);
648+
const attempts1 = Number((row1?.metadata as Record<string, unknown>).verify_attempts ?? 0);
651649
expect(attempts1).toBeGreaterThanOrEqual(1);
652650

653651
// Jump straight to MAX-1 to keep the test fast, then one more pass should

packages/cloud-shared/src/lib/services/bnb-price-oracle.ts

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -88,9 +88,7 @@ async function fetchFromChainlink(): Promise<BnbPriceQuote> {
8888
`Chainlink BNB/USD price is stale (last update ${ageSeconds}s ago); refusing to quote`,
8989
);
9090
}
91-
const priceUsd = new Decimal(answer.toString()).div(
92-
new Decimal(10).pow(Number(decimals)),
93-
);
91+
const priceUsd = new Decimal(answer.toString()).div(new Decimal(10).pow(Number(decimals)));
9492
if (priceUsd.lessThan(50) || priceUsd.greaterThan(100_000)) {
9593
// Sanity bounds — BNB has never traded outside this range.
9694
throw new Error(`Chainlink BNB/USD price out of sanity bounds: ${priceUsd.toString()}`);
@@ -153,8 +151,7 @@ export async function getBnbUsdQuote(): Promise<BnbPriceQuote> {
153151
} catch (geckoError) {
154152
const chainlinkMsg =
155153
chainlinkError instanceof Error ? chainlinkError.message : String(chainlinkError);
156-
const geckoMsg =
157-
geckoError instanceof Error ? geckoError.message : String(geckoError);
154+
const geckoMsg = geckoError instanceof Error ? geckoError.message : String(geckoError);
158155
throw new Error(
159156
`BNB price oracle unavailable. Chainlink: ${chainlinkMsg}. CoinGecko: ${geckoMsg}.`,
160157
);

packages/cloud-shared/src/lib/services/direct-wallet-payments.ts

Lines changed: 37 additions & 69 deletions
Original file line numberDiff line numberDiff line change
@@ -128,8 +128,7 @@ const NATIVE_SLIPPAGE_BPS = 200;
128128
* `CRYPTO_DIRECT_QUOTE_SIGNING_KEY` explicitly. The helper logs loudly if
129129
* the fallback is used.
130130
*/
131-
const DEV_FALLBACK_QUOTE_SIGNING_KEY =
132-
"dev-only-quote-signing-key-do-not-use-in-production";
131+
const DEV_FALLBACK_QUOTE_SIGNING_KEY = "dev-only-quote-signing-key-do-not-use-in-production";
133132

134133
function isProductionEnv(env: Bindings): boolean {
135134
const node = String(env.NODE_ENV ?? "").toLowerCase();
@@ -239,16 +238,13 @@ function buildExplorerUrl(
239238

240239
function resolveBscToken(symbol: string | undefined): DirectWalletTokenOption {
241240
if (!symbol) return BSC_TOKEN_OPTIONS[1]; // default USDT
242-
const match = BSC_TOKEN_OPTIONS.find(
243-
(t) => t.symbol.toUpperCase() === symbol.toUpperCase(),
244-
);
241+
const match = BSC_TOKEN_OPTIONS.find((t) => t.symbol.toUpperCase() === symbol.toUpperCase());
245242
if (!match) {
246243
throw new Error(`Unsupported BSC token: ${symbol}`);
247244
}
248245
return match;
249246
}
250247

251-
252248
function envString(env: Bindings, key: string): string | null {
253249
const value = env[key];
254250
return typeof value === "string" && value.trim() ? value.trim() : null;
@@ -312,9 +308,7 @@ function directPaymentConfig(
312308
const usdtOverride = envString(env, "CRYPTO_DIRECT_BSC_TOKEN_ADDRESS");
313309
const tokens: DirectWalletTokenOption[] = usdtOverride
314310
? BSC_TOKEN_OPTIONS.map((t) =>
315-
t.symbol === "USDT"
316-
? { ...t, tokenAddress: getAddress(usdtOverride) }
317-
: t,
311+
t.symbol === "USDT" ? { ...t, tokenAddress: getAddress(usdtOverride) } : t,
318312
)
319313
: BSC_TOKEN_OPTIONS;
320314
const defaultToken = tokens.find((t) => t.symbol === "USDT") ?? tokens[0];
@@ -496,8 +490,7 @@ function directMetadata(payment: CryptoPayment): {
496490
typeof rawTokenAddress === "string" && rawTokenAddress.startsWith("0x")
497491
? (rawTokenAddress as Hex)
498492
: null,
499-
tokenMint:
500-
typeof metadata.token_mint === "string" ? metadata.token_mint : null,
493+
tokenMint: typeof metadata.token_mint === "string" ? metadata.token_mint : null,
501494
tokenDecimals: Number(metadata.token_decimals ?? 0),
502495
expectedTokenUnits: BigInt(String(metadata.expected_token_units ?? "0")),
503496
bonusCredits: Number(metadata.bonus_credits ?? 0),
@@ -589,10 +582,7 @@ async function verifyEvmNativePayment(params: {
589582
// BNB. (For tokens, the Transfer-event check enforces sender identity
590583
// separately.)
591584
const tx = await client.getTransaction({ hash: params.txHash as Hex });
592-
if (
593-
!tx.to ||
594-
tx.to.toLowerCase() !== normalizeEvmAddress(params.cfg.receiveAddress)
595-
) {
585+
if (!tx.to || tx.to.toLowerCase() !== normalizeEvmAddress(params.cfg.receiveAddress)) {
596586
throw new Error("Transaction recipient does not match the receive address");
597587
}
598588
// Apply slippage tolerance to BOTH floor and ceiling for native-token
@@ -672,9 +662,7 @@ async function verifySolanaTokenPayment(params: {
672662
ata: receiverAta.toBase58(),
673663
mint,
674664
});
675-
throw new Error(
676-
"Receiving ATA owner does not match configured treasury wallet",
677-
);
665+
throw new Error("Receiving ATA owner does not match configured treasury wallet");
678666
}
679667

680668
const before = new Map<string, bigint>();
@@ -823,9 +811,7 @@ export class DirectWalletPaymentsService {
823811
// Resolve which token on the network this purchase is using. Networks
824812
// with a single token (Base USDC, Solana USDC) ignore the param.
825813
const selectedToken: DirectWalletTokenOption =
826-
params.network === "bsc"
827-
? resolveBscToken(params.tokenSymbol)
828-
: cfg.tokens[0];
814+
params.network === "bsc" ? resolveBscToken(params.tokenSymbol) : cfg.tokens[0];
829815

830816
const amount = new Decimal(params.amountUsd);
831817
const validation = validatePaymentAmount(amount);
@@ -926,36 +912,35 @@ export class DirectWalletPaymentsService {
926912
// Slippage tolerance for the on-chain verify step. Only meaningful
927913
// when paying with a non-stable native token whose price moves
928914
// between quote and broadcast. Stables ignore this.
929-
slippage_bps:
930-
selectedToken.kind === "native" ? NATIVE_SLIPPAGE_BPS : 0,
915+
slippage_bps: selectedToken.kind === "native" ? NATIVE_SLIPPAGE_BPS : 0,
931916
},
932917
})
933918
.returning();
934919
if (!created) throw new Error("Failed to create direct crypto payment");
935920
return created;
936921
});
937922

938-
const { signature: quoteSignature, canonicalInput: quoteCanonicalInput } =
939-
await signQuote(env, {
923+
const { signature: quoteSignature, canonicalInput: quoteCanonicalInput } = await signQuote(
924+
env,
925+
{
940926
paymentId: payment.id,
941927
expectedTokenUnits,
942928
receiveAddress: cfg.receiveAddress ?? "",
943929
chainId: cfg.chainId ?? null,
944930
tokenAddress: selectedToken.tokenAddress ?? null,
945931
tokenMint: selectedToken.tokenMint ?? null,
946932
expiresAt: payment.expires_at,
947-
});
933+
},
934+
);
948935

949936
// Persist the signature and canonical input for audit + later verification.
950937
await dbWrite
951938
.update(cryptoPayments)
952939
.set({
953-
metadata: sql`COALESCE(${cryptoPayments.metadata}, '{}'::jsonb) || ${JSON.stringify(
954-
{
955-
quote_signature: quoteSignature,
956-
quote_canonical_input: quoteCanonicalInput,
957-
},
958-
)}::jsonb`,
940+
metadata: sql`COALESCE(${cryptoPayments.metadata}, '{}'::jsonb) || ${JSON.stringify({
941+
quote_signature: quoteSignature,
942+
quote_canonical_input: quoteCanonicalInput,
943+
})}::jsonb`,
959944
updated_at: new Date(),
960945
})
961946
.where(eq(cryptoPayments.id, payment.id));
@@ -993,9 +978,7 @@ export class DirectWalletPaymentsService {
993978
* Idempotent: a second call with the same hash is a no-op. A different
994979
* hash on an already-attached payment errors.
995980
*/
996-
async attachTransaction(
997-
params: { paymentId: string; txHash: string; userId: string },
998-
): Promise<{
981+
async attachTransaction(params: { paymentId: string; txHash: string; userId: string }): Promise<{
999982
payment: CryptoPayment;
1000983
alreadyAttached: boolean;
1001984
}> {
@@ -1018,9 +1001,7 @@ export class DirectWalletPaymentsService {
10181001
return { payment, alreadyAttached: true };
10191002
}
10201003
if (payment.transaction_hash && payment.transaction_hash !== params.txHash) {
1021-
throw new Error(
1022-
"Payment already has a different transaction hash attached",
1023-
);
1004+
throw new Error("Payment already has a different transaction hash attached");
10241005
}
10251006
if (payment.status !== "pending") {
10261007
throw new Error(`Cannot attach tx to payment in status ${payment.status}`);
@@ -1055,9 +1036,7 @@ export class DirectWalletPaymentsService {
10551036
* the UI needs to render a "waiting for confirmation" screen without
10561037
* leaking unrelated metadata.
10571038
*/
1058-
async getPaymentStatusForUser(
1059-
params: { paymentId: string; userId: string },
1060-
): Promise<{
1039+
async getPaymentStatusForUser(params: { paymentId: string; userId: string }): Promise<{
10611040
paymentId: string;
10621041
status: string;
10631042
network: DirectWalletNetwork | null;
@@ -1084,12 +1063,9 @@ export class DirectWalletPaymentsService {
10841063
const metadata = metadataOf(payment);
10851064
const rawNetwork = metadata.direct_network;
10861065
const network: DirectWalletNetwork | null =
1087-
rawNetwork === "base" || rawNetwork === "bsc" || rawNetwork === "solana"
1088-
? rawNetwork
1089-
: null;
1066+
rawNetwork === "base" || rawNetwork === "bsc" || rawNetwork === "solana" ? rawNetwork : null;
10901067
const explorerUrl = buildExplorerUrl(network, payment.transaction_hash);
1091-
const errorValue =
1092-
typeof metadata.failure_reason === "string" ? metadata.failure_reason : null;
1068+
const errorValue = typeof metadata.failure_reason === "string" ? metadata.failure_reason : null;
10931069

10941070
return {
10951071
paymentId: payment.id,
@@ -1389,35 +1365,29 @@ export class DirectWalletPaymentsService {
13891365
// Anything else (wrong recipient, low value, reverted) is terminal
13901366
// — record it so the user sees a clear failure.
13911367
const transient =
1392-
/not found|not yet|pending|TransactionReceiptNotFoundError|could not be found/i.test(
1393-
msg,
1394-
);
1368+
/not found|not yet|pending|TransactionReceiptNotFoundError|could not be found/i.test(msg);
13951369

13961370
const attempts =
1397-
Number(
1398-
(metadataOf(payment) as Record<string, unknown>).verify_attempts ?? 0,
1399-
) + 1;
1371+
Number((metadataOf(payment) as Record<string, unknown>).verify_attempts ?? 0) + 1;
14001372

14011373
if (transient && attempts < MAX_VERIFY_ATTEMPTS) {
14021374
stats.stillPending += 1;
14031375
await dbWrite
14041376
.update(cryptoPayments)
14051377
.set({
14061378
updated_at: new Date(),
1407-
metadata: sql`COALESCE(${cryptoPayments.metadata}, '{}'::jsonb) || ${JSON.stringify(
1408-
{
1409-
verify_attempts: attempts,
1410-
last_verify_error: msg,
1411-
last_verify_at: new Date().toISOString(),
1412-
},
1413-
)}::jsonb`,
1379+
metadata: sql`COALESCE(${cryptoPayments.metadata}, '{}'::jsonb) || ${JSON.stringify({
1380+
verify_attempts: attempts,
1381+
last_verify_error: msg,
1382+
last_verify_at: new Date().toISOString(),
1383+
})}::jsonb`,
14141384
})
14151385
.where(eq(cryptoPayments.id, payment.id))
14161386
.catch((e) => {
1417-
logger.warn(
1418-
"[DirectWalletPayments] failed to bump verify_attempts",
1419-
{ paymentId: redact.paymentId(payment.id), error: String(e) },
1420-
);
1387+
logger.warn("[DirectWalletPayments] failed to bump verify_attempts", {
1388+
paymentId: redact.paymentId(payment.id),
1389+
error: String(e),
1390+
});
14211391
});
14221392
continue;
14231393
}
@@ -1435,12 +1405,10 @@ export class DirectWalletPaymentsService {
14351405
.set({
14361406
status: "failed_chain",
14371407
updated_at: new Date(),
1438-
metadata: sql`COALESCE(${cryptoPayments.metadata}, '{}'::jsonb) || ${JSON.stringify(
1439-
{
1440-
failure_reason: msg,
1441-
failed_at: new Date().toISOString(),
1442-
},
1443-
)}::jsonb`,
1408+
metadata: sql`COALESCE(${cryptoPayments.metadata}, '{}'::jsonb) || ${JSON.stringify({
1409+
failure_reason: msg,
1410+
failed_at: new Date().toISOString(),
1411+
})}::jsonb`,
14441412
})
14451413
.where(eq(cryptoPayments.id, payment.id));
14461414
logger.warn("[DirectWalletPayments] Marked payment failed_chain", {

0 commit comments

Comments
 (0)