# Welcome to Interest Protocol

We are updating our documentation. If you have any urgent questions, please reach out to one of our social channels below.

## Join us

* [Twitter](https://twitter.com/IPXSui)
* [Medium](https://medium.com/@interestprotocol)
* [Telegram](https://t.me/interestprotocol)
* [Discord](https://discord.com/invite/interestprotocol)

## Learn more&#x20;


# Sui💧


# Contracts


# Memez

{% tabs %}
{% tab title="Mainnet" %}

### Soon\~

{% endtab %}

{% tab title="Testnet" %}

### Packages

<mark style="color:yellow;">**MemezFun:**</mark> [0x8ac848bd470e8fcf64899f9361b21fd07c2c6da06e28f1edb5cd596f245f866c](https://testnet.suivision.xyz/package/0x8ac848bd470e8fcf64899f9361b21fd07c2c6da06e28f1edb5cd596f245f866c)\
\ <mark style="color:yellow;">**ACL:**</mark> [0x5d406d0307d260f6ffc01f87960b0c28b8c5c3f0e8e71897b1a924a757232179](https://testnet.suivision.xyz/package/0x5d406d0307d260f6ffc01f87960b0c28b8c5c3f0e8e71897b1a924a757232179?tab=Code)

<mark style="color:yellow;">**Vesting:**</mark> [0xdada5d84429db8d56a775593b2893fc030826055dc84fa47ccdfd4933a63d093](https://testnet.suivision.xyz/package/0xdada5d84429db8d56a775593b2893fc030826055dc84fa47ccdfd4933a63d093?tab=Code)&#x20;

<mark style="color:yellow;">**Witnesses:**</mark> [0x06267071d0eecfb7d16418cb71da4c7b7941b28208a71086ff3e47731c2d263a](https://testnet.suivision.xyz/package/0x06267071d0eecfb7d16418cb71da4c7b7941b28208a71086ff3e47731c2d263a?tab=Code)

<mark style="color:yellow;">**Migrator:**</mark> [0x5dd8927889172a7227e081bb3cb77ce3af4c9021390f5bb47aec329efea6359c](https://testnet.suivision.xyz/package/0x5dd8927889172a7227e081bb3cb77ce3af4c9021390f5bb47aec329efea6359c)

### Shared Objects

<mark style="color:yellow;">**ACL**</mark>

* **Id:** [0x1b5397ee2f6f8ccfb26016c1ed996f25b2277acb9ed5173fa0bed386360960d8](https://testnet.suivision.xyz/object/0x1b5397ee2f6f8ccfb26016c1ed996f25b2277acb9ed5173fa0bed386360960d8)
* **Initial Shared Version:** 384530228&#x20;

<mark style="color:yellow;">**MigratorList**</mark>&#x20;

* **Id:** [0xc7530527c63a3bf6dfde19522409c0b93654fe55f9664ccb54b97b94f4c58b19](https://testnet.suivision.xyz/object/0xc7530527c63a3bf6dfde19522409c0b93654fe55f9664ccb54b97b94f4c58b19)
* **Initial Shared Version:** 384530298

<mark style="color:yellow;">**Version**</mark>

* **Id:** [0xd645a047027384fee98f52d32b5730a7de65e07e79b9df8afa09ee675b9f914c](https://testnet.suivision.xyz/object/0xd645a047027384fee98f52d32b5730a7de65e07e79b9df8afa09ee675b9f914c)
* **Initial Shared Version:** 384530298

<mark style="color:yellow;">**Config**</mark>

* **Id:** [0x42136e28848781b5a0c5ff544b2df0af414588289200ee01d01fdb3b0a66a418](https://testnet.suivision.xyz/object/0x42136e28848781b5a0c5ff544b2df0af414588289200ee01d01fdb3b0a66a418)
* **Initial Shared Version:** 384530298
  {% endtab %}
  {% endtabs %}


# Libs 📚

### Interest Math

<table><thead><tr><th>Name</th><th width="317">Object Id</th><th>Type</th></tr></thead><tbody><tr><td>Package Id</td><td><a href="https://suiscan.xyz/mainnet/object/0x0a885c86b868d83e5094ef8a34985d510a99f4dd1491d115297eb23cea427595/contracts">0x0a885c86b868d83e5094ef8a34985d510a99f4dd1491d115297eb23cea427595</a></td><td>Immutable</td></tr></tbody></table>

{% @github-files/github-code-block url="<https://github.com/interest-protocol/interest-math>" %}

### IPX Coin Standard

<table><thead><tr><th>Name</th><th width="317">Object Id</th><th>Type</th></tr></thead><tbody><tr><td>Package Id</td><td><a href="https://suiscan.xyz/mainnet/object/0x7ead93e49fe002193faec3d2e4a7b750e9e568b5d875cafe17fcb0dc672b075e/contracts">0x7ead93e49fe002193faec3d2e4a7b750e9e568b5d875cafe17fcb0dc672b075e</a></td><td>Immutable</td></tr></tbody></table>

{% @github-files/github-code-block url="<https://github.com/interest-protocol/ipx-coin-standard>" %}

### Constant Product

<table><thead><tr><th>Name</th><th width="317">Object Id</th><th>Type</th></tr></thead><tbody><tr><td>Package Id</td><td><a href="https://suiscan.xyz/mainnet/object/0x9257e52d7a6545900184082fe8ad41cc6f61c3c65c14cd9710357a83bf0e1490/contracts">0x9257e52d7a6545900184082fe8ad41cc6f61c3c65c14cd9710357a83bf0e1490</a></td><td>Immutable</td></tr></tbody></table>

{% @github-files/github-code-block url="<https://github.com/interest-protocol/constant-product>" %}

### BPS

<table><thead><tr><th>Name</th><th width="317">Object Id</th><th>Type</th></tr></thead><tbody><tr><td>Package Id</td><td><a href="https://suiscan.xyz/mainnet/object/0xdd7e07fc30acb942fc757ff732d1b4db104e0aba9717133b4eac82260dcd9f18/contracts">0x861a5bc378c5a4cdb8ed680c8edf6e147427f776c3b0af0002abe508c2621998</a></td><td>Immutable</td></tr></tbody></table>

{% @github-files/github-code-block url="<https://github.com/interest-protocol/bps>" %}


# Suicoins

**Suicoins** serves as the utility layer for all tokens and NFTs on the Sui Network. Its features include:

* A **Swap** feature powered by Aftermath Finance.
* A **DCA (Dollar Cost Averaging)** tool.
* An **Airdrop** feature for seamless reward distribution.
* An **Incinerator** to help keep your wallet clean by removing unwanted tokens.
* A **Send** feature powered by Mysten Lab's xkSend for efficient transfers.
* A **Merger** to free up chain space and declutter your wallet by consolidating assets.


# Swap

Suicoins now supports **Smart Router Swapping**, an advanced feature powered by our esteemed partner Aftermath Finance. This powerful tool ensures you always get the best rates for your swaps on the **Sui Network**.

***

### <mark style="color:blue;">Smart-Order Router (SOR)</mark>

The **Smart-Order Router (SOR)** is an innovative **DEX aggregator** designed for the Sui network. It provides users with optimal swap prices by connecting to multiple liquidity pools and decentralized exchanges (DEXes) in the ecosystem.

#### <mark style="color:blue;">Key Features</mark>

1. <mark style="color:blue;">**Comprehensive Aggregation**</mark>
   * SOR searches **every liquid DEX** on Sui, ensuring the best possible swap rates.
   * As the DeFi ecosystem grows, SOR continuously integrates with new DEXes.
2. <mark style="color:blue;">**Trade Optimization**</mark>
   * Splits large trades across multiple DEXes and liquidity pools to minimize slippage and improve trade efficiency.
3. <mark style="color:blue;">**Simplicity and Security**</mark>
   * Leverages Sui’s **Programmable Transaction Blocks (PTBs)** to combine complex, multi-step swap routes into a single, secure transaction.
4. <mark style="color:blue;">**Permissionless Composability**</mark>
   * Integrates seamlessly with other dApps, wallets, and DeFi tools.
   * Current use cases include integrations with:
     * **Nightly Wallet swaps**
     * **Scallop Tools**
     * **Suiba Telegram bot**

***

#### <mark style="color:blue;">Why Use SOR on Suicoins?</mark>

* **Best Rates, Every Time:** SOR searches all DEXes on Sui to guarantee competitive trade prices.
* **One-Click Swaps:** Even for complex transactions, only one user action is required.
* **Efficient and Reliable:** SOR ensures minimal slippage by splitting large trades and optimizing liquidity utilization.

#### <mark style="color:blue;">Supported Liquidity Pools and DEXes</mark>

The SOR connects to a wide range of liquidity pools and platforms, including:

* **Aftermath**
* **DeepBook**
* **Cetus**
* **Turbos**
* **FlowX**
* **Kriya**
* **Suiswap**
* **BlueMove**

***

### <mark style="color:blue;">How It Works</mark>

1. **Search for Liquidity:** The SOR scans all integrated DEXes and liquidity pools to identify the best available trade paths.
2. **Optimize the Trade Path:** For large trades, the SOR splits transactions into smaller sub-paths to minimize slippage.
3. **Batch Execution:** Through Sui’s PTBs, the trade is executed in a single transaction, ensuring security and simplicity.

***

The **Smart-Order Router (SOR)** makes trading on Suicoins seamless, cost-efficient, and secure—empowering both traders and developers within the Sui ecosystem.

### <mark style="color:blue;">Fees</mark>

{% hint style="info" %}
Suicoins has a swap fee of 0.25% on every Swap.
{% endhint %}


# Dollar-Cost Averaging (DCA)

The **Dollar-Cost Averaging (DCA)** feature on Suicoins allows users to **buy into or sell out of tokens gradually over time**, reducing the risks associated with market volatility. This feature is designed to provide a systematic approach to trading, making it an ideal choice for both beginners and experienced investors.

***

### <mark style="color:blue;">Key Features of DCA on Suicoins</mark>

1. **Automated Buy-In and Sell-Out Strategies**
   * Users can automate their investments, purchasing or selling tokens at regular intervals based on their predefined preferences.
2. **Active and Historical Monitoring Tools**
   * **Active DCA Tracker:** Monitor ongoing DCA activities in real time to ensure your strategies are on track.
   * **Historical Data Analysis:** Access detailed records of past DCA activities to study your trading performance and refine strategies.
3. **Risk Mitigation Through Averaging**
   * Gradual buying and selling helps mitigate the impact of price volatility, making it easier to achieve long-term investment goals.
4. **User-Friendly Interface**
   * Intuitive tools ensure that setting up, monitoring, and analyzing DCA strategies is seamless, even for those new to DeFi.

***

### <mark style="color:blue;">Benefits of Using DCA on Suicoins</mark>

* **Reduce Emotional Trading:** By sticking to a systematic plan, users avoid impulsive decisions influenced by market swings.
* **Historical Insights:** Leverage past DCA data to make informed adjustments to your trading strategies.
* **Flexibility:** Customize the frequency, token pair, and amount to suit your financial goals.

***

### <mark style="color:blue;">How It Works</mark>

1. **Set Up a DCA Plan:**
   * Select the token you want to buy or sell and set the frequency and amount.
2. **Monitor Active Plans:**
   * Use the **Active DCA Tracker** to check the progress of ongoing strategies in real time.
   * Make adjustments as needed without disrupting the overall plan.
3. **Analyze Historical Data:**
   * Review detailed records of completed DCA activities, including trade dates, amounts, and market conditions.
   * Use these insights to optimize future trading plans.

***

### <mark style="color:blue;">Why Use DCA on Suicoins?</mark>

* **Consistency in Trading:** Build wealth over time by regularly investing regardless of market conditions.
* **Data-Driven Insights:** Gain a deeper understanding of your trading habits and performance through robust historical data.
* **Ease of Use:** Simplify complex trading strategies with Suicoins’ intuitive DCA tools.

***

The DCA feature on Suicoins empowers users to trade systematically and analyze their performance, fostering a disciplined and informed approach to cryptocurrency trading.

### <mark style="color:blue;">Fee</mark>

{% hint style="info" %}
Suicoins has a 0,5% fee for DCA
{% endhint %}


# Airdrop

The **Suicoins Airdrop Tool** provides a seamless way for projects and individuals to distribute tokens to specific users via CSV files, NFT collection holders, or custom addresses. Whether you need to reward thousands of wallets or target holders of a particular NFT collection, our tool makes the process straightforward and efficient.

***

### <mark style="color:blue;">**Key Features**</mark>

* **Flexible Delivery Options**: Distribute tokens using CSV files, to NFT collection holders, or to custom addresses.
* **Batch Processing**: Airdrops are divided into batches of 500 transactions. For instance, an airdrop to 1,000 wallets will require two batches, with the DApp prompting you to confirm one transaction per batch.

***

### <mark style="color:blue;">**Methods of Delivery**</mark>

#### <mark style="color:blue;">**1. CSV File Distribution**</mark>

Distribute tokens to multiple wallet addresses with customizable amounts for each address.\
Follow these steps:

1. Prepare a CSV file formatted as follows:

   | Address     | Amount |
   | ----------- | ------ |
   | 0x123...abc | 100    |
   | 0x456...def | 200    |
2. Upload your prepared CSV file.
3. Choose the token you wish to airdrop.
4. Review and confirm the transactions in your wallet.

***

### <mark style="color:blue;">**Airdrop to NFT Collection Holders**</mark>

Easily distribute tokens to all holders of a specified NFT collection. Each NFT held acts as a multiplier for the drop amount.\
Here’s how to do it:

1. Navigate to the **Airdrop** section and select the token you wish to distribute.
2. Choose the **NFT Collection** option.
3. Specify the token amount to be airdropped per NFT.
4. Review and confirm the transaction in your wallet.

**Note**:

* The distribution is proportional to the number of NFTs a wallet holds. For example, a holder with 3 NFTs will receive 3 times the specified amount.

***

### <mark style="color:blue;">**Custom Address Airdrops**</mark>

Send the same amount of tokens to multiple wallet addresses.

Steps to use this feature:

1. Navigate to the **Airdrop** section and select the token you wish to airdrop.
2. Choose the **Custom Addresses** option.
3. Enter wallet addresses, one per line.
4. Specify the token amount to distribute to each address.
5. Review and confirm the transaction in your wallet.

***

### <mark style="color:blue;">**Important**</mark>

* **Batch Transactions**: Airdrops are limited to 500 wallets per batch. For larger distributions, you’ll need to confirm multiple transactions.
* **Verification**: After completing an airdrop, all details can be checked on the Sui Explorer.

### <mark style="color:blue;">Fees</mark>

{% hint style="info" %}
Suicoins has a airdrop fee of 0.004 Sui per wallet address.
{% endhint %}


# Suiplay Airdrop

The **Suiplay Airdrop** feature enables users and projects to distribute rewards directly to holders of **SuiPlay Soulbound NFTs**. Whether rewarding **Mythics**, **Exalted**, or all Soulbound NFT holders, the Suicoins **Airdrop Tool** simplifies the process of targeted and efficient reward distribution.

***

### <mark style="color:blue;">Key Features</mark>

1. **Targeted Airdrop Distribution**
   * Choose between specific groups:
     * **Mythics Soulbound NFT Holders**
     * **Exalted Soulbound NFT Holders**
     * **All Soulbound NFT Holders**
2. **Flexible Token Options**
   * Distribute any supported token of your choice.
3. **Streamlined Process**
   * An intuitive interface guides users through the setup, review, and execution of the airdrop.

***

### <mark style="color:blue;">How It Works</mark>

1. **Navigate to the Airdrop Tool:**
   * Open the **Suicoins** and select the **Airdrop** section.
2. **Select the Delivery Method:**
   * Choose **SuiPlay Holders** as the method of delivery.
3. **Choose the Recipient Group:**
   * Select the group of SuiPlay Soulbound NFT holders to airdrop to:
     * **Mythics**
     * **Exalted**
     * **Everyone**
4. **Set Token and Amount:**
   * Specify the token and the amount to be distributed to each recipient.
5. **Review and Confirm:**
   * Double-check your transaction details.
   * Approve and confirm the transaction in your wallet.

In this example, we’ve successfully airdropped 0.001 SUI to each SuiPlay Soulbound NFT holder (Mythics and Exalted).

{% embed url="<https://youtu.be/7zVEH0Fm0-4>" %}

### <mark style="color:blue;">Fees</mark>

{% hint style="info" %}
Suicoins charges 0.002 Sui per Suiplay Wallet Address.
{% endhint %}


# Incinerator

An innovative tool developed by IPXSui for the Sui Network, the Suicoins Incinerator automates asset burning on the Sui blockchain, simplifying the removal of unwanted NFTs, tokens, and objects from your Sui Wallet. This document provides an overview of its features, usage, and implementation details.

***

### <mark style="color:blue;">Overview</mark>

The Suicoins Incinerator is designed to streamline asset management by allowing users to "burn" or delete digital assets from their Sui Wallet. Whether clearing unwanted tokens, NFTs, or other assets, the Incinerator provides a seamless interface for bulk or individual deletions. This tool helps users declutter their wallets and reclaim Sui in some cases.

### <mark style="color:blue;">Key Features</mark>

* **Automated Burning**: Burn assets in bulk or one-by-one with a single click. Say goodbye to manual transaction processes.
* **Space Optimization**: Merges multiple assets into one and frees up blockchain space, especially useful when removing scam or unwanted objects.
* **Reclaim Sui**: By freeing up space, you may recover Sui if the reclaimed value exceeds the transaction cost.
* **Clutter Management**: Keep your wallet tidy by removing or merging assets you no longer need.
* **Enhanced Security**: Integrated with `suiet_walletGuardians` to help users identify and eliminate scam assets.

***

### <mark style="color:blue;">Getting Started</mark>

1. **Access the Incinerator**: Go to [Suicoins Incinerator](http://suicoins.com).
2. **Connect Your Wallet**: Ensure you have a compatible wallet connected, such as the Suiet Wallet.
3. **Select Assets to Burn**: Choose assets from your wallet for burning or merging.
4. **Confirm Action**: Follow the prompts to confirm your selections for incineration.

***

### <mark style="color:blue;">Usage Guide</mark>

1. **Connect Wallet**: After opening the Incinerator page, connect your Sui Wallet.
2. **Select Assets**: Browse your assets, and select either "Bulk Burn" or individual burning options to manage them as desired.
3. **Merge Coins or Objects**: Use the Incinerator to combine multiple assets into a single entity before burning. This frees up blockchain space.
4. **Send to 0x0 Address**: Once merged, the Incinerator sends the asset to the `0x0` address, effectively removing it from circulation.

{% hint style="info" %}
Sui does not natively support burning coins unless specifically implemented by the coin developer. For supported assets, Suicoins’ Incinerator merges and sends them to `0x0`, similar to Ethereum and Binance.
{% endhint %}

***

### <mark style="color:red;">⚠️ Important Warning</mark>&#x20;

{% hint style="danger" %}
**Be extremely cautious when using the Suicoins Incinerator, as incineration is an irreversible action.** \
\
**Once an asset is burned, it cannot be recovered.**\
\
Ensure you are **not accidentally burning legitimate assets**. Verify each asset carefully before proceeding.\
Suicoins and IPXSui will **not be liable** for any accidental burns. We **will not provide reimbursements** for mistaken incinerations.
{% endhint %}

***

### <mark style="color:blue;">Technical Details</mark>

The Suicoins Incinerator enables asset management by consolidating multiple coins or objects into a single entity and removing them from circulation. This not only frees up wallet space but may also return Sui to the user if the combined asset value exceeds the transaction fees.

#### <mark style="color:blue;">Space Optimization</mark>

On Suicoins, burning removes assets and may return Sui to the user by merging objects, provided the reclaimed value is higher than the transaction cost.

***

### <mark style="color:blue;">WalletGuardians Integration</mark>

The Incinerator is integrated with [@suiet\_walletGuardians](https://github.com/suiet/guardians/tree/main/src), which identifies and labels scam assets, making it easier to manage and delete unwanted items from your wallet. This integration ensures a safer and more efficient burning experience for all users.

To learn more about `suiet_walletGuardians` and how it enhances asset detection, refer to the [WalletGuardians GitHub repository](https://github.com/suiet/guardians/tree/main/src).


# Send

Suicoins integrates with **Mysten Labs' zkSend** to provide an innovative way to send and claim digital assets securely and anonymously. This feature supports **any publicly transferrable asset** and enables users to create claim links with ease.

Effortlessly send coins, NFTs, and other assets on the **Sui Network** in stealth mode within seconds.

***

### <mark style="color:blue;">Key Features</mark>

1. **Create zkSend Claim Links**
   * Generate claimable links for secure and private transfers of assets.
   * Support for all publicly transferrable assets, including:
     * Coins
     * NFTs
     * Other digital tokens
2. **Two Modes of Usage**
   * **Simple Link:**\
     Combine multiple assets (e.g., coins, NFTs) into a single claimable link.
   * **Bulk Link:**\
     Distribute a specific coin through multiple claimable links, ideal for batch transactions.\
     *(Note: This feature is exclusive to coins.)*
3. **Anonymity and Speed**
   * Send and claim assets in stealth mode, ensuring privacy.
   * Transactions are completed within seconds.

***

### <mark style="color:blue;">How It Works</mark>

1. **Choose a Mode:**
   * Select either the **Simple Link** or **Bulk Link** option, depending on your transfer requirements.
2. **Prepare the Assets:**
   * For Simple Link: Add various assets like coins and NFTs to be included in one claimable link.
   * For Bulk Link: Specify the coin and number of claimable links to create.
3. **Generate and Share the Link:**
   * Suicoins will create a zkSend claim link based on your inputs.
   * Share the link with recipients for them to claim the assets.
4. **Claim Assets:**
   * Recipients can use the provided link to claim their assets instantly and privately.

***

### <mark style="color:blue;">Implementation</mark>

Developers interested in implementing zkSend functionality can use the following resources:

* **Mysten Labs SDK:** [sdk.mystenlabs.com/zksend](http://sdk.mystenlabs.com/zksend)
* **Suicoins Open-Source Code:** [github.com/interest-protocol/sui-coins](http://github.com/interest-protocol/sui-coinsS)


# Merger

Think of your wallet as a digital garage—cluttered with tiny amounts of leftover coins. The **Suicoins Merger** feature lets you tidy things up, combining small amounts of various tokens to free up space and potentially uncover hidden value.

It’s like finding a forgotten bill in your old jacket pocket or discovering spare change in your couch cushions—only cooler and crypto-focused.

***

### <mark style="color:blue;">Key Benefits of the Merger</mark>

1. **Wallet Optimization**
   * Consolidate your wallet by merging tiny balances into more meaningful amounts.
   * Free up valuable space on the **Sui Network**.
2. **Discover Hidden Value**
   * Combine overlooked small balances of coins and potentially score extra $SUI.
3. **User-Friendly and Efficient**
   * A seamless process designed to help you manage your digital assets with minimal effort.

***

### <mark style="color:blue;">How It Works</mark>

1. **Access the Merger Tool:**
   * Navigate to the [**Merger Tool**](http://suicoins.com/merge) on Suicoins.
2. **Select Coins to Merge:**
   * Choose the tiny coin balances you want to consolidate.
3. **Execute the Merge:**
   * Suicoins will combine the selected balances and free up wallet space.
   * Any additional value discovered (e.g., $SUI) will be credited to your wallet.

***

### <mark style="color:blue;">Why Use Suicoins Merger?</mark>

* **Simplify Your Wallet:** No more managing countless tiny balances.
* **Optimize Network Space:** Help reduce clutter on the **Sui Network**.
* **Find Hidden Rewards:** Merge and unlock the potential of your unused crypto.

***

With Suicoins Merger, managing your crypto becomes simpler, tidier, and more rewarding. Start decluttering your wallet today at [**suicoins.com/merge**](http://suicoins.com/merge).


# Suicoins Terminal

### <mark style="color:blue;">Overview</mark>

🌐 [terminal.suicoins.com](https://terminal.suicoins.com/)

The Suicoins Terminal is an open-source, lightweight adaptation of the Suicoins Swap feature, designed to enable seamless, end-to-end cryptocurrency swaps that can be integrated effortlessly into your platform.

#### Benefits of the Suicoins Terminal:

* **Secure on-site trading** on the Sui Network
* **Enhanced user convenience** with no need to navigate away from your platform
* **Streamlined user experience** to improve trust and engagement

***

### <mark style="color:blue;">Key Features</mark>

#### **Predefined Configurations**

Define input and output tokens easily for precise trading pair setups.

#### **Restricted Trading Options**

Restrict swaps to specific tokens for enhanced security and platform focus.

***

### <mark style="color:blue;">Trading Fees Structure</mark>

The Suicoins Terminal applies a simple fee structure for swaps:

* **0.15% for Memecoin Project.**
* **0.15% for Suicoins.**

These fees are automatically calculated and deducted during each transaction.

***

### <mark style="color:blue;">How to Integrate</mark>

#### <mark style="color:blue;">Vanilla SDK Integration</mark>

Follow these steps to integrate the Vanilla SDK into your project:

**Step 1: Add the SDK Script**

Include the following script in your HTML file:

```html
<script src="https://cdn.jsdelivr.net/npm/@interest-protocol/sui-coins-terminal-vanilla/dist/index.umd.js"></script>
```

**Step 2: Add the Terminal Container**

Add an empty `<div>` with the required `id` attribute to your code:

```html
<div id="suicoins-terminal" class="terminal"></div>
```

**Step 3: Initialize the Terminal**

Initialize the Suicoins Terminal with your custom parameters:

```html
<script>
  SuiCoinsTerminal({
    typeIn: "0x2::sui::SUI",
    projectAddress: "0xdb3a22be6a37c340c6fd3f67a7221dfb841c818442d856f5d17726f4bcf1c8af",
    typeOut: "0xdeeb7a4662eec9f2f3def03fb937a663dddaa2e215b8078a284d026b7946c270::deep::DEEP",
    slippage: 1,
  });
</script>
```

***

#### <mark style="color:blue;">React SDK Integration</mark>

**Step 1: Install the SDK**

Use one of the following package managers to add the SDK to your React project:

```bash
pnpm add @interest-protocol/sui-coins-terminal  
# or  
yarn add @interest-protocol/sui-coins-terminal  
# or  
npm install @interest-protocol/sui-coins-terminal  
```

**Step 2: Import and Configure the Terminal Component**

Import the `SwapTerminal` component and configure it with the necessary parameters:

```jsx
import { SwapTerminal } from "@interest-protocol/sui-coins-terminal";

const Terminal = () => (
  <SwapTerminal
    typeIn="0x2::sui::SUI"
    projectAddress="0xdb3a22be6a37c340c6fd3f67a7221dfb841c818442d856f5d17726f4bcf1c8af"
    typeOut="0xdeeb7a4662eec9f2f3def03fb937a663dddaa2e215b8078a284d026b7946c270::deep::DEEP"
    slippage="1"
  />
);

export default Terminal;
```

***

Visit [terminal.suicoins.com](https://terminal.suicoins.com/) to learn more and integrate the Suicoins Terminal into your platform.

For any questions or assistance, our team is here to help—don’t hesitate to reach out.

***


# Memez.gg

MemeFi

### <mark style="color:yellow;">MemeFi... what? Do you mean DeFi</mark>

MemeFi (Meme Coin + Finance) are DeFi applications designed specifically for meme coins. Meme coins have carved their presence in the web3 industry as a vehicle to grab attention, new users and build culture. We have seen social trends and memes spread world wide because of meme coins.&#x20;

Dapps built for meme coins need to take into account their users are not afraid of risk, fees, high slippage nor volatility. They provide developers with the opportunity to explore new instruments as they are as constraint like in DeFi.

### <mark style="color:yellow;">Ok, What is Memez.gg ?!</mark>

<mark style="color:yellow;">**Memez.gg**</mark> is an end to end protocol to launch,  bootstrap liquidity and trade meme coins.

* <mark style="color:yellow;">**Memez.Fun**</mark> is a virtual liquidity launchpad with three different distribution mechanisms to price meme coins and bootstrap liquidity.
* <mark style="color:yellow;">**Memez.Dex**</mark> is an exchange designed to appreciate meme coins by implementing <mark style="color:yellow;">**special mechanisms**</mark> that benefit buyers and discourage sellers.

> All Meme coins created on Memez use the [IPX Coin Standard](#user-content-fn-1)[^1]

### <mark style="color:yellow;">Official Links</mark>

* [https://www.memez.gg](https://www.memez.gg/)
* <https://x.com/memezdotgg>

[^1]:


# Coins on Memez.GG

Step by step Guide of Coins on Memez.

The coin creation tool on [<mark style="color:yellow;">**Memez GG**</mark>](/overview/sui/memez.gg) allows users to generate their own custom tokens with a range of configurable options. This functionality enables individuals and projects to launch tokens tailored to their specific needs, whether for utility, governance, or community engagement.

### <mark style="color:yellow;">Configurable Features</mark>

When creating a coin, users define key attributes:

#### <mark style="color:yellow;">**Basic Information**</mark>

* **Coin Name** – Unique identifier for the token.
* **Ticker** – Short symbol (e.g., ROOT for Rootlets).
* **Description** – Brief summary of the token’s purpose.
* **Logo** – Custom image representing the coin.

#### <mark style="color:yellow;">**Supply Settings**</mark>

* **Total Supply** – Initial token amount (supports up to **9 decimal places**).
* **Maximum Supply** – Hard cap on total token supply.

#### <mark style="color:yellow;">**Advanced Features**</mark>

* **Burnable** – Tokens can be removed from circulation, with burn permissions configurable.
* **Mintable** – Allows the deployer to create additional tokens up to the **maximum supply**.
* **Editable Metadata** – Enables modifications to **name, ticker, description, and logo** after deployme

{% hint style="info" %}
This coin creation tool empowers users to design and launch tokens with flexibility while maintaining key security and governance controls. This tool uses the [<mark style="color:yellow;">IPX Coin Standard</mark>](https://docs.interestprotocol.com/overview/sui/ipx-coin-standard).
{% endhint %}

## <mark style="color:yellow;">Creating Coin on Memez GG</mark>

On the video below we have launched a token with all the functionalities mentioned above. Here are the details of the token created:

* Name: Kumo
* Ticker: Kumo
* Description: Kumo the cat
* Supply: 1,000,000
* Max Supply: 1000,000,000
* Functions enabled: Burnable, Mintable and Editable

<mark style="color:yellow;">🎥</mark>  <mark style="color:yellow;"></mark>*<mark style="color:yellow;">Watch the video for a step-by-step walkthrough.</mark>*

{% embed url="<https://youtu.be/XgB1eL9zUQE>" %}

## <mark style="color:yellow;">Editing The Metadata</mark>

**After creating a coin with the Edit function enabled, you can update its metadata at any time. Now, let's rebrand the Kumo coin we created earlier** by updating the following details:

* **Name**: Rootlets
* **Ticker**: ROOT
* **Description**: “Just Root it”
* **Image**: A Rootlet PFP

<mark style="color:yellow;">🎥</mark>  <mark style="color:yellow;"></mark>*<mark style="color:yellow;">Watch the video for the step-by-step walkthrough.</mark>*

{% embed url="<https://youtu.be/X8xpcaOcY0k>" %}

And just like that—within a few clicks, we’ve successfully rebranded the entire coin!

## <mark style="color:yellow;">Managing Tokens: Burning & Minting</mark>

Now that you know how to create and change it's metadata, let's explore two important functions—**burning** and **minting** tokens. These actions allow you to manage the token supply dynamically.

Remember that when we created the token, we enabled the ability to **burn** and **mint** tokens, setting the initial supply to **1,000,000** and the max supply to **1,000,000,000**. This means you can perform burns and mints freely within the range of **0 to 1,000,000,000** tokens.

On the video below, we'll use the rebranded **Rootlets** token to demonstrate both processes. In this case we will first mint 100,000 tokens and then mint the same amount.

{% embed url="<https://youtu.be/YC9_i9gwo0M>" %}

## <mark style="color:yellow;">Migrating a Coin from Suicoins to Memez GG</mark>

### <mark style="color:yellow;">Introduction</mark>

In this guide, we will walk through the process of migrating a coin created on Suicoins to Memez GG. This migration ensures that the coin follows the IPX Coin Standard, gaining key functionalities such as:

* Burning tokens
* Minting new tokens
* Editing metadata

By the end of this tutorial, your migrated coin will have all of these features.

### <mark style="color:yellow;">Prerequisites</mark>

{% hint style="info" %}
Before proceeding with the migration, ensure that:

* The deployer owns the treasury cap. Without it, migration is not possible.
* When creating a coin on Suicoins, you have chosen to **keep** the treasury cap. If it has been sent to a dead address, migration is **not** possible.
  {% endhint %}

### <mark style="color:yellow;">Step 1: Creating a Coin on Suicoins</mark>

1. Navigate to Suicoins and click **Create Token**.
2. Fill in the token details. For this tutorial, we will use the following example:
   * **Name**: Prime Machine
   * **Ticker**: PRIME
   * **Description**: Suii is the endgame and starts with Studio Mirai.
   * **Image**: Prime Machine #2059
   * **Supply**: 1 million tokens
3. **Important Step:** Do **not** set a fixed supply. Setting a fixed supply sends the treasury cap to a dead address, preventing migration. By keeping a flexible supply, the treasury cap remains with the deployer.
4. Confirm the transaction in your wallet.

Once confirmed, the token is successfully created on Suiicoins.

### <mark style="color:yellow;">Step 2: Migrating to Memez GG</mark>

1. Navigate to Memez GG and click **Create Token**, then select **Migrate**.
2. Choose the token you wish to migrate (e.g., **Prime Machine**).
3. Configure the token settings. Memez GG provides options similar to the token creation process but now includes the ability to enable all functionalities of the IPX Coin Standard. Enable:
   * Burning tokens
   * Minting new tokens
   * Editing metadata
4. Set a new max supply (e.g., **1 billion tokens**).
5. Confirm the transaction in your wallet.

<mark style="color:yellow;">🎥</mark>  <mark style="color:yellow;"></mark>*<mark style="color:yellow;">Watch the video for the step-by-step walkthrough.</mark>*

{% embed url="<https://youtu.be/40D4nheSpr8>" %}


# Memez.Fun

Virtual liquidity launchpad

### <mark style="color:yellow;">Virtual ... what?</mark>

In layman terms, Memez.fun is <mark style="color:yellow;">**a platform to launch meme coins and bootstrap liquidity**</mark>. The protocol supports <mark style="color:yellow;">**three launch strategies**</mark>:

* <mark style="color:yellow;">**Auction (High Risk):**</mark> It mimics a dutch auction in which the meme coin starts at a very high price and quickly declines until a fair price is found by traders.
* <mark style="color:yellow;">**Pump (High Risk):**</mark> The traditional method pioneered by pump.fun. The coin starts at a floor price to avoid early buyers from having a very large advantage.&#x20;
* <mark style="color:yellow;">**Stable (Low Risk):**</mark> It provides a fixed trading price for the coin until the target sui amount is acquired. Unlike a normal presale platform, users can exit their position anytime before the target raise is reached.

### <mark style="color:yellow;">Phases</mark>

The pools can be in three different phases:

**Bonding**

All pools start at this phase as soon as they are created. In this phase users are allowed to buy and sell freely.

**Migrating**

This is triggered once the pool collects enough Sui to migrate from Memez.fun to a DEX. During this time, no trading is allowed. Anyone can call the migration function to move the liquidity.

**Migrated**

It indicates that a pool has successfully migrated. Trading can now be resumed in the destined DEX. E.g. On Blast.fun, users can trade on Bluefin after migration.

{% hint style="info" %}
It is impossible to return to a previous phase.
{% endhint %}

### <mark style="color:yellow;">Migration</mark>

All pools on Memez.fun migrate once a certain amount of Sui is accumulated. This is referred as <mark style="color:yellow;">**Target Sui Amount**</mark>. Once this requirement is meant the liquidity is moved from our platform to a DEX chosen by the deployer.&#x20;

### <mark style="color:yellow;">Closed Loop Tokens</mark>

If chosen by the deploye&#x72;**, Memez.Fun pools can issue a Closed Loop Token** to prevent buyers from creating pools before migration. Read more about them [here](https://docs.sui.io/standards/closed-loop-token).&#x20;

### <mark style="color:yellow;">Miscellaneous</mark>&#x20;

**Dynamic Supply**

Meme coins on Memez.fun can have any supply. The contracts do not enforce a supply of 1 billion as other launchpads. Moreover, all coins are burnable.

**Upgradeable Metadata**

Meme coins created on Memez.fun can have their metadata updated by the deployer.

* Name
* Symbol
* Description
* Icon


# Multisig

For security purposes, The Memez Upgrade and Admin Caps are controlled by the following Multisig:

[0xbe222be876a0f09c953b6217fba8b64eb77853ce298513cb3efcfe19bfbaf0aa](https://suiscan.xyz/mainnet/account/0xbe222be876a0f09c953b6217fba8b64eb77853ce298513cb3efcfe19bfbaf0aa)

<mark style="color:yellow;">**Members:**</mark>

* [Jose](https://x.com/josemvcerqueira): 1 vote&#x20;
  * 0xbbf31f4075625942aa967daebcafe0b1c90e6fa9305c9064983b5052ec442ef7
  * AK2EGUxZXMKULhS+UmmqTB3ompdDSogXO9navAa4PAvF
* [Matical](https://x.com/opiateful): 1 vote
  * 0x302756ee637804f8ed90af097eee32258ff20662129f64ff3ef31ff697e6ab53
  * ANnQR0VWisQ2+RMr3E9azXyIh0XlDAZ7CzndRjkMgr4w
* [Eason](https://x.com/Eason_C13): 1 vote
  * 0xdbef82568fc43aab7a48759310362fa9d3f81218а6е2805f0783a6427322f01a
  * AMxcce1sZzg1yS6hOVyar9h0obqtbiviSb0RCyhZnn4I

Transactions require <mark style="color:yellow;">**2 votes**</mark> to pass.

It contains the following objects:

* <mark style="color:yellow;">**Memez Publisher:**</mark> 0x68fe5e2a135799de5c53ce3cb82902b187217e81b0e24e9f0f030371f555f872
  * Add display to all objects in Memez package. Currenly no object has any displays.
* <mark style="color:yellow;">**Memez Upgrade Cap:**</mark> 0x252b53c8a16c2a8843dd47f4da60a9fe4b47b790bba37dcc388de12948ea8403
  * Allows us to upgrade the Memez Package.
* <mark style="color:yellow;">**Memez Launchpad Upgrade Cap:**</mark> 0xff3bea66bb8a6f06ace5bfe1622a61589e387d85955b61a8107ecc5bff6fd16e
  * Allows us to upgrade the Memez Launchpad Package.
* <mark style="color:yellow;">**XPump Migrator Upgrade Cap:**</mark> 0x32186a566390b462678f4a4204098266e1337b9522ffa4e4d051c22ce1c38900
  * Can upgrade the migrator package that control the LP positions for Blast on Bluefin.
* <mark style="color:yellow;">**XPump Migrator Admin Cap:**</mark> 0x60a3b91023eaec63301e4fd7011a3f8536f8f94e05895610e749dc189a704a33
  * Can claim fees accrued by the Lp Positions on Bluefin.
* <mark style="color:yellow;">**Router Upgrade Cap:**</mark> 0x0477c7f09abf142a4e8a78309f00127f05cabb87f6c519168ea9579a9dfd9983
  * Allows us to upgrade our router package that auto-creates an on-chain wallet to avoid bricking users' wallets.
* <mark style="color:yellow;">**Vesting Upgrade Cap:**</mark> 0x0c1c3cf5dea0a302153192fac4d0767c0fa8f21b7724f85290c148c8f1187896
  * Allows us to upgrade our vesting package that linear vests meme coins


# Contract

The Memez.fun contract is [open source in Github.](https://github.com/interest-protocol/memez-gg/tree/main/fun) The contract is upgradeable with version control.

* <mark style="color:yellow;">**Original Id:**</mark> 0x779829966a2e8642c310bed79e6ba603e5acd3c31b25d7d4511e2c9303d6e3ef
* <mark style="color:yellow;">**Version 4:**</mark> 0x7e6aa6e179466ab2814425a780b122575296d011119fa69d27f289f5a28814bd


# memez\_pump\_config

<mark style="color:yellow;">new -</mark> packages a vector of u64 into a PumpConfig struct.

```rust
public fun new(values: vector<u64>): PumpConfig 
```

**Arguments:**

* **`values: vector<u64>`**\
  The values to be packaged. They are done linearly.


# memez\_config

<mark style="color:yellow;">set\_public\_key -</mark> allows the admin to set a public key address to verify signatures for protected pools. It is one per configuration.

```rust
public fun set_public_key<ConfigWitness>(
    self: &mut MemezConfig,
    _: &AdminWitness<MEMEZ>,
    public_key: vector<u8>,
    _ctx: &mut TxContext,
) 
```

**Arguments:**

* **`self: &mut MemezConfig`**\
  A mutable reference to the Memez global configuration object.\
  This is the config being updated with the new public key.
* **`_: &AdminWitness<MEMEZ>`**\
  An admin witness proving that the caller is authorized to update the Memez configuration.
* **`public_key: vector<u8>`**\
  The new public key (as raw bytes) to be set in the configuration.\
  It is used for verifying signatures in the Memez system.
* **`_ctx: &mut TxContext`**\
  A mutable reference to the transaction context provided by the Sui blockchain.<br>

<mark style="color:yellow;">set\_fees -</mark> allows the admin to set the fees for a configuration. This includes: creation, meme swap, quote swap, allocation and migration fee values.

```rust
public fun set_fees<ConfigWitness>(
    self: &mut MemezConfig,
    _: &AdminWitness<MEMEZ>,
    values: vector<vector<u64>>,
    recipients: vector<vector<address>>,
    _ctx: &mut TxContext,
)
```

**Arguments:**

* **`self: &mut MemezConfig`**\
  A mutable reference to the Memez global configuration object.\
  This is the config being updated with new fee settings.
* **`_: &AdminWitness<MEMEZ>`**\
  An admin witness proving that the caller is authorized to update the Memez configuration.
* `values: vector<vector<u64>>`\
  A nested vector of fee values, expressed in basis points or absolute units.\
  Defines the fee structure to apply across different pools or operations.
* **`recipients: vector<vector<address>>`**\
  A nested vector of recipient addresses corresponding to each fee value.\
  Specifies how fees are distributed among multiple beneficiaries (e.g., treasury, referrers, liquidity providers).
* **`_ctx: &mut TxContext`**\
  A mutable reference to the transaction context provided by the Sui blockchain.<br>

<mark style="color:yellow;">set\_meme\_referrer\_fee -</mark> allows the admin to set fee that will be shared with a referrer address during meme coin swaps. It is in basis points.

```rust
public fun set_meme_referrer_fee<ConfigWitness>(
    self: &mut MemezConfig,
    _: &AdminWitness<MEMEZ>,
    fee: u64,
    _ctx: &mut TxContext,
)
```

**Arguments:**

* **`self: &mut MemezConfig`**\
  A mutable reference to the Memez global configuration object.\
  This is the config being updated with a new meme referrer fee setting.
* **`_: &AdminWitness<MEMEZ>`**\
  An admin witness proving that the caller is authorized to update the Memez configuration.\
  Ensures only governance or privileged accounts can modify referrer fees.
* **`fee: u64`**\
  The new referrer fee value, expressed in basis points. Determines the portion of each meme trade allocated to the referrer.
* **`_ctx: &mut TxContext`**\
  A mutable reference to the transaction context provided by the Sui blockchain.<br>

<mark style="color:yellow;">set\_quote\_referrer\_fee -</mark> allows the admin to set fee that will be shared with a referrer address during quote coin swaps. It is in basis points.

```rust
public fun set_quote_referrer_fee<ConfigWitness>(
    self: &mut MemezConfig,
    _: &AdminWitness<MEMEZ>,
    fee: u64,
    _ctx: &mut TxContext,
)
```

**Arguments:**

* **`self: &mut MemezConfig`**\
  A mutable reference to the Memez global configuration object.\
  This is the config being updated with a new meme referrer fee setting.
* **`_: &AdminWitness<MEMEZ>`**\
  An admin witness proving that the caller is authorized to update the Memez configuration.\
  Ensures only governance or privileged accounts can modify referrer fees.
* **`fee: u64`**\
  The new referrer fee value, expressed in basis points. Determines the portion of each meme trade allocated to the referrer.
* **`_ctx: &mut TxContext`**\
  A mutable reference to the transaction context provided by the Sui blockchain.

<mark style="color:yellow;">remove -</mark> allows the admin to remove the values of a configuration.

```rust
public fun remove<ConfigWitness, Model: drop + store>(
    self: &mut MemezConfig,
    _: &AdminWitness<MEMEZ>,
    _ctx: &mut TxContext,
)
```

**Arguments:**

* **`self: &mut MemezConfig`**\
  A mutable reference to the Memez global configuration object.\
  This is the config instance being removed.
* **`_: &AdminWitness<MEMEZ>`**\
  An admin witness proving that the caller is authorized to remove a Memez configuration.\
  Ensures only governance or privileged accounts can perform this destructive action.
* **`_ctx: &mut TxContext`**\
  A mutable reference to the transaction context provided by the Sui blockchain.

<mark style="color:yellow;">add\_quote\_coin -</mark> whitelists a quote coin for a specific configuration.

```rust
public fun add_quote_coin<ConfigWitness, Quote>(
    self: &mut MemezConfig,
    _: &AdminWitness<MEMEZ>,
    _: &mut TxContext,
)
```

**Arguments:**

* **`self: &mut MemezConfig`**\
  A mutable reference to the Memez global configuration object.\
  This is the config instance being removed.
* **`_: &AdminWitness<MEMEZ>`**\
  An admin witness proving that the caller is an admin.
* **`_ctx: &mut TxContext`**\
  A mutable reference to the transaction context provided by the Sui blockchain.

<mark style="color:yellow;">remove\_quote\_coin -</mark> removes a quote coin from the whitelist of a specific configuration.

```rust
public fun remove_quote_coin<ConfigWitness, Quote>(
    self: &mut MemezConfig,
    _: &AdminWitness<MEMEZ>,
    _: &mut TxContext,
)
```

**Arguments:**

* **`self: &mut MemezConfig`**\
  A mutable reference to the Memez global configuration object.\
  This is the config instance being removed.
* **`_: &AdminWitness<MEMEZ>`**\
  An admin witness proving that the caller is an admin.
* **`_ctx: &mut TxContext`**\
  A mutable reference to the transaction context provided by the Sui blockchain.

<mark style="color:yellow;">add\_migrator\_witness -</mark> whitelists a migrator witness for a specific configuration.

```rust
public fun add_migrator_witness<ConfigWitness, MigratorWitness>(
    self: &mut MemezConfig,
    _: &AdminWitness<MEMEZ>,
    _: &mut TxContext,
)
```

**Arguments:**

* **`self: &mut MemezConfig`**\
  A mutable reference to the Memez global configuration object.\
  This is the config instance being removed.
* **`_: &AdminWitness<MEMEZ>`**\
  An admin witness proving that the caller is an admin.
* **`_ctx: &mut TxContext`**\
  A mutable reference to the transaction context provided by the Sui blockchain.

<mark style="color:yellow;">remove\_migrator\_witness -</mark> removes a migrator witness from the whitelist of a specific configuration.

```rust
public fun remove_migrator_witness<ConfigWitness, MigratorWitness>(
    self: &mut MemezConfig,
    _: &AdminWitness<MEMEZ>,
    _: &mut TxContext,
)
```

**Arguments:**

* **`self: &mut MemezConfig`**\
  A mutable reference to the Memez global configuration object.\
  This is the config instance being removed.
* **`_: &AdminWitness<MEMEZ>`**\
  An admin witness proving that the caller is an admin.
* **`_ctx: &mut TxContext`**\
  A mutable reference to the transaction context provided by the Sui blockchain.


# memez\_pump

<mark style="color:yellow;">new -</mark> creates a new pump pool using the `ConfigKey` settings.

```rust
public fun new<Meme, Quote, ConfigKey, MigrationWitness>(
    config: &MemezConfig,
    meme_treasury_cap: TreasuryCap<Meme>,
    mut creation_fee: Coin<SUI>,
    pump_config: PumpConfig,
    first_purchase: Coin<Quote>,
    metadata: MemezMetadata,
    stake_holders: vector<address>,
    is_protected: bool,
    dev: address,
    allowed_versions: AllowedVersions,
    ctx: &mut TxContext,
): (MemezFun<Pump, Meme, Quote>, MetadataCap)
```

**Arguments:**

* **`config: &MemezConfig`**\
  The Memez [config shared object](https://suiscan.xyz/mainnet/object/0x9c665993f61a902475b083036da75240aa203bb874ebce4031810b589e485a61/tx-blocks).&#x20;
* **`meme_treasury_cap: TreasuryCap<Meme>`**\
  The treasury cap for the meme coin (`memeCoinTreasuryCap`), which represents the authority or capability to mint and manage supply for the meme coin.
* **`mut creation_fee: Coin<SUI>`**\
  The SUI fee used during creation of the pool (`creationSuiFee`). This coin will be consumed as part of the transaction costs.
* **`pump_config: PumpConfig`**\
  Configuration for the pump invariant logic — this may include values like `burnTax`, `virtualLiquidity`, `targetQuoteLiquidity`, and `liquidityProvision`.
* **`first_purchase: Coin<Quote>`**\
  A coin of the quote asset used for the first purchase in the pool (`firstPurchase`).&#x20;
* **`metadata: MemezMetadata`**\
  Arbitrary metadata associated with the meme coin (`metadata`). This may include things like creator address, X, description, and social links.
* **`stake_holders: vector<address>`**\
  A list of addresses representing the stakeholders of the meme coin. These might be early backers, team members, or governance participants. The numebr of stake\_holders depending on the configuration set by the admin.
* **`is_protected: bool`**\
  A flag that indicates whether transactions require backend signatures to process pump operations (`isProtected`). Helps prevent abuse.
* **`dev: address`**\
  The developer’s address (`developer`). This address may be eligible for future fee distributions or administrative rights.
* **`allowed_versions: AllowedVersions`**\
  A witness to ensure that the package version is up to date.
* **`ctx: &mut TxContext`**\
  A mutable reference to the transaction context provided by Sui.

<mark style="color:yellow;">pump -</mark> allows the user to buy meme coins from the pool.

```rust
public fun pump<Meme, Quote>(
    self: &mut MemezFun<Pump, Meme, Quote>,
    quote_coin: Coin<Quote>,
    referrer: Option<address>,
    signature: Option<vector<u8>>,
    min_amount_out: u64,
    allowed_versions: AllowedVersions,
    ctx: &mut TxContext,
): Coin<Meme> 
```

**Arguments:**

* **`self: &mut MemezFun<Pump, Meme, Quote>`**\
  A mutable reference to the `MemezPool` (specifically using the Pump invariant) — this is the pool that facilitates the trade.
* **`quote_coin: Coin<Quote>`**\
  The quote coin provided by the user to be exchanged for meme coin.
* **`referrer: Option<address>`**\
  An optional address of the referrer who may be eligible for referral rewards.
* **`signature: Option<vector<u8>>`**\
  An optional server-provided signature. This is **required** if the pool is marked as protected.
* **`min_amount_out: u64`**\
  The minimum amount of meme coin that the user expects to receive from the trade.\
  This prevents slippage or front-running attacks.
* **`allowed_versions: AllowedVersions`**\
  A witness to ensure that the package version being used is current and authorized.
* **`ctx: &mut TxContext`**\
  A mutable reference to the Sui transaction context.&#x20;

<mark style="color:yellow;">dump -</mark> allows the user to sell meme coins.

```rust
public fun dump<Meme, Quote>(
    self: &mut MemezFun<Pump, Meme, Quote>,
    treasury_cap: &mut IPXTreasuryStandard,
    meme_coin: Coin<Meme>,
    referrer: Option<address>,
    min_amount_out: u64,
    allowed_versions: AllowedVersions,
    ctx: &mut TxContext,
): Coin<Quote>
```

**Arguments:**

* **`self: &mut MemezFun<Pump, Meme, Quote>`**\
  A mutable reference to the MemezPool that uses the Pump invariant — this is the pool from which the meme coin will be sold.
* **`treasury_cap: &mut IPXTreasuryStandard`**\
  A mutable reference to the shared ipx treasury cap, used to authorize burns.
* **`meme_coin: Coin<Meme>`**\
  The meme coin being sold in exchange for quote (e.g., SUI).
* **`referrer: Option<address>`**\
  An optional referrer address to credit for referral rewards.\
  *(Corresponds to `referrer` in the client — can be null.)*
* **`min_amount_out: u64`**\
  The minimum amount of quote coin (e.g., SUI) the user expects to receive in return.\
  Protects against slippage or unfavorable trades.
* **`allowed_versions: AllowedVersions`**\
  A witness object ensuring the transaction uses an allowed and up-to-date package version.
* **`ctx: &mut TxContext`**\
  A mutable reference to the transaction context provided by the Sui blockchain.&#x20;

<mark style="color:yellow;">migrate -</mark> it migrates a pool to a DEX. The functions returns a hot potato that can only be destroyed by using an authorized migration witness.

```rust
public fun migrate<Meme, Quote>(
    self: &mut MemezFun<Pump, Meme, Quote>,
    allowed_versions: AllowedVersions,
    ctx: &mut TxContext,
): MemezMigrator<Meme, Quote>
```

**Arguments:**

* **`self: &mut MemezFun<Pump, Meme, Quote>`**\
  A mutable reference to the Memez pool that uses the Pump invariant — this is the pool being migrated.
* **`allowed_versions: AllowedVersions`**\
  A witness object ensuring the migration call is executed only if the contract package version is valid and up-to-date.
* **`ctx: &mut TxContext`**\
  A mutable reference to the transaction context provided by the Sui blockchain. Required for creating, transferring, and managing objects during migration.

<mark style="color:yellow;">dev\_purchase\_claim -</mark> allows the developer to claim the meme coins bought in the first purchase.

```rust
public fun dev_purchase_claim<Meme, Quote>(
    self: &mut MemezFun<Pump, Meme, Quote>,
    allowed_versions: AllowedVersions,
    ctx: &mut TxContext,
): Coin<Meme>
```

**Arguments:**

* **`self: &mut MemezFun<Pump, Meme, Quote>`**\
  A mutable reference to the Memez pool that uses the Pump invariant — this returns the developer first purchase.
* **`allowed_versions: AllowedVersions`**\
  A witness object ensuring the migration call is executed only if the contract package version is valid and up-to-date.
* **`ctx: &mut TxContext`**\
  A mutable reference to the transaction context provided by the Sui blockchain. Required for creating, transferring, and managing objects during migration.

<mark style="color:yellow;">distribute\_stake\_holders\_allocation -</mark> allows anyone to distribute the meme coin allocations to its respective recipients. It can only be done after a pool has been migrated.

```rust
public fun distribute_stake_holders_allocation<Meme, Quote>(
    self: &mut MemezFun<Pump, Meme, Quote>,
    clock: &Clock,
    allowed_versions: AllowedVersions,
    ctx: &mut TxContext,
)
```

**Arguments:**

* **`self: &mut MemezFun<Pump, Meme, Quote>`**\
  A mutable reference to the Memez pool that uses the Pump invariant — this returns the developer first purchase.
* **`clock: &Clock`**\
  The Clock shared object.
* **`allowed_versions: AllowedVersions`**\
  A witness object ensuring the migration call is executed only if the contract package version is valid and up-to-date.
* **`ctx: &mut TxContext`**\
  A mutable reference to the transaction context provided by the Sui blockchain. Required for creating, transferring, and managing objects during migration.

<mark style="color:yellow;">quote\_pump -</mark> quotes the current exchange rate between quote coin for meme coin.

```rust
public fun quote_pump<Meme, Quote>(
    self: &mut MemezFun<Pump, Meme, Quote>,
    amount_in: u64,
): vector<u64>
```

**Arguments:**

* **`self: &mut MemezFun<Pump, Meme, Quote>`**\
  A mutable reference to the Memez pool that uses the Pump invariant — this is the pool being queried for a pricing quote.
* **`amount_in: u64`**\
  The input trade size of the meme coin, expressed in its smallest unit.\
  Used to calculate how much of the quote asset (e.g., SUI) would be received under the Pump invariant.

<mark style="color:yellow;">quote\_dump -</mark> quotes the current exchange rate between meme coin for the quote coin.

```rust
public fun quote_dump<Meme, Quote>(
    self: &mut MemezFun<Pump, Meme, Quote>,
    amount_in: u64,
): vector<u64>
```

**Arguments:**

* **`self: &mut MemezFun<Pump, Meme, Quote>`**\
  A mutable reference to the Memez pool that uses the Pump invariant — this is the pool being queried for a pricing quote.
* **`amount_in: u64`**\
  The input trade size of the **quote coin** (e.g., SUI), expressed in its smallest unit.\
  Used to calculate how much of the meme coin would be received when “dumping” quote into the pool.


# memez\_fun

<mark style="color:yellow;">destroy -</mark> destroys the Migrator hot potato to get the inner balances.

```rust
public fun destroy<Meme, Quote, Witness: drop>(
    migrator: MemezMigrator<Meme, Quote>,
    _: Witness,
): (address, Balance<Meme>, Balance<Quote>)
```

**Arguments:**

* **`migrator: MemezMigrator<Meme, Quote>`**\
  The migration hot potato representing a Memez pool in its migratable state.\
  Consuming this object finalizes the migration process and allows recovery of the underlying assets.
* **`_: Witness`**\
  A witness type ensuring only the authorized package can invoke `destroy` function.\
  Serves as a compile-time capability check (must have the `drop` ability).

<mark style="color:yellow;">update\_metadata -</mark> replaces the pool metadata.

```rust
public fun update_metadata<Curve, Meme, Quote>(
    self: &mut MemezFun<Curve, Meme, Quote>,
    metadata_cap: &MetadataCap,
    mut metadata: VecMap<String, String>,
)
```

**Arguments:**

* **`self: &mut MemezFun<Curve, Meme, Quote>`**\
  A mutable reference to the Memez pool instance (for any curve type).\
  This is the pool whose metadata will be updated.
* **`metadata_cap: &MetadataCap`**\
  A capability object that authorizes metadata updates.\
  Ensures only accounts with the correct permission can modify the pool’s metadata.
* **`metadata: VecMap<String, String>`**\
  A key–value map of metadata fields (as strings) to attach or update on the pool.\
  Typical entries may include name, symbol, description, or custom fields relevant to frontends or indexers.

<mark style="color:yellow;">metadata -</mark> returns the current pool metadata

```rust
public fun metadata<Curve, Meme, Quote>(
    self: &MemezFun<Curve, Meme, Quote>,
): VecMap<String, String>
```

**Arguments:**

* **`self: &MemezFun<Curve, Meme, Quote>`**\
  An immutable reference to the Memez pool instance (for any curve type).\
  The pool whose metadata will be read.

<mark style="color:yellow;">next\_nonce -</mark> returns the next nonce for the server to create a signature valid for the `user`.

```rust
public fun next_nonce<Curve, Meme, Quote>(self: &MemezFun<Curve, Meme, Quote>, user: address): u64
```

**Arguments:**

* **`self: &MemezFun<Curve, Meme, Quote>`**\
  An immutable reference to the Memez pool instance (for any curve type).\
  The pool from which the nonce will be queried.
* **`user: address`**\
  The address of the user whose next nonce is being requested.\
  It is used to prevent replay attacks and ensure transaction uniqueness for that user in the pool.


# SDK

## Overview

**Typescript SDK to interact with** [**Memez.gg**](https://www.memez.gg/) **contracts.**&#x20;

## Installation

**The sdk is available on the** [**NPM registry.**](https://www.npmjs.com/package/@interest-protocol/memez-fun-sdk)

```sh
npm i @interest-protocol/memez-fun-sdk
```

## SDK

**How to setup the SDK.**

```typescript
import { MemezPumpSDK } from '@interest-protocol/memez-fun-sdk';

/**
* Initiates the MemezPump SDK.
*
* @param args - An object containing the necessary arguments to initialize the SDK.
* @param args.fullNodeUrl - The full node URL to use for the SDK.
* @param args.packages - The package addresses to use for the SDK.
* @param args.sharedObjects - A record of shared objects to use for the SDK.
* @param args.network - The network to use for the SDK. Either `mainnet` or `testnet`.
*/
const memezPumpSdk = new MemezPumpSDK();
```


# Pump API

### <mark style="color:yellow;">Constructor</mark>

Allows the SDK to be initiated with custom data.

* [Example](https://github.com/interest-protocol/sdk-monorepo/blob/main/scripts/memez-fun/utils.script.ts#L37)
* [Pump SDK Implementation ](https://github.com/interest-protocol/sdk-monorepo/blob/main/packages/memez-fun-sdk/src/pump.ts#L54)

#### How to use:

```typescript
import { getFullnodeUrl } from '@mysten/sui/client';
import {
  MemezPumpSDK,
  Network,
} from '@interest-protocol/memez-fun-sdk';

const payload = {
  network: Network.MAINNET,
  fullNodeUrl: getFullnodeUrl(Network.MAINNET),
};

const memezPump = new MemezPumpSDK(payload);
```

#### Arguments

* <mark style="color:yellow;">**fullNodeUrl {string} -**</mark> Url to initiate the Sui Client RPC.
* <mark style="color:yellow;">**network {Enum} -**</mark> [Enum denoting if its mainnet or testnet](https://github.com/interest-protocol/memez.gg-sdk/blob/main/src/memez/memez.types.ts#L18)

### <mark style="color:yellow;">newPumpPool</mark>

Creates a pool using the Pump invariant.&#x20;

* [Example](https://github.com/interest-protocol/memez.gg-sdk/blob/main/src/scripts/memez/pump/new.ts)
* [Implementation](https://github.com/interest-protocol/sdk-monorepo/blob/main/packages/memez-fun-sdk/src/pump.ts#L83)

#### How to use:

```typescript
  const recipient = keypair.toSuiAddress();

  const tx = new Transaction();

  const [creationSuiFee, firstPurchase] = tx.splitCoins(tx.gas, [
    tx.pure.u64(30_000_000n),
    tx.pure.u64(1_000_000_000n),
  ]);

  const { metadataCap } = await memezPumpTestnet.newPool({
    tx,
    configurationKey,
    metadata: {
      X: 'https://x.com/Meme',
      Website: 'https://meme.xyz/',
      GitHub: 'https://github.com/meme',
      videoUrl: 'https://memez.gg',
    },
    creationSuiFee,
    memeCoinTreasuryCap: TREASURY_CAP,
    firstPurchase,
    developer: recipient,
    migrationWitness: MIGRATOR_WITNESSES.testnet.TEST,
    totalSupply: TOTAL_SUPPLY,
    quoteCoinType: SUI_TYPE_ARG,
  });
  tx.transferObjects([metadataCap], tx.pure.address(recipient));

  await executeTx(tx);
```

#### Arguments

* <mark style="color:yellow;">**tx {object} -**</mark> Sui client Transaction class to chain move calls.
* <mark style="color:yellow;">**creationSuiFee {object} -**</mark> The Sui fee to create a MemezPool.
* <mark style="color:yellow;">**memeCoinTreasuryCap {string} -**</mark> The meme coin treasury cap.
* <mark style="color:yellow;">**totalSupply {string | number | bigint} -**</mark> The total supply of the meme coin.
* <mark style="color:yellow;">**isProtected {boolean} -**</mark> Whether to use pool requires a server signature authorization for users to buy coins.
* <mark style="color:yellow;">**developer {string} -**</mark> The address that can claim the dev meme coin purchase and collect post bonding fees on Bluefin.&#x20;
* <mark style="color:yellow;">**firstPurchase {object} -**</mark> A Sui coin object to place the first meme coin purchase.
* <mark style="color:yellow;">**metadata {object} -**</mark> A record of the social metadata of the meme coin.
* <mark style="color:yellow;">**configurationKey {string} -**</mark> The configuration key to use for the MemezPool.
* <mark style="color:yellow;">**migrationWitness {string} -**</mark> The migration witness to use for the MemezPool.
* <mark style="color:yellow;">**stakeholders {string\[]} -**</mark> The addresses of the stakeholders. It can be empty or undefined.
* <mark style="color:yellow;">**quoteCoinType {string} -**</mark> The quote coin type to use for the MemezPool.
* <mark style="color:yellow;">**burnTax {number} -**</mark> The amount of meme coin that will be burnt during sales in basis points.
* <mark style="color:yellow;">**virtualLiquidity {string | number | bigint} -**</mark> The initial virtual liquidity in the pool.
* <mark style="color:yellow;">**targetQuoteLiquidity {string | number | bigint} -**</mark> The amount of Sui the pool needs to collect to migrate the coin.
* <mark style="color:yellow;">**liquidityProvision {number} -**</mark> The percentage of meme coin that will be added as liquidity after migration. It is expressed in basis points.

#### Return

* <mark style="color:yellow;">**tx {object} -**</mark> Sui client Transaction class to chain move calls.
* <mark style="color:yellow;">**metadataCap {object} -**</mark> The metadata object.
  * [Check out the IPX Treasury standard](/overview/sui/ipx-coin-standard)

### <mark style="color:yellow;">pump</mark>

Swaps quote coin for a meme coin in a pool.&#x20;

* [Example](https://github.com/interest-protocol/sdk-monorepo/blob/main/scripts/memez-fun/pump/pump.ts)
* [Implementation](https://github.com/interest-protocol/sdk-monorepo/blob/main/packages/memez-fun-sdk/src/pump.ts#L535)

#### How to use

```typescript
import { coinWithBalance, Transaction } from '@mysten/sui/transactions';

import { getEnv } from '../utils.script';

(async () => {
  const tx = new Transaction();

  const { pumpSdk, executeTx, testnetPoolId, keypair } = await getEnv();

  const quoteCoin = coinWithBalance({
    balance: 100,
    type: '0x2::sui::SUI',
  });

  const { memeCoin, tx: tx2 } = await pumpSdk.pump({
    pool: testnetPoolId,
    quoteCoin,
    tx,
  });

  tx2.transferObjects([memeCoin], keypair.toSuiAddress());

  await executeTx(tx2);
})();
```

#### Arguments

* <mark style="color:yellow;">**tx {object} -**</mark> Sui client Transaction class to chain move calls.
* <mark style="color:yellow;">**pool {string | object} -**</mark> The objectId of the MemezPool or the full parsed pool.
* <mark style="color:yellow;">**quoteCoin {object} -**</mark> The quote coin to sell for the meme coin.
* <mark style="color:yellow;">**referrer {string | null} -**</mark> The address of the referrer.
* <mark style="color:yellow;">**signature {string | null} -**</mark> The server signature. It is required for protected pools.
* <mark style="color:yellow;">**minAmountOut {string | number | bigint} -**</mark> The minimum amount of meme coin expected to be received.

#### Return

* <mark style="color:yellow;">**tx {object} -**</mark> Sui client Transaction class to chain move calls.
* <mark style="color:yellow;">**memeCoin {object} -**</mark> The meme coin bought.

### <mark style="color:yellow;">dump</mark>

Swaps meme coin for quote coin in a pool.&#x20;

* [Example](https://github.com/interest-protocol/sdk-monorepo/blob/main/scripts/memez-fun/pump/dump.ts)
* [Implementation](https://github.com/interest-protocol/sdk-monorepo/blob/main/packages/memez-fun-sdk/src/pump.ts#L603)

#### How to use

```typescript
import { coinWithBalance, Transaction } from '@mysten/sui/transactions';

import { getEnv } from '../utils.script';

(async () => {
  const tx = new Transaction();

  const { pumpSdk, executeTx, testnetPoolId, keypair } = await getEnv();

  const pool = await pumpSdk.getPumpPool(testnetPoolId);

  const memeCoin = coinWithBalance({
    balance: 100n,
    type: pool.memeCoinType,
  })(tx);

  const { quoteCoin, tx: tx2 } = await pumpSdk.dump({
    pool: testnetPoolId,
    memeCoin,
    tx,
    referrer:
      '0x894261575b948c035d002adc3ca4d73c683c01a1bfafac183870940bf9afef1a',
  });

  tx2.transferObjects([quoteCoin], keypair.toSuiAddress());

  await executeTx(tx2);
})();
```

#### Arguments

* <mark style="color:yellow;">**tx {object} -**</mark> Sui client Transaction class to chain move calls.
* <mark style="color:yellow;">**pool {string | object} -**</mark> The objectId of the MemezPool or the full parsed pool.
* <mark style="color:yellow;">**memeCoin {object} -**</mark> The meme coin to sell for Sui coin.
* <mark style="color:yellow;">**referrer {string | null} -**</mark> The address of the referrer.
* <mark style="color:yellow;">**minAmountOut {string | number | bigint} -**</mark> The minimum amount of sui coin expected to be received.

#### Return

* <mark style="color:yellow;">**tx {object} -**</mark> Sui client Transaction class to chain move calls.
* <mark style="color:yellow;">**quoteCoin {object} -**</mark> The Quote coin bought.

### <mark style="color:yellow;">devClaim</mark>

Allows the developer to claim the first purchased coins. It can only be done after the pool migrates.

* [Example](https://github.com/interest-protocol/sdk-monorepo/blob/main/scripts/memez-fun/pump/dev-claim.ts)
* [Implementation](https://github.com/interest-protocol/sdk-monorepo/blob/main/packages/memez-fun-sdk/src/pump.ts#L661)

#### How to use

```typescript
const { memeCoin, tx } = await memezTestnet.devClaim({
  pool: POOL_ID,
});

tx.transferObjects([memeCoin], keypair.toSuiAddress());

await executeTx(tx);
```

#### Arguments

* <mark style="color:yellow;">**tx {object} -**</mark> Sui client Transaction class to chain move calls.
* <mark style="color:yellow;">**pool {string | object} -**</mark> The objectId of the MemezPool or the full parsed pool.

#### Return

* <mark style="color:yellow;">**tx {object} -**</mark> Sui client Transaction class to chain move calls.
* <mark style="color:yellow;">**memeCoin {object} -**</mark> The meme coin bought by the developer during deployment.

### <mark style="color:yellow;">migrate</mark>

Migrates the pool to DEX based on the MigrationWitness.

* [Example](https://github.com/interest-protocol/sdk-monorepo/blob/main/scripts/memez-fun/xpump-migrator/migrate.ts)
* [Implementation](https://github.com/interest-protocol/sdk-monorepo/blob/main/packages/memez-fun-sdk/src/pump.ts#L695)

{% hint style="warning" %}
The migrator is a hot potato that needs to be consumed. Please use the [Migrator SDK](https://github.com/interest-protocol/memez.gg-sdk/blob/main/src/memez/migrator.ts) to consume and migrate to a DEX.&#x20;
{% endhint %}

#### How to use

```typescript
const { tx, migrator } = await pumpSdk.migrate({
  pool: testnetPoolId,
});

const fee = tx.splitCoins(tx.gas, [0n]);

const { tx: tx2, suiCoin } = await xPumpMigratorSdk.migrate({
  tx,
  migrator,
  memeCoinType: pool.memeCoinType,
  feeCoinType: SUI_TYPE_ARG,
  feeCoin: fee,
  ipxMemeCoinTreasury: pool.ipxMemeCoinTreasury,
  quoteCoinType: pool.quoteCoinType,
});

tx2.transferObjects([suiCoin], keypair.toSuiAddress());

await executeTx(tx2);
```

#### Arguments

* <mark style="color:yellow;">**tx {object} -**</mark> Sui client Transaction class to chain move calls.
* <mark style="color:yellow;">**pool {string | object} -**</mark> The objectId of the MemezPool or the full parsed pool.

#### Return

* <mark style="color:yellow;">**tx {object} -**</mark> Sui client Transaction class to chain move calls.
* <mark style="color:yellow;">**migrator {object} -**</mark> The hot potato migrator containing the balances.

### <mark style="color:yellow;">quotePump</mark>

Quotes the amount of meme coin received after selling the quote coin.

* [Example](https://github.com/interest-protocol/sdk-monorepo/blob/main/scripts/memez-fun/pump/quote-pump.ts)
* [Implementation](https://github.com/interest-protocol/sdk-monorepo/blob/main/packages/memez-fun-sdk/src/pump.ts#L769)

#### How to use

```typescript
const { memeAmountOut, quoteFee, memeFee } = await memezPumpSdk.quotePump({
  pool: POOL_ID,
  amount: 15n * POW_9,
});
```

#### Arguments

* <mark style="color:yellow;">**pool {string | object} -**</mark> The objectId of the MemezPool or the full parsed pool.
* <mark style="color:yellow;">**amount {string | number | bigint} -**</mark> The amount of Sui being sold.

#### Return

* <mark style="color:yellow;">**memeAmountOut {bigint} -**</mark> The amount of meme coin that will be received.
* <mark style="color:yellow;">**quoteFee {bigint} -**</mark> The swap fee paid in the Quote coin.
* <mark style="color:yellow;">**memeFee {bigint} -**</mark> The swap fee paid in Meme coin.

### <mark style="color:yellow;">quoteDump</mark>

Quotes the amount of quote coin received after selling the meme coin.

* [Example](https://github.com/interest-protocol/memez.gg-sdk/blob/main/src/scripts/memez/pump/quote-dump.ts)
* [Implementation](https://github.com/interest-protocol/memez.gg-sdk/blob/main/src/memez/pump.ts#L540)

#### How to use

```typescript
import { memezTestnet, POW_9, TEST_POOL_ID } from '../utils.script';


const { amountOut, quoteFee, memeFee, burnFee } = await memezPumpTestnet.quoteDump({
  pool: TEST_POOL_ID,
  amount: 1_500_000n * POW_9,
});
```

#### Arguments

* <mark style="color:yellow;">**pool {string | object} -**</mark> The objectId of the MemezPool or the full parsed pool.
* <mark style="color:yellow;">**amount {string | number | bigint} -**</mark> The amount of Meme coin being sold.

#### Return

* <mark style="color:yellow;">**quoteAmountOut {bigint} -**</mark> The amount of quote coin that will be received.
* <mark style="color:yellow;">**quoteFee {bigint} -**</mark> The swap fee paid in the Quote coin.
* <mark style="color:yellow;">**memeFee {bigint} -**</mark> The swap fee paid in Meme coin.
* <mark style="color:yellow;">**burnFee {bigint} -**</mark> Burn fee in meme coin.

### <mark style="color:yellow;">getPumpData</mark>

Returns the Pump configuration for a specific integrator using a configuration key.

* [Example](https://github.com/interest-protocol/memez.gg-sdk/blob/main/src/scripts/config/get-pump-data.ts)
* [Implementation](https://github.com/interest-protocol/memez.gg-sdk/blob/main/src/memez/pump.ts#L631)

#### How to use

```typescript
import { CONFIG_KEYS } from '../../memez';
import { log, memezTestnet } from '../utils.script';


const pumpData = await memezPumpTestnet.getPumpData({
    configurationKey: CONFIG_KEYS.testnet.DEFAULT,
    totalSupply: 1e9 * 1e9,
    quoteCoinType: QUOTE_COIN_TYPE
 });
```

#### Arguments

* <mark style="color:yellow;">**configurationKey {string} -**</mark> The struct tag of a configuration key. E.g. package::module::Key
* <mark style="color:yellow;">**totalSupply {string | bigint | number} -**</mark> The total supply of the meme coin. E.g. 1 Sui would be 1e9.
* <mark style="color:yellow;">**quoteCoin {string} -**</mark> The total supply of the meme coin. E.g. 1 Sui would be 1e9.

#### Return

* <mark style="color:yellow;">**burnTax -**</mark> The tax value of the burner in bps.
* <mark style="color:yellow;">**virtualLiquidity -**</mark> The starting virtual liquidity in the pool in Sui.
* <mark style="color:yellow;">**targetQuoteLiquidity -**</mark> The amount of quote required for the pool to migrate.
* <mark style="color:yellow;">**liquidityProvision -**</mark> The amount of Meme coin that will be supplied to a DEX after migration.


# Interfaces

## <mark style="color:yellow;">MemezPool</mark>

**It represents a Memez Pool.**

```typescript
export interface MemezPool<T> {
  objectId: string;
  poolType: string;
  curveType: string;
  memeCoinType: string;
  quoteCoinType: string;
  publicKey: string | null;
  ipxMemeCoinTreasury: string;
  metadata: Record<string, string>;
  migrationWitness: string;
  progress: string;
  stateId: string;
  developer: string;
  curveState: T;
}
```

* <mark style="color:yellow;">**objectId:**</mark> The Sui Object id of this pool.
* <mark style="color:yellow;">**poolType:**</mark> The struct tag of the pool.
* <mark style="color:yellow;">**curveType:**</mark> It denotes the possible variants of the pool. E.g. Stable, Auction and Pump.
* <mark style="color:yellow;">**memeCoinType:**</mark> The struct tag of the Meme coin.
* <mark style="color:yellow;">**quoteCoinType:**</mark> The struct tag of the Quote coin.
* <mark style="color:yellow;">**publicKey:**</mark> Protected pools have a public key to verify agaisnt the signatures submitted via pump function.
* <mark style="color:yellow;">**ipxMemeCoinTreasury:**</mark> The id of the Meme coin Treasury.
  * [Check out the IPX Treasury standard](/overview/sui/ipx-coin-standard)
* <mark style="color:yellow;">**metadata:**</mark> A map of the meme coin metadata.
* <mark style="color:yellow;">**migrationWitness**</mark>**:** The struct tag of the migrator witness. It shows to which DEX the pool is going to migrate to.
* <mark style="color:yellow;">**progress:**</mark> The current status of the pool. E.g. Bonding, Migrating or Migrated.
* <mark style="color:yellow;">**stateId:**</mark> The id of of the state object to fetch the inner state.
* <mark style="color:yellow;">**developer:**</mark> The address of the user that can claim dev first purchase and earn post bonding fees.
* <mark style="color:yellow;">**curveState:**</mark> The inner state related to the variant.

## <mark style="color:yellow;">PumpState</mark>

**Represents the state of the Pump Pool that will be saved in the property curveState in the Memez Pool.**

```typescript
export interface PumpState {
  devPurchase: bigint;
  liquidityProvision: bigint;
  migrationFee: number;
  virtualLiquidity: bigint;
  targetQuoteLiquidity: bigint;
  quoteBalance: bigint;
  memeBalance: bigint;
  burnTax: number;
  memeSwapFee: number;
  quoteSwapFee: number;
  allocation: Allocation;
  memeReferrerFee: number;
  quoteReferrerFee: number;
}
```

* <mark style="color:yellow;">**devPurchase:**</mark> The coins bought by the developer.
* <mark style="color:yellow;">**liquidityProvision:**</mark> The amount of meme coin that will be added liquidity.
* <mark style="color:yellow;">**migrationFee:**</mark> The payment in Sui that will be charged during migration.
* <mark style="color:yellow;">**virtualLiquidity:**</mark> The virtual Sui liquidity to set a floor price.
* <mark style="color:yellow;">**targetQuoteLiquidity:**</mark> The amount of Quote coin required to migrate.
* <mark style="color:yellow;">**quoteBalance:**</mark> The current amount of Quote coin in the pool.
* <mark style="color:yellow;">**memeBalance:**</mark> The amount of meme coin in the pool.
* <mark style="color:yellow;">**burnTax:**</mark> The burn tax percentage in bps.
* <mark style="color:yellow;">**memeSwapFee:**</mark> The meme coin swap fee percentage in bps.
* <mark style="color:yellow;">**quoteSwapFee:**</mark> The Quote coin swap fee percentage in bps.
* <mark style="color:yellow;">**memeReferrerFee:**</mark> The meme coin referral fee percentage in bps.
* <mark style="color:yellow;">**quoteReferrerFee:**</mark> The Quote coin referral fee percentage in bps
* <mark style="color:yellow;">**allocation:**</mark> Balance of meme coins to be sent o stake holders after migration.

## <mark style="color:yellow;">Network</mark>

**An enum referring to the current network being used.**

```typescript
export enum Network {
  Mainnet = 'mainnet',
  Testnet = 'testnet',
}
```

* <mark style="color:yellow;">**Mainnet:**</mark> Sui Network main net
* <mark style="color:yellow;">**Testnet:**</mark> Sui Network test net.

## <mark style="color:yellow;">Packages</mark>

**An object containing the packages to interact with Memez.**

{% hint style="warning" %}
Testnet packages are out of date. Please use mainnet packages only!
{% endhint %}

```typescript
export const PACKAGES = {
  [Network.TESTNET]: {
    MEMEZ_FUN: {
      original: normalizeSuiAddress(
        '0xcad2e05e9771c6b1aad35d4f3df42094d5d49effc2a839e34f37ae31dc373fe7'
      ),
      latest: normalizeSuiAddress(
        '0xcad2e05e9771c6b1aad35d4f3df42094d5d49effc2a839e34f37ae31dc373fe7'
      ),
    },
    MEMEZ: {
      original: normalizeSuiAddress(
        '0x17209c541f1a372b811a42eaf95e62cd1eb46127e438f052432bd1c2318bc1c9'
      ),
      latest: normalizeSuiAddress(
        '0x17209c541f1a372b811a42eaf95e62cd1eb46127e438f052432bd1c2318bc1c9'
      ),
    },
    VESTING: {
      original: normalizeSuiAddress(
        '0xbc838799ce0c571fddb5c650adae05ed141070501558743f2f28d2d3fbede8d6'
      ),
      latest: normalizeSuiAddress(
        '0xbc838799ce0c571fddb5c650adae05ed141070501558743f2f28d2d3fbede8d6'
      ),
    },
    TEST_MEMEZ_MIGRATOR: {
      original: normalizeSuiAddress(
        '0x1e15037693e28af09771953ec8179d104fff7a225e5a5d1a65034a3636451026'
      ),
      latest: normalizeSuiAddress(
        '0x1e15037693e28af09771953ec8179d104fff7a225e5a5d1a65034a3636451026'
      ),
    },
    MEMEZ_WITNESS: {
      original: normalizeSuiAddress(
        '0x6083aeb2d22514d0e849fdde75b60c7d0f857facefb3b2d7d2e975b78d8a0c75'
      ),
      latest: normalizeSuiAddress(
        '0x6083aeb2d22514d0e849fdde75b60c7d0f857facefb3b2d7d2e975b78d8a0c75'
      ),
    },
    INTEREST_ACL: {
      original: normalizeSuiAddress(
        '0x32ffaa298a6d6528864bf2b32acfcb7976a95e26dcc24e40e2535c0551b9d68a'
      ),
      latest: normalizeSuiAddress(
        '0x32ffaa298a6d6528864bf2b32acfcb7976a95e26dcc24e40e2535c0551b9d68a'
      ),
    },
    XPUMP_MIGRATOR: {
      original: normalizeSuiAddress('0x0'),
      latest: normalizeSuiAddress('0x0'),
    },
    WALLET: {
      original: normalizeSuiAddress('0x0'),
      latest: normalizeSuiAddress('0x0'),
    },
    ROUTER: {
      original: normalizeSuiAddress('0x0'),
      latest: normalizeSuiAddress('0x0'),
    },
    IPX_COIN_STANDARD: {
      original: normalizeSuiAddress('0x0'),
      latest: normalizeSuiAddress('0x0'),
    },
  },
  [Network.MAINNET]: {
    MEMEZ_FUN: {
      original: normalizeSuiAddress(
        '0x779829966a2e8642c310bed79e6ba603e5acd3c31b25d7d4511e2c9303d6e3ef'
      ),
      latest: normalizeSuiAddress(
        '0x7e6aa6e179466ab2814425a780b122575296d011119fa69d27f289f5a28814bd'
      ),
    },
    MEMEZ: {
      original: normalizeSuiAddress(
        '0x6101835e1df12852440c3ad3f079130e31702fe201eb1e3b77d141a0c6a58539'
      ),
      latest: normalizeSuiAddress(
        '0x6101835e1df12852440c3ad3f079130e31702fe201eb1e3b77d141a0c6a58539'
      ),
    },
    VESTING: {
      original: normalizeSuiAddress(
        '0x1a184ecf7d0652f8f1285a3b0b2e644bf86ae1742317fcdaa9b11a7f3a30bd70'
      ),
      latest: normalizeSuiAddress(
        '0x1a184ecf7d0652f8f1285a3b0b2e644bf86ae1742317fcdaa9b11a7f3a30bd70'
      ),
    },
    TEST_MEMEZ_MIGRATOR: {
      original: normalizeSuiAddress(
        '0x4078fe9f8e60191b1ec85d4092b4ec070736dd7c4a3b0c69b1f121c4c6aee910'
      ),
      latest: normalizeSuiAddress(
        '0x4078fe9f8e60191b1ec85d4092b4ec070736dd7c4a3b0c69b1f121c4c6aee910'
      ),
    },
    MEMEZ_WITNESS: {
      original: normalizeSuiAddress(
        '0x6e38cc853e404376b1dc969178aee2c81799cf23af7171e74e492f6786db1cbe'
      ),
      latest: normalizeSuiAddress(
        '0x6e38cc853e404376b1dc969178aee2c81799cf23af7171e74e492f6786db1cbe'
      ),
    },
    INTEREST_ACL: {
      original: normalizeSuiAddress(
        '0xb877fe150db8e9af55c399b4e49ba8afe658bd05317cb378c940344851125e9a'
      ),
      latest: normalizeSuiAddress(
        '0xb877fe150db8e9af55c399b4e49ba8afe658bd05317cb378c940344851125e9a'
      ),
    },
    XPUMP_MIGRATOR: {
      original: normalizeSuiAddress(
        '0x7ec68f4115dc2944426239b13ce6804dd9971b24069fb4efe88360d29b17f0ce'
      ),
      latest: normalizeSuiAddress(
        '0xd4fd7ef75d33f92be5bd11f8cbd06cd15b8df68c6f5016fac6700808de0ff76e'
      ),
    },
    WALLET: {
      original: normalizeSuiAddress(
        '0x21700f31d563949214e0411f22a3cf64928f6a3e5b3c13f830a30d6884fe135b'
      ),
      latest: normalizeSuiAddress(
        '0x21700f31d563949214e0411f22a3cf64928f6a3e5b3c13f830a30d6884fe135b'
      ),
    },
    ROUTER: {
      original: normalizeSuiAddress(
        '0x07cb654d8ae22bd18fff08f322d99fdf9d1673712812329b127430b155dc44ff'
      ),
      latest: normalizeSuiAddress(
        '0x07cb654d8ae22bd18fff08f322d99fdf9d1673712812329b127430b155dc44ff'
      ),
    },
    IPX_COIN_STANDARD: {
      original: normalizeSuiAddress(
        '0xa204bd0d48d49fc7b8b05c8ef3f3ae63d1b22d157526a88b91391b41e6053157'
      ),
      latest: normalizeSuiAddress(
        '0xa204bd0d48d49fc7b8b05c8ef3f3ae63d1b22d157526a88b91391b41e6053157'
      ),
    },
  },
} as const;
```

* <mark style="color:yellow;">**MEMEZ\_FUN:**</mark> The address of the Memez launchpad package.
* <mark style="color:yellow;">**MEMEZ:**</mark> The address of the OTW Memez package.
* <mark style="color:yellow;">**INTEREST\_ACL:**</mark> The package of the Memez admin package.
* <mark style="color:yellow;">**VESTING:**</mark> The package of the vesting package of Memez package.
* <mark style="color:yellow;">**MEMEZ\_MIGRATOR:**</mark> The package of the migrator.&#x20;
* <mark style="color:yellow;">**MEMEZ\_WITNESS:**</mark> A package containing the configuration witnesses.
* <mark style="color:yellow;">**XPUMP\_MIGRATOR:**</mark> The Blast.fun migrator package.
* <mark style="color:yellow;">**WALLET:**</mark> The Memez wallet package to avoid bricking wallets.
* <mark style="color:yellow;">**ROUTER:**</mark> The Memez router package that creates wallets for referrers when buying and selling.
* <mark style="color:yellow;">**IPX\_COIN\_STANDARD:**</mark> The IPX coin standard that allowed protected access to update coin metadata and supply.

## <mark style="color:yellow;">Shared Objects</mark>

**An object containing the shared objects to interact with Memez. Each object has a mutable and immutable reference for optimization purposes.**

```typescript
export const SHARED_OBJECTS = {
  [Network.TESTNET]: {
    ACL: ({ mutable }: { mutable: boolean }) => ({
      objectId: normalizeSuiObjectId(
        '0xc8502b2e13ce57165218abaacd36850c7ea70a5ef4c0b80053eb0f6aaf1d338e'
      ),
      initialSharedVersion: '395367236',
      mutable,
    }),
    VERSION: ({ mutable }: { mutable: boolean }) => ({
      objectId: normalizeSuiObjectId(
        '0x4662e671861a4cb72ee0fe03193e3dd62645465f7cc61ce13422c8384bc8af46'
      ),
      initialSharedVersion: '395367301',
      mutable,
    }),
    CONFIG: ({ mutable }: { mutable: boolean }) => ({
      objectId: normalizeSuiObjectId(
        '0x0c8812c7ab6ae0a900a015c7db0048b20dad072c10faaef4759610a7ada97a73'
      ),
      initialSharedVersion: '395367301',
      mutable,
    }),
    XPUMP_MIGRATOR_CONFIG: ({ mutable }: { mutable: boolean }) => ({
      objectId: normalizeSuiObjectId('0x0'),
      initialSharedVersion: '0',
      mutable,
    }),
    WALLET_REGISTRY: ({ mutable }: { mutable: boolean }) => ({
      objectId: normalizeSuiObjectId('0x0'),
      initialSharedVersion: '0',
      mutable,
    }),
  },
  [Network.MAINNET]: {
    ACL: ({ mutable }: { mutable: boolean }) => ({
      objectId: normalizeSuiObjectId(
        '0x091bd217c6030076a8a97673e3b9f74e0f48bc3035dcb5d5daaf50a8a2d40b7f'
      ),
      initialSharedVersion: '549909164',
      mutable,
    }),
    VERSION: ({ mutable }: { mutable: boolean }) => ({
      objectId: normalizeSuiObjectId(
        '0x2319e3e76dfad73d8f4684bdbf42be4f32d8ce4521dd61becc8261dc918d82c0'
      ),
      initialSharedVersion: '597477043',
      mutable,
    }),
    CONFIG: ({ mutable }: { mutable: boolean }) => ({
      objectId: normalizeSuiObjectId(
        '0x9c665993f61a902475b083036da75240aa203bb874ebce4031810b589e485a61'
      ),
      initialSharedVersion: '597477043',
      mutable,
    }),
    XPUMP_MIGRATOR_CONFIG: ({ mutable }: { mutable: boolean }) => ({
      objectId: normalizeSuiObjectId(
        '0x6ac620306c77e9fb452123b8832b56cb4ec7f9bb638e42d3c6eeecdf173a9498'
      ),
      initialSharedVersion: '603610952',
      mutable,
    }),
    WALLET_REGISTRY: ({ mutable }: { mutable: boolean }) => ({
      objectId: normalizeSuiObjectId(
        '0xc6ed6d218aff361ed293ba3eaf2805772275c9dc87f650a0f8df9c80471c5fbe'
      ),
      initialSharedVersion: '611022341',
      mutable,
    }),
  },
} as const;
```

* <mark style="color:yellow;">**ACL:**</mark> Shared object holding the current whitelisted admins.
* <mark style="color:yellow;">**VERSION:**</mark> Shared object containing the latest version of the package.
* <mark style="color:yellow;">**CONFIG:**</mark> Shared object contain all different configurations:
  * Fees
  * Migration Witnesses
  * Quote coins
  * Public Key
  * Pump State
  * Stable State
  * Auction State
* <mark style="color:yellow;">**XPUMP\_MIGRATOR\_CONFIG:**</mark> The Blast.fun migrator configuration shared object.
* <mark style="color:yellow;">**WALLET\_REGISTRY:**</mark> The Memez wallet shared object. It ensures, there is only one wallet per address.

## <mark style="color:yellow;">Config Keys</mark>

**The configuration supports various values per integrator. For example the fees for Recrd and Default keys will have different values. This is set by the admin.**

```typescript
export const CONFIG_KEYS = {
  [Network.Mainnet]: {
    MEMEZ: '',
    XPUMP: ''
  },
  [Network.Testnet]: {
    MEMEZ: `${PACKAGES[Network.MAINNET].MEMEZ_WITNESS.original}::memez_witness::Memez`,
    XPUMP:
      '0x5afcb4c691bd3af2eb5de4c416b2ed501e843e81209f83ce6928bc3a10d0205c::xpump::ConfigKey',
  },
} as const;
```

* <mark style="color:yellow;">**MEMEZ:**</mark> This is the memez configuration.
* <mark style="color:yellow;">**XPUMP:**</mark> This is the Blast.fun configuration.

## <mark style="color:yellow;">Migrator Witnesses</mark>

**Record of the current allowed migrators.**

```typescript
export const MIGRATOR_WITNESSES = {
  [Network.TESTNET]: {
    TEST: `${PACKAGES[Network.TESTNET].TEST_MEMEZ_MIGRATOR.original}::dummy::Witness`,
    XPUMP: `${PACKAGES[Network.TESTNET].XPUMP_MIGRATOR.original}::xpump_migrator::Witness`,
  },
  [Network.MAINNET]: {
    TEST: `${PACKAGES[Network.MAINNET].TEST_MEMEZ_MIGRATOR.original}::dummy::Witness`,
    XPUMP: `${PACKAGES[Network.MAINNET].XPUMP_MIGRATOR.original}::xpump_migrator::Witness`,
  },
} as const;
```

* <mark style="color:yellow;">**TEST:**</mark> Currently we have a test migrator that returns the balances for testing purposes.
* <mark style="color:yellow;">**XPUMP:**</mark> The Blast.fun migrator witness.


# Configuration

## Overview

[**Memez.gg**](https://www.memez.gg/) is <mark style="color:yellow;">**highly configurable to facilitate third party integrations and revenue sharing**</mark><mark style="color:yellow;">.</mark>

&#x20;Integrators can configure the following parameters:

* **Fees**
* **Migrator**
* **Public Key**

During creation, the deployer can choose which configuration the pool will adhere to. E.g., user A could opt for the Memez configuration, while user B opts for Blast.fun configuration.

{% hint style="info" %}
Integrators need to request our team to add their configuration.&#x20;
{% endhint %}

### <mark style="color:yellow;">Fees</mark>

Memez.fun has 3 fees:

```rust
public enum Fee has copy, drop, store {
    Value(u64, Distributor),
    Percentage(BPS, Distributor),
}

public struct FeePayload has copy, drop, store {
    value: u64,
    percentages: vector<u64>,
    recipients: vector<address>,
}

public struct Allocation<phantom T> has store {
    balance: Balance<T>,
    vesting_periods: vector<u64>,
    distributor: Distributor,
}

public struct MemezFees has copy, drop, store {
    creation: FeePayload,
    meme_swap: FeePayload,
    quote_swap: FeePayload,
    migration: FeePayload,
    allocation: FeePayload,
    vesting_periods: vector<u64>,
    dynamic_stake_holders: u64,
}
```

* <mark style="color:yellow;">**Creation:**</mark> Sui amount charged to create a meme coin + pool.
* <mark style="color:yellow;">**MemeSwap:**</mark> % charged on every sell or buy in meme coin.
* <mark style="color:yellow;">**QuoteSwap:**</mark> % charged on every sell or buy in quote coin.
* <mark style="color:yellow;">**Migration:**</mark> Meme coin % to be used for DEX liquidity after migration.
* <mark style="color:yellow;">**Allocation:**</mark> Meme coin % allocated for the stake holders.
* <mark style="color:yellow;">**Vesting Period:**</mark> The duration of the linear vesting for the allocation.
* <mark style="color:yellow;">**Dynamic Stake Holders:**</mark> The number of stake holders the pool requires during creation.

The integrator can decide the total amount of each fee and the number of recipients per fee. It is **possible to charge no fees at all** and **different percentages and recipients per fee**. The swap and migration fee include the deployer as one of the recipients if chosen by the integrator.

> <mark style="color:yellow;">**For example an integrator can decide to have:**</mark>
>
> * Creation Fee of 2 Sui:
>   * 20% to X
>   * 60% to Y
>   * 20% to Z
> * No Swap fee
> * 10 % Migration quote fee
>   * 50% to A
>   * 50% to B
> * 5% Meme coin allocation to stake holders

### <mark style="color:yellow;">Pump Configuration</mark>

At pool creation the sender configures the values below.

```rust
public struct PumpConfig has copy, drop, store {
    burn_tax: u64,
    virtual_liquidity: u64,
    target_quote_liquidity: u64,
    liquidity_provision: BPS,
    quote_type: TypeName,
}
```

* <mark style="color:yellow;">**Burn Tax:**</mark> The burner tax explained above
* <mark style="color:yellow;">**Virtual Liquidity:**</mark> The floor price of the Meme coin as determined by a virtual Sui amount
* <mark style="color:yellow;">**Target Sui Liquidity:**</mark> The amount of Sui the pool must collect to migrate. It can be seen as a target price.
* <mark style="color:yellow;">**Liquidity Provision:**</mark> Percentage of Meme coin to be used to seed the liquidity pool during migration.
* <mark style="color:yellow;">**Quote Type:**</mark> The type of the quote Coin\<Quote>.

### <mark style="color:yellow;">Burn Tax</mark>

The <mark style="color:yellow;">**Auction and Pump**</mark> strategies have a burn tax built-in. This is a dynamic tax that increases linearly as the amount of Sui in the pool increases. It can range from 0 to 30%.  <mark style="color:yellow;">**This tax is only applied when one sells Meme coins for Sui.**</mark> The coins are actually burnt (not sent to 0x0) as Memez uses the [IPX Coin Standard](/overview/sui/ipx-coin-standard) for all meme coins. This is to prevent king of the hill griefing tactics. As the tax is quite high when it is close to bonding.

```rust
public struct MemezBurner has copy, drop, store {
    fee: BPS,
    target_liquidity: u64,
}
```

* <mark style="color:yellow;">**Fee:**</mark> A percentage in bps to determine how much amount to burn.
* <mark style="color:yellow;">**Target Liquidity:**</mark> The liquidity required t migrate the pool.

**Example**

> <mark style="color:yellow;">**Burner tar Tax Formula**</mark>
>
> progress = current\_liquidity / target\_liquidity
>
> tax = burner\_tax \* progress\
> \ <mark style="color:yellow;">**Example**</mark>
>
> Let's assume we have a pool using the **Pump strategy** with a **Sui Target Amount of 1\_000 Sui** and a **Burner tax of 20%** of 2\_000 basis points.&#x20;
>
> <mark style="color:yellow;">**t0**</mark>: The pool has 0 Sui - burn tax would be 0%
>
> <mark style="color:yellow;">**Math:**</mark>&#x20;
>
> progress = 0 / 1\_000 ⇒ 0
>
> 20% \* 0 / 1000 ⇒ 0%
>
> <mark style="color:yellow;">**t1**</mark>: The pool has 800 Sui - burn tax would be 16%
>
> <mark style="color:yellow;">**Math:**</mark>&#x20;
>
> progress = 800 / 1\_000 ⇒ 80%
>
> 20% \* 80% ⇒ 16%

## Move Dependencies

### Interest BPS

It is an utility library to calculate percentages from values using basis points. It is referred as `BPS`in the code blocks.

### IPX Coin Standard

It is an utility library designed to separate the capabilities of the treasury cap (mint/burn/update) to provide the owner more granular control.

### Interest Math

A math library to safely perform operations.

### Constant Product

A library that calculates the amount in and out of the constant product formula `k = x * y`&#x20;


# Migrators

## XPump

[Implementation](https://github.com/interest-protocol/memez-gg/blob/main/migrators/xpump/sources/xpump.move#L181)

The Blast.fun migrator creates a new pool on Bluefin and adds liquidity. The liquidity position is saved and can later be used by the Admin or developer to claim fees based on the configuration.

```rust
public fun migrate_to_new_pool_v3<Meme, Quote, CoinTypeFee>(
    config: &mut XPumpConfig,
    bluefin_config: &mut GlobalConfig,
    clock: &Clock,
    ipx_treasury: &IPXTreasuryStandard,
    meme_metadata: &CoinMetadata<Meme>,
    quote_metadata: &CoinMetadata<Quote>,
    migrator: MemezMigrator<Meme, Quote>,
    fee: Coin<CoinTypeFee>,
    ctx: &mut TxContext,
): Coin<Quote>
```

The Bluefin pool is initiated with the following parameters:

* <mark style="color:yellow;">**Tick Spacing:**</mark> 200.
* <mark style="color:yellow;">**Initialized Price:**</mark> Dynamically calculated based on the quote and meme coin balances to be added.
* <mark style="color:yellow;">**Tick Lower Index:**</mark> 4294523696
* <mark style="color:yellow;">**Tick Upper Index**</mark>: 443600
  * This is to ensure full range liquidity


# Bonding Curve

The **pump and auction** strategies utilize the [**constant product invariant**](https://www.reddit.com/r/ethereum/comments/55m04x/lets_run_onchain_decentralized_exchanges_the_way/) popularized by UniswapV2. The **stable** strategy utilizes a **fixed rate** to provide a no loss bonding curve.

## Constant Product

$$
k = x \* y
$$

* **k** = constant
* **x** = Reserves of Coin X
* **y** = Reserves of Coin Y

This formula defines the **pricing relationship** between **Coin X** and **Coin Y** in a pool.&#x20;

**Pricing Function**

X’ \* Y’ = K

X’ = X + amountIn

Y’ = Y - amountOut&#x20;

X \* Y = (X + amountIn) \* (Y - amountOut)

XY / (X + amountIn) = Y - amountOut

XY / (X + amountIn) - Y = -amountOut

XY / (X + amountIn) - Y (X + amountIn) / (X + amountIn) = - amountOut

\- Y \*amountIn / (X + amountIn) = - amountOut

We conclude that **amountOut in Y** is defined by

$$
Y \* amountIn / X + amountIn
$$

After every mutation, we ensure that the pool **always maintains the invariant k = x \* y** by using the pricing formula above.&#x20;

## Virtual Liquidity

The use of virtual liquidity to create a floor price for the meme coin brings **two benefits:**

* Allows the token creator to start a market **without supplying any Sui liquidity**&#x20;
* Prevents early buyers from getting too much supply.

Let us assume a pool of **Meme/Sui**. All pools on Memez.Fun use the Meme coin as the base coin and Sui as the quote coin. For example, let's imagine the absence of fees and first buy from the coin creator. If we would set up a pool with 1 billion coins of Meme and 0 Sui, we would break the invariant as `k = 1e9 * 0.`

This means that the **pool would always be worth 0.** To circumvent this issue, UniV2 forces the user to **always supply both coins**: the base coin and the quote coin. This is where virtual liquidity comes in, we can virtually set the pool with a floor price without requiring any investment from the token creator.

For example, We can set the virtual liquidity to be 1,000 Sui. If we assume that Sui is 5 dollars for simplicity sake, this means that at pool creation. The pool would be worth 10 thousand USD:

* 5 Thousand worth of Sui&#x20;
* 5 Thousand worth of Meme&#x20;

Assume we create Meme coin with 1e9 supply. **1 Meme coin** would be worth **0.000001 Sui or \~$0.000005** (assuming Sui is $5).

$$
Price = y / x\MemePrice = Sui Reserve / Meme Reserve
$$

Memez.Fun has a target Sui reserve that once it is achieved, the pool is migrated to a DEX.&#x20;

Let's assume that we want the pool to migrate once the Meme achieves a market cap of **$60,000.**

**Pool at start:**

* **Virtual Liquidity:** 1,000 Sui
* **Sui Reserves:** 0
* **Meme Reserves:** 1e9
* **Target Sui Reserve:** 2,464 Sui
* **Meme Coin price:** 0.000001 Sui
* **Target Meme Coin price:** 0.000012 SUI
* **Pool Value:** $0
* **Pool Virtual Value**: $10,000

Target Meme Coin price explanation:

> $60\_000 / 1e9 Meme coin = $0.00006 per Meme
>
> In Sui: $0.00006/$5 = 0.000012 SUI per Meme
>
> **0.000012 SUI per Meme Coin \* 1e9 Meme Coin = 12,000 Sui \~ ($60,000)**

**How do we come up with a target Sui Reserve of 2,464 Sui?**

* **Target Price** = 0.000012 Sui
* **k = x \* y** = 1e12 (1e9 \* 1000)

> x \* (0.000012x) = 1e12
>
> 0.000012x² = 1e12
>
> x = sqrt(1e12/0.000012) ≈ 288,675,135 Meme tokens
>
> Final y = 1e12/288,675,135 ≈ 3,464 Sui
>
> Sui needed = 3,464 - 1,000 = 2,464 Sui

**Conclusion:** We would need a total of **$12,321** (2,464 Sui) to migrate.

> If we use the pricing formula above, we can see that it holds true:
>
> (1e9 Meme \* 2,464 Sui) / (1,000 Sui + 2,464 Sui) = 711,316,397 Meme
>
> 1e9 - 711,316,397 = 288,683,603

The pool would have **288,683,603 Meme and 3,464 Sui after a 2,464 Sui purchase**. Using the price formula.

> **Price = y / x**
>
> 3,464 Sui  / 288,683,603 Meme \~ 0.000012
>
> 0.000012 \* 1e9 = 12,000 Sui ($60,000)

**Pool at the end:**

* **Virtual Liquidity:** 1,000 Sui
* **Sui Reserves:** 2,464
* **Meme Reserves:** 288,683,603
* **Target Sui Reserve:** 2,464 Sui
* **Meme Coin price:** 0.000012 Sui
* **Target Meme Coin price:** 0.000012 Sui
* **Pool Value:** $12,320
* **Pool Virtual Value**: $17,320


# Fees

Memez.gg has a versatile fee mechanism enforced by the contracts. Each integrator is able to customize their fees parameters.

{% hint style="success" %}
The system supports 0 fees.
{% endhint %}

### <mark style="color:yellow;">Fee Mechanism</mark>

Depending on the fee, it can be defined in basis points percentage or in a nominal value.\
The fees are collected by the stake holders depending on how the configuration is set.

#### <mark style="color:blue;">Fees Configuration</mark>

Each fee below requires the following configuration:

* Fee Value&#x20;
* Address of fee recipients
* Percentage that each recipient should receive in basis points.

&#x20;If we set the **Creation Fee** to 2 Sui and the recipients to be the following: **Alice (20%)**, **Bob (50%)** and **Jose (30%).**&#x20;

At pool creation, the contract will automatically send **0.4 Sui to Alice**, **1 Sui to Bob** and **0.6 Sui to Jose**. The system supports **dynamic fee recipients** at pool creation and **system enforced ones** as well.\
\
For example, we can set that **20% of the creation fee always goes to the integrator**, while the rest of the **fees recipients are set dynamically at pool creation**.

* <mark style="color:blue;">**Creation:**</mark> This fee is collected when a pool is created and it is defined in a nominal value. It is always charged in Sui.&#x20;
* <mark style="color:blue;">**Meme Coin Swap:**</mark> This fee is collected on every swap and is defined in percentage in meme coin.&#x20;
* <mark style="color:blue;">**Quote Coin Swap:**</mark> This fee is collected on every swap and is defined in percentage in quote coin.&#x20;
* <mark style="color:blue;">**Migration:**</mark> This fee is charged in Sui from the liquidity being migrated in percentage.
* <mark style="color:blue;">**Allocation:**</mark> This fee is charged in meme coin after migration in percentage.

The fees configuration can be fetched via the SDK using the following [**method**](https://github.com/interest-protocol/sdk-monorepo/blob/main/packages/memez-fun-sdk/src/sdk.ts#L97)**.**

At pool creation, the caller can pass an [**array of stakeholders (Sui addresses)**](https://github.com/interest-protocol/sdk-monorepo/blob/main/packages/memez-fun-sdk/src/pump.ts#L94) to set dynamic fee recipients. This has to match the number of fees distribution set by the integrator.\
\
For example: if the integrator sets the creation fee to be **2 Sui and have 3 recipients** and **one recipient to always be the system**. The pool creator must pass two additional addresses dynamically.&#x20;

### <mark style="color:yellow;">Blast.fun Configuration</mark>

Blast.fun fees configuration has 4 system addresses that earn **migration and swap fees.**

* <mark style="color:yellow;">**Blast**</mark> 0xef4145dc8710cb56970a56607a1a36da6db655ddaf1991d9f3bc3d859a81cd42

| Creation  | Meme Swap   | Quote Swap | Migration  | Allocation  |
| --------- | ----------- | ---------- | ---------- | ----------- |
| **0 Sui** | &#x30;**%** | 1.2%       | **5%**     | &#x35;**%** |
|           |             | 80% Blast  | 100% Blast | 100% Blast  |
|           |             | 20% Dev    |            |             |

Blast.fun has two owned public addresses:

* <mark style="color:yellow;">**Treasury:**</mark> 0xaab6feadd3236ecc1b4fa34d00356f0f826f5e3d225818cb738ccdf77dcac979
* <mark style="color:yellow;">**Bluefin LP Manager:**</mark> 0x22441936a0d6fd21d07d596813dfa29fbc54d44b94eb87916fbcb51d639fde96


# IPX Coin Standard

An extension to Sui Network's Coin. Coins created via the IPX Coin Standard can be minted, burnt and updated with different capabilities.

## <mark style="color:blue;">Problem</mark>

Coins created via Sui Network Coin have all the rights associated with one capability, the **TreasuryCap**.&#x20;

The holder of the **TreasuryCap can mint, burn and update** the Coi&#x6E;**.** This design is quite limiting because all the rights are associated with a single capability.&#x20;

> What happens if a user wants to ensure that its coin can be burnt but not mintable? He would have to write its own contract.

Most users choose to simply send the **TreasuryCap** to the systems address, the famous 0x0,  because no one has access to it. Therefore it is considered burnt. However, since no one has access to the TreasuryCap, no one can burn the coin nor update its icon, description, symbol or name.\
\
There are cases in which coins need to update its metadata due to a rebrand or broken uris.&#x20;

## <mark style="color:blue;">Solution</mark>

The IPX Coin Standard separates the three rights of the **TreasuryCap** into t**hree separate capabilities: Burn, Mint and Update metadata**. This flexible design means that a user can make his/her coin burnable while preventing coins to be minted forever.&#x20;

* `MintCap` allows the holder to mint coins
* `BurnCap` allows the holder to burn coins
* `MetadataCap` allows the holder to update the coin name, description, icon uri and symbol

{% hint style="info" %}
**The deployer can choose to make the coin burnable by anyone who has coins in his/her wallet.**
{% endhint %}

At deployment the user can choose to make the coin mintable, burnable and/or updateable and decide who has those rights.\
\
The code is open source on [Github](https://github.com/interest-protocol/interest-mvr/tree/main/ipx-coin-standard) and [immutable](https://suiscan.xyz/mainnet/tx/CZ8jqNcpm9aJK8NHP6bvLZruz4Rpq2BT46qZrmkV5q7K). Not even the IPX team can change the standard making it safe to use.

<mark style="color:blue;">**Mainnet Package Address:**</mark> 0xa204bd0d48d49fc7b8b05c8ef3f3ae63d1b22d157526a88b91391b41e6053157\
\ <mark style="color:blue;">**Testnet Package Address:**</mark> 0x3d9d9cf7f37daa21d6439bb4f3e90b49312cc1471e159e0b34ef18a36332ccda

## <mark style="color:blue;">MVR</mark>

IPX Coin standard is available on [Move Registry](https://www.moveregistry.com/package/@interest/coin-standard).

```bash
mvr add @interest/coin-standard --network mainnet
```


# Movement


# Interest Protocol Decentralized Exchange (DEX)

Welcome to **Interest Protocol DEX**, a versatile decentralized exchange built on the **Movement Network**. The platform is designed for seamless trading, advanced liquidity management, and effortless token creation, all while incorporating cutting-edge security features to protect users from common exploits like sandwich attacks.

### **Get Started**

1. **Visit the Platform**: [Interest Protocol DEX](https://www.interest.xyz/)
2. **Swap Tokens**: Trade safely with built-in protections.
3. **Manage Liquidity**: Provide liquidity with ease using dynamic tools.
4. **Create Tokens**: Launch and deploy liquidity pools effortlessly.

***

**Interest Protocol DEX** is your gateway to secure, efficient, and innovative DeFi trading. Dive in today and explore its powerful tools to transform your crypto journey!


# Key Features

### <mark style="color:blue;">**1. Token Swap**</mark>

The **Swap Tool** allows users to exchange tokens directly in a simple and intuitive interface. With built-in protection against sandwich attacks, Interest Protocol ensures users can trade safely without the risk of bots exploiting their transactions.

**Example: How to Swap Tokens**

* Visit [**Interest Protocol DEX**](https://www.interest.xyz/).
* Select the tokens you want to swap (e.g., **MOVE** → **RUCO**).
* Enter the desired amount and confirm the transaction.
* The DEX processes your swap securely with price stability thanks to its **slot windows**, which mitigate sandwich attacks.

**Swap Tutorial**

{% embed url="<https://youtu.be/XfYKLEyZhV8>" %}

This feature ensures smooth transactions, even in volatile markets, with no extra steps required from the user.

***

### <mark style="color:blue;">2.</mark> <mark style="color:blue;"></mark><mark style="color:blue;">**Advanced Liquidity Management**</mark>

Interest Protocol introduces a robust liquidity layer where projects and users can manage pools effortlessly. This feature supports both **passive liquidity provision** and innovative functionalities for liquidity providers (LPs):

* **One-Sided Liquidity**: LPs can provide liquidity with a single token, eliminating the need for equal-value pairs.
* **Dynamic Liquidity Adjustment**: The protocol automatically adjusts liquidity positions, reducing impermanent loss and enhancing fee capture for LPs.
* **Multi-Coin Pools**: Pools can include more than two assets, enabling creative and efficient trading pairs.
* **LpCoins**: Unlike traditional NFTs for liquidity, **LpCoins** are fungible, composable, and easily tradable, enhancing their usability within DeFi ecosystems.

***

### <mark style="color:blue;">3.</mark> <mark style="color:blue;"></mark><mark style="color:blue;">**Create and Launch Tokens**</mark>

The **Token Launcher** is a powerful tool that allows anyone to create and launch new tokens without requiring coding skills. Along with token creation, users can seamlessly deploy liquidity pools to support their tokens.

**Steps to Create and Launch a Token**

1. Navigate to the [**Create Token**](https://www.interest.xyz/create-token) page.
2. Fill in token details:
   * **Name**, **Symbol**, **Description**, and upload a **Logo**.
3. Set the **Total Supply**.
4. Choose to deploy a liquidity pool during the creation process.
5. Specify the amount of liquidity to add for your token’s pool.
6. Confirm the transaction, and your token is live, backed by a liquidity pool.

{% embed url="<https://youtu.be/QvQJllY85OA>" %}

This feature empowers developers and community members to bring new tokens to market efficiently and securely, fostering innovation in the DeFi space.


# Core Innovations

### <mark style="color:blue;">Sandwich Attack Prevention</mark>

Interest Protocol protects users from sandwich attacks by introducing **slot windows** where the bid price remains constant during transactions. This innovative approach discourages malicious bots by making such attacks unprofitable.

### <mark style="color:blue;">Stable Curve</mark>

The protocol uses a hybrid bonding curve for correlated assets, combining:

* **Constant Product Invariant**: Ensures balanced liquidity.
* **Constant Sum Invariant**: Amplifies liquidity around the mid-range for optimal pricing.

### <mark style="color:blue;">Volatile Curve</mark>

For volatile assets, the platform tracks prices with an internal **exponential moving average (EMA)**, concentrating liquidity around the current market price to enhance trading efficiency.

### <mark style="color:blue;">Hooks for Customization</mark>

Inspired by Uniswap V4, **hooks** enable deployers to customize pools with advanced features such as:

* Pre-swap/post-swap computations.
* Fee-on-swap models.
* Custom oracles or limit orders.


# sr-AMM

Sandwich Resistant Automated Market Maker

### <mark style="color:blue;">What is sandwich attacks and why should I care?</mark>

*"Just let me ape"* - everyday degenerate

AMMs are the primarly venue for meme coin trading and users tend to use high slippage to guarantee early entries. What most do not realize is that this exposes them to sandwich bots. This is a major issue that, for reference 50K Solana was essentially stolen in 1 month in 2024 due to this. The way is works is that Bots can see your transaction on the meme pool and simply place one to buy beforehand and another to sell right after. The first transaction increases the price, the user then purchases at a higher price increasing it further and then the bot sells at a profit.&#x20;

### <mark style="color:blue;">Fine, what do I do?</mark>

Glad you ask, all you have to do is trade on Interest Protocol! Our AMM prevents most of the sandwich bot attacks by introducing slot windows in which the bid price is constant. In simpler terms, if a bot sandwiches you, it will lose money. There are no extra steps needed for the users, it is an invisible solution to the application layer.

\
For further reading check out this [article](https://www.umbraresearch.xyz/writings/sandwich-resistant-amm).


# V3 (Soon)


# Audits

[interest.xyz](https://www.interest.xyz/) Aptos Move CLAMM

{% file src="/files/KJqv3PKQysZEKnOK0re6" %}

&#x20;[Memez.gg](https://www.memez.gg/) launchpad

{% file src="/files/yCA0pDasGd8RxeM73AKC" %}

{% file src="/files/k5sRBa4h7w3BbHECOwyb" %}

[interest.xyz](https://www.interest.xyz/) Movement Dynamic-Peg + Stable DEX

{% file src="/files/QPEo705dh0edEO0RP276" %}

[interestprotocol.com](https://www.interestprotocol.com/) Sui Dynamic-Peg + Stable DEX

{% file src="/files/AYrRAve8rq8aRZQsFSGK" %}

[https://www.winterwalrus.com](https://www.winterwalrus.com/) LST

{% file src="/files/KpUyQ3oGQNfxo6gYcAmI" %}


# Security

DeFi has justly been criticized for its subpar security standards. Last year, we saw a 300 million USD hack on Solana wormhole. Security is a constant battle, and there is no single solution for it. We will always prioritize security over features or development speed.

We will employ the following <mark style="color:blue;">**security measures**</mark> to fight hacks:

* 100% unit test coverage
* Formal verification tools once Move prover is updated
* Working MVP on a test-net before deployment
* Security audits before every deployment
* Upgradeable contracts to fix bugs post-deployment
* Bug bounties&#x20;
* Secure oracles with backups
* Time locks to protect users from future changes
* Multi-signature wallets&#x20;

## <mark style="color:blue;">**We are Open-source**</mark>

Open source platforms like Interest Protocol promote transparency and builds trust, encourages collaboration and innovation. We are accessible to users even those with limited resources. We feel secure because our vulnerabilities can be identified and fixed faster.

{% embed url="<https://github.com/interest-protocol/>" %}

<br>


# Deprecated

This is code that is pending to change and is not longer recommended to be used in production.&#x20;


# Coin X Oracle 🔮

### <mark style="color:blue;">Purpose</mark>

Coin X Oracle allows developers to easily deploy price oracles from various feeds without having to worry about each provider's intricacies and interfaces.&#x20;

Upon requesting a price update, the Coin X Oracle will collect the price from various feeds and run a set of checks to make sure of its liveness and accuracy.&#x20;

### <mark style="color:blue;">Flow</mark>

1. Request a price update
2. Collect the data from predetermined providers.
3. Run a set of checks to ensure the price accuracy and liveness.&#x20;

### <mark style="color:blue;">Security</mark>

The entire process from the data request to reading it inside a DeFi dApp happens in one transaction block atomically through the use of hot potatoes. Price consumers have 100% confidence in the liveness and accuracy of the data.

### <mark style="color:blue;">Feeds</mark>

The following feeds are available:

* [Pyth Network](/overview/deprecated/coin-x-oracle/pyth-network)
* [Switchboard](/overview/deprecated/coin-x-oracle/switchboard)

{% hint style="info" %}
Refer to the SuiTears[💧](https://emojipedia.org/droplet)interface documentation to learn Coin X Oracle's interface.
{% endhint %}

{% embed url="<https://github.com/interest-protocol/coin-x-oracle>" %}


# Pyth Network

Reliable, low-latency market data from institutional sources.

## [<mark style="color:blue;">Why Pyth?</mark>](https://pyth.network/)

The first price provider supported by Coin X Oracle is Pyth Network. It is the leading Oracle provider on Sui Network and the largest first-party Oracle Network in the world. It supports of over 50 chains and offers 450 price feeds.

#### First Party Institutional Providers

Pyth network data sources do not rely on intermediaries to ensure reliability and liveness of the data.

**Price Confidence**

Pyth Network is the only provider that offers a price confidence metric in all price feeds. Assets do not have a single price in a market at any given point in time. By providing a confidence range, DeFi dApps can design their invariant to take into account price variance.

## [<mark style="color:blue;">Interface</mark>](https://github.com/interest-protocol/coin-x-oracle/blob/main/contracts/sources/pyth.move)

### Structs

```rust
struct PriceInfoObjectKey has copy, drop, store {}
```

A dynamic field key to store the `sui::object::ID` of the `pyth::price_info::PriceInfoObject` that can that provide data to the oracle.

```rust
struct ConfidenceKey has copy, drop, store {}
```

A dynamic field key to save the minimum required price confidence. It is a percentage, where 100% is represented by 1e18.&#x20;

```rust
struct PythFeed has drop {}
```

A witness that is added to the `suitears::oracle::Request` to prove that it collected data from Coin X Oracle's Pyth Network module.&#x20;

### Functions

#### <mark style="color:blue;">report</mark>

**It requests a price from Pyth Network and submits the information to a Coin X oracle request.**&#x20;

```rust
public fun report<Witness: drop>(
    oracle: &Oracle<Witness>, 
    request: &mut Request, 
    wormhole_state: &WormholeState,
    pyth_state: &PythState,
    buf: vector<u8>,
    price_info_object: &mut PriceInfoObject,
    pyth_fee: Coin<SUI>,
    clock_object: &Clock
 )
```

* **@param self.** A `suiterars::oracle::Oracle` with this module's witness.
* **@param request.** A hot potato issued from the `self` to create a `suiterars::oracle::Price`.
* **@param wormhole\_state.** The state of the Wormhole module on Sui.
* **@param pyth\_state.** The state of the Pyth module on Sui.
* **@param buf.** Price attestations in bytes.
* **@param price\_info\_object.** An object that contains price information. One per asset.
* **@param pyth\_fee.** There is a cost to request a price update from Pyth.
* **@param clock\_object.** The shared Clock object from Sui

**Aborts**

* the `price_info_object` is not whitelisted.
* the price confidence is out of range.
* the price is negative or zero.

{% embed url="<https://github.com/interest-protocol/coin-x-oracle/blob/main/contracts/sources/pyth.move>" %}


# Switchboard

## [<mark style="color:blue;">Why Switchboard ?</mark>](https://docs.switchboard.xyz/)

Switchboard provides a trusted execution environment to ensure off-chain oracles are not tempered with.It also allows for developers to deploy custom oracles.

## <mark style="color:blue;">Interface</mark>

### Structs

```rust
struct AggregatorKey has copy, drop, store {}
```

A dynamic field key to store the address of the `switchboard::aggregator::Aggregator` that can that provide data to the oracle.

```rust
 struct SwitchboardFeed has drop {}
```

A witness that is added to the `suitears::oracle::Request` to prove that it collected data from Coin X Oracle's Pyth Network module.&#x20;

### Functions

#### <mark style="color:blue;">report</mark>

**It requests a price from Pyth Network and submits the information to a Coin X oracle request.**&#x20;

```rust
public fun report<Witness: drop>(oracle: &Oracle<Witness>, request: &mut Request, aggregator: &Aggregator)
```

* **@param self.** A `suiterars::oracle::Oracle` with this module's witness.
* **@param request.** A hot potato issued from the `self` to create a `suiterars::oracle::Price`.
* **@param aggregator.** `switchboard::aggregator::Aggregator` that the `self` will use to fetch the price.

**Aborts**

* the `aggregator` is not whitelisted.
* the `aggregator` price is negative or zero.


# Sui Tears 💧

[Sui Tears](https://github.com/interest-protocol/suitears) is an open source production ready Sui Move library to increase the productivity of new and experienced developers alike.&#x20;

### [<mark style="color:blue;">Airdrop</mark>](#airdrop)

* [**Airdrop Utils** ](/overview/deprecated/sui-tears/airdrop/airdrop-utils)- Verify function for the airdrop modules.
* [**Airdrop**](/overview/deprecated/sui-tears/airdrop) - A pull design airdrop to distribute tokens after a specific date.
* [**Linear Vesting Airdrop** ](/overview/deprecated/sui-tears/airdrop/linear-vesting-airdrop)**-** A pull design airdrop to distribute tokens according to a linear vesting schedule.&#x20;

### [<mark style="color:blue;">Capabilities</mark>](#capabilities)

* [**Owner**](/overview/deprecated/sui-tears/capabilities/owner) **-** Owner capability to give access to multiple objects.
* [**Quest**](/overview/deprecated/sui-tears/capabilities/quest) **-** A wrapper that can only be unwrapped once a set of actions are completed.&#x20;
* [**Time Lock**](/overview/deprecated/sui-tears/capabilities/timelock) **-** A wrapper that can only be unwrapped after a set timestamp.

### [<mark style="color:blue;">Collections</mark>](#collections)

* [**Access Collection**](broken://pages/02jnXqjdVKIzyRFmMKgg) - Capability access wrapper for collections. &#x20;
* [**BitMap**](/overview/deprecated/sui-tears/collections/bitmap) - Bitmap implementation for sequential keys. &#x20;
* [**Coin Decimals**](/overview/deprecated/sui-tears/collections/coin-decimals) - A Collection that stores coin decimals. &#x20;
* [**Witness Collection**](broken://pages/Lkp0XsBmGiH4iZw8VM1h) **-** Witness access wrapper for collections. &#x20;

### [<mark style="color:blue;">DeFi</mark>](#defi)

* [**Farm** ](/overview/deprecated/sui-tears/defi/farm)**-** Module to reward coin stakers over time. &#x20;
* [**Fund**](/overview/deprecated/sui-tears/defi/fund) - Struct to track shares associated with underlying deposits/withdrawals.&#x20;
* [**Linear Vesting Wallet**](/overview/deprecated/sui-tears/defi/linear-vesting-wallet) - Wallet that distributes tokens according to a linear vesting schedule.
* [**Linear** **Vesting Clawback Wallet**](/overview/deprecated/sui-tears/defi/linear-clawback-vesting-wallet) **-** Wallet that distributes tokens according to a linear vesting schedule and allows the owner to reclaim the locked coins.&#x20;
* [**Vesting**](/overview/deprecated/sui-tears/defi/vesting) - Virtual implementation of vesting schedules

### [<mark style="color:blue;">Governance</mark>](#governance)

* [**Dao**](/overview/deprecated/sui-tears/governance/dao) **-** Decentralized autonomous organization
* [**Dao Admin**](/overview/deprecated/sui-tears/governance/dao-admin) **-** The admin capability for DAOs&#x20;
* [**Dao Treasury**](/overview/deprecated/sui-tears/governance/dao-treasury) - Treasury plugin for DAOs&#x20;

### [<mark style="color:blue;">Math</mark>](#math)

* [**Fixed Point 64**](/overview/deprecated/sui-tears/math/fixed-point-64) - Fixed point math module for numbers scaled to x << 64.&#x20;
* [**Fixed Point Roll** ](/overview/deprecated/sui-tears/math/fixed-point-roll)- Fixed point math module for numbers with 1e9 precision.&#x20;
* [**Fixed Point Wad**](/overview/deprecated/sui-tears/math/fixed-point-wad) **-** Fixed point math for module for numbers with 1e18 decimals.&#x20;
* [**Math64**](/overview/deprecated/sui-tears/math/math64) **-** Utility math functions for u64 numbers.
* [**Math128**](/overview/deprecated/sui-tears/math/math128)  - Utility math functions for u128 numbers.&#x20;
* [**Math256**](/overview/deprecated/sui-tears/math/math256) **-** Utility math functions for u256 numbers.&#x20;
* [ **Int**](/overview/deprecated/sui-tears/math/int) - Module to handle signed integer operations.&#x20;

### [<mark style="color:blue;">Utils</mark>](/overview/deprecated/sui-tears/utils)

* [**Comparator**](/overview/deprecated/sui-tears/utils/comparator) **-** Module to compare u8 vectors (bits).&#x20;
* [**Merkle Proof**](/overview/deprecated/sui-tears/utils/merkle-proof) **-** Module to verify Merkle proofs.&#x20;
* [**ASCII Utils**](/overview/deprecated/sui-tears/utils/ascii) **-** A set of functions to operate on ASCII strings.&#x20;
* [**Vectors**](/overview/deprecated/sui-tears/utils/vectors) **-** Utility functions for vectors.&#x20;


# Airdrop


# Airdrop

Sui Tears[💧](https://emojipedia.org/droplet) Airdrop modules are "pulled" based. The modules store the root of a Merkle tree that consists of the address of the user and the airdrop amount.  Users are required to submit a Merkle proof to claim their airdrops. The leafs are constructed by hashing (sha3256) the sender's address concatenated with the amount. <br>

Please check [here](https://github.com/interest-protocol/suitears/blob/main/utils/src/airdrop-tree.ts) on how to construct the Merkle Tree.

## Structs

### <mark style="color:blue;">**Airdrop**</mark>

```rust
struct Airdrop<phantom T> has key, store { 
    id: UID,
    balance: Balance<T>,
    root: vector<u8>,
    start: u64, 
    map: Bitmap
}
```

* **balance** - Coins to airdrop
* **root** - The root of the Merkle tree
* **start** - The timestamp in which users can claim the airdrop
* **map** - Bitmap keeps track of airdrop claims. &#x20;

## Interface

### <mark style="color:blue;">new</mark>

**It creates the Airdrop object.**

```rust
public fun new(airdrop_coin: Coin<T>, root: vector<u8>, start: u64, c: &Clock, ctx: &mut TxContext): Airdrop<T>
```

* **@param airdrop\_coin:** The coin that will be distributed in the airdrop.
* **@param root:** The Merkle tree root that keeps track of all the airdrops.
* **@param start:** The start timestamp of the airdrop in milliseconds.
* **@param c:** The `sui::clock::Clock` shared object.&#x20;
* **@return** Airdrop\<T>

**Aborts**

* root is empty.&#x20;
* start time of the airdrop is in the past.&#x20;

### <mark style="color:blue;">balance</mark>

**Returns the current amount of airdrop coins in the Airdrop object.**&#x20;

```rust
public fun balance<T>(self: &Airdrop<T>): u64
```

* **@param:** self The shared Airdrop object
* **@return** u64&#x20;

### <mark style="color:blue;">root</mark>

**Returns the root of the Merkle tree for the airdrop.**

```rust
public fun root<T>(self: &Airdrop<T>): vector<u8>
```

* **@param:** self The shared Airdrop object.
* **@return** vector\<u8>.&#x20;

### <mark style="color:blue;">start</mark>

**Returns the start timestamp of the airdrop. Users can claim after this date.**

```rust
public fun start<T>(self: &Airdrop<T>): u64
```

* **@param:** self The shared Airdrop object.
* **@return** u64.&#x20;

### <mark style="color:blue;">borrow\_map</mark>

**Returns an immutable reference of the Bitmap. It keeps track of the claimed airdrops.**

```rust
public fun borrow_map<T>(self: &Airdrop<T>): &Bitmap
```

* **@param:** self The shared Airdrop object.
* **@return** \&Bitmap.

### <mark style="color:blue;">has\_account\_claimed</mark>

**Checks if a user has already claimed his airdrop.**

```rust
public fun has_account_claimed<T>(
    self: &Airdrop<T>, 
    proof: vector<vector<u8>>, 
    amount: u64, 
    user: address
  ): bool
```

* **@param self:** The shared Airdrop object.
* **@param proof:** The proof that the sender can redeem the `amount` from the airdrop.
* **@param amount:** Number of coins the sender can redeem.
* **@param address:** A user address.
* **@return** bool. True if he has claimed the airdrop already.

**Aborts**

* If the `proof` is not valid.

### <mark style="color:blue;">get\_airdrop</mark>

**Allows a user to claim his airdrop by proving that his address and amount are in the Merkle tree.**

```rust
public fun get_airdrop<T>(
    self: &mut Airdrop<T>, 
    proof: vector<vector<u8>>, 
    c: &Clock,
    amount: u64, 
    ctx: &mut TxContext
): Coin<T>
```

* **@param self:** The shared Airdrop object.
* **@param proof:** The proof that the sender can redeem the `amount` from the airdrop.
* **@param c:** The `sui::clock::Clock` shared object.&#x20;
* **@param amount:** Number of coins the sender can redeem.
* **@return** Coin\<T>. The airdrop Coin.

**Aborts**

* If the `proof` is not valid.
* The airdrop has not started yet.
* The user already claimed it

### <mark style="color:blue;">destroy\_zero</mark>

**Destroys an empty Airdrop object.**

```rust
public fun destroy_zero<T>(self: Airdrop<T>)
```

* **@param self:** The shared {Airdrop} object.

**Aborts**

* The `self` has left over coins.


# Airdrop Utils

Airdrop utils module contains the verify function to check if a Merkle proof combined with an address and amount are part of the Merkle tree root.&#x20;

### <mark style="color:blue;">verify</mark>

**Checks if the sender is allowed to redeem an `amount` from an airdrop using Merkle proofs. It returns the index of his Merkle proof to add to the Bitmap struct.**&#x20;

```rust
public fun verify(
    root: vector<u8>,
    proof: vector<vector<u8>>, 
    amount: u64, 
    sender: address
): u256
```

* **@param root:** The Merkle tree root that keeps track of all the airdrops.
* **@param proof:**  The proof that the sender can redeem the `amount` from the airdrop.
* **@param amount:** The airdrop amount.&#x20;
* **@param sender:** The address of the airdrop user.
* **@return** u256. An index.&#x20;

**Aborts**

* if the leaf or proof are invalid.&#x20;


# Linear Vesting Airdrop

Sui Tears[💧](https://emojipedia.org/droplet) Airdrop modules are "pulled" based. The modules store the root of a Merkle tree that consists of the address of the user and the airdrop amount.  Users are required to submit a Merkle proof to claim their airdrops. The leafs are constructed by hashing (sha3256) the sender's address with the amount. This module returns the airdrop inside a linear vesting airdrop wallet. <br>

Please check [here](https://github.com/interest-protocol/suitears/blob/main/utils/src/airdrop-tree.ts) on how to construct the Merkle Tree.

## Structs

### <mark style="color:blue;">**Airdrop**</mark>

```rust
struct Airdrop<phantom T> has key, store { 
    id: UID,
    balance: Balance<T>,
    root: vector<u8>,
    start: u64, 
    duration: u64,
    map: Bitmap
}
```

* **balance** - Coins to airdrop
* **root** - The root of the Merkle tree
* **start** - The timestamp in which the vesting schedule starts.
* **duration** -  The duration of the vesting schedule.&#x20;
* **map** - Bitmap keeps track of airdrop claims. &#x20;

## Interface

### <mark style="color:blue;">new</mark>

**Creates a linear vested airdrop.**

```rust
public fun new<T>(airdrop_coin: Coin<T>, root: vector<u8>, start: u64, duration: u64, c: &Clock, ctx: &mut TxContext): Airdrop<T>
```

* **@param airdrop\_coin:** The coin that will be distributed in the airdrop.
* **@param root:** The Merkle tree root that keeps track of all the airdrops.
* **@param start:** The start timestamp of the vesting schedule.
* **@param duration:** The duration of the vesting schedule.
* **@param c:** The `sui::clock::Clock` shared object.&#x20;
* **@return** Airdrop\<T>

**Aborts**

* root is empty.&#x20;
* start time of the airdrop is in the past.&#x20;

### <mark style="color:blue;">balance</mark>

**Returns the current amount of airdrop coins in the Airdrop object.**&#x20;

```rust
public fun balance<T>(self: &Airdrop<T>): u64
```

* **@param:** self The shared Airdrop object
* **@return** u64&#x20;

### <mark style="color:blue;">root</mark>

**Returns the root of the Merkle tree for the airdrop.**

```rust
public fun root<T>(self: &Airdrop<T>): vector<u8>
```

* **@param:** self The shared Airdrop object.
* **@return** vector\<u8>.&#x20;

### <mark style="color:blue;">start</mark>

**Returns the start timestamp of the airdrop. Users can claim after this date.**

```rust
public fun start<T>(self: &Airdrop<T>): u64
```

* **@param:** self The shared Airdrop object.
* **@return** u64.&#x20;

### <mark style="color:blue;">duration</mark>

**Returns the duration of the vesting schedule.**

```rust
public fun duration<T>(self: &Airdrop<T>): u64
```

* **@param:** self The shared Airdrop object.
* **@return** u64.&#x20;

### <mark style="color:blue;">borrow\_map</mark>

**Returns an immutable reference of the Bitmap. It keeps track of the claimed airdrops.**

```rust
public fun borrow_map<T>(self: &Airdrop<T>): &Bitmap
```

* **@param:** self The shared Airdrop object.
* **@return** \&Bitmap.

### <mark style="color:blue;">has\_account\_claimed</mark>

**Checks if a user has already claimed his airdrop.**

```rust
public fun has_account_claimed<T>(
    self: &Airdrop<T>, 
    proof: vector<vector<u8>>, 
    amount: u64, 
    user: address
  ): bool
```

* **@param self:** The shared Airdrop object.
* **@param proof:** The proof that the sender can redeem the `amount` from the airdrop.
* **@param amount:** Number of coins the sender can redeem.
* **@param address:** A user address.
* **@return** bool. True if he has claimed the airdrop already.

**Aborts**

* If the `proof` is not valid.

### <mark style="color:blue;">get\_airdrop</mark>

**Allows a user to claim his airdrop by proving that his address and amount are in the Merkle tree.**

```rust
  public fun get_airdrop<T>(
    self: &mut Airdrop<T>,
    proof: vector<vector<u8>>,  
    clock_object: &Clock,
    amount: u64, 
    ctx: &mut TxContext
  ): Wallet<T>
```

* **@param self:** The shared Airdrop object.
* **@param proof:** The proof that the sender can redeem the `amount` from the airdrop.
* **@param c:** The `sui::clock::Clock` shared object.&#x20;
* **@param amount:** Number of coins the sender can redeem.
* **@return** Wallet. The airdrop Coin locked in a linear vested {Wallet}.

**Aborts**

* If the `proof` is not valid.
* The user already claimed it

### <mark style="color:blue;">destroy\_zero</mark>

**Destroys an empty Airdrop.**

```rust
public fun destroy_zero<T>(self: Airdrop<T>)
```

* **@param self:** The shared {Airdrop} object.

**Aborts**

* The `self` has left over coins.


# Capabilities


# Access Control

It allows an admin to manage access control via roles.

## Structs

### <mark style="color:blue;">AccessControl</mark>

```rust
struct AccessControl has key, store {
 id: UID,
 roles: VecMap<vector<u8>, VecSet<address>>
}
```

* **roles -** Map to store a role => set of addresses with said role.

### <mark style="color:blue;">Admin</mark>

```rust
struct Admin has key, store {
 id: UID,
 access_control: address
}
```

* Address of the `AccessControl` this capability belongs to.&#x20;

## Interface

### <mark style="color:blue;">new</mark>

**It creates an \`AccessControl\`  and an \`Admin\` with the \`SUPER\_ADMIN\_ROLE\`.**&#x20;

```rust
public fun new(ctx: &mut TxContext): (AccessControl, Admin)
```

* **@return** \`AccessControl\`. It stores the role's data.
* **@return \`**&#x41;dmin\`. The \`SUPER\_ADMIN\_ROLE\` \`Admin\`.


# Owner

It provides an Owner capability that stores the IDs of other objects, Modules can assert or check if a certain ID is stored in the Owner to prove its ownership. It is used to provide access control.&#x20;

## Structs

### <mark style="color:blue;">**OwnerCap**</mark>

```rust
struct OwnerCap<phantom T> has key, store {
    id: UID,
    of: VecSet<ID>
 }
```

* **of - A set of IDs to prove that the Owner Capability has privileged access to it.**&#x20;

## Interface

### <mark style="color:blue;">new</mark>

**It creates an OwnerCap capability.**&#x20;

```rust
public fun new<T: drop>(_: T, of: vector<ID>, ctx: &mut TxContext): OwnerCap<T>
```

* **@param \_:** A witness to link an OwnerCap with the module that owns the witness.
* **@param of:** Vector of `sui::object::ID` that this capability owns.
* **@return** OwnerCap.

### <mark style="color:blue;">contains</mark>

**It checks if an ID is stored in the Owner Capability.**&#x20;

```rust
public fun contains<T: drop>(self: &OwnerCap<T>, x: ID): bool 
```

* **@param self:** An OwnerCap object.
* **@param x:** The `sui::object::ID` of an object.
* **@return** bool. True if the `self` owns `x`.

### <mark style="color:blue;">of</mark>

**Returns the vector of `sui::object::ID` that the `self` owns.**

```rust
public fun of<T: drop>(self: &OwnerCap<T>): vector<ID>
```

* **@param self:** A {OwnerCap} object.
* **@return** vector. The vector of `sui::object::ID`.

### <mark style="color:blue;">add</mark>

**Assigns the `self` OwnerCap as the owner of `x`.**

```rust
public fun add<T: drop>(self: &mut OwnerCap<T>, _: T, x: ID)
```

* **@param self:** An OwnerCap object.
* **@param \_:** A witness to make sure only the allowed module can add `sui::object::ID` to the self.
* **@param x:** The `sui::object::ID` of the object, which the `self` will have ownership rights to.

### <mark style="color:blue;">remove</mark>

**Removes the `self` OwnerCap as the owner of `x`.**

```rust
public fun remove<T: drop>(self: &mut OwnerCap<T>, _: T, x: ID)
```

* **@param self:** An OwnerCap object.
* **@param \_:** A witness to make sure only the right module can add the `sui::object::ID` to the self.
* **@param x:** The `sui::object::ID` of the object, which the `self` will lose its ownership rights to.

### <mark style="color:blue;">destroy</mark>

**Destroys an OwnerCap. It does not require the of vector to be empty.**

```rust
public fun destroy<T: drop>(self: OwnerCap<T>)
```

* **@param self:** An OwnerCap object.

### <mark style="color:blue;">destroy\_empty</mark>

**Destroys an OwnerCap. It requires the of vector to be empty.**

```rust
public fun destroy<T: drop>(self: OwnerCap<T>)
```

* **@param self:** A OwnerCap object.

**Aborts**

* If `of` vector is not empty.&#x20;

### <mark style="color:blue;">assert\_ownership</mark>

**Asserts that the `self` owns `x`.**

```rust
public fun destroy<T: drop>(self: OwnerCap<T>)
```

* **@param self:** An OwnerCap object.
* **@param x:** The `sui::object::ID` of the object, which must belong to the capability.

**Aborts**

* If the ID is not owned by the capability.


# Quest

This module wraps an object labeled as rewards that can only be unwrapped if a set of witness objects are passed as arguments to the complete function. A witness is a struct with the drop key. The idea is to have a user complete a set of tasks for a reward in different protocols . The protocols certify that the user completed the task via their Witnesses.

## Structs

### <mark style="color:blue;">**Quest**</mark>

```rust
struct Quest<Reward: store> has key, store {
    id: UID,
    required_tasks: VecSet<TypeName>,
    completed_tasks: VecSet<TypeName>,
    reward: Reward,
 }
```

* **required\_tasks** - Stores the Witnesses of all required tasks.
* **completed\_tasks** - Contains all the Witnesses the user must complete to unwrap the {Reward}.
* **reward** - An object that will be returned once the Quest has been completed.

## Interface

### <mark style="color:blue;">new</mark>

**Creates a {Quest} .**

```rust
public fun new<Reward: store>(
  required_tasks: VecSet<TypeName>, 
  reward: Reward, 
  ctx: &mut TxContext
): Quest<Reward>
```

* **@param required\_tasks:** A vector set of the required tasks to unlock the `reward`.
* **@param reward:** An object with the store ability that can be redeemed once all tasks are completed.
* **@return** Quest\<Reward>.&#x20;

### <mark style="color:blue;">required\_tasks</mark>

**Returns the required tasks of the `self`.**

```rust
public fun required_tasks<Reward: store>(self: &Quest<Reward>): vector<TypeName>
```

* **@param self:** A {Quest}.
* **@return** vector\<TypeName>. A vector of the required Witness names to complete the quest.

### <mark style="color:blue;">completed\_tasks</mark>

**Returns the completed tasks of the `self`.**

```rust
public fun required_tasks<Reward: store>(self: &Quest<Reward>): vector<TypeName>
```

* **@param self:** A {Quest}.
* **@return** vector\<TypeName>. A vector of the completed Witness names to complete the quest.

### <mark style="color:blue;">complete</mark>

**Completes a quest by adding the witness `Task` name to the `self.completed_tasks` vector.**

```rust
public fun complete<Reward: store, Task: drop>(self: &mut Quest<Reward>, _: Task)
```

* **@param self:** A {Quest}.
* **@param:** \_ A witness `Task`.

### <mark style="color:blue;">finish</mark>

**Finishes a quest and returns the `Reward` to the caller.**

```rust
public fun complete<Reward: store, Task: drop>(self: &mut Quest<Reward>, _: Task)
```

* **@param self:** A {Quest}.
* **@return:** Reward.

**Aborts**

* If the required\_tasks do not match the completed\_tasks


# Timelock

It locks any object with the store ability for a specific amount of time. We do not provide a function to read the data inside the {Timelock} to prevent capabilities from being used.

## Structs

### <mark style="color:blue;">**Timelock**</mark>

```rust
  struct Timelock<T: store> has key, store {
    id: UID,
    unlock_time: u64,
    data: T,
  }
```

* **unlock\_time** - The unlock time in milliseconds.
* **data** - Any object with the store ability.

## Interface

### <mark style="color:blue;">unlock\_time</mark>

**Returns the unlock time in milliseconds.**

```rust
public fun unlock_time<T: store>(self: &Timelock<T>): u64
```

* **@param self:** A {Timelock}
* **@return** u64. The `self.unlock_time`.

### <mark style="color:blue;">lock</mark>

**Locks the `data` for `unlock_time` milliseconds.**

```rust
public fun lock<T: store>(
    data: T, 
    c: &Clock,
    unlock_time: u64,
    ctx: &mut TxContext
): Timelock<T>
```

* **@param data:** An object with the store ability.
* **@param c:** The shared `sui::clock::Clock` object.
* **@param unlock\_time:** The lock period in milliseconds.
* **@return** {Timelock}.

**Aborts**

* `unlock_time` is in the past.

### <mark style="color:blue;">unlock</mark>

**Unlocks a {Timelock} and returns the locked resource `T`.**

```rust
public fun unlock<T: store>(self: Timelock<T>, c:&Clock): T
```

* **@param self:** A {Timelock}
* **@param c:** The shared `sui::clock::Clock` object.
* **@return** **`T`**. An object with the store ability.

**Aborts**

* `unlock_time` has not passed.


# Collections


# Bitmap

BitMaps pack 256 booleans across each bit of a single 256-bit slot of `uint256` type. Hence booleans corresponding to 256 *sequential* indices would only consume a single slot, unlike the regular `bool` which would consume an entire slot for a single value.

## Structs

### <mark style="color:blue;">**Bitmap**</mark>

```rust
struct Bitmap has key, store {
    id: UID
}
```

The module adds dynamic fields to the Bitmap.&#x20;

## Interface

### <mark style="color:blue;">new</mark>

**Creates a Bitmap.**

```rust
public fun new(ctx: &mut TxContext): Bitmap
```

* **@return AcCollection.** Bitmap.

### <mark style="color:blue;">get</mark>

**Checks if an `index`is set to true or false in the map.**

```rust
public fun get(self: &Bitmap, index: u256): bool
```

* **@param self:** A reference to the Bitmap.
* **@param index:** The slot to check if it is flagged.
* **@return bool.** If the `index` is true or false.

### <mark style="color:blue;">set</mark>

**Sets the slot `index` to true in `self`.**

```rust
public fun set(self: &mut Bitmap, index: u256)
```

* **@param self:** A reference to the Bitmap.
* **@param index**: The slot we will set to true.

### <mark style="color:blue;">unset</mark>

**Sets the slot `index` to false in `self`.**

```rust
public fun set(self: &mut Bitmap, index: u256)
```

* **@param self:** A reference to the Bitmap.
* **@param index**: The slot we will set to false.

### <mark style="color:blue;">destroy</mark>

**Destroys the `self`.**

```rust
public fun destroy(self: Bitmap)
```

* **@param self:** self A bitmap to destroy.


# Coin Decimals

It stores information about Coins' decimals to allow protocols to fetch them. The idea is to pass a single argument `CoinDecimals` to functions that require several `sui::coin::CoinMetadata` objects.

## Structs

### <mark style="color:blue;">**Decimals**</mark>

```rust
struct Decimals has store {
    decimals: u8, 
    scalar: u64
}
```

* **decimals -** decimals of a `sui::coin`
* **scalar** - The scalar of a `sui::coin`'s decimals. It is calculated by 10^decimals. E.g. `sui::sui` has a scalar of 1\_000\_000\_000 or 1e9.

### <mark style="color:blue;">**CoinDecimals**</mark>

```rust
struct CoinDecimals has key, store {
    id: UID
}
```

The  Decimals struct is saved in CoinDecimals using dynamic fields.

## Interface

### <mark style="color:blue;">new</mark>

**It creates a new CoinDecimals.**

```rust
public fun new(ctx: &mut TxContext): CoinDecimals
```

* **@return** CoinDecimals.

### <mark style="color:blue;">contains</mark>

**Checks if a coin with type `CoinType` has been added to `self`.**

```rust
public fun contains<CoinType>(self: &CoinDecimals): bool
```

* **@param** self A {CoinDecimals} object.
* **@return** bool. True if the coin's decimals and scalar are in the `self`.

### <mark style="color:blue;">decimals</mark>

**Returns the decimals of a coin with the type `CoinType`.**

```rust
public fun decimals<CoinType>(self: &CoinDecimals): u8
```

* **@param** self A CoinDecimals object.
* **@return** u8. The decimals of the coin.

**Aborts**

* `CoinType` has not been added to the `self`.

### <mark style="color:blue;">scalar</mark>

**Returns the decimals scalar of a coin with type `CoinType`.**

```rust
 public fun scalar<CoinType>(self: &CoinDecimals): u64
```

* **@param** self A {CoinDecimals} object.
* **@return** u64. The decimal's scalar. It is calculated by 10^decimals.

**Aborts**

* `CoinType` has not been added to the `self`.

### <mark style="color:blue;">add</mark>

**Adds the decimals and decimal scalar of a coin with type `CoinType` to `self`.**

```rust
public fun add<CoinType>(self: &mut CoinDecimals, coin_metadata: &CoinMetadata<CoinType>)
```

* **@param** self A CoinDecimals object.
* **@return** coin\_metadata The `sui::coin::CoinMetadata` of a coin with type `CoinType`.


# DeFi


# Oracle

An Oracle contract that collects price reports from several feeds and ensures they are within a price range and time limit. &#x20;

## Structs

### <mark style="color:blue;">**Oracle**</mark>

```rust
 struct Oracle<phantom Witness: drop> has key, store {
    id: UID,
    // Set of module Witnesses that are allowed to report prices.
    feeds: VecSet<TypeName>,
    // Reported prices must have a timestamp earlier than `current_timestamp - time_limit`. 
    // It is in milliseconds. 
    time_limit: u64,
    // Reported prices must be within the following range: `leader_price + deviation % >= reported_price >= leader_price - deviation %`.
    deviation: u256
  }  
```

* **feeds** - Set of module Witnesses that are allowed to report prices.
* **time\_limit** - Reported prices must have a timestamp earlier than \`current\_timestamp - time\_limit\`. It is in milliseconds.
* **deviation** **-** Reported prices must be within the following range: \`leader\_price + deviation % >= reported\_price >= leader\_price - deviation %\`.

### <mark style="color:blue;">**Report**</mark>

```rust
struct Report has store, copy, drop {
    price: u256,
    timestamp: u64
 }
```

* **price** - Price has 18 decimals.
* **timestamp -** Timestamp in milliseconds.&#x20;

### <mark style="color:blue;">**Price**</mark>

```rust
struct Price {
    // `sui::object::ID` of the`Oracle` this request was sent from.
    oracle: ID,
    // The first reported price. 
    // Price has 18 decimals.  
    price: u256,
    // It is always 18.  
    decimals: u8, 
    // The price was reported at this time.  
    timestamp: u64    
 }
```

* **oracle -** the \`sui::object::ID\` of the Oracle this request was sent from.
* **price -** The first reported price after all checks.&#x20;
* **decimals -** It is always 18.
* **timestamp -** The time at which this price was reported.&#x20;

## Interface

### <mark style="color:blue;">new</mark>

**Creates an `Oracle` with a set of feeds.**

```rust
public fun new<Witness: drop>(
  cap: &mut OwnerCap<Witness>,
  wit: Witness, 
  feeds: vector<TypeName>, 
  time_limit: u64, 
  deviation: u256, 
  ctx: &mut TxContext
): Oracle<Witness>
```

* **@param cap:** An owner cap from `suitears::owner`. This `OwnerCap` will be the owner of the new `Oracle`.
* **@param wit:** A Witness from the module that will manage this `Oracle`.
* **@param feeds:** Feed Witnesses. Only modules in the `Oracle.feeds` can report a price in the `Request` hot potato.
* **@param time\_limit:** A time in milliseconds that determines how old a price timestamp can be.
* **@param deviation:** A percentage that determines an acceptable price range for all reported prices.
* **@return** Oracle\<Witness>.

**Aborts**

* `feeds` vector has repeated values.
* `time_limit` must be higher than 0 milliseconds.
* `deviation` must be higher than 0.

### <mark style="color:blue;">share</mark>

**Shares the `Oracle` object.**

```rust
public fun share<Witness: drop>(self: Oracle<Witness>)
```

* **@param self:** The `Oracle`.

### <mark style="color:blue;">request</mark>

**Creates a `Request` hot potato.**

```rust
public fun request<Witness: drop>(self: &Oracle<Witness>): Request
```

* **@param self:** The `Request` will require all feeds from `Oracle` to be reported.
* **@return** `Request`.

**Aborts**

* `self.feed` is empty.

### <mark style="color:blue;">report</mark>

**Adds a price `Report` to the `Request`.**

```rust
public fun report<Witness: drop>(request: &mut Request, _: Witness, timestamp: u64, price: u128, decimals: u8)
```

* **@param request:** `Request` hot potato.
* **@param \_ :** A Witness to verify the reporters.
* **@param timestamp:** The timestamp of the price feed.
* **@param price:** The price
* **@param decimals**: The decimal houses of the `price` value.
* **@return** `Request`.

**Aborts**

* a feed reports more than once.

### <mark style="color:blue;">destroy\_request</mark>

**Destroy the `Request` potato and verify the price values and timestamps.**

```rust
public fun destroy_request<Witness: drop>(self: &Oracle<Witness>, request: Request, c: &Clock): Price
```

* **@param self:** The `Oracle` that the `Request` was sent from.
* **@param request:** The `Request`.
* **@param c:** The shared `sui::clock::Clock` object.
* **@return** `Price`.

**Aborts**

* The`Request.oracle` does not match the `self.id`.
* The number of reports does not match the number of feeds in the `Oracle.feeds`.
* The report witnesses do not match the required feed witnesses.
* The reported price is outside the `time_limit`.
* The price falls outside the outside `deviation` range.

### <mark style="color:blue;">destroy\_price</mark>

**Destroys an `Oracle` object.**

```rust
public fun destroy_oracle<Witness: drop>(self: Oracle<Witness>)
```

* **@param self:** The `Oracle` that the `Request` was sent from.
* **@param cap:** The `suitears::owner::OwnerCap` that owns the `self`.

**Aborts**

* the `cap` is not the owner of `self`.

### <mark style="color:blue;">feeds</mark>

**Returns a vector of the `Oracle.feeds`.**

```rust
public fun feeds<Witness: drop>(self: &Oracle<Witness>): vector<TypeName>
```

* **@param self:** An `Oracle` object.
* **@return** vector

### <mark style="color:blue;">feeds</mark>

**Returns a vector of the `Oracle.feeds`.**

```rust
public fun feeds<Witness: drop>(self: &Oracle<Witness>): vector<TypeName>
```

* **@param self:** An `Oracle` object.
* **@return** vector

### <mark style="color:blue;">time\_limit</mark>

**Returns a time limit set in the `Oracle`.**

```rust
public fun feeds<Witness: drop>(self: &Oracle<Witness>): vector<TypeName>
```

* **@param self:** An `Oracle` object.
* **@return** vector

### <mark style="color:blue;">deviation</mark>

**Returns the price deviation set in the `Oracle`.**

```rust
public fun deviation<Witness: drop>(self: &Oracle<Witness>): u256
```

* **@param self:** An `Oracle` object.
* **@return u**256

### <mark style="color:blue;">uid</mark>

**Allows extensions to read dynamic fields.**

```rust
public fun uid<Witness: drop>(self: &Oracle<Witness>): &UID
```

* **@param self:** An `Oracle` object.
* **@return** `sui::object::UID`

### <mark style="color:blue;">oracle</mark>

**Returns the `sui::object::ID` of a Price's oracle.**

```rust
public fun oracle(price: &Price): ID
```

* **@param price:** A `Price` potato.
* **@return** `sui::object::ID`

### <mark style="color:blue;">price</mark>

**Returns the price value of a `Price` hot potato.**

```rust
public fun price(price: &Price): u256
```

* **@param price:** A `Price` potato.
* **@return** u256

### <mark style="color:blue;">decimals</mark>

**Returns the decimal houses of the price value.**

```rust
public fun decimals(price: &Price): u8
```

* **@param price:** A `Price` potato.
* **@return** u8

### <mark style="color:blue;">timestamp</mark>

**Returns the timestamp of the a `Price`.**

```rust
public fun timestamp(price: &Price): u64
```

* **@param price:** A `Price` potato.
* **@return** u64

### <mark style="color:blue;">uid\_mut</mark>

**Allows extensions to add/remove dynamic fields.**

```rust
public fun uid_mut<Witness: drop>(self: &mut Oracle<Witness>, cap: &OwnerCap<Witness>): &mut UID
```

* **@param self:** An `Oracle` object.
* **@param cap:** The `suitears::owner::OwnerCap` that owns the `self`.
* **@return** `sui::object::UID`

**Aborts**

* The `cap` is not the owner of `self`.

### <mark style="color:blue;">add</mark>

**Adds a feed Witness to an `Oracle`.**

```rust
public fun add<Witness: drop>(self: &mut Oracle<Witness>, cap: &OwnerCap<Witness>, feed: TypeName)
```

* **@param self:** An `Oracle` object.
* **@param cap:** The `suitears::owner::OwnerCap` that owns the `self`.
* **@param feed:** A Witness feed.

**Aborts**

* The `cap` is not the owner of `self`.
* A duplicated `feed` is added.

### <mark style="color:blue;">remove</mark>

**Removes a feed Witness to an `Oracle`.**

```rust
public fun remove<Witness: drop>(self: &mut Oracle<Witness>, cap: &OwnerCap<Witness>, feed: TypeName)
```

* **@param self:** An `Oracle` object.
* **@param cap:** The `suitears::owner::OwnerCap` that owns the `self`.
* **@param feed:** A Witness feed.

**Aborts**

* The `cap` is not the owner of `self`.
* The `Oracle` has 1 feed left.

### <mark style="color:blue;">update\_time\_limit</mark>

**Updates the time\_limit of an `Oracle`.**

```rust
public fun update_time_limit<Witness: drop>(self: &mut Oracle<Witness>, cap: &OwnerCap<Witness>, time_limit: u64)
```

* **@param self:** An `Oracle` object.
* **@param cap:** The `suitears::owner::OwnerCap` that owns the `self`.
* **@param time\_limit:** The new time\_limit.

**Aborts**

* The `cap` is not the owner of `self`.
* The `time_limit` cannot be zero.

### <mark style="color:blue;">update\_deviation</mark>

**Updates the deviation of an `Oracle`.**

```rust
public fun update_deviation<Witness: drop>(self: &mut Oracle<Witness>, cap: &OwnerCap<Witness>, deviation: u256)
```

* **@param self:** An `Oracle` object.
* **@param cap:** The `suitears::owner::OwnerCap` that owns the `self`.
* **@param deviation:** The new deviation.

**Aborts**

* The `cap` is not the owner of `self`.
* The `time_limit` cannot be zero.

### <mark style="color:blue;">new\_price\_for\_testing</mark>

**Creates a `Price` for testing purposes only. Only available in tests.**

```rust
#[test_only]
public fun new_price_for_testing(
 oracle: ID,
 price: u256,
 decimals: u8,
 timestamp: u64
): Price
```

* **@param oracle:** `sui::object::ID` of the`Oracle` this request was sent from.
* **@param price:** The reported price.
* **@param decimals:** The decimals precision of `price`.
* **@param timestamp:** The timestamp in milliseconds in which the price was recorded.


# Farm

A contract to distribute reward tokens to stakers.

{% hint style="warning" %}
All times are in seconds.
{% endhint %}

## Structs

### <mark style="color:blue;">**Account**</mark>

```rust
  struct Account<phantom StakeCoin, phantom RewardCoin> has key, store {
    id: UID,
    farm_id: ID, 
    amount: u64,
    reward_debt: u256
  }
```

* **farm\_id** - The \`sui::object::ID\` of the farm to which this account belongs to.&#x20;
* **amount** - The amount of StakeCoin the user has in the Farm.
* **reward\_debt -** Amount of rewards the Farm has already paid the user.

### <mark style="color:blue;">**Farm**</mark>

```rust
struct Farm<phantom StakeCoin, phantom RewardCoin> has key, store {
    id: UID,  
    rewards_per_second: u64,
    start_timestamp: u64,
    last_reward_timestamp: u64, 
    accrued_rewards_per_share: u256,
    balance_stake_coin: Balance<StakeCoin>,
    balance_reward_coin: Balance<RewardCoin>,
    stake_coin_decimal_factor: u64,
    owned_by: ID
 }
```

* **rewards\_per\_second** - Amount of RewardCoin to give to stakers per second.
* **start\_timestamp** - The timestamp in seconds that this farm will start distributing rewards.
* &#x20;**last\_reward\_timestamp -** Last timestamp that the farm was updated.&#x20;
* **accrued\_rewards\_per\_share -** Total amount of rewards per share distributed by this farm.  &#x20;
* **balance\_stake\_coin -** StakeCoin deposited in this farm.&#x20;
* &#x20;**balance\_reward\_coin -** RewardCoin deposited in this farm.
* **stake\_coin\_decimal\_factor -** The decimal scalar of the StakeCoin.&#x20;
* **owned\_by -** The \`sui::object::ID\` of the OwnerCap that "owns" this farm.

## Interface

### <mark style="color:blue;">new\_cap</mark>

**It creates an OwnerCap. It is used to provide admin capabilities to the holder.**

```rust
public fun new_cap(ctx: &mut TxContext): OwnerCap<FarmWitness>
```

* **@return** OwnerCap.

### <mark style="color:blue;">new\_farm</mark>

**It creates an Farm\<StakeCoin, RewardCoin>. The `start_timestamp` is in seconds.**

```rust
public fun new_farm<StakeCoin, RewardCoin>(
    cap: &mut OwnerCap<FarmWitness>,
    stake_coin_metadata: &CoinMetadata<StakeCoin>,
    c: &Clock,
    rewards_per_second: u64,
    start_timestamp: u64,
    ctx: &mut TxContext
 ): Farm<StakeCoin, RewardCoin>
```

* **@param cap:** An OwnerCap that will be assigned the admin rights of the newly created Farm.
* **@param stake\_coin\_metadata:** The `sui::coin::CoinMetadata` of the `StakeCoin`.
* **@param c:** The `sui::clock::Clock` shared object.
* **@param rewards\_per\_second:**  The amount of `RewardCoin` the farm can distribute to stakers.
* **@param start\_timestamp:** The timestamp in seconds that the farm is allowed to start distributing rewards.
* **@return** Farm\<StakeCoin, RewardCoin>.

### <mark style="color:blue;">new\_account</mark>

**It creates an Account\<StakeCoin, RewardCoin>. It is used to keep track of the holder's deposit and rewards.**

```rust
public fun new_account<StakeCoin, RewardCoin>(self: &Farm<StakeCoin, RewardCoin>, ctx: &mut TxContext): Account<StakeCoin, RewardCoin>
```

* **@param cap:** self The Farm\<StakeCoin, RewardCoin>.&#x20;
* **@return** Account\<StakeCoin, RewardCoin>.

### <mark style="color:blue;">rewards\_per\_second</mark>

**Returns the `self` rewards per second.**&#x20;

```rust
public fun rewards_per_second<StakeCoin, RewardCoin>(self: &Farm<StakeCoin, RewardCoin>): u64
```

* **@param cap:** self The Farm\<StakeCoin, RewardCoin>.&#x20;
* **@return** u64.

### <mark style="color:blue;">start\_timestamp</mark>

**Returns the `self` start timestamp.**

```rust
public fun start_timestamp<StakeCoin, RewardCoin>(self: &Farm<StakeCoin, RewardCoin>): u64
```

* **@param cap:** self The Farm\<StakeCoin, RewardCoin>.&#x20;
* **@return** u64.

### <mark style="color:blue;">last\_reward\_timestamp</mark>

**Returns the `self` last reward timestamp.**

```rust
public fun last_reward_timestamp<StakeCoin, RewardCoin>(self: &Farm<StakeCoin, RewardCoin>): u64
```

* **@param cap:** self The Farm\<StakeCoin, RewardCoin>.&#x20;
* **@return** u64.

### <mark style="color:blue;">accrued\_rewards\_per\_share</mark>

**Returns the `self` accrued rewards per share.**

```rust
public fun accrued_rewards_per_share<StakeCoin, RewardCoin>(self: &Farm<StakeCoin, RewardCoin>): u256
```

* **@param cap:** self The Farm\<StakeCoin, RewardCoin>.&#x20;
* **@return** u256.

### <mark style="color:blue;">balance\_stake\_coin</mark>

**Returns the `self` stake coin balance.**

```rust
public fun balance_stake_coin<StakeCoin, RewardCoin>(self: &Farm<StakeCoin, RewardCoin>): u64
```

* **@param cap:** self The Farm\<StakeCoin, RewardCoin>.&#x20;
* **@return** u64.

### <mark style="color:blue;">balance\_reward\_coin</mark>

**Returns the `self` reward coin balance.**

```rust
public fun balance_reward_coin<StakeCoin, RewardCoin>(self: &Farm<StakeCoin, RewardCoin>): u64
```

* **@param cap:** self The Farm\<StakeCoin, RewardCoin>.&#x20;
* **@return** u64.

### <mark style="color:blue;">stake\_coin\_decimal\_factor</mark>

**Returns the `self` reward coin decimal scalar.**

```rust
public fun stake_coin_decimal_factor<StakeCoin, RewardCoin>(self: &Farm<StakeCoin, RewardCoin>): u64
```

* **@param cap:** self The Farm\<StakeCoin, RewardCoin>.&#x20;
* **@return** u64.

### <mark style="color:blue;">owned\_by</mark>

**Returns the `self` reward coin decimal scalar.**

```rust
public fun owned_by<StakeCoin, RewardCoin>(self: &Farm<StakeCoin, RewardCoin>): ID
```

* **@param cap:** self The Farm\<StakeCoin, RewardCoin>.&#x20;
* **@return** ID.

### <mark style="color:blue;">amount</mark>

**Returns the `account` staked amount.**

```rust
public fun amount<StakeCoin, RewardCoin>(account: &Account<StakeCoin, RewardCoin>): u64
```

* **@param cap:** self The Farm\<StakeCoin, RewardCoin>.&#x20;
* **@return** u64.

### <mark style="color:blue;">reward\_debt</mark>

**Returns the `account` reward debt.**

```rust
public fun reward_debt<StakeCoin, RewardCoin>(account: &Account<StakeCoin, RewardCoin>): u256
```

* **@param cap:** self The Farm\<StakeCoin, RewardCoin>.&#x20;
* **@return** u256.

### <mark style="color:blue;">pending\_rewards</mark>

**Returns the `account`'s pending rewards.** **It does not update the state.**

```rust
public fun pending_rewards<StakeCoin, RewardCoin>(
    farm: &Farm<StakeCoin, RewardCoin>, 
    account: &Account<StakeCoin, RewardCoin>,
    c: &Clock, 
 ): u64
```

* **@param** **farm:** The Farm\<StakeCoin, RewardCoin>.
* **@param** **account:** The Account associated with the `farm`.
* **@param** **c:** The `sui::clock::Clock` shared object.
* **@return** u64.

### <mark style="color:blue;">add\_rewards</mark>

**It allows anyone to add rewards to the `farm`.**

```rust
public fun add_rewards<StakeCoin, RewardCoin>(self: &mut Farm<StakeCoin, RewardCoin>, c: &Clock, reward: Coin<RewardCoin>)
```

* **@param** **self:** The Farm\<StakeCoin, RewardCoin>.
* **@param** **c:** The `sui::clock::Clock` shared object.
* **@param** **reward:** The RewardCoin to be added to the `self`.&#x20;

### <mark style="color:blue;">stake</mark>

**Allows a user to stake `stake_coin` in the `farm`. On the first deposits the returned Coin will have a value of zero. So make sure to destroy it.**

```rust
public fun stake<StakeCoin, RewardCoin>(
    farm: &mut Farm<StakeCoin, RewardCoin>, 
    account: &mut Account<StakeCoin, RewardCoin>,
    stake_coin: Coin<StakeCoin>, 
    c: &Clock,
    ctx: &mut TxContext
): Coin<RewardCoin>
```

* **@param** **farm:** The Farm\<StakeCoin, RewardCoin>.
* **@param** **account:** The Account associated with the `farm`.
* **@param** **stake\_coin:** The StakeCoin to stake in the `farm`.
* **@param c:** The `sui::clock::Clock` shared object.
* **@return Coin.** It gives any pending rewards to the user.

**Aborts**

* If the `account` does not belong to the `farm`.

### <mark style="color:blue;">unstake</mark>

**Allows a user to unstake his `stake_coin` in the `farm`.**

```rust
public fun unstake<StakeCoin, RewardCoin>(
    farm: &mut Farm<StakeCoin, RewardCoin>, 
    account: &mut Account<StakeCoin, RewardCoin>,
    amount: u64,
    c: &Clock,
    ctx: &mut TxContext
 ): (Coin<StakeCoin>, Coin<RewardCoin>)
```

* **@param** **farm:** The Farm\<StakeCoin, RewardCoin>.
* **@param** **account:** The Account associated with the `farm`.
* **@param amount**: The amount of StakeCoin to remove from the `farm`.
* **@param c:** The `sui::clock::Clock` shared object.
* **@return** Coin. The staked Coin.&#x20;
* **@return Coin.** It gives any pending rewards to the user.

**Aborts**

* `amount` is larger than the `account.amount`. If the user tries to unstake more than he has staked.

### <mark style="color:blue;">destroy\_zero\_account</mark>

**Destroys the `account`.**

```rust
public fun destroy_zero_account<StakeCoin, RewardCoin>(account: Account<StakeCoin, RewardCoin>)
```

* **@param** **account:** The Account associated with the `farm`.

**Aborts**

* `account` has an amount greater than zero.

### <mark style="color:blue;">update\_rewards\_per\_second</mark>

**Updates the rewards per second of the `farm`.**

```rust
public fun update_rewards_per_second<StakeCoin, RewardCoin>(
    farm: &mut Farm<StakeCoin, RewardCoin>,     
    cap: &OwnerCap<FarmWitness>, 
    new_rewards_per_second: u64,
    c: &Clock
)
```

* **@param** **farm:** The Farm\<StakeCoin, RewardCoin>.
* **@param** **cap:** The OwnerCap that "owns" the `farm`.
* **@param new\_rewards\_per\_second**: The new amount of RewardCoin the `farm` will give.
* **@param c:** The `sui::clock::Clock` shared object.

**Aborts**

* `cap` does not own the `farm`.

### <mark style="color:blue;">destroy\_zero\_farm</mark>

**Destroys the `farm`.**

```rust
public fun destroy_zero_farm<StakeCoin, RewardCoin>(farm: Farm<StakeCoin, RewardCoin>, cap: &OwnerCap<FarmWitness>)
```

* **@param** **farm:** The Farm\<StakeCoin, RewardCoin>.
* **@param** **cap:** The OwnerCap that "owns" the `farm`.

**Aborts**

* `cap` does not own the `farm`.
* `farm` still has staked coins.
* `farm` still has reward coins.

### <mark style="color:blue;">borrow\_mut\_uid</mark>

**Returns a mutable reference of the `farm`'s `sui::object::UI to allow the cap` owner to extend its functionalities.**

```rust
public fun borrow_mut_uid<StakeCoin, RewardCoin>(farm: &mut Farm<StakeCoin, RewardCoin>, cap: &OwnerCap<FarmWitness>): &mut UID
```

* **@param** **farm:** The Farm\<StakeCoin, RewardCoin>.
* **@param** **cap:** The OwnerCap that "owns" the `farm`.
* **@return** \&mut UID.

**Aborts**

* `cap` does not own the `farm`.


# Fund

It is a utility struct to easily know how many shares to issue/burn based on an underlying amount.

## Structs

### <mark style="color:blue;">**Account**</mark>

```rust
struct Fund has store, copy, drop {
    shares: u128,
    underlying: u128
 }
```

* **shares** - The amount of shares issued based on the underlying amount.
* **underlying** - The amount of assets in the fund.

## Interface

### <mark style="color:blue;">empty</mark>

**Creates an empty Fund.**

```rust
public fun empty(): Fund
```

* **@return** Fund.

### <mark style="color:blue;">underlying</mark>

**Returns the amount of underlying in the `self`.**

```rust
public fun underlying(self: &Fund): u64
```

* **@param self:** A Fund.
* **@return** u64. The amount of underlying.

### <mark style="color:blue;">shares</mark>

**Returns the amount of shares in the `self`.**

```rust
public fun shares(self: &Fund): u64
```

* **@param self:** A Fund.
* **@return** u64. The amount of shares.

### <mark style="color:blue;">to\_shares</mark>

**Returns the number of shares the `self` would issue if more `underlying` was deposited in it.**

```rust
public fun to_shares(self: &Fund, underlying: u64, round_up: bool): u64
```

* **@param self:** A Fund.
* **@param underlying:** The amount of underlying that the caller intends to add to the `self`.
* **@param round\_up:** If true we would round up the returned value.
* **@return u64**. The amount of shares the fund would issue.

### <mark style="color:blue;">to\_underlying</mark>

**Returns the number of shares the `self` would issue if more `underlying` was deposited in it.**

```rust
public fun to_underlying(rebase: &Fund, shares: u64, round_up: bool): u64
```

* **@param self:** A Fund.
* **@param shares:** The amount of shares that the caller intends to burn.
* **@param round\_up:** If true we would round up the returned value.
* **@return u64**. The amount underlying the fund would release.

### <mark style="color:blue;">sub\_shares</mark>

This function reduces the amount of underlying and shares in the fund.

```rust
public fun sub_shares(self: &mut Fund, shares: u64, round_up: bool): u64
```

* **@param self:** A Fund.
* **@param shares:** The amount of shares that the caller intends to burn.
* **@param round\_up:** If true we would round up the returned value.
* **@return u64**. The amount underlying the `shares` were worth.

### <mark style="color:blue;">add\_underlying</mark>

Adds `underlying` to the `self` and returns the additional shares issued. This function increases the amount of underlying and shares in the fund.

```rust
public fun add_underlying(rebase: &mut Fund, underlying: u64, round_up: bool): u64
```

* **@param self:** A Fund.
* **@param underlying:** The amount of underlying to deposit in the `self`.
* **@param round\_up:** If true we would round up the returned value.
* **@return u64.** The amount of shares the fund issued.

### <mark style="color:blue;">sub\_underlying</mark>

Removes `underlying` from the `self` and returns the burned shares. This function reduces the amount of underlying and shares in the fund.

```rust
public fun sub_underlying(rebase: &mut Fund, underlying: u64, round_up: bool): u64
```

* **@param self:** A Fund.
* **@param underlying:** The amount of underlying to remove from the `self`.
* **@param round\_up:** If true we would round up the returned value.
* **@return u64.** The amount of shares the fund burned.

### <mark style="color:blue;">add\_profit</mark>

Adds profits to the underlying. This is to add profits to the fund.

```rust
public fun add_profit(rebase: &mut Fund, profit: u64)
```

* **@param self:** A Fund.
* **@param profit:** The amount of underlying to add as profit to `self.underlying`.


# Linear Vesting Wallet

Creates a Wallet that allows the holder to claim coins linearly.

## Structs

### <mark style="color:blue;">**Wallet**</mark>

```rust
  struct Wallet<phantom T> has key, store {
    id: UID,
    balance: Balance<T>,
    start: u64,
    released: u64,
    duration: u64
  }
```

* **balance** - Amount of tokens to give to the holder of the wallet.&#x20;
* **start** - The holder can start claiming tokens after this date.
* **released -** Total amount of \`Coin\<T>\` released so far.&#x20;
* **duration -** The duration of the vesting.

## Interface

### <mark style="color:blue;">new</mark>

**It creates a new Wallet.**

```rust
public fun new<T>(token: Coin<T>, c: &Clock, start: u64, duration: u64, ctx: &mut TxContext): Wallet<T>
```

* **@param token:** A `sui::coin::Coin<T>`.
* **@param c:** The shared object `sui::clock::Clock`
* **@param start:** Dictate when the vesting schedule starts.
* **@param duration**: Dictate when the vesting schedule starts.
* **@return** Wallet.

**Aborts**

* `start` is in the past.

### <mark style="color:blue;">balance</mark>

**Returns the current amount of tokens in the `self`.**

```rust
public fun balance<T>(self: &Wallet<T>): u64
```

* **@param self:** A Wallet.
* **@return** u64.

### <mark style="color:blue;">start</mark>

**Returns the vesting schedule start time.**&#x20;

```rust
public fun start<T>(self: &Wallet<T>): u64
```

* **@param self:** A Wallet.
* **@return** u64.

### <mark style="color:blue;">released</mark>

**Returns the current amount of total released tokens from the `self`.**

```rust
public fun released<T>(self: &Wallet<T>): u64
```

* **@param self:** A Wallet.
* **@return** u64.

### <mark style="color:blue;">duration</mark>

**Returns the duration of the vesting schedule.**

```rust
public fun duration<T>(self: &Wallet<T>): u64
```

* **@param self:** A Wallet.
* **@return** u64.

### <mark style="color:blue;">vesting\_status</mark>

**Returns the current amount of coins available to the caller based on the linear schedule.**

```rust
public fun vesting_status<T>(self: &Wallet<T>, c: &Clock): u64
```

* **@param self:** A Wallet.
* **@param c:**  The `sui::clock::Clock` shared object.
* **@return** u64. A portion of the amount that can be claimed by the user.

### <mark style="color:blue;">claim</mark>

**Releases the current amount of coins available to the caller based on the linear schedule.**

```rust
public fun claim<T>(self: &mut Wallet<T>, c: &Clock, ctx: &mut TxContext): Coin<T>
```

* **@param self:** A Wallet.
* **@param c:** The `sui::clock::Clock` shared object.
* **@return** Coin.

### <mark style="color:blue;">destroy\_zero</mark>

**Destroys a Wallet with no balance.**

```rust
public fun destroy_zero<T>(self: Wallet<T>)
```

* **@param self:** A Wallet.


# Linear Clawback Vesting Wallet

Creates a Wallet that allows the holder to claim coins linearly. The holder of the `OwnerCap` can reclaim any locked coins back. &#x20;

## Structs

### <mark style="color:blue;">**Wallet**</mark>

```rust
  struct Wallet<phantom T> has key, store {
    id: UID,
    balance: Balance<T>,
    start: u64,
    released: u64,
    duration: u64,
    clawbacked: u64
  }
```

* **balance** - Amount of tokens to give to the holder of the wallet.&#x20;
* **start** - The holder can start claiming tokens after this date.
* **released -** Total amount of \`Coin\<T>\` released so far.&#x20;
* **duration -** The duration of the vesting.
* **clawbacked -** The amount of tokens recalled.&#x20;

## Interface

### <mark style="color:blue;">new</mark>

It creates a new Wallet and two capabilities for the recipient and the clawback owner.

```rust
  public fun new<T>(
    token: Coin<T>, 
    c: &Clock, 
    start: u64, 
    duration: u64, 
    ctx: &mut TxContext
  ): (OwnerCap<ClawBackWitness>, OwnerCap<RecipientWitness>, Wallet<T>)
```

* **@param token:** A `sui::coin::Coin<T>`.
* **@param c:** The shared object `sui::clock::Clock`
* **@param start:** Dictate when the vesting schedule starts.
* **@param duration**: Dictate when the vesting schedule starts.
* **@return OwnerCap<**&#x43;lawBackWitnes&#x73;**>:** The holder of this capability can claw back the coins.
* **@return OwnerCap<**&#x52;ecipientWitnes&#x73;**>:** The holder of this capability can claim tokens according to the linear schedule.
* **@return** Wallet.

**Aborts**

* `start` is in the past.

### <mark style="color:blue;">share</mark>

**It shares the Wallet with the network.**

```rust
public fun share<T>(self: Wallet<T>)
```

* **@param self:** A Wallet.

### <mark style="color:blue;">balance</mark>

**Returns the current amount of tokens in the `self`.**

```rust
public fun balance<T>(self: &Wallet<T>): u64
```

* **@param self:** A Wallet.
* **@return** u64.

### <mark style="color:blue;">start</mark>

**Returns the vesting schedule start time.**&#x20;

```rust
public fun start<T>(self: &Wallet<T>): u64
```

* **@param self:** A Wallet.
* **@return** u64.

### <mark style="color:blue;">released</mark>

**Returns the current amount of total released tokens from the `self`.**

```rust
public fun released<T>(self: &Wallet<T>): u64
```

* **@param self:** A Wallet.
* **@return** u64.

### <mark style="color:blue;">duration</mark>

**Returns the duration of the vesting schedule.**

```rust
public fun duration<T>(self: &Wallet<T>): u64
```

* **@param self:** A Wallet.
* **@return** u64.

### <mark style="color:blue;">clawbacked</mark>

**Returns the number of tokens that were claw-backed by the holder of OwnerCap from the `self`.**

```rust
public fun clawbacked<T>(self: &Wallet<T>): u64
```

* **@param self:** A Wallet.
* **@return** u64.

### <mark style="color:blue;">vesting\_status</mark>

**Returns the current amount of coins available to the caller based on the linear schedule.**

```rust
public fun vesting_status<T>(self: &Wallet<T>, c: &Clock): u64
```

* **@param self:** A Wallet.
* **@param c:**  The `sui::clock::Clock` shared object.
* **@return** u64. A portion of the amount that can be claimed by the user.

### <mark style="color:blue;">claim</mark>

**Releases the current amount of coins available to the caller based on the linear schedule.**

```rust
public fun claim<T>(self: &mut Wallet<T>, cap: &OwnerCap<RecipientWitness>, c: &Clock, ctx: &mut TxContext): Coin<T>
```

* **@param self:** A Wallet.
* **@param cap:** The recipient capability that owns the `self`.
* **@param c:** The `sui::clock::Clock` shared object.
* **@return** Coin.

**Aborts**

* `cap` does not own the `self`.

### <mark style="color:blue;">clawback</mark>

**Returns all unreleased coins to the `cap` holder.**

```rust
public fun clawback<T>(self: &mut Wallet<T>, cap: OwnerCap<ClawBackWitness>, c: &Clock, ctx: &mut TxContext): Coin<T>
```

* **@param self:** A Wallet.
* **@param cap:** The clawback capability that owns the `self`.
* **@param c:** The `sui::clock::Clock` shared object.
* **@return** Coin.

**Aborts**

* `cap` does not own the `self`.

### <mark style="color:blue;">destroy\_zero</mark>

**Destroys a Wallet with no balance.**

```rust
public fun destroy_zero<T>(self: Wallet<T>)
```

* **@param self:** A Wallet.


# Vesting

A utility module to provide virtual implementations of vesting schedules.

## Interface

### <mark style="color:blue;">new</mark>

**Calculates the amount that has already vested.**

```rust
public fun linear_vested_amount(start: u64, duration: u64, balance: u64, already_released: u64, timestamp: u64): u64
```

* **@param start:** The beginning of the vesting schedule.
* **@param duration:** The duration of the schedule.
* **@param balance:** The current amount of tokens in the wallet.
* **@param already\_released:** The total amount of tokens released.
* **@param timestamp:** The current time in milliseconds.
* **@return u64**. The vested amount.


# Governance


# DAO

It allows anyone to create a DAO, submit proposals, and execute actions on-chain.

* Proposals are voted by depositing coins. 1 Coin is 1 Vote.
* DAOs only supports 1 Coin type

The idea is to send capabilities to the DAO via `sui::transfer::transfer`.

* Users can borrow the capabilities via successful proposals.
* Developers must write custom modules that pass the `AuthorizedWitness` to borrow the capability when executing proposals.
* DAO relies on open-source code to make sure the Modules that are executing proposals do what they agreed to do.

<img src="https://3796248018-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FKUfXlMmOziV2mgIVI8u1%2Fuploads%2FhBWSk5KuwT8SITPsm7q7%2Ffile.excalidraw.svg?alt=media&amp;token=5ea8b7bd-0267-4893-8eac-7e62944e3794" alt="Proposal Life Cycle" class="gitbook-drawing">

A Successful Proposal requires:

* for\_votes > agaisnt\_votes
* for\_votes / total\_votes > quorum rate
* for\_votes >= min\_quorum\_votes

<img src="https://3796248018-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FKUfXlMmOziV2mgIVI8u1%2Fuploads%2FkbFiQvxsLstpN6AyGf26%2Ffile.excalidraw.svg?alt=media&amp;token=71dd74e9-d564-4082-85ee-8975b1567b54" alt="Vote Life Cycle" class="gitbook-drawing">

Each Vote struct belongs to a specific Proposal via the `vote.proposal_id` field.&#x20;

* A voter can revoke his vote and recover his `sui::coin::Coin` if the Proposal is active.
* A voter can recover his coins once the voting period ends.
* A Vote created from ProposalA cannot be used in ProposalB.

## Proposal States

### <mark style="color:blue;">**Pending:**</mark>**&#x20;Newly created proposal**<mark style="color:blue;">**.**</mark>

### <mark style="color:blue;">**Active:**</mark>**&#x20;Proposal is open for voting.**&#x20;

### <mark style="color:blue;">**Defeated:**</mark>**&#x20;The proposal did not pass.**&#x20;

### <mark style="color:blue;">**Agree:**</mark>**&#x20;The proposal passed**<mark style="color:blue;">**.**</mark>

### <mark style="color:blue;">**Queued:**</mark> The proposal was successful and now it is in a queue to be executed if it is executable. This gives time for people to adjust to the upcoming change.

### <mark style="color:blue;">**Executable:**</mark>**&#x20;It can be executed.**

### <mark style="color:blue;">**Finished:**</mark>**&#x20;The proposal has been executed.**

## Structs

### <mark style="color:blue;">**DAO**</mark>

```rust
struct Dao<phantom OTW> has key, store {
    id: UID,
    voting_delay: u64, 
    voting_period: u64,
    voting_quorum_rate: u64,
    min_action_delay: u64, 
    min_quorum_votes: u64,
    treasury: ID,
    coin_type: TypeName,
    admin_id: ID
 }
```

* **voting\_delay** - Voters must wait \`voting\_delay\` in milliseconds to start voting on new proposals.
* **voting\_period**- The voting duration of a proposal.
* **voting\_quorum\_rate**&#x20;
  * The minimum quorum rate to pass a proposal.&#x20;
  * If 50% votes are needed, then the voting\_quorum\_rate should be 5\_00\_000\_000.
  * It should be between (0, 1e9].
* **min\_action\_delay -** How long the proposal should wait before it can be executed (in milliseconds).
* **min\_quorum\_votes -** Minimum amount of votes for a Proposal to be successful even if it is higher than the against votes and the quorum rate.
* **treasury** - The \`sui::object::ID\` of the Treasury.
* **coin\_type -** The CoinType that can vote on this DAO's proposal.
* **admin\_id -** The DaoAdmin.

### <mark style="color:blue;">**Proposal**</mark>

```rust
  struct Proposal<phantom DaoWitness: drop> has key, store {
    id: UID,
    proposer: address,
    start_time: u64,
    end_time: u64,
    for_votes: u64,
    against_votes: u64,
    eta: u64,  
    action_delay: u64, 
    quorum_votes: u64, 
    voting_quorum_rate: u64, 
    hash: String,
    authorized_witness: Option<TypeName>, 
    capability_id: Option<ID>,
    coin_type: TypeName
  }
```

* **proposer -** The user who created the proposal.
* **start\_time -** When the users can start voting.
* **end\_time -** Users can no longer vote after the `end_time`.
* **for\_votes-** How many votes support the Proposal.
* **agaisnt\_votes-** How many votes disagree with the Proposal.
* **eta**
  * It is calculated by adding `end_time` and `action_delay`. It assumes the Proposal will be executed as soon as possible.
  * Estimated Time of Arrival.
* **action\_delay**
  * Time Delay between a successful Proposal `end_time` and when it is allowed to be executed.
  * It allows users who disagree with the proposal to make changes.
* **quorum\_votes -** The minimum amount of `for_votes` for a Proposal to pass.
* **voting\_quorum\_rate -** The minimum support rate for a Proposal to pass.
* **hash -** The hash of the description of this proposal.&#x20;
* **authorized\_witness**
  * The Witness that is allowed to call execute.
  * Not executable proposals do not have an authorized\_witness.
* **capability\_id**
  * The `sui::object::ID` that this proposal needs to execute.
  * Not all proposals are executable.
* **coin\_type -** The CoinType of the DAO

### <mark style="color:blue;">**Capability Request - Hot Potato**</mark>

```rust
  struct CapabilityRequest {  
    capability_id: ID,
    dao_id: ID
  }
```

* **capability\_id -** The `sui::object::ID` of the borrowed Capability.
* **dao\_id:** The DAO that owns said Capability.

### <mark style="color:blue;">**Vote**</mark>

```rust
  struct Vote<phantom DaoWitness: drop, phantom CoinType> has  key, store {
    id: UID,
    balance: Balance<CoinType>,
    proposal_id: ID,
    end_time: u64,
    agree: bool
  } 
```

* **balance -** The amount of Coin the user has used to vote for the Proposal.
* **proposal\_id:** The `sui::object::ID` of the Proposal.
* **end\_time:**
  * The end\_time of the Proposal.
  * User can redeem back his `balance` after this timestamp.
* **agree -** If it is a for or against vote.

## Interface

### <mark style="color:blue;">new</mark>

**It creates a DAO with Treasury.**&#x20;

```rust
public fun new<OTW: drop, CoinType: drop>(
    otw: OTW, 
    voting_delay: u64, 
    voting_period: u64, 
    voting_quorum_rate: u64, 
    min_action_delay: u64, 
    min_quorum_votes: u64,
    ctx: &mut TxContext
): (Dao<OTW>, DaoTreasury<OTW>)
```

* **@param otw:** A One Time Witness to ensure that the Dao is unique.
* **@param voting\_delay:** The minimum waiting period between the creation of a proposal and the voting period.
* **@param voting\_period:** The duration of the voting period.
* **@param voting\_quorum\_rate:** The minimum percentage of votes to pass a proposal. E.g. for\_votes / total\_votes. keep in mind (0, 1\_000\_000\_000]
* **@param min\_action\_delay:** The minimum delay required to execute a proposal after it passes.
* **@param min\_quorum\_votes:** The minimum votes required for a Proposal to be successful.
* **@return** Dao\<OTW>
* **@return** Treasury\<OTW>

**Aborts**

* `otw` is not a One Time Witness.
* `voting_quorum_rate` is larger than 1\_000\_000\_000
* `voting_quorum_rate` is zero.

### <mark style="color:blue;">voting\_delay</mark>

**Returns the minimum voting delay of the Dao.**

```rust
public fun voting_delay<DaoWitness>(self: &Dao<DaoWitness>): u64
```

* **@param self:** a Dao
* **@return** u64

### <mark style="color:blue;">voting\_period</mark>

**Returns the minimum voting period of the Dao.**

```rust
public fun voting_period<DaoWitness>(self: &Dao<DaoWitness>): u64
```

* **@param self:** a Dao
* **@return** u64

### <mark style="color:blue;">dao\_voting\_quorum\_rate</mark>

**Returns the minimum voting quorum rate of the Dao.**

```rust
public fun dao_voting_quorum_rate<DaoWitness>(self: &Dao<DaoWitness>): u64
```

* **@param self:** a Dao
* **@return** u64

### <mark style="color:blue;">min\_action\_delay</mark>

**Returns the minimum action delay of the Dao.**

```rust
public fun min_action_delay<DaoWitness>(self: &Dao<DaoWitness>): u64
```

* **@param self:** a Dao
* **@return** u64

### <mark style="color:blue;">min\_quorum\_votes</mark>

**Returns the minimum votes required to pass a proposal.**

```rust
public fun min_quorum_votes<DaoWitness>(self: &Dao<DaoWitness>): u64
```

* **@param self:** a Dao
* **@return** u64

### <mark style="color:blue;">treasury</mark>

**Returns the `sui::object::id` of the Dao wrapped in an `std::option`.**

```rust
public fun treasury<DaoWitness>(self: &Dao<DaoWitness>): ID
```

* **@param self:** a Dao
* **@return** ID

### <mark style="color:blue;">dao\_coin\_type</mark>

**Returns the `std::type_name` of the Dao's coin type. This is the Coin that can be used to vote on proposals.**

```rust
public fun dao_coin_type<DaoWitness>(self: &Dao<DaoWitness>): TypeName
```

* **@param self:** a Dao
* **@return** TypeName

### <mark style="color:blue;">admin</mark>

**Returns the `sui::object::ID` of Dao's admin capability. It is used to update the Dao's settings and transfer coins from the treasury.**

```rust
public fun admin<DaoWitness>(self: &Dao<DaoWitness>): ID
```

* **@param self:** a Dao
* **@return** ID

### <mark style="color:blue;">proposer</mark>

**Returns the address of the user who created the proposal.**

```rust
public fun proposer<DaoWitness: drop>(proposal: &Proposal<DaoWitness>): address
```

* **@param proposal:** The Proposal
* **@return** address

### <mark style="color:blue;">start\_time</mark>

**Returns start timestamp of the `proposal`.**

```rust
public fun start_time<DaoWitness: drop>(proposal: &Proposal<DaoWitness>): u64
```

* **@param proposal:** The Proposal.
* **@return** u64

### <mark style="color:blue;">end\_time</mark>

**Returns end timestamp of the `proposal`.**

```rust
public fun end_time<DaoWitness: drop>(proposal: &Proposal<DaoWitness>): u64
```

* **@param proposal:** The Proposal.
* **@return** u64

### <mark style="color:blue;">for\_votes</mark>

**Returns the number of votes that support this `proposal`.**

```rust
public fun for_votes<DaoWitness: drop>(proposal: &Proposal<DaoWitness>): u64
```

* **@param proposal:** The Proposal.
* **@return** u64

### <mark style="color:blue;">agaisnt\_votes</mark>

**Returns the number of votes against this `proposal`.**

```rust
public fun against_votes<DaoWitness: drop>(proposal: &Proposal<DaoWitness>): u64
```

* **@param proposal:** The {Proposal}.
* **@return** u64

### <mark style="color:blue;">eta</mark>

**Returns an estimation of when a successful proposal  will be executed.**

```rust
public fun eta<DaoWitness: drop>(proposal: &Proposal<DaoWitness>): u64
```

* **@param proposal:** The Proposal.
* **@return** u64

### <mark style="color:blue;">action\_delay</mark>

**Returns the minimum time a successful `proposal` has to wait before it can be executed.**

```rust
public fun action_delay<DaoWitness: drop>(proposal: &Proposal<DaoWitness>): u64
```

* **@param proposal:** The Proposal.
* **@return** u64

### <mark style="color:blue;">quorum\_votes</mark>

**Returns the minimum number of votes required for a successful `proposal`.**

```rust
public fun quorum_votes<DaoWitness: drop>(proposal: &Proposal<DaoWitness>): u64
```

* **@param proposal:** The Proposal.
* **@return** u64

### <mark style="color:blue;">voting\_quorum\_rate</mark>

**Returns the minimum rate for a `proposal` to pass. Formula: for\_votes / total\_votes. 100% is represented by 1\_000\_000\_000.**

```rust
public fun voting_quorum_rate<DaoWitness: drop>(proposal: &Proposal<DaoWitness>): u64
```

* **@param proposal:** The Proposal.
* **@return** u64

### <mark style="color:blue;">hash</mark>

**Returns the hash of the description of the `proposal`.**

```rust
public fun hash<DaoWitness: drop>(proposal: &Proposal<DaoWitness>): String
```

* **@param proposal:** The Proposal.
* **@return** vector\<u8>

### <mark style="color:blue;">authorized\_witness</mark>

**Returns the `std::type_name::TypeName` of the Witness that can execute the `proposal`.**

```rust
public fun authorized_witness<DaoWitness: drop>(proposal: &Proposal<DaoWitness>): Option<TypeName>
```

* **@param proposal:** The Proposal.
* **@return** TypeName

### <mark style="color:blue;">capability\_id</mark>

**Returns the `sui::object::ID` of the Capability that the `proposal` requires to execute.**

```rust
public fun capability_id<DaoWitness: drop>(proposal: &Proposal<DaoWitness>): Option<ID>
```

* **@param proposal:** The Proposal.
* **@return** Option\<ID>

### <mark style="color:blue;">coin\_type</mark>

**Returns the CoinType of the proposal. Votes must use this CoinType.**

```rust
public fun coin_type<DaoWitness: drop>(proposal: &Proposal<DaoWitness>): TypeName
```

* **@param proposal:** The Proposal.
* **@return** TypeName

### <mark style="color:blue;">balance</mark>

**Returns the number of votes.**

```rust
public fun balance<DaoWitness: drop, CoinType>(vote: &Vote<DaoWitness,  CoinType>): u64
```

* **@param vote:** The Vote\<DaoWitness, CoinType>.
* **@return** u64

### <mark style="color:blue;">proposal\_id</mark>

**Returns the Proposal `sui::object::ID`.**

```rust
public fun proposal_id<DaoWitness: drop, CoinType>(vote: &Vote<DaoWitness,  CoinType>): ID
```

* **@param vote:** The Vote\<DaoWitness, CoinType>.
* **@return** ID

### <mark style="color:blue;">vote\_end\_time</mark>

**Returns the ending timestamp of the proposal. Users can withdraw their deposited coins afterward.**

```rust
public fun vote_end_time<DaoWitness: drop, CoinType>(vote: &Vote<DaoWitness,  CoinType>): u64
```

* **@param vote:** The Vote\<DaoWitness, CoinType>.
* **@return** u64

### <mark style="color:blue;">agree</mark>

**Returns if it is a for or against vote.**

```rust
public fun agree<DaoWitness: drop, CoinType>(vote: &Vote<DaoWitness,  CoinType>): bool
```

* **@param vote:** The Vote\<DaoWitness, CoinType>.
* **@return** bool

### <mark style="color:blue;">state</mark>

**Returns the `proposal` state.**

```rust
public fun agree<DaoWitness: drop, CoinType>(vote: &Vote<DaoWitness,  CoinType>): bool
```

* **@param vote:** The Vote\<DaoWitness, CoinType>.
* **@return** u8

### <mark style="color:blue;">propose</mark>

**Creates a Proposal.**

```rust
public fun propose<DaoWitness: drop>(
    dao: &mut Dao<DaoWitness>,
    c: &Clock,
    authorized_witness: Option<TypeName>,
    capability_id: Option<ID>,
    action_delay: u64,
    quorum_votes: u64,
    hash: String,
    ctx: &mut TxContext    
 ): Proposal<DaoWitness>
```

* **@param** dao: The Dao.
* **@param c:** The shared `sui::clock::Clock` object.
* **@param authorized\_witness:** The Witness required to execute this proposal.
* **@param capability\_id:** The `sui::object::ID` of the Capability that this proposal needs to be executed. If a proposal is not executable pass `option::none()`
* **@param action\_delay:** The minimum waiting period for a successful Proposal to be executed.
* **@param quorum\_votes:** The minimum waiting period for a successful Proposal to be executed.
* **@param hash:** The hash of the proposal's description.
* **@return** Proposal\<DaoWitness>

**Abort**

* `action_delay` < `dao.min_action_delay`.
* `quorum_votes` < `dao.min_quorum_votes`.
* `hash` is empty.

### <mark style="color:blue;">cast\_vote</mark>

**Allows a user to use coins to vote for a `proposal`, either against or for depending on `agree`.**

```rust
  public fun cast_vote<DaoWitness: drop, CoinType>(
    proposal: &mut Proposal<DaoWitness>,
    c: &Clock,
    stake: Coin<CoinType>,
    agree: bool,
    ctx: &mut TxContext
  ): Vote<DaoWitness, CoinType>
```

* **@param proposal:** The proposal the user is voting for.
* **@param c:** The shared `sui::clock::Clock` object.
* **@param stake:** The coin that the user will deposit to vote.
* **@param agree:** Determines if the vote is for or against..
* **@return** Vote\<DaoWitness, CoinType>

**Aborts**

* if the proposal is not `ACTIVE`
* if the `stake` type does not match the `proposal.coin_type`
* if a user tries to vote with a zero coin `stake`.

### <mark style="color:blue;">change\_vote</mark>

**Allows a user to change his vote for a `proposal`.**

```rust
public fun change_vote<DaoWitness: drop, CoinType>(
    proposal: &mut Proposal<DaoWitness>,
    vote: &mut Vote<DaoWitness,  CoinType>,
    c: &Clock,
    ctx: &mut TxContext
 )
```

* **@param proposal:** The proposal the user is voting for.
* **@param vote:** The vote that will be changed.
* **@param c:** The shared `sui::clock::Clock` object.

**Aborts**

* if the proposal is not `ACTIVE`
* if the `vote` does not belong to the `proposal`.

### <mark style="color:blue;">revoke\_vote</mark>

**Allows a user to revoke his vote for a `proposal` and get his coin back.**

```rust
public fun revoke_vote<DaoWitness: drop, CoinType>(
    proposal: &mut Proposal<DaoWitness>,
    vote: Vote<DaoWitness, CoinType>,
    c: &Clock,
    ctx: &mut TxContext    
 ): Coin<CoinType>
```

* **@param proposal:** The proposal the user is voting for.
* **@param vote:** The vote that will be destroyed.
* **@param c:** The shared `sui::clock::Clock` object.
* **@return** Coin\<CoinType>

**Aborts**

* if the proposal is not `ACTIVE`
* if the `vote` does not belong to the `proposal`.

### <mark style="color:blue;">unstake\_vote</mark>

**Allows a user to unstake his vote to get his coins back after the `proposal` has ended.**

```rust
public fun unstake_vote<DaoWitness: drop, CoinType>(
    proposal: &Proposal<DaoWitness>,
    vote: Vote<DaoWitness, CoinType>,
    c: &Clock,
    ctx: &mut TxContext      
): Coin<CoinType>
```

* **@param proposal:** The proposal the user is voting for.
* **@param vote:** The vote that will be destroyed.
* **@param c:** The shared `sui::clock::Clock` object.
* **@return** Coin\<CoinType>

**Aborts**

* if the proposal has not ended.
* if the `vote` type does not match the `proposal.id`

### <mark style="color:blue;">queue</mark>

**Allows a successful `proposal` to be queued.**

```rust
public fun queue<DaoWitness: drop>(
    proposal: &mut Proposal<DaoWitness>, 
    c: &Clock
 )
```

* **@param proposal:** The proposal the user is voting for.
* **@param c:** The shared `sui::clock::Clock` object.

**Aborts**

* if the `proposal` state is not AGREED.

### <mark style="color:blue;">execute</mark>

**Executes a `proposal`.**

```rust
public fun execute<DaoWitness: drop, AuhorizedWitness: drop, Capability: key + store>(
    dao: &mut Dao<DaoWitness>,
    proposal: &mut Proposal<DaoWitness>, 
    _: AuhorizedWitness,
    receive_ticket: Receiving<Capability>,
    c: &Clock
): (Capability, CapabilityRequest)
```

* **@param dao:** The Dao.
* **@param proposal:** The proposal that will be executed.
* **@param \_:** The witness that is authorized to borrow the Capability.
* **@param receive\_ticket:** A receipt struct to borrow the Capability.
* **@param c:** The shared `sui::clock::Clock` object.
* **@return Capability** required to execute the proposal.
* **@return CapabilityRequest** A hot potato to ensure that the borrower returns the Capability to the `dao`.

**Aborts**

* if the `proposal` state is not EXECUTABLE
* if there has not passed enough time since the `end_time`
* if the Authorized Witness does not match the `proposal.authorized_witness`.
* if the borrowed capability does not match the `proposal.capability_id`.

### <mark style="color:blue;">return\_capability</mark>

**Returns the borrowed `cap` to the `dao`.**

```rust
public fun return_capability<DaoWitness: drop, Capability: key + store>(dao: &Dao<DaoWitness>, cap: Capability, receipt: CapabilityRequest)
```

* **@param dao:** The Dao.
* **@param cap:** The capability that will be returned to the `dao`.
* **@param receipt:** The request hot potato.

**Aborts**

* if the user tries to return the `cap` to the wrong `dao`
* if there user tries to return the wrong `cap`

### <mark style="color:blue;">update\_dao\_config</mark>

**Updates the configuration settings of the `dao`.**

```rust
public fun update_dao_config<DaoWitness: drop>(
    dao: &mut Dao<DaoWitness>,
    _: &DaoAdmin<DaoWitness>,
    voting_delay: Option<u64>, 
    voting_period: Option<u64>, 
    voting_quorum_rate: Option<u64>, 
    min_action_delay: Option<u64>, 
    min_quorum_votes: Option<u64>
)
```

* **@param dao:** The Dao.
* **@param \_:** Immutable reference to the DaoAdmin.
* **@param voting\_delay:** The minimum waiting period between the creation of a proposal and the voting period.
* **@param voting\_period:** The duration of the voting period.
* **@param voting\_quorum\_rate:** The minimum percentage of votes. E.g. for\_votes / total\_votes. Range = (0, 1\_000\_000\_000]
* **@param min\_action\_delay:** The delay required to execute a proposal after it passes.
* **@param min\_quorum\_votes:** The minimum votes required for a {Proposal} to be successful.

**Aborts**

* if the user tries to return the `cap` to the wrong `dao`
* if there user tries to return the wrong `cap`


# DAO Admin

It creates a capability to enable Daos to update their settings and interact with the treasury. Only the DAO module can create the DaoAdmin capability.

## Structs

### <mark style="color:blue;">**DaoAdmin**</mark>

```rust
  struct DaoAdmin<phantom OTW: drop> has key, store {
    id: UID
  }
```


# DAO Treasury

A Treasury for DAOs. It can receive and send `sui::coin::Coin`.

## Structs

### <mark style="color:blue;">**DaoTreasury**</mark>

```rust
struct DaoTreasury<phantom DaoWitness: drop> has key, store {
    id: UID,
    coins: Bag,
    dao: ID,
}
```

* **coins** - Stores the treasury coins
* **dao**- The `sui::object::ID` of the DAO.

### <mark style="color:blue;">**DaoTreasury**</mark>

```rust
struct FlashLoan<phantom DaoWitness, phantom CoinType> {
    amount: u64,
    fee: u64,
    type: TypeName
}
```

* **amounts:** The amount being borrowed
* **fee**- The fee amount to be repaid.
* **type:** The std::type\_name::TypeName of the CoinType to repay the loan.

## Interface

### <mark style="color:blue;">dao</mark>

**Returns the `sui::object::ID` of the Dao that owns the `treasury`.**

```rust
public fun dao<DaoWitness: drop>(treasury: &DaoTreasury<DaoWitness>): ID 
```

* **@param treasury:** A DaoTreasury.
* **@return** ID

### <mark style="color:blue;">balance</mark>

**Returns the amount of Coin in the `treasury`.**

```rust
public fun balance<DaoWitness: drop, CoinType>(treasury: &DaoTreasury<DaoWitness>): u64
```

* **@param treasury:** A DaoTreasury.
* **@return** u64

### <mark style="color:blue;">donate</mark>

**Adds `token` to the `treasury`.**

```rust
public fun donate<DaoWitness: drop, CoinType>(treasury: &mut DaoTreasury<DaoWitness>, token: Coin<CoinType>, ctx: &mut TxContext)
```

* **@param treasury A DaoTreasury.**
* **@param token It will be donated to the `treasury`.**

### <mark style="color:blue;">transfer</mark>

**Withdraws a coin from the `treasury`.**

```rust
public fun transfer<DaoWitness: drop, CoinType, TransferCoin>(
    treasury: &mut DaoTreasury<DaoWitness>,
    _: &DaoAdmin<DaoWitness>,
    value: u64,
    ctx: &mut TxContext
): Coin<CoinType>
```

* **@param treasury:** A DaoTreasury.
* **@param \_ :** Immutable reference to the DaoAdmin.
* **@param value :** The amount to withdraw.
* **@return** Coin

### <mark style="color:blue;">transfer\_linear\_vesting\_wallet</mark>

**Withdraws a LinearWallet from the `treasury`.**

```rust
public fun transfer_linear_vesting_wallet<DaoWitness: drop, CoinType, TransferCoin>(
    treasury: &mut DaoTreasury<DaoWitness>,
    _: &DaoAdmin<DaoWitness>,
    c: &Clock,
    value: u64,
    start: u64,
    duration: u64,
    ctx: &mut TxContext    
): LinearWallet<CoinType>
```

* **@param treasury:** A DaoTreasury.
* **@param \_ :** Immutable reference to the DaoAdmin.
* **@param c:** The `sui::clock::Clock`
* **@param value :** The amount to withdraw.
* **@param start :** The amount to withdraw.
* **@param duration :** The duration of the vesting schedule.
* **@return** LinearWallet.

### <mark style="color:blue;">flash\_loan</mark>

**Requests a Flash Loan from the `treasury`.**

```rust
public fun flash_loan<DaoWitness: drop, CoinType>(
    treasury: &mut DaoTreasury<DaoWitness>, 
    value: u64, 
    ctx: &mut TxContext
): (Coin<CoinType>, FlashLoan<DaoWitness, CoinType>)
```

* **@param treasury:** A DaoTreasury.
* **@param value :** The amount of the loan.
* **@return Coin\<CoinType>.** The coin that is being borrowed.
* **@return** FlashLoan\<DaoWitness, CoinType>. Hot potato to ensure that the coin is returned within the same transaction block.&#x20;

### <mark style="color:blue;">fee</mark>

**Returns the service fee amount that must be paid.**

```rust
public fun fee<DaoWitness: drop, CoinType>(flash_loan: &FlashLoan<DaoWitness, CoinType>): u64
```

* **@param flash\_loan:**  A FlashLoan hot potato.
* **@return u64.**&#x20;

### <mark style="color:blue;">amount</mark>

**Returns the amount of the loan without the fees.**

```rust
public fun amount<DaoWitness: drop, CoinType>(flash_loan: &FlashLoan<DaoWitness, CoinType>): u64
```

* **@param flash\_loan:**  A FlashLoan hot potato.
* **@return u64.**&#x20;

### <mark style="color:blue;">repay\_flash\_loan</mark>

**Repays the `flash_loan` to the `treasury`.**

<pre class="language-rust"><code class="lang-rust">public fun repay_flash_loan&#x3C;DaoWitness: drop, CoinType>(
    treasury: &#x26;mut DaoTreasury&#x3C;DaoWitness>, 
    flash_loan: FlashLoan&#x3C;DaoWitness, CoinType>,
    token: Coin&#x3C;CoinType>
<strong>)
</strong></code></pre>

* **@param treasury:** A DaoTreasury.
* **@param flash\_loan:**  A FlashLoan hot potato.
* **@param token:**  The borrowed coin + fee.&#x20;

**Aborts**

* `token.value` is smaller than the initial loan amount + fee amount.


# Utils


# ASCII

A utility library to perate on ASCII strings.&#x20;

## Interface

### <mark style="color:blue;">contains</mark>

**It checks if string a contains string b.**

```rust
public fun contains(a: String, b: String): bool
```

* **@param a:** A string.&#x20;
* **@param b**: Another string
* **@return bool.** True if `a` contains `b`.&#x20;

**Aborts**

* `b` is longer than `a`.

### <mark style="color:blue;">append</mark>

**Appends `a` and `b`**

```rust
public fun append(a: String, b: String): String
```

* **@param a:** The first subtring.&#x20;
* **@param b**: The second substring.&#x20;
* **@return String.**  `b` os longer than `a` \`a\` + \`b\` => "hello" \`append\` "world" => "helloworld".&#x20;

### <mark style="color:blue;">slice</mark>

**Returns a \[i, j) slice of the string starting at index i and going up to, but not including, index j.**

```rust
public fun append(a: String, b: String): String
```

* **@param s:** The string that will be sliced.&#x20;
* **@param i:** The first index of the substring. &#x20;
* **@param j:** The last index of the substring. This character is not included.&#x20;
* **@return String.** The substring.

  &#x20;

**Aborts**

* if `j` is greater than `s`.
* if `j` is smaller than `i`.

### <mark style="color:blue;">into\_char</mark>

**It returns the `Char` at index `i` from `string`.**

```rust
public fun into_char(string: &String, i: u64): Char
```

* **@param string:** The string that contains the `Char`.
* **@param i:** i The index of the `Char` we want to grab.
* **@return Char.** The `Char` at index `i`.

**Aborts**

* `i` is out of bounds

### <mark style="color:blue;">to\_lower\_case</mark>

**It lowercases the string.**

```rust
public fun to_lower_case(string: String): String
```

* **@param string:** The string we wish to lowercase.
* **@return String**. The lowercase `string`

### <mark style="color:blue;">to\_upper\_case</mark>

**It uppercases the string.**

```rust
public fun to_upper_case(string: String): String
```

* **@param string:** The string we wish to lowercase.
* **@return String**. The lowercase `string`

### <mark style="color:blue;">u128\_to\_string</mark>

**Converts a `u128` to its `ascii::String` decimal representation.**

```rust
public fun u128_to_string(value: u128): String
```

* **@param value:** A u128.
* **@return String.** The string representation of `value`. E.g. 128 => "128".

### <mark style="color:blue;">u128\_to\_hex\_string</mark>

**Converts a `u128` to its `ascii::String` hexadecimal representation.**

```rust
public fun u128_to_hex_string(value: u128): String 
```

* **@param value:** A u128.
* **@return String.** The HEX string representation of `value`. E.g. 10 => "0xA".

### <mark style="color:blue;">u128\_to\_hex\_string\_to\_fixed\_length</mark>

**Converts a `u128` to its `ascii::String` hexadecimal representation with fixed length (in whole bytes). The returned String is `2 * length + 2`(with '0x') in size.**

```rust
public fun u128_to_hex_string_fixed_length(value: u128, length: u128): String
```

* **@param value:** A u128.
* **@param length:** length of the string.
* **@return String.** The HEX string representation of `value`. E.g. 10 => "0xA".

### <mark style="color:blue;">bytes\_to\_hex\_string</mark>

**Converts a `vector<u8>` to its `ascii::String` hexadecimal representation.**

```rust
public fun bytes_to_hex_string(bytes: vector<u8>): String
```

* **@param** value A u128.
* **@return String.** The HEX string representation of `bytes`. E.g. 0b1010 => "0x0A".

### <mark style="color:blue;">addr\_into\_string</mark>

Converts an address `addr` to its `ascii::String` representation. Addresses are 32 bytes, whereas the string-encoded address is 64 bytes. Outputted strings do not include the 0x prefix.

```rust
public fun addr_into_string(addr: address): String
```

* **@param addr**: A 32-byte address.
* **@return** String. The `ascii::String` representation of `addr`.

### <mark style="color:blue;">u8\_to\_ascii</mark>

**Converts a u8 `num` to an ascii character.**

```rust
public fun u8_to_ascii(num: u8): u8
```

* **@param num:** decimal representation of an ASCII character.
* **@return u8.** The `ascii::String` code for `num`.

### <mark style="color:blue;">ascii\_to\_u8</mark>

**Converts an ASCII character to its decimal representation u8.**

```rust
public fun ascii_to_u8(char: u8): u8
```

* **@param char:** ASCII character.
* **@return u8.** The decimal representation of `char`.


# Comparator

A library to compare structs. BCS uses little-endian encoding for all integer types, so results might be unexpected.

### <mark style="color:blue;">**Result**</mark>

```rust
  struct Result has drop {
    inner: u8,
  }
```

* **inner** - It will hold one of the following values: {SMALLER}, {EQUAL} or {GREATER}.

## Interface

### <mark style="color:blue;">eq</mark>

**It checks if the `result` of {compare} is `EQUAL`.**

```rust
public fun eq(result: &Result): bool
```

* **@param result:** This struct contains one of the following values: {SMALLER}, {EQUAL} or {GREATER}.
* **@return bool.** True if it is `EQUAL`

### <mark style="color:blue;">lt</mark>

**It checks if the `result` of {compare} is `SMALLER`.**

```rust
public fun lt(result: &Result): bool
```

* **@param result:** This struct contains one of the following values: {SMALLER}, {EQUAL} or {GREATER}.
* **@return bool.** True if it is `SMALLER`

### <mark style="color:blue;">gt</mark>

**It checks if the `result` of {compare} is `GREATER`.**

```rust
public fun gt(result: &Result): bool
```

* **@param result:** This struct contains one of the following values: {SMALLER}, {EQUAL} or {GREATER}.
* **@return bool.** True if it is `GREATER`

### <mark style="color:blue;">lte</mark>

**It checks if the `result` of {compare} is `SMALLER` or `EQUAL`.**

```rust
public fun lte(result: &Result): bool
```

* **@param result:** This struct contains one of the following values: {SMALLER}, {EQUAL} or {GREATER}.
* **@return bool.** True if it is `SMALLER` or `EQUAL`.

### <mark style="color:blue;">gte</mark>

**It checks if the `result` of {compare} is `SMALLER` or `EQUAL`.**

```rust
public fun gte(result: &Result): bool
```

* **@param result:** This struct contains one of the following values: {SMALLER}, {EQUAL} or {GREATER}.
* **@return bool.** True if it is `SMALLER` or `EQUAL`.

### <mark style="color:blue;">compare</mark>

**Compares two structs of type `T`. Performs a comparison of two types after BCS serialization.**

```rust
public fun compare<T>(left: &T, right: &T): Result
```

* **@param left:** A struct of type `T`.
* **@param right:** A struct of type `T`.
* **@return Result.** A struct that contains the following values: {SMALLER}, {EQUAL} or {GREATER}.

### <mark style="color:blue;">compare\_u8\_vector</mark>

**Compares two bytes.**

```rust
public fun compare_u8_vector(left: vector<u8>, right: vector<u8>): Result
```

* **@param left:** A set of bytes.
* **@param right:** A set of bytes.
* **@return Result.** A struct that contains the following values: {SMALLER}, {EQUAL} or {GREATER}.


# Merkle Proof

Allows users to verify Merkle Tree proofs. It is based on the OZ implementation. The tree and the proofs can be generated using <https://github.com/merkletreejs/merkletreejs>.

{% hint style="danger" %}

```
You should avoid using leaf values that are 64 bytes long prior to hashing.
```

{% endhint %}

## Interface

### <mark style="color:blue;">verify</mark>

**Returns true if a `leaf` can be proved to be a part of a Merkle tree defined by `root`.**

```rust
public fun verify(
    proof: &vector<vector<u8>>,
    root: vector<u8>,
    leaf: vector<u8>
  ): bool
```

* **@param proof:** The Merkle proof.
* **@param root:** The root of Merkle Tree.
* **@param leaf:** The `leaf` we wish to prove if it is part of the tree.
* **@return bool.** If it is part of the Merkle tree.

### <mark style="color:blue;">verify\_with\_index</mark>

**Returns true if a `leaf` can be proved to be a part of a Merkle tree defined by `root`. For this, a `proof` must be provided, containing sibling hashes on the branch from the leaf to the root of the tree. Each pair of leaves and each pair of pre-images are assumed to be sorted.**

{% hint style="success" %}
The index logic is from ENS token: <https://etherscan.io/token/0xC18360217D8F7Ab5e7c516566761Ea12Ce7F9D72#code>
{% endhint %}

```rust
public fun verify_with_index(
    proof: &vector<vector<u8>>,
    root: vector<u8>,
    leaf: vector<u8>
): (bool, u256)
```

* **@param proof:** The Merkle proof.
* **@param root:** The root of Merkle Tree.
* **@param leaf:** The `leaf` we wish to prove if it is part of the tree.
* **@return bool.** If it is part of the Merkle tree.
* **@return u256.** The index of the `leaf.`


# Vectors

Utility functions for vectors.

## Interface

### <mark style="color:blue;">find\_upper\_bound</mark>

Searches a sorted `vec` and returns the first index that contains a value greater or equal to `element`. If no such index exists (i.e. all values in the vector are strictly less than `element`),  and the vector length is returned.

{% hint style="success" %}
Time complexity O(log n).
{% endhint %}

```rust
public fun find_upper_bound(vec: vector<u64>, element: u64): u64
```

* **@param vec:** The vector to be searched.
* **@param element:** We check if there is a value higher than it in the vector.
* **@return u64.** The index of the member that is larger than `element`. The length is returned if no member is found.

### <mark style="color:blue;">lt</mark>

**Checks if `a` is smaller than `b`. E.g. x"123" < x"456".**

```rust
public fun lt(a: vector<u8>, b: vector<u8>): bool
```

* **@param a:** The first operand.
* **@param b:** The second operand..
* **@return bool.** If `a` is smaller than `b`.

**Aborts**

* `a` and `b` have different lengths.

### <mark style="color:blue;">gt</mark>

**Checks if `a` is larger than `b`. E.g. x"123" < x"456".**

```rust
public fun gt(a: vector<u8>, b: vector<u8>): bool
```

* **@param a:** The first operand.
* **@param b:** The second operand..
* **@return bool.** If `a` is larger than `b`.

**Aborts**

* `a` and `b` have different lengths.

### <mark style="color:blue;">lte</mark>

**Checks if `a` is smaller or equal to `b`. E.g. x"123" =< x"456".**

```rust
public fun lte(a: vector<u8>, b: vector<u8>): bool
```

* **@param a:** The first operand.
* **@param b:** The second operand..
* **@return bool.** If `a` is smaller or equal to `b`.

**Aborts**

* `a` and `b` have different lengths.

### <mark style="color:blue;">gte</mark>

**Checks if `a` is larger or equal to `b`. E.g. x"123" =< x"456".**

```rust
public fun gte(a: vector<u8>, b: vector<u8>): bool 
```

* **@param a:** The first operand.
* **@param b:** The second operand..
* **@return bool.** If `a` is larger or equal to `b`.

**Aborts**

* `a` and `b` have different lengths.

### <mark style="color:blue;">ascending\_insertion\_sort</mark>

**Sorts a `a` in ascending order. E.g. \[342] => \[234].**

```rust
public fun ascending_insertion_sort(a: vector<u256>): vector<u256>
```

* **@param a:** The vector to sort.
* **@return vector.** Sorted `a`.

**Aborts**

* `a` and `b` have different lengths.

### <mark style="color:blue;">descending\_insertion\_sort</mark>

**Sorts a `a` in descending order. E.g. \[342] => \[432].**

```rust
public fun descending_insertion_sort(a: vector<u256>): vector<u256>
```

* **@param a:** The vector to sort.
* **@return vector.** Sorted `a`.

**Aborts**

* `a` and `b` have different lengths.

### <mark style="color:blue;">quick\_sort</mark>

**Sorts a `values`. E.g. \[342] => \[234].**

{% hint style="warning" %}
This function mutates the original vector.
{% endhint %}

```rust
public fun quick_sort(values: &mut vector<u256>, left: u64, right: u64)
```

* **@param values:** The vector to sort.
* **@param left:** The smaller side of the pivot. Pass 0.
* **@param right:** The larger side of the pivot. Pass `vector::length - 1`.


# Math


# Fixed Point 64

A library to perform math operations over an unsigned integer with 64-bit precision. Any operation that results in a number larger than the maximum unsigned 128 bit, will be considered an overflow and throw.

## Structs

### <mark style="color:blue;">**FixedPoint64**</mark>

```rust
struct FixedPoint64 has copy, drop, store { value: u128 }
```

* **value** - The number.

## Interface

### <mark style="color:blue;">value</mark>

**It returns the raw u128 value.**

```rust
public fun value(self: FixedPoint64): u128
```

* **@param self:** A FixedPoint64
* **@return u128.** The raw u128 value.

### <mark style="color:blue;">from</mark>

**Creates a FixedPoint64 from a u128 number. It scales the number.**

```rust
public fun from(value: u128): FixedPoint64
```

* **@param value:** A u128 number.
* **@return A FixedPoint64.** calculated by right shifting - `value` << 64.

**Aborts**

* The left-shifted `value` is larger than `MAX_U128`.

### <mark style="color:blue;">from\_raw\_value</mark>

**Creates a FixedPoint64 from a u128 `value`. It does not scale the `value`.**

```rust
public fun from_raw_value(value: u128): FixedPoint64
```

* **@param value:** A u128 number.
* **@return FixedPoint64.** It wraps the u128.

### <mark style="color:blue;">from\_rational</mark>

**Creates a FixedPoint64 from a rational number specified by a `numerator` and`denominator`.**

{% hint style="warning" %}
0.0125 will round down to 0.012 instead of up to 0.013.
{% endhint %}

```rust
public fun from_rational(numerator: u128, denominator: u128): FixedPoint64
```

* **@param numerator:** The numerator of the rational number.
* **@param denominator:** The denominator of the rational number.
* **@return FixedPoint64.** A FixedPoint64 from (`numerator` << 64) / `denominator.`

**Aborts**

* if the denominator is zero
* if the numerator / denominator is zero
* if the numerator is nonzero and the ratio is not in the range 2^-64 .. 2^64-1

### <mark style="color:blue;">to\_u128</mark>

**Converts a FixedPoint64 into a u128 number to the closest integer.**

```rust
public fun to_u128(self: FixedPoint64): u128
```

* **@param self.** A FixedPoint64.
* **@return u128.**

### <mark style="color:blue;">to\_u128\_down</mark>

**Converts a FixedPoint64 into a u128 number rounding down.**

```rust
public fun to_u128_down(self: FixedPoint64): u128
```

* **@param self.** A FixedPoint64.
* **@return u128.**

### <mark style="color:blue;">to\_u128\_up</mark>

**Converts a FixedPoint64 into a u128 number rounding up.**

```rust
public fun to_u128_up(self: FixedPoint64): u128
```

* **@param self.** A FixedPoint64.
* **@return u128.**

### <mark style="color:blue;">is\_zero</mark>

**Checks if `self` is zero.**

```rust
public fun is_zero(self: FixedPoint64): bool
```

* **@param self.** A FixedPoint64.
* **@return bool.** If the `self.value` is zero.

### <mark style="color:blue;">eq</mark>

**Checks if `x` is equal to `y`.**

```rust
public fun eq(x: FixedPoint64, y: FixedPoint64): bool
```

* **@param x:** A FixedPoint64.
* **@param y:** A FixedPoint64.
* **@return bool**. If the values are equal.

### <mark style="color:blue;">lt</mark>

**Checks if `x` is smaller or equal to `y`.**

```rust
public fun lt(x: FixedPoint64, y: FixedPoint64): bool
```

* **@param x:** A FixedPoint64.
* **@param y:** A FixedPoint64.
* **@return bool.** If `x` is smaller than `y`.

### <mark style="color:blue;">gt</mark>

**Checks if `x` is bigger than `y`.**

```rust
public fun gt(x: FixedPoint64, y: FixedPoint64): bool
```

* **@param x:** A FixedPoint64.
* **@param y:** A FixedPoint64.
* **@return bool.** If `x` is bigger or equal to `y`.

### <mark style="color:blue;">lte</mark>

**Checks if `x` is smaller or equal to `y`.**

```rust
public fun lte(x: FixedPoint64, y: FixedPoint64): bool
```

* **@param x:** A FixedPoint64.
* **@param y:** A FixedPoint64.
* **@return bool.** If `x` is smaller or equal to `y`.

### <mark style="color:blue;">gte</mark>

**Checks if `x` is bigger or equal to `y`.**

```rust
public fun gte(x: FixedPoint64, y: FixedPoint64): bool
```

* **@param x:** A FixedPoint64.
* **@param y:** A FixedPoint64.
* **@return bool.** If `x` is bigger or equal to `y`.

### <mark style="color:blue;">max</mark>

**It returns the larger of the two arguments.**

```rust
public fun max(x: FixedPoint64, y: FixedPoint64): FixedPoint64
```

* **@param x:** The first operand.
* **@param y:** The second operand.
* **@return FixedPoint64**. The larger argument.

### <mark style="color:blue;">min</mark>

**It returns the smaller of the two arguments.**

```rust
public fun min(x: FixedPoint64, y: FixedPoint64): FixedPoint64
```

* **@param x:** The first operand.
* **@param y:** The second operand.
* **@return FixedPoint64**. The smaller argument.

### <mark style="color:blue;">sub</mark>

**It returns `x` - `y`.**

```rust
public fun sub(x: FixedPoint64, y: FixedPoint64): FixedPoint64
```

* **@param x:** The first operand.
* **@param y:** The second operand.
* **@return FixedPoint64**. The result of `x` - `y`.

**Aborts**

* `y` > `x`

### <mark style="color:blue;">add</mark>

**It returns `x` + `y`.**

```rust
public fun add(x: FixedPoint64, y: FixedPoint64): FixedPoint64
```

* **@param x:** The first operand.
* **@param y:** The second operand.
* **@return FixedPoint64**. The result of `x` + `y`.

**Aborts**

* `y` + `x` >= `MAX_U128`

### <mark style="color:blue;">mul</mark>

**It returns `x` \* `y`.**

{% hint style="warning" %}
Use {mul\_128} if you think the values can overflow.
{% endhint %}

```rust
public fun mul(x: FixedPoint64, y: FixedPoint64): FixedPoint64
```

* **@param x:** The first operand.
* **@param y:** The second operand.
* **@return FixedPoint64**. The result of `x` \* `y`.

**Aborts**

* inner values overflow.

### <mark style="color:blue;">div</mark>

**It returns `x` / `y`.**

```rust
public fun div(x: FixedPoint64, y: FixedPoint64): FixedPoint64
```

* **@param x:** The first operand.
* **@param y:** The second operand.
* **@return FixedPoint64**. The result of `x` / `y`.

**Aborts**

* if `y` is zero.

### <mark style="color:blue;">mul\_div</mark>

**Specialized function for `x` \* `y` / `z` that omits intermediate shifting.**

```rust
public fun mul_div(x: FixedPoint64, y: FixedPoint64, z: FixedPoint64): FixedPoint64
```

* **@param x:** A FixedPoint64.
* **@param y:** A FixedPoint64.
* **@param z:** The third operand.
* **@return FixedPoint64**. The result of `x` \* `y` / `z`.

**Aborts**

* if z is zero.

### <mark style="color:blue;">mul\_u128</mark>

It returns `x` \* `y.`It multiplies a u128 number with a FixedPoint64. **It truncates the fractional part of the product. E.g. - 9 \* 0.333 = 2.**

```rust
public fun mul_u128(x: u128, y: FixedPoint64): u128
```

* **@param x:** A FixedPoint64.
* **@param y:** A FixedPoint64.
* **@return u128.** The result of `x` \* `y` without the 64-bit precision.

**Aborts**

* if the result is larger or equal to `MAX_U128`.

### <mark style="color:blue;">div\_down\_u128</mark>

**It returns `numerator` / `denominator` rounded down. It divides a FixedPoint64 by a u128 number.**

```rust
public fun div_down_u128(numerator: u128, denominator: FixedPoint64): u128
```

* **@param numerator:** The first operand, a u128 number.
* **@param denominator:** The first operand, a u128 number.
* **@return u128.** The result of `numerator` / `denominator` without the 64-bit precision.

**Aborts**

* if the result is larger or equal to `MAX_U128`.
* if the `denominator` is zero.

### <mark style="color:blue;">div\_up\_u128</mark>

**It returns `numerator` / `denominator` rounded up. It divides a FixedPoint64 by a u128 number.**

```rust
public fun div_up_u128(numerator: u128, denominator: FixedPoint64): u128
```

* **@param numerator:** The first operand, a u128 number.
* **@param denominator:** The first operand, a u128 number.
* **@return u128.** The result of `numerator` / `denominator` without the 64-bit precision.

**Aborts**

* if the result is larger or equal to `MAX_U128`.
* if the `denominator` is zero.

### <mark style="color:blue;">pow</mark>

**It returns `base` \*\* `exponent`.**

```rust
public fun pow(base: FixedPoint64, exponent: u64): FixedPoint64
```

* **@param base**: The base.
* **@param exponent:** The exponent.
* **@return FixedPoint64.** The result of `base` \*\* `exponent`.

**Aborts**

* if the end result is higher than `MAX_U128`.

### <mark style="color:blue;">sqrt</mark>

**Square root of `x`.**

```rust
public fun sqrt(x: FixedPoint64): FixedPoint64
```

* **@param x:** The operand.
* **@return FixedPoint64.** The result of the square root.

### <mark style="color:blue;">exp</mark>

**It performs e^x. Exponent function with a precision of 9 digits.**

```rust
public fun exp(x: FixedPoint64): FixedPoint64
```

* **@param x:** The operand.
* **@return FixedPoint64.** The result of e^x.


# Fixed Point Roll

A set of functions to operate over u64 numbers with 1e9 precision.

## Interface

### <mark style="color:blue;">roll</mark>

**It returns 1 ROLL - 1\_000\_000\_000.**&#x20;

```rust
public fun roll(): u64
```

* **@return u64**. 1e9

### <mark style="color:blue;">try\_mul\_down</mark>

**It tries to `x` \* `y` / 1\_000\_000\_000 rounding down. It returns zero instead of throwing an overflow error.**

```rust
public fun try_mul_down(x: u64, y: u64): (bool, u64)
```

* **@param x:** The first operand.
* **@param y:** The second operand.
* **@return bool.** If the operation was successful.
* **@return u64.** The result of `x` \* `y` / **1\_000\_000\_000**.

### <mark style="color:blue;">try\_mul\_up</mark>

**It tries to `x` \* `y` / 1\_000\_000\_000 rounding up. It returns zero instead of throwing an overflow error.**

```rust
public fun try_mul_up(x: u64, y: u64): (bool, u64)
```

* **@param x:** The first operand.
* **@param y:** The second operand.
* **@return bool.** If the operation was successful.
* **@return u64.** The result of `x` \* `y` / **1\_000\_000\_000**.

### <mark style="color:blue;">try\_div\_down</mark>

**It tries to `x` \* 1\_000\_000\_000 / `y` rounding down. It returns zero instead of throwing an overflow error.**

```rust
public fun try_div_down(x: u64, y: u64): (bool, u64)
```

* **@param x:** The first operand.
* **@param y:** The second operand.
* **@return bool.** If the operation was successful.
* **@return u64.** The result of **`x` \* 1\_000\_000\_000 / `y`**.

### <mark style="color:blue;">try\_div\_up</mark>

**It tries to `x` \* 1\_000\_000\_000 / `y` rounding up. It returns zero instead of throwing an overflow error.**

```rust
public fun try_div_up(x: u64, y: u64): (bool, u64)
```

* **@param x:** The first operand.
* **@param y:** The second operand.
* **@return bool.** If the operation was successful.
* **@return u64.** The result of **`x` \* 1\_000\_000\_000 / `y`**.

### <mark style="color:blue;">mul\_down</mark>

`x` \* `y` / **1\_000\_000\_000** rounding down.

```rust
public fun mul_down(x: u64, y: u64): u64
```

* **@param x:** The first operand.
* **@param y:** The second operand.
* **@return u64.** The result of `x` \* `y` / **1\_000\_000\_000**.

**Aborts**

* On overflow. If the result is over the maximum u256 number.

### <mark style="color:blue;">mul\_up</mark>

`x` \* `y` / **1\_000\_000\_000** rounding up.

```rust
public fun mul_up(x: u64, y: u64): u64
```

* **@param x:** The first operand.
* **@param y:** The second operand.
* **@return u64.** The result of `x` \* `y` / **1\_000\_000\_000**.

**Aborts**

* On overflow. If the result is over the maximum u256 number.

### <mark style="color:blue;">div\_down</mark>

`x` \*  **1\_000\_000\_000** / `y` rounding down.

```rust
public fun div_down(x: u64, y: u64): u64
```

* **@param x:** The first operand.
* **@param y:** The second operand.
* **@return u64.** The result of `x` \*  **1\_000\_000\_000** / `y`.

**Aborts**

* On zero division.

### <mark style="color:blue;">div\_up</mark>

`x` \*  **1\_000\_000\_000** / `y` rounding up.

```rust
public fun div_up(x: u64, y: u64): u64
```

* **@param x:** The first operand.
* **@param y:** The second operand.
* **@return u64.** The result of `x` \*  **1\_000\_000\_000** / `y`.

**Aborts**

* On zero division.

### <mark style="color:blue;">to\_roll</mark>

**It converts `x` precision to a `ROLL`, a number with a precision of 1e9.**

```rust
public fun to_roll(x: u64, decimal_factor: u64): u64
```

* **@param x:** The value to be converted.
* **@param decimal\_factor:** The current decimal scalar of x.&#x20;
* **@return u64.** The result of `x` \*  **1\_000\_000\_000** / `y`.

**Aborts**

* decimal\_factor is zero.


# Fixed Point Wad

A set of functions to operate over u256 numbers with 1e18 precision. It emulates the decimal precision of ERC20 to port some of their advanced math operations such as exp and exp and ln.

## Interface

### <mark style="color:blue;">wad</mark>

**It returns 1 WAD - 1\_000\_000\_000\_000\_000\_000.**&#x20;

```rust
public fun wad(): u256
```

* **@return u64**. 1e18

### <mark style="color:blue;">try\_mul\_down</mark>

**It tries to `x` \* `y` / 1\_000\_000\_000\_000\_000\_000 rounding down. It returns zero instead of throwing an overflow error.**

```rust
public fun try_mul_down(x: u256, y: u256): (bool, u256)
```

* **@param x:** The first operand.
* **@param y:** The second operand.
* **@return bool.** If the operation was successful.
* **@return u256.** The result of `x` \* `y` / **1\_000\_000\_000\_000\_000\_000**.

### <mark style="color:blue;">try\_mul\_up</mark>

**It tries to `x` \* `y` / 1\_000\_000\_000\_000\_000\_000 rounding up. It returns zero instead of throwing an overflow error.**

```rust
public fun try_mul_up(x: u256, y: u256): (bool, u256)
```

* **@param x:** The first operand.
* **@param y:** The second operand.
* **@return bool.** If the operation was successful.
* **@return u256.** The result of `x` \* `y` / **1\_000\_000\_000\_000\_000\_000**.

### <mark style="color:blue;">try\_div\_down</mark>

**It tries to `x` \* 1\_000\_000\_000\_000\_000\_000 / `y` rounding down. It returns zero instead of throwing an overflow error.**

```rust
public fun try_div_down(x: u256, y: u256): (bool, u256)
```

* **@param x:** The first operand.
* **@param y:** The second operand.
* **@return bool.** If the operation was successful.
* **@return u256.** The result of **`x` \* 1\_000\_000\_000\_000\_000\_000 / `y`**.

### <mark style="color:blue;">try\_div\_up</mark>

**It tries to `x` \* 1\_000\_000\_000\_000\_000\_000 / `y` rounding up. It returns zero instead of throwing an overflow error.**

```rust
public fun try_div_up(x: u256, y: u256): (bool, u256)
```

* **@param x:** The first operand.
* **@param y:** The second operand.
* **@return bool.** If the operation was successful.
* **@return u256.** The result of **`x` \* 1\_000\_000\_000\_000\_000\_000 / `y`**.

### <mark style="color:blue;">mul\_down</mark>

`x` \* `y` / **1\_000\_000\_000\_000\_000\_000** rounding down.

```rust
public fun mul_down(x: u256, y: u256): u256
```

* **@param x:** The first operand.
* **@param y:** The second operand.
* **@return u256.** The result of `x` \* `y` / **1\_000\_000\_000\_000\_000\_000**.

**Aborts**

* On overflow. If the result is over the maximum u256 number.

### <mark style="color:blue;">mul\_up</mark>

`x` \* `y` / **1\_000\_000\_000\_000\_000\_000** rounding up.

```rust
public fun mul_up(x: u256, y: u256): u256
```

* **@param x:** The first operand.
* **@param y:** The second operand.
* **@return u256.** The result of `x` \* `y` / **1\_000\_000\_000\_000\_000\_000**.

**Aborts**

* On overflow. If the result is over the maximum u256 number.

### <mark style="color:blue;">div\_down</mark>

`x` \*  **1\_000\_000\_000\_000\_000\_000** / `y` rounding down.

```rust
public fun div_down(x: u256, y: u256): u256
```

* **@param x:** The first operand.
* **@param y:** The second operand.
* **@return u256.** The result of `x` \*  **1\_000\_000\_000\_000\_000\_000** / `y`.

**Aborts**

* On zero division.

### <mark style="color:blue;">div\_up</mark>

`x` \*  **1\_000\_000\_000\_000\_000\_000** / `y` rounding up.

```rust
public fun div_up(x: u256, y: u256): u256
```

* **@param x:** The first operand.
* **@param y:** The second operand.
* **@return u256.** The result of `x` \*  **1\_000\_000\_000\_000\_000\_000** / `y`.

**Aborts**

* On zero division.

### <mark style="color:blue;">to\_wad</mark>

**It converts `x` precision to a , a number with a precision of 1e18.**

```rust
public fun to_wad(x: u256, decimal_factor: u256): u256
```

* **@param x:** The value to be converted.
* **@param decimal\_factor:** The current decimal scalar of x.&#x20;
* **@return u64.** The result of `x` \*  **1\_000\_000\_000\_000\_000\_000** / `y`.

**Aborts**

* decimal\_factor is zero.

### <mark style="color:blue;">exp</mark>

**It calculates e^x.**&#x20;

{% hint style="success" %}
All credits to Remco Bloemen and more information here: <https://xn--2-umb.com/22/exp-ln/>
{% endhint %}

```rust
public fun exp(x: Int): Int
```

* **@param x:** The exponent.
* **@return Int.** The result of e^x.

**Aborts**

* `x` is larger than 135305999368893231589.

### <mark style="color:blue;">ln</mark>

**It calculates ln(x).**&#x20;

{% hint style="success" %}
All credits to Remco Bloemen and more information here: <https://xn--2-umb.com/22/exp-ln/>
{% endhint %}

```rust
public fun ln(x: Int): Int
```

* **@param x:** The operand.
* **@return Int.** The result of ln(x).

**Aborts**

* `x` is negative or zero.


# Int

A library to convert unsigned integers to signed integers using two's complement. It contains basic arithmetic operations for signed integers.

{% hint style="info" %}
Uses arithmetic shr and shl for negative numbers
{% endhint %}

## Structs

### <mark style="color:blue;">**Int**</mark>

```rust
struct Int has copy, drop, store {
    value: u256
 }
```

* **value** - The number.

```rust
const EQUAL: u8 = 0;

const LESS_THAN: u8 = 1;

const GREATER_THAN: u8 = 2;
```

## Interface

### <mark style="color:blue;">value</mark>

**It returns the inner value inside `self`.**

```rust
public fun value(self: Int): u256
```

* **@param self:** The Int struct.
* **@return u256**.

### <mark style="color:blue;">zero</mark>

**It creates a zero `Int`.**

```rust
public fun zero(): Int
```

* **@return Int.** The wrapped value.

### <mark style="color:blue;">one</mark>

**It creates a one `Int`.**

```rust
public fun one(): Int
```

* **@return Int.** The wrapped value.

### <mark style="color:blue;">max</mark>

**It creates the largest possible `Int`.**

{% hint style="info" %}
Maximum number is : 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF
{% endhint %}

```rust
public fun max(): Int
```

* **@return Int.**&#x20;

### <mark style="color:blue;">from\_u8</mark>

**It wraps a u8 `value` into an `Int`.**

```rust
public fun from_u8(value: u8): Int
```

* **@param value:** The u8 value to wrap
* **@return Int.** The wrapped `value`

### <mark style="color:blue;">from\_u16</mark>

**It wraps a u16 `value` into an `Int`.**

```rust
public fun from_u16(value: u16): Int
```

* **@param value:** The u16 value to wrap
* **@return Int.** The wrapped `value`

### <mark style="color:blue;">from\_u32</mark>

**It wraps a u32 `value` into an `Int`.**

```rust
public fun from_u32(value: u32): Int
```

* **@param value:** The u32 value to wrap
* **@return Int.** The wrapped `value`

### <mark style="color:blue;">from\_u64</mark>

**It wraps a u64 `value` into an `Int`.**

```rust
public fun from_u64(value: u64): Int
```

* **@param value:** The u64 value to wrap
* **@return Int.** The wrapped `value`

### <mark style="color:blue;">from\_u128</mark>

**It wraps a u128 `value` into an `Int`.**

```rust
public fun from_u128(value: u128): Int
```

* **@param value:** The u128 value to wrap
* **@return Int.** The wrapped `value`

### <mark style="color:blue;">from\_u256</mark>

**It wraps a u128 `value` into an `Int`.**

```rust
public fun from_u256(value: u256): Int
```

* **@param value:** The u256 value to wrap
* **@return Int.** The wrapped `value`

**`Abort`**

* if value is larger than 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF.

### <mark style="color:blue;">neg\_from\_u8</mark>

**It wraps a u8 `value` into an `Int` and negates it.**

```rust
public fun neg_from_u8(value: u8): Int
```

* **@param value:** The u16 value to wrap
* **@return Int.** The wrapped `value`

### <mark style="color:blue;">neg\_from\_u16</mark>

**It wraps a u16 `value` into an `Int` and negates it.**

```rust
public fun neg_from_u16(value: u16): Int
```

* **@param value:** The u16 value to wrap
* **@return Int.** The wrapped `value`

### <mark style="color:blue;">neg\_from\_u32</mark>

**It wraps a u32 `value` into an `Int` and negates it.**

```rust
public fun neg_from_u32(value: u32): Int
```

* **@param value:** The u32 value to wrap
* **@return Int.** The wrapped `value`

### <mark style="color:blue;">neg\_from\_u64</mark>

**It wraps a u64 `value` into an `Int` and negates it.**

```rust
public fun neg_from_u64(value: u64): Int
```

* **@param value:** The u64 value to wrap
* **@return Int.** The wrapped `value`

### <mark style="color:blue;">neg\_from\_u128</mark>

**It wraps a u128 `value` into an `Int` and negates it.**

```rust
public fun neg_from_u128(value: u128): Int
```

* **@param value:** The u128 value to wrap
* **@return Int.** The wrapped `value`

### <mark style="color:blue;">neg\_from\_u256</mark>

**It wraps a u256 `value` into an `Int` and negates it.**

```rust
public fun neg_from_u256(value: u256): Int
```

* **@param value:** The u256 value to wrap
* **@return Int.** The wrapped `value`

### <mark style="color:blue;">to\_u8</mark>

**It unwraps the value inside `self` and casts it to u8.**

```rust
public fun to_u8(self: Int): u8
```

* **@param self:** The Int struct.
* **@return u8.** The inner value cast to u8.

**Abort**

* `self.value` is negative

### <mark style="color:blue;">to\_u16</mark>

**It unwraps the value inside `self` and casts it to u16.**

```rust
public fun to_u16(self: Int): u16
```

* **@param self:** The Int struct.
* **@return u16.** The inner value cast to u16.

**Abort**

* `self.value` is negative

### <mark style="color:blue;">to\_u32</mark>

**It unwraps the value inside `self` and casts it to u32.**

```rust
public fun to_u32(self: Int): u32
```

* **@param self:** The Int struct.
* **@return u32.** The inner value cast to u32.

**Abort**

* `self.value` is negative

### <mark style="color:blue;">to\_u64</mark>

**It unwraps the value inside `self` and casts it to u64.**

```rust
public fun to_u64(self: Int): u64
```

* **@param self:** The Int struct.
* **@return u64.** The inner value cast to u64.

**Abort**

* `self.value` is negative

### <mark style="color:blue;">to\_u128</mark>

**It unwraps the value inside `self` and casts it to u128.**

```rust
public fun to_u128(self: Int): u128
```

* **@param self:** The Int struct.
* **@return u128.** The inner value cast to u128.

**Abort**

* `self.value` is negative

### <mark style="color:blue;">to\_u256</mark>

**It unwraps the value inside `self` and casts it to u256.**

```rust
public fun to_u256(self: Int): u256
```

* **@param self:** The Int struct.
* **@return u128.** The inner value cast to u256.

**Abort**

* `self.value` is negative

### <mark style="color:blue;">truncate\_to\_u8</mark>

**It unwraps the value inside `self` and truncates it to u8.**

```rust
public fun truncate_to_u8(self: Int): u8
```

* **@param self:** The Int struct.
* **@return u8.** The inner value is truncated to u8.

### <mark style="color:blue;">truncate\_to\_u16</mark>

**It unwraps the value inside `self` and truncates it to u16.**

```rust
public fun truncate_to_u16(self: Int): u16
```

* **@param self:** The Int struct.
* **@return u8.** The inner value is truncated to u16.

### <mark style="color:blue;">truncate\_to\_u32</mark>

**It unwraps the value inside `self` and truncates it to u16.**

```rust
public fun truncate_to_u32(self: Int): u32
```

* **@param self:** The Int struct.
* **@return u8.** The inner value is truncated to u32.

### <mark style="color:blue;">truncate\_to\_u64</mark>

**It unwraps the value inside `self` and truncates it to u64.**

```rust
public fun truncate_to_u64(self: Int): u64
```

* **@param self:** The Int struct.
* **@return u8.** The inner value is truncated to u64.

### <mark style="color:blue;">truncate\_to\_u128</mark>

**It unwraps the value inside `self` and truncates it to u128.**

```rust
public fun truncate_to_u128(self: Int): u128
```

* **@param self:** The Int struct.
* **@return u8.** The inner value is truncated to u128.

### <mark style="color:blue;">flip</mark>

**It flips the sign of `self`.**

```rust
public fun flip(self: Int): Int
```

* **@param self:** The Int struct.
* **@return Int.** The returned Int will have its signed flipped.

### <mark style="color:blue;">abs</mark>

**It returns the absolute of an Int.**

```rust
public fun abs(self: Int): Int
```

* **@param self:** The Int struct.
* **@return Int.** The absolute.

### <mark style="color:blue;">is\_neg</mark>

**It checks if `self` is negative.**

```rust
public fun is_neg(self: Int): bool
```

* **@param self:** The Int struct.
* **@return bool.**

### <mark style="color:blue;">is\_zero</mark>

**It checks if `self` is zero.**

```rust
public fun is_zero(self: Int): bool
```

* **@param self:** The Int struct.
* **@return bool.**

### <mark style="color:blue;">is\_positive</mark>

**It checks if `self` is positive.**

```rust
public fun is_positive(self: Int): bool
```

* **@param self:** The Int struct.
* **@return bool.**

### <mark style="color:blue;">compare</mark>

**It compares `a` and `b`.**

```rust
public fun compare(a: Int, b: Int): u8
```

* **@param a:** An Int struct.
* **@param b:** An Int struct.
* **@return 0**. a == b.
* **@return 1.** a < b.
* **@return 2.** a > b.

### <mark style="color:blue;">eq</mark>

**It checks if `a` and `b` are equal.**

```rust
public fun eq(a: Int, b: Int): bool
```

* **@param a:** An Int struct.
* **@param b:** An Int struct.
* **@return bool.**

### <mark style="color:blue;">lt</mark>

**It checks if `a` < `b`.**

```rust
public fun lt(a: Int, b: Int): bool
```

* **@param a:** An Int struct.
* **@param b:** An Int struct.
* **@return bool.**

### <mark style="color:blue;">lte</mark>

**It checks if `a` <= `b`.**

```rust
public fun lte(a: Int, b: Int): bool
```

* **@param a:** An Int struct.
* **@param b:** An Int struct.
* **@return bool.**

### <mark style="color:blue;">gt</mark>

**It checks if `a` > `b`.**

```rust
public fun gt(a: Int, b: Int): bool
```

* **@param a:** An Int struct.
* **@param b:** An Int struct.
* **@return bool.**

### <mark style="color:blue;">gte</mark>

**It checks if `a` >= `b`.**

```rust
public fun gte(a: Int, b: Int): bool
```

* **@param a:** An Int struct.
* **@param b:** An Int struct.
* **@return bool.**

### <mark style="color:blue;">add</mark>

**It checks if `a` >= `b`.**

```rust
public fun add(a: Int, b: Int): Int
```

* **@param a:** An Int struct.
* **@param b:** An Int struct.
* **@return Int.** The result of `a` + `b`.

### <mark style="color:blue;">sub</mark>

**It performs `a` - `b.`**

```rust
public fun sub(a: Int, b: Int): Int
```

* **@param a:** An Int struct.
* **@param b:** An Int struct.
* **@return Int.** The result of `a` - `b`.

### <mark style="color:blue;">mul</mark>

**It performs `a` \* `b.`**

```rust
public fun mul(a: Int, b: Int): Int
```

* **@param a:** An Int struct.
* **@param b:** An Int struct.
* **@return Int.** The result of `a` \* `b`.

### <mark style="color:blue;">div\_down</mark>

**It performs `a` / `b` rounding down.**

```rust
public fun div_down(a: Int, b: Int): Int
```

* **@param a:** An Int struct.
* **@param b:** An Int struct.
* **@return Int.** The result of `a` / `b` rounding down.

### <mark style="color:blue;">div\_up</mark>

**It performs `a` / `b` rounding up.**

```rust
public fun div_up(a: Int, b: Int): Int
```

* **@param a:** An Int struct.
* **@param b:** An Int struct.
* **@return Int.** The result of `a` / `b` rounding up.

### <mark style="color:blue;">mod</mark>

**It performs `a` % `b`.**

```rust
public fun mod(a: Int, b: Int): Int
```

* **@param a:** An Int struct.
* **@param b:** An Int struct.
* **@return Int.** The result of `a` % `b`.

### <mark style="color:blue;">pow</mark>

**It performs `base` \*\* `exponent`.**

```rust
public fun pow(base: Int, exponent: u256): Int
```

* **@param base:** An Int struct.
* **@param exponent:** The exponent.
* **@return Int.** The result of `base` \*\* `exponent`.

### <mark style="color:blue;">shr</mark>

**It performs `self` >> `rhs`.**

```rust
public fun shr(self: Int, rhs: u8): Int
```

* **@param self:** An Int struct.
* **@param rhs:** The value to right-hand shift.
* **@return Int.** The result of `self` >> `rhs`.

### <mark style="color:blue;">shl</mark>

**It performs `self` << `lhs`.**

```rust
public fun shl(self: Int, lhs: u8): Int
```

* **@param self:** An Int struct.
* **@param lhs:** The value to right-hand shift.
* **@return Int.** The result of `self` << `lhs`.

### <mark style="color:blue;">or</mark>

**It performs `a` | `b`.**

```rust
public fun or(a: Int, b: Int): Int
```

* **@param a:** The first operand.
* **@param b:** The second operand.
* **@return Int.** The result of `a` | `b`.

### <mark style="color:blue;">and</mark>

**It performs `a` & `b`.**

```rust
public fun and(a: Int, b: Int): Int
```

* **@param a:** The first operand.
* **@param b:** The second operand.
* **@return Int.** The result of `a` & `b`.


# Math64

A set of functions to operate over u64 numbers.

{% hint style="warning" %}
Beware that some operations throw on overflow and underflows.
{% endhint %}

## Structs

### <mark style="color:blue;">**Constants**</mark>

```rust
const MAX_U64: u256 = 18446744073709551615;
```

## Interface

### <mark style="color:blue;">wrapping\_add</mark>

**It performs `x` + `y`.**

{% hint style="info" %}
It will wrap around the `MAX_U64`. `MAX_U64` + 1 = 0.
{% endhint %}

```rust
public fun wrapping_add(x: u64, y: u64): u64
```

* **@param x:** The first operand.
* **@param y:** The second operand.
* **@return u64.** The result of `x` + `y`.

### <mark style="color:blue;">wrapping\_sub</mark>

**It performs `x` - `y`.**

{% hint style="info" %}
It will wrap around zero. 0 - 1 = `MAX_U64`.
{% endhint %}

```rust
public fun wrapping_sub(x: u64, y: u64): u64
```

* **@param x:** The first operand.
* **@param y:** The second operand.
* **@return u64.** The result of `x` - `y`.

### <mark style="color:blue;">wrapping\_mul</mark>

**It performs `x` \* `y`.**

{% hint style="info" %}
It will wrap around. `MAX_U64` \* `MAX_U64` = 0.
{% endhint %}

```rust
public fun wrapping_mul(x: u64, y: u64): u64
```

* **@param x:** The first operand.
* **@param y:** The second operand.
* **@return u64.** The result of `x` \* `y`.

### <mark style="color:blue;">try\_add</mark>

**It tries to perform `x` + `y`. Checks for overflow.**

```rust
public fun try_add(x: u64, y: u64): (bool, u64)
```

* **@param x:** The first operand.
* **@param y:** The second operand.
* **@return bool.** If the operation was successful.
* **@return u64.** The result of `x` + `y`. If it fails, it will be 0.

### <mark style="color:blue;">try\_sub</mark>

**It tries to perform `x` - `y`. Checks for underflow.**

```rust
public fun try_sub(x: u64, y: u64): (bool, u64)
```

* **@param x:** The first operand.
* **@param y:** The second operand.
* **@return bool.** If the operation was successful.
* **@return u64.** The result of `x` - `y`. If it fails, it will be 0.

### <mark style="color:blue;">try\_mul</mark>

**It tries to perform `x` \* `y`.**

```rust
public fun try_mul(x: u64, y: u64): (bool, u64)
```

* **@param x:** The first operand.
* **@param y:** The second operand.
* **@return bool.** If the operation was successful.
* **@return u64.** The result of `x` \* `y`. If it fails, it will be 0.

### <mark style="color:blue;">try\_div\_down</mark>

**It tries to perform `x` / y rounding down.**

```rust
public fun try_div_down(x: u64, y: u64): (bool, u64)
```

* **@param x:** The first operand.
* **@param y:** The second operand.
* **@return bool.** If the operation was successful.
* **@return u64.** The result of x / y. If it fails, it will be 0.

### <mark style="color:blue;">try\_div\_up</mark>

**It tries to perform `x` / y rounding up.**

```rust
public fun try_div_up(x: u64, y: u64): (bool, u64)
```

* **@param x:** The first operand.
* **@param y:** The second operand.
* **@return bool.** If the operation was successful.
* **@return u64.** The result of x / y. If it fails, it will be 0.

### <mark style="color:blue;">try\_mul\_div\_down</mark>

**It tries to perform `x` \* `y` / `z` rounding down. Checks for zero division and overflow.**

```rust
public fun try_mul_div_down(x: u64, y: u64, z: u64): (bool, u64)
```

* **@param x:** The first operand.
* **@param y:** The second operand.
* **@param z:** The divisor.
* **@return bool.** If the operation was successful.
* **@return u64.** The result of `x` \* `y` / `z`. If it fails, it will be 0.

### <mark style="color:blue;">try\_mul\_div\_up</mark>

**It tries to perform `x` \* `y` / `z` rounding up. Checks for zero division and overflow.**

```rust
public fun try_mul_div_up(x: u64, y: u64, z: u64): (bool, u64)
```

* **@param x:** The first operand.
* **@param y:** The second operand.
* **@param z:** The divisor.
* **@return bool.** If the operation was successful.
* **@return u64.** The result of `x` \* `y` / `z`. If it fails, it will be 0.

### <mark style="color:blue;">try\_mod</mark>

**It tries to perform `x` % `y`.**

```rust
public fun try_mod(x: u64, y: u64): (bool, u64)
```

* **@param x:** The first operand.
* **@param y:** The second operand.
* **@param z:** The divisor.
* **@return bool.** If the operation was successful.
* **@return u64.** The result of `x` % `y`. If it fails, it will be 0.

### <mark style="color:blue;">mul</mark>

**It performs `x` \* `y`.**

```rust
public fun mul(x: u64, y: u64): u64
```

* **@param x:** The first operand.
* **@param y:** The second operand.
* **@return u64.** The result of `x` \* `y`.

### <mark style="color:blue;">div\_down</mark>

**It performs `x` / `y` rounding down.**

```rust
public fun div_down(x: u64, y: u64): u64
```

* **@param x:** The first operand.
* **@param y:** The second operand.
* **@return u64.** The result of `x` / `y`.

### <mark style="color:blue;">div\_up</mark>

**It performs `x` / `y` rounding up.**

```rust
public fun div_up(a: u64, b: u64): u64
```

* **@param x:** The first operand.
* **@param y:** The second operand.
* **@return u64.** The result of `x` / `y`.

### <mark style="color:blue;">mul\_div\_down</mark>

**It performs `x` \* `y` / `z` rounding down.**

```rust
public fun mul_div_down(x: u64, y: u64, z: u64): u64
```

* **@param x:** The first operand.
* **@param y:** The second operand.
* **@param z:** The divisor
* **@return u64.** The result of `x` \* `y` / `z`.

### <mark style="color:blue;">mul\_div\_up</mark>

**It performs `x` \* `y` / `z` rounding up.**

```rust
public fun mul_div_up(x: u64, y: u64, z: u64): u64
```

* **@param x:** The first operand.
* **@param y:** The second operand.
* **@param z:** The divisor
* **@return u64.** The result of `x` \* `y` / `z`.

### <mark style="color:blue;">min</mark>

**It returns the lowest number.**

```rust
public fun min(x: u64, y: u64): u64
```

* **@param x:** The first operand.
* **@param y:** The second operand.
* **@return u64.** The lowest number.

### <mark style="color:blue;">max</mark>

**It returns the largest number.**

```rust
public fun max(x: u64, y: u64): u64
```

* **@param x:** The first operand.
* **@param y:** The second operand.
* **@return u64.** The largest number.

### <mark style="color:blue;">clamp</mark>

**Clamps `x` between the range of \[lower, upper]**

```rust
public fun clamp(x: u64, lower: u64, upper: u64): u64
```

* **@param x:** The first operand.
* **@param y:** The second operand.
* **@return u64.** The clamped x.

### <mark style="color:blue;">diff</mark>

**Performs |x - y|.**

```rust
public fun diff(x: u64, y: u64): u64
```

* **@param x:** The first operand.
* **@param y:** The second operand.
* **@return u64.** The difference.

### <mark style="color:blue;">pow</mark>

**Performs n^e.**

```rust
public fun pow(n: u128, e: u128): u128
```

* **@param n:** The base.
* **@param e:** The exponent.
* **@return u128.** The result of n^e.

### <mark style="color:blue;">sum</mark>

**Adds all x in `nums` in a vector.**

```rust
public fun sum(nums: vector<u64>): u64
```

* **@param nums:** A vector of numbers.
* **@return u64.** The sum.

### <mark style="color:blue;">average</mark>

**It returns the average between two numbers (`x` + `y`) / 2.**

{% hint style="success" %}
It does not overflow.
{% endhint %}

```rust
public fun average(x: u64, y: u64): u64
```

* **@param** x: The first operand.
* **@param y**: The second operand.
* **@return u64.** (`x` + `y`) / 2.

### <mark style="color:blue;">average\_vector</mark>

**Calculates the average of the vector of numbers sum of vector/length of vector.**

```rust
public fun average_vector(nums: vector<u64>): u64
```

* **@param nums**: A vector of numbers.
* **@return u64.** The average.

### <mark style="color:blue;">sqrt\_down</mark>

**Returns the square root of `x` number. If the number is not a perfect square, the x is rounded down.**

```rust
public fun sqrt_down(x: u64): u64
```

* **@param a:** The operand.
* **@return u64.** The square root of x rounding down.

### <mark style="color:blue;">sqrt\_up</mark>

**Returns the square root of `x` number. If the number is not a perfect square, the `x` is rounded up.**

```rust
public fun sqrt_up(a: u64): u64
```

* **@param a:** The operand.
* **@return u64.** The square root of x rounding up.

### <mark style="color:blue;">log2\_down</mark>

**Returns the log2(x) rounding down.**

```rust
public fun log2_down(value: u64): u8
```

* **@param x:** The operand.
* **@return u8.** Log2(x).

### <mark style="color:blue;">log2\_up</mark>

**Returns the log2(x) rounding up.**

```rust
public fun log2_up(value: u64): u16
```

* **@param x:** The operand.
* **@return u16.** Log2(x).

### <mark style="color:blue;">log10\_down</mark>

**Returns the log10(x) rounding down.**

```rust
public fun log10_down(value: u64): u8
```

* **@param x:** The operand.
* **@return u8.** Log10(x)

### <mark style="color:blue;">log10\_up</mark>

**Returns the log10(x) rounding up.**

```rust
public fun log10_up(value: u64): u8 
```

* **@param x:** The operand.
* **@return u8.** Log10(x)

### <mark style="color:blue;">log256\_down</mark>

**Returns the log256(x) rounding down.**

```rust
public fun log256_down(x: u64): u8
```

* **@param x:** The operand.
* **@return u8.** Log256(x).

### <mark style="color:blue;">log256\_up</mark>

**Returns the log256(x) rounding up.**

```rust
public fun log256_up(x: u64): u8
```

* **@param x:** The operand.
* **@return u8.** Log256(x).


# Math128

A set of functions to operate over u128 numbers.

{% hint style="warning" %}
Beware that some operations throw on overflow and underflows.
{% endhint %}

## Structs

### <mark style="color:blue;">**Constants**</mark>

```rust
const MAX_U128: u256 = 340282366920938463463374607431768211455;
```

## Interface

### <mark style="color:blue;">try\_add</mark>

**It tries to perform `x` + `y`. Checks for overflow.**

```rust
public fun try_add(x: u128, y: u128): (bool, u128)
```

* **@param x:** The first operand.
* **@param y:** The second operand.
* **@return bool.** If the operation was successful.
* **@return u128.** The result of `x` + `y`. If it fails, it will be 0.

### <mark style="color:blue;">try\_sub</mark>

**It tries to perform `x` - `y`. Checks for underflow.**

```rust
public fun try_sub(x: u128, y: u128): (bool, u128)
```

* **@param x:** The first operand.
* **@param y:** The second operand.
* **@return bool.** If the operation was successful.
* **@return u128.** The result of `x` - `y`. If it fails, it will be 0.

### <mark style="color:blue;">try\_mul</mark>

**It tries to perform `x` \* `y`.**

```rust
public fun try_mul(x: u128, y: u128): (bool, u128)
```

* **@param x:** The first operand.
* **@param y:** The second operand.
* **@return bool.** If the operation was successful.
* **@return u128.** The result of `x` \* `y`. If it fails, it will be 0.

### <mark style="color:blue;">try\_div\_down</mark>

**It tries to perform `x` / y rounding down.**

```rust
public fun try_div_down(x: u128, y: u128): (bool, u128)
```

* **@param x:** The first operand.
* **@param y:** The second operand.
* **@return bool.** If the operation was successful.
* **@return u128.** The result of x / y. If it fails, it will be 0.

### <mark style="color:blue;">try\_div\_up</mark>

**It tries to perform `x` / y rounding up.**

```rust
public fun try_div_up(x: u128, y: u128): (bool, u128)
```

* **@param x:** The first operand.
* **@param y:** The second operand.
* **@return bool.** If the operation was successful.
* **@return u128.** The result of x / y. If it fails, it will be 0.

### <mark style="color:blue;">try\_mul\_div\_down</mark>

**It tries to perform `x` \* `y` / `z` rounding down. Checks for zero division and overflow.**

```rust
public fun try_mul_div_down(x: u128, y: u128, z: u128): (bool, u128)
```

* **@param x:** The first operand.
* **@param y:** The second operand.
* **@param z:** The divisor.
* **@return bool.** If the operation was successful.
* **@return u128.** The result of `x` \* `y` / `z`. If it fails, it will be 0.

### <mark style="color:blue;">try\_mul\_div\_up</mark>

**It tries to perform `x` \* `y` / `z` rounding up. Checks for zero division and overflow.**

```rust
public fun try_mul_div_up(x: u128, y: u128, z: u128): (bool, u128)
```

* **@param x:** The first operand.
* **@param y:** The second operand.
* **@param z:** The divisor.
* **@return bool.** If the operation was successful.
* **@return u128.** The result of `x` \* `y` / `z`. If it fails, it will be 0.

### <mark style="color:blue;">try\_mod</mark>

**It tries to perform `x` % `y`.**

```rust
public fun try_mod(x: u128, y: u128): (bool, u128)
```

* **@param x:** The first operand.
* **@param y:** The second operand.
* **@param z:** The divisor.
* **@return bool.** If the operation was successful.
* **@return u128.** The result of `x` % `y`. If it fails, it will be 0.

### <mark style="color:blue;">mul</mark>

**It performs `x` \* `y`.**

```rust
public fun mul(x: u128, y: u128): u128
```

* **@param x:** The first operand.
* **@param y:** The second operand.
* **@return u128.** The result of `x` \* `y`.

### <mark style="color:blue;">div\_down</mark>

**It performs `x` / `y` rounding down.**

```rust
public fun div_down(x: u128, y: u128): u128
```

* **@param x:** The first operand.
* **@param y:** The second operand.
* **@return u128.** The result of `x` / `y`.

### <mark style="color:blue;">div\_up</mark>

**It performs `x` / `y` rounding up.**

```rust
public fun div_up(a: u128, b: u128): u128
```

* **@param x:** The first operand.
* **@param y:** The second operand.
* **@return u128.** The result of `x` / `y`.

### <mark style="color:blue;">mul\_div\_down</mark>

**It performs `x` \* `y` / `z` rounding down.**

```rust
public fun mul_div_down(x: u128, y: u128, z: u128): u128
```

* **@param x:** The first operand.
* **@param y:** The second operand.
* **@param z:** The divisor
* **@return u128.** The result of `x` \* `y` / `z`.

### <mark style="color:blue;">mul\_div\_up</mark>

**It performs `x` \* `y` / `z` rounding up.**

```rust
public fun mul_div_up(x: u128, y: u128, z: u128): u128
```

* **@param x:** The first operand.
* **@param y:** The second operand.
* **@param z:** The divisor
* **@return u128.** The result of `x` \* `y` / `z`.

### <mark style="color:blue;">min</mark>

**It returns the lowest number.**

```rust
public fun min(a: u128, b: u128): u128
```

* **@param x:** The first operand.
* **@param y:** The second operand.
* **@return u128.** The lowest number.

### <mark style="color:blue;">max</mark>

**It returns the largest number.**

```rust
public fun max(x: u128, y: u128): u128
```

* **@param x:** The first operand.
* **@param y:** The second operand.
* **@return u128.** The largest number.

### <mark style="color:blue;">clamp</mark>

**Clamps `x` between the range of \[lower, upper]**

```rust
public fun clamp(x: u128, lower: u128, upper: u128): u128
```

* **@param x:** The first operand.
* **@param y:** The second operand.
* **@return u128.** The clamped x.

### <mark style="color:blue;">diff</mark>

**Performs |x - y|.**

```rust
public fun diff(x: u128, y: u128): u128
```

* **@param x:** The first operand.
* **@param y:** The second operand.
* **@return u128.** The difference.

### <mark style="color:blue;">pow</mark>

**Performs n^e.**

```rust
public fun pow(n: u128, e: u128): u128
```

* **@param n:** The base.
* **@param e:** The exponent.
* **@return u128.** The result of n^e.

### <mark style="color:blue;">sum</mark>

**Adds all x in `nums` in a vector.**

```rust
public fun sum(nums: vector<u128>): u128
```

* **@param nums:** A vector of numbers.
* **@return u256.** The sum.

### <mark style="color:blue;">average</mark>

**It returns the average between two numbers (`x` + `y`) / 2.**

{% hint style="success" %}
It does not overflow.
{% endhint %}

```rust
public fun average(a: u128, b: u128): u128
```

* **@param** x: The first operand.
* **@param y**: The second operand.
* **@return u128.** (`x` + `y`) / 2.

### <mark style="color:blue;">average\_vector</mark>

**Calculates the average of the vector of numbers sum of vector/length of vector.**

```rust
public fun average_vector(nums: vector<u128>): u128
```

* **@param nums**: A vector of numbers.
* **@return u128.** The average.

### <mark style="color:blue;">sqrt\_down</mark>

**Returns the square root of `x` number. If the number is not a perfect square, the x is rounded down.**

```rust
public fun sqrt_down(a: u128): u128
```

* **@param a:** The operand.
* **@return u128.** The square root of x rounding down.

### <mark style="color:blue;">sqrt\_up</mark>

**Returns the square root of `x` number. If the number is not a perfect square, the `x` is rounded up.**

```rust
public fun sqrt_up(a: u128): u128
```

* **@param a:** The operand.
* **@return u128.** The square root of x rounding up.

### <mark style="color:blue;">log2\_down</mark>

**Returns the log2(x) rounding down.**

```rust
public fun log2_down(x: u128): u8
```

* **@param x:** The operand.
* **@return u8.** Log2(x).

### <mark style="color:blue;">log2\_up</mark>

**Returns the log2(x) rounding up.**

```rust
public fun log2_up(x: u128): u16
```

* **@param x:** The operand.
* **@return u16.** Log2(x).

### <mark style="color:blue;">log10\_down</mark>

**Returns the log10(x) rounding down.**

```rust
public fun log10_down(x: u128): u8
```

* **@param x:** The operand.
* **@return u8.** Log10(x)

### <mark style="color:blue;">log10\_up</mark>

**Returns the log10(x) rounding up.**

```rust
public fun log10_up(x: u128): u8
```

* **@param x:** The operand.
* **@return u8.** Log10(x)

### <mark style="color:blue;">log256\_down</mark>

**Returns the log256(x) rounding down.**

```rust
public fun log256_down(x: u128): u8
```

* **@param x:** The operand.
* **@return u8.** Log256(x).

### <mark style="color:blue;">log256\_up</mark>

**Returns the log256(x) rounding up.**

```rust
public fun log256_up(x: u128): u8
```

* **@param x:** The operand.
* **@return u8.** Log256(x).


# Math256

## Structs

### <mark style="color:blue;">**Constants**</mark>

```rust
const MAX_U256: u256 = 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff;
```

## Interface

### <mark style="color:blue;">try\_add</mark>

**It tries to perform `x` + `y`. Checks for overflow.**

```rust
public fun try_add(x: u256, y: u256): (bool, u256)
```

* **@param x:** The first operand.
* **@param y:** The second operand.
* **@return bool.** If the operation was successful.
* **@return u256.** The result of `x` + `y`. If it fails, it will be 0.

### <mark style="color:blue;">try\_sub</mark>

**It tries to perform `x` - `y`. Checks for underflow.**

```rust
public fun try_sub(x: u256, y: u256): (bool, u256)
```

* **@param x:** The first operand.
* **@param y:** The second operand.
* **@return bool.** If the operation was successful.
* **@return u256.** The result of `x` - `y`. If it fails, it will be 0.

### <mark style="color:blue;">try\_mul</mark>

**It tries to perform `x` \* `y`.**

```rust
public fun try_mul(x: u256, y: u256): (bool, u256)
```

* **@param x:** The first operand.
* **@param y:** The second operand.
* **@return bool.** If the operation was successful.
* **@return u256.** The result of `x` \* `y`. If it fails, it will be 0.

### <mark style="color:blue;">try\_div\_down</mark>

**It tries to perform `x` / y rounding down.**

```rust
public fun try_div_down(x: u256, y: u256): (bool, u256)
```

* **@param x:** The first operand.
* **@param y:** The second operand.
* **@return bool.** If the operation was successful.
* **@return u256.** The result of x / y. If it fails, it will be 0.

### <mark style="color:blue;">try\_div\_up</mark>

**It tries to perform `x` / y rounding up.**

```rust
public fun try_div_up(x: u256, y: u256): (bool, u256)
```

* **@param x:** The first operand.
* **@param y:** The second operand.
* **@return bool.** If the operation was successful.
* **@return u256.** The result of `x` / `y`. If it fails, it will be 0.

### <mark style="color:blue;">try\_mul\_div\_down</mark>

**It tries to perform `x` \* `y` / `z` rounding down. Checks for zero division and overflow.**

```rust
public fun try_mul_div_down(x: u256, y: u256, z: u256): (bool, u256)
```

* **@param x:** The first operand.
* **@param y:** The second operand.
* **@param z:** The divisor.
* **@return bool.** If the operation was successful.
* **@return u256.** The result of `x` \* `y` / `z`. If it fails, it will be 0.

### <mark style="color:blue;">try\_mul\_div\_up</mark>

**It tries to perform `x` \* `y` / `z` rounding up.**

```rust
public fun try_mul_div_up(x: u256, y: u256, z: u256): (bool, u256)
```

* **@param x:** The first operand.
* **@param y:** The second operand.
* **@param z:** The divisor.
* **@return bool.** If the operation was successful.
* **@return u256.** The result of `x` \* `y` / `z`. If it fails, it will be 0.

### <mark style="color:blue;">try\_mod</mark>

**It tries to perform `x` % `y`.**

```rust
public fun try_mod(x: u256, y: u256): (bool, u256)
```

* **@param x:** The first operand.
* **@param y:** The second operand.
* **@param z:** The divisor.
* **@return bool.** If the operation was successful.
* **@return u256.** The result of `x` % `y`. If it fails, it will be 0.

### <mark style="color:blue;">mul</mark>

**It performs `x` \* `y`.**

```rust
public fun mul(x: u256, y: u256): u256
```

* **@param x:** The first operand.
* **@param y:** The second operand.
* **@return u256.** The result of `x` \* `y`.

### <mark style="color:blue;">div\_down</mark>

**It performs `x` / `y` rounding down.**

```rust
public fun div_down(x: u256, y: u256): u256
```

* **@param x:** The first operand.
* **@param y:** The second operand.
* **@return u256.** The result of `x` / `y`.

**Abort**

* It will throw on zero division.

### <mark style="color:blue;">div\_up</mark>

**It performs `x` / `y` rounding up.**

```rust
public fun div_up(x: u256, y: u256): u256
```

* **@param x:** The first operand.
* **@param y:** The second operand.
* **@return u256.** The result of `x` / `y`.

**Abort**

* It will throw on zero division.

### <mark style="color:blue;">mul\_div\_down</mark>

**It performs `x` \* `y` / `z` rounding down.**

```rust
public fun mul_div_down(x: u256, y: u256, z: u256): u256
```

* **@param x:** The first operand.
* **@param y:** The second operand.
* **@param z:** The divisor
* **@return u256.** The result of `x` \* `y` / `z`.

### <mark style="color:blue;">mul\_div\_up</mark>

**It performs `x` \* `y` / `z` rounding up.**

```rust
public fun mul_div_up(x: u256, y: u256, z: u256): u256
```

* **@param x:** The first operand.
* **@param y:** The second operand.
* **@param z:** The divisor
* **@return u256.** The result of `x` \* `y` / `z`.

### <mark style="color:blue;">min</mark>

**It returns the lowest number.**

```rust
public fun min(x: u256, y: u256): u256
```

* **@param x:** The first operand.
* **@param y:** The second operand.
* **@return u256.** The lowest number.

### <mark style="color:blue;">max</mark>

**It returns the largest number.**

```rust
public fun max(x: u256, y: u256): u256
```

* **@param x:** The first operand.
* **@param y:** The second operand.
* **@return u256.** The largest number.

### <mark style="color:blue;">clamp</mark>

**Clamps `x` between the range of \[lower, upper]**

```rust
public fun clamp(x: u256, lower: u256, upper: u256): u256
```

* **@param x:** The first operand.
* **@param y:** The second operand.
* **@return u256.** The clamped x.

### <mark style="color:blue;">diff</mark>

**Performs |x - y|.**

```rust
public fun diff(x: u256, y: u256): u256
```

* **@param x:** The first operand.
* **@param y:** The second operand.
* **@return u256.** The difference.

### <mark style="color:blue;">pow</mark>

**Performs n^e.**

```rust
public fun pow(n: u256, e: u256): u256
```

* **@param n:** The base.
* **@param e:** The exponent.
* **@return u256.** The result of n^e.

### <mark style="color:blue;">sum</mark>

**Adds all x in `nums` in a vector.**

```rust
public fun sum(nums: vector<u256>): u256
```

* **@param nums:** A vector of numbers.
* **@return u256.** The sum.

### <mark style="color:blue;">average</mark>

**It returns the average between two numbers (`x` + `y`) / 2.**

{% hint style="success" %}
It does not overflow.
{% endhint %}

```rust
public fun average(x: u256, y: u256): u256
```

* **@param** x: The first operand.
* **@param y**: The second operand.
* **@return u256.** (`x` + `y`) / 2.

### <mark style="color:blue;">average\_vector</mark>

**Calculates the average of the vector of numbers sum of vector/length of vector.**

```rust
public fun average_vector(nums: vector<u256>): u256
```

* **@param nums**: A vector of numbers.
* **@return u256.** The average.

### <mark style="color:blue;">sqrt\_down</mark>

**Returns the square root of `x` number. If the number is not a perfect square, the x is rounded down.**

```rust
public fun sqrt_down(x: u256): u256
```

* **@param a:** The operand.
* **@return u256.** The square root of x rounding down.

### <mark style="color:blue;">sqrt\_up</mark>

**Returns the square root of `x` number. If the number is not a perfect square, the `x` is rounded up.**

```rust
public fun sqrt_up(x: u256): u256
```

* **@param a:** The operand.
* **@return u256.** The square root of x rounding up.

### <mark style="color:blue;">log2\_down</mark>

**Returns the log2(x) rounding down.**

```rust
public fun log2_down(x: u256): u8
```

* **@param x:** The operand.
* **@return u8.** Log2(x).

### <mark style="color:blue;">log2\_up</mark>

**Returns the log2(x) rounding up.**

```rust
public fun log2_up(x: u256): u16
```

* **@param x:** The operand.
* **@return u16.** Log2(x).

### <mark style="color:blue;">log10\_down</mark>

**Returns the log10(x) rounding down.**

```rust
public fun log10_down(x: u256): u8
```

* **@param x:** The operand.
* **@return u8.** Log10(x)

### <mark style="color:blue;">log10\_up</mark>

**Returns the log10(x) rounding up.**

```rust
public fun log10_up(x: u256): u8
```

* **@param x:** The operand.
* **@return u8.** Log10(x)

### <mark style="color:blue;">log256\_down</mark>

**Returns the log256(x) rounding down.**

```rust
public fun log256_down(x: u256): u8
```

* **@param x:** The operand.
* **@return u8.** Log256(x).

### <mark style="color:blue;">log256\_up</mark>

**Returns the log256(x) rounding up.**

```rust
public fun log256_up(x: u256): u8
```

* **@param x:** The operand.
* **@return u8.** Log256(x).


# CLAMM🐚

Concentrated Liquidity Automated Market Maker

<mark style="color:blue;">Interest Protocol CLAMM</mark> is a decentralized exchange with the following features: <br>

* <mark style="color:blue;">Stable Curve:</mark> A bonding curve specially designed for correlated assets. It combines the constant product invariant (k = x \* y)  with the constant sum invariant (k = x + y) via an amplifier to flatten the curve in the middle. You can read more about it [here](https://miguelmota.com/blog/understanding-stableswap-curve/).
* <mark style="color:blue;">Volatile Curve:</mark> These pools track the prices of the assets via internal oracles using an exponential moving average. It concentrates the liquidity around that price.
* <mark style="color:blue;">Hooks:</mark> Inspired by [UniswapV4 hooks](https://docs.uniswap.org/contracts/v4/concepts/intro-to-v4), Interest Protocol CLAMM implements pool policies. Deployers can customize their pools by implementing custom computation before or after a swap or liquidity position change. This extends the pools to support a myriad of applications such as ERC404, fee on swap, limit orders, custom oracles, etc...
* <mark style="color:blue;">Public Good:</mark> Interest Protocol does not have access to the swap fees. They are all in control of the deployer of the pool. This makes the CLAMM into a public good. It acts as a venue for projects to own the revenue from their protocol coin volume.&#x20;
* <mark style="color:blue;">Passive Liquidity Management:</mark> UniswapV3 requires liquidity providers to actively manage their liquidity to capture fees and reduce impermanent loss. The Interest CLAMM moves the liquidity around automatically. This facilitates liquidity provision for everyone.
* <mark style="color:blue;">One Sided Liquidity:</mark> Liquidity providers are not required to provide or remove both coins in a CLAMM pool. They are free to provide their preferred coin.
* <mark style="color:blue;">LpCoins:</mark> Liquidity in the CLAMM is represed by Coins instead of NFTs. This make sit more composable in DeFi because of its fungibility. You can easily price them by checking the liquidity in the DEX and vistual price.
* <mark style="color:blue;">Multi-coin Pools:</mark> CLAMM pools support more than 2 coins. This allows for more exotic and concentrated pairs.


# Hooks

### <mark style="color:blue;">Design</mark>

Hooks follow the same design principle as Sui's  [Kiosk transfer policy](https://github.com/MystenLabs/sui/blob/main/crates/sui-framework/packages/sui-framework/sources/kiosk/transfer_policy.move). It allows developers to enforce rules to pools. The rules are completed by calling the rule's module and collecting its witness. Rules can be anything from custom oracles to fee on swap.

### <mark style="color:blue;">Hooks</mark>

The **CLAMM** supports 8 hooks:

* <mark style="color:blue;">Start Swap:</mark> This hook must be completed before a swap transaction.
* <mark style="color:blue;">Finish Swap:</mark> A swap transaction must fulfill this hook to finish.
* <mark style="color:blue;">Start Add Liquidity:</mark> This hook must be completed before a user adds liquidity.
* <mark style="color:blue;">Finish Add Liquidity:</mark> A transaction to add liquidity must fulfill this hook to finish.
* <mark style="color:blue;">Start Remove Liquidity:</mark> This hook must be completed before a user removes liquidity.
* <mark style="color:blue;">Finish Remove Liquidity:</mark> A transaction to remove liquidity must fulfill this hook to finish.
* <mark style="color:blue;">Start Donate:</mark> This hook must be completed before a swap transaction.
* <mark style="color:blue;">Finish Donate:</mark> A swap transaction must fulfill this hook to finish.

Pools are not required to have hooks and a pool can have a Start Swap hook without a Finish Swap hook. Hooks are set at deployment and cannot be changed afterwards.

### <mark style="color:blue;">Examples</mark>

We will provide a set of standard hooks that will be automatically resolved via the SDK. Please refer to them on how to use your own hooks!

<https://github.com/interest-protocol/hooks>


# Whitepapers

{% file src="/files/g0cfZJFXyZuQXWQpquTd" %}


# Glossary

<mark style="color:blue;">**APR (Annual Percent Rate):**</mark>  refers to a yearly interest generated by the sum charged to borrowers or paid to investors. It is not compounded, which is why it is always lower than the APY.

<mark style="color:blue;">**APY:**</mark> it is the APR but with compounding effects into consideration. It is also called the real returns.

<mark style="color:blue;">**Bridge:**</mark> An application that allows a token to be transferred between two blockchains.&#x20;

<mark style="color:blue;">**Collateral:**</mark> a token used to secure a loan. It provides a safety net to the lender.

<mark style="color:blue;">**Cross-chain:**</mark> refers to applications or functionalities that involve two or more blockchains. *E.g., in Interest Protocol a user will be able to provide collateral in Ethereum and borrow in BSC.*

<mark style="color:blue;">**DApp:**</mark> Decentralized application.

<mark style="color:blue;">**DEX:**</mark> Decentralized exchange. An automated broker to trade ERC20 tokens.

<mark style="color:blue;">**ERC20:**</mark> It is the interface of all cryptocurrencies issued in EVM blockchains. It is what allows tokens to be transferred and work with DApps.

<mark style="color:blue;">**EVM:**</mark> Ethereum Virtual Machine. Learn more about it [here](https://ethereum.org/en/developers/docs/evm/).

<mark style="color:blue;">**EIP:**</mark> Ethereum Improvement Proposals. Learn more about it [here](https://eips.ethereum.org/).

<mark style="color:blue;">**Farm:**</mark> A contract that rewards a depositor a token as long as he deposits a token on it. *E.g., it is usually used for a way to pay users that deposit LP Tokens.*

<mark style="color:blue;">**Finality:**</mark> How long a user must wait to consider the transaction confirmed.

<mark style="color:blue;">**Isolated Markets:**</mark> Protocols like [*Compound*](https://compound.finance) use <mark style="color:blue;">**one single pool**</mark>, which  means that any collateral can be used to borrow any asset in the pool. In an isolated architecture, the protocol consists of <mark style="color:blue;">**many pools**</mark>. Therefore, Collateral A on Pool A cannot be used to borrow assets in Pool B; thus, it isolates Collateral A risk to Pool A, keeping pool B unexposed.

<mark style="color:blue;">**Keepers:**</mark> An automated system to call contract functions. It is used for maintenance, such as maintaining the right leverage amount in the Dinero Venus Vault.

<mark style="color:blue;">**Lending Protocol:**</mark> A DApp that facilitates loans between users.

<mark style="color:blue;">**Liquidation:**</mark> When a loan is underwater, a third party can close the position by repaying the loan to the lender using a portion of the collateral deposited by the borrower. It usually comes with a penalty fee for the borrower.

<mark style="color:blue;">**LP (Token):**</mark> Liquidity provider tokens are receipt tokens given for users who deposit 2 tokens in DEXs, thus providing a swap market for other users. *E.g., when a user deposits BNB/ETH in PCS. He is giving liquidity for other users to trade BNB and ETH. In exchange, PCS gives them LP Tokens that represent his/her deposit.*

<mark style="color:blue;">**LTV (Loan-to-value-ratio):**</mark> Amount borrowed divided by the collateral supplied in USD.

<mark style="color:blue;">**Mantissa:**</mark> The number of significant digits to represent the quantity of a value. Learn more about it [here](https://www.wikiwand.com/en/Significand).

<mark style="color:blue;">**MasterChef:**</mark> Famous multi-asset staking contract popularized by Sushi Swap.

<mark style="color:blue;">**Maturity Date:**</mark> refers to the date that a loan must be repaid to avoid penalties.

<mark style="color:blue;">**NFT:**</mark> Non-fungible token. They are unique tokens.

<mark style="color:blue;">**Oracle:**</mark> A contract that is able to collect data from the outside world to be used by DApps inside the blockchain. The most famous oracle network is Chainlink.

<mark style="color:blue;">**Pair Lending Market:**</mark> A lending market consisting of two cryptocurrencies. *E.g., In the case of Dinero markets, one is used for collateral and the other for borrows. But in other designs, both of them can be used as collateral and borrows.*

<mark style="color:blue;">**PCS:**</mark> Pancake Swap. The leading DEX in Binance Smart Chain.

<mark style="color:blue;">**Pool:**</mark> refers to a contract that accepts an ERC20 token and rewards for another token. It is similar to a farm but it is meant for non LP tokens. It is usually to incentivize holding or for marketing purposes. *E.g., in PCS, a user can deposit Cake to earn more Cake.*

<mark style="color:blue;">**Over-collateralized Loans:**</mark> Unlike bank or credit loans, in which credit scores and other factors determine how much one can borrow, over-collateralized allow borrowers to borrow a percentage (the LTV - always below 100%) equivalent to their collateral. They allow borrowers to pursue long/short investment positions or attain quick liquidity without losing their portfolio positions.

<mark style="color:blue;">**P2P (Peer-to-Peer):**</mark> A contract that <mark style="color:blue;">**connects a user directly to another user**</mark>. Most lending schemas involve a user to interact with many users via pools. P2P has no pool or other intermediary in the middle. It purely acts as a way to enforce the agreed terms.&#x20;

<mark style="color:blue;">**Rebase Token:**</mark> A cryptocurrency that has an elastic supply. It can reduce or increase the balance of every user based on an algorithm. It is usually used to reward users or used to artificially increase the USD value per token.

<mark style="color:blue;">**Solvent:**</mark> Having assets in excess of liabilities; Being able to pay one's debts.

<mark style="color:blue;">**Stablecoin:**</mark> A cryptocurrency that is pegged to a FIAT currency, usually the American Dollar, USD.

<mark style="color:blue;">**Staking:**</mark> The act of depositing a token in a contract to earn a bonus. It can be voting power, a token, etc... It is usually used when a user deposits in a pool and the term farming is used when a user deposits in a farm.

<mark style="color:blue;">**Supply (Lending):**</mark> It is the act of depositing tokens in a Lending Protocol to be lent out to other users for a fee.

<mark style="color:blue;">**Synthetic:**</mark> A cryptocurrency that pegs its value to a real-world asset through clever financial incentives. *E.g., mTSLA issued by* [*Mirror Protocol*](https://mirrorprotocol.app/#/trade) *pegs to 1 share of Tesla Stock.*

<mark style="color:blue;">**TPS:**</mark> Transactions per second. A blockchain speed must take into account the TPS and finality.&#x20;

<mark style="color:blue;">**TWAP**</mark> <mark style="color:blue;">**(Time-Weighted Average Price):**</mark>  is an asset's average price over a predetermined period of time. They are an effective measure to prevent price manipulations.

<mark style="color:blue;">**TX:**</mark> Transaction. It is anything that can change the blockchain state.

<mark style="color:blue;">**Underwater Position:**</mark> A position in which the LTV is above the maximum LTV of the market. It happens when the collateral price depreciates and makes the position open for liquidation.

<mark style="color:blue;">**Vault:**</mark> A contract that applies an investment strategy to funds collected from users. It lowers investment costs by distributing the transaction costs among all users and requires no active maintenance by depositors to execute the strategy.

<mark style="color:blue;">**vToken:**</mark> A rebase token that represents an amount of underlying Token in Venus. The name was borrowed from Compound that uses cEther. *E.g., vBTC represents an amount of BTC a user has supplied to Venus.*

<mark style="color:blue;">**Wrapped Token:**</mark> A token that holds another token (the wrapped token) and provides extra functionalities to interact with it. The most popular use case is to wrap a blockchain's native currencies such as ETH and BNB to give them ERC20 functionalities to interact with DApps easily.

<mark style="color:blue;">**IPX:**</mark> Interest Protocol token, a token that is rewarded to liquidity providers to ensure that our DEX has enough liquidity to operate.


