Profile service not working (Economy system) - Error: Token Duplicate

Hi guys, I’m trying to make an econony system for a game I’m working on. We’re using the profile service thing to do all that… it’s working really well.

The problem we have is when a player rejoins the same server/game, whereby he is met with nil money - this is an obvious sign that the profile isn’t being fetched or whatever, I’ve got error logs to back it up.

It works perfectly the first time the player joins, but then for some reason is stuck with some duplciate token error or something?

Here’s the code, check out the error below:

--!strict

local service = {}

local players = game:GetService("Players")
local repStorage = game:GetService("ReplicatedStorage")
local runService = game:GetService("RunService")

-->> folders <<--

local shared = repStorage.Economy_Shared
local packages = shared.Packages

-->> packages <<--

local profileStore_lib = require(packages.ProfileStore)
local replica_lib = require(packages.Replica.ReplicaServer)
local table_util = require(packages.TableUtil) 

-->> variables <<--

local profiles = {}

-->> dependencies <<--

local template, dataStore

do
	-->> initialization <<--

	function start()
		initDependencies()
	end

	function initDependencies()
		template = require(script:WaitForChild("Template"))
		dataStore = profileStore_lib.New("PlayerEconomyData", template)
	end

	-->> events <<--

	function onPlayerAdded(player: Player)
		startProfile(player)
	end

	function onPlayerRemoving(player: Player)
		endProfile(player)
	end

	-->> functions <<--

	function startProfile(player: Player)
		local profile = startProfileSession(player)

		if profile then
			profile:AddUserId(player.UserId) 	-->> GDPR compliance 
			profile:Reconcile() 				-->> fill in missing variables from PROFILE_TEMPLATE (optional) 

			profile.OnSessionEnd:Connect(function()
				profiles[player] = nil
				player:Kick(`Economy profile session end - Please rejoin`)
			end)

			if player.Parent == players then
				profiles[player] = profile
				profile.Data = table_util.Sync(profile.Data, template)
			else
				profile:EndSession() 			-->> player has left before the profile session started
			end
		end

		if not profile then
			player:Kick(`Economy profile load fail - Please rejoin`) -->> happens only when the Roblox server is shutting down
		end
	end

	function endProfile(player: Player)
		local profile = profiles[player]

		assert(profile, "Profiles endProfile -> nil profile for leaving player "..player.Name)

		profile:EndSession()		
		profiles[player] = nil
	end

	-->> utility <<--

	function startProfileSession(player: Player)
		return dataStore:StartSessionAsync(tostring(player.UserId), {
			Cancel = function()
				return player.Parent ~= players
			end,
		})
	end

	function add(player: Player, dataPath: {string}, amount: number)
		local data = getProfileData(player)
		assert(data, "Profiles add -> adding for nil player")

		local dict = getProfileDataDict(data, dataPath)
		local toAddData = dict[dataPath[#dataPath]]
		assert(toAddData and type(toAddData) == "number", "Profiles add -> data not a number for path "..table.concat(dataPath, "."))

		dict[dataPath[#dataPath]] += amount
		return dict[dataPath[#dataPath]]
	end

	function set(player: Player, dataPath: {string}, value: any)
		local data = getProfileData(player)
		assert(data, "Profiles set -> setting for nil player")

		local dict = getProfileDataDict(data, dataPath)
		local toSetData = dict[dataPath[#dataPath]]
		assert(toSetData and type(toSetData) == type(value), "Profiles set -> data not same type as value for path "..table.concat(dataPath, "."))

		dict[dataPath[#dataPath]] = value
		return value
	end

	-->> getters <<--

	function getProfile(player: Player)
		return profiles[player]
	end

	function getProfileData(player: Player, force: boolean?): typeof(template)?
		local profile = getProfile(player)

		if not profile then
			if force then
				runService.Heartbeat:Wait()
				return getProfileData(player, true)
			end

			return nil
		end

		return profile.Data
	end

	function getProfileDataDict(profileData: typeof(template), dataPath: {string})
		local dict = profileData

		for i=1, #dataPath-1 do
			dict = dict[dataPath[i]]
		end

		return dict
	end

end

service.set = set
service.add = add
service.getProfileData = getProfileData
service.playerRemoving = onPlayerRemoving
service.playerAdded = onPlayerAdded
service.start = start
return service


The above image contains the error text saying “Token [my user id] duplicate”

Any ideas on how to fix it? what to do?

If the server closes or I join a new one, it works all fine, the error is only faced when a player first leaves the server and rejoins the same one.

1 Like

The code you provided doesn’t actually use ReplicaServer anywhere. Do you have any other pieces of code that uses it, more specifically one that makes the token?

Just for the record, you aren’t supposed to create a new token for every new player, you’re supposed to make a token once and then use it to create the replica.

1 Like

This is what I’ve got

function startReplica(player: Player)
		local profile_data = profile_service.getProfileData(player, true)

		assert(profile_data, "Economy startReplica -> starting replica for nil profile "..player.Name)

		local economy_Data = {
			cash = profile_data.cash,
			job = "",
		}

		local replica = replica_lib.New({
			Token = replica_lib.Token("Economy"..player.UserId),
			Tags = {player.UserId},
			Data = economy_Data,
		})

		replica:Subscribe(player)
		replicas[player] = replica 
	end

	function endReplica(player: Player)
		local replica = replicas[player]

		assert(replica, "Profiles endProfileReplica -> nil replica for leaving player "..player.Name)

		replica:Unsubscribe(player)
		replica:Destroy()
		replicas[player] = nil
	end

Like I said in my post, you should only make one token and keep re-using that one. Update your client scripts accordingly to receive the replica.

local token = replica_lib.Token("Economy")

function startReplica(player: Player)
	local profile_data = profile_service.getProfileData(player, true)

	assert(profile_data, "Economy startReplica -> starting replica for nil profile "..player.Name)

	local economy_Data = {
		cash = profile_data.cash,
		job = "",
	}

	local replica = replica_lib.New({
		Token = token,
		Tags = {player.UserId},
		Data = economy_Data,
	})

	replica:Subscribe(player)
	replicas[player] = replica 
end

function endReplica(player: Player)
	local replica = replicas[player]

	assert(replica, "Profiles endProfileReplica -> nil replica for leaving player "..player.Name)

	replica:Unsubscribe(player)
	replica:Destroy()
	replicas[player] = nil
end
1 Like

It appears that Replica don’t delete the token once you destroy it, you gotta add deletion of token yourself (its easy)

1 Like

Ok, so I tried this but it still doesn’t seem to work? I mean this time the money comes up as nil. I think it needs the extra identifier part to work? i.e. it needs not only just Economy but also EconomyUserID…?

1 Like

What do you mean?

function endReplica(player: Player)
		local replica = replicas[player]

		assert(replica, "Profiles endProfileReplica -> nil replica for leaving player "..player.Name)

		replica:Unsubscribe(player)
		replica:Destroy()
		replicas[player] = nil
	end

clearly says

replica:Unsubscribe(player)
replica:Destroy()
1 Like

I clearly said it doesnt removes tag from collection, this causes the error
Its not your script, its problem of replica itself

1 Like

Oh right, is there an update I’ve missed out on or something similar? I saw you said it’s an easy fix or something, but how would I go about specifically destroying the token in that case, or specifically the tag associated?

I don’t think it deletes it in the new version
Just go to ReplicaServer and find a destroy function there, and simply remove the tag from the tags collection table

Here’s what I’ve got so far, but it still doesn’t seem to be able to specifically target the token?

This is my edited version btw

function Replica:Destroy()
	local self_id = self.Id

	if Replicas[self_id] == nil then
		return
	end

	local is_top = TopReplicas[self] == true

	if self.replication ~= nil then
		if self.replication[REPLICATION_ALL] == true then
			for player in pairs(ReadyPlayers) do
				RemoteDestroy:FireClient(player, self_id)
			end
		else
			for player in pairs(self.replication) do
				RemoteDestroy:FireClient(player, self_id)
				if is_top == true then
					SelectiveSubscriptions[player][self] = nil
				end
			end
		end
	end

	TopReplicas[self] = nil
	ReplicationAllReplicas[self] = nil

	if self.Parent ~= nil then
		self.Parent.Children[self] = nil
	end

	-- the player bound replicas!!!
	if self.BoundInstance then
		local player = Players:GetPlayerFromCharacter(self.BoundInstance)
		if player then
			-- remove the tags
			CollectionService:RemoveTag(self.BoundInstance, tostring(player.UserId))
			CollectionService:RemoveTag(self.BoundInstance, "Economy"..player.UserId)
		end

		if self.Tags then
			for _, tag in pairs(self.Tags) do
				CollectionService:RemoveTag(self.BoundInstance, tostring(tag))
			end
		end
	end

	if self.bind_value then
		self.bind_value:Destroy()
		self.bind_value = nil
	end

	DestroyReplica(self)
end
if Tokens[self.Token] then
	Tokens[self.Token] = nil
end

Put that after

if Replicas[self_id] == nil then
	return
end

Better use default destroy function since you said you edited it, it might break something, don’t know

1 Like

yeah but I only edited it since you told me there’s something wrong going on with it. the default one is the one that didn’t work…

Edit: all good, thank you very much. it all works. i’m pretty new to scripting, but this is literally such an oversight on my part. it was literally: if there are any, just make it nil.

thank you again

1 Like

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