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
+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', () => {