### Install Tonstakers SDK Source: https://github.com/tonstakers/tonstakers-sdk/blob/main/README.md Instructions for installing the Tonstakers SDK using package managers like npm or yarn, essential for integrating the SDK into your project's dependencies. ```bash npm install tonstakers-sdk # or yarn add tonstakers-sdk ``` -------------------------------- ### Tonstakers SDK Event Listeners Source: https://github.com/tonstakers/tonstakers-sdk/blob/main/README.md Code examples for setting up event listeners for 'initialized' and 'deinitialized' events from the Tonstakers SDK. These listeners provide feedback on the SDK's operational status. ```javascript tonstakers.addEventListener("initialized", () => { console.log("Tonstakers SDK initialized successfully."); }); tonstakers.addEventListener("deinitialized", () => { console.log("Tonstakers SDK has been deinitialized."); }); ``` -------------------------------- ### Fetch and Display Pool Data Source: https://github.com/tonstakers/tonstakers-sdk/blob/main/demo/index.html Adds an event listener to the 'Get Pool Data' button. When clicked, it fetches staking pool information using fetchStakingPoolInfo and displays it as a JSON string in the 'poolDataDisplay' element. ```javascript document.getElementById("getPoolData").addEventListener("click", async () => { const poolData = await tonstakers.fetchStakingPoolInfo(5000); document.getElementById("poolDataDisplay").innerText = JSON.stringify(poolData, null, 2); }); ``` -------------------------------- ### Fetch and Display Round Timestamps Source: https://github.com/tonstakers/tonstakers-sdk/blob/main/demo/index.html Adds an event listener to the 'Get Rounds info' button. When clicked, it retrieves the start and end timestamps for the current staking round using getRoundTimestamps and updates the 'rounds' element with this information. ```javascript document.getElementById("getRounds").addEventListener("click", async () => { const [roundStart, roundEnd] = await tonstakers.getRoundTimestamps(5000); document.getElementById("rounds").innerText = `start: ${roundStart}, end: ${roundEnd}`; }); ``` -------------------------------- ### Tonstakers SDK Balance and Information Retrieval Source: https://github.com/tonstakers/tonstakers-sdk/blob/main/README.md Provides code examples for retrieving various balance and financial information using the Tonstakers SDK. This includes staked balance, TON balance, available balance, APY, TVL, stakers count, exchange rates, and cycle timestamps. ```javascript const stakedBalance = await tonstakers.getStakedBalance(); console.log(`Current staked balance: ${stakedBalance}`); const tonBalance = await tonstakers.getBalance(); console.log(`Current user ton balance: ${tonBalance}`); const availableBalance = await tonstakers.getAvailableBalance(); console.log(`Available balance for staking: ${availableBalance}`); const currentApy = await tonstakers.getCurrentApy(); console.log(`Current APY: ${currentApy}%`); const historicalApy = await tonstakers.getHistoricalApy(); console.log(`Historical APY data: ${historicalApy}`); const tvl = await tonstakers.getTvl(); console.log(`Total Value Locked (TVL): ${tvl}`); const stakersCount = await tonstakers.getStakersCount(); console.log(`Current number of stakers: ${stakersCount}`); const rates = await tonstakers.getRates(); console.log(`1 TON = ${rates.TONUSD} USD`); console.log(`1 tsTON = ${rates.tsTONTON} TON`); console.log(`Projected 1 tsTON = ${rates.tsTONTONProjected} TON`); const [cycleStart, cycleEnd] = await tonstakers.getRoundTimestamps(); console.log(`Cycle start: ${cycleStart}, Cycle end: ${cycleEnd}`); const activeWithdrawals = await tonstakers.getActiveWithdrawalNFTs(); console.log(`Active withdrawal NFTs: ${JSON.stringify(activeWithdrawals)}`); const instantLiquidity = await tonstakers.getInstantLiquidity(); console.log(`Instant liquidity: ${instantLiquidity}`); ``` -------------------------------- ### Get Current Staking Round Timestamps and Progress (JavaScript) Source: https://context7.com/tonstakers/tonstakers-sdk/llms.txt Fetches the start and end timestamps of the current staking cycle. It calculates and displays the round's progress percentage and the remaining time in days, hours, or minutes. Includes a function to update a UI countdown timer. ```javascript const [cycleStart, cycleEnd] = await tonstakers.getRoundTimestamps(); const startDate = new Date(cycleStart * 1000); const endDate = new Date(cycleEnd * 1000); const now = Date.now(); console.log(`Round started: ${startDate.toLocaleString()}`); console.log(`Round ends: ${endDate.toLocaleString()}`); // Calculate progress const roundDuration = cycleEnd - cycleStart; const elapsed = Math.floor(now / 1000) - cycleStart; const progressPercent = (elapsed / roundDuration) * 100; console.log(`Round progress: ${progressPercent.toFixed(1)}%`); // Time remaining const secondsRemaining = cycleEnd - Math.floor(now / 1000); const hoursRemaining = secondsRemaining / 3600; const daysRemaining = hoursRemaining / 24; if (daysRemaining >= 1) { console.log(`Time remaining: ${daysRemaining.toFixed(1)} days`); } else if (hoursRemaining >= 1) { console.log(`Time remaining: ${hoursRemaining.toFixed(1)} hours`); } else { console.log(`Time remaining: ${(secondsRemaining / 60).toFixed(0)} minutes`); } // Show countdown in UI function updateCountdown() { const now = Math.floor(Date.now() / 1000); const remaining = cycleEnd - now; if (remaining <= 0) { document.getElementById("countdown").textContent = "Round ended"; return; } const hours = Math.floor(remaining / 3600); const minutes = Math.floor((remaining % 3600) / 60); const seconds = remaining % 60; document.getElementById("countdown").textContent = `${hours}h ${minutes}m ${seconds}`; } setInterval(updateCountdown, 1000); ``` -------------------------------- ### Get Available Balance for Staking - JavaScript Source: https://context7.com/tonstakers/tonstakers-sdk/llms.txt Returns the user's TON balance, excluding a recommended fee reserve required for transactions. This provides the maximum amount of TON that can be staked. ```javascript const totalBalance = await tonstakers.getBalance(); const availableBalance = await tonstakers.getAvailableBalance(); const reserved = totalBalance - availableBalance; console.log(`Total: ${(totalBalance / 1e9).toFixed(4)} TON`); console.log(`Available: ${(availableBalance / 1e9).toFixed(4)} TON`); console.log(`Reserved for fees: ${(reserved / 1e9).toFixed(4)} TON`); // Use in UI to show maximum stakeable amount document.getElementById("maxStakeAmount").textContent = `Max: ${(availableBalance / 1e9).toFixed(2)} TON`; ``` -------------------------------- ### Fetch and Display Active Withdrawal NFTs Source: https://github.com/tonstakers/tonstakers-sdk/blob/main/demo/index.html Adds an event listener to the 'Get Withdrawal List' button. When clicked, it fetches active withdrawal NFTs using getActiveWithdrawalNFTs and displays them, or a message if none are found. Includes a helper function to format time durations. ```javascript document.getElementById("getWithdrawals").addEventListener("click", async () => { const activeWithdrawalsDiv = document.getElementById("activeWithdrawals"); activeWithdrawalsDiv.innerHTML = ""; const activeWithdrawals = await tonstakers.getActiveWithdrawalNFTs(10000); if(!activeWithdrawals.length) { activeWithdrawalsDiv.innerText = 'you have no active withdrawals' return } const formatTime = (seconds) => { const hours = Math.floor(seconds / 3600); const minutes = Math.floor((seconds % 3600) / 60); return `${hours} hours, ${minutes} minutes`; } activeWithdrawals.forEach(withdrawal => { const estimatedTim ``` -------------------------------- ### Fetch and Display Available Balance (JavaScript) Source: https://github.com/tonstakers/tonstakers-sdk/blob/main/demo/index.html This asynchronous function, `getAvailableBalance`, queries the `tonstakers.getAvailableBalance` method to get the user's available balance. Similar to other balance functions, it divides the result by 1,000,000,000 for proper display and updates the content of the 'availableBalance' HTML element. ```javascript async function getAvailableBalance() { const availableBalance = await tonstakers.getAvailableBalance(10000); document.getElementById("availableBalance").innerText = availableBalance / 1000000000; } ``` -------------------------------- ### Handle UI Interactions for Stake and Unstake Source: https://context7.com/tonstakers/tonstakers-sdk/llms.txt This snippet demonstrates how to wire up HTML button clicks to the staking and unstaking functions of the dashboard. It retrieves input values for stake/unstake amounts and unstake method from the DOM, converts them to the appropriate TON format using `toNano`, and then calls the respective dashboard methods. It also includes a basic example for a refresh button. ```javascript // Example usage document.getElementById("stakeBtn").onclick = async () => { const amount = document.getElementById("stakeInput").value; await dashboard.performStake(toNano(amount)); }; document.getElementById("unstakeBtn").onclick = async () => { const amount = document.getElementById("unstakeInput").value; const method = document.getElementById("unstakeMethod").value; await dashboard.performUnstake(toNano(amount), method); }; document.getElementById("refreshBtn").onclick = async () => { ``` -------------------------------- ### Get TON Balance - JavaScript Source: https://context7.com/tonstakers/tonstakers-sdk/llms.txt Retrieves the current TON balance of the connected wallet. It supports default caching and allows for forcing a refresh by setting the Time To Live (TTL) to 0, or using a longer cache duration. ```javascript // Get TON balance with default caching (30 seconds) const balance = await tonstakers.getBalance(); console.log(`TON Balance: ${(balance / 1e9).toFixed(4)} TON`); // Force refresh by setting TTL to 0 const freshBalance = await tonstakers.getBalance(0); console.log(`Fresh balance: ${(freshBalance / 1e9).toFixed(4)} TON`); // Use longer cache (60 seconds) for less frequent updates const cachedBalance = await tonstakers.getBalance(60000); ``` -------------------------------- ### Get Exchange Rates - JavaScript Source: https://context7.com/tonstakers/tonstakers-sdk/llms.txt Retrieves current conversion rates between TON, tsTON, and USD. It provides functions to convert tsTON to TON and USD, and estimates projected gains. This snippet uses `tonstakers.getRates()` and demonstrates utility functions for currency conversion. ```javascript const rates = await tonstakers.getRates(); console.log("Current rates:"); console.log(`1 TON = $${rates.TONUSD.toFixed(4)}`); console.log(`1 tsTON = ${rates.tsTONTON.toFixed(6)} TON`); console.log(`1 tsTON (projected) = ${rates.tsTONTONProjected.toFixed(6)} TON`); // Calculate conversion for UI function convertTsTONtoTON(tsTonAmount) { return tsTonAmount * rates.tsTONTON; } function convertTsTONtoUSD(tsTonAmount) { const tonAmount = tsTonAmount * rates.tsTONTON; return tonAmount * rates.TONUSD; } // Example: User has 100 tsTON const userTsTON = 100; console.log(`${userTsTON} tsTON = ${convertTsTONtoTON(userTsTON).toFixed(4)} TON`); console.log(`${userTsTON} tsTON = $${convertTsTONtoUSD(userTsTON).toFixed(2)}`); // Show projected gains const currentValue = userTsTON * rates.tsTONTON; const projectedValue = userTsTON * rates.tsTONTONProjected; const projectedGain = projectedValue - currentValue; console.log(`Projected gain: ${projectedGain.toFixed(6)} TON`); ``` -------------------------------- ### Get Number of Stakers - JavaScript Source: https://context7.com/tonstakers/tonstakers-sdk/llms.txt Fetches the current count of active stakers in the pool and calculates the average stake per user. It also provides a simple comparison of a user's stake against the average. This function requires `tonstakers.getStakersCount()`, `tonstakers.getTvl()`, and `tonstakers.getStakedBalance()`. ```javascript const count = await tonstakers.getStakersCount(); console.log(`Active stakers: ${count.toLocaleString()}`); // Calculate average stake per user const tvl = await tonstakers.getTvl(); const avgStake = tvl / count; console.log(`Average stake: ${(avgStake / 1e9).toFixed(2)} TON`); // Get your rank (approximate) const yourStake = await tonstakers.getStakedBalance(); if (yourStake > avgStake) { console.log("You're staking above average! 🎉"); } else { console.log(`You're staking ${(avgStake - yourStake) / 1e9).toFixed(2)} TON below average`); } ``` -------------------------------- ### Get Instant Liquidity - JavaScript Source: https://context7.com/tonstakers/tonstakers-sdk/llms.txt Fetches the amount of TON available for instant unstaking. If liquidity exists, it enables the instant unstake UI element and calculates the maximum amount that can be instantly unstaked, considering the user's staked balance. It also estimates the potential slippage. This function relies on `tonstakers.getInstantLiquidity()` and `tonstakers.getStakedBalance()`. ```javascript const liquidity = await tonstakers.getInstantLiquidity(); console.log(`Instant liquidity: ${(liquidity / 1e9).toFixed(2)} TON`); // Show instant unstake UI only if liquidity exists if (liquidity > 0) { document.getElementById("instantUnstakeBtn").style.display = "block"; // Calculate max instant unstake amount const userStaked = await tonstakers.getStakedBalance(); const maxInstant = Math.min(userStaked, liquidity); console.log(`You can instant unstake up to: ${(maxInstant / 1e9).toFixed(2)} tsTON`); // Estimate slippage for instant unstake const slippagePercent = 0.5; // Typically 0.5% or less const amountAfterSlippage = maxInstant * (1 - slippagePercent / 100); console.log(`After ~${slippagePercent}% slippage: ${(amountAfterSlippage / 1e9).toFixed(4)} TON`); } else { console.log("Instant unstake not available, use regular unstake"); document.getElementById("instantUnstakeBtn").style.display = "none"; } ``` -------------------------------- ### Get Staked tsTON Balance - JavaScript Source: https://context7.com/tonstakers/tonstakers-sdk/llms.txt Returns the amount of tsTON tokens (staked TON) held by the user. It also provides functionality to calculate the equivalent TON value and USD value based on current rates and project future value. ```javascript const stakedBalance = await tonstakers.getStakedBalance(); console.log(`Staked: ${(stakedBalance / 1e9).toFixed(4)} tsTON`); // Calculate equivalent TON value const rates = await tonstakers.getRates(); const tonValue = (stakedBalance / 1e9) * rates.tsTONTON; const usdValue = tonValue * rates.TONUSD; console.log(`Current value: ${tonValue.toFixed(4)} TON`); console.log(`USD value: $${usdValue.toFixed(2)}`); // Compare with projected value at round end const projectedTonValue = (stakedBalance / 1e9) * rates.tsTONTONProjected; const gain = projectedTonValue - tonValue; console.log(`Expected gain this round: ${gain.toFixed(6)} TON`); ``` -------------------------------- ### Get Current APY - JavaScript Source: https://context7.com/tonstakers/tonstakers-sdk/llms.txt Retrieves and displays the current Annual Percentage Yield (APY) for staking rewards. It also calculates estimated yearly and monthly earnings based on the current staked balance and APY. This function relies on the `tonstakers.getCurrentApy()` and `tonstakers.getStakedBalance()` methods. ```javascript const apy = await tonstakers.getCurrentApy(); console.log(`Current APY: ${apy.toFixed(2)}%`); // Calculate estimated earnings const stakedBalance = await tonstakers.getStakedBalance(); const yearlyEarnings = (stakedBalance / 1e9) * (apy / 100); const monthlyEarnings = yearlyEarnings / 12; console.log(`Estimated yearly earnings: ${yearlyEarnings.toFixed(4)} TON`); console.log(`Estimated monthly earnings: ${monthlyEarnings.toFixed(4)} TON`); ``` -------------------------------- ### Get Total Value Locked (TVL) - JavaScript Source: https://context7.com/tonstakers/tonstakers-sdk/llms.txt Retrieves the total amount of TON staked in the pool (TVL). It also calculates the TVL in USD by fetching current exchange rates and determines a user's share of the pool based on their staked balance. This function utilizes `tonstakers.getTvl()`, `tonstakers.getRates()`, and `tonstakers.getStakedBalance()`. ```javascript const tvl = await tonstakers.getTvl(); console.log(`Total Value Locked: ${(tvl / 1e9).toLocaleString()} TON`); // Calculate TVL in USD const rates = await tonstakers.getRates(); const tvlUsd = (tvl / 1e9) * rates.TONUSD; console.log(`TVL in USD: $${tvlUsd.toLocaleString()}`); // Calculate your share of the pool const stakedBalance = await tonstakers.getStakedBalance(); const poolShare = (stakedBalance / tvl) * 100; console.log(`Your pool share: ${poolShare.toFixed(4)}%`); ``` -------------------------------- ### Get Historical APY Data - JavaScript Source: https://context7.com/tonstakers/tonstakers-sdk/llms.txt Fetches historical APY data for analytics and charting. The data is returned as an array of objects, each containing the APY and timestamp. The snippet demonstrates calculating the average APY, finding the highest and lowest APY values, and formatting the data for use with charting libraries like Chart.js. It depends on `tonstakers.getHistoricalApy()`. ```javascript const history = await tonstakers.getHistoricalApy(); // history is an array of {apy: number, time: number} objects console.log(`APY data points: ${history.length}`); // Calculate average APY over time const avgApy = history.reduce((sum, h) => sum + h.apy, 0) / history.length; console.log(`Average APY: ${avgApy.toFixed(2)}%`); // Find highest and lowest APY const apyValues = history.map(h => h.apy); const maxApy = Math.max(...apyValues); const minApy = Math.min(...apyValues); console.log(`APY range: ${minApy.toFixed(2)}% - ${maxApy.toFixed(2)}%`); // Format for chart.js const chartData = { labels: history.map(h => new Date(h.time * 1000).toLocaleDateString()), datasets: [{ label: 'APY %', data: history.map(h => h.apy), borderColor: 'rgb(75, 192, 192)', }] }; ``` -------------------------------- ### Get Active Withdrawal NFTs with Estimated Payout Times (JavaScript) Source: https://context7.com/tonstakers/tonstakers-sdk/llms.txt Retrieves all active withdrawal NFTs, displaying their addresses, amounts, round end times, and estimated payout dates. It also sorts them by payout time and calculates the total pending withdrawal amount. This function is useful for monitoring pending withdrawals and their associated details. ```javascript const withdrawals = await tonstakers.getActiveWithdrawalNFTs(); console.log(`Active withdrawals: ${withdrawals.length}`); withdrawals.forEach((nft, index) => { const payoutDate = new Date(nft.estimatedPayoutDateTime * 1000); const roundEndDate = new Date(nft.roundEndTime * 1000); const now = Date.now(); const hoursUntilPayout = (nft.estimatedPayoutDateTime * 1000 - now) / (1000 * 60 * 60); console.log(` Withdrawal #${index + 1}:`); console.log(` NFT Address: ${nft.address}`); console.log(` Amount: ${nft.tsTONAmount} tsTON`); console.log(` Round ends: ${roundEndDate.toLocaleString()}`); console.log(` Estimated payout: ${payoutDate.toLocaleString()}`); console.log(` Time until payout: ${hoursUntilPayout.toFixed(1)} hours`); if (nft.metadata) { console.log(` NFT Name: ${nft.metadata.name}`); console.log(` NFT Image: ${nft.metadata.image}`); } }); // Sort by payout time const sorted = withdrawals.sort((a, b) => a.estimatedPayoutDateTime - b.estimatedPayoutDateTime ); if (sorted.length > 0) { const nextPayout = new Date(sorted[0].estimatedPayoutDateTime * 1000); console.log(` Next payout: ${sorted[0].tsTONAmount} tsTON at ${nextPayout.toLocaleString()}`); } // Calculate total pending withdrawals const totalPending = withdrawals.reduce((sum, nft) => sum + nft.tsTONAmount, 0); console.log(`Total pending: ${totalPending.toFixed(4)} tsTON`); ``` -------------------------------- ### Initialize Tonstakers SDK in Module Environment Source: https://github.com/tonstakers/tonstakers-sdk/blob/main/README.md Demonstrates initializing the Tonstakers SDK within a JavaScript module environment. It requires a wallet connector (e.g., TonConnect instance) and allows for optional parameters like partner code and TON API key. ```javascript import { Tonstakers } from "tonstakers-sdk"; // this is an example connector import { TonConnectUI } from "@tonconnect/ui"; export const tonConnectUI = new TonConnectUI({ manifestUrl: MANIFEST_URL, }); const tonstakers = new Tonstakers({ connector: yourWalletConnector, // Your wallet connector partnerCode: 123456, // Optional partner code tonApiKey: "YOUR_API_KEY", // Optional API key for tonapi }); ``` -------------------------------- ### Initialize Tonstakers SDK via Browser Script Tag (HTML/JavaScript) Source: https://context7.com/tonstakers/tonstakers-sdk/llms.txt Integrates the Tonstakers SDK using script tags in an HTML file, suitable for browser environments. It initializes TonConnect UI and the Tonstakers SDK, then sets up event listeners for UI updates and wallet connections. Handles basic staking functionality. ```html