# Ambassador Program Source: https://docs.swap.coffee/eng/ambassador-guides/welcome How to become an ambassador of swap.coffee, perform tasks, create content, and receive rewards. # Complete Guide to the swap.coffee Ambassador Program Welcome to the ambassador program of **swap.coffee**! In this guide, you will find all the necessary information about how to become an ambassador, what tasks to perform, how to create effective content, and how to receive rewards. ## What is swap.coffee? **swap.coffee** is a liquidity aggregator operating on the **TON blockchain**, which allows users to exchange cryptocurrency absolutely **without additional fees** and guarantees the **best price on the market**. The platform is constantly evolving, capturing new market segments and regularly updating with innovative tools and features. The main goal of swap.coffee is to build a comprehensive ecosystem where our users can solve any tasks within a single platform without turning to other services. ## Who is a swap.coffee ambassador? A swap.coffee ambassador is an enthusiast who actively contributes to the promotion and development of the platform. The main tasks of the ambassador include: * Content creation: posting materials about swap.coffee on social networks, blogs, video platforms, and forums. * Community engagement: answering user questions, helping newcomers, participating in discussions. ## How to become an ambassador? To join the ambassador program of swap.coffee, follow these steps: 1. Go to the [swap.coffee app](https://t.me/swapcoffee): Send the command /start and click the Ambassador button — you will access your personal dashboard. 2. Create content: Publish materials about swap.coffee on social media or other platforms. This can include posts, stories, articles, videos, etc. 3. Submit your content for review: After publishing, send a link to your content through the [swap.coffee app](https://t.me/swapcoffee). We will review it and assign you points. 4. Be active in the community: Join the official chats, help other users, and participate in discussions. ## Rewards and Benefits swap.coffee ambassadors receive rewards based on their contribution to the project. The size of the reward depends on the **quality and reach of the created content**, as well as on **community engagement**. Rewards are paid in **CES tokens**. Benefits of participating in the program: * Flexible schedule: You choose when and how much time to dedicate to ambassador activities. * Skill development: An opportunity to improve your content creation, marketing, and communication skills. * Community: Become part of a new active and friendly community. ### How is my reward calculated? At the end of each month, the total number of points you earned from all your content is calculated. Depending on the number of points you accumulated during the month, you receive a corresponding portion of the total reward pool. The higher your total monthly points, the greater your reward. ### When should I submit content for review? You can submit content for review **at any convenient time** via our [swap.coffee app](https://t.me/swapcoffee). ### When are rewards paid out? To receive rewards, you need to link your wallet **once** through the [swap.coffee app](https://t.me/swapcoffee) menu. After linking your wallet, all rewards will be automatically credited to your wallet via the **Claim Center**. You can change the linked wallet at any time via the menu. ## Useful Links * Official website: [swap.coffee](https://swap.coffee/) * swap.coffee APP: [t.me/swapcoffee](https://t.me/swapcoffee) * Documentation: [docs.swap.coffee](https://docs.swap.coffee/) * Brandbook: [swap.coffee Brandbook](https://www.figma.com/design/Hy5f6zwcsvvbgfm7PmhOsN/swap.coffee-guideline?node-id=0-1\&p=f\&t=56PifdcRtSgBjzis-0) ### Social networks and channels: * Telegram channel (RU): [t.me/swapcoffee\_ru](https://t.me/swapcoffee_ru) * Telegram channel (EN): [t.me/swapcoffee](https://t.me/swapcoffee) * VK community: [vk.com/swapcoffee](http://vk.com/swapcoffee) * Instagram: [instagram.com/swap\_coffee\_ton](https://instagram.com/swap_coffee_ton) * YouTube channel: [youtube.com/@swap.coffee](https://youtube.com/@swap.coffee) * TikTok: [tiktok.com/@swap\_coffee\_ton](https://www.tiktok.com/@swap_coffee_ton) ### Additional: * Emojis: [swap.coffee Emoji](https://t.me/addemoji/swap_coffee_emoji) * Sticker pack: [swap.coffee Stickers](https://t.me/addstickers/swap_coffee_animated) ## Content Creation Guidelines To effectively promote swap.coffee, it is recommended to use various platforms and content formats: * Social media: Twitter, Facebook, Instagram. Post news, updates, infographics, and short videos. * Video platforms: YouTube, TikTok. Create platform reviews, how-to guides, share personal experiences. * Blogs and forums: Medium, Reddit. Write articles, tutorials, join discussions, and respond to user questions. * Crypto communities: CoinMarketCap Community, Binance Square. Publish analytics, share news, and actively discuss the benefits and updates of swap.coffee with the broader crypto community. ### How is content evaluated? Each of your submissions is evaluated by the swap.coffee team on a 10-point scale at the time of review. The evaluation is based on quality, usefulness, presentation, originality, and overall impression of the content. Since view count affects your final reward, we recommend submitting content **a few days after publishing** — this allows your content to gain views and increase your reward. ## Frequently Asked Questions (FAQ) 1. **Do I need to have extensive experience in social media to become an ambassador?**\ No, experience is not required. The main thing is your willingness to learn, create content, and support the community. 2. **In what language should I create content?**\ You can create content in any language. However, publishing in English helps reach a broader audience. 3. **How often should I submit reports?**\ Reports can be submitted anytime you wish. 4. **What are the criteria for content evaluation?**\ Evaluation is based on quality, originality, audience reach, and engagement. 5. **Can I refer other ambassadors?**\ Yes, you can invite others to the program. For each referred ambassador, you may receive additional rewards. ## General Tips for All Video Platforms Regardless of the platform, remember: you're working within recommendation systems. Algorithms determine whether someone will see your content. To increase your reach: * Post daily or as regularly as possible — social networks reward consistency. * Introduce content series: reviews, news, debates, hacks, personal experience, analytics. * Repurpose content across all platforms. There are tools for automatic cross-platform posting — use them. * Grow as a media personality: follow successful channels, adopt best practices, and ensure high content quality. * Treat your growth like a real job — pay attention to details, analytics, engagement, and audience response. Remember: without persistence and consistent work, success won't come. Be disciplined and don’t quit after the first challenge — and you will see results. * Record detailed video reviews of the platform and highlight its unique features: no fees, high speed, intuitive UI, and the best market prices. Post educational guides regularly, from basic tools to advanced features. * Use hooks and clickbait-style titles — they help boost views. * The first 5–10 seconds of the video are crucial to capture viewer attention. Start strong: bold visuals, intriguing questions, or a teaser of what’s coming. Avoid long intros — viewers might leave before the content starts. * It's not just about attracting viewers, but also retaining their attention. YouTube considers this in its algorithms, so check YouTube Analytics regularly (e.g., average watch time and retention rate). Analyze where viewers drop off and improve based on that. Adjust video length, editing, and delivery to keep viewers watching longer. * Thumbnails are your storefront. Make them eye-catching with bold, readable fonts. Don’t place text in the bottom-right corner — it may get covered by the YouTube timestamp. Experiment with different thumbnails — YouTube allows changing them after publication. Track which designs perform best. Pro tip: analyze what works for top crypto creators and adapt it for your own style. * Ensure high video quality and clean audio — this builds trust. Use AI tools like Adobe Enhance Speech or alternatives to polish audio. You can also use Audacity or Adobe Audition to adjust volume, reduce noise, and balance levels. Clean, professional audio improves viewer experience and boosts full-watch probability. * In descriptions, include timestamps, useful links, and calls-to-action (visit the website, join the community, etc.). Add in-depth analysis and insights about the platform. While tags no longer play a huge role, it’s still good practice to include them. Focus on titles, thumbnails, and strong hooks. Cut your long videos into multiple short clips and post them across all social platforms. This format helps reach a new audience and adapt content to Reels, Shorts, and TikTok. If you don’t want to create full-length videos — focus on vertical formats. The rules stay the same: engaging hook, dynamic editing, clear sound, and a strong topic. # Cashback Source: https://docs.swap.coffee/eng/user-guides/cashback **Reward Program** for your activity on the platform. Like traditional banking, but fully decentralized. *** ### 🚀 How Does It Work? 1. You make a swap on **swap.coffee**. 2. The system automatically calculates the cashback amount. 3. You receive cashback in **tokens** from our partners. 4. Accumulated cashback can be claimed at any time. *** ## 🔍 More About Cashback ### 🪙 What is Cashback? **Cashback** is a partial return of funds after completing a transaction.\ On **swap.coffee**, cashback is paid in **tokens from our partners**. *** ### 📊 What Determines the Cashback Amount? The cashback amount directly depends on the **volume of your transactions**. > The more you swap, the greater the rewards you receive! *** ### 🏆 What Tokens Can Be Earned as Cashback? Our partners provide their tokens to be distributed among active users. > 📜 **Important**: The list of available tokens may change. *** ### 📄 Where Can I View Cashback Conditions? All terms and limits for cashback are available on a dedicated page:\ 👉 [**Active Cashback Offers**](https://swap.coffee/cashback) *** ### 💼 How to Claim Accumulated Cashback? You can claim your reward at any convenient time via:\ 👉 [**Claim Center**](https://swap.coffee/claim) *** ### ⏳ Do I Need to Claim Cashback Immediately? No, it’s **not mandatory**.\ You decide whether to accumulate cashback or claim it right after earning it. *** ## 🔥 Why is Cashback Beneficial? **Cashback on swap.coffee** is an excellent way to gain **additional benefits** from your swaps. > **Start using the platform today** and enjoy the perks! 🚀 # Claim Center Source: https://docs.swap.coffee/eng/user-guides/claiming Welcome to the **Claim Center** — your personal hub for managing rewards on **swap.coffee**. We designed it to make the reward collection process as simple and enjoyable as possible. 🚀 *** ## ❓ What is the Claim Center? The **Claim Center** is your personal section on **swap.coffee**, where you can manage all your earned rewards. ### Here you will find: * 💰 **Cashback for swaps**. * 👥 **Referral bonuses**. * 🏆 **Prizes for participating in Trading Competitions**. * 🔒 **Staking rewards**. *** ## 🛠️ How to Use the Claim Center? We made the process as convenient as possible: 1. 🔗 Go to the [Claim Center](https://swap.coffee/claim). 2. 🔒 Connect your wallet to the platform. 3. 🪙 **Select Rewards**: * Click **"Select All"** for quick selection of all rewards. * Or choose specific tokens based on your preferences. 4. ✅ Click **"Claim All"** — and your rewards are on their way to you. 5. 📲 Confirm the transaction in your wallet. 6. 🎉 Once confirmed, enjoy your rewards! > **Important**: > We value your time and money. **swap.coffee** does not charge any additional fees for claiming rewards. > You only pay the standard network fee. *** ## ⏳ How Long Does It Take? We have optimized the reward claiming process: ⏱️ Typically, it takes just **2-3 minutes**. > However, the time may vary depending on blockchain congestion. We do everything possible to expedite the process. *** ## 🏁 Final Word The **Claim Center** on **swap.coffee** is your tool for maximizing your benefits. Use it regularly and enjoy every token you earn! 🎉 # Trading Competitions Source: https://docs.swap.coffee/eng/user-guides/contests Welcome to the thrilling world of **swap.coffee** Trading Competitions! *** ## 🌟 Turn Your Swaps into Wins Here, every transaction is a step towards success, and your activity can bring not only profits but also **valuable prizes**. *** ## 🎯 Effortless Participation * ✅ **No separate registration** — just trade. * 🤖 **Automatic participation** in all ongoing competitions. * 🔄 Every swap on **swap.coffee** is your chance to win. *** ## 🔍 Explore Opportunities Follow the link [swap.coffee/contests](https://swap.coffee/contests) — your gateway to the world of trading contests, where you will find: * 🏅 **Current competitions** with attractive prizes. * 📋 **Detailed information** about rewards. * 📈 **Leaderboards** updated in real time. *** ## 🤝 Fair Play for Everyone We value **transparency** and equal opportunities: * All competition rules and details are available in the **FAQ / Competition Rules** section. * Every participant has an **equal chance** to succeed. *** ## 🚀 Ready to Become a Champion? Start trading now and turn every swap into a step towards victory! May **luck** be with you in every transaction! 💪 # DCA (Dollar-Cost Averaging) Source: https://docs.swap.coffee/eng/user-guides/dca **📈 Mindful Investments Anytime** Investing is an art of balance. DCA (Dollar-Cost Averaging) allows you to automatically buy or sell assets within predefined ranges, reducing the risks associated with market fluctuations. On swap.coffee, you set a price range within which the system will execute orders at a predetermined frequency. ## 🚀 How Does It Work? 1. **Choose an asset** — for example, CES. 2. **Define a price range** — for instance, TON $2.00 – $2.50. 3. **Set the frequency of trades** — for example, every day at 12:00 UTC. 4. swap.coffee automatically executes trades, even when you're offline. ## 🔍 Additional DCA Settings ### 📌 Maximum Number of Executions This parameter determines how many times the system can execute an order before the strategy is terminated. * **1 execution** — the order is executed once and then turned off. * **10 executions** — the system repeats the purchase up to 10 times, after which the strategy is terminated. **Example:** If you want to buy CES every 12 hours, but only 5 times, you set the maximum number of executions to 5. After the fifth trade, the system will automatically stop executing. ### 📌 Order Splitting Multiplier This parameter splits the trade into several parts to optimize the price and reduce market impact. * **Multiplier 1** — the order is executed as one large lot. * **Multiplier 3** — the trade is divided into 3 parts, each executed separately. * **Multiplier 5** — the purchase/sale is divided into 5 parts and executed over the specified interval. **Example:** If you want to buy 100 CES but don't want a single large order to affect the market, setting the multiplier to 5 will split the order into 5 parts of 20 CES each. As a result, the price will be averaged and the purchase will be less noticeable in the market. ## 🛡 Security and Decentralization * ✔️ DCA is fully automated — you don't need to manually execute trades. * ✔️ Smart contracts are used, ensuring maximum transparency. ## 🔥 DCA is a strategy for those who want to invest without stress and with maximum efficiency. # Limit Orders Source: https://docs.swap.coffee/eng/user-guides/limit **📊 Automatic trades under your conditions** Limit orders allow you to set in advance the price at which you want to buy or sell an asset. Forget constant market monitoring — swap.coffee will execute the trade automatically as soon as the price reaches the set level. ## 🚀 How do limit orders work? 1. **Choose an asset** — for example, CES. 2. **Set the price at which you want to buy or sell** — for instance, TON at \$2.30. 3. **Create a limit order.** 4. As soon as the price reaches the required level, swap.coffee automatically executes the order. You control every trade and are not at the mercy of chance. ## 🔍 Additional Limit Order Settings ### 📌 Maximum Number of Executions Determines how many times the system can repeat the order if the price is not reached. * **1 execution** — the order is triggered once. * **10 executions** — the system repeats the order up to 10 times if the price is not reached. **Example:** You place a limit order to sell CES at \$1.50 but do not want to sell the entire amount immediately. If you set the maximum number of executions to 5, swap.coffee will attempt to sell CES at that price 5 times before terminating the order. ### 📌 Sub-Order Multiplier Splits the order into several parts, reducing its impact on the price. * **Multiplier 1** — the order is executed as one whole lot. * **Multiplier 3** — the order is split into 3 parts, each executed separately. * **Multiplier 5** — the trade is divided into 5 parts, reducing market load. **Example:** You want to sell 10,000 CES, but you do not want to provoke a price drop. With a multiplier of 4, swap.coffee will split the sale into 4 orders of 2,500 CES, minimizing the market impact. ## 🛡 Security and Decentralization * ✔️ Orders are executed via smart contracts, without intermediaries. * ✔️ Full transparency of order execution on the blockchain. ## 🔥 Limit orders are a smart way to trade without constantly monitoring the market. ## 🎯 When to Use DCA and Limit Orders? | Situation | DCA | Limit Orders | | ---------------------------------------------------- | :-: | :----------: | | You want to accumulate CES or TON gradually | ✅ | ❌ | | You want to set an exact price for buying or selling | ❌ | ✅ | | You do not want to constantly monitor charts | ✅ | ✅ | | You fear strong price fluctuations | ✅ | ❌ | | You want to trade without active involvement | ✅ | ✅ | # The Most Profitable Swaps Source: https://docs.swap.coffee/eng/user-guides/profit Welcome to the world of **trades** on **swap.coffee**, where every swap - profitable. *** ## 🌟 Elegance in Every Transaction Discover **swap.coffee** — a DEX aggregator that reimagines the crypto swapping process. Our platform is a **symphony of technology**, where every transaction becomes a masterpiece of efficiency. *** ## ⚡ Intuitive Power **swap.coffee** is a tool that helps you make optimal decisions. We analyze multiple DEXs in real-time to find the perfect swap route for you. > It’s like a personal **navigator in the crypto world**, always knowing the fastest and most profitable path. *** ## 🚀 Innovative Swap Strategies Our platform uses **two key strategies** to maximize your benefit: * **💡 Split Transactions**\ We distribute your swap across multiple DEXs, minimizing price impact and maximizing the tokens you receive. * **🔗 Multi-Hop Routes**\ Tokens pass through optimal intermediate pairs before reaching their final destination, ensuring the most favorable swap. *** ## ✨ Example of swap.coffee Magic Suppose you want to swap **100 $TON for $BOLT**. Instead of a simple direct swap, **swap.coffee** creates an elegant route: * 🔹 **57.76%** goes through `TON > USDT > KINGY > BOLT` * 🔹 **22.43%** swaps directly as `TON > BOLT` * 🔹 **11.33%** follows the path `TON > USDT > BOLT` * 🔹 **8.48%** goes through `TON > SCALE > BOLT` > **Complicated?** The beauty is, you don’t have to worry about it. > We turn complexity into simplicity, delivering the best result with just one click. *** ## 🎁 More Than Just a Swap **swap.coffee** offers not only efficient swaps but also **additional benefits**: * 💵 **Cashback**\ Earn rewards for every transaction. * 🏆 **Trading Competitions**\ Participate in contests and win prizes. *** With **swap.coffee**, every transaction is a step towards more efficient management of your crypto assets. Welcome to the world of modern decentralized swaps! # Referral Program Source: https://docs.swap.coffee/eng/user-guides/referral Welcome to the world of earning opportunities with the **swap.coffee** Referral Program! Discover how to turn your activity into real benefits. *** ## 🚀 Invite and Earn Use your unique link to invite friends to the **swap.coffee** ecosystem. * 💸 **Benefit**: With every transaction your friends make, you receive a share of the fee. * 📈 **More friends** = **higher earnings**. It’s simple, transparent, and profitable! *** ## 🛠️ How to Start Using the Referral System? 1. Go to [swap.coffee/referral](https://swap.coffee/referral). 2. **Connect your wallet**. 3. Find the button **"Get Referral Link"** or QR code. 4. Send the link or QR code to your friend. 5. When your friend clicks the link and connects their wallet, they automatically become your referral. > 💡 **Tip**: The sooner you start sharing the link, the sooner you start earning! *** ## 🏆 Referral System Levels Each level opens new horizons of opportunity: * 🥉 **Bronze** * 🥈 **Silver** * 🥇 **Gold** With each level upgrade, your reward percentage increases. *** ## 🔒 Reliability and Transparency * 🔍 **Control**: Track your progress and income in real-time through your personal account. * 🛡️ **Transparency**: Every swap made by your referral is logged in your personal referral dashboard. *** ## ⚖️ Fairness is Our Priority At **swap.coffee**, we believe in fair partnerships: * 💼 **No hidden fees**: We share our profits with you. * 🤝 **Mutual benefit**: No additional commissions. *** ## 🌟 Special Privileges If you are an influencer or an active community member, **exclusive conditions** are available for you: * Contact our **Community Manager** to unlock the full potential of your participation. *** > **Important**: Participants who have already used **swap.coffee** cannot be invited as referrals. *** ## ✨ Start Right Now! Don’t miss your chance! Become part of an innovative referral program today and start your journey towards financial success with **swap.coffee**. # Expert Settings Source: https://docs.swap.coffee/eng/user-guides/settings Welcome to the **⚙️ Expert Settings** section of **swap.coffee**, where powerful tools are available for **optimizing your swaps**. These features give you full control over the process and help you achieve the best results. *** ## 🎯 Fine-Tune Your Swaps The expert settings include the following key parameters: ### 📉 Slippage Tolerance * **What is it?**: Sets the range of acceptable price changes. * **Why is it needed?**: If the price moves beyond the set range, the **transaction is automatically canceled** to protect your funds. *** ### ⚡ Price Impact Control * **Market Control**: Manage how much your swap can impact the market price. * **Result**: Reduces the risk of unwanted price fluctuations. *** ### 🔀 Intermediate Tokens * **Route Settings**: Specify the maximum number of intermediate tokens. * **Important to Know**: More intermediate tokens can: * Increase gas costs. * Raise the risk of receiving an unwanted intermediate token. *** ### 📊 Pool Volatility * **Risk Mitigation**: Exclude routes through pools with high volatility. * **Why is this useful?**: It adds stability to your swap. *** ### 🔗 Parallel Transactions * **Scaling**: With a **W5 wallet**, you can create up to **20 parallel transactions** at once. * **Advantage**: Speeds up operations and enhances efficiency. *** ## 🚀 Why is This Important? By using these settings, you can achieve **maximum efficiency** and **precision** in your swaps on **swap.coffee**. > 💡 **Tip**: Experiment with these settings to find the optimal balance for your needs. # Staking Source: https://docs.swap.coffee/eng/user-guides/staking Welcome to the world of **staking** on **swap.coffee**, where every investment is a step towards the future of cryptocurrency. *** ## 🔍 What is Staking? **Staking** is a modern way of investing, where you commit your funds and earn rewards in return. At **swap.coffee**, we have turned this process into a true art. *** ## 🎯 Your Opportunities on **swap.coffee** * **Staking \$CES**: The perfect choice for those who value stability. * **Staking LP Tokens (CES/TON)**: Enhanced returns with a **x2.5 multiplier** for maximum benefit. *** ## 🔐 Flexibility and Security * When you deposit, you choose **one of three staking durations**. The longer the duration, the higher your point multiplier. * Your assets are always safe in a smart contract that only you have access to. *** ## 💎 Points: Your Key to Rewards **Points** are a universal measure of your contribution: * The larger your share of the total points pool, the more rewards you receive. * This ensures a fair and transparent distribution of rewards. *** ## 🏆 Variety and Simplicity in Receiving Rewards Our **stakers** receive generous rewards in various tokens. ### ✨ How to Claim Rewards? All earned funds are available in our [Claim Center](https://swap.coffee/claim): * Choose when to claim your rewards. * Accumulate them or withdraw immediately after earning. *** ## 💡 Staking with **swap.coffee** Staking on **swap.coffee** is not just an investment; it is your step towards the **future of decentralized finance**. Join us and be part of the cryptocurrency revolution! # How to Swap? Source: https://docs.swap.coffee/eng/user-guides/swap ## 🚀 1. Connect Your Wallet To get started, you need to connect your wallet to the platform. It’s very simple: 1. Click the **"Connect Wallet"** button at the top right corner of the screen. 2. In the pop-up window, confirm the connection through your wallet. *** ## 💱 2. Select a Token to Swap Once your wallet is successfully connected, you can select a token to swap: 1. Click the **"Select Token"** button. 2. In the list that appears, find the token you need (for convenience, use the search bar). 3. Click on the selected token. > 💡 **Tip**: If the token you need is not in the list, you can import it manually by providing its **contract address**. *** ## ✏️ 3. Enter the Amount and Confirm the Swap Now that the token is selected: 1. Enter the amount you wish to swap. 2. Carefully check the **swap details**. 3. Click the **"Swap"** button to confirm. > ⚠️ **Important**: A transaction fee in **TON** is required for blockchain transactions. Make sure you have enough funds in your balance to cover it. *** ## ✅ 4. Confirm the Transaction After clicking the **"Swap"** button: * A request will appear in your wallet to confirm the transaction. * Carefully review the details and confirm it. *** ## 🎉 5. Complete the Swap Congratulations! 🎊 Your transaction has been sent to the blockchain. Now, you need to wait a bit: * The system will process your transaction (usually takes **a few minutes**). * After processing, you will see a notification of a **successful swap**. *** Now you know how easy and fast it is to swap tokens on **swap.coffee**. Happy swapping! 🚀 # World of swap.coffee Source: https://docs.swap.coffee/eng/user-guides/welcome Welcome to our comprehensive guide on using **swap.coffee** — an innovative cryptocurrency swap platform. Enjoy! title *** ## 📖 What is This Guide About? Whether you are: * An **experienced trader** — looking to make the most of the platform’s features, * Just starting your journey in the blockchain world of `TON`, this series of guides will be your reliable companion. *** > 💡 **Note**: Follow the steps in this guide to learn how to use the platform with maximum efficiency. # Yield Aggregator Source: https://docs.swap.coffee/eng/user-guides/yield We are excited to introduce a new product from **Swap.Coffee** — **Yield Aggregator**, which helps you invest and earn across the entire **TON** ecosystem without leaving the platform. ## ❓ What is Yield Aggregator? It’s a service for discovering liquidity pools, staking, lending, and other DeFi applications that generate income. We offer extensive functionality for filtering and searching, allowing you to quickly find the best opportunities. Manage protocols through **Swap.Coffee**, where all your positions are consolidated in one place. Forget about manually tracking balances and comparing yields — earn efficiently without leaving the platform. ## 🛠️ How to Use Yield Aggregator? The service consists of two main components: * A list of all pools; * Detailed information about each pool. ### List of All Pools 1. 🔗 Navigate to [Yield Aggregator](https://swap.coffee/earn). 2. 👛 Connect your wallet so we can display detailed information about your funds in the pools. 3. 📑 After connecting your wallet, you’ll have access to two tabs: * A general list of pools; * A list of pools where you have provided liquidity. 4. 🔍 Use the filter and sorting options at the top of the table to display relevant pools: * Select the protocols you’re interested in using the filter icon; * Enter the token name, its address, or the pair address in the **search** field; * Apply **sorting** to find the best pool by yield, liquidity volume, or other parameters; * Use the **boosts** filter to display pools with additional rewards. ### Pool Information 1. 📊 Navigate to the selected pool to view key information, your position, and earnings. 2. ⭐ **Yield Aggregator** displays farming data provided by the protocol. 3. 🚀 Interact with the pool and its boosts. Add liquidity, claim farming rewards: * ✍️ Connect your wallet and fill in the fields; * ✅ Confirm and send the transaction; * ⏳ Wait for the transaction to complete. ## 💡 Benefits of Yield Aggregator * **Convenience**: Manage all your DeFi positions in one place; * **Transparency**: Get full information about yields and positions; * **Flexibility**: Filter and sort pools to find the best opportunities; * **Boosts**: Utilize additional rewards to increase your income. # WhitePaper Source: https://docs.swap.coffee/eng/white-eng Last Updated: 27.11.2024 # Introduction **swap.coffee** is an innovative DEX aggregator and decentralized exchange (DEX) that consolidates liquidity from both decentralized exchanges and liquidity pools, enabling users to swap cryptocurrencies under the best possible conditions. The platform leverages cutting-edge technology to ensure secure and profitable transactions, providing users with access to a wide range of opportunities without the need for centralized intermediaries. On the modern cryptocurrency market, liquidity is often spread across various decentralized exchanges and liquidity pools, making it difficult for users to find the best prices for asset swaps. **swap.coffee** solves this problem by offering aggregated liquidity, which helps users get the most optimal conditions for each transaction. Our advanced routing algorithm and transaction splitting not only automatically break down large transactions into smaller parts, minimizing gas costs, but also build routes using intermediate liquidity pools, ensuring the best rates for users. The platform also introduces additional features, such as limit orders, allowing users to set specific price levels for executing trades, and an integrated RFQ protocol that sources liquidity from centralized exchanges (CEX). This allows users to significantly save on gas and achieve better exchange rates compared to other platforms. Additionally, **swap.coffee** supports DCA (Dollar Cost Averaging) and VA (Value Averaging) strategies, providing users with tools for automated investment management and minimizing risks associated with cryptocurrency market volatility. The platform does not charge additional fees, making it one of the most cost-effective options for traders of all levels. **swap.coffee** strives to become the leading decentralized cryptocurrency exchange solution, providing users with a convenient, secure, and cost-effective way to manage their digital assets. # Mission The mission of **swap.coffee** is to create a universal decentralized platform for cryptocurrency trading that ensures security, transparency, and accessibility for all users. Our approach is particularly relevant in the context of the growing TON blockchain ecosystem, which is in the active development and expansion phase. The TON blockchain offers tremendous growth and innovation potential, but like any emerging technology, it faces challenges such as low liquidity, limited trading opportunities, and the need to build infrastructure for active cryptocurrency usage. **swap.coffee** seeks to address these issues by providing powerful tools for asset swaps and investment management, which will become the foundation for trading on the TON network. We are actively working on creating and developing APIs for interacting with the TON blockchain in the trading space. This allows developers and projects to easily integrate our platform's features, providing access to liquidity and asset exchange tools. In this way, we are laying the groundwork for a full-fledged trading ecosystem, which is crucial for the further growth and attraction of new users to the TON network. **swap.coffee** sees its role as one of the pioneers in decentralized finance (DeFi) development on the TON blockchain. Our platform aggregates liquidity from various decentralized exchanges and liquidity pools, providing users with access to the best exchange conditions. This is especially important in a young and growing ecosystem, where liquidity is critical for growth and attracting new participants. Our mission is not just to create a platform for asset swaps, but to drive the development of the TON ecosystem by attracting new users, creating trading tools, and providing full integration infrastructure with the TON blockchain through our APIs. # Market Overview ## Development of DEX and DEX Aggregators ### Decentralized Exchanges (DEX) In recent years, decentralized exchanges (DEX) have become a crucial part of the cryptocurrency ecosystem, offering users the ability to trade assets directly with each other without the need for centralized intermediaries. This ensures a higher level of security and asset control, which is especially important in the context of growing concerns over privacy and cyber threats. According to Messari, the trading volume on DEX in 2022 exceeded \$1 trillion, representing a significant growth compared to previous years. This growth was driven by several factors, including the migration of users to decentralized solutions after numerous hacking incidents on centralized exchanges and increasing regulation by governments. DEX platforms offer users transparent trading conditions, where everyone can control their funds through smart contracts, eliminating the need to trust a third party. Platforms like Uniswap and SushiSwap have demonstrated that decentralized trading can be both efficient and competitive in terms of liquidity and execution speed. ### DEX Aggregators With the increasing number of decentralized exchanges, the need for aggregators emerged, allowing users to access the best trading conditions by collecting liquidity from different DEXs. DEX aggregators such as 1inch and Paraswap provide users with the opportunity to get the best prices, minimizing price differences between exchanges and reducing overall transaction costs. According to Dune Analytics, DEX aggregators play a key role in increasing trading volumes and liquidity in the market. In 2023, more than 25% of all DEX transactions were routed through aggregators, highlighting the importance of these platforms for users seeking to optimize their trading operations. Aggregators use advanced routing algorithms that automatically find the best routes for swaps, often breaking transactions into smaller parts and distributing them across different liquidity pools. This not only helps users save on gas fees but also ensures the best exchange rates, making aggregators highly sought after by professional traders and retail investors alike. ### On-Chain Limit Orders and Trading Strategies On-chain limit orders have become an integral part of decentralized finance (DeFi), offering users powerful tools for more precise control over their trades. Limit orders allow traders to place transactions at predefined prices, enabling them to trade assets only at the optimal price and avoid potential losses due to unwanted price fluctuations. According to Binance Research, limit orders are becoming increasingly popular among professional traders who want to use precise price markers to minimize risks. Studies show that traders using limit orders achieve 20% better results compared to those who trade exclusively with market orders, especially in volatile conditions. Furthermore, limit orders based on smart contracts provide full transparency and trust between participants, eliminating the need for centralized intermediaries. This has become especially important amid the growing interest in DeFi and decentralized trading, where users strive to maintain full control over their assets. Within DEX aggregators such as **swap.coffee**, the implementation of on-chain limit orders with RFQ protocols, which source liquidity from centralized exchanges (CEX), allows users not only to get favorable rates but also to save on gas costs. According to CryptoCompare, such protocols can reduce overall transaction costs by 15-25%, making them particularly useful for large transactions. ### DCA and VA Trading Strategies In addition to limit orders, popular trading strategies such as DCA (Dollar Cost Averaging) and VA (Value Averaging) remain prevalent among cryptocurrency traders. These strategies are especially relevant for long-term investors who aim to minimize risk through regular purchases or adjusting investment volumes based on market conditions. According to Arcane Research, over 60% of cryptocurrency investors use DCA strategies to reduce volatility. In unstable markets, DCA helps average the purchase price, lowering the risk of buying an asset at its peak value. For experienced traders, the VA strategy, which focuses on achieving a target portfolio value, can yield 10-15% more profit in the long run compared to traditional methods. The use of DCA and VA strategies on **swap.coffee** provides users with flexibility in managing their investments and helps effectively minimize risks and maximize returns in volatile cryptocurrency markets. # Target Audience **swap.coffee** is designed with the needs of different user categories in mind, including beginner crypto investors, large traders (whales), developers, influencers, and crypto projects. Our platform offers unique tools and opportunities for each of these segments, helping them succeed in the TON blockchain ecosystem. ### Beginner Crypto Investors For those just starting their journey into the world of cryptocurrencies, **swap.coffee** offers an intuitive and secure trading interface. Beginner users can avoid the complexities of volatility and intricate interfaces with the help of advanced tools for risk reduction. **swap.coffee** assists beginner investors by providing: * **Ease of Use:** A user-friendly interface makes asset swapping accessible without the need to learn complex tools. * **Security:** A fully decentralized platform ensures safety and transparency through smart contracts. * **Trading Strategies:** DCA (Dollar Cost Averaging) and VA (Value Averaging) allow users to minimize volatility risks by automatically averaging purchases or adjusting volumes. ### Whales (Large Traders) For large traders managing substantial assets, liquidity and low fees are crucial. **swap.coffee** offers ideal conditions for whales thanks to its deep market and efficient trading mechanisms. **swap.coffee** offers whales: * **Deep Liquidity:** Aggregated liquidity from various DEXs and pools allows for large transactions with minimal price impact. * **Fee Savings:** Transaction splitting and routing through intermediate liquidity pools minimize gas costs. * **On-Chain Limit Orders with RFQ Protocol:** Limit orders with access to CEX liquidity through RFQ protocols ensure favorable prices. ### Developers **swap.coffee** provides developers with powerful APIs for integrating trading solutions based on the TON blockchain. This gives developers the opportunity to use liquidity and trading tools from the platform to build their own products. **swap.coffee** offers developers: * **API Suite:** Our APIs provide access to aggregated liquidity, limit orders, DCA/VA strategies, and other trading solutions. * **Integration Flexibility:** High customization allows developers to easily implement our tools into their projects. * **DeFi Support:** **swap.coffee** helps build DeFi applications by providing powerful tools for liquidity management and trading. ### Influencers Influencers play a vital role in attracting new users to the platform, and **swap.coffee** offers them opportunities to earn through the referral program. With their audience, influencers can actively promote the platform and earn rewards based on the trading volume of referred users. **swap.coffee** offers influencers: * **Referral Program:** Influencers can earn a percentage of the trading volume generated by referred users, monetizing their audience. * **Ease of Promotion:** A transparent and secure platform makes **swap.coffee** attractive to their followers, boosting trust and conversion. ### Crypto Projects Crypto projects can leverage **swap.coffee** for conducting marketing campaigns such as trading competitions and cashback offers. This allows projects to attract users more effectively and stimulate active trading, strengthening their ecosystem. **swap.coffee** offers crypto projects: * **Marketing Tools:** Cashback offers and trading competitions help engage users and promote interaction with their tokens. * **Increased Liquidity:** Participation in our ecosystem gives projects access to aggregated liquidity, helping to boost trading volumes and ensure steady growth. ### Why is swap.coffee important for all segments? **swap.coffee** provides various tools and opportunities to meet the needs of each segment: * **For Beginners:** Simple interface, secure transactions, and strategies to reduce risks help new users trade confidently. * **For Whales:** High liquidity and low fees ensure effective trading of large asset volumes. * **For Developers:** Our APIs and platform flexibility enable the creation of complex DeFi solutions with access to liquidity and advanced trading tools. * **For Influencers:** The referral program provides a way to monetize their audience by attracting new users. * **For Crypto Projects:** Cashback and trading competitions enable projects to conduct effective marketing campaigns and increase liquidity for their tokens. **swap.coffee** is a platform designed for users of all experience levels and goals, providing tools for effective trading and promotion of crypto assets within the TON blockchain ecosystem. # CES Token The **CES** token is a key component of the **swap.coffee** ecosystem, offering users a wide range of benefits and opportunities. It serves not only as a means of interaction within the platform but also as an important tool for driving growth and attracting new users and developers through various programs. ### Benefits of Using the CES Token 1. **Lower Fees** Holders of the **CES** token can pay fees on the platform at reduced rates. This allows users to save on transaction costs and get better trading conditions. * **Fee Reduction:** **CES** holders are able to pay fees at significant discounts, making transactions more profitable and reducing costs. 2. **Token Staking** Users of **swap.coffee** can stake **CES** tokens and earn rewards. Staking encourages long-term token holding and participation in the ecosystem. * **Staking Rewards:** Token holders who participate in staking receive periodic rewards, which incentivize them to remain engaged with the ecosystem. 3. **Early Access to Tools** **CES** holders get exclusive early access to new tools and features on the **swap.coffee** platform. * **Exclusive Access:** **CES** provides priority access to new trading tools and features, allowing token holders to use innovative solutions first. ### Using CES to Develop the Platform The **CES** token is also used as an important tool for promoting **swap.coffee** through various programs aimed at attracting users and developers: 1. **Marketing Campaigns** **CES** plays an essential role in conducting **swap.coffee** marketing campaigns. 2. **Ambassador Program** **swap.coffee** actively uses **CES** tokens as part of the ambassador program. 3. **Grant Program** **swap.coffee** supports developers by offering them **CES** token grants for creating new solutions and integrations based on the TON blockchain. ### The Value of CES for the swap.coffee Ecosystem The **CES** token plays a vital role in supporting and growing the entire **swap.coffee** ecosystem. It drives user activity, attracts new developers through the grant program, and strengthens the platform's marketing efforts. * **User Activity:** Staking programs, marketing campaigns, and the ambassador program encourage users to participate long-term and trade actively. * **Developer Attraction:** The grant program supports the creation of new solutions, increasing the platform's value and expanding its functionality. * **Community Growth:** The **CES** token plays a crucial role in the development of the **swap.coffee** community, fostering active engagement and ecosystem growth. ### Tokenomics title # Components 1. **DEX Aggregator** — collects liquidity from various decentralized exchanges and liquidity pools to provide the best exchange rates. 2. **DEX** — a full-fledged decentralized exchange, allowing users to trade crypto assets directly with each other without intermediaries. 3. **Liquidity from CEX (Centralized Exchanges)** — is only supplied to limit orders via the RFQ protocol, ensuring better rates and gas savings for users using limit orders. 4. **Liquidity Pools** — both internal and external pools used to enhance liquidity and optimize trading routes on the platform. 5. **On-Chain Limit Orders** — allow users to place trades at fixed prices, with access to CEX liquidity through the RFQ protocol for better conditions. 6. **DCA (Dollar Cost Averaging) and VA (Value Averaging) Strategies** — tools for automating investment strategies, reducing risks, and improving returns during market volatility. 7. **Staking CES Tokens** — users can stake **CES** to earn rewards and access additional benefits. 8. **CES Token** — used for fee reduction on the platform, staking, early access to tools, and participation in marketing campaigns, the ambassador program, and the grant program. 9. **API Integrations** — provide developers with access to platform functionality for building their own solutions and products based on the TON blockchain. 10. **Referral Program** — users, including influencers, can earn a percentage of the trading volume of referred users, stimulating community growth. 11. **Trading Competitions and Cashback** — used by crypto projects for active marketing campaigns on the platform, stimulating trading and increasing liquidity. 12. **Claim Center** — a component of the platform that allows users to claim their rewards, such as staking rewards, marketing campaigns, and airdrops. 13. **User Profile** — a component that allows users to analyze their wallet, track trade history, calculate profit from trades, and manage farm positions. # DEX APR Boost Promotion Source: https://docs.swap.coffee/legal/aprboost Last Updated: 16.08.2025 ### 1. Preamble These Terms and Conditions (the “Terms”) govern participation in the promotional campaign conducted by the decentralized platform swap.coffee (the “Platform”). Participation in the Promotion constitutes full and unconditional acceptance of these Terms. Persons who do not agree with the Terms must refrain from participating. ### 2. General Provisions The organizer of the Promotion is swap.coffee, a decentralized exchange (DEX) available at [https://swap.coffee](https://swap.coffee). The Promotion is intended to provide a temporary increase in the annual percentage rate (APR) for liquidity providers in certain Coffee DEX pools. ### 3. Definitions * **Platform** – swap.coffee, a decentralized exchange (DEX). * **Promotion** – A limited-time offer providing additional annual percentage rate (APR) to participants who provide liquidity in eligible pools. * **Participant** – An individual or other legally capable entity that has provided liquidity in pools meeting the promotion criteria. * **Pools** – Token trading pairs on Coffee DEX available at [https://swap.coffee/earn?source=coffee](https://swap.coffee/earn?source=coffee). * **Claim Center** – The section of the Platform at [https://swap.coffee/claim](https://swap.coffee/claim) used to claim rewards. * **TON** – The cryptocurrency of The Open Network. * **USDT** – The Tether USD stablecoin. ### 4. Promotion Conditions * Annual Percentage Rate (APR) — 20%. * Maximum reward per wallet — equivalent of 25 USD. * The total reward pool for the Promotion is 5,000 TON. * If the total participant deposit volume exceeds the pool size, the Platform reserves the right to: 1. increase the total reward pool; or 2. proportionally distribute the existing pool among all Participants, which may result in the actual APR being lower than the stated rate. * The boost applies to all Coffee DEX pools containing tokens paired with USDT or TON. * The reward distribution mechanism will not be changed after the Promotion starts. ### 5. Participation Procedure 1. The Participant provides liquidity to one or more eligible pools. 2. Rewards are paid in TON. 3. Rewards can be claimed through the Claim Center after the Promotion ends. 4. Rewards can be withdrawn to the Participant’s wallet in accordance with these Terms. ### 6. Restrictions and Compliance * Participation is available only to users who have the technical ability to interact with the Platform. * Participation is prohibited for individuals located in jurisdictions where digital asset operations are restricted or prohibited. * Participants must comply with applicable laws, including anti-money laundering and counter-terrorist financing (AML/CTF) measures. ### 7. Information Publication All official information regarding the Promotion, including the reward distribution date, will be published exclusively through the Platform’s official channels: * Telegram (EN): [https://t.me/swap\_coffee](https://t.me/swap_coffee) * Telegram (RU): [https://t.me/swapcoffee\_ru](https://t.me/swapcoffee_ru) * X (Twitter): [https://x.com/swap\_coffee\_ton](https://x.com/swap_coffee_ton) ### 8. Disclaimer * The Promotion is provided on an “as-is” basis without warranties regarding the stated return, token price stability, absence of technical issues, or changes in the TON network. * The Platform shall not be liable for any direct or indirect losses arising from participation in the Promotion. ### 9. Final Provisions The Platform reserves the right to amend or cancel the Promotion at any time without prior notice. # Grant Program Source: https://docs.swap.coffee/legal/grantprogram Last Updated: 16.08.2025 ## 1. Introduction These Terms govern participation in the grant program organized by **swap.coffee** (hereinafter – the “Platform”). The purpose of the program is to provide limited support to developers and teams implementing projects based on the swap.coffee infrastructure. This program does **not** constitute a public offer and does not create any legal obligations until an individual agreement (grant agreement) is signed between the Platform and the participant. The Platform reserves the right at any time to: * modify the terms of the program; * suspend or terminate the program; * refuse support without providing reasons. *** ## 2. Program Objectives The grant program aims to promote the development of the swap.coffee ecosystem and DeFi infrastructure within the TON network. It supports initiatives that contribute to growth, improved user experience, and the expansion of the platform’s technical capabilities. *** ## 3. Eligibility The program is open to: * individual developers * teams and startups; * student initiatives and research groups; * existing projects interested in integrating with swap.coffee. **Minimum requirements:** * necessary technical skills; * understanding of DeFi and swap.coffee infrastructure; * readiness to cooperate and comply with the program terms. *** ## 4. Application Requirements To apply, participants must provide a brief project description in free form or as a pitch deck, including: * purpose and objectives of the project; * use of swap.coffee components (API, SDK, smart contracts, etc.); * target audience; * implementation stages and estimated timelines; * team composition and competencies; * expected scope and form of support; * contact information. *** ## 5. Application Submission Applications must be submitted via a dedicated form on the official website. The participant must provide accurate and complete information meeting the requirements outlined in Section 4. The Platform may request additional details, materials, or conduct a preliminary interview before making a decision. *** ## 6. Confidentiality The Platform undertakes not to disclose application materials to third parties without the applicant’s consent, except as required by law. Submitting an application does not constitute a confidentiality agreement (NDA). If necessary, the participant may request an NDA before sending materials. The NDA may be signed at the discretion of the Platform. *** ## 7. Review Procedure Each application undergoes internal evaluation based on: * relevance to swap.coffee; * practical value for the ecosystem and users; * technical feasibility; * team experience and resources; * justification of budget and requested support; * project sustainability and growth potential. Decisions are made at the sole discretion of the swap.coffee team. The Platform is not obligated to provide feedback on rejected applications. *** ## 8. Forms of Support Approved participants may receive one or more types of support: * **Financial support**: grants in cryptocurrency (TON, USDT, CES). The amount and payment schedule are determined individually. * **Technical support**: consultations, technical audits, integration assistance. * **Promotional support**: promotion on swap.coffee resources, announcements, participation in events (subject to agreement). Support is provided under a signed grant agreement specifying obligations, timelines, and conditions. *** ## 9. Participant Obligations Upon signing the agreement, the participant undertakes to: * complete the project within agreed timelines; * use support exclusively for project needs; * inform the Platform about progress and interim results; * comply with applicable laws and avoid infringing third-party rights; * where possible, make part of the project open source; * publicly acknowledge swap.coffee support (in descriptions, interfaces, repositories, etc.). ### 9.1. Compliance with AML and CTF Requirements The participant undertakes to: * comply with applicable anti-money laundering (AML) and counter-terrorism financing (CTF) laws; * not use the support, including cryptocurrency assets, for unlawful purposes; * provide documents and information upon request for AML/CTF checks; * promptly notify the Platform of any circumstances that may lead to a breach of these requirements. *** ## 10. Grounds for Termination of Support The Platform reserves the right to suspend or terminate support if: * the project significantly deviates from the agreed plan; * grant funds are misused; * the participant is unreachable for more than 30 calendar days; * applicable laws, program terms, or grant agreement terms are violated; * the project loses technical or economic viability. Any further cooperation after termination is at the sole discretion of the Platform. *** ## 11. Limitation of Liability swap.coffee is not liable for: * project outcomes, including technical, financial, or user-related risks; * participant actions or omissions; * any direct or indirect losses incurred by participants. Providing support does not constitute an investment and does not imply swap.coffee’s participation in equity, management, or profits. *** ## 12. Final Provisions * swap.coffee may unilaterally amend these Terms. * Continued participation after amendments constitutes acceptance of the new terms. * swap.coffee reserves the right to terminate support if the participant violates the agreement or fails to meet ethical and technical standards. This document is published for informational purposes only. To receive support, an individual grant agreement must be signed. # Privacy Policy Source: https://docs.swap.coffee/legal/policy Last Updated: 27.11.2024 This Privacy Policy describes how your personal information is collected, used, and shared when you visit or interact with **swap.coffee** (the "Site"). ## Personal Information We Collect When you visit the Site, we automatically collect certain information about your device, including: * Information about your web browser, IP address, time zone, and some of the cookies that are installed on your device. * As you browse the Site, we collect data about the individual web pages or products you view, the websites or search terms that referred you to the Site, and your interactions with the Site. We refer to this automatically-collected information as **Device Information**. ## Technologies Used to Collect Device Information: * **Cookies**: Data files placed on your device or computer that often include an anonymous unique identifier. Learn more about cookies and how to disable them at [allaboutcookies.org](http://www.allaboutcookies.org). * **Log Files**: Track actions occurring on the Site and collect data such as IP address, browser type, Internet service provider, referring/exit pages, and timestamps. * **Web Beacons**, **Tags**, and **Pixels**: Electronic files used to record information about how you browse the Site. Additionally, when you contact us via forms located on the Site, we collect: * **Contact Information**, such as your name, email address, and phone number. When we mention **Personal Information** in this policy, it includes both **Device Information** and **Contact Information**. ## How We Use Your Personal Information We use the **Contact Information** to: * Communicate with you. * Provide you with information or advertising about our products or services in line with your preferences. We use the **Device Information** to: * Screen for potential risk and fraud (especially your IP address). * Improve and optimize our Site by analyzing how customers browse and interact with it. * Assess the success of our marketing and advertising campaigns. ## Sharing Your Personal Information We share your **Personal Information** with third parties to help us use it as described above. For example: * We use **Google Analytics** to understand how customers use the Site. Learn more about how Google uses your information [here](https://www.google.com/intl/en/policies/privacy/). You can opt out of Google Analytics [here](https://tools.google.com/dlpage/gaoptout). Additionally, we may share your information to: * Comply with applicable laws and regulations. * Respond to subpoenas, search warrants, or other lawful requests. * Protect our rights. ## Behavioural Advertising We use your **Personal Information** to provide targeted advertisements or marketing communications that may interest you. You can opt out of targeted advertising: * [Facebook](https://www.facebook.com/settings/?tab=ads) * [Google](https://www.google.com/settings/ads/anonymous) * [Bing](https://about.ads.microsoft.com/en-us/resources/policies/personalized-ads) Additionally, opt out via the [Digital Advertising Alliance](http://optout.aboutads.info/). ## Do Not Track We do not alter our Site's data collection and use practices when we receive a "Do Not Track" signal from your browser. ## Your Rights If you are a European resident, you have the right to: * Access personal information we hold about you. * Request corrections, updates, or deletion of your information. To exercise these rights, please contact us via the form at [swap.coffee](https://swap.coffee). Please note: * We process your information to contact you or pursue our legitimate business interests. * Your information may be transferred outside of Europe, including to Canada and the United States. ## Data Retention We retain your **Contact Information** for our records unless and until you request its deletion. ## Changes to This Policy We may update this privacy policy from time to time to reflect changes in our practices or for operational, legal, or regulatory reasons. ## Contact Us For more information about our privacy practices, questions, or complaints, please contact us via the form at [swap.coffee](https://swap.coffee). # Terms of Use Source: https://docs.swap.coffee/legal/tos Last Updated: 27.11.2024 By accessing or using the services provided by swap.coffee (the "**Services**"), you agree to comply with and be bound by these Terms of Use (the "**Terms**") as it may be amended from time to time. If you do not agree to these Terms, please do not access or use the Services. **IMPORTANT NOTICE REGARDING ARBITRATION:** THESE TERMS CONTAIN ADDITIONAL PROVISIONS APPLICABLE ONLY TO YOU. WHEN YOU AGREE TO THESE TERMS YOU ARE AGREEING (WITH LIMITED EXCEPTION) TO RESOLVE ANY DISPUTE BETWEEN YOU AND swap.coffee THROUGH BINDING, INDIVIDUAL ARBITRATION RATHER THAN IN COURT. PLEASE REVIEW CAREFULLY **SECTION 5** BELOW FOR DETAILS REGARDING ARBITRATION. *** ## **1. Acceptance of Terms** By accessing or using the services provided by swap.coffee (the "**Services**"), you agree to comply with and be bound by these Terms of Use (the "**Terms**") as it may be amended from time to time. If you do not agree to these Terms, please do not access or use the Services. *** ## **2. Eligibility and Access** ### **2.1 Legal Age** You must be at least 18 years of age or the age of legal majority in your jurisdiction. ### **2.2 Prohibited Jurisdictions** If you are residing in, located in, or accessing the Services from jurisdictions where the Services are prohibited, including but not limited to the United States of America, you are not allowed to use the Services. ### **2.3 Compliance** You must comply with all applicable laws and regulations and are solely responsible for understanding the legal status of the Services in your jurisdiction. ### **2.4 Authority** You must have the full right, power, and authority to enter into and comply with these Terms on behalf of yourself and any party for which you may access or use the Services. Furthermore, the Services are not available to any user previously removed from the Services by us. *** ## **3. Your Responsibilities, Conduct, and Liability** ### **3.1 Knowledge Acquisition** You are responsible for acquiring adequate knowledge of blockchain technology, smart contracts, and the Services, and for understanding the risks involved. ### **3.2 Security of Credentials** You must secure your private keys, passwords, and any other credentials used to access the Services. ### **3.3 Lawful Use** You must use the Services for lawful purposes only and must not engage in any activities that could harm the Services or other users. ### **3.4 Accuracy of Information** You represent and warrant that any information you provide via the Services is accurate and complete. You accept and acknowledge that swap.coffee is not responsible for any errors or omissions that you make in connection with any transaction initiated via the Services, for instance, if you mistype a recipient’s username or otherwise provide incorrect information. You agree to review your transactions carefully before completing them via the Services. ### **3.5 Prohibited Actions** You must not misuse the Services by knowingly introducing material that is malicious or technologically harmful. If you do, your right to use the Services will cease immediately. ### **3.6 Tax Obligations** You are solely responsible for determining and paying any taxes, levies, or similar governmental assessments of any nature (collectively, “Taxes”) associated with your use of the Services. By using the Services, you agree not to hold us liable for any tax liability associated with or arising from your access or use of the Services or any other action or transaction related thereto. ### **3.7 Prohibited Activities** You agree not to do any of the following: * Use, display, mirror, or frame the Services or any individual element within the Services, the swap.coffee’s name, trademark, logo, or other proprietary information, or the layout and design of any page or form contained on a page, without swap.coffee’s express written consent; * Access, tamper with, or use non-public areas of the Services, swap.coffee’s computer systems, or the technical delivery systems of swap.coffee’s providers; * Attempt to probe, scan, or test the vulnerability of the Services, or any swap.coffee system or network, or breach any security or authentication measures; * Avoid, bypass, remove, deactivate, impair, descramble, or otherwise circumvent any technological measure implemented by swap.coffee or any of swap.coffee’s providers or any other third party (including another user) to protect the Services; * Attempt to access or search the Services or download any information from the Services through the use of any engine, software, tool, agent, device, or mechanism (including spiders, robots, crawlers, data mining tools, or the like) other than the software and/or search agents provided by swap.coffee or available through the Services; * Use or access the Services for the purpose of sending any unsolicited or unauthorized advertising, promotional materials, email, junk mail, spam, chain letters, or other form of solicitation; * Use any meta tags or other hidden text or metadata utilizing a swap.coffee trademark, logo URL, or name without swap.coffee’s express written consent; * Use the Services, or any portion thereof, for any commercial purpose or for the benefit of any third party or in any manner not permitted by these Terms; * Forge any TCP/IP packet header or any part of the header information in any email or newsgroup posting, or in any way use the Services to send altered, deceptive, or false source-identifying information; * Attempt to decipher, decompile, disassemble, or reverse engineer any of the software used to provide the Services; * Interfere with, or attempt to interfere with, the access of any user, host, or network, including, without limitation, sending a virus, overloading, flooding, spamming, or mail-bombing the Services; * Collect or store any personally identifiable information from the Services from other users of the Services without their express permission; * Impersonate or misrepresent your affiliation with any person or entity; * Use the Services for activities that are unlawful or fraudulent or have such purpose or effect or otherwise support any activities that breach applicable local, national, or international law or regulations; * Use the Services or interact with the Services in a manner that violates any law or regulation, including, without limitation, any applicable export control laws; or * Encourage or enable any other individual to do any of the foregoing. ### **3.8 Indemnification** You will indemnify and hold swap.coffee and its officers, directors, employees, and agents harmless from and against any claims, disputes, demands, liabilities, damages, losses, and costs and expenses, including, without limitation, reasonable legal and accounting fees arising out of or in any way connected with (a) your access to or use of the Services, or (b) your violation of these Terms. You agree that you will be liable for any losses sustained by us as a result of your breach of these Terms and will compensate us in full for any such losses. We reserve the right, at our own expense, to assume the exclusive defense and control of any matter otherwise subject to indemnification by you, and in such case, you agree to cooperate with us in the defense of such matter. The indemnity set out in this clause is in addition to, and not in lieu of, any other remedies that may be available to us under applicable law. *** ## **4. Intellectual Property Rights** ### **4.1 Ownership** All intellectual property rights in the Services, including but not limited to trademarks, copyrights, and patents, are owned by swap.coffee or its licensors, and the rights in the Services are only licensed to you. You acknowledge that you do not acquire any ownership rights by accessing or using the Services, or any portion thereof. ### **4.2 Restrictions** You may not copy, modify, distribute, or reverse engineer any part of the Services or its content without express written permission from swap.coffee. ### **4.3 Open Source Software** The Services may contain code, commonly referred to as open-source software, which is distributed under open-source license terms, including terms that allow the free distribution and modification of the relevant software’s source code and/or which require all distributors to make such source code freely available upon request, including any contributions or modifications made by such distributor (“**Open Source Software**”). To the extent that the Services contain any Open Source Software, that element only is licensed to you under the relevant license terms of the applicable third-party licensor (“**Open Source License Terms**”) and not under these Terms, and you accept and agree to be bound by such Open Source License Terms. *** ## **5. Dispute Resolution and Governing Law** ### **5.1 Arbitration** Any disputes arising from these Terms or the use of the Services shall be resolved through binding arbitration under the rules of the International Chamber of Commerce, in London, United Kingdom. ### **5.2 Governing Law** These Terms are governed by the laws of the United Kingdom, without regard to its conflict of law principles. ### **5.3 Class Action Waiver** You agree to resolve disputes on an individual basis and waive the right to participate in class action lawsuits. *** ## **6. Limitations of Liability and Disclaimers** ### **6.1 No Warranties** Except as set out in these Terms, we do not warrant, represent, or guarantee that the Services will be accurate, complete, correct, reliable, fit for purpose, secure, or free from weaknesses, vulnerabilities, or bugs. You understand and accept that you use the Services at your own risk. ### **6.2 "As Is" Provision** To the fullest extent permitted by law, we provide the Services to you “as is” and “as available” without any warranty, representation, or assurance (whether express or implied) in relation to merchantability, fitness for a particular purpose, availability, security, title, or non-infringement. ### **6.3 Changes to Services** We reserve the right to change the format and features of the Services by making any updates to Services or, where your device settings permit it, by automatic delivery of updates. ### **6.4 Discontinuation** We may cease to provide and/or update content to the Services, with or without notice to you, if it improves the Services we provide to you, or we need to do so for security, legal, or any other reasons. ### **6.5 Limitation of Liability** TO THE MAXIMUM EXTENT PERMITTED BY LAW, NEITHER swap.coffee NOR ITS SERVICE PROVIDERS INVOLVED IN CREATING, PRODUCING, OR DELIVERING THE SERVICES WILL BE LIABLE FOR ANY INDIRECT, INCIDENTAL, SPECIAL, PUNITIVE, EXEMPLARY, OR CONSEQUENTIAL DAMAGES, OR DAMAGES FOR LOST PROFITS, LOST REVENUES, LOST SAVINGS, LOST BUSINESS OPPORTUNITY, LOSS OF DATA OR GOODWILL, SERVICE INTERRUPTION, COMPUTER DAMAGE OR SYSTEM FAILURE, OR THE COST OF SUBSTITUTE SERVICES OF ANY KIND ARISING OUT OF OR IN CONNECTION WITH THESE TERMS OR FROM THE USE OF OR INABILITY TO USE THE SERVICES, WHETHER BASED ON WARRANTY, CONTRACT, TORT (INCLUDING NEGLIGENCE), PRODUCT LIABILITY, OR ANY OTHER LEGAL THEORY, AND WHETHER OR NOT USER OR ITS SERVICE PROVIDERS HAS BEEN INFORMED OF THE POSSIBILITY OF SUCH DAMAGE, EVEN IF A LIMITED REMEDY SET FORTH HEREIN IS FOUND TO HAVE FAILED OF ITS ESSENTIAL PURPOSE. TO THE MAXIMUM EXTENT PERMITTED BY THE LAW OF THE APPLICABLE JURISDICTION, IN NO EVENT WILL swap.coffee’S TOTAL LIABILITY ARISING OUT OF OR IN CONNECTION WITH THESE TERMS OR FROM THE USE OF OR INABILITY TO USE THE SERVICES EXCEED THE AMOUNTS YOU HAVE PAID OR ARE PAYABLE BY YOU FOR USE OF THE SERVICES OR ONE HUNDRED DOLLARS (\$100), IF YOU HAVE NOT HAD ANY PAYMENT OBLIGATIONS TO swap.coffee, AS APPLICABLE. THE EXCLUSIONS AND LIMITATIONS OF DAMAGES SET FORTH ABOVE ARE FUNDAMENTAL ELEMENTS OF THE BASIS OF THE BARGAIN BETWEEN swap.coffee AND YOU. ### **6.6 Security Disclaimer** We do not guarantee that the Services will be secure or free from bugs, security vulnerabilities, or viruses. You are responsible for configuring your information technology and computer programs to access the Services and to use your own virus protection software. If you become aware of any exploits, bugs, or vulnerabilities, please let us know at: [support@swap.coffee](mailto:support@swap.coffee). ### **6.7 Third-Party Dependencies** The Services rely in part on third-party and open-source software, including the TON network or any other supported network, and the continued development and support by third parties. There is no assurance or guarantee that those third parties will maintain their support of their software or that open-source software will continue to be maintained. This may have a material adverse effect on the Services. We do not own or control the TON network or any other supported network. The TON network, along with any other supported network, may be subject to changes (e.g., forks), and such changes may materially impact the function, value, or name of digital assets. You acknowledge and agree that: * We are not responsible for the operation of any supported network and we make no guarantee of their functionality, security, or availability; and * We may temporarily or permanently discontinue support of any supported network. ### **6.8 Third-Party Services** In connection with your use of the Services, you may be offered or made aware of services, content, features, products, third-party applications, offers, and promotions provided by third parties (collectively, “**Third-Party Services**”). Our inclusion or promotion of Third-Party Services does not reflect a sponsorship, endorsement, approval, or verification by us. Your use, access, and exchange of data with any Third-Party Services is at your own risk and subject to terms and conditions between you and the provider of the Third-Party Services. We do not warrant any Third-Party Services in any way. *** ## **7. Amendments and Termination** ### **7.1 Changes to Terms** From time to time, we may change these Terms. If we do this, then we will publish those changes on the website [https://swap.coffee](https://swap.coffee). It is important that you review these Terms each time you use or access the Services. If you continue to use or access the Services after we have posted updated Terms, it means that you accept and agree to the changes, and you will be bound by those new terms the next time you use the Services. If you do not agree to any changes, you must not access or use the Services. Because the Services are evolving over time, we may change or discontinue all or any part of the Services, at any time and without notice, at our sole discretion. ### **7.2 Termination** swap.coffee may terminate or suspend access to the Services at any time, without prior notice, for conduct that violates these Terms or is harmful to other users of the Services, swap.coffee, or third parties, or for any other reason. *** ## **8. Contact Information** For inquiries, concerns, or disputes, please contact us at: * **Email:** [info@swap.coffee](mailto:info@swap.coffee) *** ## **9. Final Provisions** ### **9.1 Monitoring and Compliance** Although we are not obligated to monitor access to or use of the Services, we have the right to do so for the purpose of operating the Services, to ensure compliance with these Terms, and to comply with applicable law or other legal requirements. We have the right to investigate violations of these Terms or conduct that affects the Services. We may also consult and cooperate with law enforcement authorities to prosecute users who violate the law. ### **9.2 Severability** If any provision of these Terms is deemed invalid or unenforceable, the remaining provisions shall continue in full force and effect. ### **9.3 No Waiver** swap.coffee’s failure to enforce any right or provision of these Terms will not be considered a waiver of such right or provision. The waiver of any such right or provision will be effective only if in writing and signed by a duly authorized representative of swap.coffee. Except as expressly set forth in these Terms, the exercise by either party of any of its remedies under these Terms will be without prejudice to its other remedies under these Terms or otherwise. ### **9.4 Third-Party Rights** Unless it expressly states otherwise, these Terms do not give rise to any third-party rights, which may be enforced against us. ### **9.5 Assignment** You may not assign or transfer these Terms, by operation of law or otherwise, without swap.coffee’s prior written consent. Any attempt by you to assign or transfer these Terms, without such consent, will be null. swap.coffee may freely assign or transfer these Terms without restriction. Subject to the foregoing, these Terms will bind and inure to the benefit of the parties, their successors, and permitted assigns. ### **9.6 Entire Agreement** These Terms, along with any documents referenced herein, constitute the entire agreement between you and swap.coffee regarding the access and use of the Service. *** **Last Reviewed:** 27.11.2024 # Амбассадорская программа Source: https://docs.swap.coffee/ru/ambassador-guides/welcome Как стать амбассадором swap.coffee, выполнять задания, создавать контент и получать вознаграждение. # Полный гайд по амбассадорской программе swap.coffee Добро пожаловать в амбассадорскую программу swap.coffee! В этом руководстве вы найдете всю необходимую информацию о том, как стать амбассадором, какие задачи выполнять, как создавать эффективный контент и получать вознаграждения. ## Что такое swap.coffee? swap.coffee - это агрегатор ликвидности, работающий на блокчейне TON, который позволяет обменивать криптовалюту абсолютно без дополнительных комиссий и гарантирует пользователям лучшую цену на рынке. Платформа постоянно развивается, захватывает новые сегменты рынка и регулярно обновляется, добавляя инновационные инструменты и возможности. Главная цель swap.coffee - создание полноценной экосистемы, в которой наши пользователи смогут решать любые задачи внутри одной платформы, не обращаясь к другим сервисам. ## Кто такой амбассадор swap.coffee? Амбассадор swap.coffee - это энтузиаст, который активно способствует продвижению и развитию платформы. Основные задачи амбассадора включают: * Создание контента: публикация материалов о swap.coffee в социальных сетях, блогах, на видеоплатформах и форумах. * Взаимодействие с сообществом: ответы на вопросы пользователей, помощь новичкам, участие в обсуждениях. ## Как стать амбассадором? Чтобы присоединиться к амбассадорской программе swap.coffee, выполните следующие шаги: 1. Перейдите в [swap.coffee app](https://t.me/swapcoffee): Напишите команду /start и нажмите кнопку Ambassador — вы попадёте в свой личный кабинет. 2. Создавайте контент: Публикуйте материалы о swap.coffee в социальных сетях или на других площадках. Это могут быть посты, сторис, статьи, видео и т.д. 3. Отправляйте материалы на проверку: После публикации отправьте ссылку на ваш контент через [swap.coffee app](https://t.me/swapcoffee). Мы его проверим и начислим вам баллы. 4. Будьте активны в сообществе: Присоединяйтесь к официальным чатам, помогайте другим пользователям, участвуйте в обсуждениях. ## Вознаграждения и преимущества Амбассадоры swap.coffee получают вознаграждения в зависимости от их вклада в развитие проекта. Размер вознаграждения зависит от качества и охвата созданного контента, а также от активности в сообществе. Выплаты производятся в токенах CES. Преимущества участия в программе: * Гибкий график: Вы сами выбираете, когда и сколько времени уделять амбассадорской деятельности. * Развитие навыков: Возможность улучшить навыки создания контента, маркетинга и коммуникации. * Часть сообщества: Станьте частью нового активного и дружелюбного сообщества. ### Как формируется моё вознаграждение? В конце каждого месяца подсчитывается общее количество баллов, набранных вами за все ваши материалы. В зависимости от суммы баллов, которые вы набрали за месяц, вам начисляется соответствующая часть от общего пула наград. Чем выше суммарное количество ваших баллов за месяц, тем большее вознаграждение вы получите. ### Когда подавать материалы на проверку? Материалы можно отправлять на проверку в любой удобный момент через наше [swap.coffee app](https://t.me/swapcoffee). ### Когда выплачиваются награды? Для получения вознаграждения необходимо один раз привязать свой кошелек в меню [swap.coffee app](https://t.me/swapcoffee). После привязки вашего кошелька, все вознаграждения будут автоматически начисляться в Claim Center на указанный кошелек. При необходимости вы всегда можете изменить привязанный кошелек через меню. ## Полезные ссылки * Официальный сайт swap.coffee: [swap.coffee](https://swap.coffee/) * swap.coffee APP: [t.me/swapcoffee](https://t.me/swapcoffee) * Документация swap.coffee: [docs.swap.coffee](https://docs.swap.coffee/) * Brandbook: [https://www.figma.com/design/Hy5f6zwcsvvbgfm7PmhOsN/swap.coffee-guideline?node-id=0-1\&p=f\&t=56PifdcRtSgBjzis-0](https://www.figma.com/design/Hy5f6zwcsvvbgfm7PmhOsN/swap.coffee-guideline?node-id=0-1\&p=f\&t=56PifdcRtSgBjzis-0) ### Социальные сети и каналы: * Telegram-канал (RU): [t.me/swapcoffee\_ru](https://t.me/swapcoffee_ru) * Telegram-канал (EN): [t.me/swapcoffee](https://t.me/swapcoffee) * VK сообщество: [vk.com/swapcoffee](http://vk.com/swapcoffee) * Instagram: [instagram.com/swap\_coffee\_ton](https://instagram.com/swap_coffee_ton) * YouTube канал: [youtube.com/@swap.coffee](https://youtube.com/@swap.coffee) * TikTok: [tiktok.com/@swap\_coffee\_ton](https://www.tiktok.com/@swap_coffee_ton) ### Дополнительно: * Эмодзи swap.coffee: [swap.coffee Emoji](https://t.me/addemoji/swap_coffee_emoji) * Стикерпак swap.coffee: [swap.coffee Stikers](https://t.me/addstickers/swap_coffee_animated) ## Рекомендации по созданию контента Для эффективного продвижения swap.coffee рекомендуется использовать различные платформы и форматы контента: * Социальные сети: Twitter, Facebook, Instagram. Публикуйте новости, обновления, инфографику и короткие видео. * Видеоплатформы: YouTube, TikTok. Создавайте обзоры платформы, инструкции по использованию, делитесь личным опытом. * Блоги и форумы: Medium, Reddit. Пишите статьи, гайды, участвуйте в обсуждениях, отвечайте на вопросы пользователей. * Крипто-сообщества: CoinMarketCap Community, Binance Square. Публикуйте аналитику, делитесь новостями и активно обсуждайте преимущества и обновления swap.coffee с участниками крупнейших крипто-сообществ. ### Как оценивается контент? Каждая ваша публикация оценивается командой swap.coffee по 10-балльной шкале в момент подачи материала на проверку. Оценка зависит от качества, полезности, оформления, оригинальности и общего впечатления от контента. Поскольку количество просмотров влияет на ваше итоговое вознаграждение, рекомендуется отправлять материалы на проверку не сразу, а через несколько дней после публикации — так ваш контент успеет собрать больше просмотров и увеличить ваше вознаграждение. ## Часто задаваемые вопросы (FAQ) 1. **Нужно ли иметь большой опыт в социальных сетях, чтобы стать амбассадором?**\ Нет, опыт не обязателен. Главное — ваше желание учиться, создавать контент и помогать сообществу. 2. **На каком языке создавать контент?**\ Контент можно создавать на любом языке. Однако публикации на английском языке помогут охватить более широкую аудиторию. 3. **Как часто нужно отправлять отчеты?**\ Отчеты отправляются в любой момент, когда вы хотите. 4. **Какие критерии оценки контента?**\ Оцениваются качество, уникальность, охват аудитории и вовлеченность пользователей. 5. **Могу ли я привлекать других амбассадоров?**\ Да, вы можете приглашать других участников в программу. За каждого привлеченного амбассадора вы можете получить дополнительное вознаграждение. ## Общие советы для всех видео-платформ Независимо от выбранной социальной сети, помните: вы работаете в системе рекомендаций. Именно алгоритмы решают, увидит ли кто-то ваш контент. Чтобы повысить шанс охвата: * Публикуйте ежедневно или максимально регулярно — соцсети любят стабильность. * Введите разные рубрики: обзоры, новости, споры, лайфхаки, личный опыт, аналитика. * Дублируйте контент по всем доступным платформам. Существуют удобные сервисы для автоматической кроссплатформенной публикации — используйте их. * Развивайтесь как ме��иа-личность: следите за успешными каналами, перенимайте лучшие приёмы и оформляйте свой контент качественно. * Относитесь к развитию себя как к работе — с вниманием к деталям, с учётом аналитики, вовлечённости и отклика аудитории. Помните: без упорства и системной работы ничего не получится. Будьте последовательны, не бросайте после первых трудностей, и вы обязательно увидите прогресс. * Записывайте подробные видео-обзоры платформы и делайте акцент на её уникальных функциях и преимуществах: отсутствие комиссий, высокая скорость, удобный интерфейс и лучшая цена на рынке. Регулярно публикуйте образовательные гайды, объясняя, как пользоваться платформой: от базовых функций до продвинутых фич. * Старайтесь использовать хуки и кликбейтные названия роликов — это поможет привлечь больше просмотров. * Первые 5–10 секунд ролика — ключевой момент для удержания внимания зрителя. Начинайте ролик динамично: яркие кадры, интригующий вопрос или краткий тизер того, что будет дальше, сразу заинтересуют аудиторию. Избегайте долгих заставок или затянутого вступления — зритель может не дождаться сути и переключится на другое видео. * Важно не только привлечь зрителя, но и удержать его интерес на протяжении всего ролика. YouTube учитывает этот показатель при продвижении роликов, поэтому регулярно проверяйте данные в YouTube Analytics (например, среднее время просмотра и процент досмотра). Анализируйте, на каких моментах зрители перестают смотреть ролик, и на основе этой информации улучшайте контент. Корректируйте длительность ролика, монтаж и подачу материала, чтобы зрители смотрели ролик как можно дольше. * Превью — это ваша витрина. Делайте его ярким, с чётким, легко читаемым шрифтом. Не размещайте важные слова в нижнем правом углу — там таймкод YouTube может их перекрыть. Экспериментируйте с различными вариантами обложек — YouTube позволяет загружать несколько превью и менять их даже после публикации. Отслеживайте, какие обложки работают лучше по вовлечённости. Подсказка: анализируйте оформления у успешных крипто и прочих каналов — перенимайте лучшие приёмы и адаптируйте под себя. * Обеспечьте высокое качество видео и чистый звук — это повышает доверие аудитории. Используйте нейросети для улучшения аудио, такие как Adobe Enhance Speech или аналогичные инструменты. Также можно воспользоваться Audacity или Adobe Audition для ручной коррекции громкости, шумоподавления и выравнивания уровней. Чистый и профессиональный звук делает ваш контент более комфортным для восприятия и увеличивает вероятность его полного просмотра. * В описании указывайте таймкоды, полезные ссылки и призыв к действию (перейти на сайт, вступить в сообщество и т.д.). и глубокие аналитические материалы о платформе. Теги больше не играют большой роли, но их стоит указывать для полноты. Главное — название, обложка и удержание внимания в первые секунды. Нарезайте ваши длинные видео на множество коротких фрагментов и размещайте их во всех социальных сетях. Такой формат позволяет охватить новую аудиторию и адаптировать контент под Reels, Shorts и TikTok. Если вы не хотите создавать полноценные длинные видео — работайте только с вертикальным форматом. Правила остаются теми же: цепляющий хук в начале, динамичный монтаж, чёткий звук и интересная тема. # Кешбэк Source: https://docs.swap.coffee/ru/user-guides/cashback **Программа вознаграждения** за вашу активность на платформе. Как в традиционном банке, только децентрализованно. *** ### 🚀 Как это работает? 1. Вы совершаете обмен на **swap.coffee**. 2. Система автоматически рассчитывает размер кешбэка. 3. Вы получаете кешбэк в **токенах** от наших партнеров. 4. Накопленный кешбэк можно забрать в любое время. *** ## 🔍 Подробнее о кешбэке ### 🪙 Что такое кешбэк? **Кешбэк** — это возврат части средств после совершения операции. На **swap.coffee** кешбэк выплачивается в **токенах наших партнеров**. *** ### 📊 От чего зависит размер кешбэка? Размер кешбэка напрямую связан с **объемом ваших транзакций**. > Чем больше вы свапаете, тем больше получаете в качестве награды! *** ### 🏆 Какие токены можно получить в качестве кешбэка? Наши партнеры предоставляют свои токены для распределения среди активных пользователей. > 📜 **Важно**: Список доступных токенов может меняться. *** ### 📄 Где посмотреть условия начисления кешбэка? Все условия и лимиты начисления доступны на специальной странице: 👉 [**Активные кешбэк акции**](https://swap.coffee/cashback) *** ### 💼 Как забрать накопленный кешбэк? Вы можете получить свою награду в любое удобное время через: 👉 [**Claim Center**](https://swap.coffee/claim) *** ### ⏳ Нужно ли сразу забирать кешбэк? Нет, это **не обязательно**. Вы сами решаете, накапливать кешбэк или забирать его сразу после начисления. *** ## 🔥 Почему кешбэк — это выгодно? **Кешбэк на swap.coffee** — это отличный способ получить **дополнительную выгоду** от ваших свапов. > **Начните пользоваться платформой уже сегодня** и наслаждайтесь преимуществами! 🚀 # Claim Center Source: https://docs.swap.coffee/ru/user-guides/claiming Добро пожаловать в **Claim Center** — ваш личный хаб для управления наградами на **swap.coffee**. Мы создали его, чтобы процесс получения вознаграждений был максимально простым и приятным. 🚀 *** ## ❓ Что такое Claim Center? **Claim Center** — это ваш персональный раздел на **swap.coffee**, где вы можете управлять всеми своими заслуженными наградами. ### Здесь вы найдете: * 💰 **Кешбэк за обмены**. * 👥 **Реферальные бонусы**. * 🏆 **Призы за участие в торговых конкурсах**. * 🔒 **Награды за стейкинг**. *** ## 🛠️ Как воспользоваться Claim Center? Мы сделали процесс максимально удобным: 1. 🔗 Перейдите в [Claim Center](https://swap.coffee/claim). 2. 🔒 Подключите ваш кошелек к платформе. 3. 🪙 **Выберите награды**: * Нажмите **"Выбрать все"** для быстрого выбора всех наград. * Или выберите конкретные токены по своим предпочтениям. 4. ✅ Нажмите **"Принять все"** — и ваши награды уже на пути к вам. 5. 📲 Подтвердите транзакцию в вашем кошельке. 6. 🎉 После подтверждения наслаждайтесь своими наградами! > **Важно**: > Мы ценим ваше время и деньги. **swap.coffee** не взимает дополнительных комиссий за получение наград. > Вы оплачиваете только стандартную комиссию сети. *** ## ⏳ Сколько это занимает? Мы оптимизировали процесс получения наград: ⏱️ Обычно это занимает всего **2-3 минуты**. > Однако время может варьироваться в зависимости от загруженности блокчейна. Мы делаем всё возможное, чтобы ускорить процесс. *** ## 🏁 Финальное слово **Claim Center** на **swap.coffee** — это ваш инструмент для получения максимальной выгоды. Регулярно используйте его и наслаждайтесь каждым заработанным токеном! 🎉 # Торговые конкурсы Source: https://docs.swap.coffee/ru/user-guides/contests Добро пожаловать в захватывающий мир торговых конкурсов **swap.coffee**! *** ## 🌟 Превратите обмены в победы Здесь каждая транзакция — это шаг к успеху, а ваша активность может принести не только прибыль, но и **ценные призы**. *** ## 🎯 Участвуйте без усилий * ✅ **Нет отдельной регистрации** — просто торгуйте. * 🤖 **Автоматическое участие** во всех текущих конкурсах. * 🔄 Каждый обмен на **swap.coffee** — это ваш шанс на победу. *** ## 🔍 Исследуйте возможности Перейдите по ссылке [swap.coffee/contests](https://swap.coffee/contests) — ваш портал в мир торговых состязаний, где вы найдете: * 🏅 **Актуальные конкурсы** с привлекательными призами. * 📋 **Подробную информацию** о наградах. * 📈 **Лидерборды**, обновляемые в реальном времени. *** ## 🤝 Честная игра для всех Мы ценим **прозрачность** и равные возможности: * Все правила и детали конкурсов доступны во вкладке **FAQ / Competition Rules**. * Каждый участник имеет **равные шансы** на успех. *** ## 🚀 Готовы стать чемпионом? Начните торговать прямо сейчас и превратите каждый свап в шаг к победе! Пусть **удача** сопутствует вам в каждой транзакции! 💪 # DCA (Dollar-Cost Averaging) Source: https://docs.swap.coffee/ru/user-guides/dca **📈 Осознанные инвестиции в любое время** Инвестирование — это искусство баланса. DCA (усреднение долларовой стоимости) позволяет автоматически покупать или продавать активы в заранее заданных диапазонах, снижая риски рыночных колебаний. На swap.coffee вы задаёте ценовой диапазон, в рамках которого система будет выполнять ордера по заранее установленной периодичности. ## 🚀 Как это работает? 1. **Выбираете актив** — например, CES. 2. **Определяете ценовой диапазон** — например, TON $2.00 – $2.50. 3. **Настраиваете периодичность сделок** — например, каждый день в 12:00 UTC. 4. swap.coffee автоматически исполняет сделки, даже если вас нет в сети. ## 🔍 Дополнительные настройки DCA ### 📌 Максимальное количество вызовов Этот параметр задаёт, сколько раз система может выполнить ордер, прежде чем стратегия будет завершена. * **1 вызов** — ордер исполняется один раз и затем отключается. * **10 вызовов** — система повторяет покупку до 10 раз, после чего стратегия завершается. **Пример:** Вы хотите покупать CES каждые 12 часов, но только 5 раз. Устанавливаете максимальное количество вызовов = 5, и после пятой сделки система автоматически завершит выполнение. ### 📌 Множитель от количества подзаказов Этот параметр разделяет сделку на несколько частей, чтобы оптимизировать цену и снизить влияние на рынок. * **Множитель 1** — ордер исполняется одним большим лотом. * **Множитель 3** — сделка разбивается на 3 части, каждая из которых выполняется отдельно. * **Множитель 5** — покупка/продажа разделяется на 5 частей и исполняется в течение заданного интервала. **Пример:** Вы хотите купить 100 CES, но не хотите резким ордером двигать рынок. Если множитель = 5, swap.coffee разобьёт ордер на 5 частей по 20 CES. В результате цена усреднится, и покупка будет менее заметной на рынке. ## 🛡 Безопасность и децентрализация * ✔️ DCA полностью автоматизировано — вам не нужно вручную выполнять сделки. * ✔️ Используются смарт-контракты, обеспечивающие максимальную прозрачность. ## 🔥 DCA — это стратегия для тех, кто хочет инвестировать без стресса и с максимальной эффективностью. # Лимитные ордера Source: https://docs.swap.coffee/ru/user-guides/limit **📊 Автоматические сделки по вашим условиям** Лимитные ордера позволяют заранее установить цену, по которой вы хотите купить или продать актив. Забудьте о постоянном мониторинге рынка — swap.coffee выполнит сделку автоматически, как только цена достигнет заданного уровня. ## 🚀 Как работают лимитные ордера? 1. **Выбираете актив** — например, CES. 2. **Устанавливаете цену, по которой хотите купить или продать** — например, TON за \$2.30. 3. **Создаёте лимитный ордер.** 4. Как только цена достигает нужного уровня, swap.coffee автоматически исполняет ордер. Вы контролируете каждую сделку и не зависите от случайностей. ## 🔍 Дополнительные настройки Лимитных ордеров ### 📌 Максимальное количество вызовов Определяет, сколько раз система может повторять заявку, если цена не достигнута. * **1 вызов** — ордер срабатывает один раз. * **10 вызовов** — система повторяет заявку до 10 раз, если цена не достигнута. **Пример:** Выставляете лимитный ордер на продажу CES по \$1.50, но не хотите продавать сразу всю сумму. Если установите максимальное количество вызовов = 5, swap.coffee 5 раз попробует продать CES по этой цене, прежде чем завершить ордер. ### 📌 Множитель от количества подзаказов Разделяет ордер на несколько частей, уменьшая влияние на цену. * **Множитель 1** — ордер исполняется полностью одним лотом. * **Множитель 3** — ордер делится на 3 части, каждая из которых исполняется отдельно. * **Множитель 5** — сделка разбивается на 5 частей, снижая нагрузку на рынок. **Пример:** Вы хотите продать 10 000 CES, но не хотите провоцировать падение цены. При множителе = 4, swap.coffee разделит продажу на 4 ордера по 2 500 CES, минимизируя влияние на рынок. ## 🛡 Безопасность и децентрализация * ✔️ Ордеры выполняются через смарт-контракты, без посредников. * ✔️ Полная прозрачность работы ордеров на блокчейне. ## 🔥 Лимитные ордера — это умный способ торговать без постоянного контроля за рынком. ## 🎯 Когда использовать DCA и Лимитные ордера? | Ситуация | DCA | Лимитные ордера | | -------------------------------------------------------- | :-: | :-------------: | | Вы хотите накапливать CES или TON постепенно | ✅ | ❌ | | Вы хотите установить точную цену для покупки или продажи | ❌ | ✅ | | Вы не хотите следить за графиком постоянно | ✅ | ✅ | | Вы боитесь сильных колебаний цены | ✅ | ❌ | | Вы хотите торговать, но без вмешательства в процесс | ✅ | ✅ | # Самые выгодные обмены Source: https://docs.swap.coffee/ru/user-guides/profit Добро пожаловать в мир **обменов** на **swap.coffee**, где каждый обмен - выгодный. *** ## 🌟 Элегантность в каждой транзакции Откройте для себя **swap.coffee** — DEX агрегатор, который переосмысливает процесс обмена криптовалют. Наша платформа — это **симфония технологий**, где каждая транзакция становится шедевром эффективности. *** ## ⚡ Интуитивная мощь **swap.coffee** — это инструмент, который помогает вам принимать оптимальные решения. Мы анализируем множество DEX-ов в реальном времени, чтобы найти для вас идеальный маршрут обмена. > Это как персональный **навигатор в мире криптовалют**, который всегда знает самый быстрый и выгодный путь. *** ## 🚀 Инновационные стратегии обмена Наша платформа использует **две ключевые стратегии**, чтобы максимизировать вашу выгоду: * **💡 Сплит-транзакции** Распределяем ваш обмен между несколькими DEX-ами, минимизируя влияние на цену и максимизируя полученные токены. * **🔗 Мульти-хоп маршруты** Токены проходят через оптимальные промежуточные пары, прежде чем достичь конечной цели, обеспечивая наиболее выгодный обмен. *** ## ✨ Пример магии swap.coffee Допустим, вы хотите обменять **100 $TON на $BOLT**. Вместо простого прямого обмена **swap.coffee** создаст элегантный маршрут: * 🔹 **57.76%** пойдет через `TON > USDT > KINGY > BOLT` * 🔹 **22.43%** обменяется напрямую `TON > BOLT` * 🔹 **11.33%** проследует по маршруту `TON > USDT > BOLT` * 🔹 **8.48%** пройдет через `TON > SCALE > BOLT` > **Сложно?** Красота в том, что вам не нужно об этом беспокоиться. > Мы превращаем сложность в простоту, предоставляя лучший результат одним нажатием кнопки. *** ## 🎁 Больше, чем просто обмен **swap.coffee** предлагает не только эффективные обмены, но и **дополнительные преимущества**: * 💵 **Кешбэк** Получайте вознаграждение за каждую транзакцию. * 🏆 **Торговые конкурсы** Участвуйте в соревнованиях и выигрывайте призы. *** Со **swap.coffee** каждая транзакция становится шагом к более эффективному управлению вашими криптоактивами. Добро пожаловать в мир современных децентрализованных обменов! # Реферальная программа Source: https://docs.swap.coffee/ru/user-guides/referral Добро пожаловать в мир возможностей зарабатывать с реферальной программой **swap.coffee**! Узнайте, как превратить свою активность в реальную выгоду. *** ## 🚀 Приглашайте и зарабатывайте Используйте свою уникальную ссылку, чтобы привлечь друзей в экосистему **swap.coffee**. * 💸 **Преимущество**: С каждой их транзакцией вы получаете часть комиссии. * 📈 **Больше друзей** = **выше доход**. Это просто, прозрачно и выгодно! *** ## 🛠️ Как начать использовать реферальную систему? 1. Перейдите на [swap.coffee/referral](https://swap.coffee/referral). 2. **Подключите свой кошелек**. 3. Найдите кнопку **"Получить реферальную ссылку"** или QR-код. 4. Отправьте ссылку или QR-код вашему другу. 5. Когда друг перейдет по ссылке и подключит свой кошелек, он автоматически станет вашим рефералом. > 💡 **Подсказка**: Чем быстрее вы начнете делиться ссылкой, тем быстрее начнете зарабатывать! *** ## 🏆 Уровни реферальной системы Каждый уровень открывает новые горизонты возможностей: * 🥉 **Бронза** * 🥈 **Серебро** * 🥇 **Золото** С повышением уровня увеличивается процент вознаграждений. *** ## 🔒 Надежность и прозрачность * 🔍 **Контроль**: Отслеживайте свои достижения и доход в реальном времени через личный кабинет. * 🛡️ **Прозрачность**: Каждый обмен вашего реферала находится в вашей таблице в личном кабинете рефералов. *** ## ⚖️ Справедливость — наш приоритет В **swap.coffee** мы верим в честное партнерство: * 💼 **Без скрытых платежей**: Мы делимся прибылью с вами. * 🤝 **Взаимовыгодное сотрудничество**: Никаких дополнительных комиссий. *** ## 🌟 Особые привилегии Если вы лидер мнений или активный участник сообщества, для вас доступны **эксклюзивные условия**: * Свяжитесь с нашим **Community Manager**, чтобы раскрыть весь потенциал вашего участия. *** > **Важно**: Участники, которые уже использовали **swap.coffee**, не могут быть приглашены как рефералы. *** ## ✨ Начните прямо сейчас! Не упустите свой шанс! Станьте частью инновационной реферальной программы уже сегодня и начните путь к финансовому успеху со **swap.coffee**. # Экспертные настройки Source: https://docs.swap.coffee/ru/user-guides/settings Добро пожаловать в раздел **⚙️ Экспертных настроек** **swap.coffee**, где представлены мощные инструменты для **оптимизации обменов**. Эти функции дают вам полный контроль над процессом и помогают достигать лучших результатов. *** ## 🎯 Тонкая настройка обмена Экспертные настройки включают в себя следующие ключевые параметры: ### 📉 Допуск проскальзывания * **Что это?**: Устанавливает диапазон допустимых изменений цены. * **Зачем это нужно?**: Если цена выходит за рамки, **транзакция автоматически отменяется**, чтобы защитить ваши средства. *** ### ⚡ Влияние на цену * **Контроль рынка**: Управляйте тем, насколько сильно ваш обмен может повлиять на рыночную цену. * **Результат**: Снижает риск нежелательных колебаний. *** ### 🔀 Промежуточные токены * **Настройка маршрута**: Укажите максимальное количество промежуточных токенов. * **Важно знать**: Большее количество промежуточных токенов: * Увеличивает расход газа. * Повышает риск получения нежелательного промежуточного токена. *** ### 📊 Волатильность пулов * **Устранение рисков**: Исключите маршруты через пулы с высокой волатильностью. * **Почему это полезно?**: Это добавляет стабильности вашему обмену. *** ### 🔗 Параллельные транзакции * **Масштабирование**: С **W5 кошельком** можно создавать до **20 параллельных транзакций** одновременно. * **Преимущество**: Ускоряет работу и повышает эффективность. *** ## 🚀 Почему это важно? Используя эти настройки, вы сможете достичь **максимальной эффективности** и **точности** при обменах на **swap.coffee**. > 💡 **Совет**: Экспериментируйте с настройками, чтобы найти оптимальный баланс для своих нужд. # Стейкинг Source: https://docs.swap.coffee/ru/user-guides/staking Добро пожаловать в мир **стейкинга** на **swap.coffee**, где каждая инвестиция — это шаг в будущее криптовалют. *** ## 🔍 Что такое стейкинг? **Стейкинг** — это современный способ инвестирования, при котором вы вносите свои средства и получаете за это вознаграждение. На **swap.coffee** мы превратили этот процесс в настоящее искусство. *** ## 🎯 Ваши возможности на **swap.coffee** * **Стейкинг \$CES**: Идеальный выбор для тех, кто ценит стабильность. * **Стейкинг LP токенов (CES/TON)**: Увеличенная доходность с множителем **x2.5** для максимальной выгоды. *** ## 🔐 Гибкость и безопасность * При депозите вы выбираете **один из трёх сроков стейкинга**. Чем больше срок, тем выше ваш множитель поинтов. * Ваши активы всегда находятся в безопасности на смарт-контракте, доступ к которому есть только у вас. *** ## 💎 Поинты: ваш ключ к наградам **Поинты** — это универсальная мера вашего вклада: * Чем больше ваша доля в общем пуле поинтов, тем больше наград вы получаете. * Это справедливое и прозрачное распределение вознаграждений. *** ## 🏆 Разнообразие и простота получения наград Наши **стейкеры** получают щедрые награды в различных токенах. ### ✨ Как получить награды? Все заработанные средства доступны в нашем [Claim Center](https://swap.coffee/claim): * Выбирайте, когда забрать награды. * Копите их или выводите сразу после начисления. *** ## 💡 Стейкинг с **swap.coffee** Стейкинг на **swap.coffee** — это не просто инвестиция, это ваш шаг в **будущее децентрализованных финансов**. Присоединяйтесь к нам и станьте частью криптовалютной революции! # Как свапать? Source: https://docs.swap.coffee/ru/user-guides/swap ## 🚀 1. Подключение кошелька Для начала работы необходимо подключить ваш кошелек к платформе. Это очень просто: 1. Нажмите кнопку **"Подключить кошелек"** в верхнем правом углу экрана. 2. В появившемся окне подтвердите подключение через ваш кошелек. *** ## 💱 2. Выбор токена для обмена После успешного подключения кошелька вы можете выбрать токен для обмена: 1. Нажмите кнопку **"Выберите токен"**. 2. В открывшемся списке найдите нужный токен (для удобства воспользуйтесь строкой поиска). 3. Кликните на выбранный токен. > 💡 **Совет**: Если нужного токена нет в списке, вы можете импортировать его вручную, указав **адрес контракта**. *** ## ✏️ 3. Ввод суммы и подтверждение обмена Теперь, когда токен выбран: 1. Введите сумму, которую хотите обменять. 2. Тщательно проверьте **детали обмена**. 3. Нажмите кнопку **"Обменять"** для подтверждения. > ⚠️ **Важно**: Для совершения транзакций в блокчейне необходима комиссия в **TON**. Убедитесь, что на вашем балансе достаточно средств для её оплаты. *** ## ✅ 4. Подтверждение транзакции После нажатия кнопки **"Обменять"**: * В вашем кошельке появится запрос на подтверждение транзакции. * Внимательно проверьте детали и подтвердите её. *** ## 🎉 5. Завершение обмена Поздравляем! 🎊 Ваша транзакция отправлена в блокчейн. Теперь нужно немного подождать: * Система обработает вашу транзакцию (обычно это занимает **несколько минут**). * После обработки вы увидите уведомление о **успешном обмене**. *** Теперь вы знаете, как легко и быстро свапать токены на **swap.coffee**. Удачных свапов! 🚀 # Мир swap.coffee! 🚀 Source: https://docs.swap.coffee/ru/user-guides/welcome Приветствуем вас в нашем подробном руководстве по использованию **swap.coffee** — инновационной платформы для обмена криптовалют. title *** ## 📖 О чем это руководство? Независимо от того, являетесь ли вы: * **опытным трейдером** — хотите получить максимальную пользу от функционала платформы, * только начинаете свой путь в мире блокчейна `TON`, данная серия гайдов станет вашим надежным помощником. *** > 💡 **Примечание**: Следуйте шагам этого руководства, чтобы узнать, как использовать платформу с максимальной эффективностью. # Yield Aggregator Source: https://docs.swap.coffee/ru/user-guides/yield Представляем вам новый продукт от **swap.coffee** — **Yield Aggregator**. который помогает инвестировать и зарабатывать на всей экосистеме **TON**, не покидая платформу. *** ## ❓Что такое Yield Aggregator? Это сервис для поиска пулов ликвидности, стейкинга, лендингов и других DeFi приложений, которые приносят доход. Мы предлагаем обширный функционал для фильтрации и поиска, позволяя быстро найти лучшие возможности. Управляйте протоколами через **swap.coffee**, где все ваши позиции собраны в одном месте. Забудьте о ручном отслеживании балансов и сравнении доходности — зарабатывайте эффективно, не покидая платформу. *** ## 🛠️ Как пользоваться Yield Aggregator? Сервис состоит из двух основных компонентов: * Списка всех пулов; * Детальной информации о каждом пуле. ### Список всех пулов 1. 🔗 Перейдите в [Yield Aggregator](https://swap.coffee/earn). 2. 👛 Подключите кошелек, что бы мы отобразили подробную информацию о ваших средствах в пулах; 3. 📑 После подключения кошелька вам будет доступно две вкладки: * Общий список пулов; * Список пулов, где у вас лежит ликвидность. 4. 🔍 Воспользуйтесь фильтром и сортировкой в верхней части таблицы, что бы отобразить актуальные пулы: * Выберите интересующие протоколы через иконку фильтра; * Введите название токена, его адрес или адрес пары в поле **поиска**; * Примените **сортировку**, чтобы найти лучший пул по доходности, объёму ликвидности или другим параметрам; * Используйте фильтр по **бустам**, чтобы отобразить пулы с дополнительными наградами. ### Информация о пуле 1. 📊 Перейдите в выбранный пул, чтобы увидеть основную информацию, вашу позицию и доход; 2. ⭐ **Yield Aggregator** отображает данные о фарминге, которые начисляет протокол; 3. 🚀 Взаимодействуйте с пулом и его бустами. Добавляйте ликвидность, собирайте награды за фарминг: * ✍️ Подключите кошелёк и заполните поля; * ✅ Подтвердите и отправьте транзакцию; * ⏳ Дождитесь завершения транзакции. *** ## 💡 Преимущества Yield Aggregator * **Удобство**: Управляйте всеми DeFi-позициями в одном месте; * **Прозрачность**: Получайте полную информацию о доходности и позициях; * **Гибкость**: Фильтруйте и сортируйте пулы для поиска лучших возможностей; * **Бусты**: Используйте дополнительные награды для увеличения дохода. # WhitePaper Source: https://docs.swap.coffee/ru/white Последнее обновление: 27.11.2024 # Введение **swap.coffee** — это инновационный DEX-агрегатор и децентрализованная биржа (DEX), объединяющая ликвидность как с различных децентрализованных бирж, так и с пулов ликвидности, что позволяет пользователям совершать свопы криптовалют с наилучшими возможными условиями. Платформа использует передовые технологии для обеспечения безопасных и выгодных сделок, предоставляя пользователям доступ к широкому спектру возможностей без необходимости в централизованных посредниках. На современном криптовалютном рынке ликвидность часто распределена между множеством децентрализованных бирж и пулов ликвидности, что затрудняет пользователям нахождение лучших цен для обмена активов. **swap.coffee** решает эту проблему, предлагая агрегированную ликвидность, которая помогает получать оптимальные условия для каждой сделки. Наш продвинутый алгоритм роутинга и сплит транзакций не только автоматически разбивает крупные сделки на несколько частей, минимизируя затраты на газ, но и строит маршруты с использованием промежуточных пулов ликвидности, что позволяет обеспечивать наилучшие курсы для пользователей. Платформа также внедряет дополнительные возможности, такие как лимитные ордера, позволяющие пользователям задавать конкретные ценовые уровни для выполнения сделок, и встроенный RFQ-протокол, который поставляет ликвидность с централизованных бирж (CEX). Это позволяет пользователям значительно экономить на газе и получать более выгодные курсы обмена по сравнению с другими платформами. Наряду с этим, **swap.coffee** поддерживает стратегии DCA (Dollar Cost Averaging) и VA (Value Averaging), предоставляя пользователям инструменты для автоматизированного управления инвестициями и минимизации риска, связанного с волатильностью криптовалютных рынков. Платформа не взимает дополнительных комиссий, что делает её одной из наиболее выгодных для трейдеров всех уровней. **swap.coffee** стремится стать ведущим решением для децентрализованного обмена криптовалют, обеспечивая пользователям удобный, безопасный и экономичный способ управления своими цифровыми активами. # Миссия Миссия **swap.coffee** заключается в создании универсальной, децентрализованной платформы для торговли криптоактивами, которая бы обеспечивала безопасность, прозрачность и доступность для всех пользователей. Наш подход особенно актуален в контексте экосистемы блокчейна TON, который находится на этапе активного развития и расширения. Блокчейн TON предлагает огромный потенциал для роста и инноваций, но, как и любая новая технология, сталкивается с рядом вызовов, таких как низкая ликвидность, ограниченные торговые возможности и необходимость построения инфраструктуры для активного использования криптовалюты. **swap.coffee** стремится решить эти проблемы, предоставляя мощные инструменты для обмена активами и управления инвестициями, которые станут фундаментом для торговли в сети TON. Мы активно работаем над созданием и развитием API для взаимодействия с блокчейном TON в сфере торгов. Это позволяет разработчикам и проектам легко интегрировать функционал нашей платформы, предоставляя доступ к ликвидности и инструментам обмена активами. Таким образом, мы закладываем основу для формирования полноценной торговой экосистемы, что крайне важно для дальнейшего роста и привлечения новых пользователей в сеть TON. **swap.coffee** видит свою роль как одного из пионеров в развитии децентрализованных финансов (DeFi) на блокчейне TON. Наша платформа агрегирует ликвидность с различных децентрализованных бирж и пулов ликвидности, предоставляя пользователям доступ к наилучшим условиям для обмена активов. Это особенно важно в условиях молодой и растущей экосистемы, где наличие ликвидности критично для роста и привлечения новых участников. Наша миссия — не просто создать платформу для обмена активами, но стать двигателем развития экосистемы TON, привлекая новых пользователей, создавая инструменты для торговли и обеспечивая полноценную инфраструктуру для интеграции с блокчейном TON через наши API. # Обзор рынка ## Развитие DEX и DEX-агрегаторов ### Децентрализованные биржи (DEX) В последние годы децентрализованные биржи (DEX) стали важной частью криптовалютной экосистемы, предлагая пользователям возможность торговать активами напрямую друг с другом без необходимости в централизованных посредниках. Это обеспечивает повышенный уровень безопасности, а также контроль над активами, что особенно важно в условиях растущей озабоченности по поводу конфиденциальности и киберугроз. По данным Messari, объем торгов на DEX в 2022 году превысил \$1 трлн, что стало значительным ростом по сравнению с предыдущими годами. Этот рост был обусловлен несколькими факторами, включая переход пользователей к децентрализованным решениям после многочисленных инцидентов взломов на централизованных биржах, а также усиливающееся регулирование со стороны государств. DEX предлагают пользователям прозрачные условия торговли, где каждый может контролировать свои средства через смарт-контракты, исключая необходимость доверия третьей стороне. Такие платформы, как Uniswap и SushiSwap, показали, что децентрализованная торговля может быть не только эффективной, но и конкурентоспособной с точки зрения ликвидности и скорости исполнения ордеров. ### Агрегаторы DEX С увеличением числа децентрализованных бирж появилась необходимость в агрегаторах, которые могут предложить пользователям доступ к лучшим условиям торговли, собирая ликвидность с различных DEX. Агрегаторы DEX, такие как 1inch и Paraswap, предоставляют пользователям возможность получить лучшие цены, минимизируя разницу в курсах между биржами и снижая общие издержки на сделку. Согласно данным Dune Analytics, агрегаторы DEX играют ключевую роль в росте объема торгов и увеличении ликвидности на рынке. В 2023 году более 25% всех транзакций на DEX прошли через агрегаторы, что подчеркивает важность этих платформ для пользователей, стремящихся оптимизировать свои торговые операции. Агрегаторы используют продвинутые алгоритмы для роутинга транзакций, которые позволяют автоматически находить лучшие маршруты для свопов, часто разбивая сделки на несколько частей и распределяя их между различными пулами ликвидности. Это не только помогает пользователям экономить на газе, но и обеспечивает наилучшие курсы обмена, что делает агрегаторы крайне востребованными среди профессиональных трейдеров и розничных инвесторов. ### Анализ рынка ончейн лимитных сделок и торговых стратегий Ончейн лимитные ордера стали неотъемлемой частью децентрализованных финансов (DeFi) и предоставляют пользователям мощные инструменты для более точного контроля своих сделок. Лимитные ордера позволяют трейдерам размещать сделки с заранее установленными ценами, что дает возможность торговать активами только по оптимальной цене, избежав потенциальных убытков от нежелательных колебаний курса. По данным Binance Research, лимитные ордера становятся все более популярными среди профессиональных трейдеров, которые стремятся использовать точные ценовые ориентиры для минимизации рисков. Исследования показывают, что трейдеры, использующие лимитные ордера, достигают на 20% лучших результатов по сравнению с теми, кто торгует исключительно по рыночным ордерам, особенно в условиях высокой волатильности. Кроме того, лимитные ордера, построенные на смарт-контрактах, обеспечивают полную прозрачность и доверие между участниками, исключая необходимость в централизованных посредниках. Это стало особенно важным на фоне роста интереса к DeFi и децентрализованной торговле, где пользователи стремятся получить полный контроль над своими активами. В рамках DEX-агрегаторов, таких как **swap.coffee**, внедрение ончейн лимитных ордеров с поддержкой RFQ-протоколов, которые предоставляют ликвидность с централизованных бирж (CEX), позволяет пользователям не только получать выгодные курсы, но и экономить на затратах на газ. По данным CryptoCompare, такие протоколы могут снизить общие издержки на 15-25%, что делает их особенно полезными для крупных сделок. ### Торговые стратегии DCA и VA Помимо лимитных ордеров, популярными среди криптовалютных трейдеров остаются стратегии DCA (Dollar Cost Averaging) и VA (Value Averaging). Эти стратегии особенно актуальны для долгосрочных инвесторов, которые стремятся минимизировать риск за счет регулярных покупок или регулирования объема инвестиций в зависимости от состояния рынка. Согласно исследованию Arcane Research, более 60% криптовалютных инвесторов используют стратегии DCA для минимизации волатильности. В условиях нестабильных рынков DCA позволяет усреднять цену покупки, снижая риск того, что актив будет куплен на пике его стоимости. Для опытных трейдеров стратегия VA, которая фокусируется на достижении определенной цели по стоимости портфеля, может приносить на 10-15% больше прибыли в долгосрочной перспективе, чем традиционные подходы. Использование DCA и VA на платформе **swap.coffee** дает пользователям гибкость в управлении своими инвестициями и позволяет более эффективно минимизировать риски и повышать доходность в условиях нестабильного криптовалютного рынка. # Целевая аудитория **swap.coffee** разработан с учетом потребностей разных категорий пользователей, включая начинающих криптоинвесторов, крупных трейдеров (китов), разработчиков, инфлюенсеров и криптопроекты. Наша платформа предлагает каждому из этих сегментов уникальные инструменты и возможности, способствуя их успешной деятельности в экосистеме блокчейна TON. ### Начинающие криптоинвесторы Для тех, кто только начинает свой путь в мире криптовалют, платформа **swap.coffee** предлагает интуитивно понятный и безопасный интерфейс для торговли. Начинающие пользователи могут избежать сложностей, связанных с волатильностью и сложными интерфейсами, благодаря продвинутым инструментам для снижения рисков. **swap.coffee** помогает начинающим инвесторам за счет: * **Простоты использования:** Удобный интерфейс делает обмен активов доступным без необходимости изучать сложные инструменты. * **Безопасности:** Полностью децентрализованная платформа обеспечивает безопасность и прозрачность через смарт-контракты. * **Торговых стратегий:** DCA (Dollar Cost Averaging) и VA (Value Averaging) позволяют минимизировать риски волатильности, автоматически усредняя покупки или регулировку объемов. ### Киты (крупные трейдеры) Для крупных трейдеров, управляющих большими объемами активов, важны ликвидность и минимальные комиссии. **swap.coffee** предлагает идеальные условия для китов благодаря глубокому рынку и эффективным механизмам торговли. **swap.coffee** предлагает китам: * **Глубокую ликвидность:** Агрегация ликвидности с различных DEX и пулов позволяет совершать крупные сделки с минимальным воздействием на цену. * **Экономия на комиссиях:** Сплит транзакции и роутинг через промежуточные пулы ликвидности минимизируют затраты на газ. * **Ончейн лимитные ордера с RFQ-протоколом:** Лимитные ордера с доступом к ликвидности CEX через RFQ-протокол обеспечивают выгодные цены. ### Разработчики **swap.coffee** предоставляет разработчикам мощные API для интеграции торговых решений на базе блокчейна TON. Это дает разработчикам возможность использовать ликвидность и торговые инструменты платформы для построения своих продуктов. **swap.coffee** предлагает разработчикам: * **Набор API:** Наши API предоставляют доступ к агрегированной ликвидности, лимитным ордерам, DCA/VA стратегиям и другим торговым решениям. * **Гибкость интеграции:** Высокая степень кастомизации позволяет разработчикам легко внедрять наши инструменты в свои проекты. * **Поддержка DeFi:** **swap.coffee** помогает строить приложения на основе DeFi, предоставляя мощные инструменты для управления ликвидностью и торговли. ### Инфлюенсеры Инфлюенсеры играют важную роль в привлечении новых пользователей к платформе, и **swap.coffee** предоставляет им возможности для дополнительного заработка через реферальную программу. Благодаря своей аудитории, инфлюенсеры могут активно продвигать платформу и получать вознаграждения от оборота привлеченных пользователей. **swap.coffee** предлагает инфлюенсерам: * **Реферальная система:** Инфлюенсеры могут зарабатывать процент от торгового оборота привлеченных пользователей, монетизируя свою аудиторию. * **Простота продвижения:** Прозрачная и безопасная платформа делает **swap.coffee** привлекательной для их подписчиков, что повышает доверие и конверсию. ### Криптопроекты Криптопроекты могут использовать **swap.coffee** для проведения маркетинговых кампаний, таких как торговые конкурсы и кешбеки. Это позволяет проектам более эффективно привлекать пользователей и стимулировать активную торговлю, укрепляя свою экосистему. **swap.coffee** предлагает криптопроектам: * **Маркетинговые инструменты:** Кешбеки и торговые конкурсы помогают активизировать торговлю и вовлекать пользователей в процесс взаимодействия с их токенами. * **Повышение ликвидности:** Участие в нашей экосистеме предоставляет проекты доступ к агрегированной ликвидности, что помогает увеличить объемы торгов и обеспечить устойчивый рост. ### Почему swap.coffee важен для всех сегментов? **swap.coffee** предоставляет различные инструменты и возможности для удовлетворения потребностей каждого сегмента: * **Для начинающих:** Простой интерфейс, безопасные сделки и стратегии для снижения рисков помогают новым пользователям уверенно торговать. * **Для китов:** Высокая ликвидность и низкие комиссии обеспечивают эффективную торговлю большими объемами активов. * **Для разработчиков:** Наши API и гибкость платформы позволяют создавать сложные DeFi-решения с доступом к ликвидности и продвинутым торговым инструментам. * **Для инфлюенсеров:** Реферальная программа предоставляет возможность монетизировать аудиторию, привлекая новых пользователей. * **Для криптопроектов:** Кешбеки и торговые конкурсы позволяют проектам эффективно проводить маркетинговые кампании и увеличивать ликвидность их токенов. **swap.coffee** — это платформа, созданная для пользователей с разными уровнями опыта и целей, предоставляющая инструменты для эффективной торговли и продвижения криптоактивов в рамках блокчейна TON. # Токен CES Токен **CES** является ключевым элементом экосистемы **swap.coffee**, предлагая пользователям широкий спектр преимуществ и возможностей. Он служит не только средством взаимодействия внутри платформы, но и важным инструментом для стимулирования роста и привлечения новых пользователей и разработчиков через различные программы. ### Преимущества использования токена CES 1. **Пониженные комиссии** Держатели токена **CES** могут оплачивать комиссии на платформе по сниженным ставкам. Это позволяет пользователям экономить при проведении сделок и получать более выгодные условия торговли. * **Снижение комиссии:** Держатели **CES** получают возможность оплачивать комиссию с существенными скидками, что делает сделки более выгодными и снижает затраты. 2. **Стейкинг токенов** Пользователи **swap.coffee** могут стейкать токены **CES** и получать за это вознаграждения. Стейкинг стимулирует долгосрочное удержание токенов и участие в экосистеме. * **Вознаграждения за стейкинг:** Держатели токенов, которые участвуют в стейкинге, получают периодические вознаграждения, что стимулирует их продолжительное участие в экосистеме. 3. **Ранний доступ к инструментам** Держатели **CES** получают эксклюзивный ранний доступ к новым инструментам и функциям платформы **swap.coffee**. * **Эксклюзивный доступ:** **CES** дает приоритетный доступ к новым торговым инструментам и функциям, что позволяет держателям **CES** первыми использовать инновационные решения платформы. ### Использование CES для развития платформы Токен **CES** также используется как важный инструмент для продвижения **swap.coffee** через ряд программ, направленных на привлечение пользователей и разработчиков: 1. **Маркетинговые кампании** **CES** играет важную роль в проведении маркетинговых кампаний платформы. 2. **Амбассадорская программа** **swap.coffee** активно использует токены **CES** в рамках амбассадорской программы. 3. **Программа грантов** **swap.coffee** поддерживает разработчиков, предлагая им гранты в токенах **CES** для создания новых решений и интеграций на основе блокчейна TON. ### Ценность CES для экосистемы swap.coffee Токен **CES** играет важную роль в поддержке и развитии всей экосистемы **swap.coffee**. Он стимулирует активность пользователей, привлекает новых разработчиков через грантовую программу и усиливает маркетинговые усилия платформы. * **Активность пользователей:** Программы стейкинга, маркетинговых кампаний и амбассадорская программа стимулируют пользователей к долгосрочному участию и активной торговле. * **Привлечение разработчиков:** Грантовая программа поддерживает создание новых решений, что увеличивает ценность платформы и расширяет её функционал. * **Рост сообщества:** Токен **CES** играет ключевую роль в развитии сообщества **swap.coffee**, поддерживая его активное участие и развитие экосистемы. ### Токеномика title # Компоненты 1. **DEX-агрегатор** — собирает ликвидность с различных децентрализованных бирж и пулов ликвидности для предоставления лучших курсов обмена. 2. **DEX** — полноценная децентрализованная биржа, позволяющая пользователям торговать криптоактивами напрямую друг с другом без участия посредников. 3. **Ликвидность с CEX (централизованные биржи)** — поставляется только в лимитные ордера через RFQ-протокол, что обеспечивает более выгодные курсы и экономию на газе для пользователей, использующих лимитные ордера. 4. **Пулы ликвидности** — внутренние и внешние пулы, используемые для улучшения ликвидности и оптимизации торговых маршрутов на платформе. 5. **Ончейн лимитные ордера** — позволяют пользователям выставлять сделки по фиксированным ценам, с доступом к ликвидности CEX через RFQ-протокол для получения лучших условий. 6. **Стратегии DCA (Dollar Cost Averaging) и VA (Value Averaging)** — инструменты для автоматизации инвестиционных стратегий, снижения рисков и улучшения доходности в условиях волатильности. 7. **Стейкинг токенов CES** — пользователи могут стейкать **CES** для получения вознаграждений и доступа к дополнительным привилегиям. 8. **Токен CES** — используется для снижения комиссий на платформе, стейкинга, получения раннего доступа к инструментам, а также для участия в маркетинговых кампаниях, амбассадорской программе и программе грантов. 9. **API-интеграции** — предоставляют разработчикам доступ к функционалу платформы для создания собственных решений и продуктов на основе блокчейна TON. 10. **Реферальная программа** — пользователи, включая инфлюенсеров, могут зарабатывать процент от оборота привлеченных пользователей, что стимулирует рост сообщества. 11. **Торговые конкурсы и кешбеки** — используются криптопроектами для проведения активных маркетинговых кампаний на платформе, стимулируя торговлю и повышая ликвидность. 12. **Клейм центр** — это компонент платформы, который позволяет пользователям клеймить свои награды, такие как вознаграждения за стейкинг, маркетинговые кампании и аирдропы. 13. **Профиль пользователя** — это компонент, который позволяет пользователям анализировать свой кошелек, отслеживать историю торговых сделок, рассчитывать выгоду по сделкам и управлять своими фарм-позициями. # Create new auth token Source: https://docs.swap.coffee/technical-guides/aggregator-api-openapi/auth/create-new-auth-token https://backend.swap.coffee/openapi post /v1/auth # Delete existing auth token Source: https://docs.swap.coffee/technical-guides/aggregator-api-openapi/auth/delete-existing-auth-token https://backend.swap.coffee/openapi delete /v1/auth # Edit existing auth token Source: https://docs.swap.coffee/technical-guides/aggregator-api-openapi/auth/edit-existing-auth-token https://backend.swap.coffee/openapi patch /v1/auth # List existing auth tokens Source: https://docs.swap.coffee/technical-guides/aggregator-api-openapi/auth/list-existing-auth-tokens https://backend.swap.coffee/openapi get /v1/auth # Build transaction to close farm position in stonfi Source: https://docs.swap.coffee/technical-guides/aggregator-api-openapi/boosts/build-transaction-to-close-farm-position-in-stonfi https://backend.swap.coffee/openapi delete /v1/boost/stonfi/{pool_address}/{position_address}/{user_address} # Build transaction to create boost for pool in swap.coffee DEX Source: https://docs.swap.coffee/technical-guides/aggregator-api-openapi/boosts/build-transaction-to-create-boost-for-pool-in-swapcoffee-dex https://backend.swap.coffee/openapi post /v1/boost/{pool_address}/{address} # Build transaction to create stonfi farm position Source: https://docs.swap.coffee/technical-guides/aggregator-api-openapi/boosts/build-transaction-to-create-stonfi-farm-position https://backend.swap.coffee/openapi post /v1/boost/stonfi/{pool_address}/{user_address} # Get detailed info about boost. Works for Coffee DEX pools only Source: https://docs.swap.coffee/technical-guides/aggregator-api-openapi/boosts/get-detailed-info-about-boost-works-for-coffee-dex-pools-only https://backend.swap.coffee/openapi get /v1/boost/{boost_factory}/{boost_id} # Returns list of boosts for the pool Source: https://docs.swap.coffee/technical-guides/aggregator-api-openapi/boosts/returns-list-of-boosts-for-the-pool https://backend.swap.coffee/openapi get /v1/boost/{pool_address} # Returns pool's aggregated APR Source: https://docs.swap.coffee/technical-guides/aggregator-api-openapi/boosts/returns-pools-aggregated-apr https://backend.swap.coffee/openapi get /v1/boost/{pool_address}/apr # Returns status of new boost creation operation. Works for Coffee DEX pools only Source: https://docs.swap.coffee/technical-guides/aggregator-api-openapi/boosts/returns-status-of-new-boost-creation-operation-works-for-coffee-dex-pools-only https://backend.swap.coffee/openapi get /v1/boost/result # Returns user's earned boosts in given pool Source: https://docs.swap.coffee/technical-guides/aggregator-api-openapi/boosts/returns-users-earned-boosts-in-given-pool https://backend.swap.coffee/openapi get /v1/boost/user/{pool_address}/{user_address} # Create new cashback distribution. For internal usage only Source: https://docs.swap.coffee/technical-guides/aggregator-api-openapi/cashback/create-new-cashback-distribution-for-internal-usage-only https://backend.swap.coffee/openapi post /v1/cashback/ # Get cashback info Source: https://docs.swap.coffee/technical-guides/aggregator-api-openapi/cashback/get-cashback-info https://backend.swap.coffee/openapi get /v1/cashback/{id} # Get cashback promos rewards for user Source: https://docs.swap.coffee/technical-guides/aggregator-api-openapi/cashback/get-cashback-promos-rewards-for-user https://backend.swap.coffee/openapi get /v1/cashback/user/{address}/list # Get cashback total info for user Source: https://docs.swap.coffee/technical-guides/aggregator-api-openapi/cashback/get-cashback-total-info-for-user https://backend.swap.coffee/openapi get /v1/cashback/user/{address} # Get cashbacks info Source: https://docs.swap.coffee/technical-guides/aggregator-api-openapi/cashback/get-cashbacks-info https://backend.swap.coffee/openapi get /v1/cashback/ # Update cashback information. For internal usage only Source: https://docs.swap.coffee/technical-guides/aggregator-api-openapi/cashback/update-cashback-information-for-internal-usage-only https://backend.swap.coffee/openapi patch /v1/cashback/{id} # Claim tokens Source: https://docs.swap.coffee/technical-guides/aggregator-api-openapi/claim/claim-tokens https://backend.swap.coffee/openapi post /v1/claim/{address} # Get account's claiming stats Source: https://docs.swap.coffee/technical-guides/aggregator-api-openapi/claim/get-accounts-claiming-stats https://backend.swap.coffee/openapi get /v1/claim/{address} # Get claiming transaction execution result Source: https://docs.swap.coffee/technical-guides/aggregator-api-openapi/claim/get-claiming-transaction-execution-result https://backend.swap.coffee/openapi get /v1/claim/result # Get state of account claimings Source: https://docs.swap.coffee/technical-guides/aggregator-api-openapi/claim/get-state-of-account-claimings https://backend.swap.coffee/openapi get /v1/claim/{address}/state # Transfer available in claim-center tokens from one account to another. For internal usage only Source: https://docs.swap.coffee/technical-guides/aggregator-api-openapi/claim/transfer-available-in-claim-center-tokens-from-one-account-to-another-for-internal-usage-only https://backend.swap.coffee/openapi post /v1/claim/transfer # Create new contest. For internal usage only Source: https://docs.swap.coffee/technical-guides/aggregator-api-openapi/contests/create-new-contest-for-internal-usage-only https://backend.swap.coffee/openapi post /v1/contests # Get contest Source: https://docs.swap.coffee/technical-guides/aggregator-api-openapi/contests/get-contest https://backend.swap.coffee/openapi get /v1/contests/{id} # Get contests Source: https://docs.swap.coffee/technical-guides/aggregator-api-openapi/contests/get-contests https://backend.swap.coffee/openapi get /v1/contests # Get top users' stats for contest Source: https://docs.swap.coffee/technical-guides/aggregator-api-openapi/contests/get-top-users-stats-for-contest https://backend.swap.coffee/openapi get /v1/contests/{id}/top # Get user stats for contest Source: https://docs.swap.coffee/technical-guides/aggregator-api-openapi/contests/get-user-stats-for-contest https://backend.swap.coffee/openapi get /v1/contests/{id}/user/{address} # Payout rewards for this contest in token. For internal usage only Source: https://docs.swap.coffee/technical-guides/aggregator-api-openapi/contests/payout-rewards-for-this-contest-in-token-for-internal-usage-only https://backend.swap.coffee/openapi post /v1/contests/{id}/payout/token # Update existing contest. For internal usage only Source: https://docs.swap.coffee/technical-guides/aggregator-api-openapi/contests/update-existing-contest-for-internal-usage-only https://backend.swap.coffee/openapi patch /v1/contests/{id} # Build transaction to create vault for the given asset Source: https://docs.swap.coffee/technical-guides/aggregator-api-openapi/dex/build-transaction-to-create-vault-for-the-given-asset https://backend.swap.coffee/openapi post /v1/dex/vault/{asset} # Build transactions to create pool of the given asset pair Source: https://docs.swap.coffee/technical-guides/aggregator-api-openapi/dex/build-transactions-to-create-pool-of-the-given-asset-pair https://backend.swap.coffee/openapi post /v1/dex/pool # Get address of the vault of the given asset Source: https://docs.swap.coffee/technical-guides/aggregator-api-openapi/dex/get-address-of-the-vault-of-the-given-asset https://backend.swap.coffee/openapi get /v1/dex/vault/{asset} # Get dex pools by filter Source: https://docs.swap.coffee/technical-guides/aggregator-api-openapi/dex/get-dex-pools-by-filter https://backend.swap.coffee/openapi get /v1/dex/pools # Clear pools metadata cache. For internal usage only Source: https://docs.swap.coffee/technical-guides/aggregator-api-openapi/entity/clear-pools-metadata-cache-for-internal-usage-only https://backend.swap.coffee/openapi delete /v1/pools # Get supported blockchains. Currently only TON is supported. Source: https://docs.swap.coffee/technical-guides/aggregator-api-openapi/entity/get-supported-blockchains-currently-only-ton-is-supported https://backend.swap.coffee/openapi get /v1/blockchains # Returns information about the given decentralized exchange for the given blockchain Source: https://docs.swap.coffee/technical-guides/aggregator-api-openapi/entity/returns-information-about-the-given-decentralized-exchange-for-the-given-blockchain https://backend.swap.coffee/openapi get /v1/dex/{blockchain}/{name} # Returns information about the given liquidity pool for the given blockchain Source: https://docs.swap.coffee/technical-guides/aggregator-api-openapi/entity/returns-information-about-the-given-liquidity-pool-for-the-given-blockchain https://backend.swap.coffee/openapi get /v1/pool/{blockchain}/{address} # Returns information about the given token by its symbol for the given blockchain Source: https://docs.swap.coffee/technical-guides/aggregator-api-openapi/entity/returns-information-about-the-given-token-by-its-symbol-for-the-given-blockchain https://backend.swap.coffee/openapi get /v1/token/{blockchain}/by-symbol/{symbol} # Returns information about the given token for the given blockchain Source: https://docs.swap.coffee/technical-guides/aggregator-api-openapi/entity/returns-information-about-the-given-token-for-the-given-blockchain https://backend.swap.coffee/openapi get /v1/token/{blockchain}/{address} # Returns list of liquid staking pools Source: https://docs.swap.coffee/technical-guides/aggregator-api-openapi/entity/returns-list-of-liquid-staking-pools https://backend.swap.coffee/openapi get /v1/liquid_staking_pools # Returns list of pools associated with given token Source: https://docs.swap.coffee/technical-guides/aggregator-api-openapi/entity/returns-list-of-pools-associated-with-given-token https://backend.swap.coffee/openapi get /v1/pool/{blockchain}/by-token/{address} # Returns list of pools which correspond to the given params Source: https://docs.swap.coffee/technical-guides/aggregator-api-openapi/entity/returns-list-of-pools-which-correspond-to-the-given-params https://backend.swap.coffee/openapi get /v1/pools # Returns list of supported decentralized exchanges supported by the service in the given blockchain Source: https://docs.swap.coffee/technical-guides/aggregator-api-openapi/entity/returns-list-of-supported-decentralized-exchanges-supported-by-the-service-in-the-given-blockchain https://backend.swap.coffee/openapi get /v1/dexes # Returns list of tokens supported by the service Source: https://docs.swap.coffee/technical-guides/aggregator-api-openapi/entity/returns-list-of-tokens-supported-by-the-service https://backend.swap.coffee/openapi get /v1/tokens # Returns list of tokens supported by the service Source: https://docs.swap.coffee/technical-guides/aggregator-api-openapi/entity/returns-list-of-tokens-supported-by-the-service-1 https://backend.swap.coffee/openapi get /v2/tokens # Returns prices for given tokens Source: https://docs.swap.coffee/technical-guides/aggregator-api-openapi/entity/returns-prices-for-given-tokens https://backend.swap.coffee/openapi post /v1/token/price # Returns staking pool for given address Source: https://docs.swap.coffee/technical-guides/aggregator-api-openapi/entity/returns-staking-pool-for-given-address https://backend.swap.coffee/openapi get /v1/liquid_staking_pools/{address} # Returns trading metrics for pools Source: https://docs.swap.coffee/technical-guides/aggregator-api-openapi/entity/returns-trading-metrics-for-pools https://backend.swap.coffee/openapi get /v1/pools/metrics # Updates pool's data. For internal usage only Source: https://docs.swap.coffee/technical-guides/aggregator-api-openapi/entity/updates-pools-data-for-internal-usage-only https://backend.swap.coffee/openapi post /v1/pool/{blockchain}/{address} # Build transaction to migrate LP to swap.coffee DEX Source: https://docs.swap.coffee/technical-guides/aggregator-api-openapi/liquidityprovisioning/build-transaction-to-migrate-lp-to-swapcoffee-dex https://backend.swap.coffee/openapi post /v1/liquidity/migration/{user_address} # Build transaction to withdraw liquidity from the given pool Source: https://docs.swap.coffee/technical-guides/aggregator-api-openapi/liquidityprovisioning/build-transaction-to-withdraw-liquidity-from-the-given-pool https://backend.swap.coffee/openapi delete /v1/liquidity/provision/{address} # Build transactions to provide liquidity to the given pool Source: https://docs.swap.coffee/technical-guides/aggregator-api-openapi/liquidityprovisioning/build-transactions-to-provide-liquidity-to-the-given-pool https://backend.swap.coffee/openapi post /v1/liquidity/provision/{address} # Return information about user's LP position in pool Source: https://docs.swap.coffee/technical-guides/aggregator-api-openapi/liquidityprovisioning/return-information-about-users-lp-position-in-pool https://backend.swap.coffee/openapi get /v1/liquidity/position/{pool_address}/{user_address} # Returns list of pools from which user may migrate tokens Source: https://docs.swap.coffee/technical-guides/aggregator-api-openapi/liquidityprovisioning/returns-list-of-pools-from-which-user-may-migrate-tokens https://backend.swap.coffee/openapi get /v1/liquidity/migration/{user_address} # Returns list of pools that are possible for migration of LP. Source: https://docs.swap.coffee/technical-guides/aggregator-api-openapi/liquidityprovisioning/returns-list-of-pools-that-are-possible-for-migration-of-lp https://backend.swap.coffee/openapi get /v1/liquidity/migration/pools/{source_pool_address} # Returns pool total supply Source: https://docs.swap.coffee/technical-guides/aggregator-api-openapi/liquidityprovisioning/returns-pool-total-supply https://backend.swap.coffee/openapi get /v1/liquidity/{pool_address}/total-supply # Returns pools on Coffee DEX that correspond to the pools of provided addresses Source: https://docs.swap.coffee/technical-guides/aggregator-api-openapi/liquidityprovisioning/returns-pools-on-coffee-dex-that-correspond-to-the-pools-of-provided-addresses https://backend.swap.coffee/openapi get /v1/liquidity/migration/corresponding-pools # Returns status of liquidity provisioning operation Source: https://docs.swap.coffee/technical-guides/aggregator-api-openapi/liquidityprovisioning/returns-status-of-liquidity-provisioning-operation https://backend.swap.coffee/openapi get /v1/liquidity/result # Accrue token to claim center. Requires associated x-api-key. Source: https://docs.swap.coffee/technical-guides/aggregator-api-openapi/partnership/accrue-token-to-claim-center-requires-associated-x-api-key https://backend.swap.coffee/openapi post /v1/partnership/claiming/accrue # Delete partner settings. For internal usage only Source: https://docs.swap.coffee/technical-guides/aggregator-api-openapi/partnership/delete-partner-settings-for-internal-usage-only https://backend.swap.coffee/openapi delete /v1/partnership/{address}/settings # Get aggregated information about staking for specific user. Requires associated x-api-key. Source: https://docs.swap.coffee/technical-guides/aggregator-api-openapi/partnership/get-aggregated-information-about-staking-for-specific-user-requires-associated-x-api-key https://backend.swap.coffee/openapi get /v1/partnership/staking/{master_address}/{address} # Get partner settings. For internal usage only Source: https://docs.swap.coffee/technical-guides/aggregator-api-openapi/partnership/get-partner-settings-for-internal-usage-only https://backend.swap.coffee/openapi get /v1/partnership/{address}/settings # Get raw transaction records with specified partner's referral address. Requires associated x-api-key. Source: https://docs.swap.coffee/technical-guides/aggregator-api-openapi/partnership/get-raw-transaction-records-with-specified-partners-referral-address-requires-associated-x-api-key https://backend.swap.coffee/openapi get /v1/partnership/{address}/transactions # Get token claiming global stats. Requires associated x-api-key. Source: https://docs.swap.coffee/technical-guides/aggregator-api-openapi/partnership/get-token-claiming-global-stats-requires-associated-x-api-key https://backend.swap.coffee/openapi get /v1/partnership/claiming/stats/{token} # Get token claiming user stats. Requires associated x-api-key. Source: https://docs.swap.coffee/technical-guides/aggregator-api-openapi/partnership/get-token-claiming-user-stats-requires-associated-x-api-key https://backend.swap.coffee/openapi get /v1/partnership/claiming/stats/{token}/{address} # Increase total amount of existing partner token within claiming center. For internal usage only. Source: https://docs.swap.coffee/technical-guides/aggregator-api-openapi/partnership/increase-total-amount-of-existing-partner-token-within-claiming-center-for-internal-usage-only https://backend.swap.coffee/openapi patch /v1/partnership/claiming # Register new partner token for claiming center. For internal usage only. Source: https://docs.swap.coffee/technical-guides/aggregator-api-openapi/partnership/register-new-partner-token-for-claiming-center-for-internal-usage-only https://backend.swap.coffee/openapi post /v1/partnership/claiming # Set partner settings. For internal usage only Source: https://docs.swap.coffee/technical-guides/aggregator-api-openapi/partnership/set-partner-settings-for-internal-usage-only https://backend.swap.coffee/openapi post /v1/partnership/{address}/settings # Get account settings Source: https://docs.swap.coffee/technical-guides/aggregator-api-openapi/profile/get-account-settings https://backend.swap.coffee/openapi get /v1/profile/{address}/settings # Get historical account transactions on swap.coffee Source: https://docs.swap.coffee/technical-guides/aggregator-api-openapi/profile/get-historical-account-transactions-on-swapcoffee https://backend.swap.coffee/openapi get /v1/profile/{address}/transactions # Update account settings Source: https://docs.swap.coffee/technical-guides/aggregator-api-openapi/profile/update-account-settings https://backend.swap.coffee/openapi post /v1/profile/{address}/settings # Validate TON proof for given account address Source: https://docs.swap.coffee/technical-guides/aggregator-api-openapi/profile/validate-ton-proof-for-given-account-address https://backend.swap.coffee/openapi post /v1/profile/{address}/proof # Bind new referral Source: https://docs.swap.coffee/technical-guides/aggregator-api-openapi/referral/bind-new-referral https://backend.swap.coffee/openapi post /v1/referral/{address} # Delete address alias Source: https://docs.swap.coffee/technical-guides/aggregator-api-openapi/referral/delete-address-alias https://backend.swap.coffee/openapi delete /v1/referral/alias/{alias} # Get account's list of referrals Source: https://docs.swap.coffee/technical-guides/aggregator-api-openapi/referral/get-accounts-list-of-referrals https://backend.swap.coffee/openapi get /v1/referral/{address}/list # Get account's referral info Source: https://docs.swap.coffee/technical-guides/aggregator-api-openapi/referral/get-accounts-referral-info https://backend.swap.coffee/openapi get /v1/referral/{address} # Get address for alias Source: https://docs.swap.coffee/technical-guides/aggregator-api-openapi/referral/get-address-for-alias https://backend.swap.coffee/openapi get /v1/referral/alias/{alias} # Set referral address alias Source: https://docs.swap.coffee/technical-guides/aggregator-api-openapi/referral/set-referral-address-alias https://backend.swap.coffee/openapi post /v1/referral/alias/{alias} # Unbind existing referral. For internal usage only. Source: https://docs.swap.coffee/technical-guides/aggregator-api-openapi/referral/unbind-existing-referral-for-internal-usage-only https://backend.swap.coffee/openapi delete /v1/referral/{address} # Update referral's info. For internal usage only. Source: https://docs.swap.coffee/technical-guides/aggregator-api-openapi/referral/update-referrals-info-for-internal-usage-only https://backend.swap.coffee/openapi patch /v1/referral/{address} # Get route transactions execution result Source: https://docs.swap.coffee/technical-guides/aggregator-api-openapi/routing/get-route-transactions-execution-result https://backend.swap.coffee/openapi get /v1/route/result # Get route transactions execution result Source: https://docs.swap.coffee/technical-guides/aggregator-api-openapi/routing/get-route-transactions-execution-result-1 https://backend.swap.coffee/openapi get /v2/route/result # Returns pre-built transaction for the given stake request. It is assumed that transaction will be signed and sent by the sender via wallet Source: https://docs.swap.coffee/technical-guides/aggregator-api-openapi/routing/returns-pre-built-transaction-for-the-given-stake-request-it-is-assumed-that-transaction-will-be-signed-and-sent-by-the-sender-via-wallet https://backend.swap.coffee/openapi post /v2/stake/ton/transaction # Returns pre-built transaction for the given unstake request. It is assumed that transaction will be signed and sent by the sender via wallet Source: https://docs.swap.coffee/technical-guides/aggregator-api-openapi/routing/returns-pre-built-transaction-for-the-given-unstake-request-it-is-assumed-that-transaction-will-be-signed-and-sent-by-the-sender-via-wallet https://backend.swap.coffee/openapi post /v2/unstake/ton/transaction # Returns pre-built transactions for the given route. It is assumed that transactions will be signed and sent by the sender via wallet Source: https://docs.swap.coffee/technical-guides/aggregator-api-openapi/routing/returns-pre-built-transactions-for-the-given-route-it-is-assumed-that-transactions-will-be-signed-and-sent-by-the-sender-via-wallet https://backend.swap.coffee/openapi post /v2/route/transactions # Returns the best route for the given list of input tokens and output token Source: https://docs.swap.coffee/technical-guides/aggregator-api-openapi/routing/returns-the-best-route-for-the-given-list-of-input-tokens-and-output-token https://backend.swap.coffee/openapi post /v1/route/multi # Returns the best route for the given trade pair Source: https://docs.swap.coffee/technical-guides/aggregator-api-openapi/routing/returns-the-best-route-for-the-given-trade-pair https://backend.swap.coffee/openapi post /v1/route # Returns the best route for the given trade pair using smart settings Source: https://docs.swap.coffee/technical-guides/aggregator-api-openapi/routing/returns-the-best-route-for-the-given-trade-pair-using-smart-settings https://backend.swap.coffee/openapi post /v1/route/smart # Build transaction to close position and withdraw all money Source: https://docs.swap.coffee/technical-guides/aggregator-api-openapi/staking/build-transaction-to-close-position-and-withdraw-all-money https://backend.swap.coffee/openapi delete /v2/staking/{master_address}/positions/{address}/{id} # Build transaction to create new staking position Source: https://docs.swap.coffee/technical-guides/aggregator-api-openapi/staking/build-transaction-to-create-new-staking-position https://backend.swap.coffee/openapi post /v2/staking/{master_address}/positions/{address} # Build transaction to extend existing position Source: https://docs.swap.coffee/technical-guides/aggregator-api-openapi/staking/build-transaction-to-extend-existing-position https://backend.swap.coffee/openapi post /v2/staking/{master_address}/positions/{address}/{id} # Get aggregated information about staking Source: https://docs.swap.coffee/technical-guides/aggregator-api-openapi/staking/get-aggregated-information-about-staking https://backend.swap.coffee/openapi get /v2/staking/{master_address} # Get aggregated information about staking for specific user Source: https://docs.swap.coffee/technical-guides/aggregator-api-openapi/staking/get-aggregated-information-about-staking-for-specific-user https://backend.swap.coffee/openapi get /v2/staking/{master_address}/{address} # Get all stakings Source: https://docs.swap.coffee/technical-guides/aggregator-api-openapi/staking/get-all-stakings https://backend.swap.coffee/openapi get /v2/staking/list # Get staking transaction execution result Source: https://docs.swap.coffee/technical-guides/aggregator-api-openapi/staking/get-staking-transaction-execution-result https://backend.swap.coffee/openapi get /v2/staking/result # Get user's balances of staked tokens Source: https://docs.swap.coffee/technical-guides/aggregator-api-openapi/staking/get-users-balances-of-staked-tokens https://backend.swap.coffee/openapi get /v2/staking/{master_address}/{address}/balances # Get user's staking points Source: https://docs.swap.coffee/technical-guides/aggregator-api-openapi/staking/get-users-staking-points https://backend.swap.coffee/openapi get /v2/staking/{master_address}/{address}/points # Get generic statistic of dex aggregation. Source: https://docs.swap.coffee/technical-guides/aggregator-api-openapi/statistics/get-generic-statistic-of-dex-aggregation https://backend.swap.coffee/openapi get /v1/statistics/generic # Cancel all strategy orders by given token pair. For internal usage only. Source: https://docs.swap.coffee/technical-guides/aggregator-api-openapi/strategies/cancel-all-strategy-orders-by-given-token-pair-for-internal-usage-only https://backend.swap.coffee/openapi delete /v1/strategies/cancel/by-tokens/{first}/{second} # Cancel all strategy orders by proxy wallet. For internal usage only. Source: https://docs.swap.coffee/technical-guides/aggregator-api-openapi/strategies/cancel-all-strategy-orders-by-proxy-wallet-for-internal-usage-only https://backend.swap.coffee/openapi delete /v1/strategies/cancel/by-wallet/{address} # Cancel all strategy orders. For internal usage only. Source: https://docs.swap.coffee/technical-guides/aggregator-api-openapi/strategies/cancel-all-strategy-orders-for-internal-usage-only https://backend.swap.coffee/openapi delete /v1/strategies/cancel/all # Cancel strategy order by id. For internal usage only. Source: https://docs.swap.coffee/technical-guides/aggregator-api-openapi/strategies/cancel-strategy-order-by-id-for-internal-usage-only https://backend.swap.coffee/openapi delete /v1/strategies/cancel/by-id/{id} # Check whether strategies wallet exists for given account address. Source: https://docs.swap.coffee/technical-guides/aggregator-api-openapi/strategies/check-whether-strategies-wallet-exists-for-given-account-address https://backend.swap.coffee/openapi get /v1/strategies/{address}/wallet # Checks whether user is eligible for using strategies Source: https://docs.swap.coffee/technical-guides/aggregator-api-openapi/strategies/checks-whether-user-is-eligible-for-using-strategies https://backend.swap.coffee/openapi get /v1/strategies/eligibility/user/{address} # Get list of supported from-tokens for strategies Source: https://docs.swap.coffee/technical-guides/aggregator-api-openapi/strategies/get-list-of-supported-from-tokens-for-strategies https://backend.swap.coffee/openapi get /v1/strategies/eligibility/from-tokens # Get list of supported to-tokens for strategies for given from-token Source: https://docs.swap.coffee/technical-guides/aggregator-api-openapi/strategies/get-list-of-supported-to-tokens-for-strategies-for-given-from-token https://backend.swap.coffee/openapi get /v1/strategies/eligibility/to-tokens/{address} # Get pre-built transaction for strategies wallet creation. Source: https://docs.swap.coffee/technical-guides/aggregator-api-openapi/strategies/get-pre-built-transaction-for-strategies-wallet-creation https://backend.swap.coffee/openapi post /v1/strategies/{address}/wallet # Get pre-built transaction for strategy order cancellation Source: https://docs.swap.coffee/technical-guides/aggregator-api-openapi/strategies/get-pre-built-transaction-for-strategy-order-cancellation https://backend.swap.coffee/openapi delete /v1/strategies/{address}/order # Get pre-built transaction for strategy order creation Source: https://docs.swap.coffee/technical-guides/aggregator-api-openapi/strategies/get-pre-built-transaction-for-strategy-order-creation https://backend.swap.coffee/openapi post /v1/strategies/{address}/order # Get strategy order Source: https://docs.swap.coffee/technical-guides/aggregator-api-openapi/strategies/get-strategy-order https://backend.swap.coffee/openapi get /v1/strategies/{address}/order # Get strategy orders Source: https://docs.swap.coffee/technical-guides/aggregator-api-openapi/strategies/get-strategy-orders https://backend.swap.coffee/openapi get /v1/strategies/{address}/orders # Make a payout from strategy wallet to wallet's owner. For internal usage only. Source: https://docs.swap.coffee/technical-guides/aggregator-api-openapi/strategies/make-a-payout-from-strategy-wallet-to-wallets-owner-for-internal-usage-only https://backend.swap.coffee/openapi post /v1/strategies/wallet/payout # Get wallet balance in nanotons (1e-9 TON) Source: https://docs.swap.coffee/technical-guides/aggregator-api-openapi/ton/get-wallet-balance-in-nanotons-1e-9-ton https://backend.swap.coffee/openapi get /v1/ton/wallet/{address}/balance # Returns wallet version and revision Source: https://docs.swap.coffee/technical-guides/aggregator-api-openapi/ton/returns-wallet-version-and-revision https://backend.swap.coffee/openapi get /v1/ton/wallet/{address}/version # Interact with yield pool Source: https://docs.swap.coffee/technical-guides/aggregator-api-openapi/yield/interact-with-yield-pool https://backend.swap.coffee/openapi post /v1/yield/pool/{pool_address}/{user_address} # Returns detailed information about requested pool Source: https://docs.swap.coffee/technical-guides/aggregator-api-openapi/yield/returns-detailed-information-about-requested-pool https://backend.swap.coffee/openapi get /v1/yield/pool/{pool_address} # Returns detailed information about user's position in the pool Source: https://docs.swap.coffee/technical-guides/aggregator-api-openapi/yield/returns-detailed-information-about-users-position-in-the-pool https://backend.swap.coffee/openapi get /v1/yield/pool/{pool_address}/{user_address} # Returns list of pools which correspond to the given params Source: https://docs.swap.coffee/technical-guides/aggregator-api-openapi/yield/returns-list-of-pools-which-correspond-to-the-given-params https://backend.swap.coffee/openapi get /v1/yield/pools # Returns status of interaction with yield pool operation Source: https://docs.swap.coffee/technical-guides/aggregator-api-openapi/yield/returns-status-of-interaction-with-yield-pool-operation https://backend.swap.coffee/openapi get /v1/yield/result # Start using swap.coffee engine today Source: https://docs.swap.coffee/technical-guides/aggregator-api/introduction Build apps on TON Blockchais like a pro.

swap.coffee logo

SDK for swap.coffee DEX aggregator

npm License

## Installation For JavaScript/TypeScript please use the SDK as stated below: ```bash theme={null} npm install @swapcoffee/sdk ``` For any other languages, you can integrate with our [Rest API](https://backend.swap.coffee/swagger-ui) directly. ## Concepts Here are some basic concepts you need to know to work with our SDK: * **Asset**: an asset is a token on a blockchain. It can be a native token (like **TON** on TON blockchain) or a token on a smart contract, named `jetton` (like **USDT** on **TON blockchain**). Each asset has a unique address on the blockchain. * **Route**: a route is a set of paths. * **Path**: a path is a list of tokens (or, more specifically, of liquidity pools) that can be swapped one to another. For example, if you want to swap **TON** to **USDT**, you can do it directly `(TON -> USDT)` or you can do it in two steps `(TON -> CES -> USDT)`. The first path has one swap, the second path has two swaps. * **Price impact**: when you perform a swap, the price of the token can change. The price impact depends on the amount you want to swap and the liquidity of the token. If you swap a small amount, the price impact will be low. If you swap a large amount, the price impact will be high. * **Price slippage**: the price of a token can change over time. When you swap tokens, you can set a slippage tolerance. If the price of the token changes more than the slippage tolerance, the transaction will fail. * **Transaction**: a transaction is a set of messages that are sent to the blockchain. Each message can be a token transfer, a contract call, etc. When you swap tokens, you need to build a transaction that will swap the tokens for you. ## API Limitations Our API is public, which means it allows unauthorized access. However, this access has its limitations: * `input_token` and `output_token` whilst building routes must be different, so you are not allowed to find cycles. Moreover, none of the returned routes will contain cycles within them (so no paths like `token1 -> token2 -> token1 -> token3` will be returned). * We believe that the average load of 1 request per second per IP is more than acceptable. If you generate more, the API will return a `429 Too Many Requests` error. * No product-specific features, such as in-depth analysis of your users trades, available. If you are considering integration with our product, building an arbitrage service or generating a higher level of load, please contact us via Telegram [@swap.coffee DEV Chat](https://t.me/swapcoffee_dev_chat) or get [API Key via Typeform.](https://swapcoffee.typeform.com/to/Zx49Ho3y) # Routing Source: https://docs.swap.coffee/technical-guides/aggregator-api/routing How tou build routes using our API? ## How our routing works 1. You provide the input token, the output token and the amount you want to swap. 2. We build the optimal route for you. This route can be direct `(input token -> output token)` or indirect `(input token -> token1 -> token2 -> ... -> output token)`. By splitting the amount of the input token between several liquidity pools on several decentralized exchanges (**DeDust**, **STONfi**, etc), we can reduce the price impact and get a better price for you. 3. We build the transactions that will swap the tokens. 4. You send the transactions to the blockchain. 5. If slippage is tolerated or deadline exceeds (in rare cases of blockchain lags), the transaction is being (possibly partially) reverted. Otherwise, you receive the output token in your wallet. ## Basic usage Swapping assets using our SDK and TonConnect SDK: ```typescript theme={null} import {ApiTokenAddress, RoutingApi} from "@swapcoffee/sdk"; import TonConnect, {WalletInfo, WalletInfoRemote} from "@tonconnect/sdk"; const connector = await setupTonConnect() const routingApi = new RoutingApi() const assetIn: ApiTokenAddress = { blockchain: "ton", address: "native" // stands for TON } const assetOut: ApiTokenAddress = { blockchain: "ton", address: "EQCl0S4xvoeGeFGijTzicSA8j6GiiugmJW5zxQbZTUntre-1" // CES } const input_amount = 5 // 5 TON // let's build an optimal route const route = await routingApi.buildRoute({ input_token: assetIn, output_token: assetOut, input_amount: input_amount, }) // then we can build transactions payload const transactions = await routingApi.buildTransactionsV2({ sender_address: connector.account?.address!!, // address of user's wallet slippage: 0.1, // 10% slippage paths: route.data.paths, }) let messages = [] for (const transaction of transactions.data.transactions) { // swap.coffee takes care of all the boring stuff here :) messages.push({ address: transaction.address, amount: transaction.value, payload: transaction.cell, }) } // just send the transaction to the user await connector.sendTransaction({ validUntil: Date.now() + 5 * 60 * 1000, messages: messages, }) ``` ## Advanced usage There are extra settings that you're able to modify in case you want more control over how routes are built. The following parameters can be configured: * max\_length - maximum path length in tokens, default is **3**. If specified, it must be an integer from **\[2; 5]** range. Value of **2** indicates that route can contain only direct-swaps paths `(input token -> output token)`. Value of **3**, however, states that route may also contain paths with one intermediate token `(input token -> token1 -> output token)`. ```typescript theme={null} const route = await routingApi.buildRoute({ input_token: assetIn, output_token: assetOut, input_amount: input_amount, max_length: 4 // allow up to 2 intermediate tokens }); ``` * max\_splits - maximum number of splits, default is **4**. If specified, it must be an integer from **\[1; 20]** range. Each split is a distinct path, therefore a distinct blockchain-message that will need to be sent. Currently, wallet contract implementations up to version **4** support not more than **4** messages in a single transaction. Starting from version **5**, the number of message in a single transaction has been raise to **255** `(but ours upper limit is 20)`. ```typescript theme={null} const route = await routingApi.buildRoute({ input_token: assetIn, output_token: assetOut, input_amount: input_amount, max_splits: 2 }); ``` * pool\_selector is an optional property that allows you to control which liquidity pools can be used whilst building the route. * `blockchains` - allows you to limit liquidity pools to given blockchains only. Currently **swap.coffee** does not support cross-chain swaps, but who knows what will happen tomorrow 🙂 If you're certain that you won't like performing cross-chain swaps in the future, set this property to **\["ton"]** value. By default, all supported blockchains are used. * `dexes` - allows you to limit liquidity pools to given dexes only. By default, all supported DEXes are used. * `max_volatility` - allows you to filter out those liquidity pools, whose price volatility over the last 15 minutes exceeded the given value. The higher the value, the more volatile liquidity pools may be used. ## Difference between direct and indirect routes Direct routes without intermediate tokens are usually more safe, but less profitable. Indirect routes with intermediate tokens are usually more profitable, but less safe, because the price of intermediate tokens can change during the transaction and chance that your may receive intermediate tokens instead of the desired output token is higher. It's called **"slippage"** - the difference between the expected price and the actual price. For example, when you set `slippage` to **0.1**, it means that transaction within blockchain must be aborted if any of the swaps lead to obtaining less than `1 - 0.1 = 0.9 = 90%` of amount predicted by **swap.coffee** backend in returned **route**. Due to async nature of **TON** blockchain, such `slippage` abortion can also lead to a situation where the sender is left with neither the input nor the output tokens, but an intermediate one. There are also tokens that can't be swapped directly, because they don't share a liquidity pool. Therefore, if you setup parameters so that only direct swaps allowed (i.e. if `max_length` is equal to **2**), an empty route will be built for you. ## ExactOut swaps If you want to receive an exact amount of output tokens, you can specify the `output_amount` parameter. Those swaps, in comparison to direct swaps (when you specify `input_amount` instead), may be significantly less profitable. They also do not support splitting, which means that resulting route (if exists) will always contain a single path. ```typescript theme={null} const route = await routingApi.buildRoute({ input_token: assetIn, output_token: assetOut, output_amount: 200 // desired amount of output token }); ``` ## Multi-asset swaps Sometimes you might want to exchange multiple input assets for a single output asset in one operation. A common use case is swapping various tokens from your balance into a primary asset like TON or USDT. swap.coffee supports this scenario through **Multi-asset swap** feature. To use this feature via sdk, you'll need `buildMultiAssetRoute` function of the `RoutingApi`. This function is similar to its single-asset counterpart (`buildRoute`), but designed for multiple inputs. Here are the key differences from `buildRoute`: 1. Input parameters: * Instead of `input_token: ApiTokenAddress` and `input_amount: number`, `buildMultiAssetRoute` accepts a single `input_assets` parameter. * `input_assets` is an array of `ApiMultiAssetInputAsset` object, where each one has the following structure: \ `{ asset: ApiTokenAddress, amount: number }` \ This allows you to specify each input token and its corresponding amount. * `buildMultiAssetRoute` does not support `output_amount` field. 2. Return value structure: * `buildMultiAssetRoute` returns an `ApiMultiAssetRoute` object. * The `ApiRoute` object (returned by `buildRoute`) describes a single swap operation and contains fields like `input_token`, `output_token`, `input_amount`, `output_amount`, and `paths`. * The `ApiMultiAssetRoute` object (returned by `buildMultiAssetRoute`) aggregates information for the multi-asset swap: * It contains a `routes: ApiRoute[]` field. Each element here is an `ApiRoute` object, representing one part of the multi-asset swap. * It contains an `output_token: ApiToken` field, representing a single output token of the multi-asset swap. * It provides aggregated totals like `total_output_amount`, `total_savings`, `total_estimated_cashback_usd`, etc., summing up corresponding values from all individual routes. Here's how you can use `buildMultiAssetRoute` to swap both TON and USDT for CES: ```typescript theme={null} import {ApiTokenAddress, RoutingApi} from "@swapcoffee/sdk"; const connector = await setupTonConnect() const routingApi = new RoutingApi() const assetTon: ApiTokenAddress = { blockchain: "ton", address: "native" // stands for TON } const assetUsdt: ApiTokenAddress = { blockchain: "ton", address: "EQCxE6mUtQJKFnGfaROTKOt1lZbDiiX1kCixRv7Nw2Id_sDs" // USDT } const assetOut: ApiTokenAddress = { blockchain: "ton", address: "EQCl0S4xvoeGeFGijTzicSA8j6GiiugmJW5zxQbZTUntre-1" // CES } // let's build an optimal route const route = await routingApi.buildMultiAssetRoute({ input_assets: [ { token: assetTon, amount: 1.0 }, { token: assetUsdt, amount: 2.0 } ], output_asset: assetOut }) // then we can build transactions payload const transactions = await routingApi.buildTransactionsV2({ sender_address: connector.account?.address!!, // address of user's wallet slippage: 0.1, // 10% slippage paths: route.data.routes.flatMap(it => it.paths), // collect all splits }) ``` ## MEV Protection You can enable MEV protection, which protects user's swaps from the so-called sandwich attacks: a MEV bot buys the token before your trade and sells it immediately afterward, causing you to purchase at a higher price. By enabling MEV protection, you can ensure that swaps are not only secure but also maximally profitable. Note that we charge an additional fee for each split in the swap. However, this fee should be absolutely justified when swapping large amounts of liquidity. Be aware that enabling MEV protection will exclude the following DEXes from the routing due to their technical limitations: * STON.fi (v1 only) To enable MEV protection, you have to pass an extra parameters to our API: ```typescript theme={null} const route = await routingApi.buildRoute({ // the rest of the parameters // ... mev_protection: true }); const transactions = await routingApi.buildTransactionsV2({ // the rest of the parameters // ... mev_protection: true }) ``` That's it. MEV protection is enabled, and our system will take care of the rest to maximize the profit from the swap. ## Checking transaction results Along with the transaction built, you receive the `route_id` field. It can be used to check the result of the route's transactions on the **blockchain**. ### Basic usage **SDK** contains inbuilt method for waiting execution results of route's transactions. Promise will be resolved when all transactions are in terminal status (one of `succeeded`, `failed` or `timed_out`). ```typescript theme={null} import {ApiTokenAddress, RoutingApi, waitForTransactionResults} from "@swapcoffee/sdk"; const connector = await setupTonConnect(); const routingApi = new RoutingApi(); const assetIn: ApiTokenAddress = { blockchain: 'ton', address: 'native', // stands for TON }; const assetOut: ApiTokenAddress = { blockchain: 'ton', address: 'EQCl0S4xvoeGeFGijTzicSA8j6GiiugmJW5zxQbZTUntre-1', // CES }; const route = await routingApi.buildRoute({ input_token: assetIn, output_token: assetOut, input_amount: 5, // 5 TON }); const transactions = await routingApi.buildTransactionsV2({ sender_address: connector.account?.address!!, slippage: 0.1, paths: route.data.paths, // note: use route.data here }); let messages = []; for (const transaction of transactions.data.transactions) { messages.push({ address: transaction.address, amount: transaction.value, payload: transaction.cell, }); } await connector.sendTransaction({ validUntil: Date.now() + 5 * 60 * 1000, messages: messages, }); const results = await waitForTransactionResults(transactions.data.route_id, routingApi); for (const result of results) { // handle result for each route's paths } ``` ### Advanced usage By passing `route_id` into `getTransactionsResult()` you can obtain current state of the route's transactions execution status. Response is as follows: ```typescript theme={null} [ { "status": "TX_STATUS", "steps": [ { "status": "SWAP_STATUS", "input": { "token_blockchain": "ton", "token_address": "EQ...1", "amount": 1.2345 }, "output": { "token_blockchain": "ton", "token_address": "EQ...2", "amount": 2.3456 } } ], "input": { "token_blockchain": "ton", "token_address": "EQ...1", "amount": 1.2345 }, "output": { "token_blockchain": "ton", "token_address": "EQ...2", "amount": 2.3456 } } ] ``` Each element of the returned array corresponds to a path at the same index that you provided `buildTransactionsV2` method with. Each element of the `steps` corresponds to a single swap within transaction. For example, if transaction is `A -> B -> C`, then first entry in steps describes `A -> B` swap, and the second one describes `B -> C`. * `TX_STATUS` is a status of a single transaction (related to a single path): * `pending` indicates that none of transaction's swaps have occurred in the blockchain yet. * `partially_complete` - some (but not all) of transaction's swaps have occurred in the blockchain. * `succeeded` - all of transaction's swaps have successfully executed in blockchain. * `failed` - one of transaction's swaps has been aborted due to slippage tolerance. * `timed_out` - our service could not wait enough for at least one of transaction's swaps to be present in the blockchain. This happens if more than 5 minutes have passed since the transaction was generated by our service until the user sent it, or if more than 3 minutes have passed since the previous swap for this transaction appeared in the blockchain. * `SWAP_STATUS` is a status of a single swap within a transaction: * `pending` indicates that this swap didn't happen yet. * `cancelled` - swap has been cancelled due to one of the previous swaps within same transaction failure or timeout. * `succeeded` - swap successfully executed. * `failed` - swap has been aborted due to slippage tolerance. * `timed_out` - our service could not wait enough for this swap to be present in the blockchain. * Transaction's `input` and `output` fields are presented only if at least one swap has already moved to status `succeeded` or `failed`. * Swap's `input` and `output` fields are presented only if swap's status is `succeeded` or `failed`. On failure (abortion due to slippage tolerance) `output` is equal to `input`. The route status can be requested within 2 hours from the moment `route_id` (and transactions) is generated via `buildTransactionsV2`. If all transactions are in terminal status (one of `succeeded`, `failed` or `timed_out`), further receipt of this route's status will be possible only for 1 minute, after which it will be invalidated from our service's cache. ## Custom fees (for partners only) Starting January 2025 various DEXes stopped sharing their fees with aggregators like **swap.coffee**. We understand the desire of our partners to continue earning on user transactions, and therefore we provide functionality for charging additional fees. To do so, it is enough to pass the `custom_fee` property to the transaction construction method: ```typescript theme={null} // building the route itself const route = await routingApi.buildRoute({ input_token: assetIn, output_token: assetOut, input_amount: input_amount, max_splits: 3 // Important! Please, continue reading to understand why }) // building transactions of the route const transactions = await routingApi.buildTransactionsV2({ sender_address: connector.account?.address!!, // address of user's wallet slippage: 0.1, // 10% slippage paths: route.data.paths, referral_name: '#YOUR_REFERRAL_NAME#', custom_fee: { fixed_fee: 'value', percentage_fee: 'value', min_percentage_fee_fixed: 'value', max_percentage_fee_fixed: 'value' } }) ``` As you can see, there are multiple opportunities to set up custom fees collection. Let's dive into them! First of all, `custom_fee` specification looks as follows: ```typescript theme={null} export interface ApiTransactionsCustomFee { /** * Value in nanotons * @type {string} * @memberof ApiTransactionsCustomFee */ 'fixed_fee'?: string; /** * Value in 1/1000000: 1 is 0.0001%, 1000000 is 100%. If present, can not be less than 10000000 (0.01 TON) * @type {number} * @memberof ApiTransactionsCustomFee */ 'percentage_fee'?: number; /** * Value in nanotons. No less than this value may be withdrawn as a percentage_fee. Must be set if percentage_fee is present. Can not be less than 10000000 (0.01 TON) * @type {string} * @memberof ApiTransactionsCustomFee */ 'min_percentage_fee_fixed'?: string; /** * Value in nanotons. If set, no more than this value may be withdrawn as a percentage_fee. Taken into account only if percentage_fee is present * @type {string} * @memberof ApiTransactionsCustomFee */ 'max_percentage_fee_fixed'?: string; } ``` You can charge fixed, volume-percentage based or even both fees every time user performs a swap throughout your service. Each method adds additional transaction to the list given to the user for signing. Regardless of the method chosen and tokens of the swap, fees are always charged in TONs. Please, keep in mind that whatever value you set, it is not the amount you will receive: all custom fees are divided equally between our partners and **swap.coffee** itself, which means that you will get only half of what you request from users there. ### Fixed fee This method is for those cases when you want to charge the same level of commission on all trades through your service, regardless of the trade volume. Please keep in mind that `fixed_fee` is specified in nano-TONs and must not be less than `10_000_000`, which equals 0.01 TON. ### Volume-percentage based fee If you want to charge more commission the larger the trade the user makes, this method is for you. `percentage_fee` is specified in a parts on `1/1_000_000`: `1` stands for `0.0001%` and `1_000_000` stands for `100%`. Whilst using this method, you must also specify `min_percentage_fee_fixed` property, which, as much as `fixed_fee`, must not be less than `10_000_000`, which equals 0.01 TON. It is also up to you whether you want to limit fee value from the above by setting `max_percentage_fee_fixed` property. Overall, the final formula for volume-percentage based fee is as follows: ``` ref_fee = max( max_percentage_fee_fixed, min( min_percentage_fee_fixed, volume_usdt * percentage_fee / 1_000_000 ) ) ``` ### Thinking of max splits Because of custom fees being withdrawn as a separate transactions, it is very important to keep in mind that wallet contracts have a limitation of how much transactions they may send at once: no more than 4 for walletV4 and no more than 255 for walletV5. That's why, when adding custom fees, you **must** guarantee that the route for which you are building transactions contains no more than `max_wallet_txs - 1` splits: it is configurable during `buildRoute` invocation (as shown above). Default value of `max_splits` for `buildRoute` is 4. So, if you haven't specified that property before, it's time to start doing so. If you have tools to determine user's wallet version, you may set it to `3` for walletV4 and to `20` for walletV5. Otherwise, you can just leave it at `3`, because in most circumstances this is more than enough for a good route to be built. # Liquid Staking API Source: https://docs.swap.coffee/technical-guides/aggregator-api/staking-api Technical documentation for interacting with TON liquid staking pools # Introduction Tokens in the swap.coffee platform can have associated staking pools. The staking pool information is represented by the `stakingPool` object, which contains details about the staking pool, such as the address, name, APY, and other relevant information. Currently, we collect staking information for the following tokens: * hTON (Hipo Staked TON) - [https://hipo.finance](https://hipo.finance) * tsTON (Tonstakers) - [https://tonstakers.com](https://tonstakers.com) * stTON (Bemo) - [https://bemo.fi](https://bemo.fi) The API located at [https://tokens.swap.coffee/docs](https://tokens.swap.coffee/docs) For example, for stTON (Bemo), the staking pool object looks like this: ```json theme={null} { "address": "0:cd872fa7c5816052acdf5332260443faec9aacc8c21cca4d92e7f47034d11892", "name": "Staked TON", "symbol": "stTON", "decimals": 9, "price_usd": 3.820352, "price_change_24h": -0.09, "tvl": 917140.097477, "holders_count": 18950, "staking_pool": { "id": 1, "address": "0:cd872fa7c5816052acdf5332260443faec9aacc8c21cca4d92e7f47034d11892", "name": "bemo", "url": "https://app.bemo.fi/", "description": "bemo is a non-custodial liquid staking protocol built on The Open Network (TON) blockchain. It is the first liquid staking application on TON that allows you to stake native TON tokens and, in return, get stTON tokens which you can use freely in DeFi.", "minimum_deposit_ton": 1, "apy": 3.83, "exchange_rate": 1.0654336036660292, "cycle_end": 1742472000 } } ``` ### Fields Description | Field | Type | Required | Description | | --------------------- | ------- | -------- | ----------------------------------------------------------------------------------------------------- | | id | integer | Yes | Unique identifier of the staking pool | | address | string | Yes | The blockchain address of the staking pool contract | | name | string | Yes | The name of the staking pool | | url | string | No | URL to the staking pool's website or documentation | | description | string | No | A description of the staking pool, its features, and benefits | | minimum\_deposit\_ton | number | No | The minimum amount of TON that can be staked in this pool | | apy | number | No | Annual Percentage Yield - the expected yearly return from staking in this pool | | exchange\_rate | number | Yes | The exchange rate between the staked token and the received token (e.g., TON to liquid staking token) | | cycle\_end | integer | No | Unix timestamp indicating when the current staking cycle ends | # Transaction Builder API swap.coffee provides API endpoints for building stake and unstake transactions for staked tokens. These functionality eliminate the need for users to manually construct transactions. ### Stake Transactions To build a transaction for staking TON tokens, use the following endpoint: ``` POST https://backend.swap.coffee/v2/stake/ton/transaction ``` This endpoint returns a pre-built transaction for the given stake request. The transaction must be signed and sent by the sender via their wallet. #### Request Parameters The stake transaction endpoint requires a JSON request body with the following parameters: | Field | Type | Required | Description | | --------------- | ------ | -------- | ---------------------------------------------------------------- | | sender\_address | string | Yes | The address of the sender who will sign and send the transaction | | amount | number | Yes | The amount of TON tokens to stake | | token\_address | string | Yes | The address of the staking pool token (e.g., stTON, hTON, tsTON) | | referral\_name | string | No | Optional referral name for tracking purposes | #### Example Request ```bash theme={null} curl -X POST https://backend.swap.coffee/v2/stake/ton/transaction \ -H "Content-Type: application/json" \ -d '{ "sender_address": "UQCNTO0Nh0Z7QNyRW1BLWfk08f2dAOw4izrx9sO6OUPg4DoV", "amount": 0.05, "token_address": "EQDY6PMeMbQSz7dltNN4RRTIxyuBJX4dQESOy8cWR2tUgBxH" }' ``` #### Response Structure The endpoint returns a response with the following structure: | Field | Type | Required | Description | | ------------- | --------------- | -------- | ------------------------------------------------------------------------------------------- | | payload\_cell | string (base64) | Yes | Base64-encoded cell that is treated as a payload field in TonConnect transaction | | address | string | Yes | The address of the contract to interact with | | value | string (int128) | Yes | Amount of nanotons to be sent with the transaction | | state\_init | string (base64) | No | Optional base64-encoded cell that is treated as a stateInit field in TonConnect transaction | #### Example Response ```json theme={null} { "payload_cell": "te6cckEBAQEAcQAA3v8AIN0gggFMl7ohggEznLqxn3Gw7UTQ0x/THzHXC//jBOCk8mCDCNcYINMf0x/TH/gjE7vyY+1E0NMf0x/T/9FRMrryoVFEuvKiBPkBVBBV+RDyo/gAkyDXSpbTB9QC+wDo0QGkyMsfyx/L/8ntVBC9ba0=", "address": "EQCM3B12QK1e4yZSf8GtBRT0aLMNyEsBc_DhVfRRtOEffLez", "value": "100000000" } ``` ### Unstake Transactions To build a transaction for unstaking TON tokens, use the following endpoint: ``` POST https://backend.swap.coffee/v2/unstake/ton/transaction ``` This endpoint returns a pre-built transaction for the given unstake request. The transaction must be signed and sent by the sender via their wallet. #### Request Parameters The unstake transaction endpoint requires a JSON request body with the following parameters: | Field | Type | Required | Description | | --------------- | ------ | -------- | ---------------------------------------------------------------- | | sender\_address | string | Yes | The address of the sender who will sign and send the transaction | | amount | number | Yes | The amount of staked tokens to unstake | | token\_address | string | Yes | The address of the staking pool token (e.g., stTON, hTON, tsTON) | | referral\_name | string | No | Optional referral name for tracking purposes | #### Example Request ```bash theme={null} curl -X POST https://backend.swap.coffee/v2/unstake/ton/transaction \ -H "Content-Type: application/json" \ -d '{ "sender_address": "UQCNTO0Nh0Z7QNyRW1BLWfk08f2dAOw4izrx9sO6OUPg4DoV", "amount": 0.05, "token_address": "EQDY6PMeMbQSz7dltNN4RRTIxyuBJX4dQESOy8cWR2tUgBxH" }' ``` #### Response Structure The endpoint returns a response with the following structure: | Field | Type | Required | Description | | ------------- | --------------- | -------- | ------------------------------------------------------------------------------------------- | | payload\_cell | string (base64) | Yes | Base64-encoded cell that is treated as a payload field in TonConnect transaction | | address | string | Yes | The address of the contract to interact with | | value | string (int128) | Yes | Amount of nanotons to be sent with the transaction | | state\_init | string (base64) | No | Optional base64-encoded cell that is treated as a stateInit field in TonConnect transaction | #### Example Response ```json theme={null} { "payload_cell": "te6cckEBAQEAcQAA3v8AIN0gggFMl7ohggEznLqxn3Gw7UTQ0x/THzHXC//jBOCk8mCDCNcYINMf0x/TH/gjE7vyY+1E0NMf0x/T/9FRMrryoVFEuvKiBPkBVBBV+RDyo/gAkyDXSpbTB9QC+wDo0QGkyMsfyx/L/8ntVBC9ba0=", "address": "EQCM3B12QK1e4yZSf8GtBRT0aLMNyEsBc_DhVfRRtOEffLez", "value": "100000000" } ``` ## Using the built message with TonConnect This transaction information can be used with wallet providers like TonConnect to execute the stake or unstake operation. Here's an example of how to use the response with TonConnect: ```javascript theme={null} const transaction = { validUntil: Math.floor(Date.now() / 1000) + 360, // 5 minutes from now messages: [ { address: response.address, amount: response.value, payload: response.payload_cell } ] }; // Send the transaction using TonConnect tonConnectUi.sendTransaction(transaction); ``` # Staking Internals Source: https://docs.swap.coffee/technical-guides/aggregator-api/staking-internals # Introduction This page describes overall architecture and possible interactions with staking protocol developed by **swap.coffee**. User-friendly interface is available at [https://swap.coffee/stake](https://swap.coffee/stake), but this document is aiming at providing readers with technical insights, TL-B schemes and others associated complexities. At the time of writing this article, we only support staking protocol for our own product, but we also have plans and are in the process of implementation (by the time you read this, it's likely already implemented) to support staking protocol for partner products as well. # Architecture Staking protocol consists of 2 on-chain contracts: **Master** and **Vault**; integral off-chain backend that is responsible for rewards calciulation; and also interacts with **swap.coffee**'s rewards distribution system. ## Master Contract **Master Contract** is used both for storing crucial data about protocol itself and keeping funds that are being distributed as a rewards. It is also fully compatible with NFT standard by supporting all related methods of NFT Collection. You may retrieve staking-related information by calling contract's get method `get_stored_data`, which returns: ### 1. int `initialized` 1 for true, 0 for false. ### 2. slice `admin_address` ### 3. slice `distributor_address` Technical wallet that is a part of **swap.coffee**'s rewards distribution system and which serves as a proxy point for users which want to claim their staking rewards. ### 4. slice `vault_address` Address of a staking **Vault Contract** associated with this **Master Contract**. ### 5. cell `state` Cell of the following format: ```tl-b theme={null} state total_points:Coins next_nft_id:uint64 = State; ``` ### 6. cell `rewards` Contains information about the rewards that were (or being) distributed across all the users that participate(d) in staking. Cell is being represented as a cell-referencing dictionary, which can be read as follows: ```func theme={null} (cell data, int found) = rewards.udict_get_ref?(256, slice_hash(jetton_wallet)); if (found) { slice ds = data.begin_parse(); int duration = ds~load_uint(64); int finish_at = ds~load_uint(64); int started_at = finish_at - duration; int reward_per_point = ds~load_coins(); } ``` Every time this cell is updated, external out message is being generated: ```tl-b theme={null} notify_reward#0xa9577f0 query_id:uint64 jetton_wallet:MsgAddressInt duration:uint64 finish_at:uint64 reward_rate:Coins = NotifyReward; ``` In the message above, `reward_rate` is being calculated in one of the following ways: ```func theme={null} int update_time = now(); if (update_time > previous_finish_at) { reward_rate = reward_total_amount / duration; } else { reward_rate = mul_add_div_mod_r(previous_finish_at - update_time, reward_per_point, reward_total_amount, duration); } ``` Simplified version of the code that allows you to calculate reward for specific staking position: ```func theme={null} int staking_position_points = 0; ;; fill with your value int staking_position_created_at = 0; ;; fill with your value int acquiring_at = now(); ;; fill with your value: time at which user decides to acquire his reward int reward_rate = 0; ;; must be retrieved by catching external out message int NORMALIZER = 1_000_000_000_000_000_000; if (staking_position_created_at < updated_at) { ;; In real world things are a bit more complicated, because rewards distribution may be updated after ;; users' staking positions were created. Internally there's a mechanism that handles such updates ;; and recalculates every staking position's rewards accordingly. return 0; } if (acquiring_time > finish_at) { acquiring_time = finish_at; } int delta_time = acquiring_time - updated_at; return reward_rate * delta_time * NORMALIZER * staking_position_points / total_points; ``` ### 7. cell `jettons` Unlike many other staking protocols, ours supports staking of not only one specific token, but of any (pre-defined by the protocol administrator) set of them. One of the purposes of the **Master Contract** is to be an entry point to retrieve list of such supported tokens, and this exact cell contains them. Cell is being represented as a cell-referencing dictionary, which can be read as follows: ```func theme={null} (cell data, int found) = jettons.udict_get_ref?(256, slice_hash(jetton_wallet)); if (found) { slice ds = data.begin_parse(); slice jetton_wallet = ds~load_msg_addr(); int jetton_normalizer = ds~load_coins(); } ``` Only those jettons that are defined in this cell may be staked. Normalizer defines amount of points being accrued for staking one piece of this jetton. ### 8. cell `periods` Investment of funds is possible only for one of the predetermined periods, which are stored in this exact cell. Cell is being represented as a cell-referencing dictionary, which can be read as follows: ```func theme={null} (cell data, int found) = periods.udict_get_ref?(32, period_id); if (found) { slice ds = data.begin_parse(); int duration = ds~load_uint(64); int percentage = ds~load_uint(64); } ``` For a given period, user final points may be calculated as: ```func theme={null} int base_points = jetton_staked_amount * jetton_normalizer; return mul_div_r(base_points, percentage, 100); ``` ## Vault Contract This contract serves both as a storage for users' staked assets and as a proxy for users' interactions with the **Master Contract**. ### Deposit New staking position may be created by sending jettons to the **Vault Contract** with specific `forward_payload`: ```tl-b theme={null} period period_id:uint32 = Period; transfer#f8a7ea5 query_id:uint64 amount:(VarUInteger 16) destination_address:MsgAddress response_address:MsgAddress custom_payload:(Maybe ^Cell) forward_amount:(VarUInteger 16) forward_payload:(Maybe ^Period) = Transfer; ``` After such action, if succeeded, users' assets will be held until he decides to withdraw them (after lock period expires), and NFT Item that corresponds to **Master Contract** as a NFT collection will be created and sent to the user who initiated this transaction. Example of full deposit transaction could be found [here](https://tonviewer.com/transaction/e25593795c06d898f2010761e910fdb1b9a63c6c3a1e431565e161412b05f758). ### Withdraw Despite being written under **Vault Contract** section, withdrawal is performed by sending a specific transaction to the NFT Item user received after staking his jettons. Message's body looks as follows: ```tl-b theme={null} close_staking_position#0xcb03bfaf query_id:uint64 = CloseStakingPosition; ``` If everything is ok, there will be a chain of messages initiated by the NFT Item that will go through the **Master Contract** right to the **Vault Contract**, freeing user's assets. ## Off-Chain Backend As briefly described before, our staking protocol hardly depends on the off-chain part that not only indexes blockchain in order to track all the users actions related to staking, but also allows us to integrate staking protocol into already existing **swap.coffee**'s rewards distribution system. This is a closed proprietary product, therefore there is not really much to write about it. Despite the fact that there are some interactions that users will encounter when using our staking protocol such as rewards claiming, we're not ready yet to provide in-depth details about it. But stay tuned and maybe in some future it will also appear on our documentation website :) # Strategy Orders Source: https://docs.swap.coffee/technical-guides/aggregator-api/strategy-orders Learn how to use LIMIT & DCA orders ## Essential knowledge All of swap.coffee's orders, regardless of their type, utilize the same **Strategy Orders Service** API (available both at our [Rest API endpoint](https://backend.swap.coffee/swagger-ui#/Strategies) or within our SDK). To start your integration journey throughout our SDK, here's a useful code snippet: ```typescript theme={null} import {StrategiesApi} from "@swapcoffee/sdk"; const strategiesApi = new StrategiesApi() ``` Our service of working with strategy orders is organized in a fairly simple way: 1. For each user we deploy a so-called **Strategies Wallet** that is being administrated by our backend systems. 2. Whenever user decides to create a new order or edit an existing one, he transfers funds and sends an associated message to that contract. Therefore, all the information about user's orders and interactions is stored within blockchain: not as a separate contract for each order, but in a single contract for all of them. 3. Our backend systems perform strategies-related logic and build routes off-chain, then initiate both exchange- and order-ending transactions on the wallet contract deployed in step (1). ## Strategies wallet First of all, in order to interact with strategies service, user needs to create his very own **Strategies Wallet**. This is a one-time action. ```typescript theme={null} import TonConnect from "@tonconnect/sdk"; const connector = await setupTonConnect() // First, we retrieve a transaction for strategies wallet creation. const tx = await strategiesApi.getStrategyWalletCreationTransaction( 'USER_WALLET_ADDRESS', 'USER_WALLET_VERIFICATION_TOKEN' ) // Then sending this transaction via TonConnect. await connector.sendTransaction({ validUntil: Date.now() + 5 * 60 * 1000, messages: [{ address: tx.data.address, amount: tx.data.value, payload: tx.data.payload_cell, stateInit: tx.data.state_init }] }) // And finally, we wait until strategies wallet is being created. while (true) { const created = await strategiesApi.doesStrategyWalletExist( 'USER_WALLET_ADDRESS', 'USER_WALLET_VERIFICATION_TOKEN' ) if (created.status != 404) { console.log('Created strategies wallet address is', created.data) break } } ``` ### Wallet verification token Many of our API methods may require a mandatory parameter `xVerify`. This is a special json-formatted string that confirms ownership of the associated wallet. The easiest way to obtain it is to authorize with your wallet at [our website](https://swap.coffee/limit) and to steal it from within browser's network profiling page (it will be in sent-headers section). The manual way to generate it is to authenticate `swap.coffee` domain using **Ton Connect**. More details about it available in [their documentation](https://ton-connect.github.io/sdk/modules/_tonconnect_sdk.html#backend-authorization). ## Creating your first order After strategies wallet has been created, you are free to use the full power of our strategies service any way you want it. Firstly, you need to decide for which pair of assets you are going to create an order. Unlike regular route building, orders can not be created for an arbitrary set of pairs. What we do instead is: ```typescript theme={null} const fromAssets = await strategiesApi.getFromTokensEligibleForStrategies( 'limit' // Pick appropriate type for your order. ) for (const fromAsset of fromAssets.data) { const toAssets = await strategiesApi.getToTokensEligibleForStrategies('limit', fromAsset) for (const toAsset of toAssets.data) { console.log('Limit order can be created for assets', fromAsset, toAsset) } } ``` After you checked that the pair of assets you wanted to create the order for is indeed supported, it is time to create the order itself: ```typescript theme={null} // Build transaction for order creation. const tx = await strategiesApi.getStrategyOrderCreationTransaction( 'USER_WALLET_ADDRESS', 'USER_WALLET_VERIFICATION_TOKEN', { type: 'limit', token_from: { blockchain: 'ton', address: fromAsset }, token_to: { blockchain: 'ton', address: toAsset }, input_amount: "VALUE", // Absolute amount of input asset. For example, 1000000000 will be used for 1 TON. max_suborders: 1, max_invocations: 1, slippage: 1, settings } ) // Then send this tx using ton-connect. ``` ### Order settings There are some non-obvious parameters in this request that require further explanation: * `max_suborders` - maximum amount of sub-orders this order may be split into. Must be within bounds `[1; 255]`. * `max_invocations` - maximum amount of sub-orders execution tries. Must be within bounds `[max_suborders; 255]`. What we mean by *try* here is as follows: * If sub-order executes successfully, it consumes one *try*, and order execution continues as planned; * Otherwise (if sub-order couldn't be fulfilled due to slippage toleration, deadline exceeding, etc), - it also consumes one *try*, but checks if there are any available *tries* left: if yes, sub-order will be retried (consuming one more *try*); if no, the whole order will be cancelled at the current stage of execution (possibly marked as only partially fulfilled). * `slippage` - this term means the same as in normal routing construction, but for **LIMIT** orders (when the system must guarantee that the order will be filled at no less than the user's requested price) it also affects how much the price must exceed the user's requested price before the order will be attempted to be filled. For example, `0.001` (0.1%) value set for **LIMIT** order, in which user wants to exchange 1 TON for at least 10 USDT, means that order will be executed when price reaches at least `10 * (1 + 0.001) = 10 * 1.001 = 10.01` USDT for 1 TON. Must be within bounds `(0; 1]`. * `settings` is the only field that is truly unique for each order type. Below it is analyzed in detail. For limit orders: ```typescript theme={null} { min_output_amount: "VALUE" // Absolute amount of output asset to be minimally received. } ``` For DCA orders: ```typescript theme={null} { delay: 60, // Delay in seconds between DCA order executions. Must be within bounds [60; 15552000]. price_range_from: 0.0, // Optional. Allows to prohibit the execution of an order if the price falls below the specified level. price_range_to: 0.0 // Optional. Allows to prohibit the execution of an order if the price rises above the specified level. } ``` ## Looking after existing orders There are 2 methods for retrieving your orders information: `getStrategyOrder` that looks for specific order identifier, and `getStrategyOrders` that supports filtering and allows to get data for multiple orders at once. Both of those methods return structure known as `StrategyOrder`, which looks as follows: ```json theme={null} { "id": 0, "type": "limit", "wallet": "string", "status": "active", "creation_timestamp": 0, "token_from": { "address": { "blockchain": "ton", "address": "native" }, "metadata": { "name": "TON", "symbol": "TON", "decimals": 9, "image_url": "string", "listed": true } }, "token_to": { "address": { "blockchain": "ton", "address": "native" }, "metadata": { "name": "TON", "symbol": "TON", "decimals": 9, "image_url": "string", "listed": true } }, "initial_input_amount": "string", "current_input_amount": "string", "settings": { "additionalProp1": "string", "additionalProp2": "string", "additionalProp3": "string" }, "current_output_amount": "string", "max_suborders": 0, "suborders_executed": 0, "max_invocations": 0, "invocations_executed": 0, "slippage": 0.0, "max_path_length": 0, "active_transactions": 0, "close_timestamp": 0 } ``` Meaning of the fields: | Field name | Field type | Meaning | | ----------------------- | ------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | id | int32 | Order's identifier. Unique for every order. | | type | enum (string) | Order's type. | | wallet | string | Address of strategies wallet associated with the order. Wallets of orders of the same user are always identical. | | status | enum (string) | Current status of the order: | | creation\_timestamp | int64 | Order's creation timestamp in unix time seconds. | | initial\_input\_amount | string | Absolute amount of the input asset (`token_from`) when this order was created. | | current\_input\_amount | string | Absolute amount of the input asset (`token_from`) as for now. May be zero if the whole input asset amount was consumed. This field does not always decrease: it may decrease when our service sends exchange transaction, but increase back if that transaction fails. | | current\_output\_amount | string | Absolute amount of the output asset (`token_to`) as for now. Starts at zero. Never decreases. | | settings | structure | Order's settings that are unique for each strategy. May include some additional (technical) fields, that were not present at the time order was created. | | max\_suborders | int8 | Maximum amount of order's suborders. Order was created with that value. | | suborders\_executed | int8 | Amount of order's suborders that were successfully executed as for now. | | max\_invocations | int8 | Maximum amount of order's invocations (*tries*). Order was created with that value. | | invocations\_executed | int8 | Amount of order's invocations (\_tries) that were executed (not necessarily successfully). | | slippage | float | Slippage with which order was created. | | max\_path\_length | int3 | Maximum length of routes for which transactions may be executed within this order, in tokens. So, for example, `2` means that only routes such as `A -> B` may be executed, and so on. This field is being set internally and therefore could not be modified in any way. | | active\_transactions | int8 | Amount of order's transactions that were sent to the blockchain and which execution status still was not handled by our service. | | close\_timestamp | int64 | Optional field that is present for orders in terminal status only. Signifies order's closing timestamp in unix time seconds. | Please, keep in mind that both `current_input_amount` and `current_output_amount` include fees to be withdrawn by our service (if any). Currently, there is no API functionality that allows to distinct funds to be sent to the user and service fees. ## Order cancellation Given an existing order in `active` status, user is able to cancel it by calling appropriate method: ```typescript theme={null} // Get transaction for order cancellation. const fromAssets = await strategiesApi.getStrategyOrderCancellationTransaction( 'USER_WALLET_ADDRESS', 'USER_WALLET_VERIFICATION_TOKEN', 42 // order identifier ) // Then execute it via ton-connect. ``` # Yield Aggregator Source: https://docs.swap.coffee/technical-guides/aggregator-api/yield-internals Learn how to integrate with Yield Aggregator to manage liquidity pools and earn rewards # Overview All operations use a unified **Yield Aggregator Service** API, accessible via [REST API](https://backend.swap.coffee/swagger-ui#/YieldAggregator). Key features of Yield Aggregator: 1. Upon request, the swap.coffee backend provides information about liquidity pools and DeFi protocols on the TON network. 2. If the user provides their wallet, the swap.coffee backend retrieves data about the user’s pools. 3. Users can interact with pools via the API: retrieve pool details, gather information about their position, and perform actions (e.g., adding liquidity). 4. Users can track the status of their transactions by querying the swap.coffee backend. ## List of Pools To retrieve the list of all pools in Yield Aggregator, use the `GET /v1/yield/pools` method. This method allows filtering and sorting pools by various parameters, including blockchains, liquidity providers, and more. ### Request Parameters | Parameter | Type | Description | Default Value | | --------------------- | ------- | ---------------------------------------------------------------- | ----------------------------------------------------- | | blockchains | array | Filter by available blockchains (e.g., `ton`). | If not specified, all supported blockchains are used. | | providers | array | Filter by pool providers (e.g., `stonfi`). | If not specified, all providers are used. | | trusted | boolean | Returns only trusted pools (verified by DEXes or the community). | True by default. | | with\_active\_boosts | boolean | Returns pools with active incentives. | False by default. | | with\_liquidity\_from | string | Filter by pools where the user has provided liquidity. | Null by default. | | search\_text | string | Search by pool address, token tickers, or token addresses. | Null by default. | | order | string | Field to sort by. | TVL by default. | | descending\_order | boolean | Sort in descending (true) or ascending (false) order. | True by default. | | in\_groups | boolean | Groups pools by liquidity providers. | False by default. | | size | integer | Number of pools per page (maximum 100). | 10 | | page | integer | Page number for pagination. | 1 | ### The `in_groups` Flag You can retrieve a preview for the specified parameters for each liquidity provider (or all providers if the `providers` parameter is `null`). To do this, set `in_groups=true` in the request. In this case, the response will contain a set of pool lists for each required liquidity provider (up to 10 entries per provider). If `in_groups=true`, the `size` and `page` parameters must be **null**. ### Response Structure The response structure contains an array of entries with the following fields: | Field | Type | Description | | ------------ | ----- | ------------------------------------------------------- | | total\_count | int32 | Total number of pools found for the specified provider. | | pools | array | List of pools. | Each element in `pools` consists of: | Field | Type | Description | | ---------------- | ------ | --------------------------------------------- | | pool\_statistics | object | Trading statistics of the pool. | | pool | object | Pool data parameterized by the `"@type"` key. | Possible values for `pool["@type"]`: * `dex_pool`, the object is a DEX pool and contains the following fields: | Field | Type | Description | | ------------------ | ------- | ------------------------------------------------------------------------- | | dex | string | Name of the DEX (e.g., `stonfi`). | | address | string | Pool address. | | type | object | Pool type (e.g., `public`, `private`). | | amm\_type | object | AMM type (e.g., `constant_product`). | | amm\_settings | object | AMM parameters. | | tokens | array | List of tokens in the pool. | | reserves | double | Pool reserves. | | restrictions | array | Token restrictions (minimum and maximum token amounts for swaps). | | fees | object | Pool fees. | | unavailable\_until | integer | Time (in seconds, UTC Unix timestamp) until the pool becomes unavailable. | The `pool_statistics` object includes the following fields: | Field | Type | Description | | ----------- | ------ | ----------------------------------- | | tvl\_usd | number | Total value locked in USD. | | volume\_usd | number | Trading volume in USD. | | fee\_usd | number | Pool fees in USD. | | apr | number | Total Annual Percentage Rate (APR). | | lp\_apr | number | APR for liquidity providers. | | boost\_apr | number | APR from boosts. | ### Example Request ```bash theme={null} curl -X GET "https://backend.swap.coffee/v1/yield/pools?blockchains=ton&trusted=true&search_text=CES&order=apr&descending_order=true&size=50&page=1" ``` ## Retrieving Pool Information To retrieve detailed information about a pool, use the `GET /v1/yield/pool/{pool_address}` method. ### Response Structure The method returns an object with fields: | Field | Type | Description | | ---------------- | ------ | --------------------------------------------- | | pool\_statistics | object | Trading statistics of the pool. | | pool | object | Pool data parameterized by the `"@type"` key. | Possible values for `pool["@type"]`: * `dex_pool`, the object is a DEX pool and has the following fields: | Field | Type | Description | | ------------- | ------ | --------------------------------- | | pool | object | Core pool data. | | boosts | array | List of active boosts. | | total\_supply | string | Total amount of minted LP tokens. | Each element in the `boosts` list has the following fields: | Field | Type | Description | Required | | ------------------------- | ------- | ------------------------------------------------------- | -------- | | pool\_address | string | Address of the pool associated with the boost. | Yes | | boost\_factory | string | Address of the boost factory. | No | | boost\_id | integer | Boost identifier. | No | | reward\_token | object | Reward token. | Yes | | reward\_rate\_per\_second | string | Reward rate per second. | Yes | | start\_seconds\_unix | integer | Boost start time (Unix timestamp, seconds). | No | | finish\_seconds\_unix | integer | Boost end time (Unix timestamp, seconds). | Yes | | rewards\_per\_day\_usd | number | Daily rewards in USD. | Yes | | apr | number | Annual Percentage Rate (APR) in percentage. | Yes | | lock\_duration\_seconds | integer | Lock duration for participating in the boost (seconds). | No | ### Example Request ```bash theme={null} curl -X GET "https://backend.swap.coffee/v1/yield/pool/EQBqg596nW5TA9cfUePEFGnyw1V0F560v7Qg3KYku5iXU217" ``` ## Retrieving User Position Information To retrieve detailed information about a user’s position in a pool, use the `GET /v1/yield/pool/{pool_address}/{user_address}` method. ### Response Structure The method returns an object with fields: | Field | Type | Description | | ----- | ------ | --------------------------------------------- | | pool | object | Pool data parameterized by the `"@type"` key. | Possible values for `pool["@type"]`: * `dex_pool`, the object is a DEX pool and has the following fields: | Field | Type | Description | | ---------------- | ------ | -------------------------------------------------------- | | user\_lp\_amount | string | Amount of the user’s LP tokens. | | user\_lp\_wallet | string | Address of the user’s wallet where LP tokens are stored. | | boosts | array | Boosts available for claiming. | Each element in the `boosts` list has the following fields: | Field | Type | Description | | -------------- | ------ | ---------------------------------------- | | token | object | Token associated with the reward. | | wallet | string | Address where rewards are stored. | | type | object | Type of reward (e.g., `rewards_stonfi`). | | claimed | string | Amount of tokens already claimed. | | locked | string | Amount of locked tokens. | | available | string | Amount of tokens available for claiming. | | available\_usd | number | Value of available tokens in USD. | ### Example Request ```bash theme={null} curl -X GET "https://backend.swap.coffee/v1/yield/pool/EQBqg596nW5TA9cfUePEFGnyw1V0F560v7Qg3KYku5iXU217/UQAj-RQTlNNwjkuRVYWdfamU0jjvQbH31lkxTw-osulj4tdj" ``` ## User Interaction with a Pool To add liquidity or withdraw funds, use the `POST /v1/yield/pool/{pool_address}/{user_address}` method. ### Interaction Types The method supports the following operations, parameterized by the `"@type"` field in the request body: * `dex_provide_liquidity`: Add liquidity to the pool. * `dex_withdraw_liquidity`: Withdraw liquidity from the pool. * `dex_stonfi_lock_staking`: Stake in Ston.fi farming service. * `dex_stonfi_withdraw_staking`: Withdraw from staking in Ston.fi. Each request returns a list of transactions that need to be signed and sent to the blockchain: | Field | Type | Description | | --------- | ------ | ------------------------------------------- | | query\_id | string | Transaction identifier for status tracking. | | message | object | Transaction to be signed and sent. | ### Example Request ```bash theme={null} curl -X POST "https://backend.swap.coffee/v1/yield/pool/EQBqg596nW5TA9cfUePEFGnyw1V0F560v7Qg3KYku5iXU217/UQAj-RQTlNNwjkuRVYWdfamU0jjvQbH31lkxTw-osulj4tdj" -H "Content-Type: application/json" \\ -d '{ "@type": "dex_provide_liquidity", "user_wallet": "UQAj-RQTlNNwjkuRVYWdfamU0jjvQbH31lkxTw-osulj4tdj", "asset_1_amount": "1000000000", "asset_2_amount": "2000000000", "min_lp_amount": "123456789" } ``` ## Checking Operation Status After submitting a transaction, you can check its statuses using the `GET /v1/yield/result` method. ### Response Structure The method returns an array of transaction statuses: * `pending`; * `success`; * `failed`. ### Example Request ```bash theme={null} curl -X GET "https://backend.swap.coffee/v1/yield/resut?query_id=123456" ``` ## Useful links * [SWAGGER API](https://backend.swap.coffee/swagger-ui#/Entity/getPools) # Custom fee Source: https://docs.swap.coffee/technical-guides/aggregator-widget/advanced/custom-fee ## Setup widget referral If you are a **unique referral** you can specify your **referral** as a parameter in the widget's creator function `createSwapWidget` *** To pass the **referral** we have a `widgetReferral` configuration parameter You can do it in a similar way: *** ```typescript theme={null} createSwapWidget("#test", { widgetReferral: "TEST_WIDGET_REFERRAL", otherConfig..., }); ``` ## Setup widget custom fees If you are an **partner** of `swap.coffee` and have a **unique referral** you can pass custom fee settings directly into the widget configuration > * You can read more about the concept of **partner custom commissions** 👉 [**here**](https://docs.swap.coffee/technical-guides/aggregator-api#custom-fees-for-partners-only) *** To pass the **referral** we have a `customFeeSettings` configuration parameter You can do it in a similar way: *** ```typescript theme={null} createSwapWidget("#test", { widgetReferral: "TEST_WIDGET_REFERRAL", customFeeSettings: { fixed_fee: 'value', percentage_fee: 0, min_percentage_fee_fixed: 'value', max_percentage_fee_fixed: 'value' }, otherConfig..., }); ``` * So, passing instead of `TEST_WIDGET_REFERRAL` your **referral** the widget will recognize your **referral** `(only if it is valid)` and share the profit with the widget integrator. **Conclusion** To receive **profit** from the protocol, you must have an `ACTIVE referral` and complete the custom `fee settings`. > 💡 **Tip**: If you are interested in creating a unique referral for your integration, contact 👉 [**Lizard**](https://t.me/lizard_tail). # Liquidity Sources Source: https://docs.swap.coffee/technical-guides/aggregator-widget/advanced/liquidity-sources Configure which liquidity providers the widget is allowed to use for swap routing. By default, `swap.coffee UI widget` supports a **full list of decentralized protocols** and automatically evaluates them at runtime. *** ## Default Behavior If you **do not provide** any liquidity-related configuration, the widget enables `all available sources`: ```typescript theme={null} ['tonco', 'stonfi_v2', 'tonstakers', 'stonfi', 'dedust', 'coffee', 'colossus', 'torch_finance', 'moon', 'bidask'] ``` These are fully **dynamic** and **toggleable** by the user in the widget UI under expert settings. ## Restricting Liquidity Sources You can **override this behavior** by passing the `liquiditySourcesList` parameter. ```typescript theme={null} liquiditySourcesList?: string[]; ``` * When this list is provided, **only the specified sources are used**, and the user **cannot change or toggle** them via the UI. ### Example: Restrict to a Single Source ```typescript theme={null} createSwapWidget("#test", { liquiditySourcesList: ["stonfi_v2"], otherConfig... }); ``` This limits swap routing **strictly** to `STONFI_V2`. All other sources like `TONCO` or `Tonstakers` **are excluded from routing and hidden in the UI**. > 🚫 When `liquiditySourcesList` is set, the widget **hides off settings for sources**. > Users **will no longer** be able to change `liquidity source` preferences **inside the widget**. # Overview Source: https://docs.swap.coffee/technical-guides/aggregator-widget/advanced/overview Widget parameters you should know about ## Optional Parameters The parameters listed in this section are **not required** for getting started with the widget. They exist to give **integrators** the flexibility of widget to their specific needs — such as setup and `customizing referral fees`, start **jetton parameters**, or configure limited **liquidity sources list**. > ⚠️ Use these options **only when necessary**. By default, the widget works out of the box with minimal setup. ### UI-Based Settings | Parameter | Type | Description | | -------------------- | --------- | ---------------------------------------------------- | | `firstTokenAmount` | `number` | Predefined `first token amount` shown on first load. | | `limitDcaVisibility` | `boolean` | Hides/show **Limited\&DCA** related UI elements. | *** ### Token Properties | Parameter | Type | Description | | --------------------------- | ---------- | ---------------------------------------------------------------------------------------- | | `sendReceiveTokenAddresses` | `string[]` | List of `token addresses` to be shown in the **Send/Receive** section only. | | `limitedJettonLists` | `string[]` | Custom list of token `addresses (jettons)` to restrict the widget UI to specific tokens. | | `enableCommunityTokens` | `boolean` | Include community tokens inside main token list. | *** ### Fee Logic | Parameter | Type | Description | | -------------------------------------------- | -------- | ------------------------------------------------------- | | `widgetReferral` | `string` | Partneer `referral tag`. Needs to setup **custom fee**. | | `customFeeSettings` | `object` | Override default **fee logic**. | | `customFeeSettings.percentage_fee` | `number` | Percentage **fee** in basis points (e.g., `3000` = 3%). | | `customFeeSettings.min_percentage_fee_fixed` | `string` | Minimum fee in nano-units (e.g., `500000000`). | | `customFeeSettings.max_percentage_fee_fixed` | `string` | Maximum fee in nano-units (e.g., `4000000000`). | | `customFeeSettings.fixed_fee` | `string` | Fixed fee in nanoton-units (e.g., `1000000000`). | ### Liquidity Sources | Parameter | Type | Description | | ------------------ | ---------- | -------------------------------------------------------------------- | | `liquiditySources` | `string[]` | Fixed list of `liquidity sources` to be included in the dex routing. | # Token Configuration Source: https://docs.swap.coffee/technical-guides/aggregator-widget/advanced/tokens Customize which tokens are first visible and available in the widget. You can control which `tokens appear` in the widget UI by using the following **optional parameters**. > ☝️ **Important** -- All `tokens (Jettons)` passed to either parameter **must be listed on [swap.coffee](https://swap.coffee)** to be recognized and rendered correctly in the widget. *** ## `sendReceiveTokenAddresses` ```typescript theme={null} sendReceiveTokenAddresses?: string[]; ``` * Defines a **custom list** of **token addresses (Jettons)** that should be available in the `Send` and `Receive` sections of the widget. * Use this when you want to set a `unique pair` of tokens that users can **swap from or to**. ```typescript theme={null} createSwapWidget("#test", { sendReceiveTokenAddresses: [ "EQAvlWFDxGF2lXm67y4yzC17wYKD9A0guwPkMs1gOsM__NOT", // SEND -> NOT "EQCl0S4xvoeGeFGijTzicSA8j6GiiugmJW5zxQbZTUntre-1" // RECEIVE -> CES ], otherConfig... }); ``` > 🚧 **Warning** -- If you pass an **invalid token address**, the widget and pair will not render correctly. ## `limitedJettonLists` ```typescript theme={null} limitedJettonLists?: string[]; ``` Provides a **custom list** of `Jetton addresses` that will be used to completely override the default token list in the widget. ```typescript theme={null} createSwapWidget("#test", { limitedJettonLists: [ "EQC98_qAmNEptUtPc7W6xdHh_ZHrBUFpw5Ft_IzNU20QAJav", // tsTON "EQBa6Oofc4vQZ1XZLTYRkbX4qWUWBCf0sFBgo0kdxdlw6rqN", // M5 "EQAvlWFDxGF2lXm67y4yzC17wYKD9A0guwPkMs1gOsM__NOT", // NOT "EQD0KpcRMh-sKO2z5-vOjgvFjTT58tO-2Nmvxqg5ocFQFtWz" // FPIBANK // other token addresses ... ], otherConfig... }); ``` > 🛑 This setting completely replaces the default token list — use it when you want a hard limit on what's shown. ### Default Assets By default, the widget always displays assets: * **TON** `(Toncoin)` * **USDT** `(Tether USDT on TON)` * **CES** `(swap.coffee)` *** These are included automatically, even when no configuration is provided. ### Search for Any Token Even if a token is not in the list, users can still discover it using the **built-in token search**. > ✅ As long as the token is listed on [swap.coffee](https://swap.coffee), it can be found. ## `enableCommunityTokens` ```typescript theme={null} enableCommunityTokens?: boolean; ``` Controls whether community tokens are included in the main token list. **Defaults to `true`**. * **`true`** (default): Community tokens are included in the main token list and mixed with whitelist tokens from swap.coffee * **`false`**: Only verified or imported tokens will be shown, excluding community tokens ```typescript theme={null} createSwapWidget("#test", { enableCommunityTokens: false, // Only verified tokens otherConfig... }); ``` > 📝 **Note** -- When disabled, users will only see tokens that have been officially verified or manually imported, providing a more curated token selection. # UI-Based Settings Source: https://docs.swap.coffee/technical-guides/aggregator-widget/advanced/ui-based Optional configuration flags that influence how the widget looks on first load. These parameters allow you to adjust the **visual behavior** of the `widget` when it first loads. They are helpful to better match your product's flow or `hide features` that may not be relevant to **your users**. > ⚠️ These parameters are purely visual — they `do not affect the widget's logic`, supported operations, or **API interactions**. *** ## `firstTokenAmount` ```typescript theme={null} firstTokenAmount?: number; ``` This parameter defines the **pre-filled** token amount in the **input field** when the widget is `first rendered`. It’s useful in cases where you want to give users a `ready-to-go` value, especially for preconfigured flows or **one-click experiences**. ```typescript theme={null} createSwapWidget("#test", { firstTokenAmount: 50, otherConfig..., }); ``` > 💡 If not set, the input field will be 0 by default. ## `limitDcaVisibility` ```typescript theme={null} limitDcaVisibility?: boolean; // default: true ``` This **parameter** controls the visibility of UI components related to: * `Limit orders` * `DCA (Dollar-Cost Averaging)` By default, these modules are **visible**. If your use case `doesn't require those features`, you can explicitly hide them by setting this flag to **false**. ```typescript theme={null} createSwapWidget("#test", { limitDcaVisibility: false, // Hides Limit & DCA modules otherConfig..., }); ``` > 💡 Default value is true, meaning the Limit & DCA UI elements are always shown unless explicitly disabled. # Widget Configuration Source: https://docs.swap.coffee/technical-guides/aggregator-widget/configuration Widget configuration and all about configuration for two connection methods ## Configure Swap Widget with TonConnectUI To integrate our Swap Widget into your application , follow these steps to configure and set up the widget using the `@swapcoffee/ui-sdk` and `@tonconnect/ui`. ### 1. **Create a Configuration File** First, create a configuration file to manage your settings for `TonConnect` and the Swap Widget. This file will include the `manifestUrl` for the TonConnect manifest and other configuration parameters. Here’s an example configuration file named `config.js`: ```javascript theme={null} import { THEME } from "@tonconnect/ui"; // TonConnect manifest URL const manifestUrl = "https://swap.coffee/tonconnect-manifest.json"; // TonConnect configuration export const tonConnectConfig = { /** * The URL of the TonConnect manifest file. * This manifest provides details about the TonConnect application and its settings. * This URL should point to a JSON file located in the public folder of your project. * * @type {string} */ manifestUrl: manifestUrl, /** * User interface preferences for TonConnect. * This allows customization of the appearance of the TonConnect UI. * * @type {Object} * @property {string} theme - The theme of the TonConnect UI. Values include 'DARK' and 'LIGHT'. */ uiPreferences: { theme: THEME.DARK }, }; // Swap Widget configuration export const swapWidgetConfig = { /** * Theme setting for the Swap Widget. * Determines the visual style of the widget. * * @type {string} */ theme: 'dark', /** * The connection method used for integrating the Swap Widget. * Defines how the widget interacts with the wallet for transactions. * * Options: * - 'tonConnect' (most common): Uses TonConnect for seamless wallet integration. * - 'payload': A custom method that bypasses TonConnect and requires manual payload configuration for wallet interactions. * * @type {string} */ injectionMode: 'tonConnect', /** * Locale setting for the Swap Widget. * Defines the language and regional settings for the widget. * * @type {string} */ locale: 'en', /** * Configuration for TonConnect manifest in the Swap Widget. * This setting tells the widget where to find the TonConnect manifest. * * @type {Object} * @property {string} url - The URL of the TonConnect manifest. */ tonConnectManifest: { url: manifestUrl } }; ``` This configuration file allows you to customize both the TonConnect UI and the Swap Widget. Make sure that the manifestUrl points to the correct location of the TonConnect manifest file in your public folder to ensure proper integration and functionality. ### 2. createSwapWidget properties (via TonConnect injection mode) When using the **TonConnect** injection mode, the `createSwapWidget` function accepts several configuration properties that allow you to customize the widget's appearance, behavior, and connection settings. *** #### **Container Selector** (`string`): * The CSS selector for the HTML element where the Swap Widget will be rendered. > **Example**: `'#swap-widget-component'` #### **Configuration Object** (`object`): This object contains the settings to customize the Swap Widget: * **`theme`** (`string`): Defines the visual theme of the widget. > **Options**: `'light'`, `'dark'`, `'coffee'` * **`locale`** (`string`): Specifies the language and regional settings for the widget. > **Options**: `'zh'`, `'ua'`, `'ru'`, `'en'`, `'es'`, `'fr'`, `'fa'` * **`tonConnectManifest`** (`object`): Configuration for the TonConnect manifest. * **`url`** (`string`): The URL pointing to the TonConnect manifest. This manifest contains details about the TonConnect application and its settings. * **`tonConnectUi`** (`TonConnectUI instance`): An instance of `TonConnectUI` for managing wallet connections and interactions. #### **`injectionMode`** (`string`): * Specifies the connection method to be used for wallet interactions. > **Example**: `'tonConnect'` *** ### 3. createSwapWidget usage ```typescript theme={null} import { createSwapWidget } from '@swapcoffee/ui-sdk'; import { TonConnectUI } from '@tonconnect/ui'; import { swapWidgetConfig } from './config'; // Configuration file createSwapWidget('#swap-widget-component', { // Provide the container selector where the Swap Widget will be rendered ...swapWidgetConfig, // Spread the existing Swap Widget configuration // Pass the initialized TonConnectUI instance for TonConnect integration tonConnectUi: tonConnectUiInstance, }); ``` ## Configure Swap Widget with Payload Injection To integrate our Swap Widget into your application, follow these steps to configure and set up the widget using the `@swapcoffee/ui-sdk` with **Payload Injection Mode**. ### 1. **Create a Configuration File** First, create a configuration file to manage your settings for the Swap Widget. This file will include the configuration parameters required for the Payload connection method. Here’s an example configuration file named `config.js`: ```typescript theme={null} // Swap Widget configuration export const swapWidgetConfig = { /** * Theme setting for the Swap Widget. * Determines the visual style of the widget. * * @type {string} */ theme: 'dark', /** * The connection method used for integrating the Swap Widget. * Defines how the widget interacts with the wallet for transactions. * * Options: * - 'tonConnect' (most common): Uses TonConnect for seamless wallet integration. * - 'payload': A custom method that bypasses TonConnect and requires manual payload configuration for wallet interactions. * * @type {string} */ injectionMode: 'payload', /** * Locale setting for the Swap Widget. * Defines the language and regional settings for the widget. * * @type {string} */ locale: 'en', }; ``` This configuration file allows you to customize the `Payload Injection Mode` for the **Swap Widget**. The `injectionMode` parameter is set to `'payload'`, indicating that the widget will **bypass TonConnect** and use a custom method for handling wallet interactions. *** ### 2. `Payload` Connection Configuration Structure for `Swap Widget` To configure the `Payload` connection for the `swap.coffee widget`, you need to define the `payload` object. This object contains all necessary parameters for establishing a manual wallet connection. > Here is an example configuration (`payload.js`): ```typescript theme={null} export const payloadConnectionExampleConfig = { /** * The wallet's metadata that is used to authenticate the wallet connection. * This includes the wallet address and the relevant signatures for secure communication. * * @type {object} */ wallet_meta: { /** * The address of the wallet, which is used for identifying the wallet in the transaction. * * @type {string} * @example "0:e82b785a9f11c271ce0418a921aa3fa255a98f6cff88be610b8ce2df66ed3ba6" */ address: "0:e82b785a9f11c271ce0418a921aa3fa255a98f6cff88be610b8ce2df66ed3ba6", }, /** * The verification data required for confirming the wallet connection. * This object contains the public key and the wallet's state initialization data, * along with a proof signature to ensure secure communication. * * @type {object} */ verify: { /** * The public key of the wallet. This is used to authenticate the wallet in the connection process. * * @type {string} * @example "a4e1e6811b634985c82132c636fc7fbfef831bbfcf1593dc35f8291fe2c4af2c" */ public_key: "a4e1e6811b634985c82132c636fc7fbfef831bbfcf1593dc35f8291fe2c4af2c", /** * The initial state of the wallet, which is encoded in Base64 format. * This includes the wallet's code and the initialization parameters necessary to establish the wallet's state. * * @type {string} * @example "to4cckECFgEAAwQAAgE0ARUBFP8A9KQT9LzssAsCAgEgAxACAUgEBwLm0AHQ0wMhcbCSXwTgItdJwSCSXwTgAtMfIYIQcGx1Z70ighBkc3RyvbCSXwXgA/pAMCD6RAHIygfL/8nQ7UTQgQFA1yH0BDBcgQEI9ApvoTGzkl8H4AXTP8glghBwbHVnupI4MOMNA4IQZHN0crqSXwbjDQUGAHgB+gD0BDD4J28iMFAKoSG+8uBQghBwbHVngx6xcIAYUATLBSbPFlj6Ahn0AMtpF8sfUmDLPyDJgED7AAYAilAEgQEI9Fkw7UTQgQFA1yDIAc8W9ADJ7VQBcrCOI4IQZHN0coMesXCAGFAFywVQA88WI/oCE8tqyx/LP8mAQPsAkl8D4gIBIAgPAgEgCQ4CAVgKCwA9sp37UTQgQFA1yH0BDACyMoHy//J0AGBAQj0Cm+hMYAIBIAwNABmtznaiaEAga5Drhf/AABmvHfaiaEAQa5DrhY/AABG4yX7UTQ1wsfgAWb0kK29qJoQICga5D6AhhHDUCAhHpJN9KZEM5pA+n/mDeBKAG3gQFImHFZ8xhAT48oMI1xgg0x/TH9MfAvgju/Jk7UTQ0x/TH9P/9ATRUUO68qFRUbryogX5AVQQZPkQ8qP4ACSkyMsfUkDLH1Iwy/9SEPQAye1U+A8B0wchwACfbFGTINdKltMH1AL7AOgw4CHAAeMAIcAC4wABwAORMOMNA6TIyx8Syx/L/xESExQAbtIH+gDU1CL5AAXIygcVy//J0Hd0gBjIywXLAiLPFlAF+gIUy2sSzMzJc/sAyEAUgQEI9FHypwIAcIEBCNcY+gDTP8hUIEeBAQj0UfKnghBub3RlcHSAGMjLBcsCUAbPFlAE+gIUy2oSyx/LP8lz+wACAGyBAQjXGPoA0z8wUiSBAQj0WfKnghBkc3RycHSAGMjLBcsCUAXPFlAD+gITy2rLHxLLP8lz+wAACvQAye1UAFEAAAAAKamjF6Ph5YEdY0mFyCEyxjb8f7/vgxu/zxWT3DX4KR/ixK8sQN9iJtU=", */ wallet_state_init: "to4cckECFgEAAwQAAgE0ARUBFP8A9KQT9LzssAsCAgEgAxACAUgEBwLm0AHQ0wMhcbCSXwTgItdJwSCSXwTgAtMfIYIQcGx1Z70ighBkc3RyvbCSXwXgA/pAMCD6RAHIygfL/8nQ7UTQgQFA1yH0BDBcgQEI9ApvoTGzkl8H4AXTP8glghBwbHVnupI4MOMNA4IQZHN0crqSXwbjDQUGAHgB+gD0BDD4J28iMFAKoSG+8uBQghBwbHVngx6xcIAYUATLBSbPFlj6Ahn0AMtpF8sfUmDLPyDJgED7AAYAilAEgQEI9Fkw7UTQgQFA1yDIAc8W9ADJ7VQBcrCOI4IQZHN0coMesXCAGFAFywVQA88WI/oCE8tqyx/LP8mAQPsAkl8D4gIBIAgPAgEgCQ4CAVgKCwA9sp37UTQgQFA1yH0BDACyMoHy//J0AGBAQj0Cm+hMYAIBIAwNABmtznaiaEAga5Drhf/AABmvHfaiaEAQa5DrhY/AABG4yX7UTQ1wsfgAWb0kK29qJoQICga5D6AhhHDUCAhHpJN9KZEM5pA+n/mDeBKAG3gQFImHFZ8xhAT48oMI1xgg0x/TH9MfAvgju/Jk7UTQ0x/TH9P/9ATRUUO68qFRUbryogX5AVQQZPkQ8qP4ACSkyMsfUkDLH1Iwy/9SEPQAye1U+A8B0wchwACfbFGTINdKltMH1AL7AOgw4CHAAeMAIcAC4wABwAORMOMNA6TIyx8Syx/L/xESExQAbtIH+gDU1CL5AAXIygcVy//J0Hd0gBjIywXLAiLPFlAF+gIUy2sSzMzJc/sAyEAUgQEI9FHypwIAcIEBCNcY+gDTP8hUIEeBAQj0UfKnghBub3RlcHSAGMjLBcsCUAbPFlAE+gIUy2oSyx/LP8lz+wACAGyBAQjXGPoA0z8wUiSBAQj0WfKnghBkc3RycHSAGMjLBcsCUAXPFlAD+gITy2rLHxLLP8lz+wAACvQAye1UAFEAAAAAKamjF6Ph5YEdY0mFyCEyxjb8f7/vgxu/zxWT3DX4KR/ixK8sQN9iJtU=", /** * The proof object is used to verify the integrity of the transaction. * It contains the timestamp, domain, payload, and the signature that is used for the proof. * * @type {object} */ proof: { /** * The timestamp of when the signature was created, in seconds since the UNIX epoch (UTC). * * @type {number} * @example 1731021811 */ timestamp: 1731021811, /** * The length of the domain name being verified, typically 11 characters for the Swap Widget. * * @type {number} * @example 11 */ domain_len: 11, /** * The domain name associated with the transaction, which should match the domain the wallet is connecting from. * * @type {string} * @example "swap.coffee" */ domain_val: "swap.coffee", /** * The payload of the wallet transaction, a string that uniquely identifies the transaction or action being verified. * * @type {string} * @example "uD3ZE2YmeErIlVNhYItMnoiPfeDqSDCs" */ payload: "uD3ZE2YmeErIlVNhYItMnoiPfeDqSDCs", /** * The signature for the proof, ensuring the authenticity of the transaction. * * @type {string} * @example "CDbBPcRMRcflfqhNK8FAW7uzcK7MZZGsK3+o+atFXAdQAs3NsGZt/YpeDZoes55bBgzQwk2hraHMOJyfZrDPBg==" */ signature: "CDbBPcRMRcflfqhNK8FAW7uzcK7MZZGsK3+o+atFXAdQAs3NsGZt/YpeDZoes55bBgzQwk2hraHMOJyfZrDPBg==" } } } ``` ### 3. createSwapWidget properties (via `payload` injection mode) When using the `payload` **injection mode**, the `createSwapWidget` function accepts several configuration properties that allow you to customize the widget's appearance, behavior, and connection settings. *** #### **Container Selector** (`string`): * The CSS selector for the HTML element where the Swap Widget will be rendered. > **Example**: `'#swap-widget-component'` #### **Configuration Object** (`object`): This object contains the settings to customize the Swap Widget: * **`theme`** (`string`): Defines the visual theme of the widget. > **Options**: `'light'`, `'dark'`, `'coffee'` * **`locale`** (`string`): Specifies the language and regional settings for the widget. > **Options**: `'zh'`, `'ua'`, `'ru'`, `'en'`, `'es'`, `'fr'`, `'fa'` #### **Payload Object** (`object`): * **`payload`** (`object`): The main object for configuring the connection to `injectionMode: 'payload'` the `swap.coffee widget`, containing all the necessary parameters to establish the connection through the wallet. > **Example**: for more information, please refer to [section 2](#2-payload-connection-configuration-structure-for-swap-widget) (`Payload` Connection Configuration Structure for `Swap Widget`). #### **`injectionMode`** (`string`): * Specifies the connection method to be used for wallet interactions. > **Options**: `'payload'` *** ### 4. createSwapWidget usage ```typescript theme={null} import { createSwapWidget } from '@swapcoffee/ui-sdk'; import { swapWidgetConfig } from './config'; // Configuration file import { payloadConnectionConfig } from "./payload"; // Path to your payload createSwapWidget('#swap-widget-component', { // Provide the container selector where the Swap Widget will be rendered ...swapWidgetConfig, // Spread the existing Swap Widget configuration // The 'payload' contains the necessary configuration for connecting the widget payload: payloadConnectionConfig, }); ``` # Events Workflow Source: https://docs.swap.coffee/technical-guides/aggregator-widget/events-feature These events allow for enhanced monitoring, reporting, and analytics. ## Overview Each of these **events** provides critical information that can be used to monitor user interactions, improve platform functionality, and generate comprehensive analytics reports. ### Supported Events Here are the events we currently support: *** ****event\_route\_built**** - `Triggered when a route is built`. ****event\_token\_changed**** - `Triggered when the selected token changes`. ****event\_swap\_settings\_updated**** - `Triggered when the swap settings are updated`. ****event\_token\_imported**** - `Triggered when a token is imported`. ****event\_transactions\_built**** - `Triggered when a set of transactions is built`. ****event\_swap\_result\_received**** - `Triggered when the swap result is received`. ****event\_wallet\_connected**** - `Triggered on wallet successfully connected` ****event\_wallet\_disconnected**** - `Triggered when wallet was disconnected` ****event\_swap\_started**** - `Triggered when SWAP transaction confirmed by wallet and started` ****event\_swap\_completed**** - `Triggered when SWAP or MultiSwap operation completed` ****event\_multi\_swap\_started**** - `Triggered when MultiSwap transaction confirmed by wallet and started` *** ### How to Listen our Events To listen for these **events** on the client side, you can use the `addEventListener` method. Here's how you can listen `event_route_built` event as example: ```typescript theme={null} // Event listener for the 'event_route_built' event window.addEventListener('event_route_built', (event) => { console.log('Route build, details:', event.detail); }); ``` ### Event Detail Each of these events carries additional data that can be accessed through `event.detail`. For example: * **`event_route_built`**: Contains information about the route, including the tokens involved and estimated fees. * **`event_token_changed`**: Contains the details of the token that has been changed. * **`event_swap_settings_updated`**: Contains the updated swap settings. * **`event_token_imported`**: Contains the details of the imported token. * **`event_transactions_built`**: Contains the details of the built transactions. * **`event_swap_result_received`**: Contains the result of the swap. * **`event_wallet_connected`**: Contains information about the connected wallet, including wallet type and address. * **`event_wallet_disconnected`**: Contains information about the disconnected wallet. * **`event_swap_started`**: Contains details about the started swap transaction, including transaction hash and tokens involved. * **`event_swap_completed`**: Contains the final result of the completed swap operation, including success status and transaction details. * **`event_multi_swap_started`**: Contains details about the started multi-swap transaction, including transaction hash and involved token pairs. ## Conclusion By following the guidelines outlined in this documentation, you can effectively manage events such as route building, token changes, swap settings updates, and more. # Start with UI Widget Source: https://docs.swap.coffee/technical-guides/aggregator-widget/introduction Integrate widget of swap.coffee aggregator in a couple of minutes.

swap.coffee logo

Swap Widget for integration swap.coffee DEX aggregator into your web application

npm License

# Installation The Swap Widget can be easily integrated into any web framework **(React, Vue, Angular, etc.)**. To install the SDK for `JavaScript/TypeScript`, use the following npm package: ```bash theme={null} $ npm install @swapcoffee/ui-sdk ``` ## Concepts Basic concept you need to know to work with our Swap Widget: * **TonConnectUI**: **TonConnectUI** is a library that simplifies the integration of the `TON` blockchain into your application. It provides a user-friendly interface for connecting and interacting with TON-compatible wallets, allowing users to perform transactions. With TonConnect, you can securely handle wallet connections within the `Swap Widget`, enhancing the user experience for token swaps. * **X-Verify(Ton Proof)**: is a secure mechanism for identity verification and user authentication through their `TON` wallet. It enables decentralized applications to confirm wallet ownership, ensuring trusted interactions for access control, voting, or other features requiring user validation. > You can learn more about **TonConnect** or **X-Verify(Ton Proof)** and its features here ([TonConnect](https://docs.ton.org/develop/dapps/ton-connect/developers), [X-Verify(TonProof)](https://docs.ton.org/develop/dapps/ton-connect/sign)). ## How our swap.coffee widget works 1. **Connect Your Wallet**: * Start by connecting your wallet through TonConnect. This step allows the widget to interact with your wallet and manage your tokens securely. 2. **Configure the Widget**: * **Basic Settings**: customize essential parameters such as slippage tolerance. These settings help in determining the acceptable range for price changes during the swap. * **Advanced Settings**: for more control, adjust expert settings including: * Price Impact - Swap Widget will not let you perform a swap if the price impact is more than this percentage. * Pools Volatility - You can exclude routes that use highly volatile (and therefore high-risk) pools. * Parallel Transactions - You can set the maximum number of parallel transactions, which allows for build more profitable routes. * Intermediate Tokens - You can configure the max number of intermediate tokens, thereby controlling the length of the route. 3. **Select Tokens**: * Choose the token you wish to exchange and the token you want to receive. This selection initiates the swap process. 4. **Routing and Optimization**: * The widget communicates with the swap.coffee API to retrieve a comprehensive routing scheme for your token swap. This includes details on which decentralized exchanges (DEXs) will be used and the chosen routes. This is where our unique routing system comes into play, optimizing the swap for the best possible rate and efficiency. 5. **Confirm and Execute Transaction**: * Review the transaction conditions and routing details provided. If satisfied, proceed by confirming the transaction. * After initiating the transaction, an animated window will appear showing the status of the transaction. Once the transaction is successfully processed, this window will display a confirmation message along with a success animation and details about the exchange. You can then enjoy a seamless and efficient token exchange experience. ## User Preferences The Swap Widget offers customization options for both themes and languages. Here’s a detailed overview: ### 1. **Available Themes** The Swap Widget supports the following themes: * **`light`** - a light-themed interface designed for bright environments, providing a clean and minimalist appearance. * **`dark`** - a dark-themed interface suitable for low-light environments, offering a sleek, modern look. * **`coffee`** - a coffee-themed interface with a warm, earthy color scheme that provides a unique and cozy aesthetic. ### 2. **Available Languages** The Swap Widget supports multiple languages to accommodate users from different regions. Currently available languages include: * **`zh`**: Chinese * **`ua`**: Ukrainian * **`ru`**: Russian * **`en`**: English * **`es`**: Spanish * **`fr`**: French * **`fa`**: Persian ### 3. **Introduction to the createSwapWidget** To get started with the Swap Widget, you'll use the `createSwapWidget` function. This function is a core part of our SDK and is responsible for creating an instance of the Swap Widget within your application. **Function Overview** * **`createSwapWidget`** - initializes the Swap Widget and integrates it into your application. It takes a container element selector and a configuration object to customize the widget’s appearance and behavior. **Importing `createSwapWidget`** You can import the `createSwapWidget` function from our SDK package as follows: ```typescript theme={null} import { createSwapWidget } from '@swapcoffee/ui-sdk'; ``` ### 4. **Styling** (Optional) You can style only the **external container** of the widget, as internal styling is controlled by the widget's predefined themes. The available themes are: * **light** * **dark** (applied by default) * **coffee**: Custom styling options are limited to the external container, and the themes control the primary look and feel of the widget. Here’s an example of basic styling for the widget container: ```css theme={null} ``` ## Types of Connection The `swap.coffee widget` offers two methods for connecting your application to our platform, tailored to different use cases and levels of complexity: *** 1. **TonConnect** > The **TonConnect** method is the simpler and more streamlined way to connect. If your application already supports **TonConnectUI** library, this is the recommended approach as it allows seamless integration with minimal configuration. **TonConnect** handles wallet authentication and transaction signing, making it ideal for projects that prioritize ease of use and compatibility with existing `TON` ecosystem wallets. 2. **Payload-Based** Connection > For scenarios where **TonConnect** is unavailable or unsupported, the `swap.coffee widget` provides an alternative connection method through a custom `payload` mechanism. This approach eliminates the dependency on TonConnect, offering greater flexibility and ensuring compatibility in diverse environments. While slightly more complex, the `payload` method gives developers **full control** over authentication and **transaction processes**. *** In the [**next section**](/technical-guides/aggregator-widget/configuration), we will guide you through configuring both connection methods step-by-step, ensuring that you can integrate the `Swap Widget` in the way that best suits your application's needs. # Playground Source: https://docs.swap.coffee/technical-guides/aggregator-widget/playground Interactive playground for testing Swap Widget ## Overview Our playground allows you to quickly test the **Swap Widget** without setting up your own project. Here you can: * **View demo**: See the widget working in real-time * **Test features**: Try all core widget capabilities * **Experiment with settings**: Change themes, languages, and other parameters * **View code**: See integration examples ## Launch Playground Click the button to open the playground in a new window

Open in StackBlitz

## What's Included ### 🚀 Quick Start The playground includes a fully configured project with: * Installed `@swapcoffee/ui-sdk` * Basic widget configuration * Wallet connection examples via TonConnect ## Additional Resources * **[Introduction](/technical-guides/aggregator-widget/introduction)** - Detailed feature overview * **[Configuration](/technical-guides/aggregator-widget/configuration)** - Step-by-step setup * **[GitHub Repository](https://github.com/vladi4kai/swap-sdk-playground)** - Playground source code ## Support If you have questions or issues with the playground: * Check the [documentation](/technical-guides/aggregator-widget/introduction) * Create an issue in the [GitHub repository](https://github.com/vladi4kai/swap-sdk-playground/issues) * Contact our support team # Code Snippets Source: https://docs.swap.coffee/technical-guides/dex/code-snippets Learn how to perform this or that action with dex contracts ## Generic Information All code examples are written in TypeScript using [Blueprint](https://github.com/ton-org/blueprint). If you need more implementation details, refer to the [DEX source code](https://github.com/swapcoffee/dex): it contains OOP implementations of all contracts, so this page is likely temporary until a full-fledged SDK is created based on that code. This document is for reference only and may contain errors. If you come across any, please consider contacting us via Telegram [@swap.coffee DEV Chat](https://t.me/swapcoffee_dev_chat). ## (De)serialization of assets ```typescript theme={null} import { Address, beginCell, Builder, Cell, Slice } from '@ton/core'; export abstract class CellSerializable { public abstract write(b: Builder): void; public toCell(): Cell { const b = beginCell(); this.write(b); return b.endCell(); } } export abstract class Asset extends CellSerializable { static fromSlice(slice: Slice): Asset { const type = slice.loadUint(2); if (type === 0) { return AssetNative.INSTANCE; } else if (type === 1) { return new AssetJetton(slice.loadUintBig(8), slice.loadUintBig(256)); } else if (type === 2) { return new AssetExtra(slice.loadUintBig(32)); } else { throw new Error('unexpected asset type'); } } static fromAny(value: any): Asset { if (value == null) { return AssetNative.INSTANCE; } else if (value instanceof Address) { return AssetJetton.fromAddress(value); } else if (typeof value === 'bigint') { return new AssetExtra(value); } else { throw new Error('unexpected asset type'); } } } export class AssetNative extends Asset { static INSTANCE = new AssetNative(); private constructor() { super(); } public write(b: Builder): void { b.storeUint(0, 2); } } export class AssetJetton extends Asset { constructor( public chain: bigint, public hash: bigint, ) { super(); } static fromAddress(address: Address): AssetJetton { return new AssetJetton( BigInt(address.workChain), beginCell().storeBuffer(address.hash).endCell().beginParse().loadUintBig(256), ); } public write(b: Builder): void { b.storeUint(1, 2).storeUint(this.chain, 8).storeUint(this.hash, 256); } public getAddress(): Address { return beginCell() .storeUint(4, 3) .storeUint(this.chain, 8) .storeUint(this.hash, 256) .endCell() .beginParse() .loadAddress() } } export class AssetExtra extends Asset { constructor(public id: bigint) { super(); } public write(b: Builder): void { b.storeUint(2, 2).storeUint(this.id, 32); } } ``` ## Vaults ### Checking for existence and activity To check whether asset's **Vault** exists and is active, you firstly need to [fetch](/technical-guides/dex/get-methods#get-vault-address) its address from the factory, then invoke a get-method [is\_active](/technical-guides/dex/get-methods#is-active). ```typescript theme={null} import { NetworkProvider } from '@ton/blueprint'; import { Address } from '@ton/core'; export async function run(provider: NetworkProvider) { const asset: Asset = AssetNative.INSTANCE // or AssetJetton or AssetExtra const factoryAddress = Address.parse('EQAsf2sDPfoo-0IjnRA7l_gJBB9jyo4zqfCG_1IFCCI_Qbef') let resp = await provider.provider(factoryAddress).get('get_vault_address', [{ type: 'slice', cell: asset.toCell() }]) const vaultAddress = resp.stack.readAddress() const vault = provider.provider(vaultAddress) const vaultState = await vault.getState() if (vaultState.state.type !== 'active') { throw new Error('Vault does not exist') } resp = await vault.get('is_active', []) const isActive = resp.stack.readBigNumber() !== 0n if (!isActive) { throw new Error('Vault exists, but is not active') } } ``` ### Creating a new one To create a new **Vault**, you need to send a [create\_vault](/technical-guides/dex/tlb-schemes#activatevault) internal message to the factory. If you are creating a **Vault** for **jetton**, make sure it goes through activation process as described [here](/technical-guides/dex/tlb-schemes#activatevaultinternal). If it was unable to automatically activate itself, please contact us via Telegram [@swap.coffee DEV Chat](https://t.me/swapcoffee_dev_chat). ```typescript theme={null} import { NetworkProvider } from '@ton/blueprint'; import { beginCell, toNano, Address } from '@ton/core'; export async function run(provider: NetworkProvider) { const asset: Asset = AssetNative.INSTANCE // or AssetJetton or AssetExtra const factoryAddress = Address.parse('EQAsf2sDPfoo-0IjnRA7l_gJBB9jyo4zqfCG_1IFCCI_Qbef') const builder = beginCell() .storeUint(0xc0ffee06, 32) .storeUint(0, 64) asset.write(builder) await provider.sender().send({ to: factoryAddress, value: toNano(.05), body: builder.endCell() }) } ``` ## Pools ### Creating a new one 1. Check that **Vault**s for both assets exist and are active (or create them instead). 2. Send create\_pool messages to both **Vault**s. Type of each message depends on the type of asset of associated **Vault**: * For TON, use [create\_pool\_native](/technical-guides/dex/tlb-schemes#createpoolnative). * For Jetton, use [create\_pool\_jetton](/technical-guides/dex/tlb-schemes#createpooljetton) as a forward payload in jetton\_transfer. * For Extra Currency, use [create\_pool\_extra](/technical-guides/dex/tlb-schemes#createpoolextra). ```typescript theme={null} import { NetworkProvider } from '@ton/blueprint'; import { beginCell, toNano, Address, Builder } from '@ton/core'; export async function run(provider: NetworkProvider) { const asset1: Asset = AssetNative.INSTANCE // or AssetJetton or AssetExtra const asset1Amount = 100n const asset2: Asset = new AssetExtra(1n) // or AssetNative or AssetJetton const asset2Amount = 100n const factoryAddress = Address.parse('EQAsf2sDPfoo-0IjnRA7l_gJBB9jyo4zqfCG_1IFCCI_Qbef') const factory = provider.provider(factoryAddress) let resp = await factory.get('get_vault_address', [{ type: 'slice', cell: asset1.toCell() }]) const vault1Address = resp.stack.readAddress() resp = await factory.get('get_vault_address', [{ type: 'slice', cell: asset2.toCell() }]) const vault2Address = resp.stack.readAddress() if (!provider.sender().address) { throw new Error('Sender address must be present') } const poolParams = beginCell() asset1.write(poolParams) asset2.write(poolParams) poolParams.storeUint(0, 3) // constant_product AMM poolParams.storeMaybeRef(null) // no AMM settings const poolCreationParams = beginCell() .storeAddress(provider.sender().address) // recipient of LP tokens .storeBit(false) // send funds to the address specified above instead of sender in case of failures .storeMaybeRef(null) // no notifications .storeUint(1, 1) // is_active = true .storeMaybeRef(null) // no extra settings await sendCreatePool(provider, poolParams, poolCreationParams, vault1Address, asset1, asset1Amount) await sendCreatePool(provider, poolParams, poolCreationParams, vault2Address, asset2, asset2Amount) } async function sendCreatePool( provider: NetworkProvider, poolParams: Builder, poolCreationParams: Builder, vaultAddress: Address, asset: Asset, amount: bigint ) { const sender = provider.sender() if (asset instanceof AssetNative) { await sender.send({ to: vaultAddress, value: amount + toNano(.1), body: beginCell() .storeUint(0xc0ffee02, 32) // create_pool_native opcode .storeUint(0, 64) .storeCoins(amount) .storeBuilder(poolParams) .storeBuilder(poolCreationParams) .endCell() }) } else if (asset instanceof AssetJetton) { const jettonMaster = provider.provider(asset.getAddress()) let resp = await jettonMaster.get('get_wallet_address', [{ type: 'slice', cell: beginCell().storeAddress(sender.address).endCell() }]) const jettonWalletAddress = resp.stack.readAddress() await sender.send({ to: jettonWalletAddress, value: toNano(.15), body: beginCell() .storeUint(0xf8a7ea5, 32) // jetton_transfer opcode .storeUint(0, 64) .storeAddress(vaultAddress) .storeAddress(sender.address) .storeMaybeRef(null) // no custom_payload .storeCoins(toNano(.1)) // fwd_gas .storeMaybeRef( beginCell() .storeUint(0xc0ffee11, 32) // create_pool_jetton opcode .storeBuilder(poolParams) .storeBuilder(poolCreationParams) .endCell() ).endCell() }) } else if (asset instanceof AssetExtra) { await sender.send({ to: vaultAddress, value: toNano(.1), extracurrency: { [Number(asset.id)]: amount }, body: beginCell() .storeUint(0xc0ffee03, 32) // create_pool_extra opcode .storeUint(0, 64) .storeBuilder(poolParams) .storeBuilder(poolCreationParams) .endCell() }) } } ``` ### Providing liquidity to existing one All you need is to send deposit\_liquidity messages to both **Vault**s. Type of each message depends on the type of asset of associated **Vault**: * For TON, use [deposit\_liquidity\_native](/technical-guides/dex/tlb-schemes#depositliquiditynative). * For Jetton, use [deposit\_liquidity\_jetton](/technical-guides/dex/tlb-schemes#depositliquidityjetton) as a forward payload in jetton\_transfer. * For Extra Currency, use [deposit\_liquidity\_extra](/technical-guides/dex/tlb-schemes#depositliquidityextra). The code itself is very similar to the one used in pools creation: ```typescript theme={null} import { NetworkProvider } from '@ton/blueprint'; import { beginCell, toNano, Address, Cell } from '@ton/core'; export async function run(provider: NetworkProvider) { const asset1: Asset = AssetNative.INSTANCE // or AssetJetton or AssetExtra const asset1Amount = 100n const asset2: Asset = new AssetExtra(1n) // or AssetNative or AssetJetton const asset2Amount = 100n const factoryAddress = Address.parse('EQAsf2sDPfoo-0IjnRA7l_gJBB9jyo4zqfCG_1IFCCI_Qbef') const factory = provider.provider(factoryAddress) let resp = await factory.get('get_vault_address', [{ type: 'slice', cell: asset1.toCell() }]) const vault1Address = resp.stack.readAddress() resp = await factory.get('get_vault_address', [{ type: 'slice', cell: asset2.toCell() }]) const vault2Address = resp.stack.readAddress() if (!provider.sender().address) { throw new Error('Sender address must be present') } const poolParams = beginCell() asset1.write(poolParams) asset2.write(poolParams) poolParams.storeUint(0, 3) // constant_product AMM poolParams.storeMaybeRef(null) // no AMM settings const poolParamsCell = poolParams.endCell() const depositLiquidityParamsCell = beginCell() .storeAddress(provider.sender().address) // recipient of LP tokens .storeBit(false) // send funds to the address specified above instead of sender in case of failures .storeAddress(null) // no referral .storeUint(Math.floor(Date.now() / 1000) + 900, 32) // deadline .storeUint(0, 2) // using no condition .storeMaybeRef(null) // no extra settings .storeMaybeRef(null) // no notifications .endCell() await sendProvideLiquidity(provider, poolParamsCell, depositLiquidityParamsCell, vault1Address, asset1, asset1Amount) await sendProvideLiquidity(provider, poolParamsCell, depositLiquidityParamsCell, vault2Address, asset2, asset2Amount) } async function sendProvideLiquidity( provider: NetworkProvider, poolParams: Cell, depositLiquidityParams: Cell, vaultAddress: Address, asset: Asset, amount: bigint ) { const sender = provider.sender() if (asset instanceof AssetNative) { await sender.send({ to: vaultAddress, value: amount + toNano(.1), body: beginCell() .storeUint(0xc0ffee04, 32) // deposit_liquidity_native opcode .storeUint(0, 64) .storeCoins(amount) .storeRef(depositLiquidityParams) .storeRef(poolParams) .endCell() }) } else if (asset instanceof AssetJetton) { const jettonMaster = provider.provider(asset.getAddress()) let resp = await jettonMaster.get('get_wallet_address', [{ type: 'slice', cell: beginCell().storeAddress(sender.address).endCell() }]) const jettonWalletAddress = resp.stack.readAddress() await sender.send({ to: jettonWalletAddress, value: toNano(.15), body: beginCell() .storeUint(0xf8a7ea5, 32) // jetton_transfer opcode .storeUint(0, 64) .storeAddress(vaultAddress) .storeAddress(sender.address) .storeMaybeRef(null) // no custom_payload .storeCoins(toNano(.1)) // fwd_gas .storeMaybeRef( beginCell() .storeUint(0xc0ffee12, 32) // deposit_liquidity_jetton opcode .storeRef(depositLiquidityParams) .storeRef(poolParams) .endCell() ).endCell() }) } else if (asset instanceof AssetExtra) { await sender.send({ to: vaultAddress, value: toNano(.1), extracurrency: { [Number(asset.id)]: amount }, body: beginCell() .storeUint(0xc0ffee05, 32) // deposit_liquidity_extra opcode .storeUint(0, 64) .storeRef(depositLiquidityParams) .storeRef(poolParams) .endCell() }) } } ``` ### Rolling back liquidity provisioning Both pool creation and liquidity provisioning operations require 2 transactions with corresponding assets to be sent. If only one of them appeared in the blockchain, you may want to rollback the whole process, therefore receiving sent funds back. In order to do so, please follow the given instructions: 1. Inspect the one transaction that appeared in the blockchain, and find out `pool_creator` or `liquidity_depository` contract address. It is the last contract in the transaction execution chain. 2. Send a [withdraw\_deposit](/technical-guides/dex/tlb-schemes#withdrawdeposit) message to that contract. ```typescript theme={null} import { NetworkProvider } from '@ton/blueprint'; import { beginCell, toNano, Address } from '@ton/core'; export async function run(provider: NetworkProvider) { const contractAddress = Address.parse('INSERT ADDRESS HERE') // address of either pool_creator or liquidity_depository await provider.sender().send({ to: contractAddress, value: toNano(.05), body: beginCell() .storeUint(0xc0ffee07, 32) .storeUint(0, 64) .endCell() }) } ``` ### Performing a swap 1. [Fetch](/technical-guides/dex/get-methods#get-vault-address) **Vault**'s address from factory for the input asset. 2. [Fetch](/technical-guides/dex/get-methods#get-pool-address-no-settings) **Pool**s addresses from factory (or another source of truth) for every pool throughout your way. 3. Send swap message to the **Vault** of input asset. Type of the message depends on the type of asset: * For TON, use [swap\_native](/technical-guides/dex/tlb-schemes#swapnative). * For Jetton, use [swap\_jetton](/technical-guides/dex/tlb-schemes#swapjetton) as a forward payload in jetton\_transfer. * For Extra Currency, use [swap\_extra](/technical-guides/dex/tlb-schemes#swapextra). ```typescript theme={null} import { NetworkProvider } from '@ton/blueprint'; import { beginCell, toNano, Address, Builder } from '@ton/core'; export async function run(provider: NetworkProvider) { const inputAsset: Asset = AssetNative.INSTANCE // or AssetJetton or AssetExtra const poolTonUsdtAddress = Address.parse('EQDETPC2Trne37AQx7JKUIFA2G9uB3ifk4O7myFB6pwI6u8M') const poolUsdtTonnelAddress = Address.parse('EQBjj5LzN3L1PvFvH5mzbTc8zp3Sp_vSWmSI3nWKM-Fr3W_g') const inputAssetAmount = toNano(1) const factoryAddress = Address.parse('EQAsf2sDPfoo-0IjnRA7l_gJBB9jyo4zqfCG_1IFCCI_Qbef') const factory = provider.provider(factoryAddress) let resp = await factory.get('get_vault_address', [{ type: 'slice', cell: inputAsset.toCell() }]) const vaultAddress = resp.stack.readAddress() const sender = provider.sender() const swapParamsCell = beginCell() .storeUint(Math.floor(Date.now() / 1000) + 900, 32) // deadline .storeAddress(sender.address) // recipient of output asset .storeAddress(null) // no referral .storeMaybeRef(null) // no notifications .endCell() let swapStepParams: Builder if (noMultihop) { // example for TON -> USDT swapStepParams = beginCell() .storeUint(getHashFromAddress(poolTonUsdtAddress), 256) .storeCoins(0n) // min USDT to receive after swap .storeMaybeRef(null) // no next step } else { // example for TON -> USDT -> TONNEL swapStepParams = beginCell() .storeUint(getHashFromAddress(poolTonUsdtAddress), 256) .storeCoins(0n) // min USDT to receive after 1st swap .storeMaybeRef( beginCell() .storeUint(getHashFromAddress(poolUsdtTonnelAddress), 256) .storeCoins(0n) // min TONNEL to receive after 2nd swap .storeMaybeRef(null) // no next step .endCell() ) } if (inputAsset instanceof AssetNative) { await sender.send({ to: vaultAddress, value: toNano(.05) + inputAssetAmount, body: beginCell() .storeUint(0xc0ffee00, 32) // swap_native opcode .storeUint(0, 64) .storeCoins(inputAssetAmount) .storeBuilder(swapStepParams) .storeRef(swapParamsCell) .endCell() }) } else if (inputAsset instanceof AssetJetton) { const jettonMaster = provider.provider(inputAsset.getAddress()) let resp = await jettonMaster.get('get_wallet_address', [{ type: 'slice', cell: beginCell().storeAddress(sender.address).endCell() }]) const jettonWalletAddress = resp.stack.readAddress() await sender.send({ to: jettonWalletAddress, value: toNano(.1), body: beginCell() .storeUint(0xf8a7ea5, 32) // jetton_transfer opcode .storeUint(0, 64) .storeAddress(vaultAddress) .storeAddress(sender.address) .storeMaybeRef(null) // no custom_payload .storeCoins(toNano(.05)) // fwd_gas .storeMaybeRef( beginCell() .storeUint(0xc0ffee10, 32) // swap_jetton opcode .storeBuilder(swapStepParams) .storeRef(swapParamsCell) .endCell() ).endCell() }) } else if (inputAsset instanceof AssetExtra) { await sender.send({ to: vaultAddress, value: toNano(.05), extracurrency: { [Number(inputAsset.id)]: inputAssetAmount }, body: beginCell() .storeUint(0xc0ffee01, 32) // swap_extra opcode .storeUint(0, 64) .storeBuilder(swapStepParams) .storeRef(swapParamsCell) .endCell() }) } } function getHashFromAddress(address: Address): bigint { return beginCell().storeBuffer(address.hash).endCell().beginParse().loadUintBig(256) } ``` ## Notifications **Notifications** are a system that allows sending a `custom_payload` upon the successful or failed execution of operations on the DEX. They can be used during pool creation, liquidity provisioning or withdrawal, as well as performing swaps. In all these cases, the approach to using notifications is the same: they are optional, and you can specify a notification for only the success case, only the failure case, or define separate notifications for each outcome. Each notification can carry a unique `custom_payload` and have a distinct recipient. Notifications are passed as an additional parameter when constructing a transaction to be sent by the user. However, depending on the operation, there are some differences in how they are ultimately processed. More on that below. Keep in mind that depending on the situation, a notification may be sent either as an internal message with its own opcode, or as a `forward_payload` within a `jetton_transfer`. In both cases, the user-defined `custom_payload` is **not** sent directly: instead, it is encapsulated within a [separate entity](/technical-guides/dex/tlb-schemes#notification). In other words, the recipient must either be capable of handling notification's opcode, or a proxy contract must be used to unwrap the encapsulated message and forward it further. The `fwd_gas` for notification must be explicitly specified in cases where the notification recipient differs from the funds recipient, or when the notification is sent as a `forward_payload` within a `jetton_transfer`. ### On pool creation or liquidity provisioning * In case of failure, the notification will be sent **twice** - once from each **Vault**, along with the refund of the assets that were intended for liquidity provision. * In case of success, the notification will be sent **once**, but the delivery method may vary: * If the notification recipient is the same as the LP tokens recipient, the notification will be delivered as a `forward_payload` inside the `jetton_transfer` that sends the LP tokens. * If recipients differ, the notification will be sent as an internal message with its own opcode. ### On liquidity withdrawal For liquidity withdrawals only on-success notification may be provided. If operation succeeds, the notification will be sent **twice** - once from each **Vault**, along with the refund of the assets that were received as a result of a liquidity withdrawal. ### On swap In all cases the notification will be sent **once** throughout the **Vault**. The method of delivery may vary: * If the recipient of the funds is different from the notification recipient, the notification will be sent as an internal message with its own opcode. * If both the funds and the notification are to be sent to the same address, the behavior depends on the asset type: * If the payout is in **TON** or **Extra Currency**, it will be an internal message with the notification opcode, and the corresponding **TON** or **Extra Currency** tokens will be attached to it. * If the payout is in **Jetton**, the notification - still encapsulating the user's `custom_payload` - will be sent a `forward_payload` within the `jetton_transfer`. # Concepts Source: https://docs.swap.coffee/technical-guides/dex/concepts This page contains information about entities which are essential for understanding the high-level design of the **swap.coffee DEX**. ## Assets Every token, currency or fund user wants to swap or deposit as liquidity throughout **swap.coffee DEX** protocol we call an **Asset**. As for now, protocol supports 3 types of assets (and more may be added in the future). Each of them corresponds to a unique [TL-B scheme](/technical-guides/dex/tlb-schemes#asset), and they're as follows: * **native** - our naming for **TON**coin itself. * **jetton** - any token that corresponds to the [Jetton Standard](https://github.com/ton-blockchain/TEPs/blob/master/text/0074-jettons-standard.md) built on TON Blockchain. * **extra** - tokens that were added to the TON Blockchain as [Extra Currencies](https://docs.ton.org/v3/documentation/dapps/defi/coins#extra-currencies). While having such an abstraction may seem like an unnecessary complication of the system to some, in fact it allows us to abstract work with higher-level entities, which we will describe in more detail in the [contracts section](#contracts). ## AMM Strategies AMM (or Automated Market Maker) strategies are a class of algorithms that sustain pools' asset reserves and mathematically ensure that trades are being performed at a fair (for all participants) price, that no more money is taken out of the **DEX** than was invested in it and a lot of other more-technical things. Each pool is uniquely identified by its assets pair, AMM strategy and AMM settings. It means that within a single implementation of a **swap.coffee DEX** there could not exist two pools of the same AMM strategy, AMM settings and, for example, an assets pair of TON/USDT. Current implementation supports only 2 AMM strategies described below, however the contracts are already coded to support more strategies if (when) it will be needed. If you're interested in addition of new AMM strategies, please contact us via Telegram [@swap.coffee DEV Chat](https://t.me/swapcoffee_dev_chat). ### Constant Product Either known as "volatile" or "Uniswap" AMM. Ensures that product of pool's reserves remains unchanged after any swap or liquidity provisioning/withdrawal after pool is initially created. In other words, if pool's reserves marked as `x` and `y`, their product must equal some predetermined `k = x * y` after every performed swap. So, for example, if we perform a swap by providing some quantity of first asset marked as `dx` and want to receive some of the second asset, quantity of second asset, marked as `dy`, must be calculated from the formula `x * y = (x + dx) * (y - dy)`. ### CurveFi Stable AMM strategy designed especially for stable-coins like USDT/USDC, prices of which should not differ widely. On the demand side, it offers a Uniswap-like automated exchange with very low price slippage (typically 100 times smaller). On the supply side, it offers a multi-stablecoin "savings account" which, according to simulation and countless production use-cases on other blockchains, can bring 300% APR, assuming that traders will arbitrage between this AMM strategy and **Constant Product** pools. More detailed explanation is available in [Curve.Fi's Document](https://docs.curve.fi/assets/pdf/stableswap-paper.pdf). An example of implementation may be found on [Curve.Fi's Repository](https://github.com/curvefi/curve-contract/blob/master/contracts/pools/eurs/StableSwapEURS.vy). Our implementation also supports assets weights, one of common use-cases for which is to normalize pool's assets whenever they have different values of decimals. ## Contracts **swap.coffee DEX** protocol introduces contracts of 5 (and a half) different types, which are described below. ### Factory The "heart" of the protocol. It serves three purposes: 1. To deploy any other contracts within the same installation of **swap.coffee DEX**. 2. To be an entry-point for any administrative actions. Any time administrator wants to perform one of them, he sends message not to the destination contract, but proxies it throughout the **Factory**. 3. And by being the central part in the security of inter-contract communications. They do not proxy their messages throughout the **Factory**, but it serves as a "cryptographic key" when they sign and verify messages of each other. #### Init This is that "half" we wrote above :) Every time **Factory** is about to deploy a new contract, it actually deploys this **Init** contract, followed by a command to overwrite its code and data cells with those that correspond to an actual type of contract **Factory** wanted to deploy. Such mechanism is being used because of how addresses work in TON blockchain: they depend on the code and data cells with which contract was initially deployed; and especially because of such behaviour it is possible to utilize inter-contract security system we developed within our protocol. ### Vault **Vaults** are main entry points for users: every time you want to perform a swap, create new pool or deposit a liquidity, you will send messages to the **Vaults**. They receive your assets, keep them on their side, and redirect your request via inter-contract communication down the road. Whenever another contract decides it's time to process a payout for you, it sends an inter-contract message to the corresponding **Vault**, and after that you receive a payment. **Vault** itself, as a naming, is a declaration of not a contract source code, but of a type (or rather interface) of contracts. Each asset type has its own implementation of **Vault** contract, therefore there are 3 of them: * **Native Vault** - there is only one, and it serves as a treasury for **TON**coin. * **Jetton Vaults** - there is one for every **Jetton** our there. * **Extra Vaults** - similarly to **Jetton Vaults**, there is one for every **Extra Currency** in TON Blockchain; but also similarly to **Native Vault** it accepts direct messages (i.e. transactions) from the users, whilst **Jetton Vaults** react to payloads from jetton transfer notifications. ### Pool Unlike **Vaults**, all the **Pools** share the same codebase: it's a single contract source code. As described below, they're being uniquely identified by the asset pair, AMM strategy type and AMM settings. Users don't directly communicate with the **Pools** on-chain: they support only inter-contract communication. ### PoolCreator and LiquidityDepository These two utility contract types are being used as a user's personal treasury anytime he is trying to create new pool or deposit some liquidity. They're being created by inter-contract communication after you already sent your assets to the corresponding **Vaults**, and they auto-destroy after process of new pool creation or liquidity provisioning comes to an end. # Error Codes Source: https://docs.swap.coffee/technical-guides/dex/error-codes This page contains extensive information about all exit codes with which execution of **DEX** contracts may end up with. Additionally to [standard exit codes](https://docs.ton.org/v3/documentation/tvm/tvm-exit-codes), our contracts feature some new ones: | Error Code | Name | Description | | ---------- | ------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | 6 | Unknown opcode (Standard) | Contract received internal message with unknown opcode or contract received jetton transfer notification with custom payload, which contains unknown opcode | | 40 | Not Enough Gas (Standard) | There is not enogh gas to perform (or continue) contract execution | | 250 | Unexpected | Some unexpected error occurred. Please, contact **swap.coffee** administration if you face this issue | | 251 | Invalid Request | Internal error that signifies about inter-contract communication going wrong | | 252 | Wrong Sender | Indicates that internal message have been sent by inappropriate contract. Usually met when somebody tries to "hack" **DEX** contracts | | 253 | Not a Factory | Indicates that internal message was expected to be sent by the factory, but it's sender differs. Usually met when somebody tries to "hack" **DEX** contracts | | 254 | Not an Admin | Indicates that internal message was expected to be sent by the administrative wallet, but it's sender differs. Usually met when somebody tries to "hack" **DEX** contracts | | 255 | Wrong Chain | Thrown when address other than from basechain (id = 0) was received as an argument in some query | | 256 | Wrong Assets | Thrown on a swap if pool doesn't correlate with given assets or if it is unable to determine which asset is input and which is output | | 257 | Same Assets | Thrown when user tries to swap/deposit liquidity/create pool for a pair of very same assets | | 258 | Wrong Signature | Thrown at a proof validation stage if proof's signature is not valid. Usually met when somebody tries to "hack" **DEX** contracts | | 259 | Invalid Balance | Indicates that message wasn't provided with enough currency | | 260 | Invalid Jetton Master | Thrown on **Jetton Vault** if activation failed due to **Jetton Master** unexpected response | | 261 | Unknown AMM | Thrown when user tries to create pool of unknown AMM | | 262 | AMM Failed | Internal error that signifies about AMM strategy logic going wrong. Please, contact **swap.coffee** administration if you face this issue | | 263 | Invalid AMM Settings | Internal error that signifies about wrong pool setup. Please, contact **swap.coffee** administration if you face this issue | | 264 | Invalid Liquidity | Thrown if user tried to deposit less liquidity than minimum allowed or in case of zero-amount of one of the assets on liquidity deposition stage | | 265 | Invalid Fees | Thrown when **DEX** administrator tried to set invalid fees for the pool or tried to withdraw too much of collected protocol fees | | 266 | Invalid Condition | Indicates that liquidity deposition condition is of inappropriate format or contains invalid data | | 267 | Invalid Asset Type | Indicates that internal message's body was built wrong and asset in it couldn't be deserialized | | 268 | Deadline Exceeded | Indicates that deadline (the one that's being specified in request body) for swap or liquidity deposition exceeded by the time contract received and tried to handle that message | | 269 | Slippage Tolerated | Indicates that request couldn't be executed, because slippage limitation (the one that's being specified in request body) had been triggered | | 270 | Pool Already Exists | Thrown on pool creation request handling if pool already exists | | 271 | Reserves Ratio Failed | Indicates that liquidity deposition reserves ratio condition (the one that's being specified in the deposit request body) check failed | | 272 | Already Active | Internal error that is being thrown whenever contracts or **DEX** administrator try to activate vault or pool, but it's already active | | 273 | Not Active | Thrown whenever user tries to swap/create pool/deposit liquidity throughout inactive vault or pool | # Examples with Visualizations Source: https://docs.swap.coffee/technical-guides/dex/examples-with-visualizations This page describes and visualizes processes which are essential for users interacting with **swap.coffee DEX**. Keep in mind that in order to make things easier to understand, many aspects of the visualizations have been simplified. ## Vault Creation If you are interested in adding new asset to the **swap.coffee DEX**, firstly you must create a **Vault** for it. As shown below, you must send a [special message]() to the **Factory** and wait until it deploys a **Vault** for you. If you are creating a **Vault** for **jetton**, make sure it goes through activation process as described [here](/technical-guides/dex/tlb-schemes#activatevaultinternal). You can check whether **Vault** is active by calling `is_active` get-method on it. If it is not, please contact us via Telegram [@swap.coffee DEV Chat](https://t.me/swapcoffee_dev_chat). Our recommendation for gas is `0.05 TON`. Excesses **won't** be returned. Vault Creation ## Pool Creation After you ensured that **Vaults** for both of the assets you want to create pool for exist (or you created them as well), it is time to create the **Pool**. Unlike many other **DEX**es, it is not possible in **swap.coffee DEX** protocol to create new **Pool** without providing it with initial liquidity. Therefore, in order to create a new **Pool**, you must send two messages: one to pool's first asset **Vault**, and second to pool's second asset **Vault**. After they both reach their destinations, an inter-contract communication will be initialized that will lead to new **Pool** creation. Keep in mind that pools with AMM strategies other than **Constant Product** may be created by **DEX** administration only. If you're interested in creation of such a pool, please contact us via Telegram [@swap.coffee DEV Chat](https://t.me/swapcoffee_dev_chat). Our recommendation for gas is `0.1 TON` for each message. Excesses will be returned. If you're using notifications, more gas may be needed. Pool Creation ## Liquidity Provisioning Similarly to **Pools** creation, liquidity provisioning has been developed as an interaction with two corresponding **Vaults**. Our recommendation for gas is `0.1 TON` for each message. Excesses will be returned. If you're using notifications, more gas may be needed. Liquidity Provisioning ## Liquidity Withdrawal Whenever you provide **swap.coffee DEX** pools with liquidity, you get LP (Liquidity Provisioning) tokens in return. Those tokens correspond to a **Jetton Standard** in which **Pool** serves as a **Jetton Master** contract. Thereby, in order to get funds back, all you need to do is to burn LP tokens you currently own. Also, our LP jetton wallets support `custom_payload` on burn so that users may specify withdrawal liquidity parameters to secure the operation. You can read more about it in [TL-B schemes](/technical-guides/dex/tlb-schemes#withdrawliquidityparams) section. Liquidity Withdrawal ## Swap **swap.coffee DEX** supports direct swaps (which involve only one **Pool** in an exchange), multi-hop swaps (when multiple **Pools** are being involved by performing swaps after each other) and even multi-dex swaps (thankfully to custom payloads support via our notification system). As stated previously, visualizations have been simplified: in particular, all **Vaults**, despite their asset-type accordance, are shown as just a simple regular **Vault**. In real world, the actual message you send to the **Vault** to initiate swap depends on your initial asset type. In a similar way some other (inter-contract and outgoing) messages may also differ. Our recommendation for gas is `0.1 TON` for the transaction itself plus `0.05 TON` for every additional swap step after the first one. So, for example, if you're performing a direct swap, our recommendation is `0.1 TON`, but if your swap route consists of 3 steps (A -> B -> C -> D), then our recommendation is `0.1 + 0.05 * 2 = 0.2 TON`. Actual usage should be much lower and all the excesses will be returned. If you're using notifications, more gas may be needed. ### Direct Direct Swap ### With multi-hops Multi-Hop Swap # Contract's Get-Methods Source: https://docs.swap.coffee/technical-guides/dex/get-methods All the methods of the contracts that may be invoked off-chain are described on this page. ## Factory ### get\_vault\_address ```func theme={null} (slice, int) get_vault_address(slice asset) ``` Properties: | Type | Name | Description | | ------------ | ----- | --------------------------------------------------------------- | | Argument | asset | Serialized [Asset](/technical-guides/dex/tlb-schemes#asset) | | Return Value | 1st | Serialized `MsgAddressInt` for the **Vault** of the given asset | | Return Value | 2nd | Hash part of the address returned before | ### get\_pool\_address ```func theme={null} (slice, int) get_pool_address( slice asset1, slice asset2, int amm, cell amm_settings ) ``` Properties: | Type | Name | Description | | ------------ | ------------- | -------------------------------------------------------------------------------- | | Argument | asset1 | Serialized [Asset](/technical-guides/dex/tlb-schemes#asset) | | Argument | asset2 | Serialized [Asset](/technical-guides/dex/tlb-schemes#asset) | | Argument | amm | Serialized [AMM](/technical-guides/dex/tlb-schemes#amm) | | Argument | amm\_settings | Serialized [AMM Settings](/technical-guides/dex/tlb-schemes#amm-settings) | | Return Value | 1st | Serialized `MsgAddressInt` for the **Pool** of the given asset pair and amm type | | Return Value | 2nd | Hash part of the address returned before | ### get\_pool\_address\_no\_settings ```func theme={null} (slice, int) get_pool_address_no_settings(slice asset1, slice asset2, int amm) ``` Same as the previous, except there are no settings. ### get\_pool\_creator\_address ```func theme={null} (slice, int) get_pool_creator_address( slice owner, slice asset1, slice asset2, int amm, cell amm_settings ) ``` Properties: | Type | Name | Description | | ------------ | ------------- | ---------------------------------------------------------------------------------------------------------------------------- | | Argument | owner | Serialized `MsgAddressInt` of the **PoolCreator**'s owner | | Argument | asset1 | Serialized [Asset](/technical-guides/dex/tlb-schemes#asset) | | Argument | asset2 | Serialized [Asset](/technical-guides/dex/tlb-schemes#asset) | | Argument | amm | Serialized [AMM](/technical-guides/dex/tlb-schemes#amm) | | Argument | amm\_settings | Serialized [AMM Settings](/technical-guides/dex/tlb-schemes#amm-settings) | | Return Value | 1st | Serialized `MsgAddressInt` for the **PoolCreator** of the given asset pair and amm type which is owned by the specified user | | Return Value | 2nd | Hash part of the address returned before | ### get\_pool\_creator\_address\_no\_settings ```func theme={null} (slice, int) get_pool_creator_address_no_settings( slice owner, slice asset1, slice asset2, int amm ) ``` Same as the previous, except there are no settings. ### get\_liquidity\_depository\_address ```func theme={null} (slice, int) get_liquidity_depository_address( slice owner, slice asset1, slice asset2, int amm, cell amm_settings ) ``` Properties: | Type | Name | Description | | ------------ | ------------- | ------------------------------------------------------------------------------------------------------------------------------------ | | Argument | owner | Serialized `MsgAddressInt` of the **LiquidityDepository**'s owner | | Argument | asset1 | Serialized [Asset](/technical-guides/dex/tlb-schemes#asset) | | Argument | asset2 | Serialized [Asset](/technical-guides/dex/tlb-schemes#asset) | | Argument | amm | Serialized [AMM](/technical-guides/dex/tlb-schemes#amm) | | Argument | amm\_settings | Serialized [AMM Settings](/technical-guides/dex/tlb-schemes#amm-settings) | | Return Value | 1st | Serialized `MsgAddressInt` for the **LiquidityDepository** of the given asset pair and amm type which is owned by the specified user | | Return Value | 2nd | Hash part of the address returned before | ### get\_liquidity\_depository\_address\_no\_settings ```func theme={null} (slice, int) get_liquidity_depository_address_no_settings( slice owner, slice asset1, slice asset2, int amm ) ``` Same as the previous, except there are no settings. ### get\_admin\_address ```func theme={null} slice get_admin_address() ``` Properties: | Type | Name | Description | | ------------ | ---- | ------------------------------------------------------------- | | Return Value | 1st | Serialized `MsgAddressInt` for the DEX administrative account | ## Vault ### get\_asset ```func theme={null} slice get_asset() ``` Properties: | Type | Name | Description | | ------------ | ---- | ------------------------------------------------------------------------------------------- | | Return Value | 1st | Serialized [Asset](/technical-guides/dex/tlb-schemes#asset) to which this vault corresponds | ### is\_active ```func theme={null} int is_active() ``` Properties: | Type | Name | Description | | ------------ | ---- | ------------------------------------------- | | Return Value | 1st | 0 if this vault is not active, -1 otherwise | ## Pool ### get\_jetton\_data Pool is a **Jetton Master** for its LP tokens. This get-methods makes it compatible with [Jetton Standard](https://github.com/ton-blockchain/TEPs/blob/master/text/0074-jettons-standard.md), therefore specifics about are accessible by the link. ### get\_wallet\_address Pool is a **Jetton Master** for its LP tokens. This get-methods makes it compatible with [Jetton Standard](https://github.com/ton-blockchain/TEPs/blob/master/text/0074-jettons-standard.md), therefore specifics about are accessible by the link. ### get\_pool\_data ```func theme={null} (int, slice, slice, int, cell, int, int, int, int, int, int) get_pool_data() ``` Properties: | Type | Name | Description | | ------------ | ---- | -------------------------------------------------------------------------------------- | | Return Value | 1st | Version of the pool code, starts at 1 | | Return Value | 2nd | Serialized first [Asset](/technical-guides/dex/tlb-schemes#asset) of this pool | | Return Value | 3rd | Serialized second [Asset](/technical-guides/dex/tlb-schemes#asset) of this pool | | Return Value | 4th | Serialized [AMM](/technical-guides/dex/tlb-schemes#amm) of this pool | | Return Value | 5th | Serialized [AMM Settings](/technical-guides/dex/tlb-schemes#amm-settings) of this pool | | Return Value | 6th | 0 if this pool is not active, -1 otherwise | | Return Value | 7th | Reserves of the first asset of this pool | | Return Value | 8th | Reserves of the second asset of this pool | | Return Value | 9th | Total supply of LP tokens | | Return Value | 10th | Protocol fee nominator\* | | Return Value | 11th | LP fee nominator\* | \* Fees are being withdrawn from swap operations only (therefore liquidity provisioning/withdrawal is fee). They are always charged from the input asset of the swap, and they're denoted by the nominators within the pool storage. Fees nominators are non-negative integers less than `max_nominator = 10000`. Denominator for fees is a constant equal to `1000000`. ### estimate\_swap\_amount ```func theme={null} (int, int) estimate_swap_amount(slice asset, int amount) ``` Properties: | Type | Name | Description | | ------------ | ------ | ------------------------------------------------------------------------------------------ | | Argument | asset | Serialized input [Asset](/technical-guides/dex/tlb-schemes#asset) for the (potential) swap | | Argument | amount | Amount of the input asset to be (potentially) swapped | | Return Value | 1st | Actual amount of the input asset that would be used for the swap | | Return Value | 2nd | Amount of output asset to be received as a result of swap | ### estimate\_liquidity\_withdraw\_amount ```func theme={null} (int, int) estimate_liquidity_withdraw_amount(int lp_amount) ``` Properties: | Type | Name | Description | | ------------ | ---------- | --------------------------------------------- | | Argument | lp\_amount | Amount of LP tokens to be burned | | Return Value | 1st | Amount of pool's first asset to be withdrawn | | Return Value | 2nd | Amount of pool's second asset to be withdrawn | ### estimate\_liquidity\_deposit\_amount ```func theme={null} (int, int, int, int) estimate_liquidity_deposit_amount( int amount1, int amount2 ) ``` Properties: | Type | Name | Description | | ------------ | ------- | ------------------------------------------------------------------------------------------------- | | Argument | amount1 | Amount of pool's first asset to be deposited | | Argument | amount2 | Amount of pool's second asset to be deposited | | Return Value | 1st | Actual amount of pool's first asset that would be deposited | | Return Value | 2nd | Actual amount of pool's second asset that would be deposited | | Return Value | 3rd | Amount of LP tokens to be received | | Return Value | 4th | How much of permanently locked initial LP tokens will be generated as a result of such deposition | # Introduction Source: https://docs.swap.coffee/technical-guides/dex/introduction **swap.coffee DEX** is an [open-source](https://github.com/swapcoffee/dex) most powerful and extensible decentralized exchange **TON**-native protocol on the TON blockchain. We truly believe that it signifies new era of both user exchanges and market evolution overall, as it aims at not only providing the smoothest user experience by securing them in all possible ways, negotiating gas consumption, allowing multi-hop and multi-dex swaps, as well as supporting unlimited AMM strategies variations for a single pair of assets, but it is also built for developers and businesses. Combined with a powerful toolset of **swap.coffee**'s products such as **Claiming Center**, [Staking Protocol](/technical-guides/staking-internals) and others, it grants us an ability to build an all-in-one ecosystem with instant payouts for liquidity providers, referrals and even B2B integrators; possibility to launch cashback-, farm- or even competition-based campaigns and much, much more. More than that, **swap.coffee DEX** is not just a protocol - it is a product itself which's built on top of that protocol. The open-source nature not only provides more transparency to our tech-savvy users who are interested to understand how things work internally, but also allows other market participants to launch their own **DEX**es backed by contracts developed by us. ## 🛡 Security Audit This project has been independently audited by [Trail of Bits](https://trailofbits.com) → [Read the full audit report here (PDF)](https://github.com/trailofbits/publications/blob/master/reviews/2025-05-swap-coffee-ton-dex-securityreview.pdf) # TL-B Schemes Source: https://docs.swap.coffee/technical-guides/dex/tlb-schemes This page contains extensive information about custom entities used in communication with/in-between **swap.coffee DEX** contracts. ## Types ### AMM ```tl-b theme={null} constant_product$000 = AMM; curve_fi_stable$001 = AMM; ``` Defines AMM strategy type of the pool. ### AMM Settings Some AMM strategies require additional settings whenever pool with such strategy is about to be created. Person who initiates this process must provide AMM settings cell within the transaction. Please, keep in mind that non-**Constant Product** pools may be created by the **DEX** administration only. #### CurveFi Stable ```tl-b theme={null} amm_settings amplification:uint16 asset1_weight:Coins asset2_weight:Coins = AmmSettings; ``` | Property Name | Meaning | | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | amplification | Multiplier used in StableSwap formulas. The higher this value is, the closer exchange price stays to 1:1. The lower this value is, the more exchange price looks like from **Constant Product** formula | | asset1\_weight | Value by which first asset reserves and amounts multiplied in StableSwap formulas. Usually a power of 10 | | asset2\_weight | Value by which second asset reserves and amounts multiplied in StableSwap formulas. Usually a power of 10 | ### Asset ```tl-b theme={null} native$00 = Asset; jetton$01 chain:uint8 hash:uint256 = Asset; extra$10 id:uint32 = Asset; ``` Defines asset type (and metadata) to work with. #### native Used for TONcoin. #### jetton Used for any jettons. #### extra Used for extra currencies. ### DepositLiquidityCondition ```tl-b theme={null} none$00 = DepositLiquidityCondition; lp_quantity$01 min_lp_amount:Coins = DepositLiquidityCondition; reserves_ratio$10 denominator:uint16 min_nominator:uint16 max_nominator:uint16 = DepositLiquidityCondition; complex$11 min_lp_amount:Coins denominator:uint16 min_nominator:uint16 max_nominator:uint16 = DepositLiquidityCondition; ``` Defines condition, which will be checked whenever contract receives liquidity deposition request. If it fails, transaction will be reverted. #### none Equivalent to no-condition. #### lp\_quantity Allows to set minimum quantity of LP tokens you will get in return after liquidity deposition happens. If real quantity is lower than the given one, transaction will be reverted. #### reserves\_ratio Allows to check pool reserves ratio before your liquidity deposition happens. In other words, all of the following formulas must be true: * `reserves1 / reserves2 >= min_nominator / denominator` * `reserves1 / reserves2 <= max_nominator / denominator` #### complex Just a combination of **lp\_quantity** and **reserves\_ratio**. ### WithdrawLiquidityCondition ```tl-b theme={null} none$00 = WithdrawLiquidityCondition; assets_quantity$01 min_first_amount:Coins min_second_amount = WithdrawLiquidityCondition; reserves_ratio$10 denominator:uint16 min_nominator:uint16 max_nominator:uint16 = WithdrawLiquidityCondition; complex$11 min_first_amount min_second_amount:Coins denominator:uint16 min_nominator:uint16 max_nominator:uint16 = WithdrawLiquidityCondition; ``` Defines condition, which will be checked whenever user tries to withdraw already provided liquidity from the pool. If it fails, transaction will be reverted (and LP tokens will be minted back). Subtypes are very similar with [DepositLiquidityCondition](#depositliquiditycondition) ones. ### PoolParams ```tl-b theme={null} pool_params first:Asset second:Asset amm:AMM amm_settings:(Maybe ^Cell) = PoolParams; ``` Used to uniquely identify the pool. Only one pool can exist for given asset-pair, AMM type and AMM settings. | Property Name | Meaning | | ------------- | --------------------------------------------------------------------------------- | | first | First [asset](#asset) of the pool (in any order) | | second | Second [asset](#asset) of the pool (in any order) | | amm | [Market-making strategy](#amm) of the pool | | amm\_settings | Cell of [AMM settings](#amm-settings). Must be set for those AMMs that require it | ### PublicPoolCreationParams ```tl-b theme={null} public_pool_creation_params recipient:MsgAddressInt use_recipient_on_failure:int1 notification_data:(Maybe ^Cell) = PublicPoolCreationParams; ``` Params that may be publicly used for new pools creation: | Property Name | Meaning | | --------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | recipient | Address to which LP tokens must go after transaction succeed (or to which funds must return in failure scenario). Must be present | | use\_recipient\_on\_failure | Determines where to accrue funds in case of any failure. If set to 0, funds will be returned to transaction initiator; otherwise they will be returned to `recipient` | | notification\_data | Used for custom payloads. See: [NotificationData](#notificationdata) | ### PrivatePoolCreationParams ```tl-b theme={null} private_pool_creation_params is_active:uint1 extra_settings:(Maybe ^Cell) = PrivatePoolCreationParams; ``` Params that may be used for new pools creation by DEX administration only: | Property Name | Meaning | | --------------- | -------------------------------------------------------------------------------------------------------------- | | is\_active | Is pool active (functional) at the time it's being created. Must be set to 1 when invoked from non-admin users | | extra\_settings | Reserved for future features, not currently in use | ### PoolCreationParams ```tl-b theme={null} pool_creation_params public:PublicPoolCreationParams private:PrivatePoolCreationParams = PoolCreationParams; ``` Params for new pools creation. ### NotificationDataSingle ```tl-b theme={null} notification_data_single receiver:MsgAddressInt fwd_gas:Coins payload:^Cell = NotificationDataSingle; ``` Defines where to send (and with how much gas) custom payload for various actions within **DEX**. If `receiver` is none, it's considered being equal to transaction recipient. ### NotificationData ```tl-b theme={null} notification_data on_success:(Maybe ^NotificationDataSingle) on_failure:(Maybe ^NotificationDataSingle) = NotificationData; ``` Defines how to handle notifications (custom payloads) in none of, one of or both scenarios of successful/failed execution. ### PoolUpdateParams ```tl-b theme={null} pool_update_params flags:(## 2) protocol_fee:flags.0?uint16 lp_fee:flags.0?uint16 is_active:flags.1?uint1 = PoolUpdateParams; ``` Defines pool's parameters that may be updated by **DEX** administrator. ### SwapParams ```tl-b theme={null} swap_params deadline:uint32 recipient:MsgAddressInt referral:MsgAddressInt notification_data:(Maybe ^NotificationData) = SwapParams; ``` Defines parameters that are essential for all (multi-hop) steps of single swap transaction: | Property Name | Meaning | | ------------------ | ------------------------------------------------------------------------------------------------------------------ | | deadline | Unix timestamp. If contract receives swap message after that time, transaction will be failed at that step | | recipient | Address to which funds must go after swap transaction is over (both in success/failure scenarios). Must be present | | referral | Address to which referral fees will be accrued. If none, referral fees go to the protocol | | notification\_data | Used for custom payloads. See: [NotificationData](#notificationdata) | ### SwapStepParams ```tl-b theme={null} swap_step_params pool_address_hash:uint256 min_output_amount:Coins next:(Maybe ^SwapStepParams) = SwapStepParams; ``` Defines parameters that are unique for every (multi-hop) step of swap transaction: | Property Name | Meaning | | ------------------- | ----------------------------------------------------------------------------------- | | pool\_address\_hash | Hash part of the pool's address | | min\_output\_amount | Minimum quantity of output asset to receive. If you get less, transaction will fail | | next | Next swap-step if any | ### SwapStepInternalParams ```tl-b theme={null} swap_step_internal_params previous_amount:Coins previous_asset_hint:(Maybe Asset) min_output_amount:Coins next:(Maybe ^SwapStepParams) = SwapStepInternalParams; ``` Same as [SwapStepParams](#SwapStepParams), but is being used in inter-contract communication. | Property Name | Meaning | | --------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | previous\_amount | Amount of asset you received on the previous swap-step | | previous\_asset\_hint | Asset you received on the previous swap-step. It's present only in cases when user tries to perform sequential swaps on pools of the same asset-pairs (but probably different AMM types) | | min\_output\_amount | Minimum quantity of output asset to receive. If you get less, transaction will fail | | next | Next swap-step if any | ### PoolReserves ```tl-b theme={null} pool_reserves input_reserve:Coins output_reserve:Coins = PoolReserves; ``` Defines reserves of the pool. ### DepositLiquidityParamsTrimmed ```tl-b theme={null} deposit_liquidity_params_trimmed recipient:MsgAddressInt use_recipient_on_failure:int1 referral:MsgAddressInt deadline:uint32 condition:DepositLiquidityCondition extra_settings:(Maybe ^Cell) notification_data:(Maybe ^NotificationData) = DepositLiquidityParamsTrimmed; ``` Defines parameters required for liquidity provisioning. This exact entity is being used in inter-contract communication and lacks some of extra information (see below). | Property Name | Meaning | | --------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | recipient | Address to which LP tokens must go after transaction succeed (or to which funds must return in failure scenario). Must be present | | use\_recipient\_on\_failure | Determines where to accrue funds in case of any failure. If set to 0, funds will be returned to transaction initiator; otherwise they will be returned to `recipient` | | referral | Referral address used exclusively for analytical purposes. No fees or any kind or rewards will be given | | deadline | Unix timestamp. If contract receives liquidity provisioning message after that time, transaction will be failed at that step | | condition | Used to protect the liquidity provider from unfavorable pool conditions. See: [DepositLiquidityCondition](#depositliquiditycondition) | | extra\_settings | Reserved for future features, not currently in use | | notification\_data | Used for custom payloads. See: [NotificationData](#notificationdata) | ### DepositLiquidityParams ```tl-b theme={null} deposit_liquidity_params params:^DepositLiquidityParamsTrimmed pool_params:^PoolParams = DepositLiquidityParams; ``` Extended version of the previous one. Pool parameters are used to identify the pool. ### WithdrawLiquidityParams ```tl-b theme={null} withdraw_liquidity_params use_recipient_on_failure:int1 deadline:uint32 condition:WithdrawLiquidityCondition extra_settings:(Maybe ^Cell) on_success:(Maybe ^NotificationDataSingle) = WithdrawLiquidityParams; ``` Defines parameters that may be specified by user when withdrawing already provided liquidity (by burning his LP tokens). This exact entity is being used as a `custom_payload` within [burn message](#burn-liquidity-withdrawal). | Property Name | Meaning | | --------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | use\_recipient\_on\_failure | Determines where to accrue funds in case of any failure. If set to 0, funds will be returned to transaction initiator; otherwise they will be returned to `recipient` | | deadline | Unix timestamp. If contract receives liquidity withdrawal message after that time, transaction will be failed at that step | | condition | Used to protect the liquidity withdrawer from unfavorable pool conditions. See: [WithdrawLiquidityCondition](#withdrawliquiditycondition) | | extra\_settings | Reserved for future features, not currently in use | | on\_success | Used for custom payloads on successful liquidity withdrawals. See: [NotificationData](#notificationdata) | ### ContractUpdate ```tl-b theme={null} contract_update code:(Maybe ^Cell) data:(Maybe ^Cell) = ContractUpdate; ``` Entity used in administrative action of contract updates. ## Messages ### Related to swaps #### SwapNative ```tl-b theme={null} swap_native#c0ffee00 query_id:uint64 amount:Coins _:SwapStepParams params:^SwapParams = SwapNative; ``` Must be sent by user to the **Native Vault** to initiate swap transaction. | Property Name | Meaning | | ------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | query\_id | Non-unique identifier which you may specify to track this transaction | | amount | Amount of TONs to swap. Must be lower than the message value of TONs (because extra TONs will be used to pay for gas, and will be returned at the end of the transaction) | | \_ | Parameters for the first swap-step of the transaction. See: [SwapStepParams](#swapstepparams) | | params | Parameters that are essential for all steps of the swap transaction. See: [SwapParams](#swapparams) | #### SwapJetton ```tl-b theme={null} swap_jetton#c0ffee10 _:SwapStepParams params:^SwapParams = SwapJetton; ``` Must be sent by user to the corresponding **Jetton Vault** as a forward payload of a jetton-transfer message to initiate swap transaction. Query ID, jetton and it's amount are being determined internally from jetton transfer notification and therefore mustn't be present here. | Property Name | Meaning | | ------------- | --------------------------------------------------------------------------------------------------- | | \_ | Parameters for the first swap-step of the transaction. See: [SwapStepParams](#swapstepparams) | | params | Parameters that are essential for all steps of the swap transaction. See: [SwapParams](#swapparams) | #### SwapExtra ```tl-b theme={null} swap_extra#c0ffee01 query_id:uint64 _:SwapStepParams params:^SwapParams = SwapExtra; ``` Must be sent by user to the corresponding **Extra-Currency Vault** to initiate swap transaction. Extra-currency and it's amount are being determined internally from the vault type and extra-currencies dictionary within the message. | Property Name | Meaning | | ------------- | --------------------------------------------------------------------------------------------------- | | query\_id | Non-unique identifier which you may specify to track this transaction | | \_ | Parameters for the first swap-step of the transaction. See: [SwapStepParams](#swapstepparams) | | params | Parameters that are essential for all steps of the swap transaction. See: [SwapParams](#swapparams) | #### SwapSuccessfulEvent ```tl-b theme={null} swap_successful_event#c0ffee30 query_id:uint64 input:Asset input_amount:Coins output_amount:Coins reserves:^PoolReserves = SwapSuccessfulEvent; ``` Is being sent by the pool as an external outgoing message whenever swap step completes successfully. This message occurs **after** payout is guaranteed to happen, but **before** it actually happens. | Property Name | Meaning | | -------------- | ------------------------------------------------------------------------------------------------------------------------------------- | | query\_id | Propagated identifier | | input | Input (given) asset of the swap operation. There is no output asset property, but it may be determined from the pool address and data | | input\_amount | Amount of input (given) asset of the swap operation | | output\_amount | Amount of output (received) asset of the swap operation | | reserves | Pool's reserves at the moment swap happened | #### SwapFailedEvent ```tl-b theme={null} swap_failed_event#c0ffee31 query_id:uint64 input:Asset input_amount:Coins reserves:(Maybe ^PoolReserves) = SwapFailedEvent; ``` Is being sent by the pool as an external outgoing message whenever swap step completes badly (i.e. it was slippage tolerated or deadline exceeded). This message occurs **after** payout (of the input asset) is guaranteed to happen, but **before** it actually happens. Despite the fact that message itself does not contain failure reason, it may be determined as an exit code of the TVM. | Property Name | Meaning | | ------------- | ---------------------------------------------------------------------------------------------------------------------------------------------- | | query\_id | Propagated identifier | | input | Input (given) asset of the swap operation. There is no output asset property, but it may be determined from the pool address and data | | input\_amount | Amount of input (given) asset of the swap operation | | reserves | Information about pool's reserves at a time it tries to execute this transaction. Guaranteed to be present to slippage-tolerated failures only | ### Related to pools creation and liquidity provisioning #### CreatePoolNative ```tl-b theme={null} create_pool_native#c0ffee02 query_id:uint64 amount:Coins params:PoolParams creation_params:PoolCreationParams = CreatePoolNative; ``` Must be sent by user to the **Native Vault** as a part of pool creation (and it's initial liquidity provisioning). | Property Name | Meaning | | ---------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | query\_id | Non-unique identifier which you may specify to track this transaction | | amount | Amount of TONs to deposit into liquidity. Must be lower than the message value of TONs (because extra TONs will be used to pay for gas, and will be returned at the end of the transaction) | | params | Parameters used to uniquely identify the pool. See: [PoolParams](#poolparams) | | creation\_params | Parameters used for pool creation. See: [PoolCreationParams](#poolcreationparams) | #### CreatePoolJetton ```tl-b theme={null} create_pool_jetton#c0ffee11 params:PoolParams creation_params:PoolCreationParams = CreatePoolJetton; ``` Must be sent by user to the corresponding **Jetton Vault** as a part of pool creation (and it's initial liquidity provisioning). This message must be included as a forward payload to the jetton-transfer message. Query ID, jetton and it's amount are being determined internally from jetton transfer notification and therefore mustn't be present here. | Property Name | Meaning | | ---------------- | --------------------------------------------------------------------------------- | | params | Parameters used to uniquely identify the pool. See: [PoolParams](#poolparams) | | creation\_params | Parameters used for pool creation. See: [PoolCreationParams](#poolcreationparams) | #### CreatePoolExtra ```tl-b theme={null} create_pool_extra#c0ffee03 query_id:uint64 params:PoolParams creation_params:PoolCreationParams = CreatePoolExtra; ``` Must be sent by user to the corresponding **Extra-Currency Vault** as a part of pool creation (and it's initial liquidity provisioning). Extra-currency and it's amount are being determined internally from the vault type and extra-currencies dictionary within the message. | Property Name | Meaning | | ---------------- | --------------------------------------------------------------------------------- | | query\_id | Non-unique identifier which you may specify to track this transaction | | params | Parameters used to uniquely identify the pool. See: [PoolParams](#poolparams) | | creation\_params | Parameters used for pool creation. See: [PoolCreationParams](#poolcreationparams) | #### DepositLiquidityNative ```tl-b theme={null} deposit_liquidity_native#c0ffee04 query_id:uint64 amount:Coins params:DepositLiquidityParams = DepositLiquidityNative; ``` Must be sent by user to the **Native Vault** as a part of liquidity provisioning process. | Property Name | Meaning | | ------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | query\_id | Non-unique identifier which you may specify to track this transaction | | amount | Amount of TONs to deposit into liquidity. Must be lower than the message value of TONs (because extra TONs will be used to pay for gas, and will be returned at the end of the transaction) | | params | Parameters used for liquidity provisioning. See: [DepositLiquidityParams](#depositliquidityparams) | #### DepositLiquidityJetton ```tl-b theme={null} deposit_liquidity_jetton#c0ffee12 params:DepositLiquidityParams = DepositLiquidityJetton; ``` Must be sent by user to the corresponding **Jetton Vault** as a part of liquidity provisioning process. This message must be included as a forward payload to the jetton-transfer message. Query ID, jetton and it's amount are being determined internally from jetton transfer notification and therefore mustn't be present here. | Property Name | Meaning | | ------------- | -------------------------------------------------------------------------------------------------- | | params | Parameters used for liquidity provisioning. See: [DepositLiquidityParams](#depositliquidityparams) | #### DepositLiquidityExtra ```tl-b theme={null} deposit_liquidity_extra#c0ffee05 query_id:uint64 params:DepositLiquidityParams = DepositLiquidityExtra; ``` Must be sent by user to the corresponding **Extra-Currency Vault** as a part of liquidity provisioning process. Extra-currency and it's amount are being determined internally from the vault type and extra-currencies dictionary within the message. | Property Name | Meaning | | ------------- | -------------------------------------------------------------------------------------------------- | | query\_id | Non-unique identifier which you may specify to track this transaction | | params | Parameters used for liquidity provisioning. See: [DepositLiquidityParams](#depositliquidityparams) | #### DepositLiquiditySuccessfulEvent ```tl-b theme={null} deposit_liquidity_successful_event#c0ffee33 query_id:uint64 amount1:Coins amount2:Coins lp_amount:Coins total_supply:PoolReserves reserves:PoolReserves = DepositLiquiditySuccessfulEvent; ``` Is being sent by the pool as an external outgoing message whenever liquidity provisioning step completes successfully. This message occurs **after** LP tokens payout is guaranteed to happen, but **before** it actually happens. | Property Name | Meaning | | ------------- | ------------------------------------------------------------------------------- | | query\_id | Propagated identifier | | amount1 | Amount of pool's first asset that were used for the liquidity provisioning | | amount2 | Amount of pool's second asset that were used for the liquidity provisioning | | lp\_amount | Amount of LP tokens user received as a result of this liquidity provisioning | | total\_supply | Information about how pool's LP tokens total supply changed with this operation | | reserves | Pool's reserves at the moment this operation happened | #### DepositLiquidityFailedEvent ```tl-b theme={null} deposit_liquidity_failed_event#c0ffee34 query_id:uint64 amount1:Coins amount2:Coins min_lp_amount:Coins total_supply:Coins reserves:PoolReserves = DepositLiquidityFailedEvent; ``` Is being sent by the pool as an external outgoing message whenever liquidity provisioning step completes badly (i.e. it's condition check failed or deadline exceeded). This message occurs **after** payout (of provided assets) is guaranteed to happen, but **before** it actually happens. Despite the fact that message itself does not contain failure reason, it may be determined as an exit code of the TVM. | Property Name | Meaning | | --------------- | --------------------------------------------------------------------------------------- | | query\_id | Propagated identifier | | amount1 | Amount of pool's first asset that were about to be used for the liquidity provisioning | | amount2 | Amount of pool's second asset that were about to be used for the liquidity provisioning | | min\_lp\_amount | Minimum amount of LP tokens user was asking for | | total\_supply | Total supply of LP tokens at the moment this liquidity provisioning was about to happen | | reserves | Pool's reserves at the moment this liquidity provisioning was about to happen | #### LiquidityWithdrawalEvent ```tl-b theme={null} liquidity_withdrawal_event#c0ffee35 query_id:uint64 amount1:Coins amount2:Coins lp_amount:Coins total_supply:PoolReserves reserves:PoolReserves = LiquidityWithdrawalEvent; ``` Is being sent by the pool as an external outgoing message whenever somebody withdraws previously provided liquidity. This message occurs **after** payout is guaranteed to happen, but **before** it actually happens. | Property Name | Meaning | | ------------- | ------------------------------------------------------------------------------- | | query\_id | Propagated identifier | | amount1 | Amount of pool's first asset that will be sent to the user | | amount2 | Amount of pool's second asset that will be sent to the user | | lp\_amount | Amount of LP tokens being burnt | | total\_supply | Information about how pool's LP tokens total supply changed with this operation | | reserves | Pool's reserves at the moment this operation happened | #### WithdrawDeposit ```tl-b theme={null} withdraw_deposit#c0ffee07 query_id:uint64 = WithdrawDeposit; ``` Must be sent by the user to the **PoolCreator** or **LiquidityDepository** if only one of 2 liquidity provisioning transactions succeeded and user decides to cancel previously initiated process. As a result of this message execution, all half-way deposited funds will be returned back to the user. #### Burn (liquidity withdrawal) To withdraw liquidity, user simply needs to burn his LP tokens by sending the following message to his LP jetton wallet, according to [jetton standard](https://github.com/ton-blockchain/TEPs/blob/master/text/0074-jettons-standard.md#2-burn): ```tl-b theme={null} burn#595f07bc query_id:uint64 amount:(VarUInteger 16) response_destination:MsgAddress custom_payload:(Maybe ^Cell) = InternalMsgBody; ``` Although this scheme includes a `custom_payload`, regular jetton wallets do not support it, and therefore there is no way for user to provide any extra data related to token burning. That's why we slightly modified code of our LP jetton wallets, and they support `custom_payload`. If needed, user may use it, passing [WithdrawLiquidityParams](#withdrawliquidityparams) as a `custom_payload`. ### Miscellaneous #### Payout ```tl-b theme={null} payout#c0ffee32 query_id:uint64 = Payout; ``` Is being sent by the **Native Vault** and **Extra-Currency Vaults** in **some** cases. More specifically, it occurs if: * Operation was initiated without notifications (custom payloads) * Operation was initiated with notification, but it's recipient differs from the wallet that receives funds It means that in a situation when operation was initiated with notification, but it's recipient is the same as the one who receives funds, this message won't be created. #### CreateVault ```tl-b theme={null} create_vault#c0ffee06 query_id:uint64 asset:Asset = CreateVault; ``` Must be sent by a user to the **Factory** in order to create new vault. | Property Name | Meaning | | ------------- | --------------------------------------------------------------------- | | query\_id | Non-unique identifier which you may specify to track this transaction | | asset | Asset for which new vault must be created | #### Notification ```tl-b theme={null} notification#c0ffee36 query_id:uint64 body:^Cell = Notification; ``` Serves as a wrapper for any outgoing messages proposed by transaction initiator as a marker of operation completion status. Therefore, is being sent by **Vault**s or **Pool**s after operation completes. ### Inter-contract communication #### SwapInternal ```tl-b theme={null} swap_internal#c0ffee20 query_id:uint64 _:SwapStepInternalParams params:^SwapParams proof:^Cell = SwapInternal; ``` For any first step of swap transaction, this message will be sent from **Vaults** to the **Pool**. For any intermediate steps of swap transaction, it will be sent from one **Pool** to another. | Property Name | Meaning | | ------------- | --------------------------------------------------------------------- | | query\_id | Propagated identifier | | \_ | Parameters of the current swap step | | params | Parameters which are essential for all steps of this swap transaction | | proof | Special cell constructed for securing inter-contract communication | #### PayoutInternal ```tl-b theme={null} payout_internal#c0ffee21 query_id:uint64 recipient:MsgAddressInt amount:Coins notification_data:(Maybe ^NotificationDataSingle) proof:(Maybe ^Cell) = PayoutInternal; ``` Is being sent by **Pools** to the **Vaults** every time **Pool** decides that a payment must happen. Keep in mind that there's no asset defined in the message, because it can be determined by the **Vault** data. | Property Name | Meaning | | ------------------ | -------------------------------------------------------------------- | | query\_id | Propagated identifier | | recipient | Address of the one who will receive funds | | amount | Amount of asset to be sent to the recipient | | notification\_data | Used for custom payloads. See: [NotificationData](#notificationdata) | | proof | Special cell constructed for securing inter-contract communication | #### Deploy ```tl-b theme={null} deploy#c0ffee22 code:^Cell data:^Cell action:(Maybe ^Cell) = Deploy; ``` Is being sent by **Factory** every time it decides to deploy a new contract. | Property Name | Meaning | | ------------- | --------------------------------------------------------------------- | | code | Code of the contract | | data | Data of the contract | | action | Optional code cell that must be invoked after contract initialization | #### CreatePoolCreatorRequest ```tl-b theme={null} create_pool_creator_request#c0ffee23 query_id:uint64 amount:Coins params:PoolParams creation_params:^PoolCreationParams sender:MsgAddressInt proof:^Cell = CreatePoolCreatorRequest; ``` Is being sent by **Vaults** to the **Factory** at the moment somebody tries to create new pool. Keep in mind that there's no asset defined in the message, because it can be determined by the **Vault** data. | Property Name | Meaning | | ---------------- | --------------------------------------------------------------------------------- | | query\_id | Propagated identifier | | amount | Amount of this vault's asset user provided as an initial liquidity for the pool | | params | Parameters for pool creation | | creation\_params | Parameters used for pool creation. See: [PoolCreationParams](#poolcreationparams) | | sender | Address of the one who initialized pool creation | | proof | Special cell constructed for securing inter-contract communication | #### CreatePoolCreatorInternal ```tl-b theme={null} create_pool_creator_internal#c0ffee24 query_id:uint64 asset:Asset amount:Coins creation_params:^PoolCreationParams = CreatePoolCreatorInternal; ``` Is being sent by the **Factory** whenever it's about to deploy new **PoolCreator**. Properties are pretty much the same with [CreatePoolCreatorRequest](#createpoolcreatorrequest). #### CreatePoolRequest ```tl-b theme={null} create_pool_request#c0ffee25 query_id:uint64 amount1:Coins amount2:Coins tx_initiator:MsgAddressInt creation_params:^PoolCreationParams proof:^Cell = CreatePoolRequest; ``` Is being sent by the **PoolCreator** to the **Factory** when it's time the uninitialize **PoolCreator** and deploy a **Pool**. Properties are pretty much the same with [CreatePoolCreatorRequest](#createpoolcreatorrequest). #### CreatePoolInternal ```tl-b theme={null} create_pool_internal#c0ffee26 query_id:uint64 amount1:Coins amount2:Coins tx_initiator:MsgAddressInt recipient:MsgAddressInt use_recipient_on_failure:int1 extra_settings:(Maybe ^Cell) notification_data:(Maybe ^NotificationData) = CreatePoolInternal; ``` Is being sent by the **Factory** whenever it's about to deploy new **Pool**. Properties are pretty much the same with [CreatePoolCreatorRequest](#createpoolcreatorrequest). #### CreateLiquidityDepositoryRequest ```tl-b theme={null} create_liquidity_depository_request#c0ffee27 query_id:uint64 amount:Coins params:DepositLiquidityParams sender:MsgAddressInt proof:^Cell = CreateLiquidityDepositoryRequest; ``` Is being sent by **Vaults** to the **Factory** at the moment somebody tries to deposit liquidity to some pool. Keep in mind that there's no asset defined in the message, because it can be determined by the **Vault** data. | Property Name | Meaning | | ------------- | -------------------------------------------------------------------------------------------- | | query\_id | Propagated identifier | | amount | Amount of this vault's asset user provided as a liquidity for the pool | | params | Parameters for liquidity provisioning. See [DepositLiquidityParams](#depositliquidityparams) | | sender | Address of the user who initiated transaction | | proof | Special cell constructed for securing inter-contract communication | #### CreateLiquidityDepositoryInternal ```tl-b theme={null} create_liquidity_depository_internal#c0ffee28 query_id:uint64 asset:Asset amount:Coins params:^DepositLiquidityParamsTrimmed = CreateLiquidityDepositoryInternal; ``` Is being sent by the **Factory** whenever it's about to deploy new **LiquidityDepository**. Properties are pretty much the same with [CreateLiquidityDepositoryRequest](#createliquiditydepositoryrequest). #### DepositLiquidityInternal ```tl-b theme={null} deposit_liquidity_internal#c0ffee29 query_id:uint64 amount1:Coins amount2:Coins tx_initiator:MsgAddressInt params:^DepositLiquidityParamsTrimmed proof:^Cell = DepositLiquidityInternal; ``` Is being sent by the **LiquidityDepository** to the **Pool** when it's time to uninitialize **LiquidityDepository** and execute liquidity provisioning on the **Pool** side. Properties are pretty much the same with [CreateLiquidityDepositoryRequest](#createliquiditydepositoryrequest). #### CreateVaultInternal ```tl-b theme={null} create_vault_internal#c0ffee2a query_id:uint64 = CreateVaultInternal; ``` Is being sent by the **Factory** whenever it's about to deploy new **Vault**. #### UpdatePoolInternal ```tl-b theme={null} update_pool_internal#c0ffee2b query_id:uint64 excesses_receiver:MsgAddressInt params:^PoolUpdateParams = UpdatePoolInternal; ``` Is being sent by the **Factory** to the **Pool** whenever it receives administrative request to do so. #### ActivateVaultInternal ```tl-b theme={null} activate_vault_internal#c0ffee2c query_id:uint64 wallet:MsgAddressInt = ActivateVaultInternal; ``` Is being sent by the **Factory** to the **Vault** whenever it receives administrative request to do so. When **Factory** creates new **Jetton Vault**, it internally initiates process of determining it's own jetton wallet's address. It is required to ensure security later on, but unfortunately in order to obtain that address **Jetton Vault** needs to ask **Jetton Master** for it. Not all **Jetton Masters** support such thing on-chain, therefore for some older jettons administrative affection is required. #### WithdrawInternal ```tl-b theme={null} withdraw_internal#c0ffee2d query_id:uint64 asset:Asset amount:Coins receiver:MsgAddressInt = WithdrawInternal; ``` Is being sent by the **Factory** to the **Pool** whenever it receives administrative request to do so. Upon receiving such a message, **Pool** checks whether administrator is trying to withdraw not more than stored amount of collected protocol fees. If so, it sends payout command to the **Vault** to fulfill initial request. #### UpdateContractInternal ```tl-b theme={null} update_contract_internal#c0ffee2e query_id:uint64 excesses_receiver:MsgAddressInt _:ContractUpdate = UpdateContractInternal; ``` Is being sent by the **Factory** to any **DEX** contract whenever it receives administrative request to do so. ### Administrative #### UpdateAdmin ```tl-b theme={null} update_admin#c0ffee40 query_id:uint64 address:MsgAddressInt = UpdateAdmin; ``` Must be sent from the administrative wallet to the **Factory** in order to update administrative wallet's address. #### UpdatePool ```tl-b theme={null} update_pool#c0ffee41 query_id:uint64 pool_params:PoolParams params:^PoolUpdateParams = UpdatePool; ``` Must be sent from the administrative wallet to the **Factory** in order to update parameters of the pool. #### ActivateVault ```tl-b theme={null} activate_vault#c0ffee42 query_id:uint64 asset:Asset wallet:MsgAddressInt = ActivateVault; ``` Must be sent from the administrative wallet to the **Factory** in order to activate some **Jetton Vault**. #### Withdraw ```tl-b theme={null} withdraw#c0ffee43 query_id:uint64 pool_address:MsgAddressInt asset:Asset amount:Coins receiver:MsgAddressInt = Withdraw; ``` Must be sent from the withdrawer wallet to the **Factory** in order to withdraw some assets. Used to withdraw collected protocol fees: they are calculated (collected) on-chain, but must be distributed off-chain in order to significantly lower gas consumption for end-users. #### UpdateCodeCell ```tl-b theme={null} update_code_cell#c0ffee44 query_id:uint64 code_cell:^Cell = UpdateCodeCell; ``` Must be sent from the administrative wallet to the **Factory** in order to update code cells of all the contracts that will be deployed by the **Factory** in the future. #### UpdateContract ```tl-b theme={null} update_contract#c0ffee45 query_id:uint64 contract_address:MsgAddressInt _:ContractUpdate = UpdateContract; ``` Must be sent from the administrative wallet to the **Factory** in order to update already existing contract. `contract_address` must be none in case of administrator wanting to upgrade the **Factory** itself. #### UpdateWithdrawer ```tl-b theme={null} update_withdrawer#c0ffee46 query_id:uint64 address:MsgAddressInt = UpdateWithdrawer; ``` Must be sent from the administrative wallet to the **Factory** in order to update withdrawer wallet's address. # MCP Server Source: https://docs.swap.coffee/technical-guides/mcp Connect AI assistants to the swap.coffee knowledge base via the Model Context Protocol. **swap.coffee** runs a hosted [**Model Context Protocol**](https://modelcontextprotocol.io/) server that exposes the full technical documentation — API references, widget guides, DEX smart-contract docs, code snippets, and OpenAPI specs — to any MCP-compatible AI client. Connect your AI application to the following URL: ``` https://docs.swap.coffee/mcp ``` Once connected, assistants like **Claude**, **Cursor**, or any other MCP client can search and read the swap.coffee knowledge base on demand, answer integration questions, and generate working code examples without any copy-pasting from the docs. ## Why MCP? The **Model Context Protocol** is an open standard for connecting AI applications to external tools and data sources. By exposing our documentation over MCP, we let AI assistants: * Find the right page for a question before attempting to answer it. * Read exact quotes from API references, guides, and OpenAPI specs — no hallucinations. * Navigate the docs structurally (list files, grep for keywords, read specific sections). * Stay up to date automatically — there is no cached snapshot to re-sync. The server is **read-only**. It only exposes public documentation. It never has access to API keys, account data, wallet activity, or any private information. ## Connecting ### Claude Desktop / Claude Code Add the server to your MCP configuration: ```json theme={null} { "mcpServers": { "swap-coffee": { "url": "https://docs.swap.coffee/mcp" } } } ``` ### Cursor, Windsurf and other MCP clients Any MCP-compatible client can connect to the same URL. Consult your client's documentation for the exact configuration syntax — in most cases it is a single field pointing at `https://docs.swap.coffee/mcp`. ## Available Tools The hosted server exposes two tools that AI clients can call on behalf of the user. ### `search_swap_coffee` Semantic search across the entire swap.coffee knowledge base — guides, API references, code examples, DEX documentation. The tool returns contextual content with titles and direct links to the corresponding documentation pages. **Use it for:** * Broad or conceptual queries (*"how does routing work?"*, *"how do I authenticate?"*, *"what is X-Verify?"*). * Locating implementation details, code examples, or the right API reference. * Finding the right page before reading its full content. If you need the full content of a specific page, feed its path into `query_docs_filesystem_swap_coffee` — the search result already includes the `.mdx` path you can pass to `head` or `cat`. ### `query_docs_filesystem_swap_coffee` A read-only virtualized filesystem rooted at `/` that contains **only** the swap.coffee documentation pages and OpenAPI specs. Despite looking like a shell, nothing runs on the user's machine, the server host, or any network — it is a sandbox backed by documentation chunks. This is how AI clients read full documentation pages: there is no separate *"get page"* tool. To read a page, pass its `.mdx` path (for example, `/technical-guides/aggregator-api/introduction.mdx`) to `head` or `cat`. To search with exact keyword or regex matches, use `rg`. To understand the docs structure, use `tree` or `ls`. **Supported commands:** `rg` (ripgrep), `grep`, `find`, `tree`, `ls`, `cat`, `head`, `tail`, `stat`, `wc`, `sort`, `uniq`, `cut`, `sed`, `awk`, `jq`, plus basic text utilities. No writes, no network, no process control. **Each call is stateless.** The working directory always resets to `/` and no shell variables, aliases, or history carry across calls. If you need to operate in a subdirectory, chain commands in one call with `&&` or pass absolute paths. **Examples:** | Command | Purpose | | :----------------------------------------------------------- | :--------------------------------------------------- | | `tree / -L 2` | See the top-level directory layout | | `rg -il "rate limit" /` | Find all files mentioning *"rate limit"* | | `rg -C 3 "apiKey" /technical-guides/` | Show matches with 3 lines of context around each hit | | `head -80 /technical-guides/aggregator-api/introduction.mdx` | Read the top 80 lines of a specific page | | `cat /technical-guides/tokens-api.mdx` | Read a full page when you need everything | | `cat /openapi/spec.json \| jq '.paths \| keys'` | List OpenAPI endpoints | ⚠️ **Note:** Output is truncated to **30 KB per call**. Prefer targeted `rg -C` or `head -N` over broad `cat` on large files. When referencing pages back to the user, convert filesystem paths to URL paths by removing the `.mdx` extension — `/technical-guides/tokens-api.mdx` becomes `/technical-guides/tokens-api`. ## Recommended Workflow The two tools are complementary. A typical session looks like this: 1. **Start with `search_swap_coffee`** for broad or conceptual questions. It returns the most relevant pages with short excerpts. 2. **Drill down with `query_docs_filesystem_swap_coffee`** when you need the full content of a page, exact regex matches, or a structural overview of the docs. 3. **Pass paths between the tools.** The `.mdx` paths returned by `search_swap_coffee` are directly usable with `head` and `cat`. ## Use Cases * **Scaffold an integration.** *"Using the swap.coffee MCP, generate a TypeScript snippet that fetches a TON → USDT route via the aggregator API and executes it through TonConnect."* * **On-the-fly reference.** Ask any question about the widget, DEX contracts, or Tokens API and get an answer grounded in the latest documentation. * **Code review.** Paste an existing swap.coffee integration and let the assistant check it against the current API contract. * **OpenAPI exploration.** Ask the assistant to enumerate endpoints, list required parameters, or compare response shapes directly from the spec. ## Notes * The MCP server exposes **public documentation only** — it cannot read or write your account, API keys, or trading history. * Documentation is refreshed automatically. There is no need to reconnect after pages change. * To query **live data** — current routes, prices, token lists, staking positions — use the [Aggregator API](/technical-guides/aggregator-api/introduction) and [Tokens API](/technical-guides/tokens-api) directly, not the MCP server. * If something is missing from the knowledge base or an answer looks wrong, reach out in [@swap.coffee DEV Chat](https://t.me/swapcoffee_dev_chat). # Thermos Market API Source: https://docs.swap.coffee/technical-guides/thermos/backend-api Technical documentation for interacting with Thermos Market API ## First Steps To get started with the Thermos Market API, you need to obtain an `API token`. You can issue it yourself directly from our Telegram bot. 1. Open a private chat with [@thermos](https://t.me/thermos). 2. Send `/api`. 3. The bot will reply with your personal token inside a Telegram spoiler — tap to reveal, long-press to copy. The token is tied to the Telegram account you sent the command from. Running `/api` again later returns the same token, so you don't need to save the message — you can always re-request it. If you haven't used Thermos before, the bot will first ask you to open the app so an account gets created. Afterwards `/api` will work. ⚠️ **Treat this token like a password.** It grants **full access to your account**, including your balance and gifts. Thermos staff and support will **never** ask you for it — anyone who does is trying to scam you. If the token leaks, contact support immediately so it can be rotated. API token simplifies your integration with the Thermos Market API and allows you to perform actions without carrying about authentication with Telegram's `initData`. The basic rate limit is two requests per second, but you can request a higher limit if needed by contacting us. A detailed description of the API can be found in the [Swagger UI](https://backend.thermos.gifts/swagger-ui). ⚠️ **Note**: The Thermos Market API is currently in beta and may change frequently. We recommend checking the [Swagger UI](https://backend.thermos.gifts/swagger-ui) for the latest version of the API. ## Authentication To authenticate your requests, you need to obtain a JWT token from your API token by calling the following endpoint: ```bash theme={null} POST https://backend.thermos.gifts/api/v1/auth/api-token?api_token={API_TOKEN} ``` You should replace `{API_TOKEN}` with your actual API token. The response will contain a JWT token that you can use to authenticate your requests to the Thermos Market API. JWT token is valid for 24 hours and should be refreshed periodically by calling the same endpoint. ```json theme={null} { "account": { "id": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "wallet_address": "string", "telegram_user_id": 0, "referral_id": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "created_at": "2025-07-03T15:42:59.502Z", "total_refshare": 0, "total_cashback": 0, "language_code": "string", "total_balance": "string", "effective_balance": "string" }, "token": "string" } ``` A quick breakdown of the response: * `account`: Contains information about your account, such as `id`, `telegram_user_id`, and other details. * `token`: The JWT token that you can use to authenticate your requests. `effective_balance` is the balance that is available for use in the Thermos Market. It may differ from `total_balance` due to various factors such as pending transactions or locked funds. Well done! Now you can use the JWT token to authenticate your requests to other Thermos Market API endpoints. 🚀 ## Fees The Thermos Market API does not charge any fees for using its endpoints. However, you should be aware that some actions, such as buying or withdrawing gifts, may incur fees in the form of marketplace fees. So, the following actions incur fees: ### Buying a gift When you buy a gift, the Thermos Market charges a marketplace fee `0.1 TON` for each gift you buy. This fee is deducted from your account balance. When you withdraw a gift or buy it for another user, the fee is increased to `0.2 TON` for each gift. ### Withdrawing a gift When you withdraw a gift from your account, the Thermos Market charges a fee of `0.1 TON` for each gift you withdraw. This fee is deducted from your account balance. ### Selling a gift When you sell a gift, the Thermos Market charges a marketplace fee of `0.1 TON` for each gift you sell. This fee is deducted from your account. Also, when you `cancel a sale`, the Thermos Market charges a fee of `0.1 TON` for each gift you cancel. ### Internal gift transfer When you transfer a gift to another user, it does not incur any fees. However, if the recipient is not registered in the Thermos Market, the operation will be bounced back and the gift will stay in your account. ## The Task API Almost each actions in the API such as buying, selling, transferring the gift responds with the same structure of the `TaskResponseMultiple` object. For example, let's say you want to buy a gift, the API will return a `TaskResponseMultiple` object that contains information about the task and its status. ``` POST https://backend.thermos.gifts/api/v1/gifts/buy Content-Type: application/json ``` ```json theme={null} { "gifts": [ { "external_id": "", "market_source": "TONNEL", "action": { "type": "KEEP" } } ] } ``` In case of success, the API will return a `TaskResponseMultiple` object that contains a list of tasks. ```json theme={null} { "type": "multiple", "task_id": "string", "sub_tasks": [ { "type": "single", "state": "STARTED", "error_message": "string", "task_id": "string" } ], "combined_state": "STARTED" } ``` A key difference between `TaskResponseMultiple` and `TaskResponseSingle` is that the former contains a list of tasks, while the latter contains a single task. A `TaskResponseMultiple` is used when you perform an action that involves multiple tasks, such as buying multiple gifts at once. It also contains a `combined_state` field that indicates the overall state of the tasks. To check the status of a task, you can use the following endpoint: ``` GET https://backend.thermos.gifts/api/v1/tasks/{task_id} ``` The `{task_id}` should be replaced with the actual ID of the task you want to check. It can be id of a single task or a combined task. As a response, you will receive the same `TaskResponseSingle` or `TaskResponseMultiple` object, depending on the type of the task. ## Task States The task can have the following states: * `STARTED` - the task is in progress * `FAILURE` - the task has failed * `SUCCESS` - the task has completed successfully In case of failure, the *optional* `error_message` field will contain a description of the error that occurred during the task execution. ## Balance Deposits To deposit funds to your account, you need to retrieve the deposit address using the following endpoint: `GET https://backend.thermos.gifts/api/v1/balance/deposit?currency=TON` The `currency` parameter supports only `TON` at the moment. The response will contain the deposit address and the minimum deposit amount: ```json theme={null} { "address": "EQD5...5Q", "memo": "string" } ``` The deposit address is stay the same for each user, only *memo* is unique for each account. The `memo` field is used to identify your deposit and should be included in the transaction when sending funds to the deposit address. To do actual deposit, you need to send a transaction to the deposit address with the specified `memo` and the amount of TON you want to deposit. ## Balance Withdrawals To withdraw funds from your account, you can use the following endpoint: ``` POST https://backend.thermos.gifts/api/v1/balance/withdraw ``` ```json theme={null} { "amount": 100000000, "destination": "string" } ``` The `amount` parameter is the amount of TON you want to withdraw, specified in `nanotons` (1 TON = 1,000,000,000 nanotons). Currently, there is a fee of *0.1* TON for each withdrawal, so make sure you have enough balance to cover the fee. The `destination` parameter is the address where you want to withdraw your funds. It can be any valid TON address. In case of success, the API will return an ID of withdrawal request ```json theme={null} { "id": 121 } ``` To check the status of your withdrawal request, you can use the following endpoint: ``` GET https://backend.thermos.gifts/api/v1/balance/withdraw/status/{withdarawal_id} ``` ```json theme={null} { "status": "PENDING" } ``` The `status` field can have the following values: * `PENDING` - the withdrawal request is pending and has not been processed yet * `PROCESSING` - the withdrawal request is being processed * `PROCESSED` - the withdrawal request has been processed successfully * `FAILED` - the withdrawal request has failed ## Deposit a Gift To deposit a gift to your account, you must send it via Telegram API to the [@thermos\_vault](https://t.me/thermos_vault) account. Note that sender's Telegram user ID must match the one you provided when getting the API token. Otherwise, you can lose your gift. To check if the gift was deposited successfully, you can use the following endpoint: ``` GET https://backend.thermos.gifts/api/v1/gifts/me/owned/{unique_name} ``` `unique_name` is the unique name of the gift you want to check. It contains the name of gift collection and its number in it (e.g. `deskcalendar-1212`). ## Buy a Gift To buy a gift, you should first retrieve the gift external ID from the catalog API. If you already have the external ID, you can use the following endpoint to buy the gift: ``` POST https://backend.thermos.gifts/api/v1/gifts/buy ``` ```json theme={null} { "gifts": [ { "external_id": "", "price": "100000000", "market_source": "TONNEL", "action": { "type": "KEEP" } } ] } ``` Let's break down the request body: * `gifts`: An array of gifts you want to buy. Each gift should have the following properties: * `external_id`: The unique identifier of the gift in the catalog. * `market_source`: The source of the market where the gift is listed (e.g., `TONNEL`, `PORTALS`, `MRKT`). * `price`: The price of the gift in nanotons (1 TON = 1,000,000,000 nanotons). It should be taken from the catalog API and should be greater than 0. The `action` field specifies what to do with the gift after buying it. The `type` can be one of the following: * `KEEP`: Keep the gift in your account. No additional fields are required. * `WITHDRAW_OTHER`: Withdraw the gift to another user's account. You should also provide `recipient_telegram_id` and `anonymous` fields. Note, that the `WITHDRAW_OTHER` also have `keep_on_balance` field that indicates whether to keep the gift on recipient's Thermos balance or withdraw it to their Telegram account. If set to `false` there is an additional fee of `0.1 TON` for each gift, otherwise there is no fee for the gift withdrawal due to gift will remain on Thermos balance and transferred internally. If there is an error during the gift transfer, your gift will remain in your account. If Thermos Market is not able to transfer the gift to the recipient, it will register this account as a gift owner and the recipient will be able to claim it later. The API will return a `TaskResponseMultiple` object that contains information about the task and its status. It is described in the [Task API](#the-task-api) section. Note that you can buy multiple gifts at once by adding them to the `gifts` array. Up to 20 gifts can be bought in a single request. ## Withdraw a Gift To withdraw a gift from your account, you can use the following endpoint: ``` POST https://backend.thermos.gifts/api/v1/gifts/transfer ``` ```json theme={null} { "owned_gift_ids": [ "3fa85f64-5717-4562-b3fc-2c963f66afa6" ] } ``` The `owned_gift_ids` parameter is an array of gift IDs that you want to withdraw. You can find this ID in [GET /gifts/me](https://backend.thermos.gifts/docs#/Gifts/get_account_gifts_api_v1_gifts_me_get) endpoint. The API will return a `TaskResponseMultiple` object that contains information about the task and its status. It is described in the [Task API](#the-task-api) section. ## Internal Gift Transfer To transfer a gift to another Thermos user, you can use the following endpoint: ``` POST https://backend.thermos.gifts/api/v1/gifts/assign ``` ```json theme={null} { "owned_gift_ids": [ "3fa85f64-5717-4562-b3fc-2c963f66afa6" ], "recipient_telegram_id": 1, "anonymous": false } ``` The `owned_gift_ids` parameter is an array of gift IDs that you want to transfer. You can find this ID in [GET /gifts/me](https://backend.thermos.gifts/docs#/Gifts/get_account_gifts_api_v1_gifts_me_get) endpoint. The `recipient_telegram_id` parameter is the Telegram user ID of the recipient. The `anonymous` parameter is used to indicate whether the transfer is anonymous or not. If set to `true`, the recipient will not see who sent the gift. The API will return a `TaskResponseMultiple` object that contains information about the task and its status. It is described in the [Task API](#the-task-api) section. If the recipient is not registered in the Thermos Market, the gift will be registered to their account, and they will be able to claim it later. ## Sell a Gift To sell a gift, you can use the following endpoint: ``` POST https://backend.thermos.gifts/api/v1/gifts/sell ``` ```json theme={null} { "gifts": [ { "price": 0, "owned_gift_id": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "market_source": "TONNEL" } ] } ``` Price is specified in nanotons (1 TON = 1,000,000,000 nanotons). It should be greater than the minimal market price for the gift. Currently, there is the following minimal market price for the gift: * `TONNEL` - 2 TON * `PORTALS` - 0.5 TON The `gifts` parameter is an array of gifts you want to sell. Each gift should have the following properties: * `price`: The price of the gift in nanotons. It should be greater than 0. * `owned_gift_id`: The ID of the gift you want to sell. You can find this ID in [GET /gifts/me](https://backend.thermos.gifts/docs#/Gifts/get_account_gifts_api_v1_gifts_me_get) endpoint. * `market_source`: The source of the market where the gift is listed (e.g., `TONNEL`, `PORTALS`, `MRKT`). The API will return a `TaskResponseMultiple` object that contains information about the task and its status. It is described in the [Task API](#the-task-api) section. After the gift is listed for sale, you can check its status using the following endpoint: ``` GET https://backend.thermos.gifts/api/v1/gifts/me/on-sale ``` This endpoint will return a list of gifts that are currently listed for sale, along with their prices and other details. ### Cancel a Sale To cancel a sale of a gift, you can use the following endpoint: ``` POST https://backend.thermos.gifts/api/v1/gifts/cancel-sale ``` ```json theme={null} { "sale_gift_ids": [ "3fa85f64-5717-4562-b3fc-2c963f66afa6" ] } ``` The `sale_gift_ids` parameter is an array of gift IDs that you want to cancel the sale for. You can find this ID in [GET /gifts/me/on-sale](https://backend.thermos.gifts/docs#/Gifts/get_account_gifts_api_v1_gifts_me_on_sale_get) endpoint. # Thermos Proxy API Source: https://docs.swap.coffee/technical-guides/thermos/proxy-api Technical documentation for interacting with Thermos Proxy API ## First Steps A detailed description of the API can be found in the [Stoplight UI](https://proxy.thermos.gifts/docs). ⚠️ **Note**: The Thermos Proxy API is currently in beta and may change frequently. We recommend checking the [Stoplight UI](https://proxy.thermos.gifts/docs) for the latest version of the API. ## General concepts ### Currency and Pricing All price values in this API (like `floor` or `price`) are represented as strings in nanotons. A string is used to avoid precision loss with very large numbers. * `1 TON = 1,000,000,000 nanoton` ### Rarity Some attributes include a `rarity_per_mille` field. This indicates the rarity of the attribute out of 1,000. For example, a `rarity_per_mille` of `30` means there is a 3% (30/1000) chance of this attribute appearing. Some attributes also include a `rarity_score` field. This number is a product of all `rarity_per_mille` values. Foe example, if gift has model (`10`), backdrop (`20`) and symbol (`5`), its `rarity_score` is `1000`. ### Colors Colors are represented as integers (decimal format of a hex code). For example, `5470609` is `#537791`. ## Gifts API ### List gift collections You can use this endpoint to obtain the full list of gift collections & associated attributes (image url, floor, count) ```bash theme={null} GET https://proxy.thermos.gifts/api/v1/collections ``` The API will return a list of `ApiGiftCollection` objects: ```json theme={null} [ { "name": "Plush Pepe", "image_url": "https://fragment.com/file/gifts/plushpepe/thumb.webp", "stats": { "count": 124, "floor": "3899000000000" } }, ... ] ``` ### List gift backdrops You can use this endpoint to obtain the full list of gift backdrops & associated attributes (colors, floor, count) ```bash theme={null} GET https://proxy.thermos.gifts/api/v1/backdrops ``` The API will return a list of `ApiBackdrop` objects: ```json theme={null} [ { "name": "Indigo Dye", "center_color": 5470609, "edge_color": 4285561, "pattern_color": 203561, "text_color": 12770542, "stats": { "count": 4749, "floor": "1239999999" } }, ... ] ``` ### List gift symbols You can use this endpoint to obtain the full list of gift symbols & associated attributes (image url, floor, count) ```bash theme={null} GET https://proxy.thermos.gifts/api/v1/symbols ``` The API will return a list of `ApiSymbol` objects: ```json theme={null} [ { "name": "Patched Heart", "image_url": "https://storage.googleapis.com/portals-market/gifts/preciouspeach/patterns/patchedheart.png", "stats": { "count": 171, "floor": "2120000000" } }, ... ] ``` ### List collection attributes You can use this endpoint to obtain supported attributes (symbols, backdrops, models) for a list of collections ```bash theme={null} POST https://proxy.thermos.gifts/api/v1/attributes Content-Type: application/json ``` You must specify list of collection names in the request body: ```json theme={null} { "collections": [ "Plush Pepe" ] } ``` The API will return an `ApiGiftCollectionAttributesResponse` object, which is a dictionary where keys are collection names and values are `ApiCollectionAttributes` objects: ```json theme={null} { "Plush Pepe": { "models": [ { "name": "Poison Dart", "rarity_per_mille": 30, "image_url": "https://gifts.coffin.meme/plush%20pepe/Poison%20Dart.png", "stats": { "count": 5, "floor": "4444000000000" } }, ... ], "backdrops": [ { "name": "Navy Blue", "rarity_per_mille": 20, "center_color": 7118557, "edge_color": 6057673, "pattern_color": 1194402, "text_color": 13885951, "stats": { "count": 1, "floor": "21000000000000" } }, ... ], "symbols": [ { "name": "Chocolate", "rarity_per_mille": 3, "stats": { "count": 1, "floor": "13777000000000" }, "image_url": "https://storage.googleapis.com/portals-market/gifts/plushpepe/patterns/chocolate.png" }, ... ] } } ``` ### Gift search You can use this endpoint to perform a complex search operation ```bash theme={null} POST https://proxy.thermos.gifts/api/v1/gifts Content-Type: application/json ``` You must specify request body which is a `ApiGiftSearchRequest` object: ```json theme={null} { "ordering": "PRICE_ASC", "page": 1, "per_page": 1, "query": "pepe #123", "price_range": { "min": "1000000000", "max": "20000000000" }, "number": 1, "collections": [ "string" ], "models": [ "Poison Dart" ], "backdrops": [ "Navy Blue" ], "symbols": [ "Chocolate" ], "markets": [ "MRKT" ] } ``` Every parameter here is optional, e.g. this request body, in fact, is valid: ```json theme={null} {} ``` Parameters overview: * `ordering`: defines the sort order of gifts. Allowed values are `PRICE_ASC`, `PRICE_DESC`, `MODEL_RARITY_ASC`, `MODEL_RARITY_DESC`, `BACKDROP_RARITY_ASC`, `BACKDROP_RARITY_DESC`, `SYMBOL_RARITY_ASC`, `SYMBOL_RARITY_DESC`, `RARITY_SCORE_ASC`, `RARITY_SCORE_DESC`, `NUMBER_ASC`, `NUMBER_DESC` * `page`: defines current page. Minimum page is `1` * `per_page`: defines number of gifts per page * `query`: defines full-text search query * `price_range`: defines min & max price; prices are specified in nanoton. min & max are optional, e.g. you can specify either one of them or both * `number`: defines the gift number * `collections`: defines the list of gift collections * `models`: defines the list of gift models * `backdrops`: defines the list of gift backdrops * `symbols`: defines the list of gift symbols * `markets`: defines the list of gift markets The API will return an `ApiGiftSearchResponse` object: ```json theme={null} { "items": [ { "external_id": "bacde555-90bf-4fee-8de2-08a929fb7bcc", "collection": "B-Day Candle", "model": { "name": "Glittery Day", "rarity_per_mille": 12 }, "symbol": { "name": "Corn", "rarity_per_mille": 4 }, "backdrop": { "name": "Strawberry", "rarity_per_mille": 15 }, "number": 240011, "price": "1240000000", "unlock_date": "2025-07-01T19:37:56Z", "lottie_url": "https://nft.fragment.com/gift/bdaycandle-240011.lottie.json", "image_url": "https://nft.fragment.com/gift/bdaycandle-240011.medium.jpg", "marketplace": "MRKT", "rarity_score": 720, "emoji_id": "5929128238172341773" } ], "count": 360254, "page": 1, "pages": 360254 } ``` Note that this api returns cached information and returned information may be outdated (e.g. price may be changed or gift may be already sold). You should always validate the current gift info by calling the `Get gift` endpoint ### Get gift You can use this endpoint to get a gift by its marketplace & external id. This endpoint always returns actual data ```bash theme={null} GET https://proxy.thermos.gifts/api/v1/gifts/{marketplace}/{external_id} ``` The API will return an `ApiGiftExternal` object in case of success, or `404` if gift is not available anymore: ```json theme={null} { "gift": { "external_id": "bacde555-90bf-4fee-8de2-08a929fb7bcc", "collection": "B-Day Candle", "model": { "name": "Glittery Day", "rarity_per_mille": 12 }, "symbol": { "name": "Corn", "rarity_per_mille": 4 }, "backdrop": { "name": "Strawberry", "rarity_per_mille": 15 }, "number": 240011, "price": "1240000000", "unlock_date": "2025-07-01T19:37:56Z", "lottie_url": "https://nft.fragment.com/gift/bdaycandle-240011.lottie.json", "image_url": "https://nft.fragment.com/gift/bdaycandle-240011.medium.jpg", "marketplace": "MRKT", "rarity_score": 720, "emoji_id": "5929128238172341773" }, "metadata": {} } ``` # Get all jettons owned by the account Source: https://docs.swap.coffee/technical-guides/tokens-api-openapi/accounts/get-all-jettons-owned-by-the-account https://tokens.swap.coffee/api/v3/openapi.yaml get /api/v3/accounts/{address}/jettons # Bulk fetch jettons by addresses (up to 100 per request) Source: https://docs.swap.coffee/technical-guides/tokens-api-openapi/jettons/bulk-fetch-jettons-by-addresses-up-to-100-per-request https://tokens.swap.coffee/api/v3/openapi.yaml post /api/v3/jettons/by-addresses # Get all jettons (up to 100 per request) Source: https://docs.swap.coffee/technical-guides/tokens-api-openapi/jettons/get-all-jettons-up-to-100-per-request https://tokens.swap.coffee/api/v3/openapi.yaml get /api/v3/jettons # Get jetton by address Source: https://docs.swap.coffee/technical-guides/tokens-api-openapi/jettons/get-jetton-by-address https://tokens.swap.coffee/api/v3/openapi.yaml get /api/v3/jettons/{address} # Get jetton OHLCV candlestick data Source: https://docs.swap.coffee/technical-guides/tokens-api-openapi/jettons/get-jetton-ohlcv-candlestick-data https://tokens.swap.coffee/api/v3/openapi.yaml get /api/v3/jettons/{address}/ohlcv-chart Returns up to `limit` most recent non-empty OHLC candles of the requested `interval` grain. Window is automatically widened: provider over-fetches, filters empty candles (zero volume and flat OHLC), retries once if not enough candles collected. Returns fewer than `limit` only if data is genuinely scarce. # Get jetton price chart data Source: https://docs.swap.coffee/technical-guides/tokens-api-openapi/jettons/get-jetton-price-chart-data https://tokens.swap.coffee/api/v3/openapi.yaml get /api/v3/jettons/{address}/price-chart # Get top 10 jetton holders Source: https://docs.swap.coffee/technical-guides/tokens-api-openapi/jettons/get-top-10-jetton-holders https://tokens.swap.coffee/api/v3/openapi.yaml get /api/v3/jettons/{address}/holders # Import a jetton. If no verification is provided, the jetton will be marked according to our own whitelist. Source: https://docs.swap.coffee/technical-guides/tokens-api-openapi/jettons/import-a-jetton-if-no-verification-is-provided-the-jetton-will-be-marked-according-to-our-own-whitelist https://tokens.swap.coffee/api/v3/openapi.yaml post /api/v3/jettons/import # Jetton hybrid search Source: https://docs.swap.coffee/technical-guides/tokens-api-openapi/jettons/jetton-hybrid-search https://tokens.swap.coffee/api/v3/openapi.yaml get /api/v3/hybrid-search If query is not specified and `kind` is either `DEXES` or `MEMES_MEMEPADS`, page is accounted for, otherwise page is ignored. If query is not specified and `kind` is `DEXES`, sort is accounted for, otherwise sort is ignored. If kind is one of `ALL`, `MEMES_ALL`, `MEMES_MEMEPADS`, `verification` must include `COMMUNITY` # Refresh jetton data from the blockchain Source: https://docs.swap.coffee/technical-guides/tokens-api-openapi/jettons/refresh-jetton-data-from-the-blockchain https://tokens.swap.coffee/api/v3/openapi.yaml post /api/v3/jettons/refresh # Update jetton verification status Source: https://docs.swap.coffee/technical-guides/tokens-api-openapi/jettons/update-jetton-verification-status https://tokens.swap.coffee/api/v3/openapi.yaml put /api/v3/jettons/{address}/verification # Assign a label to a jetton Source: https://docs.swap.coffee/technical-guides/tokens-api-openapi/labels/assign-a-label-to-a-jetton https://tokens.swap.coffee/api/v3/openapi.yaml post /api/v3/labels/{address} # Create a new label Source: https://docs.swap.coffee/technical-guides/tokens-api-openapi/labels/create-a-new-label https://tokens.swap.coffee/api/v3/openapi.yaml post /api/v3/labels # Get all labels Source: https://docs.swap.coffee/technical-guides/tokens-api-openapi/labels/get-all-labels https://tokens.swap.coffee/api/v3/openapi.yaml get /api/v3/labels # Remove a label from a jetton Source: https://docs.swap.coffee/technical-guides/tokens-api-openapi/labels/remove-a-label-from-a-jetton https://tokens.swap.coffee/api/v3/openapi.yaml delete /api/v3/labels/{address} # Hybrid Search Source: https://docs.swap.coffee/technical-guides/tokens-api/hybrid-search Search across DEX-listed jettons and pre-DEX memepad jettons in one call. Hybrid search queries jettons across two sources at once: * **DEX-listed jettons** — standard jettons tradeable through swap.coffee routing. * **Memepad jettons** — pre-DEX jettons still living on a bonding-curve launchpad (for example [TONFUN](https://tonfun.me/)). Once a memepad jetton's bonding curve graduates, the jetton transitions to a regular DEX-listed jetton. This is the recommended endpoint to power a universal *"find a token"* input in your UI. *** ## Endpoint ```http theme={null} GET /api/v3/hybrid-search ``` **Query parameters:** * **search** *(string)* — free-text query across jetton name and symbol. * **verification** *(array, default: `[WHITELISTED]`)* — verification statuses to include. Accepted values: `WHITELISTED`, `COMMUNITY`, `UNKNOWN`, `BLACKLISTED`. Pass multiple values by repeating the parameter. * **kind** *(enum)* — scope of the search: * `ALL` — everything * `DEXES` *(default)* — only jettons listed on DEXes * `MEMES_ALL` — all meme jettons (DEXes + memepads) * `MEMES_DEXES` — meme jettons already graduated to DEXes * `MEMES_MEMEPADS` — meme jettons still on memepads * **sort** *(enum)* — ordering: `FDMC`, `TVL`, `MCAP`, `VOLUME_24H`, `PRICE_CHANGE_24H`. * **page** *(integer, 1–100, default: 1)*. * **size** *(integer, 1–100, default: 20)*. ⚠️ **Note:** `page` and `sort` are ignored for some `kind` values where ordering is implicit. Refer to the [Swagger UI](https://tokens.swap.coffee/api/v3/swagger-ui) for the exact behavior per kind. *** ## Response `200 OK` — array of polymorphic jetton objects, discriminated by a `type` field: * `type: "common"` → a standard [jetton object](/technical-guides/tokens-api/jettons#jetton-object). * `type: "memepad"` → a [memepad jetton](#memepad-jettons). *** ## Memepad Jettons A memepad jetton has a smaller shape than a DEX-listed jetton, because the usual market statistics (TVL across multiple pools, holders count, multi-window price changes) do not apply while the bonding curve is still live. ### Top-level fields * **address** *(string, required)*: Raw jetton master address. * **protocol** *(string, required)*: Memepad protocol identifier, e.g. `TONFUN`. * **total\_supply** *(string, required)* * **decimals** *(integer, required)* * **mintable** *(boolean, required)* * **verification** *(enum, required)*: Same enum as for a regular jetton. * **created\_at** *(datetime, required)* * **name** *(string)* * **symbol** *(string)* * **image\_url** *(string)* * **market\_stats** *(object)* — see below. ### `market_stats` for memepad jettons * **price\_usd** *(number)* — current price in USD on the curve. * **tvl\_usd** *(number)* — total value locked in the curve. * **fdmc\_usd** *(number)* — fully diluted market cap in USD. * **collected\_ton** *(number)* — TON already collected toward graduation. * **max\_ton** *(number)* — TON target for graduation. * **progress** *(number, 0–1)* — share of the bonding curve completed. Once a memepad jetton graduates, subsequent calls return it as a regular [jetton object](/technical-guides/tokens-api/jettons#jetton-object) with the full market statistics. # Introduction Source: https://docs.swap.coffee/technical-guides/tokens-api/introduction Read live token data for the TON blockchain from the swap.coffee Tokens API. **swap.coffee** constantly updates its list of supported tokens (or **jettons** on **TON**). This list determines which assets our swap algorithms can use. Token data and its market properties **(price, TVL, volume, holders, FDMC, etc.)** are aggregated from various sources and refreshed regularly. You can read the list to power your own applications — build analytics dashboards, token explorers, trading bots, or integrate the data directly into your product. ## Endpoints * **Base URL:** `https://tokens.swap.coffee` * **Interactive Swagger UI:** [`/api/v3/swagger-ui`](https://tokens.swap.coffee/api/v3/swagger-ui) * **OpenAPI specification:** [`/api/v3/openapi.yaml`](https://tokens.swap.coffee/api/v3/openapi.yaml) You can generate your own API wrapper with any OpenAPI code generator. ## Rate Limits All read endpoints documented here are public and require no authentication. Public access is rate-limited to roughly **1 request per second per IP**. Beyond that, the API returns `429 Too Many Requests`. If you need higher throughput for an integration, request an API key through the [Get API Key](https://swapcoffee.typeform.com/to/Zx49Ho3y) form and pass it via the `X-Api-Key` header: ```bash theme={null} curl -H "X-Api-Key: " https://tokens.swap.coffee/api/v3/jettons ``` ## Error Format All error responses share the same shape: ```json theme={null} { "error": "human-readable error description" } ``` Typical status codes: * `400 Bad Request` — malformed input or invalid parameter. * `404 Not Found` — the requested jetton or resource does not exist. * `429 Too Many Requests` — rate limit hit. ## Conventions * All datetime fields are in **ISO 8601** format. * Jetton addresses are always returned in **raw** form (`workchain:hash`). * Token amounts are returned as **strings in base units** (no decimal point applied). ## Community Libraries ⚠️ **Note:** The libraries below are maintained by third parties rather than the swap.coffee team. We cannot guarantee their stability or correctness. | Language | Library | Description | | :------- | :------------------------------------------------------------------------------ | :-------------------------------------------- | | Python | [py-stollen/swapcoffee-tokens](https://github.com/py-stollen/swapcoffee-tokens) | Python wrapper for the Tokens API (legacy v2) | If you maintain a Tokens API wrapper in another language and would like it listed here, reach out in [@swap.coffee DEV Chat](https://t.me/swapcoffee_dev_chat). # Jettons Source: https://docs.swap.coffee/technical-guides/tokens-api/jettons Read jetton metadata, market statistics and per-account holdings. This page describes the canonical **jetton object** returned by the Tokens API and the read-only endpoints that serve it. ## Jetton Object Each jetton entry contains the following fields: * **address** *(string, required)*: Raw blockchain address of the jetton master contract. ⚠️ Always returned in raw hex form (`workchain:hash`). * **decimals** *(integer, required)*: Number of decimal places the jetton supports. * **created\_at** *(ISO 8601 datetime)*: Date and time the jetton was added to the list. * **total\_supply** *(string)*: Total supply in base units (no decimal point). * **name** *(string)*: Jetton name, e.g. `Tether USD`. * **symbol** *(string)*: Jetton ticker, e.g. `USDT`. * **mintable** *(boolean)*: Whether new tokens can be minted. * **buy\_fee** *(integer)*: On-chain fee (bps) charged on buys, if any. * **sell\_fee** *(integer)*: On-chain fee (bps) charged on sells, if any. * **verification** *(enum)*: Verification status — see [Verification Status](#verification-status). * **contract\_interface** *(string)*: Implementation identifier (e.g. `jetton_wallet_tonfun`). Used by the aggregator to route through specialized jetton implementations. * **image\_url** *(string)*: URL of the jetton logo. * **market\_stats** *(object)*: Aggregated market statistics — see [Market Statistics](#market-statistics). * **labels** *(array)*: Labels attached to the jetton — see [Labels](/technical-guides/tokens-api/labels). * **scaled\_ui\_multiplier** *(object)*: Optional UI multiplier (`numerator` / `denominator`) applied on top of `decimals` when displaying balances to end users. Relevant for rebase / scaled-UI jettons. ### Market Statistics The `market_stats` object aggregates the most recent on-chain and market data: * **holders\_count** *(integer)*: Number of unique jetton holders. * **price\_usd** *(number)*: Current price in USD. * **price\_change\_5m** *(number)*: Price change over the last 5 minutes (percentage). * **price\_change\_1h** *(number)*: Price change over the last hour (percentage). * **price\_change\_6h** *(number)*: Price change over the last 6 hours (percentage). * **price\_change\_24h** *(number)*: Price change over the last 24 hours (percentage). * **price\_change\_7d** *(number)*: Price change over the last 7 days (percentage). * **volume\_usd\_24h** *(number)*: 24-hour trading volume in USD. * **tvl\_usd** *(number)*: Total value locked in USD across supported pools. * **fdmc** *(number)*: Fully diluted market capitalization in USD. * **mcap** *(number)*: Circulating market capitalization in USD. * **trust\_score** *(integer, 0–100)*: Reliability score computed from multiple signals. ### Verification Status The `verification` field reflects how swap.coffee classifies a jetton. Possible values: * **`WHITELISTED`** — the jetton is verified and whitelisted by swap.coffee. Safe and routable; guaranteed to be fee-free. * **`COMMUNITY`** — the jetton's contract hash is recognized as safe, but the jetton is not used in swap.coffee routing. Guaranteed to be fee-free. * **`UNKNOWN`** — the jetton is not verified and may be unsafe. * **`BLACKLISTED`** — the jetton is blacklisted and considered dangerous. ### Example ```json theme={null} { "address": "0:a5d12e31be87867851a28d3ce271203c8fa1a28ae826256e73c506d94d49edad", "decimals": 9, "created_at": "2025-04-14T16:06:08.765Z", "total_supply": "10000000000000000", "name": "swap.coffee", "symbol": "CES", "mintable": false, "buy_fee": 0, "sell_fee": 0, "verification": "WHITELISTED", "contract_interface": "jetton_wallet", "image_url": "https://swap.coffee/logo.webp", "market_stats": { "holders_count": 6133, "price_usd": 0.8406369824666934, "price_change_5m": 0, "price_change_1h": 0, "price_change_6h": 0, "price_change_24h": 0.37, "price_change_7d": 1.12, "volume_usd_24h": 192.946, "tvl_usd": 72106.4, "fdmc": 8250090, "mcap": 8250090, "trust_score": 100 }, "labels": [ { "label": "new", "label_id": 1, "created_at": "2025-07-15T10:52:55.611Z", "expires_at": "2025-07-22T10:52:55.585Z" } ] } ``` *** ## List Jettons ```http theme={null} GET /api/v3/jettons ``` Returns up to 100 jettons per request. Supports filtering and pagination. **Query parameters:** * **search** *(string)* — free-text filter across jetton name and symbol. * **verification** *(array of verification statuses, default: `[WHITELISTED]`)* — verification statuses to include. Accepted values: `WHITELISTED`, `COMMUNITY`, `UNKNOWN`, `BLACKLISTED`. ⚠️ To pass multiple values, repeat the parameter in the query string, e.g. `verification=WHITELISTED&verification=COMMUNITY`. * **label\_id** *(integer)* — return only jettons carrying a specific label. * **page** *(integer, min: 1, default: 1)* — page number. * **size** *(integer, 1–100, default: 100)* — number of jettons per page. **Response:** `200 OK` — array of [jetton objects](#jetton-object), with a `Cache-Control` header for caching hints. *** ## Get a Single Jetton ```http theme={null} GET /api/v3/jettons/{address} ``` Fetch a single jetton by its master address. **Parameters:** * **address** *(path, required)* — raw jetton master address. * **refresh\_price** *(query, boolean, default: true)* — whether to recompute the current price on the fly from the latest pools state. Set to `false` for a cheaper read that returns a slightly stale price. **Responses:** `200 OK` — a [jetton object](#jetton-object) | `404 Not Found` — jetton is unknown. *** ## Bulk Fetch by Addresses ```http theme={null} POST /api/v3/jettons/by-addresses ``` Fetch up to 100 jettons at once. The request body is a JSON array of raw jetton master addresses. **Query parameter:** `refresh_price` *(boolean, default: true)*. **Request body:** ```json theme={null} [ "0:a5d12e31be87867851a28d3ce271203c8fa1a28ae826256e73c506d94d49edad", "0:b113a994b5024a16719f69139328eb759596c38a25f59028b146fecdc3621dfe" ] ``` **Response:** `200 OK` — array of [jetton objects](#jetton-object). *** ## Top Holders ```http theme={null} GET /api/v3/jettons/{address}/holders ``` Returns the **top 10 holders** of a jetton. **Response:** `200 OK` — array of wallet entries, each with: * **owner** — wallet owner address. * **wallet** — jetton wallet address. * **master** — jetton master address. * **balance** — balance in nano units (string). *** ## Price Chart ```http theme={null} GET /api/v3/jettons/{address}/price-chart ``` Historical price series for a jetton. **Query parameters:** * **from** *(datetime, required)* — start of the window (inclusive). * **to** *(datetime, required)* — end of the window (inclusive). * **currency** *(enum: `usd` | `ton`, default: `usd`)* — denomination for returned values. **Response:** `200 OK` ```json theme={null} { "points": [ { "time": "2025-04-14T16:06:08.765Z", "value": 0.8406 }, { "time": "2025-04-14T17:06:08.765Z", "value": 0.8411 } ] } ``` *** ## Account Jettons ```http theme={null} GET /api/v3/accounts/{address}/jettons ``` Returns all jettons owned by an account, with balances and the attached jetton metadata. **Response shape:** ```json theme={null} { "items": [ { "balance": "1000000000", "jetton_address": "0:...", "jetton_wallet": "0:...", "jetton": { /* ApiJetton object */ } } ] } ``` # Labels Source: https://docs.swap.coffee/technical-guides/tokens-api/labels Tag jettons with labels for filtering and UI classification. Labels classify jettons for UI or filtering purposes. They are attached to jettons and appear in the `labels` array of every [jetton object](/technical-guides/tokens-api/jettons#jetton-object). ## Label Structure Every label entry attached to a jetton has the following fields: * **label** *(string)*: Label name, e.g. `new`. * **label\_id** *(integer)*: Numeric identifier. * **created\_at** *(datetime)*: When the label was attached. * **expires\_at** *(datetime, optional)*: When the label will be automatically removed (for time-limited labels). ```json theme={null} { "label": "new", "label_id": 1, "created_at": "2025-07-15T10:52:55.611Z", "expires_at": "2025-07-22T10:52:55.585Z" } ``` ## Common Labels * **`new`** — the jetton was listed recently; the label remains for seven days. * **`contest`** — the jetton participates in a contest or promotion on swap.coffee. * **`cashback`** — swapping this jetton on swap.coffee qualifies for cashback rewards. ## Filtering Jettons by Label Pass the numeric `label_id` to the [`GET /api/v3/jettons`](/technical-guides/tokens-api/jettons#list-jettons) endpoint to return only jettons carrying that label: ```http theme={null} GET /api/v3/jettons?label_id=1 ``` ## List All Labels ```http theme={null} GET /api/v3/labels ``` Returns every label known to the service, with its numeric `id`, `label` name, and `created_at` timestamp. Use this endpoint to resolve a label name to its `label_id` before filtering. **Response:** `200 OK` ```json theme={null} [ { "id": 1, "label": "new", "created_at": "2025-01-01T00:00:00.000Z" }, { "id": 2, "label": "contest", "created_at": "2025-02-01T00:00:00.000Z" }, { "id": 3, "label": "cashback", "created_at": "2025-03-01T00:00:00.000Z" } ] ```