feat: productionize paid modes and PvP capture

This commit is contained in:
jwinterm
2026-07-21 20:41:27 -04:00
parent 8fb284f8ed
commit 89398335c7
230 changed files with 31755 additions and 2777 deletions
+187
View File
@@ -0,0 +1,187 @@
/**
* Public commerce disclosures and paid-action acknowledgement validation.
*
* This is a product safety control, not a jurisdiction or identity check. The server derives
* the words shown to players from the active runtime switches, and independently refuses paid
* actions unless the browser echoes the current policy version and every required acknowledgement.
*/
const DEFAULT_POLICY_VERSION = '2026-07-21';
const DEFAULT_MINIMUM_AGE = 18;
const ALLOWED_CONTACT_PROTOCOLS = new Set(['https:', 'http:', 'mailto:']);
const ACKNOWLEDGEMENT_KEYS = new Set([
'policyVersion',
'ageEligible',
'termsRead',
'riskAccepted',
'testnetUnderstood'
]);
function isTrue(value) {
return ['true', '1', 'yes', 'on'].includes(String(value || '').trim().toLowerCase());
}
function minimumAge(env = process.env) {
const value = Number(env.MINIMUM_AGE);
return Number.isInteger(value) && value >= 18 && value <= 120
? value
: DEFAULT_MINIMUM_AGE;
}
function safeContactUrl(value) {
const raw = String(value || '').trim();
if (!raw) return null;
try {
const parsed = new URL(raw);
return ALLOWED_CONTACT_PROTOCOLS.has(parsed.protocol) ? parsed.href : null;
} catch (_) {
return null;
}
}
function paidAcknowledgementRequired(env, gameModeManager) {
// Payment intake can be paused while already-purchased prestige credits remain spendable in
// PvP. Keep the public browser policy enabled for that value-bearing action too; free actions
// bypass the acknowledgement explicitly at their individual server handlers.
let matchEconomies = null;
try {
matchEconomies = gameModeManager?._getMatchEconomies?.() || null;
} catch (_) {
// Public disclosure generation must remain available during partial startup. The
// conservative fallback below still treats an enabled paid product as value-bearing.
matchEconomies = null;
}
const matchCanConsumePaidEntitlement = matchEconomies
? Boolean(matchEconomies.credits_prestige || matchEconomies.crypto_race)
: Boolean(
gameModeManager?.creditsModeEnabled
|| gameModeManager?.directModeEnabled
|| gameModeManager?.freePlayEnabled
);
const paidMatchEconomyAvailable = isTrue(env.MATCH_ENABLED)
&& matchCanConsumePaidEntitlement;
const paidSoloEntitlementAvailable = Boolean(
gameModeManager?.creditsModeEnabled || gameModeManager?.directModeEnabled
);
const productionPaid = String(env.NODE_ENV || '').toLowerCase() === 'production'
&& Boolean(
gameModeManager?.paymentsEnabled
|| paidSoloEntitlementAvailable
|| paidMatchEconomyAvailable
);
return productionPaid || isTrue(env.PAID_ACKNOWLEDGEMENT_REQUIRED);
}
function buildCommerceDisclosure(gameModeManager, env = process.env) {
const cryptoType = String(gameModeManager?.cryptoType || env.CRYPTO_TYPE || 'WOW').toUpperCase();
const network = String(gameModeManager?.network || env.MONERO_NETWORK || 'mainnet').toLowerCase();
const isTestNetwork = Boolean(gameModeManager?.isTestNetwork)
|| (cryptoType === 'XMR' && network !== 'mainnet');
const paymentsEnabled = Boolean(gameModeManager?.paymentsEnabled);
const directEnabled = paymentsEnabled && Boolean(gameModeManager?.directModeEnabled);
const creditsEnabled = paymentsEnabled && Boolean(gameModeManager?.creditsModeEnabled);
// A stale subordinate payout flag for a disabled product must not be advertised as an active
// reward. Runtime startup policy uses the same mode-enabled distinction.
const directPayouts = directEnabled
&& Boolean(gameModeManager?.isPayoutEnabledForMode?.('PAID_SINGLE'));
const creditsPayouts = creditsEnabled
&& Boolean(gameModeManager?.isPayoutEnabledForMode?.('PAID_CREDITS'));
const cryptoMatchPayouts = isTrue(env.MATCH_ENABLED)
&& isTrue(env.MATCH_CRYPTO_RACE_ENABLED)
&& isTrue(env.MATCH_PAYOUTS_ENABLED)
&& Boolean(gameModeManager?.payoutsEnabled);
const anyPayouts = directPayouts || creditsPayouts || cryptoMatchPayouts;
const currencyLabel = String(gameModeManager?.currencyLabel || (isTestNetwork ? `s${cryptoType}` : cryptoType));
const operatorContactUrl = safeContactUrl(env.OPERATOR_CONTACT_URL);
return Object.freeze({
policyVersion: String(env.LEGAL_POLICY_VERSION || DEFAULT_POLICY_VERSION).trim(),
termsEffectiveDate: String(env.TERMS_EFFECTIVE_DATE || '').trim() || null,
minimumAge: minimumAge(env),
paidAcknowledgementRequired: paidAcknowledgementRequired(env, gameModeManager),
operator: Object.freeze({
name: String(env.OPERATOR_NAME || '').trim() || 'Site operator (identity not configured)',
contactUrl: operatorContactUrl,
contactLabel: String(env.OPERATOR_CONTACT_LABEL || '').trim()
|| (operatorContactUrl ? operatorContactUrl.replace(/^mailto:/, '') : 'Operator contact is not configured')
}),
service: Object.freeze({
gameName: String(gameModeManager?.gameName || 'Wowngeon'),
cryptoType,
currencyLabel,
network,
isTestNetwork,
freePlayEnabled: Boolean(gameModeManager?.freePlayEnabled),
paymentsEnabled,
directPaidEntryEnabled: directEnabled,
paidCreditsEnabled: creditsEnabled,
soloPayoutsEnabled: directPayouts || creditsPayouts,
cryptoMatchPayoutsEnabled: cryptoMatchPayouts,
anyPayoutsEnabled: anyPayouts,
paidPrestigeOnly: (directEnabled || creditsEnabled) && !anyPayouts
}),
notices: Object.freeze({
jurisdiction: String(env.RESTRICTED_LOCATIONS_NOTICE || '').trim() || null,
legalReview: 'These product disclosures are not a legal opinion, licence, or representation that the service is lawful in every location.',
identityControl: 'The acknowledgement records a player statement; it does not verify age, identity, or location.'
}),
links: Object.freeze({
terms: '/terms',
privacy: '/privacy',
responsiblePlay: '/responsible-play'
})
});
}
function validatePaidAcknowledgement(raw, disclosure, options = {}) {
const required = options.required === true || disclosure?.paidAcknowledgementRequired === true;
if (!required) return { ok: true, code: 'NOT_REQUIRED', acknowledgement: null };
if (!raw || typeof raw !== 'object' || Array.isArray(raw)) {
return { ok: false, code: 'PAID_ACK_REQUIRED', message: 'Review and acknowledge the paid-play disclosures before continuing.' };
}
const prototype = Object.getPrototypeOf(raw);
const keys = Object.keys(raw);
if ((prototype !== Object.prototype && prototype !== null)
|| keys.length !== ACKNOWLEDGEMENT_KEYS.size
|| keys.some(key => !ACKNOWLEDGEMENT_KEYS.has(key))) {
return { ok: false, code: 'PAID_ACK_MALFORMED', message: 'The paid-play acknowledgement payload is invalid. Reload the disclosures and try again.' };
}
if (typeof raw.policyVersion !== 'string' || raw.policyVersion.length < 1 || raw.policyVersion.length > 64) {
return { ok: false, code: 'PAID_ACK_MALFORMED', message: 'The paid-play acknowledgement payload is invalid. Reload the disclosures and try again.' };
}
if (String(raw.policyVersion || '') !== String(disclosure.policyVersion || '')) {
return { ok: false, code: 'PAID_ACK_VERSION', message: 'The paid-play disclosures changed. Review the current version before continuing.' };
}
if (typeof raw.ageEligible !== 'boolean'
|| typeof raw.termsRead !== 'boolean'
|| typeof raw.riskAccepted !== 'boolean'
|| typeof raw.testnetUnderstood !== 'boolean') {
return { ok: false, code: 'PAID_ACK_MALFORMED', message: 'The paid-play acknowledgement payload is invalid. Reload the disclosures and try again.' };
}
if (raw.ageEligible !== true || raw.termsRead !== true || raw.riskAccepted !== true) {
return { ok: false, code: 'PAID_ACK_INCOMPLETE', message: 'Every paid-play acknowledgement is required before continuing.' };
}
if (disclosure.service?.isTestNetwork && raw.testnetUnderstood !== true) {
return { ok: false, code: 'PAID_ACK_TESTNET', message: 'Confirm that this test network uses valueless test coins and never send mainnet funds.' };
}
if (!disclosure.service?.isTestNetwork && raw.testnetUnderstood !== false) {
return { ok: false, code: 'PAID_ACK_MALFORMED', message: 'The paid-play acknowledgement payload is invalid. Reload the disclosures and try again.' };
}
const acknowledgement = {
policyVersion: disclosure.policyVersion,
ageEligible: true,
termsRead: true,
riskAccepted: true,
testnetUnderstood: disclosure.service?.isTestNetwork === true
};
return { ok: true, code: 'ACKNOWLEDGED', acknowledgement: Object.freeze(acknowledgement) };
}
module.exports = {
DEFAULT_POLICY_VERSION,
buildCommerceDisclosure,
minimumAge,
paidAcknowledgementRequired,
safeContactUrl,
validatePaidAcknowledgement
};
+558 -51
View File
@@ -1,90 +1,597 @@
/**
* Environment Validator
* Validates payment configuration and emits warnings for suspicious settings.
* Startup configuration validation.
*
* Development remains forgiving so a contributor can boot individual subsystems. Production is
* deliberately fail-closed: an ambiguous money or block-source setting must never silently fall
* back to a dangerous default.
*/
const { isSupported, familyFor } = require('../chain/chainProfile');
const { resolveMatchRuleset } = require('../game/rulesets');
const money = require('../money/atomic');
const {
PG_BIGINT_MAX,
cryptoRulesetSupported,
parseHouseFeeBasisPoints,
parsePositiveAtomic,
playerContract
} = require('../network/matchEconomyPolicy');
const TRUE_VALUES = new Set(['true', '1', 'yes', 'on']);
const BOOLEAN_VALUES = new Set(['true', 'false', '1', '0', 'yes', 'no', 'y', 'n', 'on', 'off']);
const PLACEHOLDER_SECRET = /(change[_-]?me|replace[_-]?with|your[_-]|example|password|secret)/i;
const BOOLEAN_ENV_KEYS = [
'PAYMENTS_ENABLED', 'PAYOUTS_ENABLED', 'DIRECT_PAYMENT_ENABLED',
'DIRECT_PAYOUTS_ENABLED', 'CREDITS_ENABLED', 'CREDITS_PAYOUTS_ENABLED',
'CREDITS_PAYOUT_ENABLED', 'FREE_PLAY_ENABLED', 'DIRECT_REQUIRES_ADDRESS',
'DIRECT_ALLOW_GUEST_PLAY', 'CREDITS_REQUIRES_ADDRESS', 'ALLOW_MIXED_MODE',
'PREFER_CREDITS_FIRST', 'EARLY_ENTRY_ENABLED', 'EARLY_ENTRY_FREE_MODE',
'EARLY_ENTRY_CREDITS_MODE', 'ALLOW_MAINNET_PAYOUTS', 'TRUST_PROXY',
'SMIRK_ENABLED', 'TAVERN_ENABLED', 'MATCH_ENABLED', 'MATCH_CRYPTO_RACE_ENABLED',
'MATCH_PAYOUTS_ENABLED',
'SIMULATED_BLOCKS', 'FORCE_SIMULATED_BLOCKS', 'DEBUG_HOTKEYS',
'PAID_ACKNOWLEDGEMENT_REQUIRED'
];
const ATOMIC_ENV_KEYS = [
'DIRECT_GAME_PRICE', 'SINGLE_GAME_PRICE', 'CREDITS_PACKAGE_PRICE',
'CREDITS_PAYOUT_BASE', 'PAYOUT_MIN_AMOUNT', 'PAYOUT_MAX_PER_GAME',
'CREDITS_PAYOUT_MIN', 'CREDITS_PAYOUT_MAX', 'MAX_CREDIT_PURCHASE_PER_DAY',
'BALANCE_WARN', 'BALANCE_CRITICAL', 'LOW_BALANCE_THRESHOLD', 'MATCH_ENTRY_FEE_ATOMIC',
'MATCH_PAYOUT_MAX'
];
const POSITIVE_ATOMIC_ENV_KEYS = new Set([
'DIRECT_GAME_PRICE', 'SINGLE_GAME_PRICE', 'CREDITS_PACKAGE_PRICE',
'CREDITS_PAYOUT_BASE', 'PAYOUT_MAX_PER_GAME', 'CREDITS_PAYOUT_MAX',
'MAX_CREDIT_PURCHASE_PER_DAY', 'MATCH_ENTRY_FEE_ATOMIC', 'MATCH_PAYOUT_MAX'
]);
function isTrue(value) {
return TRUE_VALUES.has(String(value || '').trim().toLowerCase());
}
function canonicalInteger(value) {
return String(value ?? '').trim().replace(/_/g, '');
}
function raceTicketGrant(product) {
const grants = product?.grants;
if (!grants || typeof grants !== 'object') return null;
const hasEntries = Object.prototype.hasOwnProperty.call(grants, 'race_entries')
|| Object.prototype.hasOwnProperty.call(grants, 'raceEntries');
if (!hasEntries) return null;
return {
productId: String(product.id || '(unnamed)'),
entries: grants.race_entries ?? grants.raceEntries,
valueAtomic: grants.race_entry_value_atomic ?? grants.raceEntryValueAtomic,
price: product.price
};
}
function isLoopbackHost(hostname) {
const normalized = String(hostname || '').replace(/^\[|\]$/g, '').toLowerCase();
return normalized === 'localhost' || normalized === '127.0.0.1' || normalized === '::1';
}
class EnvironmentValidator {
constructor(options = {}) {
this.logger = options.logger || console;
this.env = options.env || process.env;
}
_endpointIssue(name, value) {
if (!value) return `${name} is not set.`;
try {
const endpoint = new URL(value);
if (!['http:', 'https:'].includes(endpoint.protocol)) {
return `${name} must use http:// or https://.`;
}
return null;
} catch (_) {
return `${name} must be a valid URL.`;
}
}
_pushEndpointTransportWarning(warnings, name, value) {
if (!value) return;
try {
const endpoint = new URL(value);
if (endpoint.protocol === 'http:' && !isLoopbackHost(endpoint.hostname)) {
warnings.push(`${name} uses plaintext HTTP on a non-loopback host; use TLS or a private authenticated network.`);
}
} catch (_) {
// Syntax errors are reported separately.
}
}
validate(config) {
const env = this.env;
const warnings = [];
const errors = [];
const production = String(env.NODE_ENV || '').toLowerCase() === 'production';
const paymentsEnabled = Boolean(config?.paymentsEnabled);
const directEnabled = paymentsEnabled && Boolean(config?.modes?.direct?.enabled);
const creditsEnabled = paymentsEnabled && Boolean(config?.modes?.credits?.enabled);
const payoutMasterEnabled = Boolean(config?.payouts?.enabled);
const directPayoutsEnabled = payoutMasterEnabled && directEnabled
&& Boolean(config?.payouts?.rules?.direct?.enabled);
const creditsPayoutsEnabled = payoutMasterEnabled && creditsEnabled
&& Boolean(config?.payouts?.rules?.credits?.enabled);
const matchModeEnabled = isTrue(env.MATCH_ENABLED);
const matchCryptoEnabled = matchModeEnabled && isTrue(env.MATCH_CRYPTO_RACE_ENABLED);
const matchPayoutsEnabled = payoutMasterEnabled && matchCryptoEnabled
&& isTrue(env.MATCH_PAYOUTS_ENABLED);
const anyPayoutsEnabled = directPayoutsEnabled || creditsPayoutsEnabled || matchPayoutsEnabled;
// PAYOUTS_ENABLED also authorizes settlement of already-created durable rows even when
// every admission switch is off, so payout-only recovery has the same wallet boundary.
const walletRequired = paymentsEnabled || payoutMasterEnabled;
const cryptoType = String(env.CRYPTO_TYPE || config?.currency?.symbol || 'WOW').trim().toUpperCase();
const network = String(env.MONERO_NETWORK || 'mainnet').trim().toLowerCase();
// Check for conflicting legacy/new config
if (process.env.GAME_MODE && process.env.PAYMENT_MODES) {
if (env.GAME_MODE && env.PAYMENT_MODES) {
warnings.push('Both GAME_MODE and PAYMENT_MODES are set. PAYMENT_MODES takes precedence.');
}
// Wallet RPC required for payments
if (config.paymentsEnabled && !process.env.PRIMARY_WALLET_ENDPOINT) {
warnings.push('Payments enabled but PRIMARY_WALLET_ENDPOINT not set. Wallet RPC will fail.');
if (!isSupported(cryptoType)) {
errors.push(`CRYPTO_TYPE=${cryptoType || '(empty)'} is not a supported chain profile.`);
} else if (walletRequired && familyFor(cryptoType) !== 'monero') {
errors.push(`Paid production adapters are not implemented for CRYPTO_TYPE=${cryptoType}; use WOW or XMR.`);
}
// Blockchain RPC required for payments
if (config.paymentsEnabled && !process.env.PRIMARY_RPC_ENDPOINT) {
warnings.push('Payments enabled but PRIMARY_RPC_ENDPOINT missing. Block sync will fail.');
if (cryptoType === 'WOW' && network !== 'mainnet') {
errors.push('Wownero only supports MONERO_NETWORK=mainnet.');
}
if (cryptoType === 'XMR' && !['mainnet', 'stagenet', 'testnet'].includes(network)) {
errors.push('MONERO_NETWORK must be mainnet, stagenet, or testnet for XMR.');
}
// Direct mode price validation
if (config.modes.direct.enabled && config.modes.direct.price <= 0n) {
errors.push('Direct payment mode enabled but price is not positive.');
const walletIssue = this._endpointIssue('PRIMARY_WALLET_ENDPOINT', env.PRIMARY_WALLET_ENDPOINT);
if (walletRequired && walletIssue) {
(production ? errors : warnings).push(`Financial workers require a wallet but ${walletIssue}`);
}
// Credits mode package validation
if (config.modes.credits.enabled && !config.modes.credits.packages.length) {
errors.push('Credits mode enabled but no credit packages defined.');
if (Boolean(env.WALLET_RPC_USER) !== Boolean(env.WALLET_RPC_PASSWORD)) {
(production ? errors : warnings).push('WALLET_RPC_USER and WALLET_RPC_PASSWORD must be set together.');
}
// Validate CREDITS_PACKAGES JSON format
if (process.env.CREDITS_PACKAGES) {
if (production && paymentsEnabled) {
if (!isTrue(env.PAID_ACKNOWLEDGEMENT_REQUIRED)) {
errors.push('Production payments require PAID_ACKNOWLEDGEMENT_REQUIRED=true; the server will not accept a paid action without the current acknowledgement.');
}
if (!/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/.test(String(env.LEGAL_POLICY_VERSION || ''))) {
errors.push('LEGAL_POLICY_VERSION must be an explicit 1-64 character version identifier for production payments.');
}
const effectiveDate = String(env.TERMS_EFFECTIVE_DATE || '');
const parsedEffectiveDate = /^\d{4}-\d{2}-\d{2}$/.test(effectiveDate)
? new Date(`${effectiveDate}T00:00:00Z`)
: null;
if (!parsedEffectiveDate || Number.isNaN(parsedEffectiveDate.getTime())
|| parsedEffectiveDate.toISOString().slice(0, 10) !== effectiveDate) {
errors.push('TERMS_EFFECTIVE_DATE must be an explicit valid YYYY-MM-DD date for production payments.');
}
const configuredMinimumAge = Number(env.MINIMUM_AGE);
if (!Number.isInteger(configuredMinimumAge) || configuredMinimumAge < 18 || configuredMinimumAge > 120) {
errors.push('MINIMUM_AGE must be an explicit integer from 18 through 120 for production payments.');
}
const operatorName = String(env.OPERATOR_NAME || '').trim();
if (operatorName.length < 2 || operatorName.length > 120 || PLACEHOLDER_SECRET.test(operatorName)) {
errors.push('OPERATOR_NAME must identify the responsible operator without placeholder text for production payments.');
}
try {
const parsed = JSON.parse(process.env.CREDITS_PACKAGES);
if (!Array.isArray(parsed)) {
const contact = new URL(String(env.OPERATOR_CONTACT_URL || ''));
if (!['https:', 'mailto:'].includes(contact.protocol)) {
errors.push('OPERATOR_CONTACT_URL must use https:// or mailto: for production payments.');
}
if (PLACEHOLDER_SECRET.test(String(env.OPERATOR_CONTACT_URL || ''))) {
errors.push('OPERATOR_CONTACT_URL must not contain placeholder text for production payments.');
}
} catch (_) {
errors.push('OPERATOR_CONTACT_URL must be an explicit valid https:// or mailto: URL for production payments.');
}
}
if (production && walletRequired) {
if (!env.WALLET_RPC_USER || !env.WALLET_RPC_PASSWORD) {
errors.push('Production financial workers require WALLET_RPC_USER and WALLET_RPC_PASSWORD for wallet-rpc Digest authentication.');
} else if (String(env.WALLET_RPC_PASSWORD).length < 24
|| PLACEHOLDER_SECRET.test(String(env.WALLET_RPC_PASSWORD))) {
errors.push('WALLET_RPC_PASSWORD must be a strong non-placeholder secret of at least 24 characters in production.');
}
if (env.PRIMARY_WALLET_ENDPOINT) {
try {
const walletEndpoint = new URL(env.PRIMARY_WALLET_ENDPOINT);
if (walletEndpoint.protocol === 'http:' && !isLoopbackHost(walletEndpoint.hostname)) {
errors.push('Production wallet-rpc over plaintext HTTP must bind to a loopback address.');
}
} catch (_) {
// Endpoint syntax is reported by _endpointIssue above.
}
}
}
if (env.HOSTED_BY) {
try {
const hostedBy = new URL(env.HOSTED_BY);
if (!['http:', 'https:'].includes(hostedBy.protocol)) {
(production ? errors : warnings).push('HOSTED_BY must use http:// or https://.');
}
if (production && hostedBy.protocol !== 'https:') {
errors.push('HOSTED_BY must use https:// in production.');
}
} catch (_) {
(production ? errors : warnings).push('HOSTED_BY must be a valid public URL.');
}
}
const daemonIssue = this._endpointIssue('PRIMARY_RPC_ENDPOINT', env.PRIMARY_RPC_ENDPOINT);
if (production && daemonIssue) {
errors.push(`Production block timing requires a daemon RPC: ${daemonIssue}`);
} else if (paymentsEnabled && daemonIssue) {
warnings.push(`Payments are enabled but ${daemonIssue}`);
}
this._pushEndpointTransportWarning(warnings, 'PRIMARY_WALLET_ENDPOINT', env.PRIMARY_WALLET_ENDPOINT);
this._pushEndpointTransportWarning(warnings, 'PRIMARY_RPC_ENDPOINT', env.PRIMARY_RPC_ENDPOINT);
if (config?.modes?.direct?.enabled && config.modes.direct.price <= 0n) {
errors.push('Direct payment mode is enabled but its price is not positive.');
}
if (config?.modes?.credits?.enabled && !config.modes.credits.packages?.length) {
errors.push('Credits mode is enabled but no credit packages are defined.');
}
if (env.CREDITS_PACKAGES) {
try {
const packages = JSON.parse(env.CREDITS_PACKAGES);
if (!Array.isArray(packages)) {
errors.push('CREDITS_PACKAGES must be a JSON array.');
} else if (parsed.length === 0) {
warnings.push('CREDITS_PACKAGES is an empty array. Using defaults.');
} else if (packages.length === 0) {
errors.push('CREDITS_PACKAGES must not be empty when explicitly configured.');
} else {
// Validate each package has required fields
parsed.forEach((pkg, i) => {
if (!pkg.id) warnings.push(`CREDITS_PACKAGES[${i}] missing "id" field.`);
if (!pkg.credits && pkg.credits !== 0) warnings.push(`CREDITS_PACKAGES[${i}] missing "credits" field.`);
if (!pkg.price) warnings.push(`CREDITS_PACKAGES[${i}] missing "price" field.`);
packages.forEach((pkg, index) => {
if (!pkg || typeof pkg !== 'object') {
errors.push(`CREDITS_PACKAGES[${index}] must be an object.`);
return;
}
if (!pkg.id) errors.push(`CREDITS_PACKAGES[${index}] is missing "id".`);
if (!Number.isInteger(Number(pkg.credits)) || Number(pkg.credits) <= 0) {
errors.push(`CREDITS_PACKAGES[${index}].credits must be a positive integer.`);
}
try {
if (BigInt(pkg.price) <= 0n) throw new Error('not positive');
} catch (_) {
errors.push(`CREDITS_PACKAGES[${index}].price must be a positive atomic-unit integer.`);
}
});
}
} catch (e) {
errors.push(`CREDITS_PACKAGES is not valid JSON: ${e.message}`);
} catch (error) {
errors.push(`CREDITS_PACKAGES is not valid JSON: ${error.message}`);
}
} else if (config.modes.credits.enabled) {
this.logger.info?.('ℹ️ Credits mode enabled with default packages. Set CREDITS_PACKAGES for production.');
} else if (creditsEnabled) {
warnings.push('Credits mode is using built-in package defaults; set CREDITS_PACKAGES explicitly for production pricing.');
}
// Warn if direct payouts enabled but no wallet RPC
if (config.payouts.rules.direct.enabled && !process.env.PRIMARY_WALLET_ENDPOINT) {
warnings.push('DIRECT_PAYOUTS_ENABLED=true but no PRIMARY_WALLET_ENDPOINT. Payouts will fail.');
if (!payoutMasterEnabled
&& (Boolean(config?.payouts?.rules?.direct?.enabled) || Boolean(config?.payouts?.rules?.credits?.enabled))) {
warnings.push('Payout rules are enabled but PAYOUTS_ENABLED is off; the master switch suppresses all payout creation and dispatch.');
}
// Warn if credits payouts enabled but no wallet RPC
if (config.payouts.rules.credits.enabled && !process.env.PRIMARY_WALLET_ENDPOINT) {
warnings.push('CREDITS_PAYOUTS_ENABLED=true but no PRIMARY_WALLET_ENDPOINT. Payouts will fail.');
if (production) {
for (const key of BOOLEAN_ENV_KEYS) {
if (Object.prototype.hasOwnProperty.call(env, key)
&& !BOOLEAN_VALUES.has(String(env[key]).trim().toLowerCase())) {
errors.push(`${key} must be an explicit boolean (true or false).`);
}
}
for (const key of ATOMIC_ENV_KEYS) {
if (!Object.prototype.hasOwnProperty.call(env, key) || env[key] === '') continue;
const raw = canonicalInteger(env[key]);
if (!/^\d+$/.test(raw)) {
errors.push(`${key} must be a non-negative integer in atomic units.`);
continue;
}
try {
if (POSITIVE_ATOMIC_ENV_KEYS.has(key) && BigInt(raw) <= 0n) {
errors.push(`${key} must be greater than zero.`);
}
} catch (_) {
errors.push(`${key} must be a valid atomic-unit integer.`);
}
}
if (env.GAME_MODE && !['FREE', 'PAID_SINGLE', 'PAID_CREDITS'].includes(String(env.GAME_MODE).trim().toUpperCase())) {
errors.push('GAME_MODE must be FREE, PAID_SINGLE, or PAID_CREDITS.');
}
if (env.PAYMENT_MODES) {
const configuredModes = String(env.PAYMENT_MODES).split(',')
.map(mode => mode.trim().toLowerCase()).filter(Boolean);
const invalidModes = configuredModes.filter(mode => !['direct', 'credits'].includes(mode));
if (configuredModes.length === 0 || invalidModes.length > 0) {
errors.push('PAYMENT_MODES must contain only direct and/or credits.');
}
}
for (const key of [
'DIRECT_PAYOUT_ESCAPE', 'DIRECT_PAYOUT_TREASURE',
'CREDITS_PAYOUT_ESCAPE', 'CREDITS_PAYOUT_TREASURE'
]) {
if (!Object.prototype.hasOwnProperty.call(env, key) || env[key] === '') continue;
const multiplier = Number(env[key]);
if (!Number.isFinite(multiplier) || multiplier <= 0) {
errors.push(`${key} must be a finite number greater than zero.`);
}
}
if (Object.prototype.hasOwnProperty.call(env, 'MATCH_HOUSE_FEE_PERCENT')) {
if (parseHouseFeeBasisPoints(env.MATCH_HOUSE_FEE_PERCENT) === null) {
errors.push('MATCH_HOUSE_FEE_PERCENT must be at least 0 and less than 100.');
}
}
if (isTrue(env.TRUST_PROXY)) {
const proxyHops = Number(env.TRUST_PROXY_HOPS || 1);
if (!Number.isInteger(proxyHops) || proxyHops < 1 || proxyHops > 8) {
errors.push('TRUST_PROXY_HOPS must be an integer from 1 through 8.');
}
}
if (matchModeEnabled) {
for (const key of [
'MATCH_PAID_ENTROPY_DELAY_BLOCKS',
'MATCH_PAID_ENTROPY_CONFIRMATIONS'
]) {
const raw = String(env[key] ?? '').trim();
const value = /^\d+$/.test(raw) ? Number(raw) : NaN;
if (!Number.isSafeInteger(value) || value < 2 || value > 100) {
errors.push(`${key} must be an explicit safe integer from 2 through 100 when production match mode is enabled.`);
}
}
}
if (matchCryptoEnabled && !Object.prototype.hasOwnProperty.call(env, 'MATCH_PAYOUTS_ENABLED')) {
errors.push('Production crypto matches require an explicit MATCH_PAYOUTS_ENABLED=true|false setting.');
}
if (isTrue(env.MATCH_PAYOUTS_ENABLED) && !matchCryptoEnabled) {
errors.push('MATCH_PAYOUTS_ENABLED=true requires MATCH_ENABLED=true and MATCH_CRYPTO_RACE_ENABLED=true.');
}
if (matchPayoutsEnabled) {
if (!directEnabled && !creditsEnabled) {
errors.push('Crypto match payouts require at least one enabled paid product mode for race-entry tickets.');
}
const payoutCap = parsePositiveAtomic(env.MATCH_PAYOUT_MAX);
if (payoutCap === null) {
errors.push('MATCH_PAYOUT_MAX must be an explicit positive PostgreSQL BIGINT atomic-unit cap when crypto match payouts are enabled.');
}
const ruleset = resolveMatchRuleset(env.MATCH_RULESET_ID || 'race');
if (!cryptoRulesetSupported(ruleset)) {
errors.push(`MATCH_RULESET_ID=${ruleset.id} does not have supported single-winner crypto payout semantics.`);
}
const requestedMaxRaw = String(env.MATCH_MAX_PLAYERS ?? '').trim();
const requestedMax = /^\d+$/.test(requestedMaxRaw)
? Number(requestedMaxRaw)
: NaN;
const contract = playerContract(ruleset, env.MATCH_MAX_PLAYERS || ruleset.players.max);
if (!Number.isInteger(requestedMax)
|| requestedMax < contract.minPlayers
|| requestedMax > ruleset.players.max
|| requestedMax > 32) {
errors.push(`MATCH_MAX_PLAYERS must be an integer from ${contract.minPlayers} through ${Math.min(32, ruleset.players.max)} for ruleset ${ruleset.id}.`);
}
const entryFee = parsePositiveAtomic(env.MATCH_ENTRY_FEE_ATOMIC);
const feeBasisPoints = parseHouseFeeBasisPoints(env.MATCH_HOUSE_FEE_PERCENT);
if (entryFee === null) {
errors.push('MATCH_ENTRY_FEE_ATOMIC must be an explicit positive PostgreSQL BIGINT atomic-unit value when crypto match payouts are enabled.');
}
if (feeBasisPoints === null) {
errors.push('MATCH_HOUSE_FEE_PERCENT must be explicitly set from 0 (inclusive) to 100 (exclusive) when crypto match payouts are enabled.');
}
const catalog = [
...(config?.modes?.credits?.packages || []),
...(config?.products?.cosmetic || [])
];
const ticketProducts = catalog.map(raceTicketGrant).filter(Boolean);
if (ticketProducts.length === 0) {
errors.push('Crypto match payouts require at least one configured race-entry product with explicit per-ticket atomic backing.');
}
for (const ticket of ticketProducts) {
const rawEntries = String(ticket.entries ?? '').trim();
let ticketEntries = null;
if (/^\d+$/.test(rawEntries)) {
try {
const parsed = BigInt(rawEntries);
if (parsed > 0n && parsed <= 2147483647n) ticketEntries = parsed;
} catch (_) { /* reported below */ }
}
if (ticketEntries === null) {
errors.push(`Race-entry product ${ticket.productId} must grant a positive integer number of tickets.`);
continue;
}
const ticketValue = parsePositiveAtomic(ticket.valueAtomic);
if (ticketValue === null) {
errors.push(`Race-entry product ${ticket.productId} must set grants.race_entry_value_atomic to a positive PostgreSQL BIGINT atomic-unit value.`);
continue;
}
if (entryFee !== null && ticketValue !== entryFee) {
errors.push(`Race-entry product ${ticket.productId} backing must equal MATCH_ENTRY_FEE_ATOMIC (${entryFee} atomic units per ticket).`);
}
const price = parsePositiveAtomic(ticket.price);
const requiredBacking = ticketValue * ticketEntries;
if (price === null || price < requiredBacking) {
errors.push(`Race-entry product ${ticket.productId} price must fund at least ${requiredBacking} atomic units of ticket backing.`);
}
}
if (entryFee !== null && payoutCap !== null && feeBasisPoints !== null
&& Number.isInteger(requestedMax)) {
const pot = entryFee * BigInt(requestedMax);
const feeBp = BigInt(feeBasisPoints);
const maximumLiability = pot - ((pot * feeBp) / 10000n);
if (pot > PG_BIGINT_MAX) {
errors.push(`MATCH_ENTRY_FEE_ATOMIC * MATCH_MAX_PLAYERS exceeds PostgreSQL BIGINT (${PG_BIGINT_MAX}).`);
}
if (maximumLiability > payoutCap) {
errors.push(`MATCH_PAYOUT_MAX is below the configured ${requestedMax}-player winner liability (${maximumLiability} atomic units).`);
}
}
}
if (payoutMasterEnabled) {
const balanceCritical = parsePositiveAtomic(env.BALANCE_CRITICAL);
const balanceWarn = parsePositiveAtomic(env.BALANCE_WARN);
const acceptedLiabilities = [];
if (directPayoutsEnabled || creditsPayoutsEnabled) {
const soloPayoutCap = parsePositiveAtomic(env.PAYOUT_MAX_PER_GAME);
if (soloPayoutCap === null) {
errors.push('PAYOUT_MAX_PER_GAME must be an explicit positive PostgreSQL BIGINT atomic-unit cap when solo payouts are enabled.');
} else {
acceptedLiabilities.push({ label: 'PAYOUT_MAX_PER_GAME', amount: soloPayoutCap });
}
}
if (matchPayoutsEnabled) {
const matchPayoutCap = parsePositiveAtomic(env.MATCH_PAYOUT_MAX);
if (matchPayoutCap !== null) {
acceptedLiabilities.push({ label: 'MATCH_PAYOUT_MAX', amount: matchPayoutCap });
}
}
if (balanceCritical === null) {
errors.push('BALANCE_CRITICAL must be an explicit positive PostgreSQL BIGINT atomic-unit reserve when payouts are enabled.');
} else {
const uncovered = acceptedLiabilities
.filter(liability => balanceCritical < liability.amount)
.sort((left, right) => left.amount < right.amount ? 1 : -1);
if (uncovered.length > 0) {
const largest = uncovered[0];
errors.push(`BALANCE_CRITICAL must be at least ${largest.label} (${largest.amount} atomic units) so one accepted payout is always covered.`);
}
}
if (balanceWarn === null) {
errors.push('BALANCE_WARN must be an explicit positive PostgreSQL BIGINT atomic-unit warning threshold when payouts are enabled.');
} else if (balanceCritical !== null && balanceWarn < balanceCritical) {
errors.push(`BALANCE_WARN must be greater than or equal to BALANCE_CRITICAL (${balanceCritical} atomic units).`);
}
}
// Never let production advertise a multiplier outcome which settlement would cap or
// suppress. Browser disclosures and immutable game terms must describe the same amount.
const validateSoloOutcomes = (label, enabled, base, rule) => {
if (!enabled) return;
let baseAtomic;
let minAtomic;
let maxAtomic;
try {
baseAtomic = money.toBig(base);
minAtomic = money.toBig(rule?.minPayout);
maxAtomic = money.toBig(rule?.maxPayout);
} catch (_) {
errors.push(`${label} payout base/min/max must be exact atomic-unit integers.`);
return;
}
for (const [outcome, multiplier] of [
['escape', rule?.multipliers?.escape],
['escapeWithTreasure', rule?.multipliers?.escapeWithTreasure]
]) {
let amount;
try { amount = money.mulByDecimal(baseAtomic, multiplier); }
catch (_) {
errors.push(`${label} ${outcome} multiplier must be a non-negative decimal.`);
continue;
}
if (amount < minAtomic || amount <= 0n) {
errors.push(`${label} ${outcome} payout (${amount} atomic units) is below its configured minimum (${minAtomic}).`);
}
if (amount > maxAtomic) {
errors.push(`${label} ${outcome} payout (${amount} atomic units) exceeds its configured maximum (${maxAtomic}).`);
}
}
};
validateSoloOutcomes(
'Direct', directPayoutsEnabled,
config?.modes?.direct?.price,
config?.payouts?.rules?.direct
);
validateSoloOutcomes(
'Credits', creditsPayoutsEnabled,
config?.payouts?.rules?.credits?.baseValue,
config?.payouts?.rules?.credits
);
if (!Object.prototype.hasOwnProperty.call(env, 'PAYMENTS_ENABLED') && !env.GAME_MODE) {
errors.push('Production requires an explicit PAYMENTS_ENABLED=true|false setting.');
}
if (!Object.prototype.hasOwnProperty.call(env, 'PAYOUTS_ENABLED')) {
errors.push('Production requires an explicit PAYOUTS_ENABLED=true|false setting.');
}
if (directEnabled && !Object.prototype.hasOwnProperty.call(env, 'DIRECT_PAYOUTS_ENABLED')) {
errors.push('Production direct mode requires an explicit DIRECT_PAYOUTS_ENABLED=true|false setting.');
}
if (creditsEnabled
&& !Object.prototype.hasOwnProperty.call(env, 'CREDITS_PAYOUTS_ENABLED')
&& !Object.prototype.hasOwnProperty.call(env, 'CREDITS_PAYOUT_ENABLED')) {
errors.push('Production credits mode requires an explicit CREDITS_PAYOUTS_ENABLED=true|false setting.');
}
const adminKey = String(env.ADMIN_API_KEY || '');
if (adminKey.length < 32 || PLACEHOLDER_SECRET.test(adminKey) || new Set(adminKey).size < 8) {
errors.push('ADMIN_API_KEY must be a strong non-placeholder secret of at least 32 characters in production.');
}
if (!env.DB_PASSWORD || PLACEHOLDER_SECRET.test(String(env.DB_PASSWORD))) {
errors.push('DB_PASSWORD must be set to a non-placeholder value in production.');
}
const simulated = isTrue(env.SIMULATED_BLOCKS)
|| isTrue(env.FORCE_SIMULATED_BLOCKS)
|| String(env.BLOCK_SOURCE || '').toLowerCase() === 'simulated';
if (simulated) {
errors.push('Simulated blocks are forbidden when NODE_ENV=production.');
}
if (isTrue(env.DEBUG_HOTKEYS)) {
errors.push('DEBUG_HOTKEYS must not be enabled in production.');
}
if (payoutMasterEnabled && network === 'mainnet' && !isTrue(env.ALLOW_MAINNET_PAYOUTS)) {
errors.push('Mainnet payouts require the explicit safety acknowledgement ALLOW_MAINNET_PAYOUTS=true.');
}
if (network !== 'mainnet' && isTrue(env.SMIRK_ENABLED)) {
warnings.push('SMIRK_ENABLED is ignored on test networks; set it false to keep operator intent clear.');
}
if (isTrue(env.TRUST_PROXY) === false) {
warnings.push('TRUST_PROXY is not enabled; this is correct only when the Node process is directly exposed.');
}
}
// Info about FREE mode
if (!config.paymentsEnabled) {
this.logger.info?.('ℹ️ Payments disabled. Server running in FREE mode.');
if (!paymentsEnabled) {
this.logger.info?.('ℹ️ Payments disabled. Server will run in free mode.');
}
warnings.forEach(message => this.logger.warn?.(`⚠️ ${message}`));
errors.forEach(message => this.logger.error?.(`❌ ${message}`));
// Emit warnings and errors
if (warnings.length) {
warnings.forEach(msg => this.logger.warn?.(`⚠️ ${msg}`));
return {
warnings,
errors,
production,
money: {
paymentsEnabled,
payoutsEnabled: anyPayoutsEnabled,
payoutWorkerEnabled: payoutMasterEnabled,
walletRequired,
directPayoutsEnabled,
creditsPayoutsEnabled,
matchPayoutsEnabled
}
};
}
assertValid(config) {
const result = this.validate(config);
if (result.errors.length > 0) {
const error = new Error(`Invalid production configuration (${result.errors.length} error${result.errors.length === 1 ? '' : 's'}).`);
error.name = 'EnvironmentValidationError';
error.code = 'INVALID_ENVIRONMENT';
error.validation = result;
throw error;
}
if (errors.length) {
errors.forEach(msg => this.logger.error?.(`❌ ${msg}`));
}
return { warnings, errors };
return result;
}
}
+42 -18
View File
@@ -48,8 +48,7 @@ const DEFAULT_CONFIG = Object.freeze({
enabled: true,
multipliers: {
escape: 2.0,
escapeWithTreasure: 3.0,
perfectRun: 5.0
escapeWithTreasure: 3.0
},
minPayout: 1000000000n,
maxPayout: 10000000000000n
@@ -58,8 +57,7 @@ const DEFAULT_CONFIG = Object.freeze({
enabled: false,
multipliers: {
escape: 2.0,
escapeWithTreasure: 3.0,
perfectRun: 3.0
escapeWithTreasure: 3.0
},
baseValue: 100000000000n,
minPayout: 1000000000n,
@@ -163,10 +161,12 @@ function parseAtomicValue(value, fallback) {
}
if (typeof value === 'number') {
if (!Number.isFinite(value)) {
// A Number above MAX_SAFE_INTEGER has already lost atomic units before it reaches
// this parser. Reject it instead of freezing a rounded value into the config.
if (!Number.isSafeInteger(value)) {
return fallback;
}
return BigInt(Math.round(value));
return BigInt(value);
}
const normalized = String(value).trim().toLowerCase().replace(/_/g, '');
@@ -174,7 +174,9 @@ function parseAtomicValue(value, fallback) {
return fallback;
}
if (normalized.startsWith('0x')) {
// Parse integer text with BigInt before touching Number. Atomic-unit configuration often
// exceeds Number.MAX_SAFE_INTEGER; routing it through Number first silently rounds money.
if (/^[+-]?\d+$/.test(normalized) || /^0x[0-9a-f]+$/i.test(normalized)) {
try {
return BigInt(normalized);
} catch (error) {
@@ -182,16 +184,9 @@ function parseAtomicValue(value, fallback) {
}
}
const numeric = Number(normalized);
if (Number.isFinite(numeric)) {
return BigInt(Math.round(numeric));
}
try {
return BigInt(normalized);
} catch (error) {
return fallback;
}
// Atomic-unit configuration is integral by definition. Decimal/exponential text must
// not be rounded through Number, especially once values exceed 2^53.
return fallback;
}
function parseFloatValue(value, fallback) {
@@ -255,7 +250,12 @@ class PaymentConfigManager {
loadConfig() {
const config = cloneConfig(DEFAULT_CONFIG);
config.paymentsEnabled = parseBoolean(process.env.PAYMENTS_ENABLED, config.paymentsEnabled);
// PAYMENTS_ENABLED is the authoritative master switch. Keep its explicit value
// separate while parsing the subordinate mode selectors below; otherwise
// PAYMENT_MODES/DIRECT_PAYMENT_ENABLED/CREDITS_ENABLED can accidentally turn the
// payment system back on after an operator has set PAYMENTS_ENABLED=false.
const paymentsMaster = parseBoolean(process.env.PAYMENTS_ENABLED, null);
config.paymentsEnabled = paymentsMaster === null ? config.paymentsEnabled : paymentsMaster;
const gameModeOverride = process.env.GAME_MODE ? process.env.GAME_MODE.toUpperCase() : null;
if (gameModeOverride === 'FREE') {
@@ -299,6 +299,12 @@ class PaymentConfigManager {
if (creditsEnabled !== undefined) {
config.modes.credits.enabled = creditsEnabled;
}
if (paymentsMaster === false) {
config.paymentsEnabled = false;
config.modes.direct.enabled = false;
config.modes.credits.enabled = false;
}
config.modes.credits.creditsPerGame = parseInteger(process.env.CREDITS_PER_GAME, config.modes.credits.creditsPerGame);
config.modes.credits.requiresAddress = parseBoolean(process.env.CREDITS_REQUIRES_ADDRESS, config.modes.credits.requiresAddress);
config.modes.credits.allowMixedMode = parseBoolean(process.env.ALLOW_MIXED_MODE, config.modes.credits.allowMixedMode);
@@ -340,8 +346,21 @@ class PaymentConfigManager {
config.payouts.rules.credits.multipliers.escape = parseFloatValue(process.env.CREDITS_PAYOUT_ESCAPE, config.payouts.rules.credits.multipliers.escape);
config.payouts.rules.credits.multipliers.escapeWithTreasure = parseFloatValue(process.env.CREDITS_PAYOUT_TREASURE, config.payouts.rules.credits.multipliers.escapeWithTreasure);
config.payouts.rules.credits.baseValue = parseAtomicValue(process.env.CREDITS_PAYOUT_BASE, config.payouts.rules.credits.baseValue);
config.payouts.rules.credits.minPayout = parseAtomicValue(process.env.CREDITS_PAYOUT_MIN ?? process.env.PAYOUT_MIN_AMOUNT, config.payouts.rules.credits.minPayout);
// PAYOUT_MAX_PER_GAME is an outer safety bound for every solo payout. A dedicated
// credits override is supported, but absent one the global cap must not protect only
// direct entries while leaving credit wins at a larger default.
const globalPayoutMax = parseAtomicValue(process.env.PAYOUT_MAX_PER_GAME, null);
const creditsPayoutMax = parseAtomicValue(process.env.CREDITS_PAYOUT_MAX, config.payouts.rules.credits.maxPayout);
config.payouts.rules.credits.maxPayout = globalPayoutMax !== null && globalPayoutMax < creditsPayoutMax
? globalPayoutMax
: creditsPayoutMax;
config.payouts.processing.batchInterval = parseInteger(process.env.PAYOUT_BATCH_INTERVAL, config.payouts.processing.batchInterval);
config.payouts.processing.confirmations = parseInteger(
process.env.PAYMENT_CONFIRMATIONS,
config.payouts.processing.confirmations
);
config.payouts.processing.maxRetries = parseInteger(process.env.PAYOUT_MAX_RETRIES, config.payouts.processing.maxRetries);
config.limits.maxGamesPerHour = parseInteger(process.env.MAX_GAMES_PER_HOUR, config.limits.maxGamesPerHour);
@@ -400,6 +419,11 @@ class PaymentConfigManager {
this.logger.warn?.('⚠️ Payments enabled but no payment modes active. Falling back to FREE mode.');
}
if (!Number.isSafeInteger(this.config.payouts.processing.confirmations)
|| this.config.payouts.processing.confirmations < 1) {
throw new Error('Payment confirmations must be an integer of at least 1');
}
this.validatePrices();
return true;
}
+35
View File
@@ -0,0 +1,35 @@
/**
* Pure runtime safety policies shared by startup, public status, and background workers.
* Keeping these predicates side-effect free makes the money kill switches regression-testable.
*/
function isPayoutProcessingEnabled(config, gameModeManager, options = {}) {
if (!config?.payouts?.enabled || gameModeManager?.payoutsEnabled === false) return false;
const direct = Boolean(config.modes?.direct?.enabled)
&& Boolean(config.payouts?.rules?.direct?.enabled)
&& Boolean(gameModeManager?.directPayoutEnabled);
const credits = Boolean(config.modes?.credits?.enabled)
&& Boolean(config.payouts?.rules?.credits?.enabled)
&& Boolean(gameModeManager?.creditsPayoutEnabled);
// Admission switches are intentionally not consulted for durable liabilities. Once any
// paid game has created a payout row, turning off a product or match mode must stop new
// liabilities without stranding the existing one. Only settlement-worker callers opt into
// this behavior, and PAYOUTS_ENABLED plus the manager emergency switch remain authoritative.
const acceptedLiabilities = options.settleAcceptedLiabilities === true
// Compatibility for callers/tests written before the dispatcher was audited as generic.
|| options.settleAcceptedMatchLiabilities === true;
return direct || credits || acceptedLiabilities;
}
function isWalletRequired(config, gameModeManager, options = {}) {
// Intake needs subaddress creation/receipt checks. Settlement still needs transfer RPC when
// operators pause every new invoice, so payout-only recovery must initialize the same
// authenticated wallet boundary instead of falling through to a default endpoint.
return Boolean(config?.paymentsEnabled)
|| isPayoutProcessingEnabled(config, gameModeManager, options);
}
module.exports = { isPayoutProcessingEnabled, isWalletRequired };