feat(ads): rewarded video (VK) — client-attested credit + daily/hourly caps
CI / changes (pull_request) Successful in 4s
CI / unit (pull_request) Successful in 10s
CI / integration (pull_request) Successful in 26s
CI / ui (pull_request) Successful in 1m11s
CI / conformance (pull_request) Successful in 10s
CI / gate (pull_request) Successful in 0s
CI / deploy (pull_request) Successful in 1m53s

The first ads slice: a voluntary rewarded video credits chips. VK Mini App ads
(VKWebAppShowNativeAds) expose only a client-side watch result — no
server-to-server verify — so the credit is client-attested, guarded by a server
daily + hourly cap (config reward_daily_cap / reward_hourly_cap, default 50 / 10).
The caps are both anti-abuse (bounding a forger who skips the ad and calls the
endpoint directly) and an economic conversion lever (limiting free chips so a
player who wants more buys). D29 amended to VK's reality.

Backend: CreditReward (VK-only, order-less, idempotent on a client nonce, floored
by the caps; payout from config rewarded_payout_chips, default 0 = off) + the
wallet.reward edge op returning the updated wallet (reward_chips gates the
"watch for chips" CTA). Additive migration (two config columns).

Client: the ads-network abstraction (lib/ads.ts, VK impl) + the VK bridge
(vkRewardedReady / vkShowRewarded) + the Wallet CTA + i18n. A contour test stub
(VITE_ADS_STUB -> a toast instead of a real ad; prod always real) and a temporary
diagnostic that logs the raw VK data, so we confirm on the contour exactly what
VK returns (harden to signature-verify if it carries one).

