### 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 Tonstakers Integration
``` -------------------------------- ### Initialize TonConnectSDK and Tonstakers SDK Source: https://github.com/tonstakers/tonstakers-sdk/blob/main/demo/index.html Initializes TonConnectSDK for wallet interaction and the Tonstakers SDK for staking functionalities. It also sets up event listeners for data fetching on page load and wallet connection status changes. Dependencies include TonConnectSDK, TON_CONNECT_UI, and TonstakersSDK. ```javascript const connector = new TonConnectSDK.TonConnect({ manifestUrl: "https://tonstakers.com/dapp/tonconnect-manifest.json" }); const tonConnectUI = new TON_CONNECT_UI.TonConnectUI({ connector }); const { Tonstakers } = TonstakersSDK; const tonstakers = new Tonstakers({ connector, partnerCode: 123456 }); ``` -------------------------------- ### Initialize Tonstakers SDK with TonConnect (JavaScript) Source: https://context7.com/tonstakers/tonstakers-sdk/llms.txt Initializes the Tonstakers SDK with TonConnect for wallet integration. Requires `@tonconnect/ui` and accepts optional parameters like partner code, TON API key, and cache duration. Outputs initialization status logs. ```javascript import { Tonstakers } from "tonstakers-sdk"; import { TonConnectUI } from "@tonconnect/ui"; // Initialize wallet connector const tonConnectUI = new TonConnectUI({ manifestUrl: "https://yourdapp.com/tonconnect-manifest.json", }); // Initialize Tonstakers SDK const tonstakers = new Tonstakers({ connector: tonConnectUI, partnerCode: 123456, // Optional: your partner code tonApiKey: "YOUR_TONAPI_KEY", // Optional: for higher rate limits cacheFor: 30000, // Optional: cache duration in ms (default: 30000) }); // Listen for initialization events tonstakers.addEventListener("initialized", () => { console.log("SDK ready for operations"); updateUI(); }); tonstakers.addEventListener("deinitialized", () => { console.log("Wallet disconnected"); clearUI(); }); // Check if SDK is ready if (tonstakers.ready) { console.log("Connected to:", tonstakers.isTestnet ? "Testnet" : "Mainnet"); } ``` -------------------------------- ### Initialize Tonstakers SDK in Browser Environment Source: https://github.com/tonstakers/tonstakers-sdk/blob/main/README.md Shows how to initialize the Tonstakers SDK directly within an HTML file using a script tag. This method is suitable for simpler web integrations where a module system is not used. ```html ``` -------------------------------- ### Initialize and Manage Tonstakers SDK with TonConnectUI Source: https://context7.com/tonstakers/tonstakers-sdk/llms.txt This snippet initializes the Tonstakers SDK and TonConnectUI for a staking dashboard. It sets up event listeners for wallet connection and disconnection, enabling the dashboard to react to user authentication status. Dependencies include 'tonstakers-sdk' and '@tonconnect/ui'. ```javascript import { Tonstakers } from "tonstakers-sdk"; import { TonConnectUI } from "@tonconnect/ui"; import { toNano, fromNano } from "@ton/core"; class StakingDashboard { constructor() { this.tonConnectUI = new TonConnectUI({ manifestUrl: "https://yourdapp.com/tonconnect-manifest.json", }); this.tonstakers = new Tonstakers({ connector: this.tonConnectUI, partnerCode: 123456, tonApiKey: "YOUR_TONAPI_KEY", cacheFor: 30000, }); this.setupEventListeners(); } setupEventListeners() { this.tonstakers.addEventListener("initialized", () => { this.onWalletConnected(); }); this.tonstakers.addEventListener("deinitialized", () => { this.onWalletDisconnected(); }); } async onWalletConnected() { console.log("Wallet connected, loading data..."); try { await Promise.all([ this.updateBalances(), this.updatePoolInfo(), this.updateWithdrawals(), ]); this.enableUI(); console.log("Dashboard ready"); } catch (error) { console.error("Failed to load data:", error); } } onWalletDisconnected() { console.log("Wallet disconnected"); this.disableUI(); this.clearDisplay(); } // ... other methods ... enableUI() { // Enable stake/unstake buttons } disableUI() { // Disable all interactive elements } clearDisplay() { // Clear all displayed values } } // Initialize dashboard const dashboard = new StakingDashboard(); ``` -------------------------------- ### Tonstakers SDK Staking and Unstaking Operations Source: https://github.com/tonstakers/tonstakers-sdk/blob/main/README.md Illustrates the usage of various staking and unstaking methods provided by the Tonstakers SDK. This includes staking specific amounts, maximum available balance, instant unstaking, and unstaking at the best rate. ```javascript await tonstakers.stake(toNano(1)); // Stake 1 TON await tonstakers.unstake(toNano(1)); // Unstake 1 tsTON await tonstakers.stakeMax(); // Stake the maximum available balance await tonstakers.unstakeInstant(toNano(1)); // Instant unstake 1 tsTON await tonstakers.unstakeBestRate(toNano(1)); // Unstake 1 tsTON at the best available rate ``` -------------------------------- ### Connect Wallet Button Event Listener Source: https://github.com/tonstakers/tonstakers-sdk/blob/main/demo/index.html Adds an event listener to the 'Connect Wallet' button. When clicked, it opens the TonConnectUI modal, allowing the user to select and connect their wallet. ```javascript document.getElementById("connectWallet").addEventListener("click", async () => { await tonConnectUI.openModal(); }); ``` -------------------------------- ### Fetch and Display Wallet Balance (JavaScript) Source: https://github.com/tonstakers/tonstakers-sdk/blob/main/demo/index.html This asynchronous function, `getWalletBalance`, retrieves the user's wallet balance using the `tonstakers.getBalance` method. It then formats the balance by dividing it by 1,000,000,000 and updates the text content of an HTML element with the ID 'balance'. ```javascript async function getWalletBalance() { const balance = await tonstakers.getBalance(10000); document.getElementById("balance").innerText = balance / 1000000000; } ``` -------------------------------- ### Handle Wallet Connection Status Changes Source: https://github.com/tonstakers/tonstakers-sdk/blob/main/demo/index.html Sets up a listener for changes in the wallet connection status. When a wallet is connected, it displays the wallet address, hides the connect button, shows the disconnect button, and fetches wallet-specific balances. If disconnected, it resets the UI elements. ```javascript const unsubscribe = tonConnectUI.onStatusChange((wallet) => { if (wallet?.account?.address) { const address = wallet.account.address; document.getElementById("walletAddress").innerText = address; document.getElementById("connectWallet").style.display = "none"; document.getElementById("disconnectWallet").style.display = "inline"; getWalletBalance(); } }); ``` -------------------------------- ### Fetch and Display Staked Balance (JavaScript) Source: https://github.com/tonstakers/tonstakers-sdk/blob/main/demo/index.html The `getStakedBalance` asynchronous function fetches the amount of tsTON the user has staked using `tonstakers.getStakedBalance`. The result is then divided by 1,000,000,000 for formatting and displayed in the HTML element with the ID 'stakedBalance'. ```javascript async function getStakedBalance() { const stakedBalance = await tonstakers.getStakedBalance(10000); document.getElementById("stakedBalance").innerText = stakedBalance / 1000000000; } ``` -------------------------------- ### Fetch and Display Staking Balances and Rates Source: https://context7.com/tonstakers/tonstakers-sdk/llms.txt This JavaScript function fetches the user's TON balance, staked amount, and available balance using the Tonstakers SDK. It also retrieves current rates to calculate the total value of staked tsTON and the overall portfolio in USD. The results are logged to the console. ```javascript async updateBalances() { const [balance, staked, available] = await Promise.all([ this.tonstakers.getBalance(), this.tonstakers.getStakedBalance(), this.tonstakers.getAvailableBalance(), ]); const rates = await this.tonstakers.getRates(); const stakedValueInTON = (staked / 1e9) * rates.tsTONTON; const totalValueUSD = ((balance + stakedValueInTON * 1e9) / 1e9) * rates.TONUSD; console.log(`TON Balance: ${(balance / 1e9).toFixed(4)} TON`); console.log(`Staked: ${(staked / 1e9).toFixed(4)} tsTON (${stakedValueInTON.toFixed(4)} TON)`); console.log(`Available to stake: ${(available / 1e9).toFixed(4)} TON`); console.log(`Total value: $${totalValueUSD.toFixed(2)}`); return { balance, staked, available, rates }; } ``` -------------------------------- ### Display Withdrawal Information with Estimated Times (JavaScript) Source: https://github.com/tonstakers/tonstakers-sdk/blob/main/demo/index.html This snippet demonstrates how to format and display withdrawal details, including estimated payout times and time remaining in the current round. It dynamically creates HTML elements to show this information. It relies on a `formatTime` function (assumed to be defined elsewhere) and the `tonstakers` SDK object. ```javascript e = formatTime(withdrawal.estimatedPayoutDateTime - Math.floor(Date.now() / 1000)); const roundEnds = formatTime(withdrawal.roundEndTime - Math.floor(Date.now() / 1000)); const estimatedTimeInQueue = formatTime(withdrawal.estimatedPayoutDateTime - withdrawal.roundEndTime); const withdrawalDiv = document.createElement("div"); withdrawalDiv.classList.add("withdrawal-item"); const withdrawalInfo = ` Withdrawal ${withdrawal.tsTONAmount} tsTON
Estimated Payout Time: ${estimatedTime}
Estimated Time in Queue: ${estimatedTimeInQueue}
Round Ends: ${roundEnds}
Transfer TX: ${withdrawal.address}
Collection: ${withdrawal.collection?.address}

