diff --git a/public/Assets/locales/en.json b/public/Assets/locales/en.json index 91241eac9..b3b19a7f6 100644 --- a/public/Assets/locales/en.json +++ b/public/Assets/locales/en.json @@ -226,6 +226,16 @@ "description": "Check out the changelog to see what changed in this version.", "viewChangelog": "See what's new" }, + "devexEstimate": { + "title": "Estimated DevEx earnings", + "tooltip": "Estimated DevEx earnings for the selected period, with Robux from US players aged 18+ at the higher rate.", + "loading": "Loading...", + "loadFailed": "Couldn't load the DevEx estimate.", + "earnings": "Estimated earnings", + "payout": "You'd receive", + "eligibleRobux": "US 18+ Robux", + "standardRobux": "Other Robux" + }, "onboarding": { "title": "Welcome to RoValra!", "thankYou": "Thank you for installing RoValra!", diff --git a/src/content/core/idExtractor.js b/src/content/core/idExtractor.js index 1c45cf0de..500664676 100644 --- a/src/content/core/idExtractor.js +++ b/src/content/core/idExtractor.js @@ -56,6 +56,19 @@ export function getUniverseIdFromUrl(url = window.location.href) { } } +export function getCreatorHubUniverseIdFromUrl(url = window.location.href) { + try { + return ( + new URL(url, window.location.origin).pathname.match( + /\/dashboard\/creations\/experiences\/(\d+)/i, + )?.[1] || null + ); + } catch (e) { + console.warn('RoValra: URL parsing failed', e); + return null; + } +} + export function getGamePassIdFromUrl(url = window.location.href) { try { const urlObj = new URL(url, window.location.origin); diff --git a/src/content/core/settings/settingConfig.js b/src/content/core/settings/settingConfig.js index 4ef06a8ce..36d0b4058 100644 --- a/src/content/core/settings/settingConfig.js +++ b/src/content/core/settings/settingConfig.js @@ -1,4 +1,5 @@ import { + DEVEX_PAYOUT_METHOD_OPTIONS, ROBUX_FIAT_ESTIMATE_DEFAULT_GRADIENT, TRANSACTION_FIAT_CURRENCY_OPTIONS, TRANSACTION_FIAT_RATE_OPTIONS, @@ -2079,6 +2080,21 @@ export const SETTINGS_CONFIG = { type: 'checkbox', default: false, }, + devexEstimateEnabled: { + label: 'DevEx Earnings Estimate', + description: + 'Shows your estimated DevEx earnings on the Monetization overview and next to Robux in its charts.', + type: 'checkbox', + default: true, + }, + devexPayoutMethod: { + label: 'DevEx Payment Method', + description: + 'Your DevEx portal payment method, used to take its fees, US tax withholding and currency exchange out of the DevEx estimate.', + type: 'select', + options: DEVEX_PAYOUT_METHOD_OPTIONS, + default: 'paypal', + }, }, }, totalspentEnabled: { diff --git a/src/content/core/transactions/fiat.js b/src/content/core/transactions/fiat.js index 7f773349a..3dff27aa3 100644 --- a/src/content/core/transactions/fiat.js +++ b/src/content/core/transactions/fiat.js @@ -1,6 +1,9 @@ import { callRobloxApiJson } from '../api.js'; import { get as getCache, set as setCache } from '../storage/cacheHandler.js'; export { + DEVEX_EXCHANGE_FEE_PERCENT, + DEVEX_O18_USD_RATE, + DEVEX_PAYOUT_FEES, DEVEX_USD_RATE, ROBUX_FIAT_ESTIMATE_DEFAULT_COLOR, ROBUX_FIAT_ESTIMATE_DEFAULT_GRADIENT, @@ -14,9 +17,8 @@ export { TRANSACTION_FIAT_RATE_OPTIONS, } from './fiatConfig.js'; import { - DEVEX_USD_RATE, - ROBUX_FIAT_RATE_MODE_DEVEX, - ROBUX_FIAT_RATE_MODE_NORMAL, + DEVEX_EXCHANGE_FEE_PERCENT, + DEVEX_PAYOUT_FEES, ROBUX_FIAT_SETTINGS_DEFAULTS, } from './fiatConfig.js'; @@ -34,6 +36,7 @@ chrome.storage.onChanged.addListener((changes, areaName) => { changes.robuxFiatEstimatesEnabled || changes.robuxFiatDisplayCurrency || changes.robuxFiatRateMode || + changes.devexPayoutMethod || changes.robuxFiatEstimateColor || changes.robuxFiatEstimateStyleMode || changes.robuxFiatEstimateGradient || @@ -156,3 +159,56 @@ export function formatDisplayCurrency(amount, currencyCode = 'USD') { maximumFractionDigits: 2, }).format(roundedValue); } + +let payoutDetailsPromise = null; + +function getPayoutDetails() { + payoutDetailsPromise ??= Promise.all([ + callRobloxApiJson({ + subdomain: 'apis', + endpoint: + '/creator-tax/withholding-rate?paymentType=PAYMENT_TYPE_ROYALTY', + }) + .then((data) => (data?.rate?.withholdingRateBps || 0) / 10000) + .catch(() => 0), + callRobloxApiJson({ + subdomain: 'users', + endpoint: '/v1/users/authenticated/country-code', + }) + .then((data) => data?.countryCode || null) + .catch(() => null), + ]).then(([withholdingRate, countryCode]) => ({ + withholdingRate, + countryCode, + })); + return payoutDetailsPromise; +} + +export async function getDevexPayoutUsd( + usdAmount, + currency, + { includeFlatFee = true } = {}, +) { + const { devexPayoutMethod: method } = await getRobuxFiatSettings(); + if (!method || method === 'none') return null; + + const { withholdingRate, countryCode } = await getPayoutDetails(); + const fees = + method === 'paypal' + ? DEVEX_PAYOUT_FEES[ + countryCode === 'US' + ? 'paypalDomestic' + : 'paypalInternational' + ] + : DEVEX_PAYOUT_FEES[method]; + if (!fees) return null; + + const afterTax = usdAmount * (1 - withholdingRate); + const percentFee = (afterTax * (fees.percent || 0)) / 100; + const fee = includeFlatFee + ? Math.min(fees.cap ?? Infinity, fees.flat + percentFee) + : percentFee; + const exchangeRate = + currency === 'USD' ? 1 : 1 - DEVEX_EXCHANGE_FEE_PERCENT / 100; + return Math.max(0, afterTax - fee) * exchangeRate; +} diff --git a/src/content/core/transactions/fiatConfig.js b/src/content/core/transactions/fiatConfig.js index 4a790ccc2..a0fece20a 100644 --- a/src/content/core/transactions/fiatConfig.js +++ b/src/content/core/transactions/fiatConfig.js @@ -1,6 +1,25 @@ export const ROBUX_FIAT_RATE_MODE_NORMAL = 'normal'; export const ROBUX_FIAT_RATE_MODE_DEVEX = 'devex'; export const DEVEX_USD_RATE = 0.0038; +export const DEVEX_O18_USD_RATE = 0.0054; +export const DEVEX_EXCHANGE_FEE_PERCENT = 2.5; +export const DEVEX_PAYOUT_FEES = { + paypalDomestic: { flat: 0.1, percent: 2, cap: 1 }, + paypalInternational: { flat: 1, percent: 2, cap: 21 }, + ach: { flat: 0 }, + echeck: { flat: 5 }, + wire: { flat: 26 }, + check: { flat: 6 }, +}; + +export const DEVEX_PAYOUT_METHOD_OPTIONS = [ + { value: 'none', label: 'Do not include fees' }, + { value: 'paypal', label: 'PayPal' }, + { value: 'ach', label: 'ACH' }, + { value: 'echeck', label: 'eCheck / bank transfer' }, + { value: 'wire', label: 'Wire transfer' }, + { value: 'check', label: 'Check' }, +]; export const ROBUX_FIAT_ESTIMATE_DEFAULT_COLOR = '#7a7d81'; @@ -19,6 +38,7 @@ export const ROBUX_FIAT_SETTINGS_DEFAULTS = { robuxFiatEstimatesEnabled: false, robuxFiatDisplayCurrency: 'USD', robuxFiatRateMode: ROBUX_FIAT_RATE_MODE_NORMAL, + devexPayoutMethod: 'paypal', robuxFiatEstimateColor: ROBUX_FIAT_ESTIMATE_DEFAULT_COLOR, robuxFiatEstimateStyleMode: ROBUX_FIAT_ESTIMATE_STYLE_MODE_SOLID, robuxFiatEstimateGradient: ROBUX_FIAT_ESTIMATE_DEFAULT_GRADIENT, diff --git a/src/content/core/ui/robuxIcon.js b/src/content/core/ui/robuxIcon.js index 4df20df8c..980fa6233 100644 --- a/src/content/core/ui/robuxIcon.js +++ b/src/content/core/ui/robuxIcon.js @@ -2,12 +2,14 @@ import { observeElement, observeChildren, observeAttributes, + observeText, } from '../observer.js'; import { callRobloxApiJson } from '../api.js'; import { cleanPrice } from '../utils/priceCleaner.js'; import { addTooltip } from './tooltip.js'; import { convertCurrencyAmount, + getDevexPayoutUsd, DEVEX_USD_RATE, formatDisplayCurrency, getRobuxFiatSettings, @@ -131,7 +133,7 @@ function syncStreamerRobuxSetting() { streamerRobuxRevealed, ); }); - } catch (error) {} + } catch {} } function isTransactionsPage() { @@ -418,6 +420,14 @@ function isNavbarRobuxBalance(element) { ); } +function isCashOutBalance(element) { + return ( + isNavbarRobuxBalance(element) || + (element instanceof HTMLElement && + element.closest('#transactions-web-app .balance-label') !== null) + ); +} + function getDevexUsdAmount(robuxAmount, useEstimateApi) { if (!useEstimateApi) return robuxAmount * DEVEX_USD_RATE; @@ -459,12 +469,13 @@ async function getFormattedRobuxEstimate( const style = buildEstimateStyle(fiatSettings); if (fiatSettings.robuxFiatRateMode === ROBUX_FIAT_RATE_MODE_DEVEX) { - const usdAmount = await getDevexUsdAmount( - robuxAmount, - isNavbarRobuxBalance(element), - ); + const cashOut = isCashOutBalance(element); + const usdAmount = await getDevexUsdAmount(robuxAmount, cashOut); + const payoutUsd = await getDevexPayoutUsd(usdAmount, targetCurrency, { + includeFlatFee: cashOut, + }); const convertedAmount = await convertCurrencyAmount( - usdAmount, + payoutUsd ?? usdAmount, 'USD', targetCurrency, ); @@ -664,7 +675,10 @@ async function attachTransactionsCellEstimate(labelCell) { if (!(targetCell instanceof HTMLElement)) return; const amount = getRobuxAmountFromElement(targetCell); - if (!amount) return; + if (!amount) { + targetCell.querySelector('.rovalra-usd-estimate')?.remove(); + return; + } try { const resolvedAmount = await resolveEstimateRobuxAmount( @@ -678,13 +692,14 @@ async function attachTransactionsCellEstimate(labelCell) { targetCell, ); if (!formattedEstimate) return; + if (getRobuxAmountFromElement(targetCell) !== amount) return; upsertEstimate(targetCell, formattedEstimate, { compact: true, appendInside: true, }); labelCell.dataset.rovalraUsdAmount = String(resolvedAmount); - } catch (error) { + } catch { /* ignore */ } } @@ -735,6 +750,14 @@ function processTransactionsTable(summaryRoot) { if (!(labelCell instanceof HTMLElement)) return; attachTransactionsCellEstimate(labelCell); }); + + summaryRoot.querySelectorAll('td.amount').forEach((amountCell) => { + if (amountCell.dataset.rovalraObserved) return; + amountCell.dataset.rovalraObserved = 'true'; + observeChildren(amountCell, () => + processTransactionsTable(summaryRoot), + ); + }); } async function attachGroupRevenueEstimate(amountCell) { @@ -760,7 +783,7 @@ async function attachGroupRevenueEstimate(amountCell) { upsertEstimate(amountCell, formattedEstimate, { compact: true }); amountCell.dataset.rovalraUsdAmount = String(resolvedAmount); - } catch (error) { + } catch { /* ignore */ } } @@ -857,7 +880,7 @@ async function attachUsdEstimate(icon) { upsertEstimate(element, formattedEstimate); icon.dataset.rovalraUsdAmount = String(resolvedAmount); - } catch (error) { + } catch { /* ignore */ } } @@ -892,7 +915,7 @@ async function attachUsdEstimateToValueElement(element) { upsertEstimate(amountElement, formattedEstimate); amountElement.dataset.rovalraUsdAmount = String(resolvedAmount); - } catch (error) { + } catch { /* ignore */ } } @@ -1050,6 +1073,7 @@ export function init() { 'robuxFiatEstimatesEnabled', 'robuxFiatDisplayCurrency', 'robuxFiatRateMode', + 'devexPayoutMethod', ]; if ('streamermode' in changes || 'hideRobux' in changes) { @@ -1136,6 +1160,7 @@ export function init() { (element) => { processTransactionsTable(element); observeChildren(element, () => processTransactionsTable(element)); + observeText(element, () => processTransactionsTable(element)); observeAttributes( element, () => processTransactionsTable(element), diff --git a/src/content/core/xhr/intercept.js b/src/content/core/xhr/intercept.js index 622554d31..8dd512315 100644 --- a/src/content/core/xhr/intercept.js +++ b/src/content/core/xhr/intercept.js @@ -38,6 +38,8 @@ const LayeredAssetTypes = [64, 65, 66, 67, 68, 69, 70, 71, 72, 41]; 'https://apis.roblox.com/marketplace-widgets/v1/widgets/web'; const MARKETPLACE_RFY_WIDGET_TYPE = 'AvatarItemRfyWidget'; const MARKETPLACE_AD_SLOT_COUNT = 14; + const ANALYTICS_QUERY_API_URL = + 'https://apis.roblox.com/analytics-query-gateway/v1/metrics/resource/'; const TOOLBOX_ASSET_API_HOST = 'apis.roblox.com'; const TOOLBOX_ASSET_API_PATH = /^\/toolbox-service\/v2\/assets\/(\d+)\/?$/; const STORE_ASSET_DETAILS_TIMEOUT_MS = 3000; @@ -106,7 +108,7 @@ const LayeredAssetTypes = [64, 65, 66, 67, 68, 69, 70, 71, 72, 41]; new URL(url, window.location.origin).hostname === THUMBNAILS_API_HOST ); - } catch (e) { + } catch { return false; } } @@ -139,7 +141,7 @@ const LayeredAssetTypes = [64, 65, 66, 67, 68, 69, 70, 71, 72, 41]; } return JSON.stringify(data); - } catch (e) { + } catch { return body; } } @@ -161,7 +163,7 @@ const LayeredAssetTypes = [64, 65, 66, 67, 68, 69, 70, 71, 72, 41]; rewrittenUrl.searchParams.set('includeProfileFrame', 'false'); } return rewrittenUrl.toString(); - } catch (e) { + } catch { return url; } } @@ -208,7 +210,7 @@ const LayeredAssetTypes = [64, 65, 66, 67, 68, 69, 70, 71, 72, 41]; }), init, ]; - } catch (e) { + } catch { return args; } } @@ -216,7 +218,7 @@ const LayeredAssetTypes = [64, 65, 66, 67, 68, 69, 70, 71, 72, 41]; try { freeRobloxPlusThemesEnabled = sessionStorage.getItem('rovalra_freeRobloxPlusThemes') === 'true'; - } catch (e) {} + } catch {} document.addEventListener('rovalra:settingSaved', (event) => { if (event.detail?.name === 'robloxGroupFeaturesEnabled') { @@ -258,7 +260,7 @@ const LayeredAssetTypes = [64, 65, 66, 67, 68, 69, 70, 71, 72, 41]; 'rovalra_freeRobloxPlusThemes', String(freeRobloxPlusThemesEnabled), ); - } catch (e) {} + } catch {} }); try { @@ -274,7 +276,7 @@ const LayeredAssetTypes = [64, 65, 66, 67, 68, 69, 70, 71, 72, 41]; homeLayoutHidden = JSON.parse( sessionStorage.getItem('rovalra_homeLayoutHidden') || '[]', ); - } catch (e) {} + } catch {} document.addEventListener('rovalra-streamer-mode', (e) => { if (typeof e.detail === 'object') { @@ -313,7 +315,7 @@ const LayeredAssetTypes = [64, 65, 66, 67, 68, 69, 70, 71, 72, 41]; 'rovalra_homeLayoutHidden', JSON.stringify(homeLayoutHidden), ); - } catch (error) {} + } catch {} }); document.addEventListener('rovalra-home-extra-sorts', (e) => { @@ -408,6 +410,34 @@ const LayeredAssetTypes = [64, 65, 66, 67, 68, 69, 70, 71, 72, 41]; return homeLayoutReadyPromise; } + function dispatchDailyRevenueQuery(requestBody, response) { + let request; + try { + request = JSON.parse(requestBody); + } catch { + return; + } + const query = request?.query; + if (query?.metric !== 'DailyRevenue' || query.breakdown?.length) return; + + response + .clone() + .json() + .then((data) => { + if (!data?.operation?.done) return; + document.dispatchEvent( + new CustomEvent('rovalra-daily-revenue-query', { + detail: { + universeId: request.resourceId, + query, + values: data.operation.queryResult?.values || [], + }, + }), + ); + }) + .catch(() => {}); + } + function getRequestUrl(url) { if (typeof url === 'string') return url; if (url instanceof Request) return url.url; @@ -424,7 +454,7 @@ const LayeredAssetTypes = [64, 65, 66, 67, 68, 69, 70, 71, 72, 41]; /^(?:\/[a-z]{2}(?:-[a-z]{2})?)?\/(?:games|catalog|bundles|hidden-catalog|looks|library|game-pass|private-games)\/(\d+)/i, ); if (match && match[1]) return match[1]; - } catch (e) {} + } catch {} const match = window.location.href.match( /\/(?:games|catalog|bundles|hidden-catalog|looks|library|game-pass|private-games)\/(\d+)/, @@ -450,7 +480,7 @@ const LayeredAssetTypes = [64, 65, 66, 67, 68, 69, 70, 71, 72, 41]; pathParts[3] = gameId; requestUrl.pathname = pathParts.join('/'); return requestUrl.toString(); - } catch (e) { + } catch { return url; } } @@ -458,7 +488,7 @@ const LayeredAssetTypes = [64, 65, 66, 67, 68, 69, 70, 71, 72, 41]; function getChannelOverride() { try { return localStorage.getItem(CHANNEL_OVERRIDE_KEY)?.trim() || null; - } catch (e) { + } catch { return null; } } @@ -466,7 +496,7 @@ const LayeredAssetTypes = [64, 65, 66, 67, 68, 69, 70, 71, 72, 41]; function reportChannel(channel) { try { sessionStorage.setItem(CHANNEL_CURRENT_KEY, channel); - } catch (e) {} + } catch {} document.dispatchEvent( new CustomEvent('rovalra-channel-detected', { detail: { channel }, @@ -536,7 +566,7 @@ const LayeredAssetTypes = [64, 65, 66, 67, 68, 69, 70, 71, 72, 41]; }), init, ]; - } catch (e) { + } catch { return args; } } @@ -580,7 +610,7 @@ const LayeredAssetTypes = [64, 65, 66, 67, 68, 69, 70, 71, 72, 41]; parsedUrl.origin === endpointUrl.origin && parsedUrl.pathname === endpointUrl.pathname ); - } catch (e) { + } catch { return false; } } @@ -593,7 +623,7 @@ const LayeredAssetTypes = [64, 65, 66, 67, 68, 69, 70, 71, 72, 41]; parsedUrl.origin === endpointUrl.origin && parsedUrl.pathname === endpointUrl.pathname ); - } catch (e) { + } catch { return false; } } @@ -643,7 +673,7 @@ const LayeredAssetTypes = [64, 65, 66, 67, 68, 69, 70, 71, 72, 41]; } return pathMatch[1]; - } catch (error) { + } catch { return null; } } @@ -959,7 +989,7 @@ const LayeredAssetTypes = [64, 65, 66, 67, 68, 69, 70, 71, 72, 41]; parsedUrl.origin === endpointUrl.origin && parsedUrl.pathname === endpointUrl.pathname ); - } catch (e) { + } catch { return false; } } @@ -1041,7 +1071,7 @@ const LayeredAssetTypes = [64, 65, 66, 67, 68, 69, 70, 71, 72, 41]; return ( parsedUrl.pathname.match(TOOLBOX_ASSET_API_PATH)?.[1] ?? null ); - } catch (e) { + } catch { return null; } } @@ -1178,7 +1208,7 @@ const LayeredAssetTypes = [64, 65, 66, 67, 68, 69, 70, 71, 72, 41]; statusText: response.statusText, headers: newHeaders, }); - } catch (error) { + } catch { return response; } } @@ -1226,7 +1256,7 @@ const LayeredAssetTypes = [64, 65, 66, 67, 68, 69, 70, 71, 72, 41]; if (applyAccountSettingsUiOverrides(data)) { response = responseWithJson(response, data); } - } catch (e) {} + } catch {} } if ( @@ -1299,7 +1329,7 @@ const LayeredAssetTypes = [64, 65, 66, 67, 68, 69, 70, 71, 72, 41]; statusText: response.statusText, headers: newHeaders, }); - } catch (e) {} + } catch {} } } @@ -1312,7 +1342,7 @@ const LayeredAssetTypes = [64, 65, 66, 67, 68, 69, 70, 71, 72, 41]; if (applyMarketplaceAds(data)) { response = responseWithJson(response, data); } - } catch (error) {} + } catch {} } if (requestUrl.includes(PROFILE_API_URL)) { @@ -1323,10 +1353,16 @@ const LayeredAssetTypes = [64, 65, 66, 67, 68, 69, 70, 71, 72, 41]; if (changed) { response = responseWithJson(response, data); } - } catch (error) {} + } catch {} } if (typeof requestUrl === 'string') { + if ( + requestUrl.startsWith(ANALYTICS_QUERY_API_URL) && + typeof args[1]?.body === 'string' + ) { + dispatchDailyRevenueQuery(args[1].body, response); + } if (isUserSettingsRequest(requestUrl)) { response .clone() @@ -1656,7 +1692,7 @@ const LayeredAssetTypes = [64, 65, 66, 67, 68, 69, 70, 71, 72, 41]; } xhr._rovalra_cached_response = JSON.stringify(data); return xhr._rovalra_cached_response; - } catch (e) { + } catch { return original; } }, @@ -1668,7 +1704,7 @@ const LayeredAssetTypes = [64, 65, 66, 67, 68, 69, 70, 71, 72, 41]; if (this.responseType === 'json') { try { return JSON.parse(this.responseText); - } catch (e) { + } catch { return Object.getOwnPropertyDescriptor( XMLHttpRequest.prototype, 'response', @@ -1800,7 +1836,7 @@ const LayeredAssetTypes = [64, 65, 66, 67, 68, 69, 70, 71, 72, 41]; dispatchUserSettingsResponse( JSON.parse(xhr.responseText), ); - } catch (e) {} + } catch {} } }); diff --git a/src/content/features/create.roblox.com/devexEstimate.js b/src/content/features/create.roblox.com/devexEstimate.js new file mode 100644 index 000000000..a10e01560 --- /dev/null +++ b/src/content/features/create.roblox.com/devexEstimate.js @@ -0,0 +1,425 @@ +import { callRobloxApiJson } from '../../core/api.js'; +import { observeElement } from '../../core/observer.js'; +import { settings } from '../../core/settings/getSettings.js'; +import { ts } from '../../core/locale/i18n.js'; +import { createAssetIcon } from '../../core/ui/general/toast.js'; +import { getCreatorHubUniverseIdFromUrl } from '../../core/idExtractor.js'; +import { + DEVEX_O18_USD_RATE, + DEVEX_USD_RATE, + convertCurrencyAmount, + formatDisplayCurrency, + getDevexPayoutUsd, + getRobuxFiatSettings, +} from '../../core/transactions/fiat.js'; + +const OVERVIEW_PATH = /\/monetization\/overview\/?$/; +const CARD_CLASS = 'rovalra-devex-estimate'; +const DAY_MS = 24 * 60 * 60 * 1000; +const POLL_DELAY_MS = 1000; +const MAX_POLLS = 20; +const ELIGIBLE_COUNTRY = 'US'; +const ELIGIBLE_AGE_GROUPS = ['Age18AndOverToUnder21', 'Age21OrOver']; + +let anchorRequest = null; +let tooltipRequest = null; +let tooltipRate = null; +let hoveringRobuxChart = false; +let pageQuery = null; +let renderId = 0; + +function getOverviewUniverseId() { + return OVERVIEW_PATH.test(location.pathname) + ? getCreatorHubUniverseIdFromUrl() + : null; +} + +async function queryRevenue(universeId, query) { + for (let i = 0; i < MAX_POLLS; i++) { + const data = await callRobloxApiJson({ + subdomain: 'apis', + endpoint: `/analytics-query-gateway/v1/metrics/resource/RESOURCE_TYPE_UNIVERSE/id/${universeId}`, + method: 'POST', + body: { + resourceType: 'RESOURCE_TYPE_UNIVERSE', + resourceId: String(universeId), + query: { + metric: 'DailyRevenue', + granularity: 'METRIC_GRANULARITY_ONE_DAY', + ...query, + }, + }, + }); + if (data?.operation?.done) { + return data.operation.queryResult?.values || []; + } + await new Promise((resolve) => setTimeout(resolve, POLL_DELAY_MS)); + } + throw new Error('RoValra: Revenue query timed out'); +} + +function sumRevenue(values, since = null) { + return values.reduce( + (total, value) => + total + + value.dataPoints.reduce( + (sum, point) => + !since || new Date(point.time) >= since + ? sum + (point.value || 0) + : sum, + 0, + ), + 0, + ); +} + +function getSelectedPeriodStart(query) { + const rangeType = new URLSearchParams(location.search).get('rangeType'); + if (rangeType === 'Custom') return new Date(query.startTime); + + const end = new Date(query.endTime); + const days = Math.round((end - new Date(query.startTime)) / DAY_MS) + 1; + return new Date(end - (Math.floor(days / 2) - 1) * DAY_MS); +} + +async function getEligibleRobux(universeId, query, periodStart) { + const filters = query.filter || []; + const countryFilter = filters.find((f) => f.dimension === 'Country'); + const ageFilter = filters.find((f) => f.dimension.startsWith('AgeGroup')); + + if (countryFilter && !countryFilter.values.includes(ELIGIBLE_COUNTRY)) { + return 0; + } + const ageGroups = ageFilter + ? ELIGIBLE_AGE_GROUPS.filter((age) => ageFilter.values.includes(age)) + : ELIGIBLE_AGE_GROUPS; + if (!ageGroups.length) return 0; + + const values = await queryRevenue(universeId, { + breakdown: [{ dimensions: ['AgeGroupV2'] }], + filter: [ + ...filters.filter((f) => f !== countryFilter && f !== ageFilter), + { dimension: 'Country', values: [ELIGIBLE_COUNTRY] }, + ], + granularity: query.granularity, + startTime: periodStart.toISOString(), + endTime: query.endTime, + }); + + return sumRevenue( + values.filter((value) => + ageGroups.includes(value.breakdownValue?.[0]?.value), + ), + ); +} + +async function getDevexRates(robuxAmount) { + const amount = Math.max(1, Math.round(robuxAmount)); + try { + const data = await callRobloxApiJson({ + subdomain: 'billing', + endpoint: `/v1/estimated-fiat?robuxAmount=${amount}`, + }); + return { + standardRate: data.usdAmountMicro / 1e6 / amount || DEVEX_USD_RATE, + premiumRate: data.effectiveO18ToUsdRate || DEVEX_O18_USD_RATE, + }; + } catch { + return { + standardRate: DEVEX_USD_RATE, + premiumRate: DEVEX_O18_USD_RATE, + }; + } +} + +async function getEstimate({ universeId, query, values }) { + const periodStart = getSelectedPeriodStart(query); + const totalRobux = sumRevenue(values, periodStart); + const [eligibleRobux, { standardRate, premiumRate }] = await Promise.all([ + getEligibleRobux(universeId, query, periodStart), + getDevexRates(totalRobux), + ]); + + const premiumRobux = Math.min(totalRobux, eligibleRobux); + const regularRobux = Math.max(0, totalRobux - premiumRobux); + + return { + totalRobux, + premiumRobux, + regularRobux, + standardRate, + premiumRate, + revenueUsd: premiumRobux * premiumRate + regularRobux * standardRate, + }; +} + +function createRobuxIcon() { + const icon = document.createElement('span'); + icon.className = + 'grow-0 shrink-0 basis-auto icon icon-filled-robux size-[var(--icon-size-medium)] content-emphasis'; + return icon; +} + +function createStat(label, value, showRobuxIcon) { + const stat = document.createElement('span'); + stat.className = 'block min-width-0 max-width-full'; + + const labelElement = document.createElement('span'); + labelElement.className = 'block text-body-medium content-default'; + labelElement.textContent = label; + + const valueRow = document.createElement('span'); + valueRow.className = 'flex wrap items-center gap-y-xsmall'; + + const valueElement = document.createElement('span'); + valueElement.className = `text-heading-medium [line-height:135%] content-emphasis padding-right-small ${showRobuxIcon ? 'padding-left-xsmall' : ''}`; + valueElement.textContent = value; + + if (showRobuxIcon) valueRow.append(createRobuxIcon()); + valueRow.append(valueElement); + stat.append(labelElement, valueRow); + return stat; +} + +function createStatusText(text) { + const status = document.createElement('span'); + status.className = 'text-body-medium content-muted'; + status.textContent = text; + return status; +} + +async function renderEstimate(stats) { + const id = ++renderId; + const formatRobux = (amount) => + new Intl.NumberFormat().format(Math.round(amount)); + + const universeId = getOverviewUniverseId(); + if (!pageQuery || String(pageQuery.universeId) !== universeId) { + stats.replaceChildren(createStatusText(ts('devexEstimate.loading'))); + return; + } + + try { + const estimate = await getEstimate(pageQuery); + const { robuxFiatDisplayCurrency: currency = 'USD' } = + await getRobuxFiatSettings(); + const earnings = await convertCurrencyAmount( + estimate.revenueUsd, + 'USD', + currency, + ); + const payoutUsd = await getDevexPayoutUsd( + estimate.revenueUsd, + currency, + ); + const payout = + payoutUsd === null + ? null + : await convertCurrencyAmount(payoutUsd, 'USD', currency); + if (id !== renderId) return; + if (!Number.isFinite(earnings)) throw new Error('No conversion rate'); + + tooltipRate = estimate.totalRobux + ? { currency, perRobux: earnings / estimate.totalRobux } + : null; + + stats.replaceChildren( + ...[ + createStat( + ts('devexEstimate.earnings'), + formatDisplayCurrency(earnings, currency), + ), + Number.isFinite(payout) && + createStat( + ts('devexEstimate.payout'), + formatDisplayCurrency(payout, currency), + ), + createStat( + ts('devexEstimate.eligibleRobux'), + formatRobux(estimate.premiumRobux), + true, + ), + createStat( + ts('devexEstimate.standardRobux'), + formatRobux(estimate.regularRobux), + true, + ), + ].filter(Boolean), + ); + } catch (error) { + if (id !== renderId) return; + console.warn('RoValra: Failed to load DevEx estimate', error); + stats.replaceChildren(createStatusText(ts('devexEstimate.loadFailed'))); + } +} + +function addInfoTooltip(trigger, text) { + let tooltip = null; + + const hide = () => { + tooltip?.remove(); + tooltip = null; + }; + + const show = () => { + if (tooltip) return; + tooltip = document.createElement('div'); + tooltip.className = `${CARD_CLASS}-tooltip-popup foundation-web-portal-zindex bg-inverse-surface-0 padding-y-xsmall padding-x-small radius-small shadow-transient-low`; + + const arrow = document.createElement('span'); + arrow.className = `${CARD_CLASS}-tooltip-arrow`; + + const content = document.createElement('div'); + content.className = 'text-caption-medium content-inverse-default'; + content.textContent = text; + + tooltip.append(arrow, content); + document.body.append(tooltip); + + const triggerRect = trigger.getBoundingClientRect(); + const center = triggerRect.left + triggerRect.width / 2; + const left = Math.min( + Math.max(16, center - tooltip.offsetWidth / 2), + window.innerWidth - tooltip.offsetWidth - 16, + ); + tooltip.style.left = `${left}px`; + tooltip.style.top = `${triggerRect.bottom + 10}px`; + arrow.style.left = `${center - left - 6.5}px`; + }; + + trigger.addEventListener('mouseenter', show); + trigger.addEventListener('focus', show); + trigger.addEventListener('mouseleave', hide); + trigger.addEventListener('blur', hide); + window.addEventListener('scroll', hide, { passive: true }); +} + +function createCard() { + const card = document.createElement('div'); + card.className = `${CARD_CLASS} relative clip radius-[var(--size-300)] stroke-standard stroke-default`; + + const header = document.createElement('div'); + header.className = + 'flex items-center padding-x-xxlarge padding-top-xxlarge'; + + const title = document.createElement('h6'); + title.className = + 'flex items-center min-width-0 min-height-[34px] margin-none text-heading-small content-emphasis'; + + const titleText = document.createElement('span'); + titleText.className = + 'text-no-wrap text-truncate-end min-width-0 max-width-full block'; + titleText.textContent = ts('devexEstimate.title'); + + const info = document.createElement('span'); + info.className = + 'inline-flex shrink-0 items-center justify-center min-width-500 min-height-500 cursor-pointer'; + info.tabIndex = 0; + info.setAttribute('role', 'button'); + info.setAttribute('aria-label', ts('devexEstimate.tooltip')); + addInfoTooltip(info, ts('devexEstimate.tooltip')); + + const infoIcon = document.createElement('span'); + infoIcon.className = + 'grow-0 shrink-0 basis-auto icon icon-regular-circle-i size-[var(--icon-size-medium)]'; + infoIcon.setAttribute('aria-hidden', 'true'); + + info.append(infoIcon); + const logo = createAssetIcon({ + altText: 'RoValra', + width: '24px', + height: '24px', + }); + logo?.classList.add(`${CARD_CLASS}-logo`); + + title.append(...[logo, titleText, info].filter(Boolean)); + header.append(title); + + const body = document.createElement('div'); + body.className = + 'flex wrap justify-between items-end gap-small padding-top-medium padding-bottom-xxlarge padding-x-xxlarge'; + + const stats = document.createElement('div'); + stats.className = `${CARD_CLASS}-stats flex min-width-0 max-width-full justify-start wrap gap-x-large gap-y-small`; + + body.append(stats); + card.append(header, body); + renderEstimate(stats); + return card; +} + +function addTooltipEstimate(element) { + if (!tooltipRate || element.children.length) return; + if (element.classList.contains(`${CARD_CLASS}-tooltip`)) return; + + const text = element.textContent.trim(); + if (!/^[\d,.]+$/.test(text)) return; + + if (!hoveringRobuxChart) return; + if ( + element.nextElementSibling?.classList.contains(`${CARD_CLASS}-tooltip`) + ) { + return; + } + + const robux = Number(text.replace(/,/g, '')); + if (!Number.isFinite(robux)) return; + + const estimate = document.createElement('span'); + estimate.className = `${CARD_CLASS}-tooltip padding-left-xsmall`; + estimate.textContent = `(${formatDisplayCurrency(robux * tooltipRate.perRobux, tooltipRate.currency)})`; + element.after(estimate); +} + +if (location.hostname === 'create.roblox.com') { + document.addEventListener('pointerover', (event) => { + const chart = event.target.closest?.('.highcharts-container'); + if (!chart) return; + hoveringRobuxChart = !!chart + .closest('.stroke-standard') + ?.querySelector('.icon-filled-robux'); + }); + document.addEventListener('rovalra-daily-revenue-query', (event) => { + const universeId = getOverviewUniverseId(); + if (!universeId || String(event.detail?.universeId) !== universeId) { + return; + } + pageQuery = event.detail; + + const stats = document.querySelector(`.${CARD_CLASS}-stats`); + if (stats) renderEstimate(stats); + }); +} + +async function isEnabled() { + return ( + (await settings.robuxFiatEstimatesEnabled) === true && + (await settings.devexEstimateEnabled) === true + ); +} + +export async function init() { + anchorRequest?.disconnect(); + tooltipRequest?.disconnect(); + anchorRequest = null; + tooltipRequest = null; + tooltipRate = null; + + if (location.hostname !== 'create.roblox.com') return; + if (!getOverviewUniverseId()) return; + if (!(await isEnabled())) return; + + anchorRequest = observeElement( + '[data-testid="chart-explore-button"]', + (button) => { + if (document.querySelector(`.${CARD_CLASS}`)) return; + button.closest('.stroke-standard')?.before(createCard()); + }, + ); + + tooltipRequest = observeElement( + '.highcharts-tooltip-box span', + addTooltipEstimate, + { multiple: true }, + ); +} diff --git a/src/content/index.js b/src/content/index.js index 41dbd93a1..78d3050c8 100644 --- a/src/content/index.js +++ b/src/content/index.js @@ -243,6 +243,7 @@ import { init as initPinnedFriends } from './features/sitewide/pinnedFriends.js' // create import { init as initCreateDownload } from './features/create.roblox.com/download.js'; import { init as initOffSaleCreatePage } from './features/create.roblox.com/offSaleCreatePage.js'; +import { init as initDevexEstimate } from './features/create.roblox.com/devexEstimate.js'; import { init as initCatalogExplorer } from './features/catalog/explorer.js'; import { enforceSettingOverrides, @@ -581,6 +582,10 @@ const featureRoutes = [ features: [initModeration], }, // create + { + paths: ['/dashboard/creations/experiences'], + features: [initDevexEstimate], + }, { paths: ['/store/asset'], features: [ diff --git a/src/css/features/developer/devexEstimate.scss b/src/css/features/developer/devexEstimate.scss new file mode 100644 index 000000000..14700a269 --- /dev/null +++ b/src/css/features/developer/devexEstimate.scss @@ -0,0 +1,30 @@ +.rovalra-devex-estimate { + margin-bottom: 24px; +} + +.rovalra-devex-estimate-tooltip-popup { + position: fixed; + box-sizing: border-box; + max-width: min(300px, calc(100vw - 32px)); +} + +.rovalra-devex-estimate-tooltip-arrow { + position: absolute; + top: 0; + width: 0; + height: 0; + margin-top: -6px; + border-right: 6.5px solid transparent; + border-bottom: 6px solid var(--inverse-surface-0, #fff); + border-left: 6.5px solid transparent; +} + +.rovalra-devex-estimate-logo { + flex-shrink: 0; + margin-right: 8px; + border-radius: 6px; +} + +.rovalra-devex-estimate-tooltip { + opacity: 0.75; +} diff --git a/src/css/main.scss b/src/css/main.scss index afdbf02fd..99225b7ca 100644 --- a/src/css/main.scss +++ b/src/css/main.scss @@ -84,6 +84,7 @@ @use 'features/sitewide/kids_theme_text.scss'; @use 'features/sitewide/roblox2016Theme.scss'; @use 'features/developer/debug_overlay.scss'; +@use 'features/developer/devexEstimate.scss'; @use 'features/play/channel_overlay.scss'; @use 'features/play/server_location_overlay.scss'; @use 'features/plus/sendRobux.scss';