Simple Daily reward system. (Not much code)

Just added the basic logic, I shouldn’t have any issues. If you spot something please let me know.

ClaimEvent.OnServerEvent:Connect(function(player)
	local userId = player.UserId
	local data = RewardStore:GetAsync(tostring(userId)) or {currentDay = 1, lastClaimTime = 0}
	local now = os.time()

	if now - data.lastClaimTime < 24 * 60 * 60 then
		-- Too soon
		print("Player tried to claim too early.")
		return
	end

	local day = data.currentDay

	-- Give the reward
	if rewards[day] then
		rewards[day](player)
	else
		warn("Invalid reward day: " .. tostring(day))
		return
	end

	-- Prepare next day or reset
	day += 1
	if day > 7 then
		day = 1
	end

	-- Save new data
	RewardStore:SetAsync(tostring(userId), {
		currentDay = day,
		lastClaimTime = now
	})
end)
ClaimEvent.OnServerEvent:Connect(function(player)
	local userId = tostring(player.UserId)
	local now = os.time()

	-- Fetch existing data or use default values
	local success, data = pcall(function()
		return RewardStore:GetAsync(userId)
	end)

	if not success then
		warn("Failed to load reward data for userId:", userId)
		return
	end

	data = data or { currentDay = 1, lastClaimTime = 0 }

	-- Check if 24 hours have passed since last claim
	local timeSinceLastClaim = now - data.lastClaimTime
	if timeSinceLastClaim < 24 * 60 * 60 then
		print(("Player %s tried to claim too early. %d seconds remaining."):format(userId, 24 * 60 * 60 - timeSinceLastClaim))
		return
	end

	local day = data.currentDay

	-- Grant the reward if valid
	local rewardFunc = rewards[day]
	if typeof(rewardFunc) == "function" then
		rewardFunc(player)
	else
		warn("Invalid reward function for day:", day)
		return
	end

	-- Advance to next day or reset to day 1
	local nextDay = (day % 7) + 1

	-- Save updated progress
	local successSave, err = pcall(function()
		RewardStore:SetAsync(userId, {
			currentDay = nextDay,
			lastClaimTime = now,
		})
	end)

	if not successSave then
		warn("Failed to save reward data for userId:", userId, err)
	end
end)

You had a solid start! I cleaned up the code to make it safer, more readable, and more resilient. The biggest win was adding error handling, which means your game won’t break if Roblox’s DataStore decides to take a nap. I also cleaned up the math and added better warnings/logs so you know what’s happening when things go wrong.

1 Like

Awesome, thanks! Something I also added was a player specific denounce too, totally forgot. Just so the player doesn’t spam the event and add a Data Queue

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.