@b3dotfun/leaderboards
Version:
SDK to interact with leaderboards smart contract
272 lines • 10 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.LeaderboardFactory = void 0;
const viem_1 = require("viem");
const accounts_1 = require("viem/accounts");
const LeaderboardFactoryABI_1 = require("./abis/LeaderboardFactoryABI");
const config_1 = require("./config");
const leaderboard_1 = require("./leaderboard");
class LeaderboardFactory {
contract;
publicClient;
contractAddress;
chain;
walletKey;
constructor(chainId, walletKey) {
if (walletKey && !walletKey.startsWith("0x")) {
walletKey = `0x${walletKey}`;
}
const config = (0, config_1.getConfig)(chainId);
this.chain = config.chain;
this.walletKey = walletKey || "";
this.contractAddress = config.leaderboardFactoryContractAddress;
}
connect(provider) {
try {
const client = (0, viem_1.createWalletClient)({
chain: this.chain,
transport: provider ? (0, viem_1.custom)(provider) : (0, viem_1.http)(),
});
this.contract = (0, viem_1.getContract)({
address: this.contractAddress,
abi: LeaderboardFactoryABI_1.LeaderboardFactoryABI,
client: client,
});
// Initialize public client for reading transaction receipts
this.publicClient = (0, viem_1.createPublicClient)({
chain: this.chain,
transport: (0, viem_1.http)(),
});
return true;
}
catch (error) {
console.error("Connection failed:", error);
return false;
}
}
async handleError(error) {
if (error.data === "0xce967011") {
throw new Error("Leaderboard already created");
}
else if (error.data === "0x72f68b1f") {
throw new Error("Leaderboard not created");
}
else {
throw error;
}
}
async createLeaderboard(admin, slug, startTime, endTime, title, isPrivate = false, useLatestScore = false, hasAttemptLimit = false, initialAttempts = 0, isReverseSort = false) {
if (!this.walletKey) {
throw new Error("Wallet key not set");
}
try {
// Send the transaction
const hash = await this.contract.write.createLeaderboard([
admin,
slug,
startTime,
endTime,
title,
isPrivate,
useLatestScore,
hasAttemptLimit,
BigInt(initialAttempts),
isReverseSort,
], {
account: (0, accounts_1.privateKeyToAccount)(this.walletKey),
chain: this.chain,
});
// Wait for the transaction to be mined and get the receipt
const receipt = await this.publicClient.waitForTransactionReceipt({
hash,
});
// Find the LeaderboardCreated event
const event = receipt.logs.find((log) => {
try {
const decoded = (0, viem_1.decodeEventLog)({
abi: LeaderboardFactoryABI_1.LeaderboardFactoryABI,
data: log.data,
topics: log.topics,
});
return decoded.eventName === "LeaderboardCreated";
}
catch {
return false;
}
});
if (!event) {
throw new Error("LeaderboardCreated event not found in transaction logs");
}
// Parse the event to get the leaderboard address
const decoded = (0, viem_1.decodeEventLog)({
abi: LeaderboardFactoryABI_1.LeaderboardFactoryABI,
data: event.data,
topics: event.topics,
});
return decoded.args.leaderboardAddress;
}
catch (error) {
return await this.handleError(error);
}
}
async getLeaderboardAddressesBySlug(slug) {
try {
const result = await this.contract.read.getLeaderboards([slug]);
return Array.from(result);
}
catch (error) {
return await this.handleError(error);
}
}
async getAllLeaderboards() {
try {
return await this.contract.read.getAllLeaderboards();
}
catch (error) {
return [];
}
}
async getLatestLeaderboardBySlug(slug) {
try {
return await this.contract.read.getLatestLeaderboard([slug]);
}
catch (error) {
return "0x";
}
}
async getLeaderboardCountBySlug(slug) {
try {
return Number(await this.contract.read.getLeaderboardCount([slug]));
}
catch (error) {
return 0;
}
}
async getTotalLeaderboardCount() {
try {
return Number(await this.contract.read.getTotalLeaderboardCount());
}
catch (error) {
return 0;
}
}
async getLeaderboardsWithProps(slug) {
try {
// Get all leaderboard addresses for this slug
const addresses = await this.getLeaderboardAddressesBySlug(slug);
if (!addresses.length) {
return [];
}
// Get properties for each leaderboard
const leaderboardsWithProps = await Promise.all(addresses.map(async (address) => {
try {
// Initialize a new Leaderboard instance with this address
const leaderboard = new leaderboard_1.Leaderboard(this.chain.id, this.walletKey, address);
// Connect to the leaderboard contract
const isConnected = leaderboard.connect();
if (!isConnected) {
return undefined;
}
// Get the leaderboard properties
const properties = await leaderboard.getLeaderboardProperties();
if (!properties) {
return undefined;
}
return {
address,
properties,
};
}
catch (error) {
console.error(`Error fetching properties for leaderboard ${address}:`, error);
return undefined;
}
}));
// Filter out any undefined values from failed fetches
return leaderboardsWithProps.filter((item) => item !== undefined);
}
catch (error) {
console.error("Error getting leaderboards with props:", error);
return [];
}
}
async getLatestLeaderboardWithProps(slug) {
try {
// Get the latest leaderboard address for this slug
const address = await this.getLatestLeaderboardBySlug(slug);
if (address === "0x") {
return undefined;
}
// Initialize a new Leaderboard instance with this address
const leaderboard = new leaderboard_1.Leaderboard(this.chain.id, this.walletKey, address);
// Connect to the leaderboard contract
const isConnected = leaderboard.connect();
if (!isConnected) {
return undefined;
}
// Get the leaderboard properties
const properties = await leaderboard.getLeaderboardProperties();
if (!properties) {
return undefined;
}
return {
address,
properties,
};
}
catch (error) {
console.error("Error getting leaderboard with props:", error);
return undefined;
}
}
async getAllLeaderboardsWithProps() {
try {
// Get all leaderboard addresses
const addresses = await this.getAllLeaderboards();
if (!addresses.length) {
return [];
}
// Get properties for each leaderboard
const leaderboardsWithProps = await Promise.all(addresses.map(async (address) => {
try {
// Initialize a new Leaderboard instance with this address
const leaderboardInstance = new leaderboard_1.Leaderboard(this.chain.id, this.walletKey, address);
// Connect to the leaderboard contract
const isConnected = leaderboardInstance.connect();
if (!isConnected) {
return undefined;
}
// Get the leaderboard properties
const properties = await leaderboardInstance.getLeaderboardProperties();
if (!properties) {
return undefined;
}
return {
address,
properties,
};
}
catch (error) {
console.error(`Error fetching properties for leaderboard ${address}:`, error);
return undefined;
}
}));
// Filter out any undefined values from failed fetches
return leaderboardsWithProps.filter((item) => item !== undefined);
}
catch (error) {
console.error("Error getting all leaderboards with props:", error);
return [];
}
}
async getAdmins() {
try {
return await this.contract.read.getAdmins();
}
catch (error) {
return [];
}
}
}
exports.LeaderboardFactory = LeaderboardFactory;
//# sourceMappingURL=leaderboardFactory.js.map