UNPKG

@b3dotfun/leaderboards

Version:

SDK to interact with leaderboards smart contract

241 lines 9.94 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const tslib_1 = require("tslib"); const dotenv = tslib_1.__importStar(require("dotenv")); const chains_1 = require("viem/_types/chains"); const leaderboard_1 = require("../leaderboard"); dotenv.config(); const CHAIN_ID = chains_1.base.id; // Use "testnet" for testnet, "mainnet" for mainnet const LEADERBOARD_ADDRESS = "0x393B28862962B33F253c955b9295b8f30e83104B"; // Example leaderboard address const USER_ADDRESS = "0x1234567890123456789012345678901234567890"; // Example user address const NEW_ADMIN_ADDRESS = "0x9876543210987654321098765432109876543210"; // Example new admin address /** * Initialize and connect to a specific Leaderboard contract * @returns Connected Leaderboard instance */ function initializeLeaderboard() { const leaderboard = new leaderboard_1.Leaderboard(CHAIN_ID, process.env.LEADERBOARD_ADMIN_PRIVATE_KEY, LEADERBOARD_ADDRESS); const isConnected = leaderboard.connect(); if (!isConnected) { console.error("Failed to connect to the Leaderboard contract."); return null; } console.log("Connected to the Leaderboard contract"); return leaderboard; } /** * Manage administrative functions of the leaderboard * @param leaderboard Connected Leaderboard instance * @param newAdmin Address of the new admin to add */ async function manageAdmins(leaderboard, newAdmin) { // Add new admin await leaderboard.addAdmin(newAdmin); console.log("Added new admin:", newAdmin); // Get current admins const admins = await leaderboard.getAdmins(); console.log("Current admins:", admins); } /** * Update leaderboard configuration parameters * @param leaderboard Connected Leaderboard instance * @param durationInHours New duration in hours * @param title New title for the leaderboard */ async function updateLeaderboardConfig(leaderboard, durationInHours, title) { const now = Math.floor(Date.now() / 1000); const endTime = now + durationInHours * 3600; await leaderboard.updateLeaderboard(now, endTime, title); console.log("Updated leaderboard parameters:"); console.log(`- Title: ${title}`); console.log(`- Start time: ${new Date(now * 1000).toISOString()}`); console.log(`- End time: ${new Date(endTime * 1000).toISOString()}`); } /** * Manage user scores with various operations * @param leaderboard Connected Leaderboard instance * @param user User address to update */ async function manageUserScores(leaderboard, user) { const timestamp = Math.floor(Date.now() / 1000); // Check if user is eligible (for private leaderboards) const isPrivate = await leaderboard.isPrivate(); if (isPrivate) { const isEligible = await leaderboard.isUserEligible(user); if (!isEligible) { console.log(`User ${user} is not eligible for this private leaderboard`); return; } } // Check if user is blacklisted const isBlacklisted = await leaderboard.isUserBlacklisted(user); if (isBlacklisted) { console.log(`User ${user} is blacklisted`); return; } // Update scores await leaderboard.updateScores([{ user, score: 1000, timestamp }]); console.log(`Set initial score for ${user}: 1000`); // Increment score await leaderboard.incrementScores([{ user, score: 500, timestamp }]); console.log(`Incremented score for ${user} by 500`); // Get updated score const userScore = await leaderboard.getUserScore(user); console.log(`Current score for ${user}: ${userScore}`); } /** * Display leaderboard rankings in different formats * @param leaderboard Connected Leaderboard instance */ async function displayLeaderboardRankings(leaderboard) { // Display top 3 users const topScores = await leaderboard.getTopScores(3); console.log("\nTop 3 Users:"); console.log("-------------"); topScores.forEach(({ player, score, rank }) => { console.log(`${rank}. ${player}: ${score} points`); }); // Display all users const allScores = await leaderboard.getAllScores(); console.log("\nFull Leaderboard Rankings:"); console.log("-------------------------"); allScores.forEach(({ player, score, rank }) => { console.log(`${rank}. ${player}: ${score} points`); }); // Get specific user's ranking const userRanking = await leaderboard.getPlayerRanking(USER_ADDRESS); if (userRanking) { console.log("\nYour User Stats:"); console.log("----------------"); console.log(`Rank: ${userRanking.rank}`); console.log(`Score: ${userRanking.score}`); } else { console.log("\nUser not found in leaderboard"); } } /** * Get and display detailed leaderboard information * @param leaderboard Connected Leaderboard instance */ async function getLeaderboardInfo(leaderboard) { const props = await leaderboard.getLeaderboardProperties(); const isActive = await leaderboard.isLeaderboardActive(); const userCount = await leaderboard.getLeaderboardUserCount(); console.log("\nLeaderboard Information:"); console.log("------------------------"); if (props) { console.log("- Title:", props.title); console.log("- Slug:", props.slug); console.log("- Start time:", new Date(props.startTime * 1000).toISOString()); console.log("- End time:", new Date(props.endTime * 1000).toISOString()); console.log("- Status:", isActive ? "Active" : "Inactive"); console.log("- Concluded:", props.hasConcluded ? "Yes" : "No"); console.log("- Private:", props.isPrivate ? "Yes" : "No"); console.log("- Use Latest Score:", props.useLatestScore ? "Yes" : "No"); console.log("- Total Users:", userCount); } else { console.log("Could not fetch leaderboard properties"); } } /** * Manage user eligibility for private leaderboards * @param leaderboard Connected Leaderboard instance * @param users Array of user addresses */ async function manageEligibleUsers(leaderboard, users) { const isPrivate = await leaderboard.isPrivate(); if (!isPrivate) { console.log("This is not a private leaderboard"); return; } // Add eligible users await leaderboard.addEligibleUsers(users); console.log("Added eligible users:", users); // Get all eligible users const eligibleUsers = await leaderboard.getEligibleUsers(); console.log("Current eligible users:", eligibleUsers); } async function displayLeaderboardProperties(leaderboard) { const properties = await leaderboard.getLeaderboardProperties(); if (!properties) { console.log("Error: Could not fetch leaderboard properties"); return; } console.log("\nLeaderboard Properties:"); console.log("======================"); console.log("- Title:", properties.title); console.log("- Slug:", properties.slug); console.log("- Start time:", new Date(properties.startTime * 1000).toISOString()); console.log("- End time:", new Date(properties.endTime * 1000).toISOString()); console.log("- Concluded:", properties.hasConcluded ? "Yes" : "No"); console.log("- Private:", properties.isPrivate ? "Yes" : "No"); console.log("- Use Latest Score:", properties.useLatestScore ? "Yes" : "No"); console.log("- Has Attempt Limit:", properties.hasAttemptLimit ? "Yes" : "No"); console.log("- Initial Attempts:", properties.initialAttempts); console.log("- Reverse Sort:", properties.isReverseSort ? "Yes" : "No"); } async function displayRankings(leaderboard) { // Get the leaderboard properties to check if it's reverse sorted const properties = await leaderboard.getLeaderboardProperties(); if (!properties) { console.log("Error: Could not fetch leaderboard properties"); return; } // Get top 10 scores const topScores = await leaderboard.getTopScores(10); console.log("\nTop 10 Scores:"); console.log("=============="); if (properties.isReverseSort) { console.log("(Note: This leaderboard uses reverse sorting - lower scores are better)"); } topScores.forEach((score, index) => { console.log(`${index + 1}. User: ${score.player} - Score: ${score.score}`); }); // Get user's rank and surrounding scores const userAddress = "0x1234567890123456789012345678901234567890"; const userRanking = await leaderboard.getPlayerRanking(userAddress); if (userRanking) { console.log("\nYour Ranking:"); console.log("============="); console.log(`Rank: ${userRanking.rank}`); console.log(`Score: ${userRanking.score}`); } else { console.log("\nUser not found in leaderboard"); } } async function main() { try { // Initialize the leaderboard const leaderboard = initializeLeaderboard(); if (!leaderboard) return; // Display leaderboard properties await displayLeaderboardProperties(leaderboard); // Check if leaderboard is active const isActive = await leaderboard.isLeaderboardActive(); console.log("\nLeaderboard is active:", isActive); if (isActive) { // Manage user scores await manageUserScores(leaderboard, USER_ADDRESS); // Display rankings await displayRankings(leaderboard); // Manage eligible users (if private) const properties = await leaderboard.getLeaderboardProperties(); if (properties?.isPrivate) { await manageEligibleUsers(leaderboard, [USER_ADDRESS]); } } else { console.log("Leaderboard is not active. No further actions can be taken."); } } catch (error) { console.error("Error:", error); } } // Execute the example main().catch(console.error); //# sourceMappingURL=leaderboard.js.map