This section contains quickstart guides to help you integrate STON.fi features
Welcome to the STON.fi Quickstart Guides section. These guides provide step-by-step instructions for implementing STON.fi features in your applications with minimal effort.
Each guide is designed to be beginner-friendly and focuses on practical implementation. The guides include complete code examples that you can use as a starting point for your own projects.
Available Guides
Currently, we offer the following quickstart guides:
Swap Guide - Learn how to build a simple token swap interface using React and the STON.fi SDK
What You'll Learn
Our quickstart guides typically cover:
Project setup with the necessary dependencies
Integration with TON wallets using TonConnect
Fetching data from STON.fi API
Executing transactions on the TON blockchain
Building user interfaces for STON.fi features
Prerequisites
While our guides are designed to be accessible, having basic knowledge of the following will be helpful:
JavaScript/TypeScript
React (for frontend guides)
Basic understanding of blockchain concepts
Additional Resources
After completing these quickstart guides, you may want to explore more detailed documentation:
API References - For direct interaction with smart contracts
Feedback
We're constantly working to improve our documentation. If you have suggestions or encounter any issues with these guides, please contact us.
Swap Guide
This guide will walk you through creating a basic token swap app using the STON.fi SDK and API in a React project. We'll integrate wallet connectivity with TonConnect (via @tonconnect/ui-react) to allow users to connect their TON wallet and perform a swap. The guide is beginner-friendly and assumes minimal React experience.
Note: In this demo, we will leverage Tailwind CSS for styling instead of using custom CSS. The setup for Tailwind CSS is already included in the instructions below, so you don't need to set it up separately.
Note: You can use any package manager (npm, yarn, pnpm, or bun) to set up your React project. In this tutorial, we'll demonstrate with pnpm.
In this quickstart, we will build a minimal React app to:
Connect to a TON wallet (via TonConnect UI).
Fetch available tokens from STON.fi (via @ston-fi/api).
Simulate a swap (to see expected output).
Execute a swap transaction on-chain (via @ston-fi/sdk).
We will use:
@ston-fi/sdk – Helps build the payload for the actual swap transaction.
@ston-fi/api – Lets us fetch asset lists, pool data, and run swap simulations.
@tonconnect/ui-react – Provides a React-based TON wallet connect button and utilities.
2. Setting Up the Project
2.1 Create a React App
First, let's check if pnpm is installed on your system:
pnpm --version
If you see a version number (like 10.4.0), pnpm is installed. If you get an error, you'll need to install pnpm first:
npm install -g pnpm
Now we'll create a new React project using Vite. However, you can use any React setup you prefer (Next.js, CRA, etc.).
Run the following command to create a new Vite-based React project:
pnpm create vite --template react
When prompted, type your desired project name (e.g., stonfi-swap-app):
Project name: » stonfi-swap-app
Then enter the folder:
cd stonfi-swap-app
2.2 Adjust Dependencies for React 18
Latest version of @tonconnect/ui-react have compatibility issues with React 19 (or higher). To ensure compatibility, we will pin React dependencies to React 18.
Open your package.json and replace the default dependencies with:
After making these changes, you can verify that your app still runs correctly by starting the development server:
pnpm install
pnpm dev
This should launch your app in development mode, typically at http://localhost:5173. Make sure everything loads without errors before proceeding to the next step.
2.3 Installing the Required Packages
Within your new React project directory, install the STON.fi packages, TonConnect UI, and the TON SDK:
Additionally, install the Node.js polyfills plugin for Vite, which is necessary to provide Buffer and other Node.js APIs in the browser environment (required by TON libraries):
pnpm add vite-plugin-node-polyfills
Configure the Vite plugin by updating vite.config.js file:
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
import tailwindcss from '@tailwindcss/vite'
import { nodePolyfills } from 'vite-plugin-node-polyfills'
// https://vite.dev/config/
export default defineConfig({
plugins: [react(), tailwindcss(), nodePolyfills()],
})
Then, import Tailwind CSS in your main CSS file. Open src/index.css and replace all code with:
@import "tailwindcss";
You can also remove src/App.css we don't need it anymore
3. Connecting the Wallet
3.1 Add the TonConnect Provider
Open src/main.jsx (Vite's default entry point) and wrap your application with the TonConnectUIProvider. This provider makes the TonConnect context available to your app for wallet connectivity. Also, point it to a manifest file (which we will create next) that describes your app to wallets.
// src/main.jsx
import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client'
import { TonConnectUIProvider } from '@tonconnect/ui-react';
import './index.css'
import App from './App.jsx'
createRoot(document.getElementById('root')).render(
<StrictMode>
<TonConnectUIProvider manifestUrl={`${window.location.origin}/tonconnect-manifest.json`}>
<App />
</TonConnectUIProvider>
</StrictMode>,
)
This wraps the <App /> component with TonConnectUIProvider. The manifestUrl points to a tonconnect-manifest.json file that should be served at the root of your app (we'll create this below). Using window.location.origin ensures it picks the correct host (e.g., http://localhost:5173/tonconnect-manifest.json in development).
3.2 Create the TonConnect Manifest
In the public folder of your project, create a file named tonconnect-manifest.json. This manifest provides wallet apps with information about your application (like name and icon). Add the following JSON content:
url should be the base URL where your app is served (for development, http://localhost:5173 is fine; update this to your production URL when deploying).
name is a display name for your app (wallets will show this to the user).
iconUrl is a link to a 180×180 PNG icon for your app. You can use any accessible image URL or add an image to your public folder and reference it. (In the example above, we use a TON logo URL for simplicity.)
Make sure this file is accessible. When the dev server runs, you should be able to fetch it in your browser at http://localhost:5173/tonconnect-manifest.json.
3.3 Add the Connect Wallet Button
In your main App component (e.g., src/App.jsx), import and include the TonConnectButton. For example:
This will render a "Connect Wallet" button. When clicked, it opens a modal with available TON wallets. After the user connects, the button will automatically display the wallet address or account info. TonConnect UI handles the connection state for you.
4. Fetching Available Assets
Next, let's retrieve the list of tokens (assets) that can be swapped on STON.fi. We use the STON.fi API client (@ston-fi/api) for this.
Initialize the API client: In the component where you will handle swapping (we can continue working in App.jsx for simplicity), create a client instance from StonApiClient. This has methods to get assets, pools, simulate swaps, etc.
Fetch assets on load: Using React's effect hook, fetch the asset list when the component mounts. Store the assets in state so you can display them.
"Simulate" and "Swap" buttons (not functional yet).
5. Simulating a Swap
Before executing a swap transaction, it's good practice to simulate it. Simulation tells us how much of the target token we should receive given an input amount, factoring in liquidity and slippage. We'll use the simulateSwap function from StonApiClient.
// Step #5 changes in App.jsx
// keep all imports from step #4
function App() {
// keep existing state from step #4 and add simulationResult state
const [simulationResult, setSimulationResult] = useState(null);
// update handleChange from step #4 to reset simulationResult when changing inputs
const handleChange = (setter) => (e) => {
// keep existing code from step #4
setSimulationResult(null);
};
// add the handleSimulate function
const handleSimulate = async () => {
if (!fromAsset || !toAsset || !amount) return;
try {
const { decimals: fromDecimals } = getAssetInfo(fromAsset);
const client = new StonApiClient();
const result = await client.simulateSwap({
offerAddress: fromAsset.contractAddress,
askAddress: toAsset.contractAddress,
slippageTolerance: '0.01',
offerUnits: BigInt(Math.floor(Number(amount) * fromDecimals)).toString(),
});
setSimulationResult(result);
} catch (err) {
console.error('Simulation failed:', err);
setSimulationResult(null);
}
};
return (
// keep the same JSX wrapper from step #4
<div className="flex flex-col items-center justify-center min-h-screen bg-gradient-to-b from-blue-50 to-indigo-100 p-6">
{/* ... existing code from step #4 ... */}
{/* Update the Simulate button to attach handler */}
<button
onClick={handleSimulate}
className="flex-1 bg-indigo-100 hover:bg-indigo-200 text-indigo-700 font-medium py-3 px-4 rounded-lg transition-all"
>
Simulate
</button>
{/* ... existing code from step #4 ... */}
{/* Show simulation result if present */}
{/* add simulation result */}
{simulationResult && (
<div className="mt-4 w-full max-w-md bg-white rounded-xl shadow-lg p-4">
<div className="text-center">
<p className="text-lg font-medium text-gray-800">Swap Summary</p>
<div className="flex justify-center items-center space-x-2 mt-2">
<p className="text-md font-bold">
{amount} {displaySymbol(fromAsset)}
</p>
<span className="text-gray-500">→</span>
<p className="text-md font-bold">
{(Number(simulationResult.minAskUnits) / getAssetInfo(toAsset).decimals).toFixed(
getAssetInfo(toAsset).decimals === 1e9 ? 4 : 2
)}{' '}
{displaySymbol(toAsset)}
</p>
</div>
</div>
</div>
)}
<div className="mt-6 text-center text-xs text-gray-500">
Powered by STON.fi
</div>
</div>
);
}
export default App;
That's it for simulation. Now if you:
Select "From" and "To" tokens
Enter an amount
Click "Simulate"
…you should see an expected output.
6. Executing a Swap Transaction
Finally, let's make the Swap button actually send a transaction. We'll use the @ston-fi/sdk to build the swap parameters and pass them to the wallet via TonConnect.
We just add one more handler, handleSwap, and wire it to the Swap button. We'll also import everything needed from @ston-fi/sdk, plus the TonConnect UI hook to send transactions.
In App.jsx, near the top:
// Step #6 changes
// add extra imports:
import { dexFactory, Client } from "@ston-fi/sdk";
import { TonConnectButton, useTonConnectUI, useTonAddress } from '@tonconnect/ui-react';
Inside the App component, after handleSimulate, add:
Finally, attach this new handler to the Swap button:
// in the render, near the Simulate button
<button
className="flex-1 bg-indigo-600 hover:bg-indigo-700 text-white font-medium py-3 px-4 rounded-lg transition-all"
onClick={handleSwap}
>
Swap
</button>
Everything else stays the same as in Step #5.
7. Testing Your Swap
Now that your app is running, you can test the swap functionality:
Connect your wallet by clicking the "Connect Wallet" button and selecting your TON wallet from the modal.
Select tokens from the dropdown menus:
Choose a token you own in the "From" dropdown
Select a token you want to receive in the "To" dropdown
Enter an amount you wish to swap (make sure it's an amount you actually have in your wallet).
Simulate the swap by clicking the "Simulate" button to see the expected output amount before committing to the transaction.
Execute the swap by clicking the "Swap" button. This will prompt your wallet to approve the transaction.
Confirm in your wallet when the approval request appears.
Upon successful completion, the transaction will be processed on-chain, and your wallet balances will update accordingly. The whole process typically takes just a few seconds to complete.
8. Conclusion
You now have a React + Vite app with Tailwind CSS that:
Connects to a TON wallet using TonConnect.
Fetches available tokens from STON.fi.
Simulates swaps (via simulateSwap).
Builds and sends swap transactions (via @ston-fi/sdk).
Feel free to expand this demo with:
Improved decimal handling for each token.
Custom slippage tolerance settings.
More robust error/success messages.
Happy building on TON and STON.fi!
9. Live Demo
With this Replit demo, you can:
Open the project directly in your browser
Fork the Replit to make your own copy
Run the application to see it in action
Explore and modify the code to learn how it works
Experiment with different features and UI changes
10. Advanced Example App
For those seeking a feature-rich, more advanced approach, we also have a Next.js Demo App that:
Uses Next.js for a scalable framework
Utilizes hooks and providers for an elegant architecture
Demonstrates better error handling, robust state management, and additional STON.fi features