Tests: backend integration (credit, nonce idempotency, hourly cap, disabled,
non-VK refusal) + codec unit (reward wire). Docs: PAYMENTS(+ru) §10, D29 amend,
PLAN E6. Bundle: shared budget 30->31 (reward i18n strings).
This commit is contained in:
Ilia Denisov
2026-07-10 00:41:42 +02:00
parent 68c937f3b6
commit dbd76d53e8
38 changed files with 798 additions and 24 deletions
+1
View File
@@ -88,6 +88,7 @@ export { Wallet } from './scrabblefb/wallet.js';
export { WalletBuyRequest } from './scrabblefb/wallet-buy-request.js';
export { WalletOrderRequest } from './scrabblefb/wallet-order-request.js';
export { WalletOrderResponse } from './scrabblefb/wallet-order-response.js';
export { WalletRewardRequest } from './scrabblefb/wallet-reward-request.js';
export { WalletSegment } from './scrabblefb/wallet-segment.js';
export { WordCheckResult } from './scrabblefb/word-check-result.js';
export { YourTurnEvent } from './scrabblefb/your-turn-event.js';
@@ -0,0 +1,60 @@
// automatically generated by the FlatBuffers compiler, do not modify
import * as flatbuffers from 'flatbuffers';
export class WalletRewardRequest {
bb: flatbuffers.ByteBuffer|null = null;
bb_pos = 0;
__init(i:number, bb:flatbuffers.ByteBuffer):WalletRewardRequest {
this.bb_pos = i;
this.bb = bb;
return this;
}
static getRootAsWalletRewardRequest(bb:flatbuffers.ByteBuffer, obj?:WalletRewardRequest):WalletRewardRequest {
return (obj || new WalletRewardRequest()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
}
static getSizePrefixedRootAsWalletRewardRequest(bb:flatbuffers.ByteBuffer, obj?:WalletRewardRequest):WalletRewardRequest {
bb.setPosition(bb.position() + flatbuffers.SIZE_PREFIX_LENGTH);
return (obj || new WalletRewardRequest()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
}
nonce():string|null
nonce(optionalEncoding:flatbuffers.Encoding):string|Uint8Array|null
nonce(optionalEncoding?:any):string|Uint8Array|null {
const offset = this.bb!.__offset(this.bb_pos, 4);
return offset ? this.bb!.__string(this.bb_pos + offset, optionalEncoding) : null;
}
diag():string|null
diag(optionalEncoding:flatbuffers.Encoding):string|Uint8Array|null
diag(optionalEncoding?:any):string|Uint8Array|null {
const offset = this.bb!.__offset(this.bb_pos, 6);
return offset ? this.bb!.__string(this.bb_pos + offset, optionalEncoding) : null;
}
static startWalletRewardRequest(builder:flatbuffers.Builder) {
builder.startObject(2);
}
static addNonce(builder:flatbuffers.Builder, nonceOffset:flatbuffers.Offset) {
builder.addFieldOffset(0, nonceOffset, 0);
}
static addDiag(builder:flatbuffers.Builder, diagOffset:flatbuffers.Offset) {
builder.addFieldOffset(1, diagOffset, 0);
}
static endWalletRewardRequest(builder:flatbuffers.Builder):flatbuffers.Offset {
const offset = builder.endObject();
return offset;
}
static createWalletRewardRequest(builder:flatbuffers.Builder, nonceOffset:flatbuffers.Offset, diagOffset:flatbuffers.Offset):flatbuffers.Offset {
WalletRewardRequest.startWalletRewardRequest(builder);
WalletRewardRequest.addNonce(builder, nonceOffset);
WalletRewardRequest.addDiag(builder, diagOffset);
return WalletRewardRequest.endWalletRewardRequest(builder);
}
}
+12 -2
View File
@@ -48,8 +48,13 @@ hints():number {
return offset ? this.bb!.readInt32(this.bb_pos + offset) : 0;
}
rewardChips():number {
const offset = this.bb!.__offset(this.bb_pos, 12);
return offset ? this.bb!.readInt32(this.bb_pos + offset) : 0;
}
static startWallet(builder:flatbuffers.Builder) {
builder.startObject(4);
builder.startObject(5);
}
static addSegments(builder:flatbuffers.Builder, segmentsOffset:flatbuffers.Offset) {
@@ -80,17 +85,22 @@ static addHints(builder:flatbuffers.Builder, hints:number) {
builder.addFieldInt32(3, hints, 0);
}
static addRewardChips(builder:flatbuffers.Builder, rewardChips:number) {
builder.addFieldInt32(4, rewardChips, 0);
}
static endWallet(builder:flatbuffers.Builder):flatbuffers.Offset {
const offset = builder.endObject();
return offset;
}
static createWallet(builder:flatbuffers.Builder, segmentsOffset:flatbuffers.Offset, adsForever:boolean, adsPaidUntilMs:bigint, hints:number):flatbuffers.Offset {
static createWallet(builder:flatbuffers.Builder, segmentsOffset:flatbuffers.Offset, adsForever:boolean, adsPaidUntilMs:bigint, hints:number, rewardChips:number):flatbuffers.Offset {
Wallet.startWallet(builder);
Wallet.addSegments(builder, segmentsOffset);
Wallet.addAdsForever(builder, adsForever);
Wallet.addAdsPaidUntilMs(builder, adsPaidUntilMs);
Wallet.addHints(builder, hints);
Wallet.addRewardChips(builder, rewardChips);
return Wallet.endWallet(builder);
}
}
+51
View File
@@ -0,0 +1,51 @@
// The ads-network abstraction (D28). VK is the only network now; a future network for another
// platform implements the same rewardedReady/showRewarded surface without touching the callers. On
// the contour a build flag (VITE_ADS_STUB) substitutes a toast stub for the real ad, so the reward
// flow is testable without waiting for a real ad — production never sets the flag, so a real ad that
// fails to load there must not credit (no stub fallback in prod).
import { executionContext } from './wallet';
import { vkRewardedReady, vkShowRewarded } from './vk';
/**
* adsStubEnabled reports the contour test stub (VITE_ADS_STUB=1). Production never sets it, so it
* always shows real ads. The mock e2e forces it on so the reward flow is exercisable without a VK
* bridge. To capture the real VK ad result on the contour (the diagnostic), deploy with the flag
* off first; flip it on afterwards for routine stub testing.
*/
export function adsStubEnabled(): boolean {
if (import.meta.env.MODE === 'mock') return true;
return (import.meta.env as Record<string, string | undefined>).VITE_ADS_STUB === '1';
}
/** RewardedResult is one rewarded-ad view: whether it was watched, the raw provider result as JSON
* (forwarded for the contour diagnostic), and whether it was the test stub (so the caller can show
* the "ad fired" marker toast). */
export interface RewardedResult {
watched: boolean;
data: string;
stub: boolean;
}
/**
* rewardedReady reports whether a rewarded ad is ready to show, gating the "watch for chips" button.
* The stub is always ready; a real ad is ready only inside VK with preloaded material. Rewarded is
* VK-only (D28).
*/
export async function rewardedReady(): Promise<boolean> {
if (adsStubEnabled()) return true;
if (executionContext() !== 'vk') return false;
return vkRewardedReady();
}
/**
* showRewarded shows a rewarded ad and reports whether it was watched, the raw provider result, and
* whether it was the stub. On the stub it resolves watched immediately (the caller shows the "ad
* fired" toast).
*/
export async function showRewarded(): Promise<RewardedResult> {
if (adsStubEnabled()) {
return { watched: true, data: JSON.stringify({ stub: true }), stub: true };
}
const r = await vkShowRewarded();
return { watched: r.watched, data: r.data, stub: false };
}
+4
View File
@@ -151,6 +151,10 @@ export interface GatewayClient {
/** walletOrder opens a money order to fund a chip pack and returns the provider launch URL the
* client opens; chips are credited later, by the verified server callback. Direct rail only. */
walletOrder(productId: string): Promise<WalletOrder>;
/** walletReward credits a watched rewarded video (VK ads) and returns the updated wallet. nonce is
* the per-view idempotency key; diag carries the raw VK ad result for the contour diagnostic.
* Client-attested + a server daily/hourly cap; a reached cap rejects with a domain code. */
walletReward(nonce: string, diag: string): Promise<Wallet>;
// --- friends ---
friendsList(): Promise<AccountRef[]>;
+11
View File
@@ -15,6 +15,7 @@ import {
decodeOutgoingList,
decodeProfile,
decodeWallet,
encodeWalletReward,
decodeCatalog,
encodeWalletBuy,
encodeWalletOrder,
@@ -66,6 +67,7 @@ describe('codec', () => {
fb.Wallet.addAdsForever(b, false);
fb.Wallet.addAdsPaidUntilMs(b, BigInt(1_700_000_000_000));
fb.Wallet.addHints(b, 5);
fb.Wallet.addRewardChips(b, 7);
b.finish(fb.Wallet.endWallet(b));
const w = decodeWallet(b.asUint8Array());
@@ -73,6 +75,15 @@ describe('codec', () => {
expect(w.adsForever).toBe(false);
expect(w.adsPaidUntilMs).toBe(1_700_000_000_000);
expect(w.hints).toBe(5);
expect(w.rewardChips).toBe(7);
});
it('round-trips the wallet reward request (nonce + diag)', () => {
const req = fb.WalletRewardRequest.getRootAsWalletRewardRequest(
new ByteBuffer(encodeWalletReward('nonce-9', '{"result":true}')),
);
expect(req.nonce()).toBe('nonce-9');
expect(req.diag()).toBe('{"result":true}');
});
it('round-trips the wallet order request and response', () => {
+13
View File
@@ -398,9 +398,22 @@ export function decodeWallet(buf: Uint8Array): Wallet {
adsForever: w.adsForever(),
adsPaidUntilMs: Number(w.adsPaidUntilMs()),
hints: w.hints(),
rewardChips: w.rewardChips(),
};
}
// encodeWalletReward wraps a watched rewarded video for crediting (POST /user/wallet/reward): the
// per-view idempotency nonce and the raw VK ad result forwarded for the contour diagnostic.
export function encodeWalletReward(nonce: string, diag: string): Uint8Array {
const b = new Builder(64);
const n = b.createString(nonce);
const d = b.createString(diag);
fb.WalletRewardRequest.startWalletRewardRequest(b);
fb.WalletRewardRequest.addNonce(b, n);
fb.WalletRewardRequest.addDiag(b, d);
return finish(b, fb.WalletRewardRequest.endWalletRewardRequest(b));
}
// decodeWalletOrder reads the created order: its id and the provider launch URL the client opens.
export function decodeWalletOrder(buf: Uint8Array): WalletOrder {
const o = fb.WalletOrderResponse.getRootAsWalletOrderResponse(new ByteBuffer(buf));
+5
View File
@@ -242,6 +242,11 @@ export const en = {
'wallet.store': 'Store',
'wallet.empty': 'The store is empty for now',
'wallet.buy': 'Buy',
'wallet.rewardWatch': 'Watch an ad for {n} 🪙',
'wallet.rewardCta': 'Watch',
'wallet.rewardCredited': '+{n} 🪙 for watching',
'wallet.rewardCapped': "You've reached today's reward limit",
'wallet.rewardFailed': 'The ad could not be shown',
'wallet.offer': 'Public offer',
'wallet.platformNoBuy': 'Purchases are not available on this platform',
'wallet.iosBlockedPre': 'Purchases on iOS are prohibited by Apple policy. Try the ',
+5
View File
@@ -242,6 +242,11 @@ export const ru: Record<MessageKey, string> = {
'wallet.store': 'Магазин',
'wallet.empty': 'Магазин пока пуст',
'wallet.buy': 'Купить',
'wallet.rewardWatch': 'Ролик за {n} 🪙',
'wallet.rewardCta': 'Смотреть',
'wallet.rewardCredited': '+{n} 🪙 за просмотр',
'wallet.rewardCapped': 'Достигнут дневной лимит наград',
'wallet.rewardFailed': 'Не удалось показать ролик',
'wallet.offer': 'Публичная оферта',
'wallet.platformNoBuy': 'На данной платформе покупки невозможны',
'wallet.iosBlockedPre': 'Покупки на iOS запрещены политикой Apple. Попробуйте воспользоваться ',
+9
View File
@@ -126,6 +126,7 @@ export class MockGateway implements GatewayClient {
adsForever: false,
adsPaidUntilMs: 0,
hints: 5,
rewardChips: 5,
};
// The mock storefront: two chip-priced values (one cheap enough to draw direct only, one that
// reaches into vk → the warning) and one RUB-priced chip pack (the direct-context method).
@@ -234,12 +235,20 @@ export class MockGateway implements GatewayClient {
// the provider hand-off without leaving the app.
return { orderId: 'mock-order-' + productId, redirectUrl: 'https://mock.local/robokassa?order=' + productId };
}
async walletReward(_nonce: string, _diag: string): Promise<Wallet> {
// Mock rewarded credit: add the configured payout to the vk segment (no cap in the mock).
const vk = this.mockWallet.segments.find((s) => s.source === 'vk');
if (vk) vk.chips += this.mockWallet.rewardChips;
return this.cloneWallet();
}
private cloneWallet(): Wallet {
return {
segments: this.mockWallet.segments.map((s) => ({ ...s })),
adsForever: this.mockWallet.adsForever,
adsPaidUntilMs: this.mockWallet.adsPaidUntilMs,
hints: this.mockWallet.hints,
rewardChips: this.mockWallet.rewardChips,
};
}
async fetchDict(variant: Variant, _version: string, opts?: { signal?: AbortSignal; reload?: boolean }): Promise<ArrayBuffer> {
+3
View File
@@ -168,6 +168,9 @@ export interface Wallet {
/** No-ads term end as unix milliseconds; 0 = no active term. */
adsPaidUntilMs: number;
hints: number;
/** Chips a rewarded-video view earns in the current context; 0 = unavailable here (outside VK or
* unconfigured). The client shows the "watch for chips" button only when this is positive. */
rewardChips: number;
}
/** One atom line of a storefront product: the base value type it grants ("chips"/"hints"/
+3
View File
@@ -240,6 +240,9 @@ export function createTransport(baseUrl: string): GatewayClient {
async walletOrder(productId: string) {
return codec.decodeWalletOrder(await exec('wallet.order', codec.encodeWalletOrder(productId)));
},
async walletReward(nonce: string, diag: string) {
return codec.decodeWallet(await exec('wallet.reward', codec.encodeWalletReward(nonce, diag)));
},
async friendsList() {
return codec.decodeFriendList(await exec('friends.list', codec.empty()));
+29
View File
@@ -197,6 +197,35 @@ export async function vkShowOrderBox(item: string): Promise<boolean> {
}
}
/**
* vkRewardedReady reports whether a rewarded ad is preloaded and ready to show
* (VKWebAppCheckNativeAds, required before a rewarded view). A false — or an unavailable method —
* hides the "watch for chips" button, since tapping it would show nothing.
*/
export async function vkRewardedReady(): Promise<boolean> {
try {
const data = await (await bridge()).send('VKWebAppCheckNativeAds', { ad_format: 'reward' });
return !!(data as { result?: boolean }).result;
} catch {
return false;
}
}
/**
* vkShowRewarded shows a rewarded ad (VKWebAppShowNativeAds) and reports whether it was watched
* (data.result) plus the full raw provider result as JSON — forwarded to the backend for the
* temporary contour diagnostic (to confirm exactly what VK returns). A rejected call reports
* not-watched with the error captured.
*/
export async function vkShowRewarded(): Promise<{ watched: boolean; data: string }> {
try {
const data = await (await bridge()).send('VKWebAppShowNativeAds', { ad_format: 'reward' });
return { watched: !!(data as { result?: boolean }).result, data: JSON.stringify(data) };
} catch (e) {
return { watched: false, data: JSON.stringify({ error: String(e) }) };
}
}
/**
* vkDownloadFile downloads url as filename through the VK client (VKWebAppDownloadFile) —
* the mobile in-app file delivery, where the webview ignores <a download>. Resolves false
+1 -1
View File
@@ -7,7 +7,7 @@ function seg(source: string, chips: number, spendable = true): WalletSegment {
}
function wallet(segments: WalletSegment[]): Wallet {
return { segments, adsForever: false, adsPaidUntilMs: 0, hints: 0 };
return { segments, adsForever: false, adsPaidUntilMs: 0, hints: 0, rewardChips: 0 };
}
describe('money formatting', () => {
+48
View File
@@ -10,6 +10,8 @@
import { onExternalLinkClick, openExternalUrl } from '../lib/links';
import { vkPlatform, vkShowOrderBox } from '../lib/vk';
import { telegramOpenInvoice } from '../lib/telegram';
import { rewardedReady, showRewarded } from '../lib/ads';
import { GatewayError } from '../lib/client';
import type { Wallet, Catalog, CatalogProduct } from '../lib/model';
// The Wallet section: the context-visible chip balances, the active benefits, and the storefront.
@@ -41,6 +43,41 @@
const values = $derived(catalog?.products.filter((p) => p.kind === 'value') ?? []);
const packs = $derived(catalog?.products.filter((p) => p.kind === 'pack') ?? []);
// Rewarded video (VK ads): the "watch for chips" CTA shows only when the server offers a payout in
// this context (wallet.rewardChips > 0 — VK, configured) and an ad is ready to show.
let rewardReady = $state(false);
const canReward = $derived(!!wallet && wallet.rewardChips > 0 && rewardReady);
// onWatchAd shows a rewarded ad and, if watched, credits the payout server-side (client-attested +
// a server daily/hourly cap). A stub view (contour test) shows an "ad fired" marker; a reached cap
// is surfaced as its own toast, distinct from a generic error.
async function onWatchAd() {
if (busy) return;
busyId = 'reward';
try {
const res = await showRewarded();
if (res.stub) showToast('ad fired');
if (!res.watched) {
showToast(t('wallet.rewardFailed'));
return;
}
const nonce = crypto.randomUUID();
const before = wallet?.segments.find((s) => s.source === 'vk')?.chips ?? 0;
const w = await gateway.walletReward(nonce, res.data);
wallet = w;
const gained = (w.segments.find((s) => s.source === 'vk')?.chips ?? 0) - before;
showToast(gained > 0 ? t('wallet.rewardCredited', { n: gained }) : t('wallet.rewardCredited', { n: w.rewardChips }));
} catch (e) {
if (e instanceof GatewayError && e.code === 'reward_capped') {
showToast(t('wallet.rewardCapped'));
} else {
handleError(e);
}
} finally {
busyId = null;
}
}
async function load() {
try {
const [w, c] = await Promise.all([gateway.wallet(), gateway.catalog()]);
@@ -54,6 +91,9 @@
}
onMount(() => {
void load();
// Probe rewarded-ad readiness once so the "watch for chips" button only shows when a view would
// actually play.
void rewardedReady().then((r) => (rewardReady = r));
// Fallback to the payment push: re-fetch when the tab regains focus, i.e. the user returned
// from the provider's payment window.
const onVisible = () => {
@@ -171,6 +211,14 @@
<!-- prettier-ignore -->
<p class="ios-note" data-testid="ios-note">{t('wallet.iosBlockedPre')}<a href={siteRoot} target="_blank" rel="noopener noreferrer" onclick={onExternalLinkClick}>{t('wallet.iosBlockedLink')}</a>{t('wallet.iosBlockedPost')}</p>
{/if}
{#if canReward}
<div class="row reward" data-testid="reward-row">
<span class="name">{t('wallet.rewardWatch', { n: wallet?.rewardChips ?? 0 })}</span>
<button class="buy" class:working={busyId === 'reward'} data-testid="watch-ad" disabled={busy} onclick={onWatchAd}
>{t('wallet.rewardCta')}</button
>
</div>
{/if}
{#each values as p (p.productId)}
<div class="row product" data-testid="product" data-kind="value" data-pid={p.productId}>
<span class="name">{p.title}</span>