After changing about commission dispatch and adding sharing card2
This commit is contained in:
parent
8fbf1bc41a
commit
facf920825
@ -29,6 +29,19 @@ export async function getBetShareCard(req: AuthRequest, res: Response): Promise<
|
||||
}
|
||||
}
|
||||
|
||||
export async function getTransactionShareCard(req: AuthRequest, res: Response): Promise<void> {
|
||||
try {
|
||||
const transactionId = String(req.params.transactionId || '');
|
||||
const payload = await shareCardService.getWalletOpSharePayloadForOwner(
|
||||
req.user!.userId,
|
||||
transactionId
|
||||
);
|
||||
res.json(payload);
|
||||
} catch (e) {
|
||||
sendError(res, e, 'Failed');
|
||||
}
|
||||
}
|
||||
|
||||
export async function verifyShareCard(req: AuthRequest, res: Response): Promise<void> {
|
||||
try {
|
||||
const token = String(req.params.token || '');
|
||||
@ -58,6 +71,10 @@ export async function updateAdminSettings(req: AuthRequest, res: Response): Prom
|
||||
allowWon?: boolean;
|
||||
allowLost?: boolean;
|
||||
allowRefunded?: boolean;
|
||||
walletOpsEnabled?: boolean;
|
||||
allowDeposit?: boolean;
|
||||
allowWithdrawal?: boolean;
|
||||
allowTransfer?: boolean;
|
||||
};
|
||||
const settings = await shareCardService.updateSettings(body);
|
||||
res.json(settings);
|
||||
|
||||
@ -2465,6 +2465,10 @@ CREATE TABLE IF NOT EXISTS share_card_settings (
|
||||
allow_won BOOLEAN NOT NULL DEFAULT TRUE,
|
||||
allow_lost BOOLEAN NOT NULL DEFAULT TRUE,
|
||||
allow_refunded BOOLEAN NOT NULL DEFAULT TRUE,
|
||||
wallet_ops_enabled BOOLEAN NOT NULL DEFAULT TRUE,
|
||||
allow_deposit BOOLEAN NOT NULL DEFAULT TRUE,
|
||||
allow_withdrawal BOOLEAN NOT NULL DEFAULT TRUE,
|
||||
allow_transfer BOOLEAN NOT NULL DEFAULT TRUE,
|
||||
updated_at TIMESTAMPTZ DEFAULT NOW()
|
||||
);
|
||||
|
||||
@ -2472,6 +2476,21 @@ INSERT INTO share_card_settings (id)
|
||||
VALUES (1)
|
||||
ON CONFLICT (id) DO NOTHING;
|
||||
|
||||
DO $$
|
||||
BEGIN
|
||||
IF NOT EXISTS (
|
||||
SELECT 1 FROM information_schema.columns
|
||||
WHERE table_schema = 'public' AND table_name = 'share_card_settings'
|
||||
AND column_name = 'wallet_ops_enabled'
|
||||
) THEN
|
||||
ALTER TABLE share_card_settings
|
||||
ADD COLUMN wallet_ops_enabled BOOLEAN NOT NULL DEFAULT TRUE,
|
||||
ADD COLUMN allow_deposit BOOLEAN NOT NULL DEFAULT TRUE,
|
||||
ADD COLUMN allow_withdrawal BOOLEAN NOT NULL DEFAULT TRUE,
|
||||
ADD COLUMN allow_transfer BOOLEAN NOT NULL DEFAULT TRUE;
|
||||
END IF;
|
||||
END $$;
|
||||
|
||||
-- Tamper trigger for share_card_settings (created after the table exists)
|
||||
DO $$
|
||||
BEGIN
|
||||
|
||||
@ -1,5 +1,5 @@
|
||||
/**
|
||||
* Share card settings (single-row admin config for prediction result sharing).
|
||||
* Share card settings (single-row admin config for prediction + wallet op sharing).
|
||||
*/
|
||||
|
||||
import { query } from '../db/connection';
|
||||
@ -13,11 +13,17 @@ export type ShareCardSettingsRow = {
|
||||
allow_won: boolean;
|
||||
allow_lost: boolean;
|
||||
allow_refunded: boolean;
|
||||
wallet_ops_enabled: boolean;
|
||||
allow_deposit: boolean;
|
||||
allow_withdrawal: boolean;
|
||||
allow_transfer: boolean;
|
||||
updated_at: Date;
|
||||
};
|
||||
|
||||
const SELECT_COLS = `id, enabled, allow_main_wallet, allow_bonus_wallet, allow_test_wallet,
|
||||
allow_won, allow_lost, allow_refunded, updated_at`;
|
||||
allow_won, allow_lost, allow_refunded,
|
||||
wallet_ops_enabled, allow_deposit, allow_withdrawal, allow_transfer,
|
||||
updated_at`;
|
||||
|
||||
export async function getSettings(): Promise<ShareCardSettingsRow> {
|
||||
const rows = await query<ShareCardSettingsRow[]>(
|
||||
@ -37,6 +43,10 @@ export async function updateSettings(input: {
|
||||
allowWon?: boolean;
|
||||
allowLost?: boolean;
|
||||
allowRefunded?: boolean;
|
||||
walletOpsEnabled?: boolean;
|
||||
allowDeposit?: boolean;
|
||||
allowWithdrawal?: boolean;
|
||||
allowTransfer?: boolean;
|
||||
}): Promise<ShareCardSettingsRow> {
|
||||
const current = await getSettings();
|
||||
const rows = await query<ShareCardSettingsRow[]>(
|
||||
@ -48,6 +58,10 @@ export async function updateSettings(input: {
|
||||
allow_won = COALESCE($5, allow_won),
|
||||
allow_lost = COALESCE($6, allow_lost),
|
||||
allow_refunded = COALESCE($7, allow_refunded),
|
||||
wallet_ops_enabled = COALESCE($8, wallet_ops_enabled),
|
||||
allow_deposit = COALESCE($9, allow_deposit),
|
||||
allow_withdrawal = COALESCE($10, allow_withdrawal),
|
||||
allow_transfer = COALESCE($11, allow_transfer),
|
||||
updated_at = NOW()
|
||||
WHERE id = 1
|
||||
RETURNING ${SELECT_COLS}`,
|
||||
@ -59,6 +73,10 @@ export async function updateSettings(input: {
|
||||
input.allowWon ?? null,
|
||||
input.allowLost ?? null,
|
||||
input.allowRefunded ?? null,
|
||||
input.walletOpsEnabled ?? null,
|
||||
input.allowDeposit ?? null,
|
||||
input.allowWithdrawal ?? null,
|
||||
input.allowTransfer ?? null,
|
||||
]
|
||||
);
|
||||
return rows[0] ?? current;
|
||||
|
||||
@ -29,6 +29,14 @@ export async function getWalletTypeByCode(code: string): Promise<WalletType | nu
|
||||
return rows[0] || null;
|
||||
}
|
||||
|
||||
export async function getWalletTypeById(id: number): Promise<WalletType | null> {
|
||||
const rows = await query<WalletType[]>(
|
||||
'SELECT id, code, name, network, decimals, contract_address FROM wallet_types WHERE id = $1',
|
||||
[id]
|
||||
);
|
||||
return rows[0] || null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieves a user's wallet for a specific wallet type.
|
||||
* @param userId - ID of the user.
|
||||
|
||||
@ -209,6 +209,7 @@ router.get('/test-wallet', testWalletController.getTestWalletStatus);
|
||||
router.post('/test-wallet/request-credits', validateBody(testWalletCreditBodySchema), testWalletController.requestTestCredits);
|
||||
router.get('/share-cards/config', shareCardController.getConfig);
|
||||
router.get('/share-cards/bets/:betId', shareCardController.getBetShareCard);
|
||||
router.get('/share-cards/transactions/:transactionId', shareCardController.getTransactionShareCard);
|
||||
router.get('/referral/me', referralController.getMyReferralInfo);
|
||||
router.get('/referral/dashboard', referralController.getMyReferralDashboard);
|
||||
router.get('/referral/commissions', referralController.getMyReferralCommissions);
|
||||
|
||||
@ -1,5 +1,6 @@
|
||||
/**
|
||||
* Share Cards: eligibility, signed verify tokens, and share payloads for prediction results.
|
||||
* Share Cards: eligibility, signed verify tokens, and share payloads
|
||||
* for prediction results and wallet operations (deposit / withdrawal / transfer).
|
||||
*/
|
||||
|
||||
import crypto from 'crypto';
|
||||
@ -8,10 +9,14 @@ import { getPublicWebBaseUrl, buildReferralRegisterLink } from '../utils/publicW
|
||||
import * as shareCardRepository from '../repositories/shareCardRepository';
|
||||
import * as candlePredictRepository from '../repositories/candlePredictRepository';
|
||||
import * as referralRepository from '../repositories/referralRepository';
|
||||
import * as transactionRepository from '../repositories/transactionRepository';
|
||||
import * as walletRepository from '../repositories/walletRepository';
|
||||
import type { ShareCardSettingsRow } from '../repositories/shareCardRepository';
|
||||
import type { Transaction } from '../models';
|
||||
|
||||
export type ShareableBetStatus = 'won' | 'lost' | 'refunded';
|
||||
export type StakeAccountKind = 'main' | 'bonus' | 'test';
|
||||
export type ShareableWalletOpType = 'deposit' | 'withdrawal' | 'transfer';
|
||||
|
||||
const STAKE_DECIMALS = 6;
|
||||
|
||||
@ -24,6 +29,10 @@ export function mapSettingsForClient(row: ShareCardSettingsRow) {
|
||||
allowWon: row.allow_won,
|
||||
allowLost: row.allow_lost,
|
||||
allowRefunded: row.allow_refunded,
|
||||
walletOpsEnabled: row.wallet_ops_enabled,
|
||||
allowDeposit: row.allow_deposit,
|
||||
allowWithdrawal: row.allow_withdrawal,
|
||||
allowTransfer: row.allow_transfer,
|
||||
updatedAt: row.updated_at.toISOString(),
|
||||
};
|
||||
}
|
||||
@ -45,11 +54,23 @@ export function canSharePredictionResult(
|
||||
return true;
|
||||
}
|
||||
|
||||
function rawToDisplay(raw: bigint): string {
|
||||
export function canShareWalletOperation(
|
||||
settings: ShareCardSettingsRow,
|
||||
input: { type: string }
|
||||
): boolean {
|
||||
if (!settings.enabled || !settings.wallet_ops_enabled) return false;
|
||||
if (input.type === 'deposit') return settings.allow_deposit;
|
||||
if (input.type === 'withdrawal') return settings.allow_withdrawal;
|
||||
if (input.type === 'transfer') return settings.allow_transfer;
|
||||
return false;
|
||||
}
|
||||
|
||||
function rawToDisplay(raw: bigint, decimals = STAKE_DECIMALS): string {
|
||||
const neg = raw < 0n;
|
||||
const abs = neg ? -raw : raw;
|
||||
const whole = abs / 10n ** BigInt(STAKE_DECIMALS);
|
||||
const frac = (abs % 10n ** BigInt(STAKE_DECIMALS)).toString().padStart(STAKE_DECIMALS, '0');
|
||||
const base = 10n ** BigInt(decimals);
|
||||
const whole = abs / base;
|
||||
const frac = (abs % base).toString().padStart(decimals, '0');
|
||||
const trimmed = frac.replace(/0+$/, '');
|
||||
const body = trimmed ? `${whole}.${trimmed}` : whole.toString();
|
||||
return neg ? `-${body}` : body;
|
||||
@ -93,15 +114,26 @@ function shareSecret(): string {
|
||||
return process.env.SHARE_CARD_SECRET?.trim() || config.jwt.secret;
|
||||
}
|
||||
|
||||
export function createShareVerifyToken(betId: string, userId: string): string {
|
||||
const payload = b64url(JSON.stringify({ b: betId, u: userId, v: 1 }));
|
||||
export type ShareTokenKind = 'bet' | 'tx';
|
||||
|
||||
export function createShareVerifyToken(
|
||||
kind: ShareTokenKind,
|
||||
resourceId: string,
|
||||
userId: string
|
||||
): string {
|
||||
const payload = b64url(JSON.stringify({ k: kind, id: resourceId, u: userId, v: 2 }));
|
||||
const sig = crypto.createHmac('sha256', shareSecret()).update(payload).digest();
|
||||
return `${payload}.${b64url(sig)}`;
|
||||
}
|
||||
|
||||
/** @deprecated Prefer createShareVerifyToken('bet', ...) — kept for call-site clarity. */
|
||||
export function createBetShareVerifyToken(betId: string, userId: string): string {
|
||||
return createShareVerifyToken('bet', betId, userId);
|
||||
}
|
||||
|
||||
export function parseShareVerifyToken(
|
||||
token: string
|
||||
): { betId: string; userId: string } | null {
|
||||
): { kind: ShareTokenKind; id: string; userId: string } | null {
|
||||
const parts = token.split('.');
|
||||
if (parts.length !== 2) return null;
|
||||
const [payload, sig] = parts;
|
||||
@ -112,12 +144,23 @@ export function parseShareVerifyToken(
|
||||
if (a.length !== b.length || !crypto.timingSafeEqual(a, b)) return null;
|
||||
try {
|
||||
const json = JSON.parse(Buffer.from(payload, 'base64url').toString('utf8')) as {
|
||||
k?: string;
|
||||
id?: string;
|
||||
b?: string;
|
||||
u?: string;
|
||||
v?: number;
|
||||
};
|
||||
if (!json.b || !json.u) return null;
|
||||
return { betId: json.b, userId: json.u };
|
||||
if (!json.u) return null;
|
||||
// v2: { k, id, u }
|
||||
if (json.k === 'bet' || json.k === 'tx') {
|
||||
if (!json.id) return null;
|
||||
return { kind: json.k, id: json.id, userId: json.u };
|
||||
}
|
||||
// v1 legacy prediction tokens: { b, u }
|
||||
if (json.b) {
|
||||
return { kind: 'bet', id: json.b, userId: json.u };
|
||||
}
|
||||
return null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
@ -127,7 +170,7 @@ export function buildShareVerifyUrl(token: string): string {
|
||||
return `${getPublicWebBaseUrl()}/share/r/${encodeURIComponent(token)}`;
|
||||
}
|
||||
|
||||
function buildCardPayload(
|
||||
function buildPredictionCardPayload(
|
||||
bet: candlePredictRepository.CandlePredictBetWithSettlement,
|
||||
opts: { includeReferral: boolean; referralCode: string | null }
|
||||
) {
|
||||
@ -135,13 +178,14 @@ function buildCardPayload(
|
||||
const stakeRaw = BigInt(bet.stake_raw);
|
||||
const payoutRaw = BigInt(bet.payout_raw);
|
||||
const result = computeResultAmount(status, stakeRaw, payoutRaw);
|
||||
const token = createShareVerifyToken(bet.id, bet.user_id);
|
||||
const token = createShareVerifyToken('bet', bet.id, bet.user_id);
|
||||
const verifyUrl = buildShareVerifyUrl(token);
|
||||
const registerUrl = opts.referralCode
|
||||
? buildReferralRegisterLink(opts.referralCode)
|
||||
: `${getPublicWebBaseUrl()}/register`;
|
||||
|
||||
return {
|
||||
kind: 'prediction' as const,
|
||||
betId: bet.id,
|
||||
gameName: 'Candle Predict',
|
||||
direction: bet.direction,
|
||||
@ -166,6 +210,53 @@ function buildCardPayload(
|
||||
};
|
||||
}
|
||||
|
||||
function shortAssetSymbol(code: string): string {
|
||||
const base = code.split('_')[0] || code;
|
||||
return base.toUpperCase();
|
||||
}
|
||||
|
||||
async function buildWalletOpCardPayload(
|
||||
tx: Transaction,
|
||||
opts: { includeReferral: boolean; referralCode: string | null }
|
||||
) {
|
||||
const wt = await walletRepository.getWalletTypeById(tx.wallet_type_id);
|
||||
const decimals = wt?.decimals ?? STAKE_DECIMALS;
|
||||
const amountRaw = BigInt(tx.amount);
|
||||
const amountDisplay = rawToDisplay(amountRaw, decimals);
|
||||
const assetCode = wt?.code ?? 'USDT';
|
||||
const assetSymbol = shortAssetSymbol(assetCode);
|
||||
const network = wt?.network ?? null;
|
||||
const token = createShareVerifyToken('tx', tx.id, tx.user_id);
|
||||
const verifyUrl = buildShareVerifyUrl(token);
|
||||
const registerUrl = opts.referralCode
|
||||
? buildReferralRegisterLink(opts.referralCode)
|
||||
: `${getPublicWebBaseUrl()}/register`;
|
||||
|
||||
const signedDisplay =
|
||||
tx.type === 'deposit' ? `+${amountDisplay}` : tx.type === 'withdrawal' ? `-${amountDisplay}` : amountDisplay;
|
||||
|
||||
return {
|
||||
kind: 'wallet' as const,
|
||||
transactionId: tx.id,
|
||||
operationType: tx.type as ShareableWalletOpType,
|
||||
status: tx.status,
|
||||
amountRaw: tx.amount,
|
||||
amountDisplay,
|
||||
amountSignedDisplay: signedDisplay,
|
||||
feeRaw: tx.fee,
|
||||
assetCode,
|
||||
assetSymbol,
|
||||
assetName: wt?.name ?? assetCode,
|
||||
network,
|
||||
createdAt: tx.created_at.toISOString(),
|
||||
blockchainTxId: tx.blockchain_tx_id,
|
||||
verifyUrl,
|
||||
verifyToken: token,
|
||||
referralCode: opts.includeReferral ? opts.referralCode : null,
|
||||
registerUrl,
|
||||
};
|
||||
}
|
||||
|
||||
export async function getConfigForUser() {
|
||||
const settings = await shareCardRepository.getSettings();
|
||||
return mapSettingsForClient(settings);
|
||||
@ -184,6 +275,10 @@ export async function updateSettings(input: {
|
||||
allowWon?: boolean;
|
||||
allowLost?: boolean;
|
||||
allowRefunded?: boolean;
|
||||
walletOpsEnabled?: boolean;
|
||||
allowDeposit?: boolean;
|
||||
allowWithdrawal?: boolean;
|
||||
allowTransfer?: boolean;
|
||||
}) {
|
||||
const row = await shareCardRepository.updateSettings(input);
|
||||
return mapSettingsForClient(row);
|
||||
@ -213,7 +308,20 @@ export async function getSharePayloadForOwner(userId: string, betId: string) {
|
||||
throw new ShareCardError('Sharing is not available for this prediction', 403);
|
||||
}
|
||||
const referralCode = await referralRepository.getUserReferralCode(userId);
|
||||
return buildCardPayload(bet, { includeReferral: true, referralCode });
|
||||
return buildPredictionCardPayload(bet, { includeReferral: true, referralCode });
|
||||
}
|
||||
|
||||
export async function getWalletOpSharePayloadForOwner(userId: string, transactionId: string) {
|
||||
const settings = await shareCardRepository.getSettings();
|
||||
const tx = await transactionRepository.findById(transactionId);
|
||||
if (!tx || tx.user_id !== userId) {
|
||||
throw new ShareCardError('Transaction not found', 404);
|
||||
}
|
||||
if (!canShareWalletOperation(settings, { type: tx.type })) {
|
||||
throw new ShareCardError('Sharing is not available for this operation', 403);
|
||||
}
|
||||
const referralCode = await referralRepository.getUserReferralCode(userId);
|
||||
return buildWalletOpCardPayload(tx, { includeReferral: true, referralCode });
|
||||
}
|
||||
|
||||
export async function getPublicVerifyPayload(token: string) {
|
||||
@ -225,7 +333,37 @@ export async function getPublicVerifyPayload(token: string) {
|
||||
if (!settings.enabled) {
|
||||
throw new ShareCardError('Share cards are disabled', 404);
|
||||
}
|
||||
const bet = await candlePredictRepository.getBetById(parsed.betId);
|
||||
|
||||
if (parsed.kind === 'tx') {
|
||||
if (!settings.wallet_ops_enabled) {
|
||||
throw new ShareCardError('Wallet share cards are disabled', 404);
|
||||
}
|
||||
const tx = await transactionRepository.findById(parsed.id);
|
||||
if (!tx || tx.user_id !== parsed.userId) {
|
||||
throw new ShareCardError('Transaction not found', 404);
|
||||
}
|
||||
if (!canShareWalletOperation(settings, { type: tx.type })) {
|
||||
throw new ShareCardError('This operation is no longer shareable', 404);
|
||||
}
|
||||
const referralCode = await referralRepository.getUserReferralCode(tx.user_id);
|
||||
const card = await buildWalletOpCardPayload(tx, { includeReferral: true, referralCode });
|
||||
return {
|
||||
authentic: true as const,
|
||||
kind: 'wallet' as const,
|
||||
operationType: card.operationType,
|
||||
status: card.status,
|
||||
amountSignedDisplay: card.amountSignedDisplay,
|
||||
amountDisplay: card.amountDisplay,
|
||||
assetSymbol: card.assetSymbol,
|
||||
assetCode: card.assetCode,
|
||||
network: card.network,
|
||||
createdAt: card.createdAt,
|
||||
registerUrl: card.registerUrl,
|
||||
referralCode: card.referralCode,
|
||||
};
|
||||
}
|
||||
|
||||
const bet = await candlePredictRepository.getBetById(parsed.id);
|
||||
if (!bet || bet.user_id !== parsed.userId) {
|
||||
throw new ShareCardError('Prediction not found', 404);
|
||||
}
|
||||
@ -238,10 +376,10 @@ export async function getPublicVerifyPayload(token: string) {
|
||||
throw new ShareCardError('This result is no longer shareable', 404);
|
||||
}
|
||||
const referralCode = await referralRepository.getUserReferralCode(bet.user_id);
|
||||
const card = buildCardPayload(bet, { includeReferral: true, referralCode });
|
||||
// Public verify: omit internal ids that aren't needed for marketing display
|
||||
const card = buildPredictionCardPayload(bet, { includeReferral: true, referralCode });
|
||||
return {
|
||||
authentic: true as const,
|
||||
kind: 'prediction' as const,
|
||||
gameName: card.gameName,
|
||||
direction: card.direction,
|
||||
sequence: card.sequence,
|
||||
|
||||
@ -2,6 +2,7 @@ import { describe, test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {
|
||||
canSharePredictionResult,
|
||||
canShareWalletOperation,
|
||||
createShareVerifyToken,
|
||||
parseShareVerifyToken,
|
||||
} from '../services/shareCardService';
|
||||
@ -17,6 +18,10 @@ function settings(partial: Partial<ShareCardSettingsRow> = {}): ShareCardSetting
|
||||
allow_won: true,
|
||||
allow_lost: true,
|
||||
allow_refunded: true,
|
||||
wallet_ops_enabled: true,
|
||||
allow_deposit: true,
|
||||
allow_withdrawal: true,
|
||||
allow_transfer: true,
|
||||
updated_at: new Date(),
|
||||
...partial,
|
||||
};
|
||||
@ -63,19 +68,41 @@ describe('share card eligibility', () => {
|
||||
false
|
||||
);
|
||||
});
|
||||
|
||||
test('wallet ops respect global and per-type flags', () => {
|
||||
assert.equal(canShareWalletOperation(settings(), { type: 'deposit' }), true);
|
||||
assert.equal(
|
||||
canShareWalletOperation(settings({ wallet_ops_enabled: false }), { type: 'deposit' }),
|
||||
false
|
||||
);
|
||||
assert.equal(
|
||||
canShareWalletOperation(settings({ allow_transfer: false }), { type: 'transfer' }),
|
||||
false
|
||||
);
|
||||
assert.equal(canShareWalletOperation(settings(), { type: 'game_stake' }), false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('share card verify token', () => {
|
||||
test('round-trips bet and user ids', () => {
|
||||
const betId = '11111111-1111-1111-1111-111111111111';
|
||||
const userId = '22222222-2222-2222-2222-222222222222';
|
||||
const token = createShareVerifyToken(betId, userId);
|
||||
const token = createShareVerifyToken('bet', betId, userId);
|
||||
const parsed = parseShareVerifyToken(token);
|
||||
assert.deepEqual(parsed, { betId, userId });
|
||||
assert.deepEqual(parsed, { kind: 'bet', id: betId, userId });
|
||||
});
|
||||
|
||||
test('round-trips wallet transaction tokens', () => {
|
||||
const txId = '33333333-3333-3333-3333-333333333333';
|
||||
const userId = '22222222-2222-2222-2222-222222222222';
|
||||
const token = createShareVerifyToken('tx', txId, userId);
|
||||
const parsed = parseShareVerifyToken(token);
|
||||
assert.deepEqual(parsed, { kind: 'tx', id: txId, userId });
|
||||
});
|
||||
|
||||
test('rejects tampered token', () => {
|
||||
const token = createShareVerifyToken(
|
||||
'bet',
|
||||
'11111111-1111-1111-1111-111111111111',
|
||||
'22222222-2222-2222-2222-222222222222'
|
||||
);
|
||||
|
||||
@ -196,6 +196,10 @@ export const shareCardSettingsBodySchema = atLeastOneField(
|
||||
allowWon: z.boolean().optional(),
|
||||
allowLost: z.boolean().optional(),
|
||||
allowRefunded: z.boolean().optional(),
|
||||
walletOpsEnabled: z.boolean().optional(),
|
||||
allowDeposit: z.boolean().optional(),
|
||||
allowWithdrawal: z.boolean().optional(),
|
||||
allowTransfer: z.boolean().optional(),
|
||||
})
|
||||
);
|
||||
|
||||
|
||||
@ -7,6 +7,10 @@ class ShareCardConfig {
|
||||
required this.allowWon,
|
||||
required this.allowLost,
|
||||
required this.allowRefunded,
|
||||
required this.walletOpsEnabled,
|
||||
required this.allowDeposit,
|
||||
required this.allowWithdrawal,
|
||||
required this.allowTransfer,
|
||||
});
|
||||
|
||||
final bool enabled;
|
||||
@ -16,6 +20,10 @@ class ShareCardConfig {
|
||||
final bool allowWon;
|
||||
final bool allowLost;
|
||||
final bool allowRefunded;
|
||||
final bool walletOpsEnabled;
|
||||
final bool allowDeposit;
|
||||
final bool allowWithdrawal;
|
||||
final bool allowTransfer;
|
||||
|
||||
factory ShareCardConfig.fromJson(Map<String, dynamic> json) {
|
||||
return ShareCardConfig(
|
||||
@ -26,10 +34,14 @@ class ShareCardConfig {
|
||||
allowWon: json['allowWon'] != false,
|
||||
allowLost: json['allowLost'] != false,
|
||||
allowRefunded: json['allowRefunded'] != false,
|
||||
walletOpsEnabled: json['walletOpsEnabled'] != false,
|
||||
allowDeposit: json['allowDeposit'] != false,
|
||||
allowWithdrawal: json['allowWithdrawal'] != false,
|
||||
allowTransfer: json['allowTransfer'] != false,
|
||||
);
|
||||
}
|
||||
|
||||
bool isEligible({
|
||||
bool isPredictionEligible({
|
||||
required String? status,
|
||||
required String? stakeAccountKind,
|
||||
bool requireStatus = true,
|
||||
@ -46,58 +58,119 @@ class ShareCardConfig {
|
||||
if (status == 'refunded' && !allowRefunded) return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
bool isWalletOpEligible(String operationType) {
|
||||
if (!enabled || !walletOpsEnabled) return false;
|
||||
switch (operationType) {
|
||||
case 'deposit':
|
||||
return allowDeposit;
|
||||
case 'withdrawal':
|
||||
return allowWithdrawal;
|
||||
case 'transfer':
|
||||
return allowTransfer;
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// Backward-compatible alias.
|
||||
bool isEligible({
|
||||
required String? status,
|
||||
required String? stakeAccountKind,
|
||||
bool requireStatus = true,
|
||||
}) =>
|
||||
isPredictionEligible(
|
||||
status: status,
|
||||
stakeAccountKind: stakeAccountKind,
|
||||
requireStatus: requireStatus,
|
||||
);
|
||||
}
|
||||
|
||||
class ShareCardPayload {
|
||||
const ShareCardPayload({
|
||||
required this.betId,
|
||||
required this.gameName,
|
||||
required this.direction,
|
||||
required this.status,
|
||||
required this.resultSignedDisplay,
|
||||
required this.stakeDisplay,
|
||||
required this.intervalMinutes,
|
||||
required this.settledAt,
|
||||
required this.kind,
|
||||
required this.verifyUrl,
|
||||
required this.predictionMode,
|
||||
required this.isAuto,
|
||||
this.betId,
|
||||
this.gameName,
|
||||
this.direction,
|
||||
this.status,
|
||||
this.resultSignedDisplay,
|
||||
this.stakeDisplay,
|
||||
this.intervalMinutes,
|
||||
this.settledAt,
|
||||
this.predictionMode,
|
||||
this.isAuto = false,
|
||||
this.sequence = const [],
|
||||
this.transactionId,
|
||||
this.operationType,
|
||||
this.amountSignedDisplay,
|
||||
this.amountDisplay,
|
||||
this.assetSymbol,
|
||||
this.assetName,
|
||||
this.network,
|
||||
this.createdAt,
|
||||
this.txStatus,
|
||||
});
|
||||
|
||||
final String betId;
|
||||
final String gameName;
|
||||
final String direction;
|
||||
final String status;
|
||||
final String resultSignedDisplay;
|
||||
final num stakeDisplay;
|
||||
final int intervalMinutes;
|
||||
final String settledAt;
|
||||
final String kind; // prediction | wallet
|
||||
final String verifyUrl;
|
||||
final String predictionMode;
|
||||
|
||||
// Prediction
|
||||
final String? betId;
|
||||
final String? gameName;
|
||||
final String? direction;
|
||||
final String? status;
|
||||
final String? resultSignedDisplay;
|
||||
final num? stakeDisplay;
|
||||
final int? intervalMinutes;
|
||||
final String? settledAt;
|
||||
final String? predictionMode;
|
||||
final bool isAuto;
|
||||
final List<String> sequence;
|
||||
|
||||
// Wallet
|
||||
final String? transactionId;
|
||||
final String? operationType;
|
||||
final String? amountSignedDisplay;
|
||||
final String? amountDisplay;
|
||||
final String? assetSymbol;
|
||||
final String? assetName;
|
||||
final String? network;
|
||||
final String? createdAt;
|
||||
final String? txStatus;
|
||||
|
||||
bool get isWallet => kind == 'wallet';
|
||||
|
||||
factory ShareCardPayload.fromJson(Map<String, dynamic> json) {
|
||||
final kind = (json['kind'] ?? 'prediction').toString();
|
||||
final seq = json['sequence'];
|
||||
return ShareCardPayload(
|
||||
betId: (json['betId'] ?? '').toString(),
|
||||
kind: kind,
|
||||
verifyUrl: (json['verifyUrl'] ?? '').toString(),
|
||||
betId: json['betId']?.toString(),
|
||||
gameName: (json['gameName'] ?? 'Candle Predict').toString(),
|
||||
direction: (json['direction'] ?? 'long').toString(),
|
||||
status: (json['status'] ?? '').toString(),
|
||||
resultSignedDisplay: (json['resultSignedDisplay'] ?? '0').toString(),
|
||||
status: json['status']?.toString(),
|
||||
resultSignedDisplay: json['resultSignedDisplay']?.toString(),
|
||||
stakeDisplay: json['stakeDisplay'] is num
|
||||
? json['stakeDisplay'] as num
|
||||
: num.tryParse('${json['stakeDisplay']}') ?? 0,
|
||||
: num.tryParse('${json['stakeDisplay']}'),
|
||||
intervalMinutes: json['intervalMinutes'] is int
|
||||
? json['intervalMinutes'] as int
|
||||
: int.tryParse('${json['intervalMinutes']}') ?? 1,
|
||||
settledAt: (json['settledAt'] ?? '').toString(),
|
||||
verifyUrl: (json['verifyUrl'] ?? '').toString(),
|
||||
: int.tryParse('${json['intervalMinutes']}'),
|
||||
settledAt: json['settledAt']?.toString(),
|
||||
predictionMode: (json['predictionMode'] ?? 'single').toString(),
|
||||
isAuto: json['isAuto'] == true,
|
||||
sequence: seq is List
|
||||
? seq.map((e) => e.toString()).toList()
|
||||
: const <String>[],
|
||||
sequence: seq is List ? seq.map((e) => e.toString()).toList() : const <String>[],
|
||||
transactionId: json['transactionId']?.toString(),
|
||||
operationType: json['operationType']?.toString(),
|
||||
amountSignedDisplay: json['amountSignedDisplay']?.toString(),
|
||||
amountDisplay: json['amountDisplay']?.toString(),
|
||||
assetSymbol: json['assetSymbol']?.toString(),
|
||||
assetName: json['assetName']?.toString(),
|
||||
network: json['network']?.toString(),
|
||||
createdAt: json['createdAt']?.toString(),
|
||||
txStatus: json['status']?.toString(),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@ -39,4 +39,15 @@ class ShareCardRepository {
|
||||
throw AppException.fromDio(e);
|
||||
}
|
||||
}
|
||||
|
||||
Future<ShareCardPayload> getTransactionShareCard(String transactionId) async {
|
||||
try {
|
||||
final res = await _api.dio.get<Map<String, dynamic>>(
|
||||
'/api/v1/share-cards/transactions/$transactionId',
|
||||
);
|
||||
return ShareCardPayload.fromJson(res.data ?? {});
|
||||
} on DioException catch (e) {
|
||||
throw AppException.fromDio(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ -16,17 +16,23 @@ import '../../../shared/widgets/prediqo_logo.dart';
|
||||
|
||||
Future<void> openShareResultDialog(
|
||||
BuildContext context, {
|
||||
required String betId,
|
||||
String? betId,
|
||||
String? transactionId,
|
||||
}) {
|
||||
assert(betId != null || transactionId != null);
|
||||
return showDialog<void>(
|
||||
context: context,
|
||||
builder: (ctx) => _ShareResultDialog(betId: betId),
|
||||
builder: (ctx) => _ShareResultDialog(
|
||||
betId: betId,
|
||||
transactionId: transactionId,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
class _ShareResultDialog extends StatefulWidget {
|
||||
const _ShareResultDialog({required this.betId});
|
||||
final String betId;
|
||||
const _ShareResultDialog({this.betId, this.transactionId});
|
||||
final String? betId;
|
||||
final String? transactionId;
|
||||
|
||||
@override
|
||||
State<_ShareResultDialog> createState() => _ShareResultDialogState();
|
||||
@ -51,7 +57,10 @@ class _ShareResultDialogState extends State<_ShareResultDialog> {
|
||||
_error = null;
|
||||
});
|
||||
try {
|
||||
final payload = await sl<ShareCardRepository>().getBetShareCard(widget.betId);
|
||||
final repo = sl<ShareCardRepository>();
|
||||
final payload = widget.transactionId != null
|
||||
? await repo.getTransactionShareCard(widget.transactionId!)
|
||||
: await repo.getBetShareCard(widget.betId!);
|
||||
if (!mounted) return;
|
||||
setState(() {
|
||||
_payload = payload;
|
||||
@ -77,9 +86,12 @@ class _ShareResultDialogState extends State<_ShareResultDialog> {
|
||||
final bytes = await image.toByteData(format: ui.ImageByteFormat.png);
|
||||
if (bytes == null) throw Exception('export failed');
|
||||
final dir = await getTemporaryDirectory();
|
||||
final file = File(
|
||||
'${dir.path}/prediqo-${payload.status}-${payload.betId.substring(0, 8)}.png',
|
||||
);
|
||||
final tag = payload.isWallet
|
||||
? (payload.operationType ?? 'wallet')
|
||||
: (payload.status ?? 'result');
|
||||
final id = (payload.isWallet ? payload.transactionId : payload.betId) ?? 'x';
|
||||
final shortId = id.length >= 8 ? id.substring(0, 8) : id;
|
||||
final file = File('${dir.path}/prediqo-$tag-$shortId.png');
|
||||
await file.writeAsBytes(bytes.buffer.asUint8List());
|
||||
await SharePlus.instance.share(
|
||||
ShareParams(
|
||||
@ -153,6 +165,16 @@ class ShareResultCard extends StatelessWidget {
|
||||
const ShareResultCard({super.key, required this.payload});
|
||||
final ShareCardPayload payload;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return payload.isWallet ? _WalletCard(payload: payload) : _PredictionCard(payload: payload);
|
||||
}
|
||||
}
|
||||
|
||||
class _PredictionCard extends StatelessWidget {
|
||||
const _PredictionCard({required this.payload});
|
||||
final ShareCardPayload payload;
|
||||
|
||||
Color get _accent {
|
||||
switch (payload.status) {
|
||||
case 'won':
|
||||
@ -167,17 +189,105 @@ class ShareResultCard extends StatelessWidget {
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final s = context.strings;
|
||||
final settled = DateTime.tryParse(payload.settledAt)?.toLocal();
|
||||
final settled = DateTime.tryParse(payload.settledAt ?? '')?.toLocal();
|
||||
final direction = payload.sequence.isNotEmpty
|
||||
? payload.sequence.map(_dirLabel).join(' → ')
|
||||
: _dirLabel(payload.direction);
|
||||
: _dirLabel(payload.direction ?? 'long');
|
||||
final statusLabel = switch (payload.status) {
|
||||
'won' => s.t('Won', 'Gagné'),
|
||||
'lost' => s.t('Lost', 'Perdu'),
|
||||
'refunded' => s.t('Refunded', 'Remboursé'),
|
||||
_ => payload.status,
|
||||
_ => payload.status ?? '',
|
||||
};
|
||||
|
||||
return _CardShell(
|
||||
title: payload.gameName ?? 'Candle Predict',
|
||||
accent: _accent,
|
||||
amountLine: '${payload.resultSignedDisplay ?? '0'} USDT',
|
||||
subtitle: statusLabel,
|
||||
rows: [
|
||||
_KV(s.t('Prediction', 'Prédiction'), direction),
|
||||
_KV(s.t('Interval', 'Intervalle'), '${payload.intervalMinutes ?? 1} min'),
|
||||
_KV(s.t('Stake', 'Mise'), '${payload.stakeDisplay ?? 0} USDT'),
|
||||
if (settled != null) _KV(s.t('Settled', 'Validé le'), _fmt(settled)),
|
||||
],
|
||||
verifyUrl: payload.verifyUrl,
|
||||
);
|
||||
}
|
||||
|
||||
String _dirLabel(String d) => d == 'short' ? 'Short' : 'Long';
|
||||
}
|
||||
|
||||
class _WalletCard extends StatelessWidget {
|
||||
const _WalletCard({required this.payload});
|
||||
final ShareCardPayload payload;
|
||||
|
||||
Color get _accent {
|
||||
switch (payload.operationType) {
|
||||
case 'deposit':
|
||||
return const Color(0xFF3DDC97);
|
||||
case 'withdrawal':
|
||||
return const Color(0xFF5EB2D6);
|
||||
default:
|
||||
return const Color(0xFFC4A4FF);
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final s = context.strings;
|
||||
final created = DateTime.tryParse(payload.createdAt ?? '')?.toLocal();
|
||||
final opLabel = switch (payload.operationType) {
|
||||
'deposit' => s.t('Deposit', 'Dépôt'),
|
||||
'withdrawal' => s.t('Withdrawal', 'Retrait'),
|
||||
'transfer' => s.t('Transfer', 'Transfert'),
|
||||
_ => payload.operationType ?? '',
|
||||
};
|
||||
final statusLabel = switch (payload.txStatus) {
|
||||
'completed' => s.t('Completed', 'Réussi'),
|
||||
'pending' => s.t('Pending', 'En attente'),
|
||||
'confirming' => s.t('Confirming', 'Confirmation'),
|
||||
'failed' => s.t('Failed', 'Échoué'),
|
||||
_ => payload.txStatus ?? '',
|
||||
};
|
||||
|
||||
return _CardShell(
|
||||
title: 'Prediqo Wallet',
|
||||
accent: _accent,
|
||||
amountLine: '${payload.amountSignedDisplay ?? '0'} ${payload.assetSymbol ?? ''}',
|
||||
subtitle: opLabel,
|
||||
rows: [
|
||||
_KV(s.t('Status', 'Statut'), statusLabel),
|
||||
_KV(s.t('Asset', 'Actif'), payload.assetName ?? payload.assetSymbol ?? ''),
|
||||
if ((payload.network ?? '').isNotEmpty)
|
||||
_KV(s.t('Network', 'Réseau'), payload.network!),
|
||||
if (created != null) _KV(s.t('Date', 'Date'), _fmt(created)),
|
||||
],
|
||||
verifyUrl: payload.verifyUrl,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _CardShell extends StatelessWidget {
|
||||
const _CardShell({
|
||||
required this.title,
|
||||
required this.accent,
|
||||
required this.amountLine,
|
||||
required this.subtitle,
|
||||
required this.rows,
|
||||
required this.verifyUrl,
|
||||
});
|
||||
|
||||
final String title;
|
||||
final Color accent;
|
||||
final String amountLine;
|
||||
final String subtitle;
|
||||
final List<_KV> rows;
|
||||
final String verifyUrl;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final s = context.strings;
|
||||
return Container(
|
||||
width: 320,
|
||||
padding: const EdgeInsets.all(18),
|
||||
@ -206,7 +316,7 @@ class ShareResultCard extends StatelessWidget {
|
||||
),
|
||||
const Spacer(),
|
||||
Text(
|
||||
payload.gameName,
|
||||
title,
|
||||
style: const TextStyle(
|
||||
color: Colors.white70,
|
||||
fontWeight: FontWeight.w700,
|
||||
@ -217,29 +327,29 @@ class ShareResultCard extends StatelessWidget {
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
Text(
|
||||
'${payload.resultSignedDisplay} USDT',
|
||||
style: TextStyle(
|
||||
color: _accent,
|
||||
fontWeight: FontWeight.w900,
|
||||
fontSize: 28,
|
||||
),
|
||||
),
|
||||
Text(
|
||||
statusLabel,
|
||||
style: TextStyle(color: _accent, fontWeight: FontWeight.w800),
|
||||
amountLine,
|
||||
style: TextStyle(color: accent, fontWeight: FontWeight.w900, fontSize: 28),
|
||||
),
|
||||
Text(subtitle, style: TextStyle(color: accent, fontWeight: FontWeight.w800)),
|
||||
const SizedBox(height: 12),
|
||||
_row(s.t('Prediction', 'Prédiction'), direction),
|
||||
_row(s.t('Interval', 'Intervalle'), '${payload.intervalMinutes} min'),
|
||||
_row(s.t('Stake', 'Mise'), '${payload.stakeDisplay} USDT'),
|
||||
if (settled != null)
|
||||
_row(
|
||||
s.t('Settled', 'Validé le'),
|
||||
'${settled.day.toString().padLeft(2, '0')}/'
|
||||
'${settled.month.toString().padLeft(2, '0')}/'
|
||||
'${settled.year} '
|
||||
'${settled.hour.toString().padLeft(2, '0')}:'
|
||||
'${settled.minute.toString().padLeft(2, '0')}',
|
||||
for (final row in rows)
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(bottom: 4),
|
||||
child: Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: Text(row.k, style: const TextStyle(color: Colors.white54, fontSize: 12)),
|
||||
),
|
||||
Text(
|
||||
row.v,
|
||||
style: const TextStyle(
|
||||
color: Colors.white,
|
||||
fontWeight: FontWeight.w700,
|
||||
fontSize: 12,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 14),
|
||||
const Divider(color: Colors.white12),
|
||||
@ -249,17 +359,15 @@ class ShareResultCard extends StatelessWidget {
|
||||
Container(
|
||||
padding: const EdgeInsets.all(6),
|
||||
color: Colors.white,
|
||||
child: QrImageView(
|
||||
data: payload.verifyUrl,
|
||||
size: 64,
|
||||
padding: EdgeInsets.zero,
|
||||
),
|
||||
child: QrImageView(data: verifyUrl, size: 64, padding: EdgeInsets.zero),
|
||||
),
|
||||
const SizedBox(width: 12),
|
||||
Expanded(
|
||||
child: Text(
|
||||
s.t('Scan to verify · Authentic Prediqo result',
|
||||
'Scanner pour vérifier · Résultat Prediqo authentique'),
|
||||
s.t(
|
||||
'Scan to verify · Authentic Prediqo result',
|
||||
'Scanner pour vérifier · Résultat Prediqo authentique',
|
||||
),
|
||||
style: const TextStyle(color: Colors.white70, fontSize: 11),
|
||||
),
|
||||
),
|
||||
@ -269,34 +377,36 @@ class ShareResultCard extends StatelessWidget {
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
String _dirLabel(String d) => d == 'short' ? 'Short' : 'Long';
|
||||
class _KV {
|
||||
const _KV(this.k, this.v);
|
||||
final String k;
|
||||
final String v;
|
||||
}
|
||||
|
||||
Widget _row(String label, String value) {
|
||||
return Padding(
|
||||
padding: const EdgeInsets.only(bottom: 4),
|
||||
child: Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: Text(label, style: const TextStyle(color: Colors.white54, fontSize: 12)),
|
||||
),
|
||||
Text(value, style: const TextStyle(color: Colors.white, fontWeight: FontWeight.w700, fontSize: 12)),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
String _fmt(DateTime dt) {
|
||||
final d = dt.day.toString().padLeft(2, '0');
|
||||
final m = dt.month.toString().padLeft(2, '0');
|
||||
final h = dt.hour.toString().padLeft(2, '0');
|
||||
final min = dt.minute.toString().padLeft(2, '0');
|
||||
return '$d/$m/${dt.year} $h:$min';
|
||||
}
|
||||
|
||||
class ShareResultIconButton extends StatefulWidget {
|
||||
const ShareResultIconButton({
|
||||
super.key,
|
||||
required this.betId,
|
||||
this.betId,
|
||||
this.transactionId,
|
||||
this.operationType,
|
||||
this.status,
|
||||
this.stakeAccountKind,
|
||||
this.requireStatus = true,
|
||||
});
|
||||
|
||||
final String betId;
|
||||
final String? betId;
|
||||
final String? transactionId;
|
||||
final String? operationType;
|
||||
final String? status;
|
||||
final String? stakeAccountKind;
|
||||
final bool requireStatus;
|
||||
@ -332,16 +442,22 @@ class _ShareResultIconButtonState extends State<ShareResultIconButton> {
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
if (!_loaded || _config == null) return const SizedBox.shrink();
|
||||
final ok = _config!.isEligible(
|
||||
status: widget.status,
|
||||
stakeAccountKind: widget.stakeAccountKind,
|
||||
requireStatus: widget.requireStatus,
|
||||
);
|
||||
final ok = widget.transactionId != null
|
||||
? _config!.isWalletOpEligible(widget.operationType ?? '')
|
||||
: _config!.isPredictionEligible(
|
||||
status: widget.status,
|
||||
stakeAccountKind: widget.stakeAccountKind,
|
||||
requireStatus: widget.requireStatus,
|
||||
);
|
||||
if (!ok) return const SizedBox.shrink();
|
||||
return IconButton(
|
||||
tooltip: context.strings.t('Share result', 'Partager le résultat'),
|
||||
icon: const Icon(Icons.ios_share_rounded),
|
||||
onPressed: () => openShareResultDialog(context, betId: widget.betId),
|
||||
onPressed: () => openShareResultDialog(
|
||||
context,
|
||||
betId: widget.betId,
|
||||
transactionId: widget.transactionId,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@ -954,6 +954,11 @@ class _StatusTxTile extends StatelessWidget {
|
||||
),
|
||||
],
|
||||
),
|
||||
if (tx.type == 'deposit' || tx.type == 'withdrawal' || tx.type == 'transfer')
|
||||
ShareResultIconButton(
|
||||
transactionId: tx.id,
|
||||
operationType: tx.type,
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
|
||||
@ -1,5 +1,5 @@
|
||||
/**
|
||||
* Admin configuration for Share Cards (prediction result sharing).
|
||||
* Admin configuration for Share Cards (prediction + wallet operation sharing).
|
||||
*/
|
||||
import {
|
||||
Alert,
|
||||
@ -27,6 +27,10 @@ export type ShareCardSettings = {
|
||||
allowWon: boolean;
|
||||
allowLost: boolean;
|
||||
allowRefunded: boolean;
|
||||
walletOpsEnabled: boolean;
|
||||
allowDeposit: boolean;
|
||||
allowWithdrawal: boolean;
|
||||
allowTransfer: boolean;
|
||||
updatedAt: string;
|
||||
};
|
||||
|
||||
@ -68,6 +72,8 @@ export function ShareCardsAdminPage() {
|
||||
);
|
||||
}
|
||||
|
||||
const walletOpsDisabled = !form.enabled || !form.walletOpsEnabled;
|
||||
|
||||
return (
|
||||
<Box sx={{ minWidth: 0 }}>
|
||||
<Stack direction="row" spacing={1.5} sx={{ alignItems: 'center', mb: 2 }}>
|
||||
@ -104,6 +110,9 @@ export function ShareCardsAdminPage() {
|
||||
<Divider sx={{ my: 2 }} />
|
||||
|
||||
<Typography variant="subtitle2" sx={{ fontWeight: 800, mb: 1 }}>
|
||||
{t('admin.shareCards.predictionsTitle')}
|
||||
</Typography>
|
||||
<Typography variant="caption" color="text.secondary" sx={{ display: 'block', mb: 1 }}>
|
||||
{t('admin.shareCards.walletsTitle')}
|
||||
</Typography>
|
||||
<Stack spacing={0.5} sx={{ mb: 2 }}>
|
||||
@ -139,9 +148,7 @@ export function ShareCardsAdminPage() {
|
||||
/>
|
||||
</Stack>
|
||||
|
||||
<Divider sx={{ my: 2 }} />
|
||||
|
||||
<Typography variant="subtitle2" sx={{ fontWeight: 800, mb: 1 }}>
|
||||
<Typography variant="caption" color="text.secondary" sx={{ display: 'block', mb: 1 }}>
|
||||
{t('admin.shareCards.outcomesTitle')}
|
||||
</Typography>
|
||||
<Stack spacing={0.5} sx={{ mb: 2 }}>
|
||||
@ -177,6 +184,57 @@ export function ShareCardsAdminPage() {
|
||||
/>
|
||||
</Stack>
|
||||
|
||||
<Divider sx={{ my: 2 }} />
|
||||
|
||||
<Typography variant="subtitle2" sx={{ fontWeight: 800, mb: 1 }}>
|
||||
{t('admin.shareCards.walletOpsTitle')}
|
||||
</Typography>
|
||||
<FormControlLabel
|
||||
control={
|
||||
<Switch
|
||||
checked={form.walletOpsEnabled}
|
||||
disabled={!form.enabled}
|
||||
onChange={(e) => setForm({ ...form, walletOpsEnabled: e.target.checked })}
|
||||
/>
|
||||
}
|
||||
label={t('admin.shareCards.walletOpsEnabled')}
|
||||
/>
|
||||
<Typography variant="caption" color="text.secondary" sx={{ display: 'block', mb: 1 }}>
|
||||
{t('admin.shareCards.walletOpsHelper')}
|
||||
</Typography>
|
||||
<Stack spacing={0.5} sx={{ mb: 2 }}>
|
||||
<FormControlLabel
|
||||
control={
|
||||
<Switch
|
||||
checked={form.allowDeposit}
|
||||
disabled={walletOpsDisabled}
|
||||
onChange={(e) => setForm({ ...form, allowDeposit: e.target.checked })}
|
||||
/>
|
||||
}
|
||||
label={t('admin.shareCards.allowDeposit')}
|
||||
/>
|
||||
<FormControlLabel
|
||||
control={
|
||||
<Switch
|
||||
checked={form.allowWithdrawal}
|
||||
disabled={walletOpsDisabled}
|
||||
onChange={(e) => setForm({ ...form, allowWithdrawal: e.target.checked })}
|
||||
/>
|
||||
}
|
||||
label={t('admin.shareCards.allowWithdrawal')}
|
||||
/>
|
||||
<FormControlLabel
|
||||
control={
|
||||
<Switch
|
||||
checked={form.allowTransfer}
|
||||
disabled={walletOpsDisabled}
|
||||
onChange={(e) => setForm({ ...form, allowTransfer: e.target.checked })}
|
||||
/>
|
||||
}
|
||||
label={t('admin.shareCards.allowTransfer')}
|
||||
/>
|
||||
</Stack>
|
||||
|
||||
<Button
|
||||
variant="contained"
|
||||
disabled={saveMut.isPending}
|
||||
@ -189,6 +247,10 @@ export function ShareCardsAdminPage() {
|
||||
allowWon: form.allowWon,
|
||||
allowLost: form.allowLost,
|
||||
allowRefunded: form.allowRefunded,
|
||||
walletOpsEnabled: form.walletOpsEnabled,
|
||||
allowDeposit: form.allowDeposit,
|
||||
allowWithdrawal: form.allowWithdrawal,
|
||||
allowTransfer: form.allowTransfer,
|
||||
})
|
||||
}
|
||||
>
|
||||
|
||||
@ -7,37 +7,42 @@ import { useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { useShareCardConfig } from './hooks';
|
||||
import { ShareResultDialog } from './ShareResultDialog';
|
||||
import { isShareEligibleClient } from './types';
|
||||
import { isPredictionShareEligible, isWalletOpShareEligible } from './types';
|
||||
|
||||
type Props = {
|
||||
type PredictionProps = {
|
||||
kind?: 'prediction';
|
||||
betId: string;
|
||||
status?: string | null;
|
||||
stakeAccountKind?: string | null;
|
||||
/** When true (default), status must be won/lost/refunded. Set false for wallet rows. */
|
||||
requireStatus?: boolean;
|
||||
size?: 'small' | 'medium';
|
||||
};
|
||||
|
||||
export function ShareResultButton({
|
||||
betId,
|
||||
status,
|
||||
stakeAccountKind,
|
||||
requireStatus = true,
|
||||
size = 'small',
|
||||
}: Props) {
|
||||
type WalletProps = {
|
||||
kind: 'wallet';
|
||||
transactionId: string;
|
||||
operationType: 'deposit' | 'withdrawal' | 'transfer';
|
||||
size?: 'small' | 'medium';
|
||||
};
|
||||
|
||||
type Props = PredictionProps | WalletProps;
|
||||
|
||||
export function ShareResultButton(props: Props) {
|
||||
const { t } = useTranslation();
|
||||
const configQ = useShareCardConfig();
|
||||
const [open, setOpen] = useState(false);
|
||||
const size = props.size ?? 'small';
|
||||
|
||||
if (
|
||||
!isShareEligibleClient(configQ.data, {
|
||||
status,
|
||||
stakeAccountKind,
|
||||
requireStatus,
|
||||
})
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
const eligible =
|
||||
props.kind === 'wallet'
|
||||
? isWalletOpShareEligible(configQ.data, props.operationType)
|
||||
: isPredictionShareEligible(configQ.data, {
|
||||
status: props.status,
|
||||
stakeAccountKind: props.stakeAccountKind,
|
||||
requireStatus: props.requireStatus ?? true,
|
||||
});
|
||||
|
||||
if (!eligible) return null;
|
||||
|
||||
return (
|
||||
<>
|
||||
@ -54,7 +59,12 @@ export function ShareResultButton({
|
||||
<ShareRoundedIcon fontSize="inherit" />
|
||||
</IconButton>
|
||||
</Tooltip>
|
||||
<ShareResultDialog open={open} betId={betId} onClose={() => setOpen(false)} />
|
||||
<ShareResultDialog
|
||||
open={open}
|
||||
betId={props.kind === 'wallet' ? null : props.betId}
|
||||
transactionId={props.kind === 'wallet' ? props.transactionId : null}
|
||||
onClose={() => setOpen(false)}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
@ -1,27 +1,46 @@
|
||||
/**
|
||||
* Visual Share Card for prediction results (exported to PNG for social share).
|
||||
* Visual Share Cards for prediction results and wallet operations.
|
||||
*/
|
||||
import type { Ref } from 'react';
|
||||
import type { ReactNode, Ref } from 'react';
|
||||
import { Box, Stack, Typography } from '@mui/material';
|
||||
import QRCode from 'react-qr-code';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { PrediqoLogo } from '../../shared/brand/PrediqoLogo';
|
||||
import type { ShareCardPayload } from './types';
|
||||
import type { ShareCardPayload, ShareCardPredictionPayload, ShareCardWalletPayload } from './types';
|
||||
|
||||
type Props = {
|
||||
payload: ShareCardPayload;
|
||||
cardRef?: Ref<HTMLDivElement>;
|
||||
};
|
||||
|
||||
const OUTCOME_COLOR: Record<ShareCardPayload['status'], string> = {
|
||||
const PREDICTION_COLOR: Record<ShareCardPredictionPayload['status'], string> = {
|
||||
won: '#3DDC97',
|
||||
lost: '#FF6B6B',
|
||||
refunded: '#FFB020',
|
||||
};
|
||||
|
||||
const OP_COLOR: Record<ShareCardWalletPayload['operationType'], string> = {
|
||||
deposit: '#3DDC97',
|
||||
withdrawal: '#5EB2D6',
|
||||
transfer: '#C4A4FF',
|
||||
};
|
||||
|
||||
export function ShareResultCard({ payload, cardRef }: Props) {
|
||||
if (payload.kind === 'wallet') {
|
||||
return <WalletOpCard payload={payload} cardRef={cardRef} />;
|
||||
}
|
||||
return <PredictionCard payload={payload} cardRef={cardRef} />;
|
||||
}
|
||||
|
||||
function PredictionCard({
|
||||
payload,
|
||||
cardRef,
|
||||
}: {
|
||||
payload: ShareCardPredictionPayload;
|
||||
cardRef?: Ref<HTMLDivElement>;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const accent = OUTCOME_COLOR[payload.status];
|
||||
const accent = PREDICTION_COLOR[payload.status];
|
||||
const directionLabel =
|
||||
payload.predictionMode === 'multi_candle' && payload.sequence?.length
|
||||
? payload.sequence.map((d) => t(`shareCard.direction.${d}`)).join(' → ')
|
||||
@ -29,28 +48,7 @@ export function ShareResultCard({ payload, cardRef }: Props) {
|
||||
const settled = new Date(payload.settledAt);
|
||||
|
||||
return (
|
||||
<Box
|
||||
ref={cardRef}
|
||||
sx={{
|
||||
width: 420,
|
||||
maxWidth: '100%',
|
||||
borderRadius: 3,
|
||||
overflow: 'hidden',
|
||||
background:
|
||||
'linear-gradient(155deg, #0B1220 0%, #142033 45%, #0E1A2B 100%)',
|
||||
border: '1px solid rgba(255,255,255,0.12)',
|
||||
color: '#F5F7FA',
|
||||
p: 2.5,
|
||||
boxSizing: 'border-box',
|
||||
}}
|
||||
>
|
||||
<Stack direction="row" sx={{ justifyContent: 'space-between', alignItems: 'center', mb: 2 }}>
|
||||
<PrediqoLogo variant="wordmark" size={36} wordmarkSx={{ color: '#F5F7FA' }} />
|
||||
<Typography variant="caption" sx={{ opacity: 0.7, fontWeight: 700, letterSpacing: 0.6 }}>
|
||||
{payload.gameName}
|
||||
</Typography>
|
||||
</Stack>
|
||||
|
||||
<CardShell cardRef={cardRef} title={payload.gameName}>
|
||||
<Typography
|
||||
sx={{
|
||||
fontSize: 42,
|
||||
@ -66,11 +64,9 @@ export function ShareResultCard({ payload, cardRef }: Props) {
|
||||
USDT
|
||||
</Typography>
|
||||
</Typography>
|
||||
|
||||
<Typography sx={{ fontWeight: 800, color: accent, mb: 2 }}>
|
||||
{t(`shareCard.status.${payload.status}`)}
|
||||
</Typography>
|
||||
|
||||
<Stack spacing={0.75} sx={{ mb: 2.5 }}>
|
||||
<Row label={t('shareCard.prediction')} value={directionLabel} />
|
||||
<Row
|
||||
@ -80,50 +76,134 @@ export function ShareResultCard({ payload, cardRef }: Props) {
|
||||
<Row label={t('shareCard.stake')} value={`${payload.stakeDisplay} USDT`} />
|
||||
<Row
|
||||
label={t('shareCard.settledAt')}
|
||||
value={settled.toLocaleString(undefined, {
|
||||
dateStyle: 'medium',
|
||||
timeStyle: 'short',
|
||||
})}
|
||||
value={settled.toLocaleString(undefined, { dateStyle: 'medium', timeStyle: 'short' })}
|
||||
/>
|
||||
{payload.isAuto ? <Row label={t('shareCard.mode')} value={t('shareCard.modeAuto')} /> : null}
|
||||
{payload.predictionMode === 'multi_candle' ? (
|
||||
<Row label={t('shareCard.mode')} value={t('shareCard.modeMulti')} />
|
||||
) : null}
|
||||
</Stack>
|
||||
<VerifyFooter verifyUrl={payload.verifyUrl} />
|
||||
</CardShell>
|
||||
);
|
||||
}
|
||||
|
||||
<Stack
|
||||
direction="row"
|
||||
spacing={2}
|
||||
function WalletOpCard({
|
||||
payload,
|
||||
cardRef,
|
||||
}: {
|
||||
payload: ShareCardWalletPayload;
|
||||
cardRef?: Ref<HTMLDivElement>;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const accent = OP_COLOR[payload.operationType];
|
||||
const created = new Date(payload.createdAt);
|
||||
|
||||
return (
|
||||
<CardShell cardRef={cardRef} title="Prediqo Wallet">
|
||||
<Typography
|
||||
sx={{
|
||||
alignItems: 'center',
|
||||
pt: 1.5,
|
||||
borderTop: '1px solid rgba(255,255,255,0.1)',
|
||||
fontSize: 42,
|
||||
fontWeight: 900,
|
||||
lineHeight: 1.05,
|
||||
color: accent,
|
||||
letterSpacing: 0.5,
|
||||
mb: 1,
|
||||
}}
|
||||
>
|
||||
<Box
|
||||
sx={{
|
||||
p: 1,
|
||||
borderRadius: 1.5,
|
||||
backgroundColor: '#fff',
|
||||
display: 'grid',
|
||||
placeItems: 'center',
|
||||
}}
|
||||
>
|
||||
<QRCode value={payload.verifyUrl} size={72} />
|
||||
</Box>
|
||||
<Box sx={{ flex: 1, minWidth: 0 }}>
|
||||
<Typography variant="caption" sx={{ fontWeight: 800, display: 'block' }}>
|
||||
{t('shareCard.verifyTitle')}
|
||||
</Typography>
|
||||
<Typography variant="caption" sx={{ opacity: 0.7 }}>
|
||||
{t('shareCard.verifyHint')}
|
||||
</Typography>
|
||||
</Box>
|
||||
{payload.amountSignedDisplay}{' '}
|
||||
<Typography component="span" sx={{ fontSize: 18, fontWeight: 700, opacity: 0.85 }}>
|
||||
{payload.assetSymbol}
|
||||
</Typography>
|
||||
</Typography>
|
||||
<Typography sx={{ fontWeight: 800, color: accent, mb: 2 }}>
|
||||
{t(`shareCard.operationType.${payload.operationType}`)}
|
||||
</Typography>
|
||||
<Stack spacing={0.75} sx={{ mb: 2.5 }}>
|
||||
<Row
|
||||
label={t('shareCard.txStatus')}
|
||||
value={t(`shareCard.txStatusLabel.${payload.status}`, {
|
||||
defaultValue: payload.status,
|
||||
})}
|
||||
/>
|
||||
<Row label={t('shareCard.asset')} value={payload.assetName} />
|
||||
{payload.network ? <Row label={t('shareCard.network')} value={payload.network} /> : null}
|
||||
<Row
|
||||
label={t('shareCard.date')}
|
||||
value={created.toLocaleString(undefined, { dateStyle: 'medium', timeStyle: 'short' })}
|
||||
/>
|
||||
</Stack>
|
||||
<VerifyFooter verifyUrl={payload.verifyUrl} />
|
||||
</CardShell>
|
||||
);
|
||||
}
|
||||
|
||||
function CardShell({
|
||||
children,
|
||||
cardRef,
|
||||
title,
|
||||
}: {
|
||||
children: ReactNode;
|
||||
cardRef?: Ref<HTMLDivElement>;
|
||||
title: string;
|
||||
}) {
|
||||
return (
|
||||
<Box
|
||||
ref={cardRef}
|
||||
sx={{
|
||||
width: 420,
|
||||
maxWidth: '100%',
|
||||
borderRadius: 3,
|
||||
overflow: 'hidden',
|
||||
background: 'linear-gradient(155deg, #0B1220 0%, #142033 45%, #0E1A2B 100%)',
|
||||
border: '1px solid rgba(255,255,255,0.12)',
|
||||
color: '#F5F7FA',
|
||||
p: 2.5,
|
||||
boxSizing: 'border-box',
|
||||
}}
|
||||
>
|
||||
<Stack direction="row" sx={{ justifyContent: 'space-between', alignItems: 'center', mb: 2 }}>
|
||||
<PrediqoLogo variant="wordmark" size={36} wordmarkSx={{ color: '#F5F7FA' }} />
|
||||
<Typography variant="caption" sx={{ opacity: 0.7, fontWeight: 700, letterSpacing: 0.6 }}>
|
||||
{title}
|
||||
</Typography>
|
||||
</Stack>
|
||||
{children}
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
function VerifyFooter({ verifyUrl }: { verifyUrl: string }) {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<Stack
|
||||
direction="row"
|
||||
spacing={2}
|
||||
sx={{ alignItems: 'center', pt: 1.5, borderTop: '1px solid rgba(255,255,255,0.1)' }}
|
||||
>
|
||||
<Box
|
||||
sx={{
|
||||
p: 1,
|
||||
borderRadius: 1.5,
|
||||
backgroundColor: '#fff',
|
||||
display: 'grid',
|
||||
placeItems: 'center',
|
||||
}}
|
||||
>
|
||||
<QRCode value={verifyUrl} size={72} />
|
||||
</Box>
|
||||
<Box sx={{ flex: 1, minWidth: 0 }}>
|
||||
<Typography variant="caption" sx={{ fontWeight: 800, display: 'block' }}>
|
||||
{t('shareCard.verifyTitle')}
|
||||
</Typography>
|
||||
<Typography variant="caption" sx={{ opacity: 0.7 }}>
|
||||
{t('shareCard.verifyHint')}
|
||||
</Typography>
|
||||
</Box>
|
||||
</Stack>
|
||||
);
|
||||
}
|
||||
|
||||
function Row({ label, value }: { label: string; value: string }) {
|
||||
return (
|
||||
<Stack direction="row" spacing={2} sx={{ justifyContent: 'space-between' }}>
|
||||
|
||||
@ -1,5 +1,5 @@
|
||||
/**
|
||||
* Preview dialog: load share payload, show card, then share/download PNG.
|
||||
* Preview dialog: load share payload (prediction or wallet op), then share/download PNG.
|
||||
*/
|
||||
import CloseRoundedIcon from '@mui/icons-material/CloseRounded';
|
||||
import DownloadRoundedIcon from '@mui/icons-material/DownloadRounded';
|
||||
@ -22,13 +22,16 @@ import { useEffect, useRef, useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import axios from 'axios';
|
||||
import { copyTextToClipboard } from '../../shared/utils/clipboard';
|
||||
import { fetchShareCardPayload } from './hooks';
|
||||
import { fetchShareCardPayload, fetchWalletShareCardPayload } from './hooks';
|
||||
import { ShareResultCard } from './ShareResultCard';
|
||||
import type { ShareCardPayload } from './types';
|
||||
|
||||
type Props = {
|
||||
open: boolean;
|
||||
betId: string | null;
|
||||
/** Prediction bet id */
|
||||
betId?: string | null;
|
||||
/** Wallet transaction id */
|
||||
transactionId?: string | null;
|
||||
onClose: () => void;
|
||||
};
|
||||
|
||||
@ -69,7 +72,7 @@ async function shareOrDownloadPng(blob: Blob, filename: string, verifyUrl: strin
|
||||
await copyTextToClipboard(verifyUrl);
|
||||
}
|
||||
|
||||
export function ShareResultDialog({ open, betId, onClose }: Props) {
|
||||
export function ShareResultDialog({ open, betId, transactionId, onClose }: Props) {
|
||||
const { t } = useTranslation();
|
||||
const cardRef = useRef<HTMLDivElement>(null);
|
||||
const [payload, setPayload] = useState<ShareCardPayload | null>(null);
|
||||
@ -79,7 +82,7 @@ export function ShareResultDialog({ open, betId, onClose }: Props) {
|
||||
const [hint, setHint] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (!open || !betId) {
|
||||
if (!open || (!betId && !transactionId)) {
|
||||
setPayload(null);
|
||||
setError(null);
|
||||
setHint(null);
|
||||
@ -88,7 +91,10 @@ export function ShareResultDialog({ open, betId, onClose }: Props) {
|
||||
let cancelled = false;
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
void fetchShareCardPayload(betId)
|
||||
const loader = transactionId
|
||||
? fetchWalletShareCardPayload(transactionId)
|
||||
: fetchShareCardPayload(betId!);
|
||||
void loader
|
||||
.then((data) => {
|
||||
if (!cancelled) setPayload(data);
|
||||
})
|
||||
@ -104,7 +110,7 @@ export function ShareResultDialog({ open, betId, onClose }: Props) {
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [open, betId, t]);
|
||||
}, [open, betId, transactionId, t]);
|
||||
|
||||
const exportPng = async (share: boolean) => {
|
||||
if (!cardRef.current || !payload) return;
|
||||
@ -118,7 +124,12 @@ export function ShareResultDialog({ open, betId, onClose }: Props) {
|
||||
});
|
||||
const res = await fetch(dataUrl);
|
||||
const blob = await res.blob();
|
||||
const filename = `prediqo-${payload.status}-${payload.betId.slice(0, 8)}.png`;
|
||||
const id =
|
||||
payload.kind === 'wallet'
|
||||
? payload.transactionId.slice(0, 8)
|
||||
: payload.betId.slice(0, 8);
|
||||
const tag = payload.kind === 'wallet' ? payload.operationType : payload.status;
|
||||
const filename = `prediqo-${tag}-${id}.png`;
|
||||
if (share) {
|
||||
await shareOrDownloadPng(blob, filename, payload.verifyUrl);
|
||||
setHint(t('shareCard.sharedOrDownloaded'));
|
||||
|
||||
@ -1,5 +1,5 @@
|
||||
/**
|
||||
* Public authenticity page for shared prediction result cards.
|
||||
* Public authenticity page for shared prediction / wallet operation cards.
|
||||
*/
|
||||
import {
|
||||
Alert,
|
||||
@ -42,6 +42,8 @@ export function ShareResultVerifyPage() {
|
||||
},
|
||||
});
|
||||
|
||||
const data = q.data;
|
||||
|
||||
return (
|
||||
<Box
|
||||
sx={{
|
||||
@ -66,32 +68,45 @@ export function ShareResultVerifyPage() {
|
||||
{errorMessage(q.error, t('shareCard.verifyInvalid'))}
|
||||
</Alert>
|
||||
)}
|
||||
{q.data && (
|
||||
{data?.kind === 'prediction' && (
|
||||
<>
|
||||
<Alert severity="success">{t('shareCard.verifyAuthentic')}</Alert>
|
||||
<Typography sx={{ fontSize: 36, fontWeight: 900 }}>
|
||||
{q.data.resultSignedDisplay} USDT
|
||||
{data.resultSignedDisplay} USDT
|
||||
</Typography>
|
||||
<Typography sx={{ fontWeight: 700 }}>
|
||||
{t(`shareCard.status.${q.data.status}`)} · {q.data.gameName}
|
||||
{t(`shareCard.status.${data.status}`)} · {data.gameName}
|
||||
</Typography>
|
||||
<Typography variant="body2" color="text.secondary">
|
||||
{t(`shareCard.direction.${q.data.direction}`)} ·{' '}
|
||||
{t('shareCard.intervalValue', { minutes: q.data.intervalMinutes })} ·{' '}
|
||||
{new Date(q.data.settledAt).toLocaleString()}
|
||||
{t(`shareCard.direction.${data.direction}`)} ·{' '}
|
||||
{t('shareCard.intervalValue', { minutes: data.intervalMinutes })} ·{' '}
|
||||
{new Date(data.settledAt).toLocaleString()}
|
||||
</Typography>
|
||||
<Button
|
||||
component={RouterLink}
|
||||
to={
|
||||
q.data.referralCode
|
||||
? `/register?ref=${encodeURIComponent(q.data.referralCode)}`
|
||||
: '/register'
|
||||
}
|
||||
variant="contained"
|
||||
fullWidth
|
||||
>
|
||||
{t('shareCard.joinCta')}
|
||||
</Button>
|
||||
<JoinButton referralCode={data.referralCode} />
|
||||
</>
|
||||
)}
|
||||
{data?.kind === 'wallet' && (
|
||||
<>
|
||||
<Alert severity="success">{t('shareCard.verifyAuthentic')}</Alert>
|
||||
<Typography sx={{ fontSize: 36, fontWeight: 900 }}>
|
||||
{data.amountSignedDisplay} {data.assetSymbol}
|
||||
</Typography>
|
||||
<Typography sx={{ fontWeight: 700 }}>
|
||||
{t(`shareCard.operationType.${data.operationType}`)} ·{' '}
|
||||
{t(`shareCard.txStatusLabel.${data.status}`, { defaultValue: data.status })}
|
||||
</Typography>
|
||||
<Typography variant="body2" color="text.secondary">
|
||||
{data.network ? `${data.network} · ` : ''}
|
||||
{new Date(data.createdAt).toLocaleString()}
|
||||
</Typography>
|
||||
<JoinButton referralCode={data.referralCode} />
|
||||
</>
|
||||
)}
|
||||
{/* Legacy responses without kind field (older prediction tokens) */}
|
||||
{data && !('kind' in data) && (
|
||||
<>
|
||||
<Alert severity="success">{t('shareCard.verifyAuthentic')}</Alert>
|
||||
<JoinButton referralCode={(data as { referralCode?: string | null }).referralCode ?? null} />
|
||||
</>
|
||||
)}
|
||||
</Stack>
|
||||
@ -99,3 +114,17 @@ export function ShareResultVerifyPage() {
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
function JoinButton({ referralCode }: { referralCode: string | null }) {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<Button
|
||||
component={RouterLink}
|
||||
to={referralCode ? `/register?ref=${encodeURIComponent(referralCode)}` : '/register'}
|
||||
variant="contained"
|
||||
fullWidth
|
||||
>
|
||||
{t('shareCard.joinCta')}
|
||||
</Button>
|
||||
);
|
||||
}
|
||||
|
||||
@ -18,3 +18,12 @@ export async function fetchShareCardPayload(betId: string): Promise<ShareCardPay
|
||||
const res = await api.get<ShareCardPayload>(`/api/v1/share-cards/bets/${betId}`);
|
||||
return res.data;
|
||||
}
|
||||
|
||||
export async function fetchWalletShareCardPayload(
|
||||
transactionId: string
|
||||
): Promise<ShareCardPayload> {
|
||||
const res = await api.get<ShareCardPayload>(
|
||||
`/api/v1/share-cards/transactions/${transactionId}`
|
||||
);
|
||||
return res.data;
|
||||
}
|
||||
|
||||
@ -6,10 +6,15 @@ export type ShareCardConfig = {
|
||||
allowWon: boolean;
|
||||
allowLost: boolean;
|
||||
allowRefunded: boolean;
|
||||
walletOpsEnabled: boolean;
|
||||
allowDeposit: boolean;
|
||||
allowWithdrawal: boolean;
|
||||
allowTransfer: boolean;
|
||||
updatedAt?: string;
|
||||
};
|
||||
|
||||
export type ShareCardPayload = {
|
||||
export type ShareCardPredictionPayload = {
|
||||
kind: 'prediction';
|
||||
betId: string;
|
||||
gameName: string;
|
||||
direction: 'short' | 'long';
|
||||
@ -33,23 +38,62 @@ export type ShareCardPayload = {
|
||||
registerUrl: string;
|
||||
};
|
||||
|
||||
export type ShareCardVerifyPayload = {
|
||||
authentic: true;
|
||||
gameName: string;
|
||||
direction: 'short' | 'long';
|
||||
sequence: ('short' | 'long')[] | null;
|
||||
multiLevel: number | null;
|
||||
predictionMode: string;
|
||||
status: 'won' | 'lost' | 'refunded';
|
||||
resultSignedDisplay: string;
|
||||
stakeDisplay: number;
|
||||
intervalMinutes: number;
|
||||
settledAt: string;
|
||||
registerUrl: string;
|
||||
export type ShareCardWalletPayload = {
|
||||
kind: 'wallet';
|
||||
transactionId: string;
|
||||
operationType: 'deposit' | 'withdrawal' | 'transfer';
|
||||
status: string;
|
||||
amountRaw: string;
|
||||
amountDisplay: string;
|
||||
amountSignedDisplay: string;
|
||||
feeRaw: string;
|
||||
assetCode: string;
|
||||
assetSymbol: string;
|
||||
assetName: string;
|
||||
network: string | null;
|
||||
createdAt: string;
|
||||
blockchainTxId: string | null;
|
||||
verifyUrl: string;
|
||||
verifyToken: string;
|
||||
referralCode: string | null;
|
||||
registerUrl: string;
|
||||
};
|
||||
|
||||
export function isShareEligibleClient(
|
||||
export type ShareCardPayload = ShareCardPredictionPayload | ShareCardWalletPayload;
|
||||
|
||||
export type ShareCardVerifyPayload =
|
||||
| {
|
||||
authentic: true;
|
||||
kind: 'prediction';
|
||||
gameName: string;
|
||||
direction: 'short' | 'long';
|
||||
sequence: ('short' | 'long')[] | null;
|
||||
multiLevel: number | null;
|
||||
predictionMode: string;
|
||||
status: 'won' | 'lost' | 'refunded';
|
||||
resultSignedDisplay: string;
|
||||
stakeDisplay: number;
|
||||
intervalMinutes: number;
|
||||
settledAt: string;
|
||||
registerUrl: string;
|
||||
referralCode: string | null;
|
||||
}
|
||||
| {
|
||||
authentic: true;
|
||||
kind: 'wallet';
|
||||
operationType: 'deposit' | 'withdrawal' | 'transfer';
|
||||
status: string;
|
||||
amountSignedDisplay: string;
|
||||
amountDisplay: string;
|
||||
assetSymbol: string;
|
||||
assetCode: string;
|
||||
network: string | null;
|
||||
createdAt: string;
|
||||
registerUrl: string;
|
||||
referralCode: string | null;
|
||||
};
|
||||
|
||||
export function isPredictionShareEligible(
|
||||
config: ShareCardConfig | null | undefined,
|
||||
input: { stakeAccountKind?: string | null; status?: string | null; requireStatus?: boolean }
|
||||
): boolean {
|
||||
@ -61,7 +105,6 @@ export function isShareEligibleClient(
|
||||
|
||||
const status = input.status;
|
||||
if (!status) {
|
||||
// Wallet activity may not know outcome yet; allow button if wallets pass.
|
||||
return input.requireStatus === false;
|
||||
}
|
||||
if (status !== 'won' && status !== 'lost' && status !== 'refunded') return false;
|
||||
@ -70,3 +113,17 @@ export function isShareEligibleClient(
|
||||
if (status === 'refunded' && !config.allowRefunded) return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
export function isWalletOpShareEligible(
|
||||
config: ShareCardConfig | null | undefined,
|
||||
operationType: string
|
||||
): boolean {
|
||||
if (!config?.enabled || !config.walletOpsEnabled) return false;
|
||||
if (operationType === 'deposit') return config.allowDeposit;
|
||||
if (operationType === 'withdrawal') return config.allowWithdrawal;
|
||||
if (operationType === 'transfer') return config.allowTransfer;
|
||||
return false;
|
||||
}
|
||||
|
||||
/** @deprecated use isPredictionShareEligible */
|
||||
export const isShareEligibleClient = isPredictionShareEligible;
|
||||
|
||||
@ -54,10 +54,18 @@ function predictionShareMeta(tx: WalletTransaction): {
|
||||
if (tx.type === 'game_refund') {
|
||||
return { betId, status: 'refunded', stakeAccountKind };
|
||||
}
|
||||
// Stake row: outcome unknown until settle (lost has no payout row).
|
||||
return { betId, stakeAccountKind };
|
||||
}
|
||||
|
||||
function walletOpShareMeta(
|
||||
tx: WalletTransaction
|
||||
): { transactionId: string; operationType: 'deposit' | 'withdrawal' | 'transfer' } | null {
|
||||
if (tx.type === 'deposit' || tx.type === 'withdrawal' || tx.type === 'transfer') {
|
||||
return { transactionId: tx.id, operationType: tx.type };
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Maps wallet_type_id to wallet type metadata for display. */
|
||||
function walletTypeById(
|
||||
balances: BalanceEntry[],
|
||||
@ -142,7 +150,8 @@ export function TransactionList({
|
||||
const credit = isCredit(tx);
|
||||
const [c1, c2] = coinColors(code);
|
||||
const human = rawToHuman(tx.amount, decimals);
|
||||
const share = predictionShareMeta(tx);
|
||||
const predictionShare = predictionShareMeta(tx);
|
||||
const walletShare = walletOpShareMeta(tx);
|
||||
|
||||
return (
|
||||
<TableRow key={tx.id} hover>
|
||||
@ -200,12 +209,18 @@ export function TransactionList({
|
||||
</Typography>
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
{share ? (
|
||||
{predictionShare ? (
|
||||
<ShareResultButton
|
||||
betId={share.betId}
|
||||
status={share.status}
|
||||
stakeAccountKind={share.stakeAccountKind}
|
||||
requireStatus={Boolean(share.status)}
|
||||
betId={predictionShare.betId}
|
||||
status={predictionShare.status}
|
||||
stakeAccountKind={predictionShare.stakeAccountKind}
|
||||
requireStatus={Boolean(predictionShare.status)}
|
||||
/>
|
||||
) : walletShare ? (
|
||||
<ShareResultButton
|
||||
kind="wallet"
|
||||
transactionId={walletShare.transactionId}
|
||||
operationType={walletShare.operationType}
|
||||
/>
|
||||
) : null}
|
||||
</TableCell>
|
||||
|
||||
@ -234,10 +234,27 @@ export const en = {
|
||||
modeMulti: 'Multi-candle',
|
||||
verifyTitle: 'Scan to verify',
|
||||
verifyHint: 'Authentic Prediqo result',
|
||||
verifyPageTitle: 'Verified prediction result',
|
||||
verifyAuthentic: 'This Prediqo result is authentic.',
|
||||
verifyPageTitle: 'Verified Prediqo share',
|
||||
verifyAuthentic: 'This Prediqo share is authentic.',
|
||||
verifyInvalid: 'This share link is invalid or no longer available.',
|
||||
joinCta: 'Join Prediqo',
|
||||
operation: 'Operation',
|
||||
amount: 'Amount',
|
||||
asset: 'Asset',
|
||||
network: 'Network',
|
||||
date: 'Date',
|
||||
txStatus: 'Status',
|
||||
operationType: {
|
||||
deposit: 'Deposit',
|
||||
withdrawal: 'Withdrawal',
|
||||
transfer: 'Transfer',
|
||||
},
|
||||
txStatusLabel: {
|
||||
pending: 'Pending',
|
||||
confirming: 'Confirming',
|
||||
completed: 'Completed',
|
||||
failed: 'Failed',
|
||||
},
|
||||
status: {
|
||||
won: 'Won',
|
||||
lost: 'Lost',
|
||||
@ -1717,6 +1734,7 @@ export const en = {
|
||||
loadError: 'Failed to load Share Card settings.',
|
||||
globalEnabled: 'Enable Share Cards',
|
||||
globalHelper: 'When off, share buttons are hidden everywhere.',
|
||||
predictionsTitle: 'Prediction results',
|
||||
walletsTitle: 'Allowed stake wallets',
|
||||
allowMain: 'Main wallet',
|
||||
allowBonus: 'Bonus wallet',
|
||||
@ -1725,6 +1743,12 @@ export const en = {
|
||||
allowWon: 'Won',
|
||||
allowLost: 'Lost',
|
||||
allowRefunded: 'Refunded (neutral)',
|
||||
walletOpsTitle: 'Wallet operations',
|
||||
walletOpsEnabled: 'Enable wallet operation sharing',
|
||||
walletOpsHelper: 'Allow users to share deposits, withdrawals, and transfers from Wallet Activity.',
|
||||
allowDeposit: 'Deposits',
|
||||
allowWithdrawal: 'Withdrawals',
|
||||
allowTransfer: 'Transfers',
|
||||
save: 'Save settings',
|
||||
saveFailed: 'Save failed',
|
||||
saved: 'Settings saved.',
|
||||
|
||||
@ -241,10 +241,27 @@ export const fr = {
|
||||
modeMulti: 'Multi-bougies',
|
||||
verifyTitle: 'Scanner pour vérifier',
|
||||
verifyHint: 'Résultat Prediqo authentique',
|
||||
verifyPageTitle: 'Résultat de prédiction vérifié',
|
||||
verifyAuthentic: 'Ce résultat Prediqo est authentique.',
|
||||
verifyPageTitle: 'Partage Prediqo vérifié',
|
||||
verifyAuthentic: 'Ce partage Prediqo est authentique.',
|
||||
verifyInvalid: 'Ce lien de partage est invalide ou n’est plus disponible.',
|
||||
joinCta: 'Rejoindre Prediqo',
|
||||
operation: 'Opération',
|
||||
amount: 'Montant',
|
||||
asset: 'Actif',
|
||||
network: 'Réseau',
|
||||
date: 'Date',
|
||||
txStatus: 'Statut',
|
||||
operationType: {
|
||||
deposit: 'Dépôt',
|
||||
withdrawal: 'Retrait',
|
||||
transfer: 'Transfert',
|
||||
},
|
||||
txStatusLabel: {
|
||||
pending: 'En attente',
|
||||
confirming: 'Confirmation',
|
||||
completed: 'Réussi',
|
||||
failed: 'Échoué',
|
||||
},
|
||||
status: {
|
||||
won: 'Gagné',
|
||||
lost: 'Perdu',
|
||||
@ -1733,6 +1750,7 @@ export const fr = {
|
||||
loadError: 'Impossible de charger les paramètres Share Cards.',
|
||||
globalEnabled: 'Activer les Share Cards',
|
||||
globalHelper: 'Si désactivé, les boutons de partage sont masqués partout.',
|
||||
predictionsTitle: 'Résultats de prédiction',
|
||||
walletsTitle: 'Wallets de mise autorisés',
|
||||
allowMain: 'Wallet principal',
|
||||
allowBonus: 'Wallet bonus',
|
||||
@ -1741,6 +1759,13 @@ export const fr = {
|
||||
allowWon: 'Gagné',
|
||||
allowLost: 'Perdu',
|
||||
allowRefunded: 'Remboursé (neutre)',
|
||||
walletOpsTitle: 'Opérations Wallet',
|
||||
walletOpsEnabled: 'Activer le partage des opérations Wallet',
|
||||
walletOpsHelper:
|
||||
'Autoriser les utilisateurs à partager dépôts, retraits et transferts depuis l’Activity du Wallet.',
|
||||
allowDeposit: 'Dépôts',
|
||||
allowWithdrawal: 'Retraits',
|
||||
allowTransfer: 'Transferts',
|
||||
save: 'Enregistrer les paramètres',
|
||||
saveFailed: 'Échec de l’enregistrement',
|
||||
saved: 'Paramètres enregistrés.',
|
||||
|
||||
Loading…
Reference in New Issue
Block a user