`; withdrawalDiv.innerHTML = withdrawalInfo; activeWithdrawalsDiv.appendChild(withdrawalDiv); ``` -------------------------------- ### Fetch and Display Staking Data on Page Load Source: https://github.com/tonstakers/tonstakers-sdk/blob/main/demo/index.html Fetches and displays current APY, TVL, staker count, round timestamps, and exchange rates when the DOM is fully loaded. It uses the tonstakers object to interact with the staking pool. Errors during fetching are logged to the console. ```javascript window.addEventListener("DOMContentLoaded", async () => { try { const apy = await tonstakers.getCurrentApy(600000); document.getElementById("apy").innerText = apy; const tvl = await tonstakers.getTvl(600000); document.getElementById("tvl").innerText = tvl / 1000000000; const stakers = await tonstakers.getStakersCount(600000); document.getElementById("stakers").innerText = stakers; const [roundStart, roundEnd] = await tonstakers.getRoundTimestamps(5000); document.getElementById("rounds").innerText = `start ${roundStart}, end ${roundEnd}`; const rates = await tonstakers.getRates(600000); document.getElementById("TONUSD").innerText = rates.TONUSD; document.getElementById("tsTONTON").innerText = rates.tsTONTON; } catch (error) { console.error("Error fetching initial data:", error); } }); ``` -------------------------------- ### Refresh Balances on Click Event (JavaScript) Source: https://github.com/tonstakers/tonstakers-sdk/blob/main/demo/index.html This code sets up an event listener for a 'click' event on the HTML element with the ID 'refreshBalances'. When clicked, it triggers the `getWalletBalance` and `getStakedBalance` functions, allowing the user to refresh their displayed financial information. ```javascript document .getElementById("refreshBalances") .addEventListener("click", () => { getWalletBalance(); getStakedBalance(); }); ``` -------------------------------- ### Tonstakers SDK Storage Management Source: https://github.com/tonstakers/tonstakers-sdk/blob/main/README.md Demonstrates the methods for clearing cached data within the Tonstakers SDK. This includes options to clear all cached data or specifically user-specific cached data. ```javascript await tonstakers.clearStorageData(); // Clear all cached data await tonstakers.clearStorageUserData(); // Clear cached user-specific data ``` -------------------------------- ### Stake TON tokens with Tonstakers SDK (JavaScript) Source: https://context7.com/tonstakers/tonstakers-sdk/llms.txt Performs a standard staking operation to convert TON tokens to tsTON tokens using the Tonstakers SDK. It requires the `toNano` utility from `@ton/core` for amount conversion. The output includes the transaction BOC and logs the new staked balance after a short delay. ```javascript import { toNano } from "@ton/core"; // Stake 10 TON try { const result = await tonstakers.stake(toNano("10")); console.log("Transaction BOC:", result.boc); // Wait for confirmation and check new balance setTimeout(async () => { const stakedBalance = await tonstakers.getStakedBalance(); console.log(`New staked balance: ${stakedBalance / 1e9} tsTON`); }, 5000); } catch (error) { console.error("Staking failed:", error.message); } ``` -------------------------------- ### Perform Stake Operation with Tonstakers SDK Source: https://context7.com/tonstakers/tonstakers-sdk/llms.txt This function handles the staking process. It takes an amount in TON (converted using `toNano`), logs the staking attempt, sends the transaction via the Tonstakers SDK, and logs the transaction details. It includes a timeout to refresh balances after a successful stake. Error handling is included for failed staking operations. ```javascript async performStake(amount) { try { console.log(`Staking ${fromNano(amount)} TON...`); const result = await this.tonstakers.stake(amount); console.log("Stake transaction sent:", result.boc); // Wait and update setTimeout(() => this.updateBalances(), 5000); return result; } catch (error) { console.error("Stake failed:", error.message); throw error; } } ``` -------------------------------- ### Perform Unstake Operation with Different Methods Source: https://context7.com/tonstakers/tonstakers-sdk/llms.txt This function manages unstaking operations, allowing users to choose between 'regular', 'instant', or 'bestRate' methods. It takes the amount to unstake (converted using `toNano`), calls the appropriate Tonstakers SDK method, logs the transaction, and updates balances and withdrawals after a short delay. Error handling is included. ```javascript async performUnstake(amount, method = "regular") { try { console.log(`Unstaking ${fromNano(amount)} tsTON (${method})...`); let result; switch (method) { case "instant": result = await this.tonstakers.unstakeInstant(amount); break; case "bestRate": result = await this.tonstakers.unstakeBestRate(amount); break; default: result = await this.tonstakers.unstake(amount); } console.log("Unstake transaction sent:", result.boc); // Wait and update setTimeout(() => { this.updateBalances(); this.updateWithdrawals(); }, 5000); return result; } catch (error) { console.error("Unstake failed:", error.message); throw error; } } ``` -------------------------------- ### Unstake Instant tsTON Button Event Listener Source: https://github.com/tonstakers/tonstakers-sdk/blob/main/demo/index.html Adds an event listener to the 'Unstake 1 tsTON Instant' button. If a wallet is connected, it calls the unstakeInstant function of the tonstakers object with a specified amount (1 tsTON). Logs success or error. ```javascript document.getElementById("unstakeInstant").addEventListener("click", async () => { if (tonstakers) { await tonstakers.unstakeInstant(1000000000n); // Example unstake amount console.log("Unstaked 1 tsTON Instant"); } else { console.error("Wallet not connected"); } }); ``` -------------------------------- ### Clear Storage and Update Data - JavaScript Source: https://context7.com/tonstakers/tonstakers-sdk/llms.txt This snippet demonstrates clearing storage data and updating various dashboard metrics. It's useful for refreshing application state and ensuring the latest information is displayed to the user. Dependencies include the Tonstakers SDK's dashboard object. ```javascript await dashboard.tonstakers.clearStorageData(); await dashboard.updateBalances(); await dashboard.updatePoolInfo(); await dashboard.updateWithdrawals(); ``` -------------------------------- ### Initiate Standard Unstake - JavaScript Source: https://context7.com/tonstakers/tonstakers-sdk/llms.txt Initiates the standard unstaking process for tsTON, which completes at the end of the current staking round. This method returns a withdrawal NFT upon initiation. It includes logic to check for active withdrawals after a delay. ```javascript import { toNano } from "@ton/core"; // Unstake 5 tsTON try { const result = await tonstakers.unstake(toNano("5")); console.log("Unstake initiated, will receive withdrawal NFT"); // Check active withdrawals setTimeout(async () => { const withdrawals = await tonstakers.getActiveWithdrawalNFTs(); console.log(`You have ${withdrawals.length} pending withdrawals`); withdrawals.forEach((nft, index) => { const payoutDate = new Date(nft.estimatedPayoutDateTime * 1000); console.log(`Withdrawal ${index + 1}:`); console.log(` Amount: ${nft.tsTONAmount} tsTON`); console.log(` Estimated payout: ${payoutDate.toLocaleString()}`); }); }, 5000); } catch (error) { console.error("Unstake failed:", error.message); } ``` -------------------------------- ### Retrieve and Display Staking Pool Information Source: https://context7.com/tonstakers/tonstakers-sdk/llms.txt This function retrieves key metrics of the staking pool, including the current Annual Percentage Yield (APY), Total Value Locked (TVL), and the number of stakers. It calculates the average stake per user and logs these details to the console. This information is vital for users to assess the pool's performance and size. ```javascript async updatePoolInfo() { const [apy, tvl, stakersCount] = await Promise.all([ this.tonstakers.getCurrentApy(), this.tonstakers.getTvl(), this.tonstakers.getStakersCount(), ]); const avgStake = tvl / stakersCount; console.log(`Current APY: ${apy.toFixed(2)}%`); console.log(`TVL: ${(tvl / 1e9).toLocaleString()} TON`); console.log(`Stakers: ${stakersCount.toLocaleString()}`); console.log(`Avg stake: ${(avgStake / 1e9).toFixed(2)} TON`); return { apy, tvl, stakersCount }; } ``` -------------------------------- ### Stake TON Button Event Listener Source: https://github.com/tonstakers/tonstakers-sdk/blob/main/demo/index.html Adds an event listener to the 'Stake 1 TON' button. If a wallet is connected, it calls the stake function of the tonstakers object with a specified amount (1 TON). Logs success or error. ```javascript document.getElementById("stake").addEventListener("click", async () => { if (tonstakers) { await tonstakers.stake(1000000000n); // Example stake amount console.log("Staked 1 TON"); } else { console.error("Wallet not connected"); } }); ``` -------------------------------- ### Perform Instant Liquidity Unstake - JavaScript Source: https://context7.com/tonstakers/tonstakers-sdk/llms.txt Immediately converts tsTON back to TON by utilizing available pool liquidity, which may involve slippage. The code first checks for available instant liquidity and proceeds with the instant unstake only if sufficient liquidity exists. Otherwise, it falls back to the standard unstake method. ```javascript import { toNano } from "@ton/core"; // Check instant liquidity availability first const instantLiquidity = await tonstakers.getInstantLiquidity(); console.log(`Instant liquidity available: ${instantLiquidity / 1e9} TON`); const amountToUnstake = toNano("2"); if (instantLiquidity >= amountToUnstake) { try { const result = await tonstakers.unstakeInstant(amountToUnstake); console.log("Instant unstake completed!"); console.log("Received TON immediately to your wallet"); } catch (error) { console.error("Instant unstake failed:", error.message); } } else { console.log("Not enough instant liquidity, use regular unstake"); await tonstakers.unstake(amountToUnstake); } ``` -------------------------------- ### Stake MAX TON Button Event Listener Source: https://github.com/tonstakers/tonstakers-sdk/blob/main/demo/index.html Adds an event listener to the 'Stake MAX' button. If a wallet is connected, it calls the stakeMax function of the tonstakers object to stake the maximum available amount. Logs success or error. ```javascript document.getElementById("stakeMax").addEventListener("click", async () => { if (tonstakers) { await tonstakers.stakeMax(); console.log("Staked MAX TON"); } else { console.error("Wallet not connected"); } }); ```