From 4c2aa876b65379019bfd2c3bc633a39287d2a331 Mon Sep 17 00:00:00 2001 From: N0VAN0M4LY <224130499+N0VAN0M4LY@users.noreply.github.com> Date: Thu, 26 Nov 2026 09:59:05 +0800 Subject: [PATCH] Show native receipts for store purchases Persist the actual grant in the purchase log and open one native receipt per unread entry. Keep pending receipts during log trimming and resume them when the price table becomes available. Verified TypeScript types, GUI patch application, and Quirrel syntax. --- .../patch.json | 28 ++++++++ .../patch.json | 31 +++++++++ .../patch.json | 30 +++++++++ .../render-retired-entitlement-log/patch.json | 30 +++++++++ .../patch.json | 30 +++++++++ .../patch.json | 29 ++++++++ .../patch.json | 28 ++++++++ .../show-direct-entitlement-gifts/patch.json | 28 ++++++++ .../patch.json | 30 +++++++++ .../patch.json | 31 +++++++++ .../src/profile/profile-trophies-log.ts | 66 +++++++++++++++++-- .../local-service/src/profile/server-time.ts | 4 ++ .../local-service/src/store/store-purchase.ts | 17 ++++- 13 files changed, 376 insertions(+), 6 deletions(-) create mode 100644 gui-patches/online-shop/collect-entitlement-purchase-rewards/patch.json create mode 100644 gui-patches/online-shop/open-entitlement-purchase-receipts/patch.json create mode 100644 gui-patches/online-shop/present-saved-entitlement-grants/patch.json create mode 100644 gui-patches/online-shop/render-retired-entitlement-log/patch.json create mode 100644 gui-patches/online-shop/resume-purchase-receipts-after-price-update/patch.json create mode 100644 gui-patches/online-shop/return-entitlement-reward-handler/patch.json create mode 100644 gui-patches/online-shop/show-direct-entitlement-gift-icons/patch.json create mode 100644 gui-patches/online-shop/show-direct-entitlement-gifts/patch.json create mode 100644 gui-patches/online-shop/show-entitlement-purchase-rewards/patch.json create mode 100644 gui-patches/online-shop/use-entitlement-receipt-for-native-payment/patch.json diff --git a/gui-patches/online-shop/collect-entitlement-purchase-rewards/patch.json b/gui-patches/online-shop/collect-entitlement-purchase-rewards/patch.json new file mode 100644 index 0000000..1ba3316 --- /dev/null +++ b/gui-patches/online-shop/collect-entitlement-purchase-rewards/patch.json @@ -0,0 +1,28 @@ +{ + "id": "online-shop/collect-entitlement-purchase-rewards", + "title": "Track entitlement purchases by user log", + "file": "scripts/userlog/userlogdata.nut", + "program_behaviour": { + "stock": "Resource rewards share an entitlement-name map.", + "patched": "Maintain a separate list of purchases so every purchase can open its own receipt." + }, + "derivation": { + "requirement": "Present each saved entitlement purchase and acknowledge the log after its receipt opens.", + "cause": "Several purchases of the same entitlement can be present in one profile refresh.", + "lighter_options_ruled_out": [ + "Reuse the resource map keyed by product ID. Two purchases of the same product would collapse into one receipt." + ], + "if_not_applied": "Repeated purchases in one update can be under-reported." + }, + "features": [ + "G-Store", + "G-Premium Account" + ], + "evidence": [ + "2.61.0.37 scripts/userlog/userlogdata.nut: checkNewNotificationUserlogs declares the entitlement reward collection." + ], + "edit": { + "find": " let entitlementRewards = {}\r\n", + "replace": " let entitlementRewards = {}\r\n let purchaseReceipts = []\r\n" + } +} diff --git a/gui-patches/online-shop/open-entitlement-purchase-receipts/patch.json b/gui-patches/online-shop/open-entitlement-purchase-receipts/patch.json new file mode 100644 index 0000000..6bb23e4 --- /dev/null +++ b/gui-patches/online-shop/open-entitlement-purchase-receipts/patch.json @@ -0,0 +1,31 @@ +{ + "id": "online-shop/open-entitlement-purchase-receipts", + "title": "Acknowledge each purchase after its receipt opens", + "file": "scripts/userlog/userlogdata.nut", + "program_behaviour": { + "stock": "The resource reward queue acknowledges records before opening entitlement windows.", + "patched": "Queue each saved purchase once per active handler and acknowledge it after the receipt opens." + }, + "derivation": { + "requirement": "Present each saved entitlement purchase and acknowledge the log after its receipt opens.", + "cause": "A refresh can return multiple purchases and the current price table can temporarily lack a product.", + "lighter_options_ruled_out": [ + "Use the existing resource map and acknowledgement timing. Repeated purchases would merge and missing products could be marked seen." + ], + "if_not_applied": "Repeated purchases or products missing from the current catalogue can lose their unread notification." + }, + "features": [ + "G-Store", + "G-Premium Account" + ], + "evidence": [ + "2.61.0.37 scripts/userlog/userlogdata.nut: entitlementRewards dispatches dialogs through doWhenActive.", + "2.61.0.37 scripts/sqDagui/framework/baseGuiHandler.nut: doWhenActive queues while another modal owns the scene.", + "2.61.0.37 scripts/userlog/userlogutils.nut: disableSeenUserlogs persists seen IDs through job 223.", + "2.61.0.37 scripts/sqdagui/framework/baseguihandlermanager.nut: isHandlerValid and handler weak references." + ], + "edit": { + "find": " entitlementRewards.each(\r\n @(_, entId) handler.doWhenActive(@() showEntitlement(entId, { ignoreAvailability = true })))", + "replace": " entitlementRewards.each(\r\n @(_, entId) handler.doWhenActive(@() showEntitlement(entId, { ignoreAvailability = true })))\r\n\r\n if (purchaseReceipts.len() > 0 && !ENTITLEMENTS_PRICE.isActual()) {\r\n waitingForPurchasePrices = true\r\n ENTITLEMENTS_PRICE.checkUpdate()\r\n }\r\n\r\n foreach (logId, owner in clone queuedPurchaseReceipts)\r\n if (!handlersManager.isHandlerValid(owner))\r\n queuedPurchaseReceipts.$rawdelete(logId)\r\n\r\n foreach (entry in purchaseReceipts) {\r\n let receipt = entry\r\n if (receipt.logId in queuedPurchaseReceipts)\r\n continue\r\n\r\n queuedPurchaseReceipts[receipt.logId] <- handler.weakref()\r\n handler.doWhenActive(function() {\r\n if (!shownUserlogNotifications.get().contains(receipt.logId)\r\n && ENTITLEMENTS_PRICE.isActual()\r\n && showPurchaseReceipt(receipt) != null)\r\n disableSeenUserlogs([receipt.logId])\r\n\r\n queuedPurchaseReceipts.$rawdelete(receipt.logId)\r\n })\r\n }" + } +} diff --git a/gui-patches/online-shop/present-saved-entitlement-grants/patch.json b/gui-patches/online-shop/present-saved-entitlement-grants/patch.json new file mode 100644 index 0000000..3231cef --- /dev/null +++ b/gui-patches/online-shop/present-saved-entitlement-grants/patch.json @@ -0,0 +1,30 @@ +{ + "id": "online-shop/present-saved-entitlement-grants", + "title": "Present the benefits recorded by the purchase", + "file": "scripts/userlog/userlogdata.nut", + "program_behaviour": { + "stock": "Entitlement rewards are displayed from the current catalogue.", + "patched": "Use the stored grant amounts and vehicle IDs for the purchase receipt. A retired product uses the existing text confirmation." + }, + "derivation": { + "requirement": "Present the benefits recorded by the purchase", + "cause": "Catalogue bundles include all offered benefits, including vehicles the buyer may already own, and can be retired after the purchase.", + "lighter_options_ruled_out": [ + "Render the current catalogue product directly. This cannot describe what was actually granted." + ], + "if_not_applied": "Already owned vehicles can be listed as new, and receipts for removed products do not open." + }, + "features": [ + "G-Store", + "G-Premium Account" + ], + "evidence": [ + "2.61.0.37 scripts/onlineshop/entitlementview.nut: aircraftGift, goldIncome, wpIncome and entitlementGift are the reward list inputs.", + "2.61.0.37 scripts/onlineshop/onlinepurchase.nut and scripts/sqdagui/framework/msgbox.nut: purchase_done text confirmation and modal result.", + "packages/local-service/src/profile/profile-trophies-log.ts: purchaseReceipt stores the actual grant." + ], + "edit": { + "find": "let { ENTITLEMENTS_PRICE } = require(\"%scripts/utils/configs.nut\")\r\n", + "replace": "let { ENTITLEMENTS_PRICE } = require(\"%scripts/utils/configs.nut\")\r\n\r\nlet queuedPurchaseReceipts = {}\r\nlocal waitingForPurchasePrices = false\r\n\r\nfunction showPurchaseReceipt(receipt) {\r\n let { getEntitlementConfig } = require(\"%scripts/onlineShop/entitlements.nut\")\r\n if (getEntitlementConfig(receipt.entitlement) == null)\r\n return scene_msg_box(\"purchase_done\", get_cur_gui_scene(),\r\n format(loc(\"userlog/buy_entitlement\"), receipt.entitlement),\r\n [[\"ok\", @() null]], \"ok\", { cancel_fn = @() null })\r\n\r\n let granted = receipt.granted\r\n let premiumDays = granted?.premiumDays ?? 0\r\n return showEntitlement(receipt.entitlement, { ignoreAvailability = true }, {\r\n goldIncome = granted?.goldIncome\r\n wpIncome = granted?.wpIncome\r\n aircraftGift = granted % \"aircraftGift\"\r\n entitlementGift = premiumDays > 0 ? [{ alias = \"PremiumAccount\", ttl = premiumDays }] : []\r\n })\r\n}\r\n" + } +} diff --git a/gui-patches/online-shop/render-retired-entitlement-log/patch.json b/gui-patches/online-shop/render-retired-entitlement-log/patch.json new file mode 100644 index 0000000..3804c99 --- /dev/null +++ b/gui-patches/online-shop/render-retired-entitlement-log/patch.json @@ -0,0 +1,30 @@ +{ + "id": "online-shop/render-retired-entitlement-log", + "title": "Keep purchase history readable after a product is removed", + "file": "scripts/userlog/userlogviewdata.nut", + "program_behaviour": { + "stock": "The purchase history renderer looks up the recorded entitlement in the current store catalogue and passes that result to the price and name formatters.", + "patched": "Use the recorded product ID when the current catalogue no longer includes its entry." + }, + "derivation": { + "requirement": "Purchase history remains readable when store tuning removes a configurable product.", + "cause": "getEntitlementConfig returns null for a removed product. The original formatter expects a table.", + "lighter_options_ruled_out": [ + "Remove purchase logs when a product is removed. That loses valid acquisition history." + ], + "if_not_applied": "An older purchase can trigger a script error in the user log after its catalogue entry is removed." + }, + "features": [ + "G-Store", + "G-Premium Account" + ], + "evidence": [ + "2.61.0.37 scripts/userlog/userlogviewdata.nut: EULT_BUYENTITLEMENT renderer.", + "2.61.0.37 scripts/onlineshop/entitlements.nut: getEntitlementConfig, getEntitlementPrice and getEntitlementName.", + "packages/local-service/src/store/store-tuning.ts: configurable product IDs and packs." + ], + "edit": { + "find": " let ent = getEntitlementConfig(logObj.name)\r\n if (\"cost\" in logObj)\r\n ent[\"goldCost\"] <- logObj.cost\r\n local costText = getEntitlementPrice(ent)\r\n if (costText != \"\")\r\n costText = $\" ({costText})\"\r\n\r\n res.name = \"\".concat(format(loc($\"userlog/{logName}\"), getEntitlementName(ent)), costText)", + "replace": " let ent = getEntitlementConfig(logObj.name)\r\n if (ent != null && \"cost\" in logObj)\r\n ent[\"goldCost\"] <- logObj.cost\r\n local costText = ent != null ? getEntitlementPrice(ent) : \"\"\r\n if (costText != \"\")\r\n costText = $\" ({costText})\"\r\n\r\n let productName = ent != null ? getEntitlementName(ent) : logObj.name\r\n res.name = \"\".concat(format(loc($\"userlog/{logName}\"), productName), costText)" + } +} diff --git a/gui-patches/online-shop/resume-purchase-receipts-after-price-update/patch.json b/gui-patches/online-shop/resume-purchase-receipts-after-price-update/patch.json new file mode 100644 index 0000000..b0da179 --- /dev/null +++ b/gui-patches/online-shop/resume-purchase-receipts-after-price-update/patch.json @@ -0,0 +1,30 @@ +{ + "id": "online-shop/resume-purchase-receipts-after-price-update", + "title": "Open pending receipts when the price table arrives", + "file": "scripts/userlog/userlogdata.nut", + "program_behaviour": { + "stock": "The reward scan runs on profile updates and after the reward window closes.", + "patched": "Resume the reward scan when a price update completes for waiting purchase receipts." + }, + "derivation": { + "requirement": "A successful purchase can be displayed when its profile arrives ahead of the price table.", + "cause": "The catalogue and profile are returned by different native tasks.", + "lighter_options_ruled_out": [ + "Wait for the next profile update. A player can remain in the hangar without another profile request after the current refresh." + ], + "if_not_applied": "A recorded receipt can remain unread until an unrelated profile update." + }, + "features": [ + "G-Store", + "G-Premium Account" + ], + "evidence": [ + "2.61.0.37 scripts/utils/configs.nut: ENTITLEMENTS_PRICE broadcasts EntitlementsPriceUpdated.", + "2.61.0.37 scripts/utils/configbase.nut: checkUpdate and the existing price update task.", + "2.61.0.37 scripts/userlog/userlogdata.nut: listener registration for reward scans." + ], + "edit": { + "find": " UpdateGamercard = @(_p) checkNewNotificationUserlogs()\r\n})", + "replace": " UpdateGamercard = @(_p) checkNewNotificationUserlogs()\r\n EntitlementsPriceUpdated = function(_p) {\r\n if (!waitingForPurchasePrices)\r\n return\r\n\r\n waitingForPurchasePrices = false\r\n checkNewNotificationUserlogs()\r\n }\r\n})" + } +} diff --git a/gui-patches/online-shop/return-entitlement-reward-handler/patch.json b/gui-patches/online-shop/return-entitlement-reward-handler/patch.json new file mode 100644 index 0000000..bed273c --- /dev/null +++ b/gui-patches/online-shop/return-entitlement-reward-handler/patch.json @@ -0,0 +1,29 @@ +{ + "id": "online-shop/return-entitlement-reward-handler", + "title": "Open a receipt using the persisted grant", + "file": "scripts/onlineshop/entitlementrewardwnd.nut", + "program_behaviour": { + "stock": "showEntitlement opens the configured reward handler without returning it.", + "patched": "Accept a grant override for saved purchases and return the handler opened by the GUI manager." + }, + "derivation": { + "requirement": "Present each saved entitlement purchase and acknowledge the log after its receipt opens.", + "cause": "A saved purchase can grant fewer items than the current catalogue lists, and the log should be marked seen only once the window opens.", + "lighter_options_ruled_out": [ + "Assume the dialog opened if the product is present. The modal manager may still fail to create the handler." + ], + "if_not_applied": "The calling code cannot distinguish successful display from an unavailable receipt." + }, + "features": [ + "G-Store", + "G-Premium Account" + ], + "evidence": [ + "2.61.0.37 scripts/onlineshop/entitlementrewardwnd.nut: showEntitlement.", + "2.61.0.37 scripts/sqDagui/framework/baseGuiHandlerManager.nut: loadHandler returns the loaded handler." + ], + "edit": { + "find": "function showEntitlement(entitlementId, params = {}) {\r\n let config = getEntitlementConfig(entitlementId)\r\n if (!config) {\r\n logerr($\"Entitlement Reward: Could not find entitlement config {entitlementId}\")\r\n return\r\n }\r\n\r\n handlersManager.loadHandler(EntitlementRewardWnd, {\r\n entitlementConfig = config\r\n viewParams = params\r\n })\r\n}", + "replace": "function showEntitlement(entitlementId, params = {}, granted = null) {\r\n let config = getEntitlementConfig(entitlementId)\r\n if (!config) {\r\n logerr($\"Entitlement Reward: Could not find entitlement config {entitlementId}\")\r\n return\r\n }\r\n\r\n return handlersManager.loadHandler(EntitlementRewardWnd, {\r\n entitlementConfig = granted == null ? config : config.__merge(granted)\r\n viewParams = params\r\n })\r\n}" + } +} diff --git a/gui-patches/online-shop/show-direct-entitlement-gift-icons/patch.json b/gui-patches/online-shop/show-direct-entitlement-gift-icons/patch.json new file mode 100644 index 0000000..7b82172 --- /dev/null +++ b/gui-patches/online-shop/show-direct-entitlement-gift-icons/patch.json @@ -0,0 +1,28 @@ +{ + "id": "online-shop/show-direct-entitlement-gift-icons", + "title": "Include awarded Premium Account days in the receipt icon list", + "file": "scripts/onlineshop/entitlementview.nut", + "program_behaviour": { + "stock": "Gift icons are listed for current catalogue products.", + "patched": "Use the same entitlement gift resolver as the reward list." + }, + "derivation": { + "requirement": "Include awarded Premium Account days in the receipt icon list", + "cause": "A duration recorded by a purchase does not always correspond to a current product ID.", + "lighter_options_ruled_out": [ + "List the new gift only as text. The award would be omitted from the icon count." + ], + "if_not_applied": "The receipt art would omit awarded Premium Account days." + }, + "features": [ + "G-Store", + "G-Premium Account" + ], + "evidence": [ + "2.61.0.37 scripts/onlineshop/entitlementview.nut: getSortedLayersIcons and reward_entitlement." + ], + "edit": { + "find": " .filter(@(entId) getEntitlementConfig(entId) != null)\r\n", + "replace": " .filter(@(gift) getEntitlementGiftConfig(gift) != null)\r\n" + } +} diff --git a/gui-patches/online-shop/show-direct-entitlement-gifts/patch.json b/gui-patches/online-shop/show-direct-entitlement-gifts/patch.json new file mode 100644 index 0000000..1f0e8a0 --- /dev/null +++ b/gui-patches/online-shop/show-direct-entitlement-gifts/patch.json @@ -0,0 +1,28 @@ +{ + "id": "online-shop/show-direct-entitlement-gifts", + "title": "Render awarded Premium Account days in purchase receipts", + "file": "scripts/onlineshop/entitlementview.nut", + "program_behaviour": { + "stock": "Entitlement gift entries are resolved from catalog IDs.", + "patched": "The same gift renderer accepts a Premium Account gift carrying its awarded duration." + }, + "derivation": { + "requirement": "Render awarded Premium Account days in purchase receipts", + "cause": "A pack can grant a duration that is not sold as a separate catalogue product.", + "lighter_options_ruled_out": [ + "Look up a separate Premium Account SKU by duration. Pack durations are independently configurable." + ], + "if_not_applied": "The receipt can omit Premium Account days granted by a pack." + }, + "features": [ + "G-Store", + "G-Premium Account" + ], + "evidence": [ + "2.61.0.37 scripts/onlineshop/entitlementview.nut: getEntitlementGiftView uses the Premium Account icon and getEntitlementName." + ], + "edit": { + "find": "let getEntitlementGiftView = @(entitlement) (entitlement?.entitlementGift ?? []).map(function(giftId) {\r\n let config = getEntitlementConfig(giftId)", + "replace": "let getEntitlementGiftConfig = @(gift) type(gift) == \"table\" ? gift : getEntitlementConfig(gift)\r\n\r\nlet getEntitlementGiftView = @(entitlement) (entitlement?.entitlementGift ?? []).map(function(gift) {\r\n let config = getEntitlementGiftConfig(gift)" + } +} diff --git a/gui-patches/online-shop/show-entitlement-purchase-rewards/patch.json b/gui-patches/online-shop/show-entitlement-purchase-rewards/patch.json new file mode 100644 index 0000000..1be7161 --- /dev/null +++ b/gui-patches/online-shop/show-entitlement-purchase-rewards/patch.json @@ -0,0 +1,30 @@ +{ + "id": "online-shop/show-entitlement-purchase-rewards", + "title": "Read each saved entitlement purchase", + "file": "scripts/userlog/userlogdata.nut", + "program_behaviour": { + "stock": "The notification parser queues receipt dialogs for resource logs carrying an entitlement name.", + "patched": "Collect each purchase log carrying its persisted grant details." + }, + "derivation": { + "requirement": "Present each saved entitlement purchase and acknowledge the log after its receipt opens.", + "cause": "Entitlement purchases belong to EULT_BUYENTITLEMENT. The resource log detail view requires decorator fields.", + "lighter_options_ruled_out": [ + "Use an EULT_BUYING_RESOURCE log for general store products. That would provide an invalid decorator log." + ], + "if_not_applied": "The saved purchase has no receipt when the profile loads." + }, + "features": [ + "G-Store", + "G-Premium Account" + ], + "evidence": [ + "2.61.0.37 scripts/userlog/userlogdata.nut: checkNewNotificationUserlogs, entitlementRewards and disableSeenUserlogs.", + "2.61.0.37 scripts/userlog/userlogviewdata.nut: EULT_BUYENTITLEMENT reads name and optional cost.", + "2.61.0.37 aces.exe: EULT_BUYENTITLEMENT is registered with value 13 at 0x1a5569e." + ], + "edit": { + "find": " else if (blk?.type == EULT_BUYING_RESOURCE) {\r\n", + "replace": " else if (blk?.type == EULT_BUYENTITLEMENT) {\r\n let entitlement = blk?.body.name\r\n let granted = blk?.body.purchaseReceipt\r\n let logId = blk?.id\r\n if (entitlement != null && granted != null && logId != null)\r\n purchaseReceipts.append({ entitlement, granted, logId })\r\n }\r\n else if (blk?.type == EULT_BUYING_RESOURCE) {\r\n" + } +} diff --git a/gui-patches/online-shop/use-entitlement-receipt-for-native-payment/patch.json b/gui-patches/online-shop/use-entitlement-receipt-for-native-payment/patch.json new file mode 100644 index 0000000..54f618b --- /dev/null +++ b/gui-patches/online-shop/use-entitlement-receipt-for-native-payment/patch.json @@ -0,0 +1,31 @@ +{ + "id": "online-shop/use-entitlement-receipt-for-native-payment", + "title": "Use the entitlement receipt as the native payment confirmation", + "file": "scripts/onlineshop/onlinepurchase.nut", + "program_behaviour": { + "stock": "A successful native payment requests a profile update and immediately shows a text-only confirmation.", + "patched": "Track the profile task through its native error handler. The saved purchase log provides the success receipt." + }, + "derivation": { + "requirement": "Present a single success dialog for a successful native payment.", + "cause": "The immediate confirmation and the reward from the persisted purchase log would both report the same grant.", + "lighter_options_ruled_out": [ + "Keep an immediate native success box alongside the receipt. The confirmed grant would be presented again when its log arrives.", + "Show a separate success box on a refresh error. The purchase still has a pending log and would be presented a second time on the next successful refresh." + ], + "if_not_applied": "A successful native purchase can display an immediate confirmation followed by a second one from the purchase log." + }, + "features": [ + "G-Store", + "G-Premium Account" + ], + "evidence": [ + "2.61.0.37 scripts/onlineshop/onlinepurchase.nut: doYuplayPurchase displays a confirmation after update_entitlements.", + "2.61.0.37 scripts/clientstate/localprofile.nut and scripts/userlog/userlogdata.nut: the profile update triggers a gamercard update and unread reward processing.", + "2.61.0.37 scripts/tasker.nut: showErrorMessageBox displays the existing task error on a failed refresh." + ], + "edit": { + "find": " update_entitlements()\r\n\r\n scene_msg_box(\"purchase_done\", get_cur_gui_scene(),\r\n format(loc(\"userlog/buy_entitlement\"), getEntitlementName(product)),\r\n [[\"ok\", @() null]], \"ok\", { cancel_fn = @() null })", + "replace": " let { addTask } = require(\"%scripts/tasker.nut\")\r\n addTask(update_entitlements(), { showErrorMessageBox = true })" + } +} diff --git a/packages/local-service/src/profile/profile-trophies-log.ts b/packages/local-service/src/profile/profile-trophies-log.ts index d810089..14b4385 100644 --- a/packages/local-service/src/profile/profile-trophies-log.ts +++ b/packages/local-service/src/profile/profile-trophies-log.ts @@ -4,12 +4,16 @@ * - `userlogs{ <16-hex-id>{ type:i= time:i= roomId:i64=0 [disabled:b=yes] body{ ... } } }` * (UserLog::serialize 0x95f160, entry fields 0x95ec30; EULT_OPEN_TROPHY = 30 at 0x1a5599b). */ -import { ensureBlock, findBlock, setParam, type BlkBlock, type BlkParam } from '@wto/blk'; +import { appendParam, emptyBlock, ensureBlock, findBlock, findParam, setParam, type BlkBlock, type BlkParam } from '@wto/blk'; import { intField } from './blk-fields.ts'; +import { serverTimeToUnixSeconds, type ServerTime } from './server-time.ts'; const TROPHIES = 'trophies'; const USERLOGS = 'userlogs'; +const PURCHASE_RECEIPT = 'purchaseReceipt'; +// Registered by the client at 0x1a5569e (2.61.0.37). +const EULT_BUYENTITLEMENT = 13; export const EULT_OPEN_TROPHY = 30; export const EULT_BUY_TROPHY = 20; @@ -34,8 +38,16 @@ export interface NewUserLogEntry { export function appendUserLog(profile: BlkBlock, entry: NewUserLogEntry): string { const logs = ensureBlock(profile, USERLOGS); - const seq = logs.blocks.length + 1; - const idHex = ((BigInt(entry.timeSec) * 1000n) + BigInt(seq)).toString(16).padStart(16, '0'); + const timeId = BigInt(entry.timeSec) * 1000n; + // Older entries may be out of timestamp order after a system clock correction. + let highestId = 0n; + for (const log of logs.blocks) { + if (!/^[0-9a-f]{16}$/i.test(log.name)) continue; + const logId = BigInt('0x' + log.name); + if (logId > highestId) highestId = logId; + } + const id = timeId > highestId ? timeId : highestId + 1n; + const idHex = id.toString(16).padStart(16, '0'); logs.blocks.push({ name: idHex, params: [ @@ -52,6 +64,40 @@ export function appendUserLog(profile: BlkBlock, entry: NewUserLogEntry): string return idHex; } +interface EntitlementPurchase { + readonly productId: string; + readonly goldenEagleCost: number | undefined; + readonly goldenEagles: number; + readonly silverLions: number; + readonly premiumDays: number; + readonly vehicles: readonly string[]; +} + +export function appendEntitlementPurchase( + profile: BlkBlock, purchase: EntitlementPurchase, time: ServerTime, +): void { + const bodyParams: BlkParam[] = [ + { name: 'name', value: { type: 'string', value: purchase.productId } }, + ]; + if (purchase.goldenEagleCost !== undefined) { + bodyParams.push({ name: 'cost', value: { type: 'int', value: purchase.goldenEagleCost } }); + } + + const receipt = emptyBlock(PURCHASE_RECEIPT); + if (purchase.goldenEagles > 0) setParam(receipt, 'goldIncome', { type: 'int', value: purchase.goldenEagles }); + if (purchase.silverLions > 0) setParam(receipt, 'wpIncome', { type: 'int64', value: BigInt(purchase.silverLions) }); + if (purchase.premiumDays > 0) setParam(receipt, 'premiumDays', { type: 'int', value: purchase.premiumDays }); + for (const vehicle of purchase.vehicles) { + appendParam(receipt, 'aircraftGift', { type: 'string', value: vehicle }); + } + appendUserLog(profile, { + type: EULT_BUYENTITLEMENT, + timeSec: serverTimeToUnixSeconds(time), + bodyParams, + bodyBlocks: [receipt], + }); +} + /** Mark seen user logs as disabled (`cln_update` `haveToDisable:b=yes` -> `disabled:b=yes`, 0x95ed29/0x95ed66). */ export function disableUserLogs(profile: BlkBlock, ids: Iterable): void { const logs = findBlock(profile, USERLOGS); @@ -62,8 +108,18 @@ export function disableUserLogs(profile: BlkBlock, ids: Iterable): void } } -/** Keep only the newest `keep` user logs (tuning/limits.jsonc userLogsKept); run on every profile refresh. */ +function isPendingPurchaseReceipt(log: BlkBlock): boolean { + if (intField(log, 'type') !== EULT_BUYENTITLEMENT) return false; + const disabled = findParam(log, 'disabled')?.value; + if (disabled?.type === 'bool' && disabled.value) return false; + const body = findBlock(log, 'body'); + return body !== undefined && findBlock(body, PURCHASE_RECEIPT) !== undefined; +} + +/** Keep the newest `keep` user logs and any purchase receipts the client has not seen. */ export function trimUserLogs(profile: BlkBlock, keep: number): void { const logs = findBlock(profile, USERLOGS); - if (logs && logs.blocks.length > keep) logs.blocks.splice(0, logs.blocks.length - keep); + if (!logs || logs.blocks.length <= keep) return; + const cutoff = logs.blocks.length - keep; + logs.blocks = logs.blocks.filter((log, index) => index >= cutoff || isPendingPurchaseReceipt(log)); } diff --git a/packages/local-service/src/profile/server-time.ts b/packages/local-service/src/profile/server-time.ts index 1f9a128..0f3cf68 100644 --- a/packages/local-service/src/profile/server-time.ts +++ b/packages/local-service/src/profile/server-time.ts @@ -21,6 +21,10 @@ export function serverTimeNow(): ServerTime { return serverTimeFromUnixMs(Date.now()); } +export function serverTimeToUnixSeconds(time: ServerTime): number { + return Number((time - UNIX_EPOCH) / (1000n * TICKS_PER_MILLISECOND)); +} + /** A whole or fractional number of hours as ticks. */ export function hoursToTicks(hours: number): bigint { return BigInt(Math.round(hours * 3_600_000)) * TICKS_PER_MILLISECOND; diff --git a/packages/local-service/src/store/store-purchase.ts b/packages/local-service/src/store/store-purchase.ts index 38250d7..651dd5e 100644 --- a/packages/local-service/src/store/store-purchase.ts +++ b/packages/local-service/src/store/store-purchase.ts @@ -9,6 +9,7 @@ import type { BlkBlock } from '@wto/blk'; import { addGoldenEagles, addSilverLions, balanceOf, canAfford, pay, payGjnCents } from '../profile/profile-currency.ts'; import { extendPremiumAccount, hasEntitlement, recordEntitlementPurchase } from '../profile/profile-entitlements.ts'; import { addOwnedVehicle, ownsVehicle } from '../profile/profile-hangar.ts'; +import { appendEntitlementPurchase } from '../profile/profile-trophies-log.ts'; import { ACCEPTED, refused, type RuleOutcome } from '../research/rule-outcome.ts'; import type { StoreCatalogue, StoreProduct } from './store-catalogue.ts'; @@ -65,16 +66,30 @@ export function buyFreeStoreProduct(profile: BlkBlock, product: StoreProduct, no } function grantProductRewards(profile: BlkBlock, product: StoreProduct, nowFiletime: bigint): void { + const before = balanceOf(profile); + const newVehicles: string[] = []; if (product.id !== 'PremiumAccount') recordEntitlementPurchase(profile, product.id); if (product.goldIncome) addGoldenEagles(profile, product.goldIncome); if (product.silverIncome) addSilverLions(profile, product.silverIncome); if (product.premiumDays) extendPremiumAccount(profile, product.premiumDays, nowFiletime); if (product.vehicles) { for (const vehicle of product.vehicles) { - if (!ownsVehicle(profile, vehicle.name)) addOwnedVehicle(profile, vehicle.name); + if (!ownsVehicle(profile, vehicle.name)) { + addOwnedVehicle(profile, vehicle.name); + newVehicles.push(vehicle.name); + } for (const part of vehicle.parts) { if (!ownsVehicle(profile, part)) addOwnedVehicle(profile, part); } } } + const after = balanceOf(profile); + appendEntitlementPurchase(profile, { + productId: product.id, + goldenEagleCost: product.goldCost, + goldenEagles: after.goldenEagles - before.goldenEagles, + silverLions: after.silverLions - before.silverLions, + premiumDays: product.premiumDays ?? 0, + vehicles: newVehicles, + }, nowFiletime); }