@rbxts/scribe 2.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/NOTICE +21 -0
- package/README.md +100 -0
- package/Scribe-source-map.json +1 -0
- package/licenses/ProfileStore-Apache-2.0.txt +201 -0
- package/package.json +32 -0
- package/src/Client/DebugHook.luau +457 -0
- package/src/Client/init.luau +1607 -0
- package/src/Internal/Addons.luau +68 -0
- package/src/Internal/Big.luau +582 -0
- package/src/Internal/Budget.luau +377 -0
- package/src/Internal/Clock.luau +75 -0
- package/src/Internal/Config.luau +17 -0
- package/src/Internal/Conform.luau +400 -0
- package/src/Internal/Datatypes.luau +653 -0
- package/src/Internal/Defaults.luau +12 -0
- package/src/Internal/Derived.luau +428 -0
- package/src/Internal/Exchange.luau +556 -0
- package/src/Internal/ExchangeLeg.luau +1368 -0
- package/src/Internal/ExchangeVerdict.luau +179 -0
- package/src/Internal/Failure.luau +148 -0
- package/src/Internal/Health.luau +320 -0
- package/src/Internal/LeaderboardDiagnostics.luau +36 -0
- package/src/Internal/Log.luau +378 -0
- package/src/Internal/Marker.luau +76 -0
- package/src/Internal/Metrics.luau +152 -0
- package/src/Internal/Node.luau +3954 -0
- package/src/Internal/Profile.luau +69 -0
- package/src/Internal/Rng.luau +83 -0
- package/src/Internal/Sched.luau +56 -0
- package/src/Internal/Signal.luau +199 -0
- package/src/Internal/Store/ProfileStore.luau +3019 -0
- package/src/Internal/Store/init.luau +18 -0
- package/src/Internal/StudioCodec.luau +155 -0
- package/src/Internal/Template.luau +1848 -0
- package/src/Internal/Transport.luau +169 -0
- package/src/Internal/Util.luau +517 -0
- package/src/Internal/Version.luau +4 -0
- package/src/Internal/Wire.luau +1283 -0
- package/src/Server/Analytics.luau +223 -0
- package/src/Server/Commands.luau +728 -0
- package/src/Server/DebugHook.luau +1490 -0
- package/src/Server/Exchanges.luau +737 -0
- package/src/Server/Leaderboards.luau +2143 -0
- package/src/Server/Monetization.luau +3212 -0
- package/src/Server/Persistence.luau +3775 -0
- package/src/Server/Replication.luau +1253 -0
- package/src/Server/ServerStore.luau +81 -0
- package/src/Server/Timed.luau +579 -0
- package/src/Server/init.luau +672 -0
- package/src/Types.luau +480 -0
- package/src/init.luau +2231 -0
- package/types/api.d.ts +252 -0
- package/types/common.d.ts +355 -0
- package/types/index.d.ts +226 -0
- package/types/schema.d.ts +276 -0
|
@@ -0,0 +1,3212 @@
|
|
|
1
|
+
--!strict
|
|
2
|
+
-- Monetization, perks, and gifting. Receipts are fail-closed: PurchaseGranted is
|
|
3
|
+
-- returned only after the grant is durably committed, otherwise NotProcessedYet so
|
|
4
|
+
-- Roblox retries. Never eat Robux.
|
|
5
|
+
|
|
6
|
+
local MarketplaceService = game:GetService("MarketplaceService")
|
|
7
|
+
local Players = game:GetService("Players")
|
|
8
|
+
|
|
9
|
+
local Internal = script.Parent.Parent.Internal
|
|
10
|
+
local Util = require(Internal.Util)
|
|
11
|
+
local Node = require(Internal.Node)
|
|
12
|
+
local Template = require(Internal.Template)
|
|
13
|
+
local Log = require(Internal.Log)
|
|
14
|
+
local Metrics = require(Internal.Metrics)
|
|
15
|
+
local Health = require(Internal.Health)
|
|
16
|
+
local Clock = require(Internal.Clock)
|
|
17
|
+
local Sched = require(Internal.Sched)
|
|
18
|
+
local Rng = require(Internal.Rng)
|
|
19
|
+
local Failure = require(Internal.Failure)
|
|
20
|
+
-- For MAX_IDEMPOTENCY_KEY_BYTES only. Wire's own requires are Internal leaves, so
|
|
21
|
+
-- this adds no module to the bundle and no cycle.
|
|
22
|
+
local Wire = require(Internal.Wire)
|
|
23
|
+
|
|
24
|
+
local Monetization = {}
|
|
25
|
+
|
|
26
|
+
-- Shared across bundles via the require cache: ProcessReceipt is a single
|
|
27
|
+
-- global callback, so a second receipt-owning bundle would silently steal it.
|
|
28
|
+
local receiptsBound = false
|
|
29
|
+
|
|
30
|
+
local PURCHASE_ID_TTL = 7 * 24 * 3600
|
|
31
|
+
local RECEIPT_HISTORY_TTL = 30 * 24 * 3600
|
|
32
|
+
local RECEIPT_HISTORY_BYTES = 1024 * 1024
|
|
33
|
+
local MAX_RECEIPT_HISTORY_BYTES = 2 * 1024 * 1024
|
|
34
|
+
local RECEIPT_PROFILE_BYTES = 3800000
|
|
35
|
+
|
|
36
|
+
-- Unresolved destinations keep their slots until settlement or cancellation.
|
|
37
|
+
local GIFT_AIM_CAP = 64
|
|
38
|
+
-- Caller-supplied idempotency keys live in the Timed store under this prefix, which
|
|
39
|
+
-- keeps shop claims separate from receipt history.
|
|
40
|
+
local PURCHASE_IDEM_PREFIX = "@pi|"
|
|
41
|
+
-- Runaway guard on how many claims can be live at once, not a working limit: an
|
|
42
|
+
-- eviction can let a retry apply a purchase twice (PURCHASE_CLAIM_EVICTED). A game that
|
|
43
|
+
-- outruns it should shorten PurchaseClaimTTL rather than raise this.
|
|
44
|
+
local PURCHASE_CLAIM_CAP = 1000
|
|
45
|
+
|
|
46
|
+
function Monetization.new(ctx: any)
|
|
47
|
+
local self = {} :: any
|
|
48
|
+
local options = ctx.Options
|
|
49
|
+
local compiled: Template.Compiled = ctx.Compiled
|
|
50
|
+
|
|
51
|
+
local logOptions = options.PurchaseLog or {}
|
|
52
|
+
-- Floor at 1: the ring evictors loop `while count >= cap`, so a configured cap of
|
|
53
|
+
-- 0 would spin forever on an empty ring.
|
|
54
|
+
local robuxCap: number = math.max(1, tonumber(logOptions.RobuxCap) or 100)
|
|
55
|
+
local inGameCap: number = math.max(1, tonumber(logOptions.InGameCap) or 100)
|
|
56
|
+
local declaredCategories: { [string]: boolean }? = nil
|
|
57
|
+
if logOptions.PurchaseLogCategories then
|
|
58
|
+
declaredCategories = {}
|
|
59
|
+
for _, category in logOptions.PurchaseLogCategories :: { string } do
|
|
60
|
+
(declaredCategories :: { [string]: boolean })[category] = true
|
|
61
|
+
end
|
|
62
|
+
end
|
|
63
|
+
|
|
64
|
+
-- Which (userId, purchaseId) pairs are mid-grant on THIS server. An in-flight marker,
|
|
65
|
+
-- never persisted; ProcessedPurchaseIds holds durable completion records.
|
|
66
|
+
local receiptsInFlight: { [string]: true } = {}
|
|
67
|
+
|
|
68
|
+
local giftCooldown: number = options.GiftCooldown or 5
|
|
69
|
+
local giftMaxPending: number = options.GiftMaxPending or 20
|
|
70
|
+
local giftIntentTTL: number = options.GiftIntentTTL or 3600
|
|
71
|
+
local purchaseIdTTL: number = options.PurchaseIdTTL or PURCHASE_ID_TTL
|
|
72
|
+
local receiptHistoryBytes = if options.MaxReceiptHistoryBytes ~= nil
|
|
73
|
+
then options.MaxReceiptHistoryBytes
|
|
74
|
+
else RECEIPT_HISTORY_BYTES
|
|
75
|
+
if
|
|
76
|
+
type(receiptHistoryBytes) ~= "number"
|
|
77
|
+
or receiptHistoryBytes ~= receiptHistoryBytes
|
|
78
|
+
or receiptHistoryBytes % 1 ~= 0
|
|
79
|
+
or receiptHistoryBytes < 1
|
|
80
|
+
or receiptHistoryBytes > MAX_RECEIPT_HISTORY_BYTES
|
|
81
|
+
then
|
|
82
|
+
error(`Scribe: MaxReceiptHistoryBytes must be an integer from 1 to {MAX_RECEIPT_HISTORY_BYTES}`, 0)
|
|
83
|
+
end
|
|
84
|
+
local receiptReservations: { [any]: { [string]: true } } = setmetatable({}, { __mode = "k" }) :: any
|
|
85
|
+
-- Caller-supplied purchase claims keep their own retry window.
|
|
86
|
+
local purchaseClaimTTL: number = options.PurchaseClaimTTL or purchaseIdTTL
|
|
87
|
+
local purchaseClaimCap: number = math.max(1, tonumber(options.MaxPurchaseClaims) or PURCHASE_CLAIM_CAP)
|
|
88
|
+
local giftAimCap: number = math.max(1, GIFT_AIM_CAP)
|
|
89
|
+
local allowDuplicateGifts: boolean = options.AllowDuplicateGifts == true
|
|
90
|
+
local noGiftIntentPolicy: string = options.NoGiftIntentPolicy or "GrantOrCredit"
|
|
91
|
+
|
|
92
|
+
-- Overridable for the test harness (fake players cannot be prompted).
|
|
93
|
+
local promptProductPurchase: (player: Player, productId: number) -> () = options.PromptProductPurchase
|
|
94
|
+
or function(player: Player, productId: number)
|
|
95
|
+
MarketplaceService:PromptProductPurchase(player, productId)
|
|
96
|
+
end
|
|
97
|
+
|
|
98
|
+
local promptGamePassPurchase: (player: Player, passId: number) -> () = options.PromptGamePassPurchase
|
|
99
|
+
or function(player: Player, passId: number)
|
|
100
|
+
MarketplaceService:PromptGamePassPurchase(player, passId)
|
|
101
|
+
end
|
|
102
|
+
local promptStopped = false
|
|
103
|
+
type PurchasePrompt = { Entry: any, Connection: any?, Closed: boolean, Cancelled: boolean?, Saving: boolean? }
|
|
104
|
+
local purchasePrompts: { [Player]: PurchasePrompt } = {}
|
|
105
|
+
|
|
106
|
+
local function clearPurchasePrompt(player: Player, pending: PurchasePrompt)
|
|
107
|
+
pending.Closed = true
|
|
108
|
+
if purchasePrompts[player] == pending then
|
|
109
|
+
purchasePrompts[player] = nil
|
|
110
|
+
end
|
|
111
|
+
local connection = pending.Connection
|
|
112
|
+
pending.Connection = nil
|
|
113
|
+
if connection then
|
|
114
|
+
pcall(function()
|
|
115
|
+
connection:Disconnect()
|
|
116
|
+
end)
|
|
117
|
+
end
|
|
118
|
+
end
|
|
119
|
+
|
|
120
|
+
local function finishCancellation(player: Player)
|
|
121
|
+
local pending = purchasePrompts[player]
|
|
122
|
+
if not pending or not pending.Cancelled or pending.Saving then
|
|
123
|
+
return
|
|
124
|
+
end
|
|
125
|
+
pending.Saving = true
|
|
126
|
+
local ok, saved = pcall(ctx.Persistence.AwaitSave, pending.Entry, 10)
|
|
127
|
+
pending.Saving = false
|
|
128
|
+
if ok and saved then
|
|
129
|
+
clearPurchasePrompt(player, pending)
|
|
130
|
+
end
|
|
131
|
+
end
|
|
132
|
+
|
|
133
|
+
-- Same seam as the prompt above: patching MarketplaceService itself is illegal on a
|
|
134
|
+
-- real service Instance, so no ownership spec could run in Studio without it.
|
|
135
|
+
local userOwnsGamePass: (userId: number, passId: number) -> boolean = options.UserOwnsGamePassAsync
|
|
136
|
+
or function(userId: number, passId: number): boolean
|
|
137
|
+
return MarketplaceService:UserOwnsGamePassAsync(userId, passId)
|
|
138
|
+
end
|
|
139
|
+
local getPolicyInfo: (player: Player) -> any = options.GetPolicyInfoAsync
|
|
140
|
+
or function(player: Player): any
|
|
141
|
+
return (game:GetService("PolicyService") :: any):GetPolicyInfoForPlayerAsync(player)
|
|
142
|
+
end
|
|
143
|
+
|
|
144
|
+
-- Registry ----------------------------------------------------------------
|
|
145
|
+
|
|
146
|
+
type Product = {
|
|
147
|
+
Name: string,
|
|
148
|
+
Id: number,
|
|
149
|
+
Category: string?,
|
|
150
|
+
Grant: ((data: any) -> ())?,
|
|
151
|
+
Grants: string?,
|
|
152
|
+
PaidRandom: boolean,
|
|
153
|
+
Retired: boolean,
|
|
154
|
+
}
|
|
155
|
+
local productsByName: { [string]: Product } = {}
|
|
156
|
+
local retiredByName: { [string]: Product } = {}
|
|
157
|
+
local productsById: { [number]: Product } = {}
|
|
158
|
+
local function registerProduct(name: string, config: any, retired: boolean)
|
|
159
|
+
-- Name and Category are persisted as table keys and log values, so invalid UTF-8
|
|
160
|
+
-- would fail the DataStore save (error 104). Reject at registration, not at save.
|
|
161
|
+
if not Util.isUtf8(name) then
|
|
162
|
+
error("Scribe: a product name contains invalid UTF-8 bytes", 0)
|
|
163
|
+
end
|
|
164
|
+
if type(config.Id) ~= "number" then
|
|
165
|
+
error(`Scribe: product "{name}" must declare a numeric Id`, 0)
|
|
166
|
+
end
|
|
167
|
+
-- Grants names a perk key persisted under Perks; checked here so a wrong type or
|
|
168
|
+
-- bad UTF-8 does not wait until someone buys the product.
|
|
169
|
+
if config.Grants ~= nil then
|
|
170
|
+
if type(config.Grants) ~= "string" or config.Grants == "" then
|
|
171
|
+
error(`Scribe: product "{name}" Grants must be a non-empty string naming a perk`, 0)
|
|
172
|
+
end
|
|
173
|
+
if not Util.isUtf8(config.Grants) then
|
|
174
|
+
error(`Scribe: product "{name}" Grants contains invalid UTF-8 bytes`, 0)
|
|
175
|
+
end
|
|
176
|
+
end
|
|
177
|
+
if config.Category ~= nil and not Util.isUtf8(config.Category) then
|
|
178
|
+
error(`Scribe: product "{name}" Category contains invalid UTF-8 bytes`, 0)
|
|
179
|
+
end
|
|
180
|
+
if config.PaidRandom ~= nil and type(config.PaidRandom) ~= "boolean" then
|
|
181
|
+
error(`Scribe: product "{name}" PaidRandom must be a boolean`, 0)
|
|
182
|
+
end
|
|
183
|
+
local product: Product = {
|
|
184
|
+
Name = name,
|
|
185
|
+
Id = config.Id,
|
|
186
|
+
Category = config.Category,
|
|
187
|
+
Grant = config.Grant,
|
|
188
|
+
Grants = config.Grants,
|
|
189
|
+
PaidRandom = config.PaidRandom == true,
|
|
190
|
+
Retired = retired,
|
|
191
|
+
}
|
|
192
|
+
if productsByName[name] or retiredByName[name] then
|
|
193
|
+
error(`Scribe: duplicate active/retired product name "{name}"`, 0)
|
|
194
|
+
end
|
|
195
|
+
(if retired then retiredByName else productsByName)[name] = product
|
|
196
|
+
if productsById[config.Id] then
|
|
197
|
+
error(`Scribe: duplicate product Id {config.Id}`, 0)
|
|
198
|
+
end
|
|
199
|
+
productsById[config.Id] = product
|
|
200
|
+
end
|
|
201
|
+
for name, config in (options.Products or {}) :: { [string]: any } do
|
|
202
|
+
registerProduct(name, config, false)
|
|
203
|
+
end
|
|
204
|
+
for name, config in (options.RetiredProducts or {}) :: { [string]: any } do
|
|
205
|
+
registerProduct(name, config, true)
|
|
206
|
+
end
|
|
207
|
+
|
|
208
|
+
local passesByName: { [string]: { Id: number, Category: string? } } = {}
|
|
209
|
+
local passNamesById: { [number]: string } = {}
|
|
210
|
+
for name, config in (options.Passes or {}) :: { [string]: any } do
|
|
211
|
+
-- Pass Name/Category feed the same persisted structures as products.
|
|
212
|
+
if not Util.isUtf8(name) then
|
|
213
|
+
error("Scribe: a pass name contains invalid UTF-8 bytes", 0)
|
|
214
|
+
end
|
|
215
|
+
if type(config.Id) ~= "number" then
|
|
216
|
+
error(`Scribe: pass "{name}" must declare a numeric Id`, 0)
|
|
217
|
+
end
|
|
218
|
+
if config.Category ~= nil and not Util.isUtf8(config.Category) then
|
|
219
|
+
error(`Scribe: pass "{name}" Category contains invalid UTF-8 bytes`, 0)
|
|
220
|
+
end
|
|
221
|
+
if config.PaidRandom ~= nil then
|
|
222
|
+
error(
|
|
223
|
+
`Scribe: pass "{name}" cannot be PaidRandom; a pass grants a fixed perk, so only a product can be a paid random item`,
|
|
224
|
+
0
|
|
225
|
+
)
|
|
226
|
+
end
|
|
227
|
+
-- One name, one thing. PromptPurchase resolves a name against both registries, so a
|
|
228
|
+
-- name in both would leave resolution order deciding what the player is charged for.
|
|
229
|
+
if productsByName[name] or retiredByName[name] then
|
|
230
|
+
error(
|
|
231
|
+
`Scribe: "{name}" is declared as both a product and a pass; one name cannot mean two `
|
|
232
|
+
.. "purchasable things, because a prompt resolves by name",
|
|
233
|
+
0
|
|
234
|
+
)
|
|
235
|
+
end
|
|
236
|
+
passesByName[name] = { Id = config.Id, Category = config.Category }
|
|
237
|
+
-- Only this reverse map can collide, and PromptGamePassPurchaseFinished is its one
|
|
238
|
+
-- reader: the sole place an engine-supplied Id must become a name again.
|
|
239
|
+
if passNamesById[config.Id] then
|
|
240
|
+
error(
|
|
241
|
+
`Scribe: duplicate pass Id {config.Id}; two pass names cannot share one gamepass Id, because a `
|
|
242
|
+
.. "purchase reports only the Id and Scribe could credit just one of them",
|
|
243
|
+
0
|
|
244
|
+
)
|
|
245
|
+
end
|
|
246
|
+
passNamesById[config.Id] = name
|
|
247
|
+
end
|
|
248
|
+
|
|
249
|
+
local anyPaidRandom = false
|
|
250
|
+
for _, product in productsById do
|
|
251
|
+
anyPaidRandom = anyPaidRandom or product.PaidRandom
|
|
252
|
+
end
|
|
253
|
+
|
|
254
|
+
local declaredPerks: { [string]: boolean }? = nil
|
|
255
|
+
if options.Perks then
|
|
256
|
+
declaredPerks = {}
|
|
257
|
+
for _, perk in options.Perks :: { string } do
|
|
258
|
+
(declaredPerks :: { [string]: boolean })[perk] = true
|
|
259
|
+
end
|
|
260
|
+
end
|
|
261
|
+
|
|
262
|
+
-- Every string Owns() can legitimately answer true for. Owns silently returns false
|
|
263
|
+
-- for anything else, which hides a typo, so warn once per unknown key in DevMode.
|
|
264
|
+
local knownOwnsKeys: { [string]: boolean } = { RobloxPlus = true }
|
|
265
|
+
for name in passesByName do
|
|
266
|
+
knownOwnsKeys[name] = true
|
|
267
|
+
end
|
|
268
|
+
if declaredPerks then
|
|
269
|
+
for perk in declaredPerks do
|
|
270
|
+
knownOwnsKeys[perk] = true
|
|
271
|
+
end
|
|
272
|
+
end
|
|
273
|
+
for _, product in productsById do
|
|
274
|
+
if product.Grants then
|
|
275
|
+
knownOwnsKeys[product.Grants] = true
|
|
276
|
+
-- Otherwise a typo here only surfaces once a player buys the product: the perk
|
|
277
|
+
-- lands under the wrong key and Owns keeps answering false. A declared PASS
|
|
278
|
+
-- name is a legitimate target, not a typo; see checkPerkName.
|
|
279
|
+
if
|
|
280
|
+
ctx.DevMode
|
|
281
|
+
and declaredPerks
|
|
282
|
+
and not declaredPerks[product.Grants]
|
|
283
|
+
and not passesByName[product.Grants]
|
|
284
|
+
then
|
|
285
|
+
Log.Warn(
|
|
286
|
+
"Monetization",
|
|
287
|
+
"UNDECLARED_PERK",
|
|
288
|
+
`product "{product.Name}" grants perk "{product.Grants}", which is not in the Perks registry (typo?)`,
|
|
289
|
+
{ Product = product.Name, Perk = product.Grants }
|
|
290
|
+
)
|
|
291
|
+
end
|
|
292
|
+
end
|
|
293
|
+
end
|
|
294
|
+
local warnedOwnsKeys: { [string]: boolean } = {}
|
|
295
|
+
-- Every public ownership API calls this first. The type check is load-bearing: without
|
|
296
|
+
-- it a nil key reaches `warnedOwnsKeys[key] = true` below, which raises, and only in
|
|
297
|
+
-- Studio since DevMode gates that branch. Everywhere else it falls through and answers
|
|
298
|
+
-- false, silently denying a player who has paid.
|
|
299
|
+
local function checkOwnsKey(key: string, what: string)
|
|
300
|
+
if type(key) ~= "string" then
|
|
301
|
+
-- 4: checkOwnsKey -> self.<Api> -> Data.<Api> -> the game code that got it wrong.
|
|
302
|
+
error(`Scribe: {what}: key must be a string, got {typeof(key)}`, 4)
|
|
303
|
+
end
|
|
304
|
+
if ctx.DevMode and not knownOwnsKeys[key] and not warnedOwnsKeys[key] then
|
|
305
|
+
warnedOwnsKeys[key] = true
|
|
306
|
+
Log.Warn(
|
|
307
|
+
"Monetization",
|
|
308
|
+
"UNKNOWN_OWNS_KEY",
|
|
309
|
+
`Owns("{key}"): "{key}" is not a registered pass, declared perk, or product grant (typo?); it will always return false`,
|
|
310
|
+
{}
|
|
311
|
+
)
|
|
312
|
+
end
|
|
313
|
+
end
|
|
314
|
+
|
|
315
|
+
-- Reserved-root helpers -------------------------------------------------------------
|
|
316
|
+
|
|
317
|
+
-- The library's privileged handle on the reserved root. The public
|
|
318
|
+
-- `Tree.Accessor[RESERVED_ROOT]` refuses every mutator; these ledgers are Scribe's.
|
|
319
|
+
local function reservedAcc(entry: any): any
|
|
320
|
+
return entry.Tree.Reserved
|
|
321
|
+
end
|
|
322
|
+
|
|
323
|
+
local function reservedRaw(data: { [string]: any }): { [string]: any }
|
|
324
|
+
local reserved = data[Template.RESERVED_ROOT]
|
|
325
|
+
if type(reserved) ~= "table" then
|
|
326
|
+
reserved = {}
|
|
327
|
+
data[Template.RESERVED_ROOT] = reserved
|
|
328
|
+
end
|
|
329
|
+
for _, key in
|
|
330
|
+
{
|
|
331
|
+
"Perks",
|
|
332
|
+
"ProcessedPurchaseIds",
|
|
333
|
+
"ReceiptReservations",
|
|
334
|
+
"PendingGifts",
|
|
335
|
+
"GiftAims",
|
|
336
|
+
"GiftCredits",
|
|
337
|
+
"PurchaseLogs",
|
|
338
|
+
}
|
|
339
|
+
do
|
|
340
|
+
if type(reserved[key]) ~= "table" then
|
|
341
|
+
reserved[key] = {}
|
|
342
|
+
end
|
|
343
|
+
end
|
|
344
|
+
if type(reserved.PurchaseLogs.Robux) ~= "table" then
|
|
345
|
+
reserved.PurchaseLogs.Robux = {}
|
|
346
|
+
end
|
|
347
|
+
if type(reserved.PurchaseLogs.InGame) ~= "table" then
|
|
348
|
+
reserved.PurchaseLogs.InGame = {}
|
|
349
|
+
end
|
|
350
|
+
return reserved
|
|
351
|
+
end
|
|
352
|
+
|
|
353
|
+
-- Accept both timestamped records and older bare IDs.
|
|
354
|
+
local function processedId(item: any): string?
|
|
355
|
+
if type(item) == "string" then
|
|
356
|
+
return item
|
|
357
|
+
end
|
|
358
|
+
if type(item) == "table" and type(item.Id) == "string" then
|
|
359
|
+
return item.Id
|
|
360
|
+
end
|
|
361
|
+
return nil
|
|
362
|
+
end
|
|
363
|
+
|
|
364
|
+
local function processedAt(item: any, now: number): number
|
|
365
|
+
local at = if type(item) == "table" then item.At else nil
|
|
366
|
+
return if type(at) == "number" and at == at and at >= 0 and at < math.huge then at else now
|
|
367
|
+
end
|
|
368
|
+
|
|
369
|
+
local function isProcessedRaw(data: { [string]: any }, purchaseId: string): boolean
|
|
370
|
+
local now = Clock.Now()
|
|
371
|
+
for _, item in reservedRaw(data).ProcessedPurchaseIds do
|
|
372
|
+
if processedId(item) == purchaseId and now - processedAt(item, now) < RECEIPT_HISTORY_TTL then
|
|
373
|
+
return true
|
|
374
|
+
end
|
|
375
|
+
end
|
|
376
|
+
return false
|
|
377
|
+
end
|
|
378
|
+
|
|
379
|
+
local function isProcessed(entry: any, purchaseId: string): boolean
|
|
380
|
+
return entry.LiveData ~= nil and isProcessedRaw(entry.LiveData, purchaseId)
|
|
381
|
+
end
|
|
382
|
+
|
|
383
|
+
-- Unknown-age IDs get a full window when migrated.
|
|
384
|
+
local function compactProcessed(list: { any }, preserveUnknown: boolean?): ({ any }, boolean)
|
|
385
|
+
local kept: { any } = {}
|
|
386
|
+
local seen: { [string]: number } = {}
|
|
387
|
+
local now = Clock.Now()
|
|
388
|
+
local changed = false
|
|
389
|
+
for _, item in list do
|
|
390
|
+
local id = processedId(item)
|
|
391
|
+
local at = processedAt(item, now)
|
|
392
|
+
local unknown = type(item) ~= "table" or item.At ~= at
|
|
393
|
+
if id == nil or now - at >= RECEIPT_HISTORY_TTL then
|
|
394
|
+
changed = true
|
|
395
|
+
elseif seen[id] then
|
|
396
|
+
local index = seen[id]
|
|
397
|
+
if at > processedAt(kept[index], now) then
|
|
398
|
+
kept[index] = if preserveUnknown and unknown then id else { Id = id, At = at }
|
|
399
|
+
end
|
|
400
|
+
changed = true
|
|
401
|
+
else
|
|
402
|
+
local record = if preserveUnknown and unknown then id else { Id = id, At = at }
|
|
403
|
+
table.insert(kept, record)
|
|
404
|
+
seen[id] = #kept
|
|
405
|
+
if unknown and (not preserveUnknown or type(item) ~= "string") then
|
|
406
|
+
changed = true
|
|
407
|
+
end
|
|
408
|
+
end
|
|
409
|
+
end
|
|
410
|
+
return kept, changed
|
|
411
|
+
end
|
|
412
|
+
|
|
413
|
+
local function historyForProfile(data: { [string]: any }): ({ any }, boolean)
|
|
414
|
+
local previous = reservedRaw(data).ProcessedPurchaseIds
|
|
415
|
+
local kept, changed = compactProcessed(previous)
|
|
416
|
+
if changed then
|
|
417
|
+
-- Leave migration pending if timestamps would overflow the profile.
|
|
418
|
+
local growth = Util.approxSize(kept) - Util.approxSize(previous)
|
|
419
|
+
if growth > 0 and Util.approxSize(data) + growth > RECEIPT_PROFILE_BYTES then
|
|
420
|
+
return compactProcessed(previous, true)
|
|
421
|
+
end
|
|
422
|
+
end
|
|
423
|
+
return kept, changed
|
|
424
|
+
end
|
|
425
|
+
|
|
426
|
+
local function pruneProcessed(entry: any)
|
|
427
|
+
local kept, changed = historyForProfile(entry.LiveData)
|
|
428
|
+
if changed then
|
|
429
|
+
reservedAcc(entry).ProcessedPurchaseIds.Set(kept)
|
|
430
|
+
end
|
|
431
|
+
end
|
|
432
|
+
|
|
433
|
+
local function pruneProcessedRaw(data: { [string]: any })
|
|
434
|
+
local reserved = reservedRaw(data)
|
|
435
|
+
reserved.ProcessedPurchaseIds = historyForProfile(data)
|
|
436
|
+
end
|
|
437
|
+
|
|
438
|
+
local function canRecordReceipt(
|
|
439
|
+
data: { [string]: any },
|
|
440
|
+
purchaseId: string,
|
|
441
|
+
entry: any?,
|
|
442
|
+
userId: number?,
|
|
443
|
+
route: any?
|
|
444
|
+
): boolean
|
|
445
|
+
if isProcessedRaw(data, purchaseId) then
|
|
446
|
+
return true
|
|
447
|
+
end
|
|
448
|
+
local reserved = reservedRaw(data)
|
|
449
|
+
local existing = reserved.ReceiptReservations[purchaseId]
|
|
450
|
+
if existing and (route == nil or type(existing) == "table") then
|
|
451
|
+
return true -- finishing a durable reservation releases its capacity
|
|
452
|
+
end
|
|
453
|
+
local ids = compactProcessed(reserved.ProcessedPurchaseIds)
|
|
454
|
+
local completedBytes = Util.approxSize(ids)
|
|
455
|
+
local seen = {}
|
|
456
|
+
for _, record in ids do
|
|
457
|
+
seen[record.Id] = true
|
|
458
|
+
end
|
|
459
|
+
local function include(id: string)
|
|
460
|
+
if not seen[id] then
|
|
461
|
+
seen[id] = true
|
|
462
|
+
table.insert(ids, { Id = id, At = Clock.Now() })
|
|
463
|
+
end
|
|
464
|
+
end
|
|
465
|
+
for id in reserved.ReceiptReservations do
|
|
466
|
+
include(id)
|
|
467
|
+
end
|
|
468
|
+
for id in (entry and receiptReservations[entry]) or {} do
|
|
469
|
+
include(id)
|
|
470
|
+
end
|
|
471
|
+
include(purchaseId)
|
|
472
|
+
local bytes = Util.approxSize(ids)
|
|
473
|
+
local profileBytes = Util.approxSize(data) - Util.approxSize(reserved.ProcessedPurchaseIds) + bytes
|
|
474
|
+
if route then
|
|
475
|
+
profileBytes += Util.approxSize({ [purchaseId] = route }) - Util.approxSize(
|
|
476
|
+
if existing ~= nil then { [purchaseId] = existing } else {}
|
|
477
|
+
)
|
|
478
|
+
end
|
|
479
|
+
if (existing or bytes <= receiptHistoryBytes) and profileBytes <= RECEIPT_PROFILE_BYTES then
|
|
480
|
+
return true
|
|
481
|
+
end
|
|
482
|
+
Log.Error(
|
|
483
|
+
"Monetization",
|
|
484
|
+
"RECEIPT_HISTORY_FULL",
|
|
485
|
+
"receipt history is full; grant deferred without dropping unexpired IDs",
|
|
486
|
+
{
|
|
487
|
+
Player = entry and entry.Player,
|
|
488
|
+
UserId = if entry then entry.UserId else userId,
|
|
489
|
+
PurchaseId = purchaseId,
|
|
490
|
+
Bytes = bytes,
|
|
491
|
+
Limit = receiptHistoryBytes,
|
|
492
|
+
ProfileBytes = profileBytes,
|
|
493
|
+
CompletedBytes = completedBytes,
|
|
494
|
+
}
|
|
495
|
+
)
|
|
496
|
+
Metrics.Add("ReceiptHistoryRefusals")
|
|
497
|
+
return false
|
|
498
|
+
end
|
|
499
|
+
|
|
500
|
+
local function reserveReceipt(entry: any, purchaseId: string): ((() -> ())?, boolean)
|
|
501
|
+
local pending = receiptReservations[entry]
|
|
502
|
+
if pending and pending[purchaseId] then
|
|
503
|
+
return nil, false
|
|
504
|
+
end
|
|
505
|
+
if not canRecordReceipt(entry.LiveData, purchaseId, entry) then
|
|
506
|
+
return nil, true
|
|
507
|
+
end
|
|
508
|
+
if not pending then
|
|
509
|
+
pending = {}
|
|
510
|
+
receiptReservations[entry] = pending
|
|
511
|
+
end
|
|
512
|
+
pending[purchaseId] = true
|
|
513
|
+
return function()
|
|
514
|
+
pending[purchaseId] = nil
|
|
515
|
+
if next(pending) == nil then
|
|
516
|
+
receiptReservations[entry] = nil
|
|
517
|
+
end
|
|
518
|
+
end,
|
|
519
|
+
false
|
|
520
|
+
end
|
|
521
|
+
|
|
522
|
+
local function markProcessedRaw(data: { [string]: any }, purchaseId: string)
|
|
523
|
+
local reserved = reservedRaw(data)
|
|
524
|
+
local kept = historyForProfile(data)
|
|
525
|
+
if not isProcessedRaw(data, purchaseId) then
|
|
526
|
+
table.insert(kept, { Id = purchaseId, At = Clock.Now() })
|
|
527
|
+
end
|
|
528
|
+
reserved.ProcessedPurchaseIds = kept
|
|
529
|
+
reserved.ReceiptReservations[purchaseId] = nil
|
|
530
|
+
end
|
|
531
|
+
|
|
532
|
+
local function markProcessed(entry: any, purchaseId: string)
|
|
533
|
+
local accessor = reservedAcc(entry).ProcessedPurchaseIds
|
|
534
|
+
local kept = historyForProfile(entry.LiveData)
|
|
535
|
+
if not isProcessed(entry, purchaseId) then
|
|
536
|
+
table.insert(kept, { Id = purchaseId, At = Clock.Now() })
|
|
537
|
+
end
|
|
538
|
+
accessor.Set(kept)
|
|
539
|
+
if reservedRaw(entry.LiveData).ReceiptReservations[purchaseId] then
|
|
540
|
+
reservedAcc(entry).ReceiptReservations[purchaseId].Set(nil)
|
|
541
|
+
end
|
|
542
|
+
end
|
|
543
|
+
|
|
544
|
+
-- Gift records: the live intent and the archived aim -------------------------
|
|
545
|
+
--
|
|
546
|
+
-- Both have the same shape ({ RecipientId, GiftId, Ts, Product }), so the receipt arms
|
|
547
|
+
-- settle an aim with the code that settles an intent rather than a hand-mirrored copy
|
|
548
|
+
-- that drifts. `fromAim` selects the container everywhere.
|
|
549
|
+
local PENDING_GIFTS = "PendingGifts"
|
|
550
|
+
local GIFT_AIMS = "GiftAims"
|
|
551
|
+
|
|
552
|
+
local function giftRecordKey(fromAim: boolean): string
|
|
553
|
+
return if fromAim then GIFT_AIMS else PENDING_GIFTS
|
|
554
|
+
end
|
|
555
|
+
|
|
556
|
+
local function validRecipientId(value: any): number?
|
|
557
|
+
local recipientId = tonumber(value)
|
|
558
|
+
if
|
|
559
|
+
recipientId == nil
|
|
560
|
+
or recipientId ~= recipientId
|
|
561
|
+
or recipientId == math.huge
|
|
562
|
+
or recipientId == -math.huge
|
|
563
|
+
or recipientId <= 0
|
|
564
|
+
or recipientId % 1 ~= 0
|
|
565
|
+
then
|
|
566
|
+
return nil
|
|
567
|
+
end
|
|
568
|
+
return recipientId
|
|
569
|
+
end
|
|
570
|
+
|
|
571
|
+
-- Receipt-bound routes outlive replaceable product intents and aims.
|
|
572
|
+
local function readReceiptRoute(reserved: any, purchaseId: string, product: Product): (any?, boolean)
|
|
573
|
+
local route = reserved.ReceiptReservations[purchaseId]
|
|
574
|
+
if route == nil or route == true then
|
|
575
|
+
return nil, false
|
|
576
|
+
end
|
|
577
|
+
if
|
|
578
|
+
type(route) ~= "table"
|
|
579
|
+
or route.Product ~= product.Name
|
|
580
|
+
or route.ProductId ~= product.Id
|
|
581
|
+
or type(route.RecipientId) ~= "number"
|
|
582
|
+
or validRecipientId(route.RecipientId) == nil
|
|
583
|
+
or type(route.GiftId) ~= "string"
|
|
584
|
+
or route.GiftId == ""
|
|
585
|
+
or type(route.FromAim) ~= "boolean"
|
|
586
|
+
then
|
|
587
|
+
return nil, true
|
|
588
|
+
end
|
|
589
|
+
return route, false
|
|
590
|
+
end
|
|
591
|
+
|
|
592
|
+
local function giftReceiptRoute(product: Product, record: any, fromAim: boolean): any
|
|
593
|
+
return {
|
|
594
|
+
Product = product.Name,
|
|
595
|
+
ProductId = product.Id,
|
|
596
|
+
RecipientId = validRecipientId(record.RecipientId),
|
|
597
|
+
GiftId = record.GiftId,
|
|
598
|
+
FromAim = fromAim,
|
|
599
|
+
}
|
|
600
|
+
end
|
|
601
|
+
|
|
602
|
+
-- Only complete records for this product can supply a destination.
|
|
603
|
+
local function readGiftRecord(
|
|
604
|
+
reserved: { [string]: any },
|
|
605
|
+
fromAim: boolean,
|
|
606
|
+
product: Product
|
|
607
|
+
): {
|
|
608
|
+
[string]: any,
|
|
609
|
+
}?
|
|
610
|
+
local record = reserved[giftRecordKey(fromAim)][tostring(product.Id)]
|
|
611
|
+
if type(record) ~= "table" then
|
|
612
|
+
return nil
|
|
613
|
+
end
|
|
614
|
+
if record.Product ~= nil and record.Product ~= product.Name then
|
|
615
|
+
return nil
|
|
616
|
+
end
|
|
617
|
+
if validRecipientId(record.RecipientId) == nil or type(record.GiftId) ~= "string" or record.GiftId == "" then
|
|
618
|
+
return nil
|
|
619
|
+
end
|
|
620
|
+
-- Age does not release an unresolved destination.
|
|
621
|
+
return record
|
|
622
|
+
end
|
|
623
|
+
|
|
624
|
+
-- Clear only this gift: a saved receipt route may outlive its product slot.
|
|
625
|
+
local function clearGiftRecord(entry: any, productIdStr: string, giftId: string): boolean
|
|
626
|
+
local cleared = false
|
|
627
|
+
for _, key in { PENDING_GIFTS, GIFT_AIMS } do
|
|
628
|
+
local live = reservedRaw(entry.LiveData)[key][productIdStr]
|
|
629
|
+
if type(live) == "table" and tostring(live.GiftId) == giftId then
|
|
630
|
+
reservedAcc(entry)[key][productIdStr].Set(nil)
|
|
631
|
+
cleared = true
|
|
632
|
+
end
|
|
633
|
+
end
|
|
634
|
+
return cleared
|
|
635
|
+
end
|
|
636
|
+
|
|
637
|
+
local function hasPendingGift(entry: any, productId: number): boolean
|
|
638
|
+
local reserved = reservedRaw(entry.LiveData)
|
|
639
|
+
local key = tostring(productId)
|
|
640
|
+
return reserved.PendingGifts[key] ~= nil or reserved.GiftAims[key] ~= nil
|
|
641
|
+
end
|
|
642
|
+
|
|
643
|
+
local function hasConflictingGiftRecords(reserved: any, productId: number): boolean
|
|
644
|
+
local key = tostring(productId)
|
|
645
|
+
local pending, aim = reserved.PendingGifts[key], reserved.GiftAims[key]
|
|
646
|
+
if pending == nil or aim == nil then
|
|
647
|
+
return false
|
|
648
|
+
end
|
|
649
|
+
return type(pending) ~= "table"
|
|
650
|
+
or type(aim) ~= "table"
|
|
651
|
+
or pending.GiftId ~= aim.GiftId
|
|
652
|
+
or pending.RecipientId ~= aim.RecipientId
|
|
653
|
+
or pending.Product ~= aim.Product
|
|
654
|
+
end
|
|
655
|
+
|
|
656
|
+
local function giftHasReceipt(reserved: any, giftId: string): boolean
|
|
657
|
+
for _, route in reserved.ReceiptReservations do
|
|
658
|
+
if route == true or (type(route) == "table" and route.GiftId == giftId) then
|
|
659
|
+
return true
|
|
660
|
+
end
|
|
661
|
+
end
|
|
662
|
+
return false
|
|
663
|
+
end
|
|
664
|
+
|
|
665
|
+
local function cancelGiftRecord(entry: any, productIdStr: string, giftId: string): boolean
|
|
666
|
+
if entry.State ~= "Ready" or entry.TornDown or ctx.Persistence.EntryFor(entry.Player) ~= entry then
|
|
667
|
+
return false
|
|
668
|
+
end
|
|
669
|
+
-- A close event cannot cancel a receipt already being settled.
|
|
670
|
+
if giftHasReceipt(reservedRaw(entry.LiveData), giftId) then
|
|
671
|
+
return false
|
|
672
|
+
end
|
|
673
|
+
return clearGiftRecord(entry, productIdStr, giftId)
|
|
674
|
+
end
|
|
675
|
+
|
|
676
|
+
--- The offline mirror, for use INSIDE an UpdateOffline transform where the slot
|
|
677
|
+
--- has to be re-read against the compare-and-set's own draft.
|
|
678
|
+
local function clearGiftRecordRaw(reserved: { [string]: any }, productIdStr: string, giftId: string)
|
|
679
|
+
for _, key in { PENDING_GIFTS, GIFT_AIMS } do
|
|
680
|
+
local container = reserved[key]
|
|
681
|
+
local live = container[productIdStr]
|
|
682
|
+
if type(live) == "table" and tostring(live.GiftId) == giftId then
|
|
683
|
+
container[productIdStr] = nil
|
|
684
|
+
end
|
|
685
|
+
end
|
|
686
|
+
end
|
|
687
|
+
|
|
688
|
+
local function cancelUnopenedGift(entry: any, productIdStr: string, giftId: string, pending: PurchasePrompt?)
|
|
689
|
+
if entry.State == "Ready" and not entry.TornDown and ctx.Persistence.EntryFor(entry.Player) == entry then
|
|
690
|
+
local cleared = cancelGiftRecord(entry, productIdStr, giftId)
|
|
691
|
+
if cleared and pending and purchasePrompts[entry.Player] == pending and not pending.Closed then
|
|
692
|
+
pending.Cancelled = true
|
|
693
|
+
finishCancellation(entry.Player)
|
|
694
|
+
elseif cleared and promptStopped then
|
|
695
|
+
ctx.Persistence.AwaitSave(entry, 10)
|
|
696
|
+
end
|
|
697
|
+
return
|
|
698
|
+
end
|
|
699
|
+
-- The buyer may have left while the intent save was yielding.
|
|
700
|
+
ctx.Persistence.UpdateOffline(entry.UserId, function(data)
|
|
701
|
+
local reserved = reservedRaw(data)
|
|
702
|
+
if not giftHasReceipt(reserved, giftId) then
|
|
703
|
+
clearGiftRecordRaw(reserved, productIdStr, giftId)
|
|
704
|
+
end
|
|
705
|
+
end)
|
|
706
|
+
end
|
|
707
|
+
|
|
708
|
+
--- Keep a record alive while its purchase is still retrying. Same ownership guard as
|
|
709
|
+
--- the clears, plus a bare `[id].Ts = now` on an absent slot materializes a phantom.
|
|
710
|
+
local function refreshGiftRecordTs(entry: any, fromAim: boolean, productIdStr: string, giftId: string)
|
|
711
|
+
local key = giftRecordKey(fromAim)
|
|
712
|
+
local live = reservedRaw(entry.LiveData)[key][productIdStr]
|
|
713
|
+
if type(live) == "table" and tostring(live.GiftId) == giftId then
|
|
714
|
+
reservedAcc(entry)[key][productIdStr].Ts.Set(Clock.Now())
|
|
715
|
+
end
|
|
716
|
+
end
|
|
717
|
+
|
|
718
|
+
-- Archive only when the destination fits; otherwise keep the pending intent.
|
|
719
|
+
local function archiveGiftAim(entry: any, productIdStr: string, intent: any): boolean
|
|
720
|
+
if
|
|
721
|
+
type(intent) ~= "table"
|
|
722
|
+
or validRecipientId(intent.RecipientId) == nil
|
|
723
|
+
or type(intent.GiftId) ~= "string"
|
|
724
|
+
or intent.GiftId == ""
|
|
725
|
+
then
|
|
726
|
+
return false -- Keep malformed records for repair.
|
|
727
|
+
end
|
|
728
|
+
local aims = reservedRaw(entry.LiveData).GiftAims
|
|
729
|
+
local existing = aims[productIdStr]
|
|
730
|
+
if existing ~= nil then
|
|
731
|
+
return type(existing) == "table"
|
|
732
|
+
and existing.GiftId == intent.GiftId
|
|
733
|
+
and existing.RecipientId == intent.RecipientId
|
|
734
|
+
and existing.Product == intent.Product
|
|
735
|
+
end
|
|
736
|
+
if Util.count(aims) >= giftAimCap then
|
|
737
|
+
Log.Warn(
|
|
738
|
+
"Gifting",
|
|
739
|
+
"GIFT_AIM_CAP_REACHED",
|
|
740
|
+
`the gift aim store is at its cap ({giftAimCap}); keeping the pending gift until it settles`,
|
|
741
|
+
{
|
|
742
|
+
Player = entry.Player,
|
|
743
|
+
Product = tostring(intent.Product),
|
|
744
|
+
RecipientId = tonumber(intent.RecipientId),
|
|
745
|
+
}
|
|
746
|
+
)
|
|
747
|
+
return false
|
|
748
|
+
end
|
|
749
|
+
reservedAcc(entry).GiftAims[productIdStr].Set({
|
|
750
|
+
RecipientId = tonumber(intent.RecipientId),
|
|
751
|
+
GiftId = tostring(intent.GiftId),
|
|
752
|
+
Ts = tonumber(intent.Ts) or Clock.Now(),
|
|
753
|
+
Product = intent.Product,
|
|
754
|
+
})
|
|
755
|
+
return true
|
|
756
|
+
end
|
|
757
|
+
|
|
758
|
+
local function checkCategory(category: string?)
|
|
759
|
+
if ctx.DevMode and declaredCategories and category and not declaredCategories[category] then
|
|
760
|
+
Log.Warn("Monetization", "UNDECLARED_CATEGORY", `purchase log category "{category}" is not declared`, {})
|
|
761
|
+
end
|
|
762
|
+
end
|
|
763
|
+
|
|
764
|
+
local function appendRing(ringAccessor: any, cap: number, logEntry: { [string]: any })
|
|
765
|
+
while ringAccessor.Count() >= cap and ringAccessor.Count() > 0 do
|
|
766
|
+
ringAccessor.Remove(1)
|
|
767
|
+
end
|
|
768
|
+
ringAccessor.Insert(logEntry)
|
|
769
|
+
end
|
|
770
|
+
|
|
771
|
+
-- Written only by the receipt/grant path here; game code cannot forge entries.
|
|
772
|
+
local function robuxLog(entry: any, logEntry: { [string]: any })
|
|
773
|
+
checkCategory(logEntry.Category)
|
|
774
|
+
appendRing(reservedAcc(entry).PurchaseLogs.Robux, robuxCap, logEntry)
|
|
775
|
+
end
|
|
776
|
+
|
|
777
|
+
local function robuxLogRaw(data: { [string]: any }, logEntry: { [string]: any })
|
|
778
|
+
local ring = reservedRaw(data).PurchaseLogs.Robux
|
|
779
|
+
while #ring >= robuxCap and #ring > 0 do
|
|
780
|
+
table.remove(ring, 1)
|
|
781
|
+
end
|
|
782
|
+
table.insert(ring, logEntry)
|
|
783
|
+
end
|
|
784
|
+
|
|
785
|
+
-- Perks and unified ownership ---------------------------------------------------
|
|
786
|
+
|
|
787
|
+
--- A declared PASS is a legitimate perk name, for the same reason it is a legitimate
|
|
788
|
+
--- Grants target: a pass cannot be transferred, so granting the perk of the same name
|
|
789
|
+
--- is how a gift confers it, and Owns answers across both namespaces.
|
|
790
|
+
local function checkPerkName(key: string)
|
|
791
|
+
if ctx.DevMode and declaredPerks and not declaredPerks[key] and not passesByName[key] then
|
|
792
|
+
Log.Warn("Monetization", "UNDECLARED_PERK", `perk "{key}" is not in the Perks registry (typo?)`, {})
|
|
793
|
+
end
|
|
794
|
+
end
|
|
795
|
+
|
|
796
|
+
function self.GrantPerk(player: Player, key: string)
|
|
797
|
+
local entry = ctx.Persistence.EntryFor(player)
|
|
798
|
+
if not entry or entry.State ~= "Ready" then
|
|
799
|
+
error("Scribe: GrantPerk requires a Ready player (use Data.WaitForData)", 2)
|
|
800
|
+
end
|
|
801
|
+
checkPerkName(key)
|
|
802
|
+
reservedAcc(entry).Perks[key].Set(true)
|
|
803
|
+
Log.Info("Monetization", "PERK_GRANTED", `perk "{key}" granted`, { Player = player, Perk = key })
|
|
804
|
+
end
|
|
805
|
+
|
|
806
|
+
function self.RevokePerk(player: Player, key: string)
|
|
807
|
+
local entry = ctx.Persistence.EntryFor(player)
|
|
808
|
+
if not entry or entry.State ~= "Ready" then
|
|
809
|
+
error("Scribe: RevokePerk requires a Ready player", 2)
|
|
810
|
+
end
|
|
811
|
+
reservedAcc(entry).Perks[key].Set(nil)
|
|
812
|
+
Log.Info("Monetization", "PERK_REVOKED", `perk "{key}" revoked`, { Player = player, Perk = key })
|
|
813
|
+
end
|
|
814
|
+
|
|
815
|
+
-- The ownership predicate: perk flag, cached pass ownership, or Roblox Plus. No DevMode
|
|
816
|
+
-- warning and no entry lookup, because internal scans legitimately walk keys that were
|
|
817
|
+
-- never registered.
|
|
818
|
+
local function ownsInternal(player: Player, entry: any, key: string): boolean
|
|
819
|
+
local reserved = reservedRaw(entry.LiveData)
|
|
820
|
+
if reserved.Perks[key] == true then
|
|
821
|
+
return true
|
|
822
|
+
end
|
|
823
|
+
local ownsCache = entry.SessionStore[Template.SESSION_ROOT]
|
|
824
|
+
ownsCache = if type(ownsCache) == "table" then ownsCache.OwnsCache else nil
|
|
825
|
+
if type(ownsCache) == "table" and ownsCache[key] == true then
|
|
826
|
+
return true
|
|
827
|
+
end
|
|
828
|
+
if key == "RobloxPlus" then
|
|
829
|
+
-- Coerce: the property is nil on a player object that predates it, and a nil
|
|
830
|
+
-- would read as "changed" against a false baseline on every ownership scan.
|
|
831
|
+
return player.HasRobloxSubscription == true
|
|
832
|
+
end
|
|
833
|
+
return false
|
|
834
|
+
end
|
|
835
|
+
|
|
836
|
+
-- Paid random items. The policy is per session, read once off the join path;
|
|
837
|
+
-- unknown refuses.
|
|
838
|
+
local POLICY_ATTEMPTS = 3
|
|
839
|
+
local POLICY_RETRY_BASE = 2
|
|
840
|
+
local POLICY_REARM_AFTER = 30
|
|
841
|
+
|
|
842
|
+
local function readPolicy(entry: any, attempts: number)
|
|
843
|
+
local policy = entry.Policy
|
|
844
|
+
for attempt = 1, attempts do
|
|
845
|
+
policy.LastAttempt = Clock.Monotonic()
|
|
846
|
+
local ok, info = pcall(getPolicyInfo, entry.Player)
|
|
847
|
+
if ok and type(info) == "table" then
|
|
848
|
+
policy.Restricted = info.ArePaidRandomItemsRestricted == true
|
|
849
|
+
policy.Phase = "known"
|
|
850
|
+
return
|
|
851
|
+
end
|
|
852
|
+
if attempt == attempts then
|
|
853
|
+
policy.Phase = "failed"
|
|
854
|
+
if not policy.Logged then
|
|
855
|
+
policy.Logged = true
|
|
856
|
+
Log.Warn(
|
|
857
|
+
"Monetization",
|
|
858
|
+
"POLICY_READ_FAIL",
|
|
859
|
+
`could not read the player's policy: {tostring(info)}; paid random items stay refused`,
|
|
860
|
+
{ Player = entry.Player }
|
|
861
|
+
)
|
|
862
|
+
end
|
|
863
|
+
return
|
|
864
|
+
end
|
|
865
|
+
Clock.Wait(Rng.Jitter(POLICY_RETRY_BASE * 2 ^ (attempt - 1)))
|
|
866
|
+
end
|
|
867
|
+
end
|
|
868
|
+
|
|
869
|
+
local function ensurePolicy(entry: any)
|
|
870
|
+
local policy = entry.Policy
|
|
871
|
+
if policy == nil then
|
|
872
|
+
policy = { Phase = "pending", Restricted = false, LastAttempt = 0, Logged = false }
|
|
873
|
+
entry.Policy = policy
|
|
874
|
+
Sched.Spawn(readPolicy, entry, POLICY_ATTEMPTS)
|
|
875
|
+
elseif policy.Phase == "failed" and Clock.Monotonic() - policy.LastAttempt >= POLICY_REARM_AFTER then
|
|
876
|
+
policy.Phase = "pending"
|
|
877
|
+
Sched.Spawn(readPolicy, entry, 1)
|
|
878
|
+
end
|
|
879
|
+
return policy
|
|
880
|
+
end
|
|
881
|
+
|
|
882
|
+
-- Purchase and PromptGift answer in sentences; PromptPurchase answers in ProductState.
|
|
883
|
+
local PAID_RANDOM_REASON: { [string]: string } = {
|
|
884
|
+
["paid-random-restricted"] = "paid random items are not available for this account",
|
|
885
|
+
["policy-pending"] = "cannot check account settings right now; try again in a moment",
|
|
886
|
+
}
|
|
887
|
+
|
|
888
|
+
-- nil when the player may buy paid random items.
|
|
889
|
+
local function paidRandomState(entry: any): string?
|
|
890
|
+
local policy = ensurePolicy(entry)
|
|
891
|
+
if policy.Phase == "known" then
|
|
892
|
+
return if policy.Restricted then "paid-random-restricted" else nil
|
|
893
|
+
end
|
|
894
|
+
return "policy-pending"
|
|
895
|
+
end
|
|
896
|
+
|
|
897
|
+
-- NON-YIELDING: reads the cache refreshOwnership fills asynchronously, so a
|
|
898
|
+
-- genuinely-owned gamepass can still read false just after join. Use OwnsAsync when
|
|
899
|
+
-- the answer has to be authoritative immediately.
|
|
900
|
+
function self.Owns(player: Player, key: string): boolean
|
|
901
|
+
checkOwnsKey(key, "Owns")
|
|
902
|
+
local entry = ctx.Persistence.EntryFor(player)
|
|
903
|
+
if not entry or entry.State ~= "Ready" or not entry.LiveData then
|
|
904
|
+
return false
|
|
905
|
+
end
|
|
906
|
+
return ownsInternal(player, entry, key)
|
|
907
|
+
end
|
|
908
|
+
|
|
909
|
+
-- One function behind both the query and the prompt, so they cannot disagree.
|
|
910
|
+
local function productState(entry: any, name: string, product: any, pass: any): string
|
|
911
|
+
if not entry or entry.State ~= "Ready" then
|
|
912
|
+
return "not-loaded"
|
|
913
|
+
end
|
|
914
|
+
if product and product.PaidRandom then
|
|
915
|
+
local refused = paidRandomState(entry)
|
|
916
|
+
if refused ~= nil then
|
|
917
|
+
return refused
|
|
918
|
+
end
|
|
919
|
+
end
|
|
920
|
+
local ownedKey = if pass then name else product.Grants
|
|
921
|
+
if ownedKey ~= nil and self.Owns(entry.Player, ownedKey) then
|
|
922
|
+
return "owned"
|
|
923
|
+
end
|
|
924
|
+
return "purchasable"
|
|
925
|
+
end
|
|
926
|
+
|
|
927
|
+
function self.GetProductState(player: Player, name: string): string
|
|
928
|
+
local product, pass = productsByName[name], passesByName[name]
|
|
929
|
+
if not product and not pass then
|
|
930
|
+
-- 3: here -> Data.GetProductState -> the caller.
|
|
931
|
+
error(`Scribe.GetProductState: "{tostring(name)}" is not a declared pass or product`, 3)
|
|
932
|
+
end
|
|
933
|
+
return productState(ctx.Persistence.EntryFor(player), name, product, pass)
|
|
934
|
+
end
|
|
935
|
+
|
|
936
|
+
local function setOwnsCache(entry: any, key: string, owned: boolean)
|
|
937
|
+
if entry.Tree and not entry.Tree.Dead then
|
|
938
|
+
entry.Tree.Accessor[Template.SESSION_ROOT].OwnsCache[key].Set(if owned then true else nil)
|
|
939
|
+
end
|
|
940
|
+
end
|
|
941
|
+
|
|
942
|
+
-- Ownership only gains during a session, so a late answer must not clear a confirmed pass.
|
|
943
|
+
local function foldOwnsCache(entry: any, key: string, owned: boolean): boolean
|
|
944
|
+
if not entry.Tree or entry.Tree.Dead then
|
|
945
|
+
return owned
|
|
946
|
+
end
|
|
947
|
+
local kept = owned or entry.Tree.Accessor[Template.SESSION_ROOT].OwnsCache[key].Get() == true
|
|
948
|
+
setOwnsCache(entry, key, kept)
|
|
949
|
+
return kept
|
|
950
|
+
end
|
|
951
|
+
|
|
952
|
+
-- Every key whose ownership is worth tracking: everything registered, plus whatever
|
|
953
|
+
-- the profile actually holds.
|
|
954
|
+
local function ownershipCandidates(entry: any): { [string]: boolean }
|
|
955
|
+
local candidates: { [string]: boolean } = {}
|
|
956
|
+
for key in knownOwnsKeys do
|
|
957
|
+
candidates[key] = true
|
|
958
|
+
end
|
|
959
|
+
local reserved = reservedRaw(entry.LiveData)
|
|
960
|
+
for key in reserved.Perks do
|
|
961
|
+
candidates[key] = true
|
|
962
|
+
end
|
|
963
|
+
local session = entry.SessionStore[Template.SESSION_ROOT]
|
|
964
|
+
local ownsCache = if type(session) == "table" then session.OwnsCache else nil
|
|
965
|
+
if type(ownsCache) == "table" then
|
|
966
|
+
for key in ownsCache do
|
|
967
|
+
candidates[key] = true
|
|
968
|
+
end
|
|
969
|
+
end
|
|
970
|
+
return candidates
|
|
971
|
+
end
|
|
972
|
+
|
|
973
|
+
-- Recompute effective ownership and fire OnOwnershipChanged for keys that actually
|
|
974
|
+
-- flipped. Watching the two inputs (Perks and OwnsCache) covers every write site
|
|
975
|
+
-- with no per-site instrumentation. `silent` seeds the baseline at load.
|
|
976
|
+
local function scanOwnership(entry: any, silent: boolean?)
|
|
977
|
+
if entry.TornDown or not entry.LiveData or entry.State ~= "Ready" then
|
|
978
|
+
return
|
|
979
|
+
end
|
|
980
|
+
local player = entry.Player
|
|
981
|
+
local last = entry.OwnsLast
|
|
982
|
+
if not last then
|
|
983
|
+
last = {}
|
|
984
|
+
entry.OwnsLast = last
|
|
985
|
+
end
|
|
986
|
+
local candidates = ownershipCandidates(entry)
|
|
987
|
+
-- A key that went away still needs its false. ownershipCandidates is built from
|
|
988
|
+
-- current state, so a perk revoked under a name outside the Perks registry is listed
|
|
989
|
+
-- nowhere and its false would never fire. The baseline records what was last
|
|
990
|
+
-- reported, so unioning it in is exactly the set that could still owe a transition,
|
|
991
|
+
-- and it cannot grow without bound: a false fired here never fires again.
|
|
992
|
+
for key in last do
|
|
993
|
+
candidates[key] = true
|
|
994
|
+
end
|
|
995
|
+
for key in candidates do
|
|
996
|
+
local owned = ownsInternal(player, entry, key)
|
|
997
|
+
if owned ~= (last[key] == true) then
|
|
998
|
+
last[key] = owned
|
|
999
|
+
if not silent then
|
|
1000
|
+
ctx.Signals.OnOwnershipChanged:Fire(player, key, owned)
|
|
1001
|
+
end
|
|
1002
|
+
end
|
|
1003
|
+
end
|
|
1004
|
+
end
|
|
1005
|
+
|
|
1006
|
+
-- Attach the ownership watchers for an entry. Detached on unload.
|
|
1007
|
+
local function watchOwnership(entry: any)
|
|
1008
|
+
if not entry.Tree or entry.Tree.Dead then
|
|
1009
|
+
return
|
|
1010
|
+
end
|
|
1011
|
+
local accessor = entry.Tree.Accessor
|
|
1012
|
+
scanOwnership(entry, true) -- baseline: record current state without firing
|
|
1013
|
+
local function onChange()
|
|
1014
|
+
scanOwnership(entry)
|
|
1015
|
+
end
|
|
1016
|
+
entry.OwnsWatchers = {
|
|
1017
|
+
-- Through the privileged handle, not the public child: a public read hands back
|
|
1018
|
+
-- a detached deep copy (readOut in Node.luau), and this callback ignores the
|
|
1019
|
+
-- value entirely.
|
|
1020
|
+
reservedAcc(entry).Perks.Changed(onChange),
|
|
1021
|
+
accessor[Template.SESSION_ROOT].OwnsCache.Changed(onChange),
|
|
1022
|
+
}
|
|
1023
|
+
end
|
|
1024
|
+
|
|
1025
|
+
-- Push the player's current ownership of `key`, then again on every change, deduped so
|
|
1026
|
+
-- only real transitions fire. Returns a disconnect. The public doc-comment lives on
|
|
1027
|
+
-- Data.ObserveOwned (Server/init.luau); keep this a plain comment so docgen does not
|
|
1028
|
+
-- emit a duplicate entry.
|
|
1029
|
+
function self.ObserveOwned(player: Player, key: string, callback: (owned: boolean) -> ()): () -> ()
|
|
1030
|
+
checkOwnsKey(key, "ObserveOwned")
|
|
1031
|
+
local entry = ctx.Persistence.EntryFor(player)
|
|
1032
|
+
if not entry or entry.State ~= "Ready" or not entry.Tree or entry.Tree.Dead then
|
|
1033
|
+
error("Scribe: ObserveOwned requires a Ready player (use Data.WaitForData)", 3)
|
|
1034
|
+
end
|
|
1035
|
+
local last: boolean? = nil
|
|
1036
|
+
local function push()
|
|
1037
|
+
if entry.TornDown or not entry.LiveData then
|
|
1038
|
+
return
|
|
1039
|
+
end
|
|
1040
|
+
local owned = ownsInternal(player, entry, key)
|
|
1041
|
+
if owned ~= last then
|
|
1042
|
+
last = owned
|
|
1043
|
+
Sched.Spawn(callback, owned)
|
|
1044
|
+
end
|
|
1045
|
+
end
|
|
1046
|
+
local accessor = entry.Tree.Accessor
|
|
1047
|
+
-- Privileged handle: see the note in watchOwnership.
|
|
1048
|
+
local disconnectPerk = reservedAcc(entry).Perks.Changed(push)
|
|
1049
|
+
local disconnectCache = accessor[Template.SESSION_ROOT].OwnsCache.Changed(push)
|
|
1050
|
+
push()
|
|
1051
|
+
return function()
|
|
1052
|
+
disconnectPerk()
|
|
1053
|
+
disconnectCache()
|
|
1054
|
+
end
|
|
1055
|
+
end
|
|
1056
|
+
|
|
1057
|
+
-- Flip the replicated OwnsSynced flag once every gamepass check has resolved, so the
|
|
1058
|
+
-- client OwnsAsync knows the initial sync is complete. Idempotent per entry.
|
|
1059
|
+
local function markOwnershipReady(entry: any)
|
|
1060
|
+
if entry.OwnershipReady then
|
|
1061
|
+
return
|
|
1062
|
+
end
|
|
1063
|
+
entry.OwnershipReady = true
|
|
1064
|
+
if entry.Tree and not entry.Tree.Dead then
|
|
1065
|
+
entry.Tree.Accessor[Template.SESSION_ROOT].OwnsSynced.Set(true)
|
|
1066
|
+
end
|
|
1067
|
+
end
|
|
1068
|
+
|
|
1069
|
+
local function refreshOwnership(entry: any)
|
|
1070
|
+
local player = entry.Player
|
|
1071
|
+
entry.OwnershipReady = false
|
|
1072
|
+
setOwnsCache(entry, "RobloxPlus", player.HasRobloxSubscription)
|
|
1073
|
+
-- Count the outstanding gamepass checks; the last to resolve marks the entry
|
|
1074
|
+
-- ownership-ready. No yield between the decrement and the check, so this is safe.
|
|
1075
|
+
local pending = 0
|
|
1076
|
+
for _ in passesByName do
|
|
1077
|
+
pending += 1
|
|
1078
|
+
end
|
|
1079
|
+
if pending == 0 then
|
|
1080
|
+
markOwnershipReady(entry)
|
|
1081
|
+
return
|
|
1082
|
+
end
|
|
1083
|
+
for name, pass in passesByName do
|
|
1084
|
+
Sched.Spawn(function()
|
|
1085
|
+
local ok, owned = pcall(function()
|
|
1086
|
+
return userOwnsGamePass(entry.UserId, pass.Id)
|
|
1087
|
+
end)
|
|
1088
|
+
if ok and not entry.TornDown then
|
|
1089
|
+
-- Fold this resolution into the join baseline before writing it.
|
|
1090
|
+
-- watchOwnership takes its silent baseline while this network round trip
|
|
1091
|
+
-- is still out, so without this every player who already owned a pass got
|
|
1092
|
+
-- a spurious owned=true. OR, never assign: ownership is the union of
|
|
1093
|
+
-- Perks, OwnsCache and RobloxPlus. A nil OwnsLast means the baseline has
|
|
1094
|
+
-- not been taken yet and that scan absorbs this by itself.
|
|
1095
|
+
local last = entry.OwnsLast
|
|
1096
|
+
if last ~= nil and entry.Tree and not entry.Tree.Dead then
|
|
1097
|
+
last[name] = last[name] == true or owned == true
|
|
1098
|
+
end
|
|
1099
|
+
foldOwnsCache(entry, name, owned == true)
|
|
1100
|
+
elseif not ok then
|
|
1101
|
+
-- A throw or throttle leaves this pass unresolved and the cache not-owned.
|
|
1102
|
+
-- Surface it rather than treating a failed check as a confirmed not-owned.
|
|
1103
|
+
Metrics.Add("OwnershipCheckFailures")
|
|
1104
|
+
Log.Warn(
|
|
1105
|
+
"Monetization",
|
|
1106
|
+
"OWNERSHIP_CHECK_FAIL",
|
|
1107
|
+
tostring(owned),
|
|
1108
|
+
{ Player = entry.Player, Pass = name, PassId = pass.Id }
|
|
1109
|
+
)
|
|
1110
|
+
end
|
|
1111
|
+
pending -= 1
|
|
1112
|
+
if pending <= 0 and not entry.TornDown then
|
|
1113
|
+
markOwnershipReady(entry)
|
|
1114
|
+
end
|
|
1115
|
+
end)
|
|
1116
|
+
end
|
|
1117
|
+
end
|
|
1118
|
+
|
|
1119
|
+
-- Like self.Owns, but AUTHORITATIVE: a cached "owned" is returned as-is, anything else
|
|
1120
|
+
-- is verified live against MarketplaceService, so a pass bought moments ago shows
|
|
1121
|
+
-- immediately. Yields. `_timeout` exists only for parity with the client version. The
|
|
1122
|
+
-- public doc-comment lives on Data.OwnsAsync (Server/init.luau); keep this a plain
|
|
1123
|
+
-- comment so docgen does not emit a duplicate entry.
|
|
1124
|
+
function self.OwnsAsync(player: Player, key: string, _timeout: number?): boolean
|
|
1125
|
+
checkOwnsKey(key, "OwnsAsync")
|
|
1126
|
+
local entry = ctx.Persistence.EntryFor(player)
|
|
1127
|
+
if not entry or entry.State ~= "Ready" or not entry.LiveData then
|
|
1128
|
+
return false
|
|
1129
|
+
end
|
|
1130
|
+
-- Ownership only ever gains for the session, so a cached true is already
|
|
1131
|
+
-- verified; skip the query.
|
|
1132
|
+
if self.Owns(player, key) then
|
|
1133
|
+
return true
|
|
1134
|
+
end
|
|
1135
|
+
-- Not owned per the cache. Verify live with the server-side UserOwnsGamePassAsync:
|
|
1136
|
+
-- this is the exploit-proof check to gate grants on, and the client's Owns/OwnsAsync
|
|
1137
|
+
-- are mirror reads that must never gate one. Refresh the cache while we are here.
|
|
1138
|
+
local pass = passesByName[key]
|
|
1139
|
+
if pass and not entry.TornDown then
|
|
1140
|
+
local ok, owned = pcall(function()
|
|
1141
|
+
return userOwnsGamePass(entry.UserId, pass.Id)
|
|
1142
|
+
end)
|
|
1143
|
+
if ok then
|
|
1144
|
+
if not entry.TornDown then
|
|
1145
|
+
return foldOwnsCache(entry, key, owned == true)
|
|
1146
|
+
end
|
|
1147
|
+
return owned == true
|
|
1148
|
+
end
|
|
1149
|
+
Metrics.Add("OwnershipCheckFailures")
|
|
1150
|
+
Log.Warn(
|
|
1151
|
+
"Monetization",
|
|
1152
|
+
"OWNERSHIP_CHECK_FAIL",
|
|
1153
|
+
tostring(owned),
|
|
1154
|
+
{ Player = entry.Player, Pass = key, PassId = pass.Id }
|
|
1155
|
+
)
|
|
1156
|
+
end
|
|
1157
|
+
return self.Owns(player, key)
|
|
1158
|
+
end
|
|
1159
|
+
|
|
1160
|
+
-- Grant application ----------------------------------------------------------------------
|
|
1161
|
+
|
|
1162
|
+
-- DevMode only. A Grant that writes THROUGH a key naming no element dereferences a
|
|
1163
|
+
-- dangling pointer: the element seeds from its defaults, the receipt settles
|
|
1164
|
+
-- PurchaseGranted, and the goods land where the player can never see them. A warning
|
|
1165
|
+
-- and not a refusal, because a dangling id is indistinguishable from a deliberate one.
|
|
1166
|
+
local function seedWatcher(entry: any, label: string): ((seeded: { { string | number } }) -> ())?
|
|
1167
|
+
if not ctx.DevMode then
|
|
1168
|
+
return nil
|
|
1169
|
+
end
|
|
1170
|
+
return function(seeded)
|
|
1171
|
+
local paths = table.create(#seeded)
|
|
1172
|
+
for _, path in seeded do
|
|
1173
|
+
table.insert(paths, Util.pathString(path))
|
|
1174
|
+
end
|
|
1175
|
+
local joined = table.concat(paths, ", ")
|
|
1176
|
+
Log.Warn(
|
|
1177
|
+
"Monetization",
|
|
1178
|
+
"GRANT_SEEDED_ELEMENT",
|
|
1179
|
+
`{label} brought {#paths} container element(s) into existence by writing THROUGH a key `
|
|
1180
|
+
.. `that named none: {joined}. Expected when the id is one you just minted -- a fresh `
|
|
1181
|
+
.. "key starting from the element defaults is ordinary. The case to check is an id "
|
|
1182
|
+
.. "that came from STORED data (a slot, an equipped item, any pointer): if it names "
|
|
1183
|
+
.. "nothing, this grant landed where the player will never see it and the receipt "
|
|
1184
|
+
.. "still settles as delivered. Resolve the id before you spend it. To silence this "
|
|
1185
|
+
.. "for a genuinely new element, create it with a whole-element Set instead.",
|
|
1186
|
+
{ Player = entry.Player, Paths = joined }
|
|
1187
|
+
)
|
|
1188
|
+
end
|
|
1189
|
+
end
|
|
1190
|
+
|
|
1191
|
+
-- Applies a product's effects to a Ready entry. Returns (granted, partial): `granted`
|
|
1192
|
+
-- false means a Grant callback threw, and `partial` says whether writes from before the
|
|
1193
|
+
-- throw are still in the tree. Only the yielding path can leave them, and the caller has
|
|
1194
|
+
-- to know because retrying a partial re-applies it.
|
|
1195
|
+
local function applyProductGrant(entry: any, product: Product): (boolean, boolean)
|
|
1196
|
+
if not product.Grant and not product.Grants then
|
|
1197
|
+
return true, false
|
|
1198
|
+
end
|
|
1199
|
+
-- Atomic, because a receipt is retried: a Grant that wrote part-way and then threw
|
|
1200
|
+
-- would leave those writes in the profile while markProcessed never ran, so every
|
|
1201
|
+
-- retry re-applies them. The Grant must therefore not yield, which is refused loudly
|
|
1202
|
+
-- rather than silently rolled back.
|
|
1203
|
+
local function apply()
|
|
1204
|
+
if product.Grant then
|
|
1205
|
+
(product.Grant :: (any) -> ())(entry.Tree.Accessor)
|
|
1206
|
+
end
|
|
1207
|
+
if product.Grants then
|
|
1208
|
+
checkPerkName(product.Grants)
|
|
1209
|
+
reservedAcc(entry).Perks[product.Grants].Set(true)
|
|
1210
|
+
end
|
|
1211
|
+
end
|
|
1212
|
+
|
|
1213
|
+
local ok, err = entry.Tree:RunTransaction(apply, seedWatcher(entry, `product "{product.Name}"`))
|
|
1214
|
+
if ok then
|
|
1215
|
+
return true, false
|
|
1216
|
+
end
|
|
1217
|
+
|
|
1218
|
+
if err == Node.YIELD_ERROR then
|
|
1219
|
+
-- The Grant yielded, so it cannot be made atomic: a rollback across a yield would
|
|
1220
|
+
-- revert unrelated writes that landed meanwhile, which here means destroying paid
|
|
1221
|
+
-- currency. Refusing outright is a permanent NotProcessedYet, which is worse. Run
|
|
1222
|
+
-- it non-atomically and say so loudly.
|
|
1223
|
+
Log.Error(
|
|
1224
|
+
"Monetization",
|
|
1225
|
+
"GRANT_FAIL",
|
|
1226
|
+
`product "{product.Name}" Grant yields, so it cannot be applied atomically. `
|
|
1227
|
+
.. "It ran WITHOUT rollback: if it throws part-way, its partial writes stay "
|
|
1228
|
+
.. "and Roblox re-applies them on every receipt retry. Move the async work "
|
|
1229
|
+
.. "outside Grant (do it before the prompt, or after via OnSave).",
|
|
1230
|
+
{ Player = entry.Player, Product = product.Name }
|
|
1231
|
+
)
|
|
1232
|
+
local ranOk, ranErr = xpcall(apply, function(e)
|
|
1233
|
+
return debug.traceback(tostring(e), 2)
|
|
1234
|
+
end)
|
|
1235
|
+
if not ranOk then
|
|
1236
|
+
Log.Error("Monetization", "GRANT_FAIL", `product "{product.Name}" Grant threw: {ranErr}`, {
|
|
1237
|
+
Player = entry.Player,
|
|
1238
|
+
})
|
|
1239
|
+
-- PARTIAL: the pre-throw writes are in the tree and cannot be rolled back.
|
|
1240
|
+
return false, true
|
|
1241
|
+
end
|
|
1242
|
+
return true, false
|
|
1243
|
+
end
|
|
1244
|
+
|
|
1245
|
+
Log.Error("Monetization", "GRANT_FAIL", `product "{product.Name}" Grant failed: {err}`, {
|
|
1246
|
+
Player = entry.Player,
|
|
1247
|
+
})
|
|
1248
|
+
-- Not partial: RunTransaction rolled this one back.
|
|
1249
|
+
return false, false
|
|
1250
|
+
end
|
|
1251
|
+
|
|
1252
|
+
-- Gift delivery to a Ready entry on this server. Returns (applied, durable,
|
|
1253
|
+
-- refundable): `applied` means the grant is in the recipient's memory, `durable` that it
|
|
1254
|
+
-- is confirmed saved, and callers reporting PurchaseGranted must require `durable`.
|
|
1255
|
+
-- `refundable` means the delivery PROVABLY did not happen, and is false by default:
|
|
1256
|
+
-- every other failure is ambiguous, and refunding one that did happen grants twice.
|
|
1257
|
+
local function deliverGiftLocalCore(
|
|
1258
|
+
recipientEntry: any,
|
|
1259
|
+
product: Product,
|
|
1260
|
+
purchaseId: string,
|
|
1261
|
+
giftId: string,
|
|
1262
|
+
fromUserId: number
|
|
1263
|
+
): (boolean, boolean, boolean)
|
|
1264
|
+
if isProcessed(recipientEntry, purchaseId) then
|
|
1265
|
+
-- Already granted in memory (possibly on a prior attempt whose save failed);
|
|
1266
|
+
-- confirm it is durable before acknowledging. Held in a local rather than
|
|
1267
|
+
-- tail-returned: a tail call would land AwaitSave's second return in `refundable`.
|
|
1268
|
+
local durable = ctx.Persistence.AwaitSave(recipientEntry, 10)
|
|
1269
|
+
return true, durable, false
|
|
1270
|
+
end
|
|
1271
|
+
local granted, partial = applyProductGrant(recipientEntry, product)
|
|
1272
|
+
if not granted and not partial then
|
|
1273
|
+
-- PROVABLY not delivered: RunTransaction rolled the Grant back, so there is no
|
|
1274
|
+
-- write and no marker. Refunding here is correct.
|
|
1275
|
+
return false, false, true
|
|
1276
|
+
end
|
|
1277
|
+
if not granted then
|
|
1278
|
+
-- Same rule as the online receipt path: a yielding Grant that threw leaves
|
|
1279
|
+
-- writes that cannot be rolled back, and answering "not delivered" makes the
|
|
1280
|
+
-- receipt retry and re-apply them on the RECIPIENT. Settle it once, loudly.
|
|
1281
|
+
Metrics.Add("ReceiptsPartial")
|
|
1282
|
+
Failure.Report({
|
|
1283
|
+
Subsystem = "Receipt",
|
|
1284
|
+
Key = purchaseId,
|
|
1285
|
+
Category = "Monetization",
|
|
1286
|
+
Code = "GRANT_PARTIAL",
|
|
1287
|
+
Message = `gifted product "{product.Name}" Grant yielded and then threw; its partial writes stand, `
|
|
1288
|
+
.. "and the gift is being settled so retries cannot compound them",
|
|
1289
|
+
Context = { Player = recipientEntry.Player, Product = product.Name, PurchaseId = purchaseId },
|
|
1290
|
+
})
|
|
1291
|
+
end
|
|
1292
|
+
robuxLog(recipientEntry, {
|
|
1293
|
+
PurchaseId = purchaseId,
|
|
1294
|
+
Product = product.Name,
|
|
1295
|
+
Category = product.Category,
|
|
1296
|
+
From = { Type = "GiftReceived", FromUserId = fromUserId, GiftId = giftId },
|
|
1297
|
+
Ts = Clock.Now(),
|
|
1298
|
+
})
|
|
1299
|
+
markProcessed(recipientEntry, purchaseId)
|
|
1300
|
+
Metrics.Add("GiftsDelivered")
|
|
1301
|
+
ctx.Signals.OnGiftReceived:Fire(recipientEntry.Player, {
|
|
1302
|
+
FromUserId = fromUserId,
|
|
1303
|
+
Product = product.Name,
|
|
1304
|
+
GiftId = giftId,
|
|
1305
|
+
})
|
|
1306
|
+
-- Await the RECIPIENT's save: the paid value lives in their profile. Held in a
|
|
1307
|
+
-- local for the same reason as the isProcessed exit above.
|
|
1308
|
+
local durable = ctx.Persistence.AwaitSave(recipientEntry, 10)
|
|
1309
|
+
return true, durable, false
|
|
1310
|
+
end
|
|
1311
|
+
|
|
1312
|
+
local function deliverGiftLocal(
|
|
1313
|
+
recipientEntry: any,
|
|
1314
|
+
product: Product,
|
|
1315
|
+
purchaseId: string,
|
|
1316
|
+
giftId: string,
|
|
1317
|
+
fromUserId: number
|
|
1318
|
+
): (boolean, boolean, boolean)
|
|
1319
|
+
pruneProcessed(recipientEntry)
|
|
1320
|
+
if isProcessed(recipientEntry, purchaseId) then
|
|
1321
|
+
return deliverGiftLocalCore(recipientEntry, product, purchaseId, giftId, fromUserId)
|
|
1322
|
+
end
|
|
1323
|
+
local release, clean = reserveReceipt(recipientEntry, purchaseId)
|
|
1324
|
+
if not release then
|
|
1325
|
+
return false, false, clean
|
|
1326
|
+
end
|
|
1327
|
+
local ok, applied, durable, refundable =
|
|
1328
|
+
pcall(deliverGiftLocalCore, recipientEntry, product, purchaseId, giftId, fromUserId)
|
|
1329
|
+
release()
|
|
1330
|
+
if not ok then
|
|
1331
|
+
error(applied, 0)
|
|
1332
|
+
end
|
|
1333
|
+
return applied, durable, refundable
|
|
1334
|
+
end
|
|
1335
|
+
|
|
1336
|
+
-- Durable delivery to any recipient: same server applies directly, another server or
|
|
1337
|
+
-- offline goes by ProfileStore MessageAsync. Returns (applied, durable, refundable)
|
|
1338
|
+
-- as deliverGiftLocal, under the same default.
|
|
1339
|
+
local function deliverGift(
|
|
1340
|
+
product: Product,
|
|
1341
|
+
recipientUserId: number,
|
|
1342
|
+
purchaseId: string,
|
|
1343
|
+
giftId: string,
|
|
1344
|
+
fromUserId: number
|
|
1345
|
+
): (boolean, boolean, boolean)
|
|
1346
|
+
local recipientEntry = ctx.Persistence.EntryForUserId(recipientUserId)
|
|
1347
|
+
if recipientEntry and recipientEntry.State == "Ready" then
|
|
1348
|
+
return deliverGiftLocal(recipientEntry, product, purchaseId, giftId, fromUserId)
|
|
1349
|
+
end
|
|
1350
|
+
-- Not durable and not refundable: the receipt retries on a live server.
|
|
1351
|
+
if ctx.Persistence.Mode == "NoSave" then
|
|
1352
|
+
ctx.Persistence.RefuseNoSave("GiftDelivery")
|
|
1353
|
+
return false, false, false
|
|
1354
|
+
end
|
|
1355
|
+
local ok, delivered, reason, provablyClean = pcall(function()
|
|
1356
|
+
return ctx.Persistence.Store:MessageAsync(ctx.Persistence.KeyFor(recipientUserId), {
|
|
1357
|
+
ScribeGift = true,
|
|
1358
|
+
GiftId = giftId,
|
|
1359
|
+
PurchaseId = purchaseId,
|
|
1360
|
+
Product = product.Name,
|
|
1361
|
+
FromUserId = fromUserId,
|
|
1362
|
+
})
|
|
1363
|
+
end)
|
|
1364
|
+
if ok and delivered == true then
|
|
1365
|
+
-- MessageAsync durably commits the gift to the recipient's key.
|
|
1366
|
+
Health.ReportSuccess("GiftDelivery")
|
|
1367
|
+
Metrics.Add("GiftsDelivered")
|
|
1368
|
+
return true, true, false
|
|
1369
|
+
end
|
|
1370
|
+
if ok and reason == "QueueFull" then
|
|
1371
|
+
-- The recipient's inbox is at its cap. `durable = false` keeps the PAID gift
|
|
1372
|
+
-- alive: the buyer's escrow intent stands, the receipt answers NotProcessedYet
|
|
1373
|
+
-- and Roblox's retry re-sends. This arm cannot say on its own that the CALL wrote
|
|
1374
|
+
-- nothing, because MessageAsync retries UpdateAsync inside one call, so a
|
|
1375
|
+
-- QueueFull can be reported for a message an earlier attempt already queued;
|
|
1376
|
+
-- `provablyClean` is the only value entitled to claim otherwise.
|
|
1377
|
+
--
|
|
1378
|
+
-- Not reported through Failure.Report: a full inbox is a property of one player's
|
|
1379
|
+
-- profile rather than a DataStore fault, and degrading to Outage would start
|
|
1380
|
+
-- refusing every Robux grant, including this receipt's retry.
|
|
1381
|
+
Metrics.Add("MessageQueueFull")
|
|
1382
|
+
if provablyClean ~= true then
|
|
1383
|
+
-- The ambiguous shape, the one that can end in two grants off one payment. A
|
|
1384
|
+
-- second counter rather than a split, so a dashboard watching
|
|
1385
|
+
-- MessageQueueFull still sees every refusal.
|
|
1386
|
+
Metrics.Add("MessageQueueFullAmbiguous")
|
|
1387
|
+
end
|
|
1388
|
+
Log.Warn(
|
|
1389
|
+
"Gifting",
|
|
1390
|
+
"MESSAGE_QUEUE_FULL",
|
|
1391
|
+
if provablyClean == true
|
|
1392
|
+
then "the recipient's message queue is at its cap and no attempt in this call reached "
|
|
1393
|
+
.. "storage; the gift was not delivered and the receipt will retry"
|
|
1394
|
+
else "the recipient's message queue is at its cap, but an earlier attempt in the same "
|
|
1395
|
+
.. "call may already have queued this gift; it is being retried and could arrive twice",
|
|
1396
|
+
{
|
|
1397
|
+
RecipientId = recipientUserId,
|
|
1398
|
+
Product = product.Name,
|
|
1399
|
+
-- False means this refusal is not evidence the gift is absent.
|
|
1400
|
+
ProvablyClean = provablyClean == true,
|
|
1401
|
+
}
|
|
1402
|
+
)
|
|
1403
|
+
-- Refundable only where the store says the whole call is clean. A refund after a
|
|
1404
|
+
-- commit hands back a credit whose retry mints a fresh giftId the recipient's
|
|
1405
|
+
-- receipt history has never seen, so one credit grants twice. Not "was this the first
|
|
1406
|
+
-- attempt?" either: a throttled request never reaches storage, so a full inbox
|
|
1407
|
+
-- behind one is as clean as a full inbox behind nothing.
|
|
1408
|
+
return false, false, provablyClean == true
|
|
1409
|
+
end
|
|
1410
|
+
-- Keyed by recipient. Past this point the send threw, MessageAsync gave up
|
|
1411
|
+
-- retrying, or it refused at its IsClosing door without attempting anything.
|
|
1412
|
+
-- Reporting is the same for all three; the refund below is not.
|
|
1413
|
+
Failure.Report({
|
|
1414
|
+
Subsystem = "GiftDelivery",
|
|
1415
|
+
Key = tostring(recipientUserId),
|
|
1416
|
+
Error = if ok then nil else delivered,
|
|
1417
|
+
Category = "Gifting",
|
|
1418
|
+
Code = "GIFT_DELIVERY_RETRY",
|
|
1419
|
+
Message = "MessageAsync failed; receipt will retry",
|
|
1420
|
+
Context = { RecipientId = recipientUserId, Product = product.Name },
|
|
1421
|
+
})
|
|
1422
|
+
-- AMBIGUOUS BY DEFAULT, refundable only where the store says otherwise. This is the
|
|
1423
|
+
-- lost-answer exit: a throw carries the doubt inside one attempt (a 504 may have
|
|
1424
|
+
-- landed), and a bare `false` carries it whenever the retry loop ended at BindToClose
|
|
1425
|
+
-- after an attempt that could have committed. ProfileStore retries inside this call,
|
|
1426
|
+
-- so the class of the last attempt says nothing about the ones before it;
|
|
1427
|
+
-- `provablyClean` is its aggregate across them. Every throw therefore reads as
|
|
1428
|
+
-- ambiguous, because one lost credit is preferred over one double grant.
|
|
1429
|
+
return false, false, ok and provablyClean == true
|
|
1430
|
+
end
|
|
1431
|
+
|
|
1432
|
+
-- Cross-server message handler (registered by Persistence once Ready).
|
|
1433
|
+
function self.OnProfileMessage(entry: any, message: any, processed: () -> ())
|
|
1434
|
+
if type(message) ~= "table" or message.ScribeGift ~= true then
|
|
1435
|
+
return -- not ours; leave it for other handlers
|
|
1436
|
+
end
|
|
1437
|
+
pruneProcessed(entry)
|
|
1438
|
+
local purchaseId = tostring(message.PurchaseId)
|
|
1439
|
+
if isProcessed(entry, purchaseId) then
|
|
1440
|
+
processed()
|
|
1441
|
+
return
|
|
1442
|
+
end
|
|
1443
|
+
local product = productsByName[tostring(message.Product)] or retiredByName[tostring(message.Product)]
|
|
1444
|
+
if not product then
|
|
1445
|
+
Log.Error(
|
|
1446
|
+
"Gifting",
|
|
1447
|
+
"GIFT_UNKNOWN_PRODUCT",
|
|
1448
|
+
`gift message for unregistered product "{tostring(message.Product)}"`,
|
|
1449
|
+
{
|
|
1450
|
+
Player = entry.Player,
|
|
1451
|
+
}
|
|
1452
|
+
)
|
|
1453
|
+
return -- keep the message; a later deploy can process it
|
|
1454
|
+
end
|
|
1455
|
+
-- Gate on `durable` (2nd return), NOT `applied` (1st): this queued message is the
|
|
1456
|
+
-- only surviving durable copy of the paid gift, and processed() removes it for good.
|
|
1457
|
+
-- Ack-ing a merely in-memory grant loses the gift on a crash.
|
|
1458
|
+
--
|
|
1459
|
+
-- Completion records deduplicate redelivery within the retention window.
|
|
1460
|
+
local _, durable =
|
|
1461
|
+
deliverGiftLocal(entry, product, purchaseId, tostring(message.GiftId), tonumber(message.FromUserId) or 0)
|
|
1462
|
+
if durable then
|
|
1463
|
+
processed()
|
|
1464
|
+
end
|
|
1465
|
+
end
|
|
1466
|
+
|
|
1467
|
+
-- Receipt handling -------------------------------------------------------------
|
|
1468
|
+
|
|
1469
|
+
local NOT_PROCESSED = Enum.ProductPurchaseDecision.NotProcessedYet
|
|
1470
|
+
local GRANTED = Enum.ProductPurchaseDecision.PurchaseGranted
|
|
1471
|
+
|
|
1472
|
+
local function canInferGift(receiptInfo: any): boolean
|
|
1473
|
+
local channel = receiptInfo.ProductPurchaseChannel
|
|
1474
|
+
-- Legacy receipts omit the channel; other channels cannot select an in-game gift.
|
|
1475
|
+
return channel == nil or channel == Enum.ProductPurchaseChannel.InExperience
|
|
1476
|
+
end
|
|
1477
|
+
|
|
1478
|
+
local function retryGiftRoute(userId: number, product: Product, purchaseId: string): Enum.ProductPurchaseDecision
|
|
1479
|
+
Metrics.Add("ReceiptsRetried")
|
|
1480
|
+
Log.Warn("Monetization", "RECEIPT_RETRY", "gift route or recipient proof unavailable; letting Roblox retry", {
|
|
1481
|
+
UserId = userId,
|
|
1482
|
+
Product = product.Name,
|
|
1483
|
+
PurchaseId = purchaseId,
|
|
1484
|
+
})
|
|
1485
|
+
return NOT_PROCESSED
|
|
1486
|
+
end
|
|
1487
|
+
|
|
1488
|
+
local function checkGiftRecord(userId: number, product: Product, purchaseId: string, record: any): boolean
|
|
1489
|
+
if type(record) ~= "table" then
|
|
1490
|
+
retryGiftRoute(userId, product, purchaseId)
|
|
1491
|
+
return false
|
|
1492
|
+
end
|
|
1493
|
+
if validRecipientId(record.RecipientId) == nil then
|
|
1494
|
+
Log.Error(
|
|
1495
|
+
"Gifting",
|
|
1496
|
+
"GIFT_INVALID_RECIPIENT",
|
|
1497
|
+
"gift has an invalid recipient; holding the receipt for repair",
|
|
1498
|
+
{
|
|
1499
|
+
UserId = userId,
|
|
1500
|
+
Product = product.Name,
|
|
1501
|
+
PurchaseId = purchaseId,
|
|
1502
|
+
RecipientId = record.RecipientId,
|
|
1503
|
+
}
|
|
1504
|
+
)
|
|
1505
|
+
Metrics.Add("ReceiptsRetried")
|
|
1506
|
+
return false
|
|
1507
|
+
end
|
|
1508
|
+
if type(record.GiftId) ~= "string" or record.GiftId == "" then
|
|
1509
|
+
retryGiftRoute(userId, product, purchaseId)
|
|
1510
|
+
return false
|
|
1511
|
+
end
|
|
1512
|
+
return true
|
|
1513
|
+
end
|
|
1514
|
+
|
|
1515
|
+
-- Malformed gift slots cannot fall through to a self purchase.
|
|
1516
|
+
local function checkGiftSlots(reserved: any, userId: number, product: Product, purchaseId: string): boolean
|
|
1517
|
+
for _, key in { PENDING_GIFTS, GIFT_AIMS } do
|
|
1518
|
+
local record = reserved[key][tostring(product.Id)]
|
|
1519
|
+
if record == nil then
|
|
1520
|
+
continue
|
|
1521
|
+
end
|
|
1522
|
+
if type(record) == "table" and record.Product ~= nil and record.Product ~= product.Name then
|
|
1523
|
+
continue
|
|
1524
|
+
end
|
|
1525
|
+
if not checkGiftRecord(userId, product, purchaseId, record) then
|
|
1526
|
+
return false
|
|
1527
|
+
end
|
|
1528
|
+
end
|
|
1529
|
+
return true
|
|
1530
|
+
end
|
|
1531
|
+
|
|
1532
|
+
local function recipientAlreadyOwns(recipientUserId: number, perkKey: string): boolean
|
|
1533
|
+
local recipientEntry = ctx.Persistence.EntryForUserId(recipientUserId)
|
|
1534
|
+
if recipientEntry and recipientEntry.State == "Ready" then
|
|
1535
|
+
if self.Owns(recipientEntry.Player, perkKey) then
|
|
1536
|
+
return true
|
|
1537
|
+
end
|
|
1538
|
+
else
|
|
1539
|
+
local data = ctx.Persistence.GetOffline(recipientUserId)
|
|
1540
|
+
if data then
|
|
1541
|
+
local reserved = data[Template.RESERVED_ROOT]
|
|
1542
|
+
if
|
|
1543
|
+
type(reserved) == "table"
|
|
1544
|
+
and type(reserved.Perks) == "table"
|
|
1545
|
+
and reserved.Perks[perkKey] == true
|
|
1546
|
+
then
|
|
1547
|
+
return true
|
|
1548
|
+
end
|
|
1549
|
+
end
|
|
1550
|
+
end
|
|
1551
|
+
local pass = passesByName[perkKey]
|
|
1552
|
+
if pass then
|
|
1553
|
+
local ok, owned = pcall(function()
|
|
1554
|
+
return MarketplaceService:UserOwnsGamePassAsync(recipientUserId, pass.Id)
|
|
1555
|
+
end)
|
|
1556
|
+
if not ok then
|
|
1557
|
+
Metrics.Add("OwnershipCheckFailures")
|
|
1558
|
+
Log.Warn(
|
|
1559
|
+
"Monetization",
|
|
1560
|
+
"OWNERSHIP_CHECK_FAIL",
|
|
1561
|
+
tostring(owned),
|
|
1562
|
+
{ UserId = recipientUserId, PassId = pass.Id }
|
|
1563
|
+
)
|
|
1564
|
+
elseif owned == true then
|
|
1565
|
+
return true
|
|
1566
|
+
end
|
|
1567
|
+
end
|
|
1568
|
+
return false
|
|
1569
|
+
end
|
|
1570
|
+
|
|
1571
|
+
-- Whether THIS purchase was already delivered to the recipient. Returns nil when the
|
|
1572
|
+
-- recipient's data cannot be read, and the caller must then retry, never credit.
|
|
1573
|
+
local function giftAlreadyDelivered(recipientUserId: number, purchaseId: string): boolean?
|
|
1574
|
+
local recipientEntry = ctx.Persistence.EntryForUserId(recipientUserId)
|
|
1575
|
+
if recipientEntry and recipientEntry.State == "Ready" then
|
|
1576
|
+
return isProcessed(recipientEntry, purchaseId)
|
|
1577
|
+
end
|
|
1578
|
+
local data = ctx.Persistence.GetOffline(recipientUserId)
|
|
1579
|
+
if data == nil then
|
|
1580
|
+
return nil
|
|
1581
|
+
end
|
|
1582
|
+
return isProcessedRaw(data, purchaseId)
|
|
1583
|
+
end
|
|
1584
|
+
|
|
1585
|
+
local function intentFor(entry: any, product: Product): { [string]: any }?
|
|
1586
|
+
local reserved = reservedRaw(entry.LiveData)
|
|
1587
|
+
local intent = reserved.PendingGifts[tostring(product.Id)]
|
|
1588
|
+
if type(intent) ~= "table" then
|
|
1589
|
+
return nil
|
|
1590
|
+
end
|
|
1591
|
+
-- Intents are keyed by product Id, so if a deploy retired the product and reused its
|
|
1592
|
+
-- Id within the TTL the stored intent belongs to the OLD product. Honouring it would
|
|
1593
|
+
-- gift the new product to the old recipient, so expire it.
|
|
1594
|
+
if intent.Product ~= nil and intent.Product ~= product.Name then
|
|
1595
|
+
reservedAcc(entry).PendingGifts[tostring(product.Id)].Set(nil)
|
|
1596
|
+
Log.Warn("Gifting", "GIFT_INTENT_EXPIRED", "gift intent belonged to a retired product reusing this Id", {
|
|
1597
|
+
Player = entry.Player,
|
|
1598
|
+
Product = product.Name,
|
|
1599
|
+
})
|
|
1600
|
+
return nil
|
|
1601
|
+
end
|
|
1602
|
+
return intent
|
|
1603
|
+
end
|
|
1604
|
+
|
|
1605
|
+
--- Settle a receipt as the gift it was bought as. `fromAim` says which container holds
|
|
1606
|
+
--- the record: false for a live PendingGifts intent, true for an archived GiftAims aim
|
|
1607
|
+
--- the sweep kept after the intent went stale. One implementation for both, because a
|
|
1608
|
+
--- hand-mirrored copy drifts and every drift here is real money.
|
|
1609
|
+
local function handleGiftReceipt(
|
|
1610
|
+
entry: any,
|
|
1611
|
+
product: Product,
|
|
1612
|
+
intent: { [string]: any },
|
|
1613
|
+
receiptInfo: any,
|
|
1614
|
+
fromAim: boolean
|
|
1615
|
+
): Enum.ProductPurchaseDecision
|
|
1616
|
+
local purchaseId = tostring(receiptInfo.PurchaseId)
|
|
1617
|
+
local route, invalid = readReceiptRoute(reservedRaw(entry.LiveData), purchaseId, product)
|
|
1618
|
+
if invalid then
|
|
1619
|
+
return retryGiftRoute(entry.UserId, product, purchaseId)
|
|
1620
|
+
end
|
|
1621
|
+
if route == nil then
|
|
1622
|
+
if not checkGiftRecord(entry.UserId, product, purchaseId, intent) then
|
|
1623
|
+
return NOT_PROCESSED
|
|
1624
|
+
end
|
|
1625
|
+
route = giftReceiptRoute(product, intent, fromAim)
|
|
1626
|
+
if not canRecordReceipt(entry.LiveData, purchaseId, entry, nil, route) then
|
|
1627
|
+
return NOT_PROCESSED
|
|
1628
|
+
end
|
|
1629
|
+
reservedAcc(entry).ReceiptReservations[purchaseId].Set(route)
|
|
1630
|
+
end
|
|
1631
|
+
-- Pin the receipt's destination before another profile receives value.
|
|
1632
|
+
if not ctx.Persistence.AwaitSave(entry, 10) then
|
|
1633
|
+
Metrics.Add("ReceiptsRetried")
|
|
1634
|
+
return NOT_PROCESSED
|
|
1635
|
+
end
|
|
1636
|
+
fromAim = route.FromAim
|
|
1637
|
+
local recipientId = route.RecipientId
|
|
1638
|
+
local giftId = route.GiftId
|
|
1639
|
+
local productIdStr = tostring(product.Id)
|
|
1640
|
+
|
|
1641
|
+
-- The recipient may have acquired the perk between the prompt and the receipt, so
|
|
1642
|
+
-- delivering would be a no-op grant that burns the buyer's Robux; convert to a gift
|
|
1643
|
+
-- credit instead. Only if this purchase was not already delivered on a prior attempt
|
|
1644
|
+
-- whose buyer-commit failed, or one payment yields both a gift and a credit.
|
|
1645
|
+
local convertToCredit = false
|
|
1646
|
+
if
|
|
1647
|
+
product.Grants
|
|
1648
|
+
and not product.Grant
|
|
1649
|
+
and not allowDuplicateGifts
|
|
1650
|
+
and recipientAlreadyOwns(recipientId, product.Grants)
|
|
1651
|
+
then
|
|
1652
|
+
local delivered = giftAlreadyDelivered(recipientId, purchaseId)
|
|
1653
|
+
if delivered == nil then
|
|
1654
|
+
return retryGiftRoute(entry.UserId, product, purchaseId)
|
|
1655
|
+
end
|
|
1656
|
+
convertToCredit = not delivered
|
|
1657
|
+
end
|
|
1658
|
+
if convertToCredit then
|
|
1659
|
+
local creditsAccessor = reservedAcc(entry).GiftCredits[product.Name]
|
|
1660
|
+
creditsAccessor.Set((tonumber(creditsAccessor.Get()) or 0) + 1)
|
|
1661
|
+
-- Receipt retries may outlive their original product slot.
|
|
1662
|
+
clearGiftRecord(entry, productIdStr, giftId)
|
|
1663
|
+
robuxLog(entry, {
|
|
1664
|
+
PurchaseId = purchaseId,
|
|
1665
|
+
Product = product.Name,
|
|
1666
|
+
Category = product.Category,
|
|
1667
|
+
PriceInRobux = receiptInfo.CurrencySpent,
|
|
1668
|
+
From = { Type = "GiftCredit", IntendedFor = recipientId },
|
|
1669
|
+
Ts = Clock.Now(),
|
|
1670
|
+
})
|
|
1671
|
+
markProcessed(entry, purchaseId)
|
|
1672
|
+
Log.Warn(
|
|
1673
|
+
"Gifting",
|
|
1674
|
+
"GIFT_RECIPIENT_ALREADY_OWNS",
|
|
1675
|
+
"recipient acquired the perk before delivery; converted the purchase to a gift credit",
|
|
1676
|
+
{
|
|
1677
|
+
Player = entry.Player,
|
|
1678
|
+
Product = product.Name,
|
|
1679
|
+
RecipientId = recipientId,
|
|
1680
|
+
}
|
|
1681
|
+
)
|
|
1682
|
+
ctx.Signals.OnGiftCredit:Fire(entry.Player, product.Name)
|
|
1683
|
+
if ctx.Persistence.AwaitSave(entry, 10) then
|
|
1684
|
+
return GRANTED
|
|
1685
|
+
end
|
|
1686
|
+
Metrics.Add("ReceiptsRetried")
|
|
1687
|
+
return NOT_PROCESSED -- idempotency makes the retry safe
|
|
1688
|
+
end
|
|
1689
|
+
|
|
1690
|
+
local _, durable = deliverGift(product, recipientId, purchaseId, giftId, entry.UserId)
|
|
1691
|
+
if not durable then
|
|
1692
|
+
-- Refresh only our record; delivery may have yielded past a replacement.
|
|
1693
|
+
refreshGiftRecordTs(entry, fromAim, productIdStr, giftId)
|
|
1694
|
+
Metrics.Add("ReceiptsRetried")
|
|
1695
|
+
return NOT_PROCESSED
|
|
1696
|
+
end
|
|
1697
|
+
|
|
1698
|
+
-- A retry must never clear another gift's product slot.
|
|
1699
|
+
clearGiftRecord(entry, productIdStr, giftId)
|
|
1700
|
+
robuxLog(entry, {
|
|
1701
|
+
PurchaseId = purchaseId,
|
|
1702
|
+
Product = product.Name,
|
|
1703
|
+
Category = product.Category,
|
|
1704
|
+
PriceInRobux = receiptInfo.CurrencySpent,
|
|
1705
|
+
-- IntendedFor only on an aim-settled line: it is the field every other
|
|
1706
|
+
-- aim-resolved line carries, so one query finds them all.
|
|
1707
|
+
From = {
|
|
1708
|
+
Type = "GiftSent",
|
|
1709
|
+
ToUserId = recipientId,
|
|
1710
|
+
GiftId = giftId,
|
|
1711
|
+
IntendedFor = if fromAim then recipientId else nil,
|
|
1712
|
+
},
|
|
1713
|
+
Ts = Clock.Now(),
|
|
1714
|
+
})
|
|
1715
|
+
markProcessed(entry, purchaseId)
|
|
1716
|
+
Log.Info("Gifting", "GIFT_RECEIPT_GRANTED", "gift purchase delivered", {
|
|
1717
|
+
Player = entry.Player,
|
|
1718
|
+
Product = product.Name,
|
|
1719
|
+
PurchaseId = purchaseId,
|
|
1720
|
+
RecipientId = recipientId,
|
|
1721
|
+
})
|
|
1722
|
+
Metrics.Add("ReceiptsGranted")
|
|
1723
|
+
if ctx.Persistence.AwaitSave(entry, 10) then
|
|
1724
|
+
return GRANTED
|
|
1725
|
+
end
|
|
1726
|
+
Metrics.Add("ReceiptsRetried")
|
|
1727
|
+
return NOT_PROCESSED -- idempotency makes the retry safe
|
|
1728
|
+
end
|
|
1729
|
+
|
|
1730
|
+
local function handleOnlineReceipt(entry: any, product: Product, receiptInfo: any): Enum.ProductPurchaseDecision
|
|
1731
|
+
local purchaseId = tostring(receiptInfo.PurchaseId)
|
|
1732
|
+
-- No duplicate check here, deliberately: handleReceipt does it and there is no yield
|
|
1733
|
+
-- between the two, so a copy here could never see anything new.
|
|
1734
|
+
|
|
1735
|
+
local reserved = reservedRaw(entry.LiveData)
|
|
1736
|
+
local route, invalid = readReceiptRoute(reserved, purchaseId, product)
|
|
1737
|
+
if invalid then
|
|
1738
|
+
return retryGiftRoute(entry.UserId, product, purchaseId)
|
|
1739
|
+
end
|
|
1740
|
+
if route then
|
|
1741
|
+
return handleGiftReceipt(entry, product, route, receiptInfo, route.FromAim)
|
|
1742
|
+
end
|
|
1743
|
+
if
|
|
1744
|
+
(canInferGift(receiptInfo) or reserved.ReceiptReservations[purchaseId] == true)
|
|
1745
|
+
and not checkGiftSlots(reserved, entry.UserId, product, purchaseId)
|
|
1746
|
+
then
|
|
1747
|
+
return NOT_PROCESSED
|
|
1748
|
+
end
|
|
1749
|
+
-- Older builds could leave two destinations for one product. Never guess.
|
|
1750
|
+
if
|
|
1751
|
+
hasConflictingGiftRecords(reserved, product.Id)
|
|
1752
|
+
and (canInferGift(receiptInfo) or reserved.ReceiptReservations[purchaseId] == true)
|
|
1753
|
+
then
|
|
1754
|
+
return retryGiftRoute(entry.UserId, product, purchaseId)
|
|
1755
|
+
end
|
|
1756
|
+
local staleIntent = readGiftRecord(reserved, false, product)
|
|
1757
|
+
if reserved.ReceiptReservations[purchaseId] == true then
|
|
1758
|
+
local legacyRecord = staleIntent or readGiftRecord(reserved, true, product)
|
|
1759
|
+
if legacyRecord == nil then
|
|
1760
|
+
return retryGiftRoute(entry.UserId, product, purchaseId)
|
|
1761
|
+
end
|
|
1762
|
+
return handleGiftReceipt(entry, product, legacyRecord, receiptInfo, staleIntent == nil)
|
|
1763
|
+
end
|
|
1764
|
+
|
|
1765
|
+
local inferGift = canInferGift(receiptInfo)
|
|
1766
|
+
local intent = if inferGift then intentFor(entry, product) else nil
|
|
1767
|
+
if intent then
|
|
1768
|
+
return handleGiftReceipt(entry, product, intent, receiptInfo, false)
|
|
1769
|
+
end
|
|
1770
|
+
|
|
1771
|
+
-- Retained aims still own in-experience receipts, regardless of age.
|
|
1772
|
+
local record, fromAim = staleIntent, false
|
|
1773
|
+
if record == nil then
|
|
1774
|
+
record = readGiftRecord(reservedRaw(entry.LiveData), true, product)
|
|
1775
|
+
fromAim = record ~= nil
|
|
1776
|
+
end
|
|
1777
|
+
if record then
|
|
1778
|
+
local aimedAt = tonumber(record.RecipientId) or 0
|
|
1779
|
+
local presumable = inferGift and fromAim
|
|
1780
|
+
local delivered = if presumable then true else giftAlreadyDelivered(aimedAt, purchaseId)
|
|
1781
|
+
if delivered == nil then
|
|
1782
|
+
return retryGiftRoute(entry.UserId, product, purchaseId)
|
|
1783
|
+
end
|
|
1784
|
+
if delivered then
|
|
1785
|
+
if fromAim then
|
|
1786
|
+
Log.Warn(
|
|
1787
|
+
"Gifting",
|
|
1788
|
+
"GIFT_AIM_SETTLED",
|
|
1789
|
+
"a receipt arrived after its gift intent had been swept; settling it from the durable aim "
|
|
1790
|
+
.. "instead of granting it to the buyer",
|
|
1791
|
+
{
|
|
1792
|
+
Player = entry.Player,
|
|
1793
|
+
Product = product.Name,
|
|
1794
|
+
PurchaseId = purchaseId,
|
|
1795
|
+
RecipientId = aimedAt,
|
|
1796
|
+
}
|
|
1797
|
+
)
|
|
1798
|
+
Metrics.Add("GiftAimsSettled")
|
|
1799
|
+
end
|
|
1800
|
+
return handleGiftReceipt(entry, product, record, receiptInfo, fromAim)
|
|
1801
|
+
end
|
|
1802
|
+
if inferGift and not fromAim then
|
|
1803
|
+
clearGiftRecord(entry, tostring(product.Id), tostring(record.GiftId))
|
|
1804
|
+
end
|
|
1805
|
+
end
|
|
1806
|
+
|
|
1807
|
+
-- No matching intent: NoGiftIntentPolicy. A product with a consumable Grant still
|
|
1808
|
+
-- delivers real value, so the credit path only covers pure perk products.
|
|
1809
|
+
if product.Grants and not product.Grant and self.Owns(entry.Player, product.Grants) then
|
|
1810
|
+
-- Hold further credits until the existing paid credit is spent. Roblox may retry later.
|
|
1811
|
+
if (tonumber(reservedRaw(entry.LiveData).GiftCredits[product.Name]) or 0) > 0 then
|
|
1812
|
+
Log.Warn(
|
|
1813
|
+
"Gifting",
|
|
1814
|
+
"RECEIPT_DECLINED_PENDING_CREDIT",
|
|
1815
|
+
"buyer owns the perk and already holds an unused gift credit; declining the purchase",
|
|
1816
|
+
{
|
|
1817
|
+
Player = entry.Player,
|
|
1818
|
+
Product = product.Name,
|
|
1819
|
+
}
|
|
1820
|
+
)
|
|
1821
|
+
Metrics.Add("ReceiptsDeclined")
|
|
1822
|
+
return NOT_PROCESSED
|
|
1823
|
+
end
|
|
1824
|
+
if noGiftIntentPolicy == "Hold" then
|
|
1825
|
+
Log.Warn(
|
|
1826
|
+
"Gifting",
|
|
1827
|
+
"RECEIPT_HELD",
|
|
1828
|
+
"no gift intent and buyer owns the perk; holding (NoGiftIntentPolicy=Hold)",
|
|
1829
|
+
{
|
|
1830
|
+
Player = entry.Player,
|
|
1831
|
+
Product = product.Name,
|
|
1832
|
+
}
|
|
1833
|
+
)
|
|
1834
|
+
return NOT_PROCESSED
|
|
1835
|
+
end
|
|
1836
|
+
-- GrantOrCredit: a no-op grant would burn Robux, so write a durable gift credit.
|
|
1837
|
+
-- A no-intent purchase never stacks onto a pending credit (declined above), but
|
|
1838
|
+
-- an aimed-gift conversion in handleGiftReceipt may, since that money is taken.
|
|
1839
|
+
local creditsAccessor = reservedAcc(entry).GiftCredits[product.Name]
|
|
1840
|
+
creditsAccessor.Set((creditsAccessor.Get() or 0) + 1)
|
|
1841
|
+
robuxLog(entry, {
|
|
1842
|
+
PurchaseId = purchaseId,
|
|
1843
|
+
Product = product.Name,
|
|
1844
|
+
Category = product.Category,
|
|
1845
|
+
PriceInRobux = receiptInfo.CurrencySpent,
|
|
1846
|
+
From = { Type = "GiftCredit" },
|
|
1847
|
+
Ts = Clock.Now(),
|
|
1848
|
+
})
|
|
1849
|
+
markProcessed(entry, purchaseId)
|
|
1850
|
+
Log.Warn("Gifting", "GIFT_CREDIT_ISSUED", "buyer already owns the perk; issued an unassigned gift credit", {
|
|
1851
|
+
Player = entry.Player,
|
|
1852
|
+
Product = product.Name,
|
|
1853
|
+
})
|
|
1854
|
+
ctx.Signals.OnGiftCredit:Fire(entry.Player, product.Name)
|
|
1855
|
+
if ctx.Persistence.AwaitSave(entry, 10) then
|
|
1856
|
+
return GRANTED
|
|
1857
|
+
end
|
|
1858
|
+
return NOT_PROCESSED
|
|
1859
|
+
end
|
|
1860
|
+
|
|
1861
|
+
if product.Grants and not product.Grant then
|
|
1862
|
+
-- A giftable perk product bought without intent: grant to the buyer.
|
|
1863
|
+
Log.Warn("Gifting", "GIFT_NO_INTENT", "perk product purchased with no gift intent; granting to buyer", {
|
|
1864
|
+
Player = entry.Player,
|
|
1865
|
+
Product = product.Name,
|
|
1866
|
+
})
|
|
1867
|
+
end
|
|
1868
|
+
|
|
1869
|
+
local granted, partial = applyProductGrant(entry, product)
|
|
1870
|
+
if not granted and not partial then
|
|
1871
|
+
Metrics.Add("ReceiptsRetried")
|
|
1872
|
+
return NOT_PROCESSED
|
|
1873
|
+
end
|
|
1874
|
+
if not granted then
|
|
1875
|
+
-- The Grant yielded and then threw, so its writes cannot be taken back and every
|
|
1876
|
+
-- NotProcessedYet retry re-applies them. Settle it as delivered-once and be loud
|
|
1877
|
+
-- so an operator can compensate; unbounded inflation is worse than one partial.
|
|
1878
|
+
Metrics.Add("ReceiptsPartial")
|
|
1879
|
+
Failure.Report({
|
|
1880
|
+
Subsystem = "Receipt",
|
|
1881
|
+
Key = purchaseId,
|
|
1882
|
+
Category = "Monetization",
|
|
1883
|
+
Code = "GRANT_PARTIAL",
|
|
1884
|
+
Message = `product "{product.Name}" Grant yielded and then threw; its partial writes stand, and the `
|
|
1885
|
+
.. "receipt is being settled so retries cannot compound them",
|
|
1886
|
+
Context = { Player = entry.Player, Product = product.Name, PurchaseId = purchaseId },
|
|
1887
|
+
})
|
|
1888
|
+
end
|
|
1889
|
+
robuxLog(entry, {
|
|
1890
|
+
PurchaseId = purchaseId,
|
|
1891
|
+
Product = product.Name,
|
|
1892
|
+
Category = product.Category,
|
|
1893
|
+
PriceInRobux = receiptInfo.CurrencySpent,
|
|
1894
|
+
From = { Type = "Purchase", Partial = if granted then nil else true },
|
|
1895
|
+
Ts = Clock.Now(),
|
|
1896
|
+
})
|
|
1897
|
+
markProcessed(entry, purchaseId)
|
|
1898
|
+
Log.Info("Monetization", "RECEIPT_GRANTED", "purchase granted", {
|
|
1899
|
+
Player = entry.Player,
|
|
1900
|
+
PurchaseId = purchaseId,
|
|
1901
|
+
ProductId = product.Id,
|
|
1902
|
+
})
|
|
1903
|
+
Metrics.Add("ReceiptsGranted")
|
|
1904
|
+
|
|
1905
|
+
-- Auto-flush after every grant: a crash between "player paid" and the next
|
|
1906
|
+
-- autosave must never eat a purchase.
|
|
1907
|
+
if ctx.Persistence.AwaitSave(entry, 10) then
|
|
1908
|
+
return GRANTED
|
|
1909
|
+
end
|
|
1910
|
+
Metrics.Add("ReceiptsRetried")
|
|
1911
|
+
Log.Warn("Monetization", "RECEIPT_RETRY", "grant applied but save unconfirmed; letting Roblox retry", {
|
|
1912
|
+
Player = entry.Player,
|
|
1913
|
+
PurchaseId = purchaseId,
|
|
1914
|
+
})
|
|
1915
|
+
return NOT_PROCESSED
|
|
1916
|
+
end
|
|
1917
|
+
|
|
1918
|
+
--- The offline mirror of handleGiftReceipt, for a buyer no longer on this server.
|
|
1919
|
+
--- `fromAim` selects the container exactly as it does online.
|
|
1920
|
+
---
|
|
1921
|
+
--- Hand-mirrored rather than shared with the online arm because the two write through
|
|
1922
|
+
--- different machinery (accessor tree vs. an UpdateOffline compare-and-set), so
|
|
1923
|
+
--- GiftArmParity.spec is what holds them level.
|
|
1924
|
+
local function settleOfflineGift(
|
|
1925
|
+
userId: number,
|
|
1926
|
+
product: Product,
|
|
1927
|
+
receiptInfo: any,
|
|
1928
|
+
record: { [string]: any },
|
|
1929
|
+
fromAim: boolean
|
|
1930
|
+
): Enum.ProductPurchaseDecision
|
|
1931
|
+
local purchaseId = tostring(receiptInfo.PurchaseId)
|
|
1932
|
+
local productIdStr = tostring(product.Id)
|
|
1933
|
+
|
|
1934
|
+
-- Persist the route and capacity before another profile receives value.
|
|
1935
|
+
local completed = false
|
|
1936
|
+
local reservedOk = ctx.Persistence.UpdateOffline(userId, function(offlineData)
|
|
1937
|
+
pruneProcessedRaw(offlineData)
|
|
1938
|
+
if isProcessedRaw(offlineData, purchaseId) then
|
|
1939
|
+
completed = true
|
|
1940
|
+
return
|
|
1941
|
+
end
|
|
1942
|
+
local reserved = reservedRaw(offlineData)
|
|
1943
|
+
local route, invalid = readReceiptRoute(reserved, purchaseId, product)
|
|
1944
|
+
if invalid then
|
|
1945
|
+
error("gift receipt route does not match this product", 0)
|
|
1946
|
+
end
|
|
1947
|
+
if route == nil then
|
|
1948
|
+
if not checkGiftRecord(userId, product, purchaseId, record) then
|
|
1949
|
+
error("invalid gift record", 0)
|
|
1950
|
+
end
|
|
1951
|
+
if canInferGift(receiptInfo) or reserved.ReceiptReservations[purchaseId] == true then
|
|
1952
|
+
if not checkGiftSlots(reserved, userId, product, purchaseId) then
|
|
1953
|
+
error("invalid gift record", 0)
|
|
1954
|
+
end
|
|
1955
|
+
if hasConflictingGiftRecords(reserved, product.Id) then
|
|
1956
|
+
retryGiftRoute(userId, product, purchaseId)
|
|
1957
|
+
error("ambiguous gift route", 0)
|
|
1958
|
+
end
|
|
1959
|
+
end
|
|
1960
|
+
-- Recheck the selected destination against the writable profile.
|
|
1961
|
+
local current = readGiftRecord(reserved, fromAim, product)
|
|
1962
|
+
if
|
|
1963
|
+
current == nil
|
|
1964
|
+
or current.GiftId ~= record.GiftId
|
|
1965
|
+
or validRecipientId(current.RecipientId) ~= validRecipientId(record.RecipientId)
|
|
1966
|
+
then
|
|
1967
|
+
retryGiftRoute(userId, product, purchaseId)
|
|
1968
|
+
error("gift destination changed before reservation", 0)
|
|
1969
|
+
end
|
|
1970
|
+
route = giftReceiptRoute(product, record, fromAim)
|
|
1971
|
+
end
|
|
1972
|
+
if not canRecordReceipt(offlineData, purchaseId, nil, userId, route) then
|
|
1973
|
+
error("receipt history full", 0)
|
|
1974
|
+
end
|
|
1975
|
+
reservedRaw(offlineData).ReceiptReservations[purchaseId] = route
|
|
1976
|
+
record, fromAim = route, route.FromAim
|
|
1977
|
+
end)
|
|
1978
|
+
if not reservedOk then
|
|
1979
|
+
return NOT_PROCESSED
|
|
1980
|
+
end
|
|
1981
|
+
if completed then
|
|
1982
|
+
return GRANTED
|
|
1983
|
+
end
|
|
1984
|
+
local recipientId = record.RecipientId
|
|
1985
|
+
local giftId = record.GiftId
|
|
1986
|
+
|
|
1987
|
+
-- Same recipient re-check as the online intent path: a no-op delivery burns the
|
|
1988
|
+
-- buyer's Robux, so convert to a credit, but only if this exact purchase is undelivered.
|
|
1989
|
+
local convertToCredit = false
|
|
1990
|
+
if
|
|
1991
|
+
product.Grants
|
|
1992
|
+
and not product.Grant
|
|
1993
|
+
and not allowDuplicateGifts
|
|
1994
|
+
and recipientAlreadyOwns(recipientId, product.Grants)
|
|
1995
|
+
then
|
|
1996
|
+
local delivered = giftAlreadyDelivered(recipientId, purchaseId)
|
|
1997
|
+
if delivered == nil then
|
|
1998
|
+
return retryGiftRoute(userId, product, purchaseId)
|
|
1999
|
+
end
|
|
2000
|
+
convertToCredit = not delivered
|
|
2001
|
+
end
|
|
2002
|
+
if convertToCredit then
|
|
2003
|
+
local ok = ctx.Persistence.UpdateOffline(userId, function(offlineData)
|
|
2004
|
+
-- The dedupe marker, re-read INSIDE the transaction: the decision above was
|
|
2005
|
+
-- made against a GetOffline snapshot, so a cycle that committed in between is
|
|
2006
|
+
-- invisible both to it and to the compare-and-set, whose fingerprint is by
|
|
2007
|
+
-- now the fresh one. Returning early still commits the unchanged draft, so
|
|
2008
|
+
-- the caller answers GRANTED, which is correct: the purchase IS granted, just
|
|
2009
|
+
-- not by this cycle.
|
|
2010
|
+
if isProcessedRaw(offlineData, purchaseId) then
|
|
2011
|
+
return
|
|
2012
|
+
end
|
|
2013
|
+
local offlineReserved = reservedRaw(offlineData)
|
|
2014
|
+
-- Clear OUR record, and only ours. Re-reading the slot inside the transform
|
|
2015
|
+
-- is NOT this guard: the decision that this receipt owns one was made from a
|
|
2016
|
+
-- snapshot taken before two round trips, and a second gift of the same
|
|
2017
|
+
-- product can hold the slot by now with the key unlocked, so nothing refuses.
|
|
2018
|
+
-- Identity is the GiftId, never the slot.
|
|
2019
|
+
clearGiftRecordRaw(offlineReserved, productIdStr, giftId)
|
|
2020
|
+
offlineReserved.GiftCredits[product.Name] = (tonumber(offlineReserved.GiftCredits[product.Name]) or 0)
|
|
2021
|
+
+ 1
|
|
2022
|
+
robuxLogRaw(offlineData, {
|
|
2023
|
+
PurchaseId = purchaseId,
|
|
2024
|
+
Product = product.Name,
|
|
2025
|
+
Category = product.Category,
|
|
2026
|
+
PriceInRobux = receiptInfo.CurrencySpent,
|
|
2027
|
+
From = { Type = "GiftCredit", IntendedFor = recipientId },
|
|
2028
|
+
Ts = Clock.Now(),
|
|
2029
|
+
})
|
|
2030
|
+
markProcessedRaw(offlineData, purchaseId)
|
|
2031
|
+
end)
|
|
2032
|
+
if ok then
|
|
2033
|
+
Log.Warn(
|
|
2034
|
+
"Gifting",
|
|
2035
|
+
"GIFT_RECIPIENT_ALREADY_OWNS",
|
|
2036
|
+
"recipient acquired the perk before delivery; converted the purchase to a gift credit",
|
|
2037
|
+
{
|
|
2038
|
+
UserId = userId,
|
|
2039
|
+
Product = product.Name,
|
|
2040
|
+
RecipientId = recipientId,
|
|
2041
|
+
}
|
|
2042
|
+
)
|
|
2043
|
+
end
|
|
2044
|
+
return if ok then GRANTED else NOT_PROCESSED
|
|
2045
|
+
end
|
|
2046
|
+
|
|
2047
|
+
local _, durable = deliverGift(product, recipientId, purchaseId, giftId, userId)
|
|
2048
|
+
if not durable then
|
|
2049
|
+
-- Keep retry activity current without modifying a replacement record.
|
|
2050
|
+
ctx.Persistence.UpdateOffline(userId, function(offlineData)
|
|
2051
|
+
local offlineReserved = reservedRaw(offlineData)
|
|
2052
|
+
local live = offlineReserved[giftRecordKey(fromAim)][productIdStr]
|
|
2053
|
+
if type(live) == "table" and tostring(live.GiftId) == giftId then
|
|
2054
|
+
live.Ts = Clock.Now()
|
|
2055
|
+
end
|
|
2056
|
+
end)
|
|
2057
|
+
return NOT_PROCESSED
|
|
2058
|
+
end
|
|
2059
|
+
local ok = ctx.Persistence.UpdateOffline(userId, function(offlineData)
|
|
2060
|
+
-- The dedupe marker, re-read INSIDE the transaction; see the credit arm above.
|
|
2061
|
+
pruneProcessedRaw(offlineData)
|
|
2062
|
+
if isProcessedRaw(offlineData, purchaseId) then
|
|
2063
|
+
return
|
|
2064
|
+
end
|
|
2065
|
+
local offlineReserved = reservedRaw(offlineData)
|
|
2066
|
+
-- Clear OUR record, and only ours. The decision that this receipt owns one was
|
|
2067
|
+
-- made from a snapshot taken before deliverGift's cross-server round trip, and a
|
|
2068
|
+
-- second gift of the same product can hold the slot by now. Identity is the
|
|
2069
|
+
-- GiftId, never the slot.
|
|
2070
|
+
clearGiftRecordRaw(offlineReserved, productIdStr, giftId)
|
|
2071
|
+
robuxLogRaw(offlineData, {
|
|
2072
|
+
PurchaseId = purchaseId,
|
|
2073
|
+
Product = product.Name,
|
|
2074
|
+
Category = product.Category,
|
|
2075
|
+
PriceInRobux = receiptInfo.CurrencySpent,
|
|
2076
|
+
-- IntendedFor only on an aim-settled line; see the online arm.
|
|
2077
|
+
From = {
|
|
2078
|
+
Type = "GiftSent",
|
|
2079
|
+
ToUserId = recipientId,
|
|
2080
|
+
GiftId = giftId,
|
|
2081
|
+
IntendedFor = if fromAim then recipientId else nil,
|
|
2082
|
+
},
|
|
2083
|
+
Ts = Clock.Now(),
|
|
2084
|
+
})
|
|
2085
|
+
markProcessedRaw(offlineData, purchaseId)
|
|
2086
|
+
end)
|
|
2087
|
+
return if ok then GRANTED else NOT_PROCESSED
|
|
2088
|
+
end
|
|
2089
|
+
|
|
2090
|
+
-- Player left mid-receipt: grant via UpdateOffline where that is safely expressible
|
|
2091
|
+
-- (perk products), else NotProcessedYet.
|
|
2092
|
+
local function handleOfflineReceipt(
|
|
2093
|
+
userId: number,
|
|
2094
|
+
product: Product,
|
|
2095
|
+
receiptInfo: any
|
|
2096
|
+
): Enum.ProductPurchaseDecision
|
|
2097
|
+
local purchaseId = tostring(receiptInfo.PurchaseId)
|
|
2098
|
+
local data = ctx.Persistence.GetOffline(userId)
|
|
2099
|
+
if not data then
|
|
2100
|
+
-- No profile, or the offline read failed (GetOffline logs that separately).
|
|
2101
|
+
-- Either way this receipt is undebuggable without the PurchaseId.
|
|
2102
|
+
Metrics.Add("ReceiptsRetried")
|
|
2103
|
+
Log.Warn("Monetization", "RECEIPT_OFFLINE_RETRY", "offline receipt could not read the buyer's profile", {
|
|
2104
|
+
UserId = userId,
|
|
2105
|
+
ProductId = product.Id,
|
|
2106
|
+
PurchaseId = purchaseId,
|
|
2107
|
+
})
|
|
2108
|
+
return NOT_PROCESSED
|
|
2109
|
+
end
|
|
2110
|
+
if isProcessedRaw(data, purchaseId) then
|
|
2111
|
+
Metrics.Add("ReceiptsDuplicate")
|
|
2112
|
+
return GRANTED
|
|
2113
|
+
end
|
|
2114
|
+
|
|
2115
|
+
local reserved = reservedRaw(data)
|
|
2116
|
+
local route, invalid = readReceiptRoute(reserved, purchaseId, product)
|
|
2117
|
+
if invalid then
|
|
2118
|
+
return retryGiftRoute(userId, product, purchaseId)
|
|
2119
|
+
end
|
|
2120
|
+
if route then
|
|
2121
|
+
return settleOfflineGift(userId, product, receiptInfo, route, route.FromAim)
|
|
2122
|
+
end
|
|
2123
|
+
if
|
|
2124
|
+
(canInferGift(receiptInfo) or reserved.ReceiptReservations[purchaseId] == true)
|
|
2125
|
+
and not checkGiftSlots(reserved, userId, product, purchaseId)
|
|
2126
|
+
then
|
|
2127
|
+
return NOT_PROCESSED
|
|
2128
|
+
end
|
|
2129
|
+
if
|
|
2130
|
+
hasConflictingGiftRecords(reserved, product.Id)
|
|
2131
|
+
and (canInferGift(receiptInfo) or reserved.ReceiptReservations[purchaseId] == true)
|
|
2132
|
+
then
|
|
2133
|
+
return retryGiftRoute(userId, product, purchaseId)
|
|
2134
|
+
end
|
|
2135
|
+
if reserved.ReceiptReservations[purchaseId] == true then
|
|
2136
|
+
local legacyIntent = readGiftRecord(reserved, false, product)
|
|
2137
|
+
local legacyRecord = legacyIntent or readGiftRecord(reserved, true, product)
|
|
2138
|
+
if legacyRecord == nil then
|
|
2139
|
+
return retryGiftRoute(userId, product, purchaseId)
|
|
2140
|
+
end
|
|
2141
|
+
return settleOfflineGift(userId, product, receiptInfo, legacyRecord, legacyIntent == nil)
|
|
2142
|
+
end
|
|
2143
|
+
local inferGift = canInferGift(receiptInfo)
|
|
2144
|
+
local intent = if inferGift then reserved.PendingGifts[tostring(product.Id)] else nil
|
|
2145
|
+
-- Mirror intentFor's reused-Id guard: an intent whose stored Product name differs
|
|
2146
|
+
-- belongs to a retired product that reused this Id. Treat as no-intent.
|
|
2147
|
+
if type(intent) == "table" and intent.Product ~= nil and intent.Product ~= product.Name then
|
|
2148
|
+
Log.Warn(
|
|
2149
|
+
"Gifting",
|
|
2150
|
+
"GIFT_INTENT_EXPIRED",
|
|
2151
|
+
"offline gift intent belonged to a retired product reusing this Id",
|
|
2152
|
+
{
|
|
2153
|
+
UserId = userId,
|
|
2154
|
+
Product = product.Name,
|
|
2155
|
+
}
|
|
2156
|
+
)
|
|
2157
|
+
intent = nil
|
|
2158
|
+
end
|
|
2159
|
+
if type(intent) == "table" then
|
|
2160
|
+
return settleOfflineGift(userId, product, receiptInfo, intent, false)
|
|
2161
|
+
end
|
|
2162
|
+
|
|
2163
|
+
-- NO LIVE INTENT, offline: the same two questions the online arm asks, in the same
|
|
2164
|
+
-- order. Both are here because the arm a receipt takes depends only on whether the
|
|
2165
|
+
-- buyer is still on this server, which is not a fact about the purchase.
|
|
2166
|
+
local record, fromAim = readGiftRecord(reserved, false, product), false
|
|
2167
|
+
if record == nil then
|
|
2168
|
+
record = readGiftRecord(reserved, true, product)
|
|
2169
|
+
fromAim = record ~= nil
|
|
2170
|
+
end
|
|
2171
|
+
if record then
|
|
2172
|
+
local aimedAt = tonumber(record.RecipientId) or 0
|
|
2173
|
+
local presumable = inferGift and fromAim
|
|
2174
|
+
local delivered = if presumable then true else giftAlreadyDelivered(aimedAt, purchaseId)
|
|
2175
|
+
if delivered == nil then
|
|
2176
|
+
return retryGiftRoute(userId, product, purchaseId)
|
|
2177
|
+
end
|
|
2178
|
+
if delivered then
|
|
2179
|
+
if fromAim then
|
|
2180
|
+
Log.Warn(
|
|
2181
|
+
"Gifting",
|
|
2182
|
+
"GIFT_AIM_SETTLED",
|
|
2183
|
+
"a receipt arrived after its gift intent had been swept; settling it from the durable aim "
|
|
2184
|
+
.. "instead of granting it to the buyer",
|
|
2185
|
+
{
|
|
2186
|
+
UserId = userId,
|
|
2187
|
+
Product = product.Name,
|
|
2188
|
+
PurchaseId = purchaseId,
|
|
2189
|
+
RecipientId = aimedAt,
|
|
2190
|
+
}
|
|
2191
|
+
)
|
|
2192
|
+
Metrics.Add("GiftAimsSettled")
|
|
2193
|
+
end
|
|
2194
|
+
return settleOfflineGift(userId, product, receiptInfo, record, fromAim)
|
|
2195
|
+
end
|
|
2196
|
+
end
|
|
2197
|
+
|
|
2198
|
+
if product.Grants and not product.Grant then
|
|
2199
|
+
local perkKey = product.Grants :: string
|
|
2200
|
+
-- Pass-aware ownership, matching the online path, so an offline buyer who owns
|
|
2201
|
+
-- the pass is not re-granted.
|
|
2202
|
+
local ownsPerk = reserved.Perks[perkKey] == true or recipientAlreadyOwns(userId, perkKey)
|
|
2203
|
+
-- Online parity: hold an owned-perk purchase for retry instead of crediting.
|
|
2204
|
+
if ownsPerk and noGiftIntentPolicy == "Hold" then
|
|
2205
|
+
Metrics.Add("ReceiptsRetried")
|
|
2206
|
+
return NOT_PROCESSED
|
|
2207
|
+
end
|
|
2208
|
+
-- Same rule as the online path: owned perk plus an unused credit means this
|
|
2209
|
+
-- purchase could only stack another credit, so decline it.
|
|
2210
|
+
if ownsPerk and (tonumber(reserved.GiftCredits[product.Name]) or 0) > 0 then
|
|
2211
|
+
Log.Warn(
|
|
2212
|
+
"Gifting",
|
|
2213
|
+
"RECEIPT_DECLINED_PENDING_CREDIT",
|
|
2214
|
+
"offline buyer owns the perk and already holds an unused gift credit; declining the purchase",
|
|
2215
|
+
{
|
|
2216
|
+
UserId = userId,
|
|
2217
|
+
Product = product.Name,
|
|
2218
|
+
}
|
|
2219
|
+
)
|
|
2220
|
+
Metrics.Add("ReceiptsDeclined")
|
|
2221
|
+
return NOT_PROCESSED
|
|
2222
|
+
end
|
|
2223
|
+
local ok = ctx.Persistence.UpdateOffline(userId, function(offlineData)
|
|
2224
|
+
-- The dedupe marker, re-read INSIDE the transaction; see settleOfflineGift.
|
|
2225
|
+
pruneProcessedRaw(offlineData)
|
|
2226
|
+
if isProcessedRaw(offlineData, purchaseId) then
|
|
2227
|
+
return
|
|
2228
|
+
end
|
|
2229
|
+
if not canRecordReceipt(offlineData, purchaseId, nil, userId) then
|
|
2230
|
+
error("receipt history full", 0)
|
|
2231
|
+
end
|
|
2232
|
+
local offlineReserved = reservedRaw(offlineData)
|
|
2233
|
+
-- ownsPerk is pass-aware and resolved before the transaction; the in-txn
|
|
2234
|
+
-- flag re-check guards against a concurrent change.
|
|
2235
|
+
if ownsPerk or offlineReserved.Perks[perkKey] == true then
|
|
2236
|
+
offlineReserved.GiftCredits[product.Name] = (
|
|
2237
|
+
tonumber(offlineReserved.GiftCredits[product.Name]) or 0
|
|
2238
|
+
) + 1
|
|
2239
|
+
else
|
|
2240
|
+
offlineReserved.Perks[perkKey] = true
|
|
2241
|
+
end
|
|
2242
|
+
robuxLogRaw(offlineData, {
|
|
2243
|
+
PurchaseId = purchaseId,
|
|
2244
|
+
Product = product.Name,
|
|
2245
|
+
Category = product.Category,
|
|
2246
|
+
PriceInRobux = receiptInfo.CurrencySpent,
|
|
2247
|
+
From = { Type = "Purchase" },
|
|
2248
|
+
Ts = Clock.Now(),
|
|
2249
|
+
})
|
|
2250
|
+
markProcessedRaw(offlineData, purchaseId)
|
|
2251
|
+
end)
|
|
2252
|
+
if ok then
|
|
2253
|
+
Log.Info("Monetization", "RECEIPT_GRANTED", "offline perk grant committed", {
|
|
2254
|
+
UserId = userId,
|
|
2255
|
+
PurchaseId = purchaseId,
|
|
2256
|
+
})
|
|
2257
|
+
Metrics.Add("ReceiptsGranted")
|
|
2258
|
+
return GRANTED
|
|
2259
|
+
end
|
|
2260
|
+
end
|
|
2261
|
+
-- Consumable Grant functions need a live tree; Roblox retries, including on the
|
|
2262
|
+
-- player's next session.
|
|
2263
|
+
Metrics.Add("ReceiptsRetried")
|
|
2264
|
+
return NOT_PROCESSED
|
|
2265
|
+
end
|
|
2266
|
+
|
|
2267
|
+
local function processReceipt(userId: number, product: Product, receiptInfo: any): Enum.ProductPurchaseDecision
|
|
2268
|
+
if promptStopped or ctx.Persistence.Stopped or ctx.Persistence.Closing then
|
|
2269
|
+
Metrics.Add("ReceiptsRetried")
|
|
2270
|
+
return NOT_PROCESSED
|
|
2271
|
+
end
|
|
2272
|
+
local productId = product.Id
|
|
2273
|
+
local entry: { [string]: any }? = ctx.Persistence.EntryForUserId(userId)
|
|
2274
|
+
local player = if entry then entry.Player else Players:GetPlayerByUserId(userId)
|
|
2275
|
+
if player and (not entry or entry.State ~= "Ready") then
|
|
2276
|
+
-- Join receipts can arrive before Scribe starts or finishes loading.
|
|
2277
|
+
local timeout = math.max(60, tonumber(options.LoadTimeout) or 120)
|
|
2278
|
+
local data = ctx.Persistence.WaitForData(player, timeout)
|
|
2279
|
+
entry = ctx.Persistence.EntryForUserId(userId)
|
|
2280
|
+
if
|
|
2281
|
+
promptStopped
|
|
2282
|
+
or ctx.Persistence.Stopped
|
|
2283
|
+
or ctx.Persistence.Closing
|
|
2284
|
+
or not data
|
|
2285
|
+
or not entry
|
|
2286
|
+
or entry.Player ~= player
|
|
2287
|
+
or entry.State ~= "Ready"
|
|
2288
|
+
or entry.TornDown
|
|
2289
|
+
then
|
|
2290
|
+
Metrics.Add("ReceiptsRetried")
|
|
2291
|
+
return NOT_PROCESSED
|
|
2292
|
+
end
|
|
2293
|
+
end
|
|
2294
|
+
if entry and entry.State == "Ready" then
|
|
2295
|
+
pruneProcessed(entry)
|
|
2296
|
+
end
|
|
2297
|
+
if
|
|
2298
|
+
product.PaidRandom
|
|
2299
|
+
and entry
|
|
2300
|
+
and entry.Policy
|
|
2301
|
+
and entry.Policy.Phase == "known"
|
|
2302
|
+
and entry.Policy.Restricted
|
|
2303
|
+
and not isProcessed(entry, tostring(receiptInfo.PurchaseId))
|
|
2304
|
+
then
|
|
2305
|
+
-- External sales bypass prompt checks; the buyer has already paid.
|
|
2306
|
+
Log.Warn(
|
|
2307
|
+
"Monetization",
|
|
2308
|
+
"PAID_RANDOM_RECEIPT",
|
|
2309
|
+
`receipt for paid random product "{product.Name}" from a player whose policy restricts it; granted`,
|
|
2310
|
+
{ Player = entry.Player, ProductId = productId }
|
|
2311
|
+
)
|
|
2312
|
+
end
|
|
2313
|
+
if entry and entry.State == "Ready" and isProcessed(entry, tostring(receiptInfo.PurchaseId)) then
|
|
2314
|
+
Metrics.Add("ReceiptsDuplicate")
|
|
2315
|
+
-- Logged as well as counted: the metric alone leaves an operator with no
|
|
2316
|
+
-- per-receipt record to correlate.
|
|
2317
|
+
Log.Info("Monetization", "RECEIPT_DUPLICATE", "duplicate receipt acknowledged", {
|
|
2318
|
+
Player = entry.Player,
|
|
2319
|
+
PurchaseId = tostring(receiptInfo.PurchaseId),
|
|
2320
|
+
ProductId = productId,
|
|
2321
|
+
})
|
|
2322
|
+
-- Acknowledge a duplicate only when the grant that set this marker is durable.
|
|
2323
|
+
-- Dirty alone is not enough: it resets when a save's payload is serialized, so a
|
|
2324
|
+
-- clean flag with a save still in flight means the covering save may yet fail,
|
|
2325
|
+
-- and a crash after GRANTED would lose both the grant and the marker.
|
|
2326
|
+
if (not entry.SaveInfo.Dirty and entry.SavesInFlight == 0) or ctx.Persistence.AwaitSave(entry, 10) then
|
|
2327
|
+
return GRANTED
|
|
2328
|
+
end
|
|
2329
|
+
Metrics.Add("ReceiptsRetried")
|
|
2330
|
+
return NOT_PROCESSED
|
|
2331
|
+
end
|
|
2332
|
+
|
|
2333
|
+
if Health.GetStatus() == "Outage" then
|
|
2334
|
+
-- Outage policy: never eat Robux.
|
|
2335
|
+
Metrics.Add("ReceiptsRetried")
|
|
2336
|
+
return NOT_PROCESSED
|
|
2337
|
+
end
|
|
2338
|
+
|
|
2339
|
+
if entry and entry.State == "Ready" then
|
|
2340
|
+
local release = reserveReceipt(entry, tostring(receiptInfo.PurchaseId))
|
|
2341
|
+
if not release then
|
|
2342
|
+
Metrics.Add("ReceiptsRetried")
|
|
2343
|
+
return NOT_PROCESSED
|
|
2344
|
+
end
|
|
2345
|
+
local ok, result = pcall(handleOnlineReceipt, entry, product, receiptInfo)
|
|
2346
|
+
release()
|
|
2347
|
+
if not ok then
|
|
2348
|
+
error(result, 0)
|
|
2349
|
+
end
|
|
2350
|
+
return result
|
|
2351
|
+
end
|
|
2352
|
+
return handleOfflineReceipt(userId, product, receiptInfo)
|
|
2353
|
+
end
|
|
2354
|
+
|
|
2355
|
+
-- Unknown products fall through only when an external receipt router owns them.
|
|
2356
|
+
local function handleReceipt(receiptInfo: any, strict: boolean): Enum.ProductPurchaseDecision?
|
|
2357
|
+
local userId = tonumber(receiptInfo.PlayerId) or 0
|
|
2358
|
+
local productId = tonumber(receiptInfo.ProductId) or 0
|
|
2359
|
+
local product = productsById[productId]
|
|
2360
|
+
if not product then
|
|
2361
|
+
if not strict then
|
|
2362
|
+
return nil
|
|
2363
|
+
end
|
|
2364
|
+
Metrics.Add("ReceiptsReceived")
|
|
2365
|
+
Log.Error(
|
|
2366
|
+
"Monetization",
|
|
2367
|
+
"RECEIPT_UNKNOWN_PRODUCT",
|
|
2368
|
+
`receipt for unregistered product {productId}: register it in Products`,
|
|
2369
|
+
{ UserId = userId, ProductId = productId }
|
|
2370
|
+
)
|
|
2371
|
+
return NOT_PROCESSED
|
|
2372
|
+
end
|
|
2373
|
+
Metrics.Add("ReceiptsReceived")
|
|
2374
|
+
|
|
2375
|
+
-- Claim before waiting so duplicate callbacks cannot queue another grant.
|
|
2376
|
+
local flightKey = `{userId}|{tostring(receiptInfo.PurchaseId)}`
|
|
2377
|
+
if receiptsInFlight[flightKey] then
|
|
2378
|
+
Metrics.Add("ReceiptsRetried")
|
|
2379
|
+
Log.Warn(
|
|
2380
|
+
"Monetization",
|
|
2381
|
+
"RECEIPT_IN_FLIGHT",
|
|
2382
|
+
"the same receipt is already being processed on this server; letting Roblox retry",
|
|
2383
|
+
{ UserId = userId, PurchaseId = tostring(receiptInfo.PurchaseId), ProductId = product.Id }
|
|
2384
|
+
)
|
|
2385
|
+
return NOT_PROCESSED
|
|
2386
|
+
end
|
|
2387
|
+
receiptsInFlight[flightKey] = true
|
|
2388
|
+
-- Release the claim even if loading or granting throws.
|
|
2389
|
+
local dispatchOk, decision = pcall(processReceipt, userId, product, receiptInfo)
|
|
2390
|
+
receiptsInFlight[flightKey] = nil
|
|
2391
|
+
if not dispatchOk then
|
|
2392
|
+
error(decision, 0)
|
|
2393
|
+
end
|
|
2394
|
+
return decision
|
|
2395
|
+
end
|
|
2396
|
+
|
|
2397
|
+
function self.HandleReceipt(receiptInfo: any): Enum.ProductPurchaseDecision
|
|
2398
|
+
return handleReceipt(receiptInfo, true) :: Enum.ProductPurchaseDecision
|
|
2399
|
+
end
|
|
2400
|
+
|
|
2401
|
+
function self.TryHandleReceipt(receiptInfo: any): Enum.ProductPurchaseDecision?
|
|
2402
|
+
return handleReceipt(receiptInfo, false)
|
|
2403
|
+
end
|
|
2404
|
+
|
|
2405
|
+
-- Gifting flow --------------------------------------------------------------------
|
|
2406
|
+
|
|
2407
|
+
--- What a finished gamepass purchase does. Named rather than inline in the Connect so a
|
|
2408
|
+
--- spec can drive it: a real RBXScriptSignal has no Fire, so the only other way to
|
|
2409
|
+
--- reach this is a real purchase.
|
|
2410
|
+
function self.OnPassPurchaseFinished(player: Player, passId: number, purchased: boolean)
|
|
2411
|
+
if not purchased then
|
|
2412
|
+
return
|
|
2413
|
+
end
|
|
2414
|
+
local passName = passNamesById[passId]
|
|
2415
|
+
if not passName then
|
|
2416
|
+
return
|
|
2417
|
+
end
|
|
2418
|
+
local entry = ctx.Persistence.EntryFor(player)
|
|
2419
|
+
if not entry or entry.State ~= "Ready" then
|
|
2420
|
+
return
|
|
2421
|
+
end
|
|
2422
|
+
-- CONFIRM BEFORE CREDITING. This reports that the purchase DIALOG closed, not a
|
|
2423
|
+
-- completed transaction: a gamepass has no ProcessReceipt to be authoritative. The
|
|
2424
|
+
-- session cache would heal on the next join, but robuxLog writes the PERSISTED
|
|
2425
|
+
-- purchase history, so an unconfirmed event falsifies it.
|
|
2426
|
+
Sched.Spawn(function()
|
|
2427
|
+
local ok, owned = pcall(function()
|
|
2428
|
+
return userOwnsGamePass(entry.UserId, passId)
|
|
2429
|
+
end)
|
|
2430
|
+
if entry.TornDown then
|
|
2431
|
+
return
|
|
2432
|
+
end
|
|
2433
|
+
if not ok or owned ~= true then
|
|
2434
|
+
-- Self-heals: the join scan re-resolves every declared pass, so a real
|
|
2435
|
+
-- purchase the API had not caught up with is credited on the next load.
|
|
2436
|
+
Metrics.Add("PassPurchasesUnconfirmed")
|
|
2437
|
+
Log.Warn(
|
|
2438
|
+
"Monetization",
|
|
2439
|
+
"PASS_PURCHASE_UNCONFIRMED",
|
|
2440
|
+
if ok then "ownership check says not owned" else tostring(owned),
|
|
2441
|
+
{ Player = player, Pass = passName, PassId = passId, Errored = not ok }
|
|
2442
|
+
)
|
|
2443
|
+
return
|
|
2444
|
+
end
|
|
2445
|
+
setOwnsCache(entry, passName, true)
|
|
2446
|
+
robuxLog(entry, {
|
|
2447
|
+
PurchaseId = `pass:{passId}:{Clock.Now()}`,
|
|
2448
|
+
Product = passName,
|
|
2449
|
+
Category = passesByName[passName].Category or "Gamepass",
|
|
2450
|
+
From = { Type = "GamePass" },
|
|
2451
|
+
Ts = Clock.Now(),
|
|
2452
|
+
})
|
|
2453
|
+
ctx.Persistence.AwaitSave(entry, 15)
|
|
2454
|
+
end)
|
|
2455
|
+
end
|
|
2456
|
+
|
|
2457
|
+
-- Client requests and direct server calls share the same eligibility gate and
|
|
2458
|
+
-- active dialog. A request carries a registry name, never an arbitrary asset ID.
|
|
2459
|
+
function self.PromptPurchase(player: Player, name: string): (boolean, string?)
|
|
2460
|
+
local product = productsByName[name]
|
|
2461
|
+
local pass = passesByName[name]
|
|
2462
|
+
if not product and not pass then
|
|
2463
|
+
return false, `unknown product or pass "{name}"`
|
|
2464
|
+
end
|
|
2465
|
+
local entry = ctx.Persistence.EntryFor(player)
|
|
2466
|
+
if promptStopped or not entry or entry.State ~= "Ready" or entry.TornDown then
|
|
2467
|
+
return false, "not-loaded"
|
|
2468
|
+
end
|
|
2469
|
+
finishCancellation(player)
|
|
2470
|
+
if promptStopped or entry.State ~= "Ready" or entry.TornDown or ctx.Persistence.EntryFor(player) ~= entry then
|
|
2471
|
+
return false, "not-loaded"
|
|
2472
|
+
end
|
|
2473
|
+
local state = productState(entry, name, product, pass)
|
|
2474
|
+
if state ~= "purchasable" then
|
|
2475
|
+
if state == "paid-random-restricted" or state == "policy-pending" then
|
|
2476
|
+
Metrics.Add("PaidRandomRefused")
|
|
2477
|
+
end
|
|
2478
|
+
return false, state
|
|
2479
|
+
end
|
|
2480
|
+
|
|
2481
|
+
if purchasePrompts[player] or (product and hasPendingGift(entry, product.Id)) then
|
|
2482
|
+
return false, "purchase prompt already open"
|
|
2483
|
+
end
|
|
2484
|
+
local promptId = if pass then pass.Id else (product :: Product).Id
|
|
2485
|
+
local prompt = if pass then promptGamePassPurchase else promptProductPurchase
|
|
2486
|
+
local pending: PurchasePrompt = { Entry = entry, Closed = false }
|
|
2487
|
+
purchasePrompts[player] = pending
|
|
2488
|
+
local prompted = false
|
|
2489
|
+
|
|
2490
|
+
-- Subscribe before prompting: even a prompt which closes immediately releases
|
|
2491
|
+
-- its guard. The listener exists only while this player's dialog is active.
|
|
2492
|
+
local ok, err = pcall(function()
|
|
2493
|
+
local finished = if pass
|
|
2494
|
+
then options.PromptGamePassPurchaseFinished or MarketplaceService.PromptGamePassPurchaseFinished
|
|
2495
|
+
else options.PromptProductPurchaseFinished or MarketplaceService.PromptProductPurchaseFinished
|
|
2496
|
+
local connection = finished:Connect(function(target: any, finishedId: number)
|
|
2497
|
+
local matchingPlayer = if pass then target == player else target == entry.UserId
|
|
2498
|
+
if matchingPlayer and finishedId == promptId and ctx.Persistence.EntryFor(player) == entry then
|
|
2499
|
+
clearPurchasePrompt(player, pending)
|
|
2500
|
+
end
|
|
2501
|
+
end)
|
|
2502
|
+
pending.Connection = connection
|
|
2503
|
+
-- A test seam may yield or run teardown from Connect. Never leave its late
|
|
2504
|
+
-- connection attached, nor prompt for a session that ended in that gap.
|
|
2505
|
+
if
|
|
2506
|
+
pending.Closed
|
|
2507
|
+
or promptStopped
|
|
2508
|
+
or entry.State ~= "Ready"
|
|
2509
|
+
or entry.TornDown
|
|
2510
|
+
or ctx.Persistence.EntryFor(player) ~= entry
|
|
2511
|
+
then
|
|
2512
|
+
clearPurchasePrompt(player, pending)
|
|
2513
|
+
return
|
|
2514
|
+
end
|
|
2515
|
+
prompt(player, promptId)
|
|
2516
|
+
prompted = true
|
|
2517
|
+
end)
|
|
2518
|
+
if not ok then
|
|
2519
|
+
clearPurchasePrompt(player, pending)
|
|
2520
|
+
return false, `purchase prompt failed: {err}`
|
|
2521
|
+
end
|
|
2522
|
+
if not prompted then
|
|
2523
|
+
return false, "not-loaded"
|
|
2524
|
+
end
|
|
2525
|
+
Metrics.Add("PurchasePrompts")
|
|
2526
|
+
return true, nil
|
|
2527
|
+
end
|
|
2528
|
+
|
|
2529
|
+
local function promptGift(
|
|
2530
|
+
buyer: Player,
|
|
2531
|
+
productName: string,
|
|
2532
|
+
recipientUserId: number,
|
|
2533
|
+
pending: PurchasePrompt?
|
|
2534
|
+
): (boolean, string?)
|
|
2535
|
+
local product = productsByName[productName] or retiredByName[productName]
|
|
2536
|
+
if not product then
|
|
2537
|
+
return false, `unknown product "{productName}"`
|
|
2538
|
+
end
|
|
2539
|
+
local entry = ctx.Persistence.EntryFor(buyer)
|
|
2540
|
+
if promptStopped or not entry or entry.State ~= "Ready" or entry.TornDown then
|
|
2541
|
+
return false, "buyer data not loaded"
|
|
2542
|
+
end
|
|
2543
|
+
if product.Retired and (tonumber(reservedRaw(entry.LiveData).GiftCredits[productName]) or 0) <= 0 then
|
|
2544
|
+
return false, "product retired"
|
|
2545
|
+
end
|
|
2546
|
+
if type(recipientUserId) ~= "number" or recipientUserId <= 0 or recipientUserId % 1 ~= 0 then
|
|
2547
|
+
return false, "invalid recipient"
|
|
2548
|
+
end
|
|
2549
|
+
if recipientUserId == entry.UserId then
|
|
2550
|
+
return false, "cannot gift yourself"
|
|
2551
|
+
end
|
|
2552
|
+
if product.PaidRandom then
|
|
2553
|
+
local refused = paidRandomState(entry)
|
|
2554
|
+
if refused == nil then
|
|
2555
|
+
-- Readable only for a Player on this server; anyone else stays unknown.
|
|
2556
|
+
local recipientEntry = ctx.Persistence.EntryForUserId(recipientUserId)
|
|
2557
|
+
if recipientEntry and recipientEntry.State == "Ready" then
|
|
2558
|
+
refused = paidRandomState(recipientEntry)
|
|
2559
|
+
else
|
|
2560
|
+
refused = "policy-pending"
|
|
2561
|
+
end
|
|
2562
|
+
end
|
|
2563
|
+
if refused ~= nil then
|
|
2564
|
+
Metrics.Add("PaidRandomRefused")
|
|
2565
|
+
return false, PAID_RANDOM_REASON[refused]
|
|
2566
|
+
end
|
|
2567
|
+
end
|
|
2568
|
+
|
|
2569
|
+
-- Anti-abuse: per-sender cooldown + max pending gifts.
|
|
2570
|
+
local now = Clock.Monotonic()
|
|
2571
|
+
if now - entry.GiftLastAt < giftCooldown then
|
|
2572
|
+
return false, "gift cooldown"
|
|
2573
|
+
end
|
|
2574
|
+
if Util.count(reservedRaw(entry.LiveData).PendingGifts) >= giftMaxPending then
|
|
2575
|
+
return false, "too many pending gifts"
|
|
2576
|
+
end
|
|
2577
|
+
-- Reserve archive capacity before opening a paid prompt.
|
|
2578
|
+
local productIdStr = tostring(product.Id)
|
|
2579
|
+
-- Count each product once across active and archived intents.
|
|
2580
|
+
local function aimStoreIsFull(): boolean
|
|
2581
|
+
local live = reservedRaw(entry.LiveData)
|
|
2582
|
+
local aims, intents = live.GiftAims, live.PendingGifts
|
|
2583
|
+
if aims[productIdStr] ~= nil or intents[productIdStr] ~= nil then
|
|
2584
|
+
return false
|
|
2585
|
+
end
|
|
2586
|
+
local reservedSlots = Util.count(aims)
|
|
2587
|
+
for pendingIdStr in intents do
|
|
2588
|
+
if aims[pendingIdStr] == nil then
|
|
2589
|
+
reservedSlots += 1
|
|
2590
|
+
end
|
|
2591
|
+
end
|
|
2592
|
+
return reservedSlots >= giftAimCap
|
|
2593
|
+
end
|
|
2594
|
+
if aimStoreIsFull() then
|
|
2595
|
+
Log.Warn(
|
|
2596
|
+
"Gifting",
|
|
2597
|
+
"GIFT_AIM_CAP_REACHED",
|
|
2598
|
+
`the gift aim store is at its cap ({giftAimCap}); refusing the prompt rather than taking money for `
|
|
2599
|
+
.. "a gift whose recipient could not be recorded durably",
|
|
2600
|
+
{ Player = buyer, Product = productName }
|
|
2601
|
+
)
|
|
2602
|
+
return false, "too many unsettled gift purchases; try again later"
|
|
2603
|
+
end
|
|
2604
|
+
if Health.GetStatus() == "Outage" then
|
|
2605
|
+
-- Cannot durably record intent, so never take money.
|
|
2606
|
+
return false, "data services are experiencing issues; try again later"
|
|
2607
|
+
end
|
|
2608
|
+
|
|
2609
|
+
-- Charge the sender's cooldown BEFORE the first expensive step: recipientAlreadyOwns
|
|
2610
|
+
-- issues a full-profile GetAsync for an offline recipient, and with the stamp below
|
|
2611
|
+
-- it a refused prompt left the cooldown unspent, letting one sender repeat that work
|
|
2612
|
+
-- without limit. The checks above are local and cheap, so they still cost nothing.
|
|
2613
|
+
entry.GiftLastAt = now
|
|
2614
|
+
|
|
2615
|
+
-- Step 1: duplicate guard.
|
|
2616
|
+
if product.Grants and not allowDuplicateGifts then
|
|
2617
|
+
if recipientAlreadyOwns(recipientUserId, product.Grants) then
|
|
2618
|
+
return false, "recipient already owns this"
|
|
2619
|
+
end
|
|
2620
|
+
end
|
|
2621
|
+
|
|
2622
|
+
-- recipientAlreadyOwns YIELDED, so the buyer has had a round trip in which to leave.
|
|
2623
|
+
-- Every step below writes through the accessor tree and a torn-down tree RAISES,
|
|
2624
|
+
-- which is the one thing PromptGift is documented not to do: its contract is
|
|
2625
|
+
-- (false, reason). It sits here because both the credit path and the intent path
|
|
2626
|
+
-- take their first accessor write after this point.
|
|
2627
|
+
--
|
|
2628
|
+
-- State, not entry.Tree.Dead: teardown sets SessionEnded before it destroys the tree,
|
|
2629
|
+
-- so State is the strictly earlier signal and also covers the window where the
|
|
2630
|
+
-- session is going away but the tree is still alive.
|
|
2631
|
+
if promptStopped or entry.State ~= "Ready" or entry.TornDown or ctx.Persistence.EntryFor(buyer) ~= entry then
|
|
2632
|
+
return false, "buyer data not loaded"
|
|
2633
|
+
end
|
|
2634
|
+
|
|
2635
|
+
-- Step 2: credit consumption. No purchase prompt, no charge.
|
|
2636
|
+
local reserved = reservedRaw(entry.LiveData)
|
|
2637
|
+
local credits = tonumber(reserved.GiftCredits[productName]) or 0
|
|
2638
|
+
if credits > 0 then
|
|
2639
|
+
local giftId = Util.guid()
|
|
2640
|
+
local creditAccessor = reservedAcc(entry).GiftCredits[productName]
|
|
2641
|
+
-- Refunds re-read the live count instead of restoring the stale pre-read value: a
|
|
2642
|
+
-- receipt retry can issue a credit during the yields below, and an absolute
|
|
2643
|
+
-- restore would erase it. Both steps between the spend and this refund yield, so
|
|
2644
|
+
-- the buyer can be gone by the time a delivery failure brings us back here;
|
|
2645
|
+
-- writing through the accessor would raise on the dead tree and skip the refund
|
|
2646
|
+
-- on a credit that is PAID FOR, so a departed buyer goes through UpdateOffline.
|
|
2647
|
+
local function refundCredit()
|
|
2648
|
+
if entry.State == "Ready" and not entry.Tree.Dead then
|
|
2649
|
+
creditAccessor.Set((tonumber(creditAccessor.Get()) or 0) + 1)
|
|
2650
|
+
return
|
|
2651
|
+
end
|
|
2652
|
+
local restored, why = ctx.Persistence.UpdateOffline(entry.UserId, function(offlineData)
|
|
2653
|
+
local offlineReserved = reservedRaw(offlineData)
|
|
2654
|
+
local have = tonumber(offlineReserved.GiftCredits[productName]) or 0
|
|
2655
|
+
offlineReserved.GiftCredits[productName] = have + 1
|
|
2656
|
+
end)
|
|
2657
|
+
if not restored then
|
|
2658
|
+
Failure.Report({
|
|
2659
|
+
Subsystem = "GiftCredit",
|
|
2660
|
+
Key = tostring(entry.UserId),
|
|
2661
|
+
Category = "Gifting",
|
|
2662
|
+
Code = "GIFT_CREDIT_REFUND_FAIL",
|
|
2663
|
+
Message = "the buyer left during a gift delivery that failed, and the paid credit "
|
|
2664
|
+
.. "could not be restored to their stored profile; it is lost",
|
|
2665
|
+
Context = { UserId = entry.UserId, Product = productName, Reason = why },
|
|
2666
|
+
})
|
|
2667
|
+
end
|
|
2668
|
+
end
|
|
2669
|
+
-- Reserve the credit DURABLY before delivering, so a crash can never restore a
|
|
2670
|
+
-- consumed credit after the gift has already gone out.
|
|
2671
|
+
creditAccessor.Set(if credits - 1 > 0 then credits - 1 else nil)
|
|
2672
|
+
if not ctx.Persistence.AwaitSave(entry, 10) then
|
|
2673
|
+
refundCredit()
|
|
2674
|
+
return false, "could not reserve gift credit; try again later"
|
|
2675
|
+
end
|
|
2676
|
+
-- ONE RULE AT TWO GATES: prefer a bounded value loss over a double grant. This
|
|
2677
|
+
-- spend has no id a retry could reuse, so a credit handed back can buy a SECOND
|
|
2678
|
+
-- grant under a purchaseId the recipient's receipt history has never seen.
|
|
2679
|
+
-- First gate, on `applied` not `durable`: a same-server grant is marked processed
|
|
2680
|
+
-- under this giftId and persists on the next save. Second gate, on `refundable`:
|
|
2681
|
+
-- MessageAsync can commit and lose its answer. A raise out of deliverGift would
|
|
2682
|
+
-- unwind past both gates, so it is caught and read as AMBIGUOUS.
|
|
2683
|
+
local deliveryOk, applied, _, refundable =
|
|
2684
|
+
pcall(deliverGift, product, recipientUserId, `credit:{giftId}`, giftId, entry.UserId)
|
|
2685
|
+
local deliveryError = if deliveryOk then nil else tostring(applied)
|
|
2686
|
+
if not deliveryOk then
|
|
2687
|
+
-- `applied` currently holds the error message, which is truthy. Both values are
|
|
2688
|
+
-- forced to the ambiguous reading before either gate reads them, so a raise can
|
|
2689
|
+
-- neither report a delivery nor buy a refund.
|
|
2690
|
+
applied, refundable = false, false
|
|
2691
|
+
end
|
|
2692
|
+
if not applied and refundable then
|
|
2693
|
+
refundCredit()
|
|
2694
|
+
Sched.Spawn(function()
|
|
2695
|
+
ctx.Persistence.AwaitSave(entry, 15)
|
|
2696
|
+
end)
|
|
2697
|
+
return false, "could not deliver gift; try again later"
|
|
2698
|
+
end
|
|
2699
|
+
if not applied then
|
|
2700
|
+
-- Ambiguous. The credit STAYS SPENT and the buyer is told not to send it again,
|
|
2701
|
+
-- because the alternative is the double grant above. No save is spawned as the
|
|
2702
|
+
-- refund arm does one: the spend was already made durable. Loud, because this
|
|
2703
|
+
-- is the one outcome where a player is out paid value with no retry that would
|
|
2704
|
+
-- help. Log.Warn rather than Failure.Report: deliverGift already reported this
|
|
2705
|
+
-- once, and a second report would count one fault twice against the health window.
|
|
2706
|
+
Metrics.Add("GiftCreditsUnconfirmed")
|
|
2707
|
+
Log.Warn(
|
|
2708
|
+
"Gifting",
|
|
2709
|
+
"GIFT_CREDIT_UNCONFIRMED",
|
|
2710
|
+
"the gift delivery neither succeeded nor provably failed, so the paid credit was NOT handed "
|
|
2711
|
+
.. "back: the gift may already be queued, and refunding would let one payment be spent "
|
|
2712
|
+
.. "again under a new id and grant twice",
|
|
2713
|
+
{
|
|
2714
|
+
Player = buyer,
|
|
2715
|
+
Product = productName,
|
|
2716
|
+
RecipientId = recipientUserId,
|
|
2717
|
+
GiftId = giftId,
|
|
2718
|
+
-- Present only when the delivery RAISED, which is a bug in
|
|
2719
|
+
-- this file rather than a DataStore fault.
|
|
2720
|
+
Error = deliveryError,
|
|
2721
|
+
}
|
|
2722
|
+
)
|
|
2723
|
+
return false, "gift delivery could not be confirmed; do not send it again"
|
|
2724
|
+
end
|
|
2725
|
+
Log.Info("Gifting", "GIFT_CREDIT_USED", "gift delivered from an unassigned credit", {
|
|
2726
|
+
Player = buyer,
|
|
2727
|
+
Product = productName,
|
|
2728
|
+
RecipientId = recipientUserId,
|
|
2729
|
+
})
|
|
2730
|
+
return true, nil
|
|
2731
|
+
end
|
|
2732
|
+
|
|
2733
|
+
if product.Retired then
|
|
2734
|
+
return false, "product retired"
|
|
2735
|
+
end
|
|
2736
|
+
|
|
2737
|
+
-- Recheck after recipient lookups: no yield may replace an unresolved destination.
|
|
2738
|
+
if not pending or pending.Closed or purchasePrompts[buyer] ~= pending or hasPendingGift(entry, product.Id) then
|
|
2739
|
+
return false, "a gift of this item is already pending; try again shortly"
|
|
2740
|
+
end
|
|
2741
|
+
local giftId = Util.guid()
|
|
2742
|
+
local intentAccessor = reservedAcc(entry).PendingGifts[productIdStr]
|
|
2743
|
+
intentAccessor.Set({
|
|
2744
|
+
RecipientId = recipientUserId,
|
|
2745
|
+
GiftId = giftId,
|
|
2746
|
+
Ts = Clock.Now(),
|
|
2747
|
+
Product = productName,
|
|
2748
|
+
})
|
|
2749
|
+
-- Roll back only this attempt, never a replacement written during the save.
|
|
2750
|
+
if not ctx.Persistence.AwaitSave(entry, 10) then
|
|
2751
|
+
cancelUnopenedGift(entry, productIdStr, giftId, pending)
|
|
2752
|
+
Log.Error("Gifting", "GIFT_INTENT_WRITE_FAIL", "could not durably record gift intent; refusing prompt", {
|
|
2753
|
+
Player = buyer,
|
|
2754
|
+
Product = productName,
|
|
2755
|
+
})
|
|
2756
|
+
return false, "could not record gift intent; try again later"
|
|
2757
|
+
end
|
|
2758
|
+
|
|
2759
|
+
local function stillCurrent(): boolean
|
|
2760
|
+
local live = reservedRaw(entry.LiveData).PendingGifts[productIdStr]
|
|
2761
|
+
return not promptStopped
|
|
2762
|
+
and not pending.Closed
|
|
2763
|
+
and purchasePrompts[buyer] == pending
|
|
2764
|
+
and entry.State == "Ready"
|
|
2765
|
+
and not entry.TornDown
|
|
2766
|
+
and ctx.Persistence.EntryFor(buyer) == entry
|
|
2767
|
+
and type(live) == "table"
|
|
2768
|
+
and live.GiftId == giftId
|
|
2769
|
+
end
|
|
2770
|
+
if not stillCurrent() then
|
|
2771
|
+
cancelUnopenedGift(entry, productIdStr, giftId, pending)
|
|
2772
|
+
return false, "buyer data not loaded"
|
|
2773
|
+
end
|
|
2774
|
+
|
|
2775
|
+
local opened = false
|
|
2776
|
+
local ok, err = pcall(function()
|
|
2777
|
+
local finished = options.PromptProductPurchaseFinished or MarketplaceService.PromptProductPurchaseFinished
|
|
2778
|
+
local connection = finished:Connect(function(userId: number, finishedId: number, purchased: boolean)
|
|
2779
|
+
if not opened or pending.Closed or pending.Cancelled or purchasePrompts[buyer] ~= pending then
|
|
2780
|
+
return
|
|
2781
|
+
end
|
|
2782
|
+
if userId ~= entry.UserId or finishedId ~= product.Id or ctx.Persistence.EntryFor(buyer) ~= entry then
|
|
2783
|
+
return
|
|
2784
|
+
end
|
|
2785
|
+
if purchased == false and cancelGiftRecord(entry, productIdStr, giftId) then
|
|
2786
|
+
-- Save cancellation before another receipt can be prompted.
|
|
2787
|
+
pending.Cancelled = true
|
|
2788
|
+
finishCancellation(buyer)
|
|
2789
|
+
return
|
|
2790
|
+
end
|
|
2791
|
+
clearPurchasePrompt(buyer, pending)
|
|
2792
|
+
end)
|
|
2793
|
+
pending.Connection = connection
|
|
2794
|
+
if not stillCurrent() then
|
|
2795
|
+
clearPurchasePrompt(buyer, pending)
|
|
2796
|
+
return
|
|
2797
|
+
end
|
|
2798
|
+
opened = true
|
|
2799
|
+
promptProductPurchase(buyer, product.Id)
|
|
2800
|
+
end)
|
|
2801
|
+
if not ok then
|
|
2802
|
+
cancelUnopenedGift(entry, productIdStr, giftId, pending)
|
|
2803
|
+
return false, `purchase prompt failed: {err}`
|
|
2804
|
+
end
|
|
2805
|
+
if not opened then
|
|
2806
|
+
cancelUnopenedGift(entry, productIdStr, giftId, pending)
|
|
2807
|
+
return false, "buyer data not loaded"
|
|
2808
|
+
end
|
|
2809
|
+
Metrics.Add("GiftPrompts")
|
|
2810
|
+
return true, nil
|
|
2811
|
+
end
|
|
2812
|
+
|
|
2813
|
+
function self.PromptGift(buyer: Player, productName: string, recipientUserId: number): (boolean, string?)
|
|
2814
|
+
finishCancellation(buyer)
|
|
2815
|
+
local entry = ctx.Persistence.EntryFor(buyer)
|
|
2816
|
+
local product = productsByName[productName] or retiredByName[productName]
|
|
2817
|
+
if not product or product.Retired or promptStopped or not entry or entry.State ~= "Ready" or entry.TornDown then
|
|
2818
|
+
return promptGift(buyer, productName, recipientUserId, nil)
|
|
2819
|
+
end
|
|
2820
|
+
-- Credits create no purchase dialog or unbound receipt.
|
|
2821
|
+
if (tonumber(reservedRaw(entry.LiveData).GiftCredits[productName]) or 0) > 0 then
|
|
2822
|
+
return promptGift(buyer, productName, recipientUserId, nil)
|
|
2823
|
+
end
|
|
2824
|
+
if purchasePrompts[buyer] or hasPendingGift(entry, product.Id) then
|
|
2825
|
+
return false, "a gift of this item is already pending; try again shortly"
|
|
2826
|
+
end
|
|
2827
|
+
local pending: PurchasePrompt = { Entry = entry, Closed = false }
|
|
2828
|
+
purchasePrompts[buyer] = pending
|
|
2829
|
+
local ok, prompted, reason = pcall(promptGift, buyer, productName, recipientUserId, pending)
|
|
2830
|
+
if (not ok or not prompted) and not pending.Cancelled then
|
|
2831
|
+
clearPurchasePrompt(buyer, pending)
|
|
2832
|
+
end
|
|
2833
|
+
if not ok then
|
|
2834
|
+
error(prompted, 0)
|
|
2835
|
+
end
|
|
2836
|
+
-- A credit could have arrived during the recipient lookup.
|
|
2837
|
+
if pending.Connection == nil and not pending.Cancelled then
|
|
2838
|
+
clearPurchasePrompt(buyer, pending)
|
|
2839
|
+
end
|
|
2840
|
+
return prompted, reason
|
|
2841
|
+
end
|
|
2842
|
+
|
|
2843
|
+
function self.GetGiftCredits(player: Player): { [string]: number }
|
|
2844
|
+
local entry = ctx.Persistence.EntryFor(player)
|
|
2845
|
+
if not entry or entry.State ~= "Ready" then
|
|
2846
|
+
return {}
|
|
2847
|
+
end
|
|
2848
|
+
return Util.deepClone(reservedRaw(entry.LiveData).GiftCredits)
|
|
2849
|
+
end
|
|
2850
|
+
|
|
2851
|
+
-- In-game purchases ------------------------------------------------------
|
|
2852
|
+
|
|
2853
|
+
function self.RecordPurchase(player: Player, logEntry: { [string]: any })
|
|
2854
|
+
local entry = ctx.Persistence.EntryFor(player)
|
|
2855
|
+
if not entry or entry.State ~= "Ready" then
|
|
2856
|
+
error("Scribe: RecordPurchase requires a Ready player", 2)
|
|
2857
|
+
end
|
|
2858
|
+
checkCategory(logEntry.Category)
|
|
2859
|
+
local record = table.clone(logEntry)
|
|
2860
|
+
record.Ts = record.Ts or Clock.Now()
|
|
2861
|
+
appendRing(reservedAcc(entry).PurchaseLogs.InGame, inGameCap, record)
|
|
2862
|
+
end
|
|
2863
|
+
|
|
2864
|
+
function self.GetPurchases(player: Player, filter: { [string]: any }?): { { [string]: any } }
|
|
2865
|
+
local entry = ctx.Persistence.EntryFor(player)
|
|
2866
|
+
if not entry or entry.State ~= "Ready" then
|
|
2867
|
+
return {}
|
|
2868
|
+
end
|
|
2869
|
+
local reserved = reservedRaw(entry.LiveData)
|
|
2870
|
+
local out: { { [string]: any } } = {}
|
|
2871
|
+
local function collect(kind: string, ring: { any })
|
|
2872
|
+
if filter and filter.Kind and filter.Kind ~= kind then
|
|
2873
|
+
return
|
|
2874
|
+
end
|
|
2875
|
+
for _, item in ring do
|
|
2876
|
+
if filter then
|
|
2877
|
+
if filter.Category and item.Category ~= filter.Category then
|
|
2878
|
+
continue
|
|
2879
|
+
end
|
|
2880
|
+
if filter.ItemId and item.ItemId ~= filter.ItemId then
|
|
2881
|
+
continue
|
|
2882
|
+
end
|
|
2883
|
+
if filter.Since and (tonumber(item.Ts) or 0) < filter.Since then
|
|
2884
|
+
continue
|
|
2885
|
+
end
|
|
2886
|
+
end
|
|
2887
|
+
local record = Util.deepClone(item)
|
|
2888
|
+
record.Kind = kind
|
|
2889
|
+
table.insert(out, record)
|
|
2890
|
+
end
|
|
2891
|
+
end
|
|
2892
|
+
collect("Robux", reserved.PurchaseLogs.Robux)
|
|
2893
|
+
collect("InGame", reserved.PurchaseLogs.InGame)
|
|
2894
|
+
table.sort(out, function(a, b)
|
|
2895
|
+
return (tonumber(a.Ts) or 0) > (tonumber(b.Ts) or 0)
|
|
2896
|
+
end)
|
|
2897
|
+
if filter and filter.Limit then
|
|
2898
|
+
for i = #out, (filter.Limit :: number) + 1, -1 do
|
|
2899
|
+
out[i] = nil
|
|
2900
|
+
end
|
|
2901
|
+
end
|
|
2902
|
+
return out
|
|
2903
|
+
end
|
|
2904
|
+
|
|
2905
|
+
-- Atomic soft-currency purchase: check funds, debit, grant, log and emit analytics
|
|
2906
|
+
-- inside a Transaction. A throwing Grant rolls everything back.
|
|
2907
|
+
function self.Purchase(player: Player, spec: { [string]: any }): (boolean, string?)
|
|
2908
|
+
local entry = ctx.Persistence.EntryFor(player)
|
|
2909
|
+
if not entry or entry.State ~= "Ready" then
|
|
2910
|
+
return false, "player data not loaded"
|
|
2911
|
+
end
|
|
2912
|
+
if spec.PaidRandom == true then
|
|
2913
|
+
local refused = paidRandomState(entry)
|
|
2914
|
+
if refused ~= nil then
|
|
2915
|
+
Metrics.Add("PaidRandomRefused")
|
|
2916
|
+
return false, PAID_RANDOM_REASON[refused]
|
|
2917
|
+
end
|
|
2918
|
+
end
|
|
2919
|
+
-- Optional caller-supplied idempotency key. Deliberately NOT stored in
|
|
2920
|
+
-- _Scribe.ProcessedPurchaseIds: ordinary shop claims should expire independently.
|
|
2921
|
+
local idemKey = spec.IdempotencyKey
|
|
2922
|
+
if idemKey ~= nil then
|
|
2923
|
+
-- Wire's cap, read at the use site rather than aliased: a local literal is how
|
|
2924
|
+
-- this path came to enforce its own 64 while Wire's comment claimed it was shared.
|
|
2925
|
+
if type(idemKey) ~= "string" or idemKey == "" or #idemKey > Wire.MAX_IDEMPOTENCY_KEY_BYTES then
|
|
2926
|
+
return false, "invalid IdempotencyKey"
|
|
2927
|
+
end
|
|
2928
|
+
-- The key becomes a raw persisted table key, bypassing the accessor write
|
|
2929
|
+
-- guard, so invalid UTF-8 would fail the whole profile save.
|
|
2930
|
+
if not Util.isUtf8(idemKey) then
|
|
2931
|
+
return false, "invalid IdempotencyKey"
|
|
2932
|
+
end
|
|
2933
|
+
end
|
|
2934
|
+
|
|
2935
|
+
local cost = spec.Cost
|
|
2936
|
+
if type(cost) ~= "table" or type(cost.Path) ~= "string" or type(cost.Amount) ~= "number" then
|
|
2937
|
+
return false, "invalid Cost spec"
|
|
2938
|
+
end
|
|
2939
|
+
local amount: number = cost.Amount
|
|
2940
|
+
-- A non-positive amount would pass the funds check and CREDIT currency while
|
|
2941
|
+
-- still granting the item.
|
|
2942
|
+
if amount <= 0 or amount ~= amount then
|
|
2943
|
+
return false, "invalid Cost amount"
|
|
2944
|
+
end
|
|
2945
|
+
local costPath = Util.parsePath(cost.Path)
|
|
2946
|
+
-- The index walk can THROW for a path that typos a closed element field, and a
|
|
2947
|
+
-- bad cost path must come back as (false, err) like every other Purchase refusal.
|
|
2948
|
+
local walked, costAccessor = pcall(function()
|
|
2949
|
+
local acc = entry.Tree.Accessor
|
|
2950
|
+
for _, segment in costPath do
|
|
2951
|
+
acc = acc[segment]
|
|
2952
|
+
end
|
|
2953
|
+
return acc
|
|
2954
|
+
end)
|
|
2955
|
+
if not walked then
|
|
2956
|
+
return false, "invalid cost path"
|
|
2957
|
+
end
|
|
2958
|
+
-- Follow the schema the way the accessor above does. Template.Resolve descends
|
|
2959
|
+
-- node.Children only, so a DictOf/ArrayOf element would stop the walk at the
|
|
2960
|
+
-- container, silently disabling the fractional-amount guard and flooring Min at 0.
|
|
2961
|
+
local costSchema, dynStart = Template.Resolve(compiled, costPath :: { string | number })
|
|
2962
|
+
for i = dynStart, #costPath do
|
|
2963
|
+
local next_ = Template.ChildSchema(costSchema, costPath[i])
|
|
2964
|
+
if next_ == nil then
|
|
2965
|
+
break
|
|
2966
|
+
end
|
|
2967
|
+
costSchema = next_
|
|
2968
|
+
end
|
|
2969
|
+
-- A fractional amount on an int currency rounds the debit toward zero, or to no
|
|
2970
|
+
-- debit at all, while the grant still runs.
|
|
2971
|
+
if costSchema.ValueType == "int" and amount % 1 ~= 0 then
|
|
2972
|
+
return false, "invalid Cost amount"
|
|
2973
|
+
end
|
|
2974
|
+
local floor: number = costSchema.Min or 0
|
|
2975
|
+
|
|
2976
|
+
-- A DictOf currency key the player never touched reads nil, but the declared element
|
|
2977
|
+
-- default is its true balance, so without this a starting balance is unspendable.
|
|
2978
|
+
local isElementLeaf = false
|
|
2979
|
+
do
|
|
2980
|
+
local cursor: any = costSchema
|
|
2981
|
+
while cursor do
|
|
2982
|
+
if cursor.IsElement then
|
|
2983
|
+
isElementLeaf = true
|
|
2984
|
+
break
|
|
2985
|
+
end
|
|
2986
|
+
cursor = cursor.Parent
|
|
2987
|
+
end
|
|
2988
|
+
end
|
|
2989
|
+
local function readBalance(): any
|
|
2990
|
+
local value = costAccessor.Get()
|
|
2991
|
+
if value == nil and isElementLeaf and type(costSchema.Default) == "number" then
|
|
2992
|
+
return costSchema.Default
|
|
2993
|
+
end
|
|
2994
|
+
return value
|
|
2995
|
+
end
|
|
2996
|
+
|
|
2997
|
+
-- Already granted under this key? Return the ORIGINAL outcome, matching the receipt
|
|
2998
|
+
-- path; the "this was a duplicate" signal goes to logs and metrics rather than into
|
|
2999
|
+
-- the return value, where a caller would have to special-case it.
|
|
3000
|
+
if idemKey ~= nil and ctx.Timed.IsClaimed(entry, PURCHASE_IDEM_PREFIX .. idemKey) then
|
|
3001
|
+
Metrics.Add("PurchasesDuplicate")
|
|
3002
|
+
Log.Info("Monetization", "PURCHASE_DUPLICATE", "purchase skipped: idempotency key already applied", {
|
|
3003
|
+
Player = player,
|
|
3004
|
+
Key = idemKey,
|
|
3005
|
+
})
|
|
3006
|
+
return true, nil
|
|
3007
|
+
end
|
|
3008
|
+
|
|
3009
|
+
local current = readBalance()
|
|
3010
|
+
if type(current) ~= "number" then
|
|
3011
|
+
-- Two different refusals wearing one string. The accessor walk above already
|
|
3012
|
+
-- SUCCEEDED, so the path is not a typo: it resolved to something real that cannot
|
|
3013
|
+
-- be spent, Scribe.Big being the case that bites (stored as a table, while
|
|
3014
|
+
-- Purchase does plain arithmetic). Only for a DECLARED non-numeric type: an
|
|
3015
|
+
-- element of a dynamic container has no ValueType, and there the old string is
|
|
3016
|
+
-- still the honest answer.
|
|
3017
|
+
local valueType = costSchema.ValueType
|
|
3018
|
+
if valueType ~= nil and valueType ~= "any" and valueType ~= "int" and valueType ~= "number" then
|
|
3019
|
+
return false, "cost path is not a spendable number"
|
|
3020
|
+
end
|
|
3021
|
+
return false, "invalid cost path"
|
|
3022
|
+
end
|
|
3023
|
+
if current - amount < floor then
|
|
3024
|
+
return false, "insufficient funds"
|
|
3025
|
+
end
|
|
3026
|
+
|
|
3027
|
+
local ok, err = entry.Tree:RunTransaction(function()
|
|
3028
|
+
local balance = readBalance()
|
|
3029
|
+
if balance - amount < floor then
|
|
3030
|
+
error("insufficient funds")
|
|
3031
|
+
end
|
|
3032
|
+
costAccessor.Set(balance - amount)
|
|
3033
|
+
if spec.Grant then
|
|
3034
|
+
(spec.Grant :: (any) -> ())(entry.Tree.Accessor)
|
|
3035
|
+
end
|
|
3036
|
+
checkCategory(spec.Category)
|
|
3037
|
+
-- Claimed INSIDE the transaction, so a Grant that throws rolls the claim back with
|
|
3038
|
+
-- the debit. A claim taken outside would survive the rollback and permanently
|
|
3039
|
+
-- block a retry of a purchase that never happened.
|
|
3040
|
+
if idemKey ~= nil then
|
|
3041
|
+
-- Make room INSIDE the transaction, so an eviction rolls back with its purchase.
|
|
3042
|
+
local dropped = ctx.Timed.PruneClaims(entry, PURCHASE_IDEM_PREFIX, purchaseClaimCap)
|
|
3043
|
+
if dropped > 0 then
|
|
3044
|
+
Log.Warn(
|
|
3045
|
+
"Monetization",
|
|
3046
|
+
"PURCHASE_CLAIM_EVICTED",
|
|
3047
|
+
`dropped {dropped} un-expired purchase idempotency claim(s) to stay under MaxPurchaseClaims `
|
|
3048
|
+
.. `({purchaseClaimCap}); a retry of one of them would apply the purchase again; `
|
|
3049
|
+
.. "raise the cap or shorten PurchaseClaimTTL",
|
|
3050
|
+
{ Player = player, Dropped = dropped, Cap = purchaseClaimCap }
|
|
3051
|
+
)
|
|
3052
|
+
Metrics.Add("PurchaseClaimsEvicted", dropped)
|
|
3053
|
+
end
|
|
3054
|
+
ctx.Timed.Claim(entry, PURCHASE_IDEM_PREFIX .. idemKey, purchaseClaimTTL)
|
|
3055
|
+
end
|
|
3056
|
+
appendRing(reservedAcc(entry).PurchaseLogs.InGame, inGameCap, {
|
|
3057
|
+
Category = spec.Category,
|
|
3058
|
+
ItemId = spec.ItemId,
|
|
3059
|
+
Currency = tostring(costPath[#costPath]),
|
|
3060
|
+
Amount = amount,
|
|
3061
|
+
Ts = Clock.Now(),
|
|
3062
|
+
Meta = spec.Meta,
|
|
3063
|
+
})
|
|
3064
|
+
end, seedWatcher(entry, `Data.Purchase "{tostring(spec.ItemId or spec.Category or "?")}"`))
|
|
3065
|
+
if not ok then
|
|
3066
|
+
if err and string.find(err, "insufficient funds", 1, true) then
|
|
3067
|
+
return false, "insufficient funds"
|
|
3068
|
+
end
|
|
3069
|
+
return false, err
|
|
3070
|
+
end
|
|
3071
|
+
|
|
3072
|
+
-- Analytics only after commit so a rollback emits no event.
|
|
3073
|
+
ctx.Analytics.Economy(player, costPath, -amount, costAccessor.Get(), {
|
|
3074
|
+
Source = spec.ItemId or spec.Category or "Purchase",
|
|
3075
|
+
Flow = "Sink",
|
|
3076
|
+
Item = spec.ItemId,
|
|
3077
|
+
})
|
|
3078
|
+
return true, nil
|
|
3079
|
+
end
|
|
3080
|
+
|
|
3081
|
+
-- Lifecycle -----------------------------------------------------------------------------
|
|
3082
|
+
|
|
3083
|
+
function self.OnLoad(entry: any)
|
|
3084
|
+
pruneProcessed(entry)
|
|
3085
|
+
-- Archive stale intents without discarding unresolved destinations.
|
|
3086
|
+
local reserved = reservedRaw(entry.LiveData)
|
|
3087
|
+
local now = Clock.Now()
|
|
3088
|
+
for productIdStr, intent in reserved.PendingGifts do
|
|
3089
|
+
if type(intent) ~= "table" or now - (tonumber(intent.Ts) or 0) > giftIntentTTL then
|
|
3090
|
+
if archiveGiftAim(entry, productIdStr, intent) then
|
|
3091
|
+
reservedAcc(entry).PendingGifts[productIdStr].Set(nil)
|
|
3092
|
+
end
|
|
3093
|
+
end
|
|
3094
|
+
end
|
|
3095
|
+
-- Time alone cannot prove an unresolved gift was cancelled.
|
|
3096
|
+
-- Gift credits are durable paid value keyed by product NAME, so a renamed or removed
|
|
3097
|
+
-- product silently strands them. Surface it, never delete: the credit is player money.
|
|
3098
|
+
for creditName, count in reserved.GiftCredits do
|
|
3099
|
+
if
|
|
3100
|
+
productsByName[creditName] == nil
|
|
3101
|
+
and retiredByName[creditName] == nil
|
|
3102
|
+
and (tonumber(count) or 0) > 0
|
|
3103
|
+
then
|
|
3104
|
+
Log.Warn(
|
|
3105
|
+
"Gifting",
|
|
3106
|
+
"GIFT_CREDIT_UNKNOWN_PRODUCT",
|
|
3107
|
+
`player holds {tostring(count)} gift credit(s) for "{tostring(creditName)}", which is not in Products; `
|
|
3108
|
+
.. "they are unspendable until the product returns or a migration renames the credit key",
|
|
3109
|
+
{ Player = entry.Player, Product = tostring(creditName) }
|
|
3110
|
+
)
|
|
3111
|
+
end
|
|
3112
|
+
end
|
|
3113
|
+
if next(passesByName) == nil then
|
|
3114
|
+
refreshOwnership(entry)
|
|
3115
|
+
else
|
|
3116
|
+
Sched.Spawn(refreshOwnership, entry)
|
|
3117
|
+
end
|
|
3118
|
+
watchOwnership(entry)
|
|
3119
|
+
-- Last and spawned: the hooks after this one end with the first snapshot.
|
|
3120
|
+
if anyPaidRandom then
|
|
3121
|
+
ensurePolicy(entry)
|
|
3122
|
+
end
|
|
3123
|
+
end
|
|
3124
|
+
|
|
3125
|
+
function self.OnUnload(entry: any)
|
|
3126
|
+
local pending = purchasePrompts[entry.Player]
|
|
3127
|
+
if pending and pending.Entry == entry then
|
|
3128
|
+
clearPurchasePrompt(entry.Player, pending)
|
|
3129
|
+
end
|
|
3130
|
+
local watchers = entry.OwnsWatchers
|
|
3131
|
+
if watchers then
|
|
3132
|
+
entry.OwnsWatchers = nil
|
|
3133
|
+
for _, disconnect in watchers do
|
|
3134
|
+
disconnect()
|
|
3135
|
+
end
|
|
3136
|
+
end
|
|
3137
|
+
end
|
|
3138
|
+
|
|
3139
|
+
local connections: { any } = {}
|
|
3140
|
+
function self.ListenerCount(): number
|
|
3141
|
+
return #connections
|
|
3142
|
+
end
|
|
3143
|
+
local boundReceipts = false
|
|
3144
|
+
|
|
3145
|
+
function self.Start()
|
|
3146
|
+
-- Only take over ProcessReceipt when there are developer products to grant, so a
|
|
3147
|
+
-- data-only or pass-only game keeps its own receipt handler.
|
|
3148
|
+
if options.OwnReceipts ~= false and next(productsById) ~= nil then
|
|
3149
|
+
if receiptsBound then
|
|
3150
|
+
error(
|
|
3151
|
+
"Scribe: a Scribe bundle already owns MarketplaceService.ProcessReceipt. "
|
|
3152
|
+
.. "Set OwnReceipts = false on the secondary bundle and route its receipts "
|
|
3153
|
+
.. "manually via Data.HandleReceipt.",
|
|
3154
|
+
0
|
|
3155
|
+
)
|
|
3156
|
+
end
|
|
3157
|
+
receiptsBound = true
|
|
3158
|
+
boundReceipts = true
|
|
3159
|
+
MarketplaceService.ProcessReceipt = function(receiptInfo)
|
|
3160
|
+
return self.HandleReceipt(receiptInfo)
|
|
3161
|
+
end
|
|
3162
|
+
Log.Info(
|
|
3163
|
+
"Monetization",
|
|
3164
|
+
"RECEIPT_HANDLER_BOUND",
|
|
3165
|
+
"Scribe is now handling MarketplaceService.ProcessReceipt; set OwnReceipts = false to keep your own",
|
|
3166
|
+
{}
|
|
3167
|
+
)
|
|
3168
|
+
end
|
|
3169
|
+
|
|
3170
|
+
if next(passesByName) ~= nil then
|
|
3171
|
+
connections[#connections + 1] = MarketplaceService.PromptGamePassPurchaseFinished:Connect(
|
|
3172
|
+
function(player: Player, passId: number, purchased: boolean)
|
|
3173
|
+
self.OnPassPurchaseFinished(player, passId, purchased)
|
|
3174
|
+
end
|
|
3175
|
+
)
|
|
3176
|
+
end
|
|
3177
|
+
|
|
3178
|
+
connections[#connections + 1] = Players.PlayerMembershipChanged:Connect(function(player: Player)
|
|
3179
|
+
local entry = ctx.Persistence.EntryFor(player)
|
|
3180
|
+
if entry and entry.State == "Ready" then
|
|
3181
|
+
setOwnsCache(entry, "RobloxPlus", player.HasRobloxSubscription)
|
|
3182
|
+
end
|
|
3183
|
+
end)
|
|
3184
|
+
end
|
|
3185
|
+
|
|
3186
|
+
-- Release the marketplace listeners and hand ProcessReceipt back. The receiptsBound
|
|
3187
|
+
-- guard is module-global, so leaving it set would make a later bundle in the same
|
|
3188
|
+
-- process throw even though nothing owns the handler.
|
|
3189
|
+
function self.Stop()
|
|
3190
|
+
promptStopped = true
|
|
3191
|
+
for player, pending in purchasePrompts do
|
|
3192
|
+
clearPurchasePrompt(player, pending)
|
|
3193
|
+
end
|
|
3194
|
+
for _, connection in connections do
|
|
3195
|
+
pcall(function()
|
|
3196
|
+
connection:Disconnect()
|
|
3197
|
+
end)
|
|
3198
|
+
end
|
|
3199
|
+
table.clear(connections)
|
|
3200
|
+
if boundReceipts then
|
|
3201
|
+
boundReceipts = false
|
|
3202
|
+
receiptsBound = false
|
|
3203
|
+
pcall(function()
|
|
3204
|
+
MarketplaceService.ProcessReceipt = nil
|
|
3205
|
+
end)
|
|
3206
|
+
end
|
|
3207
|
+
end
|
|
3208
|
+
|
|
3209
|
+
return self
|
|
3210
|
+
end
|
|
3211
|
+
|
|
3212
|
+
return Monetization
|