-- Server Script (Placed in ServerScriptService)
local ReplicatedStorage = game:GetService("ReplicatedStorage")
-- RemoteEvents for handling communication securely
local LoanRequestEvent = Instance.new("RemoteEvent")
LoanRequestEvent.Name = "LoanRequestEvent"
LoanRequestEvent.Parent = ReplicatedStorage
-- Simulated Database / Inventory Tracking
local ActiveLoans = {}
-- Function to handle loaning an item
local function loanItem(lender, borrower, itemName, duration)
-- 1. Security Check: Verify both players exist
if not lender or not borrower then return end
-- 2. Verify Ownership: Check if the lender actually owns the item
local lenderInventory = lender:FindFirstChild("Inventory")
local item = lenderInventory and lenderInventory:FindFirstChild(itemName)
if item then
-- 3. Remove from lender and transfer to borrower securely
item.Parent = borrower:FindFirstChild("Inventory")
-- 4. Record the active loan on the server
local loanID = lender.UserId .. "_" .. borrower.UserId .. "_" .. itemName
ActiveLoans[loanID] = {
Lender = lender,
Borrower = borrower,
ItemName = itemName,
OriginalParent = lenderInventory
}
print(borrower.Name .. " borrowed " .. itemName .. " from " .. lender.Name)
-- 5. Set an automatic return timer
task.delay(duration, function()
returnItem(loanID)
end)
else
warn("Lender does not own this item or it is already loaned.")
end
end
-- Function to return the item securely
function returnItem(loanID)
local loanData = ActiveLoans[loanID]
if not loanData then return end
local borrower = loanData.Borrower
local lender = loanData.Lender
local itemName = loanData.ItemName
local originalParent = loanData.OriginalParent
-- Check if the borrower still exists and has the item
if borrower and borrower:FindFirstChild("Inventory") then
local borrowerInventory = borrower.Inventory
local item = borrowerInventory:FindFirstChild(itemName)
-- Move the item back to the original owner if they are still in the game
if item and lender and originalParent then
item.Parent = originalParent
print(itemName .. " has been returned to " .. lender.Name)
elseif item then
-- If the lender left the game, the server safely deletes the temporary copy
item:Destroy()
-- Note: In a production game, you would save it back to the lender's offline DataStore
end
end
-- Clear the loan record from memory
ActiveLoans[loanID] = nil
end
-- Listen for secure server requests
LoanRequestEvent.OnServerEvent:Connect(function(player, targetPlayer, itemName)
-- In a real game, you would add UI prompts here to ask targetPlayer for permission
-- For this example, we simulate a 30-second safe loan duration
loanItem(targetPlayer, player, itemName, 30)
end)
Comments
Join the discussion about this script.
No comments yet
Be the first to share your thoughts!