# Introducing Kodiak

Leading Decentralized Trading & Liquidity Platform

<figure><img src="/files/be9xw5j9zFSDFV71U0vx" alt=""><figcaption></figcaption></figure>

Kodiak, is the first vertically-integrated liquidity platform combining the following layers:

* [Decentralized Exchange (Kodiak DEX)](/protocol/dex): providing users with a non-custodial, highly capital-efficient trading and liquidity provision experience powered by its concentrated and full-range AMMs.&#x20;
* [Automated Liquidity Manager (Kodiak Islands)](/protocol/islands): attracting sticky deposits from the average user through our set-and-forget automated concentrated liquidity strategy vaults.
* [Integrated Incentive Layer (Sweetened Islands)](/protocol/islands/sweetened-islands): tapping into Berachain’s Proof-of-Liquidity (PoL) mechanism to sustainably incentivize liquidity for Kodiak Islands.
* [No-Code Token Deployer Factory (Panda Factory)](/protocol/panda-factory): facilitating the permissionless deployment of new tokens and their initial (e.g., memecoins) liquidity on the Kodiak full-range AMM (on Berachain) or Uniswap V2 (on Robinhood Chain). This is ideal for highly volatile assets whose price characteristics are undiscovered.&#x20;
* [BGT Auto-Compounding Vaults (Baults)](/protocol/baults): ERC-4626 compatible smart yield-maximizing, yield-bearing vaults that help users automatically grow their Kodiak Island Tokens.
* [Super Aggregator (kX)](/protocol/kx):  advanced swap aggregator and API, automatically finding the best route to swap,  whether or not it's in a Kodiak Liquidity Pool.
* [Decentralized Perpetual Exchange (Kodiak Perps)](/protocol/perps): enabling users to trade the most popular tokens with up to 100x leverage with PoL-powered incentives.

<figure><img src="/files/R7xEiyuBxpPGIeNCXk6M" alt=""><figcaption></figcaption></figure>


# Kodiak x Berachain

Why Berachain?

<figure><img src="/files/7k2DJizUeRQXLEEvi4Tg" alt=""><figcaption></figcaption></figure>

Kodiak is the only DEX incubated by Berachain's Build-a-Bera accelerator program with the mandate of providing Berachain a suite of token launching, trading and liquidity provisioning solutions.

Berachain is a highly performant EVM-compatible layer one blockchain secured by its novel PoL consensus mechanism. For a traditional Delegated Proof of Stake (DPos) network, stakeholders and users must compromise between staking the network's governance token with the validator set to provide security or contributing liquidity to the network's decentralized applications. However, with PoL, the only way to gain the network's governance token (BGT) is by providing liquidity to a set of whitelisted applications, liquidity pools, and/or vaults on the chain. As a result, PoL provides a solution that ensures that liquidity grows in tandem with staking.

The initial set of whitelisted applications starts with the chain-owned DEX (BEX), perpetual futures exchange (Berps), and lending platform (Bend), but will quickly expand to any smart contract deployed on the chain via governance. The Kodiak core team worked closely with the Berachain developer team to ensure that Kodiak’s Islands will be compatible with Berachain’s Proof of Liquidity (PoL) consensus mechanism.

Kodiak and BEX are not competitors, but meant to be complementary with each other. By design, BEX is a full-range AMM and does not offer nor does it plan on offering a concentrated liquidity solution. Additionally, one of the major concerns of concentrated liquidity in the PoL system is that users could sybil farm BGT emissions by providing concentrated liquidity that is either always out of range or in a very tight range. This is where Kodiak comes in with its unique Islands product.

By leveraging our sophisticated back-end infrastructure, Kodiak Islands are automated vaults designed to dynamically adjust concentrated liquidity based on market conditions to optimize risk-adjusted returns with maximal in-range liquidity uptime. Kodiak also leverages liquidity on BEX when an Island needs to be rebalanced. Islands free users from the need for constant manual intervention while also securing Berachain with deep and in-range concentrated liquidity.


# Contact Us

How to reach out to us.

Whether you're an up-coming project planning to launch on Berachain, or an existing project looking for a new DEX to extend your reach, please contact us on Discord or email us at <partnerships@kodiak.finance>.


# Kodiak Contracts

## Kodiak Berachain Mainnet Deployments

<table><thead><tr><th width="244.99993896484375">Name</th><th>Contract Address</th></tr></thead><tbody><tr><td>UniswapV3Factory</td><td>0xD84CBf0B02636E7f53dB9E5e45A616E05d710990</td></tr><tr><td>UniswapV2Factory</td><td>0x5e705e184d233ff2a7cb1553793464a9d0c3028f</td></tr><tr><td>NonfungiblePositionManager</td><td>0xFE5E8C83FFE4d9627A75EaA7Fee864768dB989bD</td></tr><tr><td>SwapRouter</td><td>0xEd158C4b336A6FCb5B193A5570e3a571f6cbe690</td></tr><tr><td>SwapRouter02</td><td>0xe301E48F77963D3F7DbD2a4796962Bd7f3867Fb4</td></tr><tr><td>UniswapV2Router02</td><td>0xd91dd58387Ccd9B66B390ae2d7c66dBD46BC6022</td></tr><tr><td>QuoterV2</td><td>0x644C8D6E501f7C994B74F5ceA96abe65d0BA662B</td></tr><tr><td>MixedRouteQuoterV1</td><td>0xfa0276F06161cC2f66Aa51f3500484EdF8Fc94bB</td></tr><tr><td>kXRouter</td><td>0x43Dac637c4383f91B4368041E7A8687da3806Cae</td></tr><tr><td>kXExecutor</td><td>0xEB109d3935eA00B90b6eBe56e4606a1CdacF0b98</td></tr><tr><td>TickLens</td><td>0xa73C6F1FeC76D5487dC30bdB8f11d1F390394b48</td></tr><tr><td>Multicall</td><td>0x89ff70257bc747F310bB538eeFC46aDD763e75d8</td></tr><tr><td>Multicall3</td><td>0xcA11bde05977b3631167028862bE2a173976CA11</td></tr><tr><td>KodiakIslandFactory</td><td>0x5261c5A5f08818c08Ed0Eb036d9575bA1E02c1d6</td></tr><tr><td>KodiakIslandRouter</td><td>0x679a7C63FC83b6A4D9C1F931891d705483d4791F</td></tr><tr><td>InitHashCodeV2</td><td>0x190cc7bdd70507a793b76d7bc2bf03e1866989ca7881812e0e1947b23e099534</td></tr><tr><td>InitHashCodeV3</td><td>0xd8e2091bc519b509176fc39aeb148cc8444418d3ce260820edc44e806c2c2339</td></tr><tr><td>KodiakIsland</td><td>0xCFe9Ee61c271fBA4D190498b5A71B8CB365a3590</td></tr><tr><td>KodiakFarmFactory</td><td>0xAeAa563d9110f833FA3fb1FF9a35DFBa11B0c9cF</td></tr><tr><td>KodiakFarm</td><td>0xEB81a9EEAF156d4Cfec2AF364aF36Ad65cF9f0fa</td></tr><tr><td>xKDK (pre-TGE)</td><td>0xe8D7b965BA082835EA917F2B173Ff3E035B69eeB</td></tr><tr><td>PandaFactory</td><td>0xac335fe675699b0ce4c927bdaa572eb647ed9f02</td></tr><tr><td>BaultFactory</td><td>0xffCAED1971C28cCcEaff111f4eD2235532537b8F</td></tr><tr><td>BaultRouter</td><td>0x89c8c594f8Dea5600bf8A30877E921a5E63DCCF3</td></tr><tr><td>BountyHelper</td><td>0xF88CA555751f5CDa616b1d97282c9fddA07dD913</td></tr><tr><td>KodiakRewards</td><td>0xBc3dfE5eE6bCE8b301a3661B3528a5c605eAf6aF</td></tr><tr><td>TokenMigrator</td><td>0x88Eb43086EdDf189856af7B00A09259598De8210</td></tr></tbody></table>

### ​Berachain Tokens​ <a href="#berachain-primary-tokens-bartio" id="berachain-primary-tokens-bartio"></a>

<table><thead><tr><th width="246.60003662109375">Name</th><th>Addres</th></tr></thead><tbody><tr><td>WBERA</td><td>0x6969696969696969696969696969696969696969</td></tr><tr><td>xKDK</td><td>0x040EA7D4B559357425407fdFC3c774c5DfC04677</td></tr><tr><td>KDK</td><td>0xc0D1aC00A30fA4e30e44AFc7313d6312c87E21dF</td></tr></tbody></table>

## Kodiak Robinhood Chain Deployments

<table><thead><tr><th width="250.60003662109375">Name</th><th>Address</th><th data-hidden></th></tr></thead><tbody><tr><td>UniswapV2Factory</td><td>0x8bcEaA40B9AcdfAedF85AdF4FF01F5Ad6517937f</td><td></td></tr><tr><td>PandaFactory</td><td>0x5e705e184D233FF2A7cb1553793464a9d0C3028F</td><td></td></tr><tr><td>UniswapV2Router02</td><td>0x89e5db8b5aa49aa85ac63f691524311aeb649eba</td><td></td></tr><tr><td>Multicall3</td><td>0xcA11bde05977b3631167028862bE2a173976CA11</td><td></td></tr></tbody></table>


# Kodiak-Boyco

Q4.69 is here.

<figure><img src="/files/hQJrs3rqrAtxs0amf23u" alt=""><figcaption></figcaption></figure>

## **Boyco Overview:**&#x20;

As Berachain makes its final spring towards Mainnet launch, the Boyco campaign takes center stage as a chain-wide initiative designed to help applications such as Kodiak seamlessly bootstrap liquidity from day one. Through Boyco, Kodiak can effortlessly onboard liquidity directly into our protocol upon mainnet deployment. This ensures that we can focus on innovation and growth within the Berachain ecosystem without being bogged down by early liquidity challenges.

The program also empowers liquidity providers (LPs) by offering a streamlined way to explore and allocate their capital across a variety of protocols. LPs can easily filter opportunities based on asset types, lock durations, application categories, and return profiles, ensuring flexibility and alignment with their personal yield strategies.

Berachain has committed 2% of the BERA supply for the Boyco program. More details can be found in their blog post [here](https://blog.berachain.com/blog/boyco-markets-overview).

Berachain Boyco Website: [https://boyco.berachain.com/ ](<https://boyco.berachain.com/ &#xA;>)

## Kodiak x Boyco:

Kodiak is one of the whitelisted protocols participating in the Boyco campaign. **3%** of the Kodiak token supply (in the form of xKDK) is allocated to participating Boyco markets, allocated proportionately to Bodiak Points. Bodiak Points are allocated proportionately to $ TVL \* Multiplier. The Bodiak Points Multiplier varies for each market and ranges between 1-12x.

There are 48 Boyco markets where all or a portion of the user deposits will flow into the Kodiak DEX on Berachain Mainnet. All of these Boyco markets will have a lock-up period of **90 days**, starting from Berachain's Mainnet launch.

In congruence with the Berachain and the other ecosystem rewards for Boyco, the xKDK incentives will be awarded on a cliff at the end of the market expiration. xKDK is Kodiak’s non-transferable escrowed governance token. Until Kodiak’s official TGE, xKDK neither can be staked nor converted to KDK (the liquid version of the Kodiak token).&#x20;

All liquidity deposited in Kodiak Boyco markets will be bridged over to Berachain and deposited into a corresponding Kodiak Island.

Every Island has a pre-defined strategy, by which the liquidity will be deployed in Kodiak pools (concentrated liquidity).  Each island has a receipt token (ERC20).  In some select Boyco markets, these receipt tokens are also staked with Infrared, and are additionally incentivized by Infrared.  These are our "Flagship" pools and "Infrared x Kodiak."

Regarding how liquidity is deployed, this is different for stable-pairs vs volatile pairs, and within stable-pairs.

**Stable Pairs:**

These include BTCLST-WBTC, ETHLST-WETH, Stablecoin-HONEY, and similar pairs.

All of these will have range centered at "fair price" and a concentrated liquidity range, that ranges from 0 to +/- 15%, determined in conjunction with the asset issuer, and lending protocols.

For example:

* USDT-HONEY, centered at 1.0, range determined with USDT0 team (probably +/- 5%)
* sUSDe-HONEY, centered at \~1.15 (actual price of sUSDe on Ethereum Mainnet), range determined with Ethena team and lending protocols (probably +/- 15%).  Note that as the "fair price" of sUSDe increases over time, Kodiak Islands will re-center the periodically.

**Volatile Pairs:**

These include WETH-HONEY, WBTC-HONEY, and WETH-WBTC.&#x20;

All of these will start full-range, and move to "very wide but effectively full range."  The reason to keep at effectively full range is because there is no other liquidity on Berachain to rebalance with initially, so it must never risk going out of range.  From a economic exposure standpoint, the IL experienced on these should be similar to full-range LP.

The specific ranges we are committing to is - centered around "fair price" and a range of 1/5 to 5x of price.

For example:

* WBTC-HONEY: Centered around \~100k, range 20k-500k.
* WETH-HONEY: Centered around \~3100, range 620-15k.
* WBTC-WETH: same thing.

At no point will these Islands be more "concentrated" or risk higher IL than this during the Boyco period.  The goal of the Kodiak Islands is to keep liquidity active and in-range at all times in order to be eligible for Berachain's Proof-of-Liquidity / BGT.  The goal is to be the baseline liquidity - not to be a fee farm / high IL option. Other ALM providers specialize in these kind of pools, and those options will be made available to interested users through our partner ALM program after mainnet launch.

1. ### Infrared x Kodiak Markets

For these exclusive markets, Infrared will provide additional incentives.

Boyco users will be providing liquidity into the corresponding Kodiak Islands and the Island receipt tokens will also be staked in their respective Infrared iBGT-compatible Vault. The following Boyco Markets fall under this category:

<table data-full-width="false"><thead><tr><th>Boyco Market</th><th>Rewards</th></tr></thead><tbody><tr><td><a href="https://berachain.royco.org/market/1/0/0x17ffd16948c053cc184c005477548e559566879a0e2847e87ebd1111c602535c"><strong>WETH-HONEY LP</strong></a></td><td><ul><li>Berachain: 4.20x Bucket 2 Multiplier</li><li>Kodiak: 12x Bodiak Points</li><li>Infrared: 6x Points</li><li>DEX Fees: Estimated 15-30% APY</li></ul></td></tr><tr><td><a href="https://berachain.royco.org/market/1/0/0x6262ac035c2284f5b5249a690a6fd81c35f1ecef501da089f25741a4492cf5f3"><strong>WBTC-HONEY LP</strong></a></td><td><ul><li>Berachain: 4.20x Bucket Two Multiplier</li><li>Kodiak: 12x Bodiak Points</li><li>Infrared: 6x Points</li><li>DEX Fees: Estimated 15-30% APY</li></ul></td></tr><tr><td><a href="https://berachain.royco.org/market/1/0/0xab37ea8895eed81c4aa76d5dba64441756904b15e78f6ffa5183b0fc1563c1c5"><strong>WBTC-WETH LP</strong></a></td><td><ul><li>Berachain: 4.20x Bucket Two Multiplier</li><li>Kodiak: 10x Bodiak Points</li><li>Infrared: 5x Points</li><li>DEX Fees: Estimated 15-30% APY</li></ul></td></tr><tr><td><a href="https://berachain.royco.org/market/1/0/0xf8f745f188ddb10c16724faee95583521191c3c69e15490fa53c1136b73c17d7"><strong>USDT0-HONEY LP</strong></a></td><td><ul><li>Berachain: 1.35x Bucket Two Multiplier</li><li>Kodiak: 4x Bodiak Points</li><li>Infrared: 1x Points</li><li>DEX Fees: Variable Rate</li></ul></td></tr><tr><td><a href="https://berachain.royco.org/market/1/0/0x72bec627884d7bdf538f174bedd551e9eccf3995adc880f40972e2bab87df3b9"><strong>USDC-HONEY LP</strong></a></td><td><ul><li>Berachain: 1.35x Bucket Two Multiplier</li><li>Kodiak: 3.5x Bodiak Points</li><li>Infrared: 1x Points</li><li>DEX Fees: Variable Rate</li></ul></td></tr><tr><td><a href="https://berachain.royco.org/market/1/0/0xaf2a845c9d6007128b7aec375a4fcdee2b12bbaeb78caf928d3bd08e104417d6"><strong>WETH-beraETH LP</strong></a></td><td><ul><li>Berachain: 2.69x Bucket One Multiplier</li><li>Kodiak: 3x Bodiak Points</li><li>Infrared: 2.5x Points</li><li>Dinero: 520k Points per Week, Pro-Rata</li><li>ETH (Re)Staking Rewards: Variable Rate (for eligible assets)</li><li>DEX Fees: Variable Rate</li></ul></td></tr><tr><td><a href="https://berachain.royco.org/market/1/0/0x5f7935e257b94aee6caf9bbe917d4cfad75e8bc3b231806769ca0935af8371e8"><strong>USDe-HONEY LP</strong></a></td><td><p></p><ul><li>Berachain: 2.69x Bucket One Multiplier</li><li>Kodiak: 3x Bodiak Points</li><li>Infrared: 1x Points</li><li>Ethena: 30x Sats</li><li>DEX Fees: Variable Rate</li></ul></td></tr><tr><td><a href="https://berachain.royco.org/market/1/0/0xad9ee12ea8b3dccf85934c2918bd4ad38ccf7bc8b43d5fcb6f298858aa4c9ca4"><strong>sUSDe-HONEY LP</strong></a></td><td><ul><li>Berachain: 2.69x Bucket One Multiplier</li><li>Kodiak: 3x Bodiak Points</li><li>Infrared: 1x Points</li><li>Ethena: 5x Sats</li><li>Ethena sUSDe Yield: Variable Rate (on sUSDe portion)</li><li>DEX Fees: Variable Rate</li></ul></td></tr><tr><td><a href="https://berachain.royco.org/market/1/0/0x9a117f13c7d5d2b4b18e444f72e6e77c010a1fd90cf21135be75669d66ad9428"><strong>MIM-HONEY LP</strong></a></td><td><ul><li>Berachain: 2.69x Bucket One Multiplier</li><li>Kodiak: 2.5x Bodiak Points</li><li>Infrared: 1x Points</li><li>Abracadabra: 500M total SPELL tokens, pro-rata</li><li>DEX Fees: Variable Rate</li></ul></td></tr><tr><td><a href="https://berachain.royco.org/market/1/0/0x1997c604de34a71974228bca4a66f601427c48960b6e59ff7ebc8e34f43f3ecf"><strong>beraETH-STONE LP</strong></a></td><td><ul><li>Berachain: 1.369x Bucket One Multiplier</li><li>Kodiak: 2x Bodiak Points</li><li>Infrared: 2x Points</li><li>Dinero: 150k Points per Week, Pro-Rata</li><li>StakeStone: 6x Boyco Bonus</li><li>ETH (Re)Staking Rewards: Variable Rate (for eligible assets)</li><li>DEX Fees: Variable Rate</li></ul></td></tr><tr><td><a href="https://berachain.royco.org/market/1/0/0x7ecf55915abe3c24dc5d8365a8edabc8833f4efb8e7c027429c9528aed91ecb7"><strong>WETH-STONE LP</strong></a></td><td><ul><li>Berachain: 2.69x Bucket One Multiplier</li><li>Kodiak: 2x Bodiak Points</li><li>Infrared: 1.5x Points</li><li>StakeStone: 6x Boyco Bonus</li><li>ETH (Re)Staking Rewards: Variable Rate (for eligible assets)</li><li>DEX Fees: Variable Rate</li></ul></td></tr></tbody></table>

2. ### Standard Kodiak Markets

For these markets, Boyco users will be providing liquidity into the corresponding Kodiak Islands (automated liquidity management vaults). Each Kodiak Island represents a tokenized V3 liquidity position within an underlying liquidity range on the Kodiak DEX and facilitates the automated management of this liquidity position. The following Boyco Markets fall under this category:

* [pumpBTC.bera-ylpumpBTC LP](https://berachain.royco.org/market/1/0/0xaa636d73f39ea0de0e04ed9270eac5d943707e7f8fb9c3480c0d80eb015ccfc8) (1x Bodiak Points)&#x20;
* [pumpBTC.bera-ylBTCLST LP](https://berachain.royco.org/market/1/0/0x2fa37184f43783f5d6b23548c4a7a21bb86cd2f314bba9d5bb7d2415d61d11c8) (1x Bodiak Points)&#x20;
* [WBTC](https://berachain.royco.org/market/1/0/0x49104b3cadbb31470e5b949c6892a33954ee9ce35041df4a04a88eb694b645c0)[-waBTC LP](https://berachain.royco.org/market/1/0/0x49104b3cadbb31470e5b949c6892a33954ee9ce35041df4a04a88eb694b645c0) (2x Bodiak Points)&#x20;
* [USDa](https://berachain.royco.org/market/1/0/0xfa4917a871f9cf06d3d00be6678993888b3aac41c3da21edf32c3c9cf3978d70)[-HONEY LP](https://berachain.royco.org/market/1/0/0xfa4917a871f9cf06d3d00be6678993888b3aac41c3da21edf32c3c9cf3978d70) (2x Bodiak Points)&#x20;
* [sUSDa-USDa LP](https://berachain.royco.org/market/1/0/0xd70673b98af7096f575717d70fbf2fa935dd719926b55c0e011480678cdac563) (1x Bodiak Points)&#x20;
* [USDe-USDa LP](https://berachain.royco.org/market/1/0/0xab689b5eac7541b8cc774f0ca3705a91b21660e8221fc7bd8e93c391fb5d690d) (1x Bodiak Points)&#x20;
* [rUSD-HONEY LP](https://berachain.royco.org/market/1/0/0xcdb30c06ea11f3f5408bce5eefdb392dfe0008ef81af3a486bcfed891f9cc112) (2x Bodiak Points)
* [beraETH-RSWETH LP](https://berachain.royco.org/market/1/0/0x3ef317447bd10825f0a053565f8474a460cfb22cda414ea30b671e304f0691b6) (1x Bodiak Points)
* [ WBTC-uniBTC LP](https://berachain.royco.org/market/1/0/0x568f3bb6ba4c6afe37899fda35bc315ae8167274685ea295e03cf20d471afd8b) (2x Bodiak Points)
* [SBTC-WBTC LP](https://berachain.royco.org/market/1/0/0x289dc2a22ebb4ef7404de9293b6718d9f81f0843e1af4cf9a9c51d2e757348d6) (2x Bodiak Points)
* &#x20;[WBTC-SolvBTC LP](https://berachain.royco.org/market/1/0/0x290aad1fabd8d2557d28a3854a2433ddc11a35f0d12936dd99102067ac515d07) (2x Bodiak Points)
* [SolvBTC-SolvBTC.BBN LP](https://berachain.royco.org/market/1/0/0x378d4d32d89450978d01cfdf1ff1907d4419aa186c48abb94e612b76d75f3fae) (1x Bodiak Points)
* [WBTC-pumpBTC.bera LP](https://berachain.royco.org/market/1/0/0xa74b61544834483b093531cff533d01788a5dea12d8a83902646111025303bfb) (2x Bodiak Points)
* [WBTC-stBTC LP](https://berachain.royco.org/market/1/0/0x9b60d30f266858fa671bf268796aa503700310e31a8f46ebaa8f8281fbad89aa) (2x Bodiak Points)
* [uniBTC-ylBTCLST LP](https://berachain.royco.org/market/1/0/0x21c6a0baa6f41b060937be5a4f1be096b63f426c50f763b4dabd1af46803fa2f) (1x Bodiak Points)
* [FBTC-SolvBTC LP](https://berachain.royco.org/market/1/0/0xc5165360e2e8b195cb55e21cf259ce6a5ee996b055057d8705851d9b01fc8620) (1x Bodiak Points)
* [pumpBTC.bera-FBTC LP](https://berachain.royco.org/market/1/0/0xab27dc8061f66791bb94a536546b08ba15e06344dabad2cc6267cf44f0070574) (1x Bodiak Points)
* [WBTC-FBTC LP](https://berachain.royco.org/market/1/0/0xd6e9ff1fa0c9c6bb25cafcb76c61c0d398a479ba073509e10209271f40a01712) (2x Bodiak Points)
* [rsETH-beraETH LP](https://berachain.royco.org/market/1/0/0x25f7a422282a1f26d9d96b5d1c43fa5c6f8c355b0ed7a4755ac8d04a504817f5) (1x Bodiak Points)
* [rsETH-ylrsETH LP](https://berachain.royco.org/market/1/0/0x460ec133419318efe4e05b4c3b6db421503fd6fcefbb20a43f50e3fc50f2ee39) (1x Bodiak Points)
* [beraETH-ylstETH LP](https://berachain.royco.org/market/1/0/0x219169d9e78064768cddd0397c2202dc9e5c2bc0e1dbc13465363b0458d33c34) (1x Bodiak Points)

3. ### Beraborrow x Kodiak Markets

These are markets that are additionally incentivized by Beraborrow for actions that involve the minting of their stablecoin, NECT. The following Boyco Markets fall under this category:

* [Kodiak x Beraborrow WBTC-HONEY to mint NECT](https://berachain.royco.org/market/1/0/0xcdd60ed30d20f9edc3fac624bb623db32103658b6da678949ef53df16139b488) (6x Bodiak Points)
* [Kodiak x Beraborrow WETH-HONEY to mint NECT](https://berachain.royco.org/market/1/0/0xf8663b3c0f78b4efae0422b163e86e79afa1ce90778885d93d53c9d4f6d5c3d8) (6x Bodiak Points)
* [Kodiak x Beraborrow WBTC-WETH to mint NECT](https://berachain.royco.org/market/1/0/0x568d2509ec17c27426a9d55e58673160c937aeaedc0a3fcc7c63c5b7df495ec7) (5x Bodiak Points)
* [NECT-HONEY LP](https://berachain.royco.org/market/1/0/0x62bb6fb784e059f338340a9724b35ef2ef8fde5e65613e9fcaacd097d81dc67e) (2.5x Bodiak Points)
* [USDe-NECT LP](https://berachain.royco.org/market/1/0/0x2240151f263be555a4ef61476a5c111373e0efe8cd539f179b4b5850977e9d4e) (1x Bodiak Points)

4. ### Concrete x Ethena & Concrete x Lombard Markets

These are markets additionally incentivized by Concrete x Ethena and Concrete x Lombard, deploying a portion of the deposited TVL into their respective Kodiak Islands. **Only the portion of the TVL deposited into these markets that are then deposited into Kodiak Islands are eligible for the Bodiak Points.** The following Boyco Markets fall under this category:

* [Supply WBTC to Concrete x Lombard Vault](https://berachain.royco.org/market/1/0/0xece925dbccbb21333dbe99679fef655ad2dc2cb185e0963711c944e302595b28) (3x Bodiak Points for Eligible Assets)
* [Supply LBTC to Concrete x Lombard Vault](https://berachain.royco.org/market/1/0/0xa31a8bb230f77a5d286985b92fe8d0c7504a1892568d70685659f781aec78209) (3x Bodiak Points for Eligible Assets)
* [Supply sUSDe to Concrete x Ethena Vault](https://berachain.royco.org/market/1/0/0x3d7cf2bd0a04fd3c66a5fa334a399b3926efe0fc0450b8da49a5da29f2c36d7f) (3x Bodiak Points for Eligible Assets)
* [Supply USDe to Concrete x Ethena Vault](https://berachain.royco.org/market/1/0/0x5043bfe3f6bab5fa4c8f19fb2f6856de2d2e717a541e0d7126b308926be04e2e) (3x Bodiak Points for Eligible Assets)

5. ### Ether.Fi x Veda Markets

These are markets additionally incentivized by Ether.Fi x Veda, deploying a portion of the deposited TVL into their respective Kodiak Islands. **Only the portion of the TVL deposited into these markets that are then deposited into Kodiak Islands are eligible for the Bodiak Points.** The following Boyco Markets fall under this category:

* [Veda x Ether.fi eBTC Vault - wBTC Supply](https://berachain.royco.org/market/1/0/0xb36f14fd392b9a1d6c3fabedb9a62a63d2067ca0ebeb63bbc2c93b11cc8eb3a2) (3x Bodiak Points for Eligible Assets)
* [Veda x Ether.fi eBTC Vault - LBTC Supply](https://berachain.royco.org/market/1/0/0xabf4b2f17bc32faf4c3295b1347f36d21ec5629128d465b5569e600bf8d46c4f) (3x Bodiak Points for Eligible Assets)
* [Veda x Ether.fi weETH Vault](https://berachain.royco.org/market/1/0/0xff0182973d5f1e9a64392c413caaa75f364f24632a7de0fdd1a31fe30517fdd2) (3x Bodiak Points for Eligible Assets)
* [Veda x Ether.fi weETH Vault - wETH Supply](https://berachain.royco.org/market/1/0/0x0484203315d701daff0d6dbdd55c49c3f220c3c7b917892bed1badb8fdc0182e) (3x Bodiak Points for Eligible Assets)

6. ### Goldilocks Markets

These are markets not incentivized by Kodiak directly, but instead by Goldilocks and relevant asset issuers. The following Boyco Markets fall under this category:

* [Supply uniBTC into Goldilocks](https://berachain.royco.org/market/1/0/0x72679855f582a6d908bf39d40cb5a299b6a98a82bf1bfd9055f1853fc5160f54)
* [Supply solvBTC.bbn into Goldilocks](https://berachain.royco.org/market/1/0/0xbd3ef685577bdca03225bb2cd2158f0772cdfd694ba03b9eb4856b59a7288081)
* [Supply rsETH into Goldilocks](https://berachain.royco.org/market/1/0/0xab32e1695b84b148140cb78c044d247e307b26cb043dc5538657f3a5634dee6e)


# DEX

Kodiak's Decentralized Exchange.

The Kodiak DEX is a decentralized exchange native to Berachain. The DEX is powered by its V2 (full-range) and V3 (concentrated) AMMs, both of which are based on their respective Uniswap AMM designs.

* Traders: enjoy seamless, low-slippage token swaps when liquidity for both tokens are sufficient.
* Liquidity Providers: flexibility to choose from various liquidity provision methods, some of which optimize fee efficiency.

{% hint style="info" %}
Kodiak's V2 AMM is based on Uniswap V2, which is powered by the constant product formula (𝑥 · 𝑦 = 𝑘). For technical documentation, please refer to [Uniswap's V2 Protocol documentation](https://docs.uniswap.org/contracts/v2/overview).\
\
Kodiak's V3 AMM is based on Uniswap V3, which introduced the concept of deploying liquidity at a specific price range. For technical documentation, please refer to [Uniswap's V3 Protocol documentation](https://docs.uniswap.org/contracts/v2/overview). \
\
However, unlike Uniswap, Kodiak has the fee switch turned on from the start.
{% endhint %}


# Swaps

Trading tokens on the Kodiak DEX.

The Kodiak DEX enables users to swap between two tokens with liquidity in the protocol. Token swaps are optimized for users by Kodiak's Pathfinder router, which automatically finds the best route across V3 and V2 liquidity pools for efficient trade execution.

This smooth process relies on the availability of ample liquidity for the desired token pair. When liquidity is sufficient, swaps are executed as single hops, resulting in lower fees and minimized slippage for users. In situations with limited liquidity between input and output tokens, Pathfinder utilizes multi-hop swaps, intelligently linking multiple pools to complete the exchange smoothly.&#x20;

Through Kodiak's frontend web app, users have the power to customize their swaps according to their preferences. They can adjust parameters such as:

* Swap Tokens: Select the input and output tokens for the swap.
* Swap Token Quantity: Set the fixed input or output token quantity for the swap.
* Slippage Tolerance: Set the maximum slippage allowed for the swap (default is set to Auto).
* Show Chart: Display the corresponding token pair's price chart (default is set to hide the chart).

<figure><img src="/files/26rWtV68NRuasdUEkrnM" alt=""><figcaption><p>Swap Page</p></figcaption></figure>

**User Guide**

See user guides for:

* Standard swap: [Swap](/user-guide/swap)&#x20;
* Multi swap: \<add user guide>
* Advanced:&#x20;
  * Limit Order: [Limit Orders](/user-guide/limit-orders)
  * TWAP: [TWAP](/user-guide/twap)
  * TP / SL: \<add user guide>

Standard and Multi swaps are powered by Kodiak's advanced swap aggregator [kX](/protocol/kx)

Advanced Orders (Limit, TWAP, TP, SL) functionality is powered by [Orbs Network](https://www.orbs.com/), a decentralized L3 for advanced trading.


# Liquidity Provision

Providing liquidity to the Kodiak DEX.

{% hint style="warning" %}
Providing liquidity comes with the risk of impermanent loss, which occurs when the value of tokens in a liquidity pool diverges from holding those tokens directly in one's wallet due to price changes.
{% endhint %}

The Kodiak DEX enables users to provide liquidity to the protocol and earn trading fees. Users have the flexibility in providing liquidity on the DEX in the following ways:

## Islands (Auto-Managed) Liquidity

<figure><img src="/files/8oWcHhkRIADVkguBjqFc" alt=""><figcaption><p>Island Vaults Page</p></figcaption></figure>

Depositing liquidity into one of Kodiak's Islands represents is the most straightforward method for contributing liquidity on the Kodiak DEX. These Islands are automated liquidity management vaults with predefined rules tailored for V3 liquidity. These rules are designed to establish optimal ranges for a given Island's token pair and systematically rebalance liquidity to ensure that it consistently remains in-range.&#x20;

Providing V3 custom liquidity (see below) offers Liquidity Providers (LPs) with more autonomy in managing their concentrated liquidity. However, it involves labor-intensive efforts, requiring LPs to continuously monitor and manually adjust their positions based on their strategies. Additionally, with V3 custom liquidity positions, LPs earn fees solely for trades within their chosen tick range. If prices move outside this range, their liquidity stops earning fees until prices return inside the selected range or LPs manually readjust their tick ranges. On the contrary, Island LPs continuously earn trading fees while still benefiting from the fee efficiency of concentrated liquidity since Islands are designed to keep liquidity always in-range.

For more details on Kodiak Islands, head over to the [Islands](/protocol/islands) section.

## V3 (Concentrated) Liquidity

<figure><img src="/files/AtY2m9XqQiwCp80CFjat" alt=""><figcaption><p>V3 Pools Page</p></figcaption></figure>

The Kodiak V3 AMM, based on Uniswap V3, provides users with the ability to create V3 (concentrated) liquidity positions for a token pair. These positions focus liquidity on a specific price range, represented by ticks. By concentrating liquidity within two ticks, Liquidity Providers can capture more trading fees when swaps occur within that range and potentially mitigate impermanent loss risk compared to providing V2 (full-range) liquidity.

When users create V3 liquidity positions, they receive an ERC-721 Non-Fungible Token (NFT) as a receipt token. This NFT position contains information about the price range that the liquidity is concentrated in, the amount of each token contributed, the fee tier selected for the provided liquidity and other parameters specific to the liquidity provision. For each token pair, distinct liquidity pools exist for each of the unique fee tiers where liquidity is deployed.

The NFT position serves as a distinct receipt token, enabling LPs to effectively manage and monitor their specific liquidity contribution within the pool. For each V3 liquidity position, the LP can also choose to increase or remove (all or a portion) of their liquidity. When liquidity is removed, the LP will also automatically claim the accrued trading fees proportionate to the liquidity withdrawal amount. Accumulated fees can also be manually claimed without removing liquidity.

## V2 (Full-Range) Liquidity

<figure><img src="/files/GPsrCXgElupA9yg90ArB" alt=""><figcaption><p>V2 Pools Page</p></figcaption></figure>

The Kodiak V2 AMM, based on Uniswap V2, allows users to provide an equal value of two tokens to a liquidity pool.&#x20;

For V2 liquidity, liquidity positions are represented as shares of the liquidity pool. When a liquidity provider contributes to a V2 liquidity pool, they receive ERC-20 LP tokens representing their proportional ownership of that specific pool. These LP tokens serve as a proof of ownership in the pool's liquidity.&#x20;

V2 liquidity providers do not need to manually claim fees. Instead, fees are automatically accrued and added to the liquidity pool over time. As trades occur within the liquidity pool, a portion of the trading fees is distributed proportionally among liquidity providers based on their share of the liquidity provided. This process continuously compounds, increasing the LP's holdings in the pool, including their earned fees, all while remaining within the pool's liquidity.&#x20;


# Trading Fees

Details on the Kodiak DEX trading fees.

## Trading Fees

Users incur fees when swapping tokens, and the fee structure differs between V2 and V3 liquidity pools:

* **V2 Liquidity**: In V2, fees remain uniform (***0.3%***) across the entire liquidity pool for a token pair. Trades routed exclusively through V2 incur a fee determined by the liquidity provider for that pool, applied as a percentage of the trade amount.
* **V3 Liquidity**: V3's fee structure varies within different price ranges or liquidity positions. Trades routed through V3 encounter fees contingent on the specific price range they interact with. Consequently, if a trade spans multiple ranges, it incurs varying fees based on each range's fee tier. Below is the list of available fee tiers each liquidity provider can set for their V3 liquidity positions:
  * 0.05%
  * 0.3%
  * 1%
  * 2%
* **Both V2 and V3 Liquidity**: Trades routed through both V2 and V3 liquidity accrue fees based on the specific pools and price ranges they engage with along their path. Fees accumulate from multiple pools or different price ranges across V2 and V3 liquidity, resulting in a cumulative fee for the trade.
* **Advanced Orders**: An additional fee of 0.17% that goes to incentivize [Orbs Network](https://www.orbs.com/).

## Trading Fees Split

Since the fee switch is turned on at Kodiak's launch, trading fees generated on the Kodiak DEX are split in the following way for the different liquidity provision options:

V3  Trading Fees:

* Liquidity Providers (LP): 65%
* Protocol: 35%

V2 Trading Fees:

* Liquidity Providers (LP): 83.33%
* Protocol: 16.67%


# Islands

Kodiak's automated liquidity management vaults.

<figure><img src="/files/qvclced9OtBtdI7jtZvV" alt=""><figcaption></figcaption></figure>

Introduction to Automated Liquidity Management (ALM)

Concentrated liquidity in Kodiak V3 pool offers significantly higher capital efficiency compared to traditional AMMs, but it comes with increased complexity in liquidity management. As liquidity providers need to actively manage their positions to maintain optimal ranges as prices move, Automated Liquidity Management (ALM) solutions become essential for efficient capital deployment.

#### What are Kodiak Islands?

Kodiak Islands are ERC20-wrapped Kodiak V3 positions that enable simplified liquidity provision through a fungible token interface. When users add liquidity to an Island, they receive Kodiak Island tokens representing their proportional ownership of the underlying Kodiak V3 position. These tokens can be freely transferred, traded, or redeemed for the underlying assets at any time.

Key benefits:

* Simplified liquidity provision through standard ERC20 interface
* Liquidity is rebalanced to stay "in range" and balanced around "fair price" (for managed Islands)
* Compatible with Berachain Proof-of-Liquidity, and eligible for BGT whitelisting
* Fungible ERC-20 representation of Concentrated Liquidity positions
* Automatic fee compounding
* Rebalance using liquidity through-out Berachain, not just what's in the pool

### Types of Kodiak Islands

* **Kodiak Islands** - Kodiak Islands are deployed and permissioned by Kodiak Protocol and rebalanced by permissioned parties (manager) authorized by the Kodiak Protocol.  Each Island has a strategy designed to keep the Island "in range" around "fair price" in order to be compatible with Proof-of-Liquidity.  For each island, the strategy involves determining the "fair price" (with an off-chain, external oracle), a range around that price (determined based on the volatility of the underlying pool), and a rebalancing frequency.  Kodiak Islands charge a manager fee of 10% of LP fees generated; these are used to fund and cover all gas fees, infrastructure, R\&D, and other operational costs of "running the Island."
* **Permissionless Islands** - Deployed by anyone, this enables anyone to create ERC-20 wrappers on a particular "fixed range" Kodiak V3 pool of their choice. For trust minimization, once the Island is deployed, the ranges cannot be adjusted. Permissionless Islands can be used to ERC-20 tokenize concentrated liquidity positions to assist with incentivization (Kodiak Farms or BGT), or to encourage pooled liquidity in a particular range. Permissionless Islands are also automatically whitelisted and discoverable in the Kodiak Frontend, along with analytics. Permissionless Islands charge a manager fee of 10% of LP fees generated, used to fund and cover all operational costs.


# Island Liquidity Provision

Depositing liquidity into Islands.

<figure><img src="/files/lMFhTFjeacvhHb54O41E" alt=""><figcaption></figcaption></figure>

Depositing liquidity into one of Kodiak's Islands represents is the most straightforward method for contributing liquidity on the Kodiak DEX. These Islands are automated liquidity management vaults with predefined rules tailored for V3 liquidity. These rules are designed to establish optimal ranges for a given Island's token pair and systematically rebalance liquidity to ensure that it consistently remains in-range.&#x20;

When liquidity is added to an Island, the protocol responds by minting Kodiak Island shares, which are then allocated to the liquidity provider. On the other hand, the burning of Kodiak Island shares facilitates the redemption of a corresponding portion of the pool's V3 position liquidity, accompanied by the retrieval of earned fees. Essentially, holding Kodiak Island shares represents proportional ownership or shares of the underlying V3 position.

The minted Kodiak Island shares are ERC-20 tokens which can be staked into a Farm or PoL Reward Vaults to earn additional incentives for eligible Islands (Sweetened Islands) or rehypothecated throughout various Berachain DeFi applications.&#x20;


# Sweetened Islands

Incentive layer for Islands.

Kodiak Sweetened Islands are specific Islands that are incentivized with one or more token rewards. The rewards that you earn from these Kodiak Sweetened Islands are proportional to the amount of liquidity that you provide. This means that the more tokens you stake, the more rewards you will earn.

Users engaging with Sweetened Islands are required to stake their deposited liquidity to access additional rewards. There are two types of Sweetened Islands:

1. **Farms:** Islands where Kodiak and partner protocols are incentivizing deposits into specific Islands. These rewards have the potential to be augmented through a multiplier factor, contingent upon the chosen duration for which a user opts to lock their staked Island liquidity position (ranging from 0 to 30 days). Adding a layer of versatility, users have the option to apply multiple locks, enabling them to segregate and customize various portions of a given Island liquidity position.

<figure><img src="/files/AO18s7CO9w0YA2kOBkom" alt="" width="354"><figcaption></figcaption></figure>

2. **Reward Vaults:** Islands with their Island Shares (LP token) whitelisted for Berachain's Proof of Liquidity (PoL) Reward Vaults and are thus eligible for BGT emissions. Sweetened Islands that are earning BGT emissions are clearly marked by the BGT logo under the `APR` column of the `Top Pools` tab of the `Liquidity` page. Unlike Farms, users that deposit and stake their Island Shares with the respective Reward Vault (can be done directly within the Kodiak dApp) do not have the option to lock up their stake for a set duration to earn a multiplier on their rewards — this also means that user's can unstake from a Reward Vault at any given time.

<figure><img src="/files/Jh9kG5YFHHfY8Jc5ofRa" alt=""><figcaption></figcaption></figure>


# Island Mechanics

See detailed sections


# Auto-BGT

Kodiak Islands were designed specifically to be compatible with PoL. As such, in order to optimize yield for both liquidity providers (LPs) and BGT delegates of validators that include the corresponding Kodiak Island in their cutting board, Kodiak is introducing a project-specific opt-in mechanism. This will dynamically adjust the allocation of LP fees, directing them toward reward vault incentives instead of distributing them directly to LPs. In fact, up to 100% of LP fees can be redirected to reward vaults.

Why does this make sense? By design, PoL incentivizes protocols to direct rewards toward validators, encouraging them to allocate BGT emissions to whitelisted reward vaults rather than directly rewarding LPs. The rationale is simple: the value of BGT emissions secured from validators should exceed the value of incentives given to validators.

As a result, when applicable, LPs stand to gain higher overall yields when their traditional fees are redirected into reward vault incentives. This also sets off a flywheel effect—LPs who earn BGT through these incentives can then delegate their BGT to validators that include their relevant Kodiak Islands, further boosting their earnings by reclaiming a share of the LP fees initially redirected. With this mechanism, PoL benefits from sustainable reward vault incentives, proportional to the value generated by the ecosystem.

<figure><img src="/files/cpnXetkN78norkz8DCiR" alt=""><figcaption></figcaption></figure>

**Auto-BGT Requirements** <br>

To enable Auto-BGT for a Kodiak Island, the following conditions must be met:

* The pool must be a "managed" Kodiak Island (no V2, no "permissionless" islands).&#x20;
* The pool must be BGT whitelisted with an actively used reward vault that is earning BGT emissions.
* The pool’s fee tier must be 0.3% or higher. &#x20;
* Two of the reward vault’s incentive tokens (out of the three maximum) must match the two assets in the underlying pool.

**How LP Fee Redirection Works**

When Auto-BGT is active, the Liquidity Provider portion of the fees are redirected to the corresponding Reward Vault Contract Address. During the current pilot phase, these distributions are semi-automated and occur once per week, with full automation on the way.

Currently (as of May 2025), up to 90% of the Liquidity Provider portion of the fees are redirected to the Reward Vault.  This share is configured the same for all pools participating in the Auto-BGT program, and is set at a high rate as $1 in incentives translates to much more than $1 in BGT earned, making this positive-sum for LPs staked in Reward Vaults.

**How to Add Incentives**

Once the LP fees are redirected to the Reward Vault, it is the responsibility of the Reward Manager to decide the rate and pace at which to add incentives. &#x20;

Each Reward Vault has a Reward Manager for every incentive token, who can review and Approve incoming third-party incentives under the specific Reward Vault's “Pending” section on Berachain Hub.

![](/files/s52skNjMJ9wfgsYYmL47)

:warning: The Incentive Rate must be set before adding incentives.  When executing the “Approve” transaction from the "Pending" section, the selected amount of tokens will be added as incentives using the current incentive rate. If you wish to apply a different rate, be sure to adjust the incentive rate prior to approval.

:warning: Consistently adding the incentives to the reward vault and ensuring BGT is actually emitted to LPs is a requirement for continued participation in the Auto-BGT program


# Real-time Security

All managed, whitelisted Kodiak Islands have real-time pre-crime security monitoring with our security partner HyperNative. HyperNative uses their advanced threat detection algorithms to detect "hacks before they happen." Kodiak Islands are configured to automatically pause \*all\* islands in case malicious activity is detected in any \*one\* of them.  If a malicious threat were to be detected, all deposits and withdrawals are paused until the security partner (HyperNative) investigates.

As of May 2025, a pausing event has been triggered one time (on April 26, 2025) based on HyperNative's monitoring.  Upon investigation, we learned that the alert is benign and a standard arbitrage contract was mistakenly tagged as malicious.  There was never any risk to any Kodiak Islands or user funds, nor was there any malicious targeting.  All islands were promptly unpaused and normal operations resumed within one hour.

Read more here: [https://www.hypernative.io/blog/meet-berachain-projects-joining-hypernatives-ecosystem-wide-security-umbrella](https://www.hypernative.io/blog/meet-berachain-projects-joining-hypernatives-ecosystem-wide-security-umbrella?utm_source=x\&utm_medium=organic_social\&utm_content=berachain-blog-kodiak)

Additionally, all islands are continuously monitored against standard parameters, any abnormal conditions are automatically flagged with both soft and hard thresholds.  For example, islands with high idle balances (indicating a rebalance needs to occur) or ratios that are off from target are automatically flagged using HyperNative Agents.  All large transfers are also monitored for abnormal activity.


# Rebalancing

There are 3 types of rebalance functions, each is described below

Permissionless Rebalance (cannot change range, cannot do swap): `rebalance`

The standard permissionless rebalance harvests fees, and re-adds it maximally into the LP without doing any swap.  This can be called by anyone.  In general, permissionless rebalances are called at least once per day on all Islands by bots.

Basic Rebalance (change range, can only do swap in own pool): `executiveRebalance`&#x20;

The basic permissioned rebalance can be used to change the range, but it can only swap within the underlying Kodiak V3 pool.  This function is generally only used to change the range when no swap is required (such as setting up a new island).  Only the `manager` role can call this function.  This function and underlying mechanism was taken from ArrakisV1 contracts.

Full Rebalance (change range, swap through any whitelisted router): `executiveRebalanceWithRouter`

The full rebalance function is a Kodiak native feature, that allows rebalance operations to occur while routing liquidity through any whitelisted external router.  All rebalance with swaps now use the Full Rebalance feature, using all available liquidity on Berachain.

*Routing through external routers*:

* Rebalances use Kodiak's meta-aggregator [kX](/protocol/kx), which routes through all possible liquidity sources to give the best possible quote for the Island (including routing through all non-Kodiak venues)
* The minimum output / slippage is strictly enforced to have a very tight slippage, both off-chain and using an on-chain TWAP on the pool itself
* Each rebalance swap is monitoring for potential MEV impacts

*The size and pace of rebalance swaps are limited by*:

* Liquidity (slippage cannot be too high) through Berachain
* Volumes (Kodiak rebalances cannot be too large a share of the pool volume)
* Current price relative to recent TWAP ("Opportunistic" rebalancing)

:warning: Kodiak Islands cannot arbitrarily change asset ratios, only gradually with rebalances (+ swaps) that are constrained by the parameters listed above.&#x20;


# Strategies

**Asset-specific strategies, as for May 2025 (post Boyco unlocks):**

**BGT LSTs**

BGT LSTs (iBGT, yBGT, LBGT, osBGT, stBGT, etc) have a unique property in that they have a effective "floor price" at 0.95-1 BERA (since the underlying BGT can be redeemed, and LSTs provide redemption functions). &#x20;

When Berachain first launched, all the BGT LST islands were set to have a high upper end to the price (5.0/BERA in iBGT-BERA, for example).   While there is no technical upper bound in price, the trading range has peaked around 2-2.5 BERA.  As of May 2025 - the Berachain Foundation has indicated that the expected price based on their modeling is around 1.25/BERA.&#x20;

Based on the most recent data and feedback from asset issuers, the forward looking price range is expected to be much narrower, and Kodiak Islands will gradually narrow the range in line with the expected forward-looking volatility in order to provide the optimal balance between yield generation and IL, while still ensuring the "always in range" strategy.

**Stable Pairs**

USDT-HONEY, USDC-HONEY

Post Boyco, this liquidity is no longer being incentivized by Kodiak and there is no whitelisted island for these pairs.  The necessary stablecoin liquidity to facilitate stablecoin routing and bridge volume on Kodiak is supplied with Protocol owned liquidity and partnerships with external market makers.

Stablecoin-HONEY, BTCLST-WBTC, ETHLST-WETH, and similar pairs&#x20;

All of these will have range centered at "fair price" and a concentrated liquidity range, that ranges from 0 to +/- 15%, determined in conjunction with the asset issuer, and lending protocols.  As the "fair price" increases (e.g. for ETHLST, when staking yield accrues), the island is adjusted to re-center the range.

**Volatile Pairs (Major)**

These include: WETH-HONEY, WBTC-HONEY, WETH-WBTC, WBERA-HONEY, WBERA-WETH, WBERA-WBTC. &#x20;

In general, the goal for majors on Kodiak Islands is to be the baseline liquidity that works in tandem with BEX to be the most important routes for Berachain - not to be a fee farm / high IL option.  Note that the pace of rebalances is always constrained by available liquidity (including outside the island), ensuring the Island rebalances are not a large share of the volume, and always proceeding gradually (e.g. TWAP back to target range), so as not to be disruptive to LPs and the overall ecosystem.

Liquidity provision provides a "short gamma" economic exposure, which results in needing to buy when prices go up, and sell when prices go down to rebalance to the 50-50 ratio.  Therefore, over-rebalancing ends up resulting in losses from LPs both from slippage incurred from swaps and consistent "buy high" / "sell low" behavior (thus, converting IL into realized loss).  It's important to carefully manage this.

All these are following Kodiak's flagship "wide range strategy." In general, the target asset ratios are:

* Baseline:  50-50
* Soft tolerance: 60-40 - this means, for small changes in price, there will be limited / "opportunitic" rebalancing.  This is because small imbalances tend to "fix" themselves as prices tend to mean revert.  When asset ratios move more skewed than 60-40 ratio, Kodiak Islands will initiate rebalances to move the range gradually back to a 60-40 ratio, and rely on price movements to take it towards the baseline 50-50 ratio. &#x20;
* 2z Target: 75-25 - this means, that with a high confidence interval (2 std deviation range) during the "average rebalancing period", the asset ratio will not be more skewed than 70-30

The target range around the current price is a function of:

* Volatility of the pair (the more volatile, the wider the bands would be)
* Average rebalancing period (this is a function of liquidity for these assets outside the island)

Given the annualized volatility, and the "average rebalancing period" in days, the mathematical result for the range is given as follows:

<figure><img src="/files/zOQczHhGLv92eZswuUA5" alt=""><figcaption></figcaption></figure>

How to derive this:

Assume that the baseline range is symmetric around current price:

```
Range = [P_0 / R ​​, P_0​ * R] //for example, 1/4 to 4x
```

Given an annualized volatility of `sigma`  and a average rebalancing frequency of `r` (in days):

```
P = P_0 * (1 + 2 * sigma * sqrt(r/365)) //scales with sqrt(r)
```

We then solve for the V3 range `R` such that a 2z at price `P`  the token ratio becomes 70/30.  The result is in the chart above.  As a first order approximation, the target range is linearly proportional to the annualized volatility and the sqrt(average rebalancing period).

Forward looking annualized volatilities of assets are determined by looking at implied volatility for assets with liquid options markets (e.g. BTC, ETH), and realized trailing volatility for others (e.g. BERA).

Asset-asset Pair volatilities (e.g. BTC-ETH), are computed by looking at realizing trailing correlations and using this formula:

```
sigma_a,b = sqrt(sigma_a^2 + sigma_b^2 - 2 * sigma_a * sigma_b * corr_a,b)
```

As of May 2025, here are the latest volatility estimates for the majors:

<figure><img src="/files/AYmIEO9OtJXn6cQInUWI" alt=""><figcaption></figcaption></figure>

For non-BERA pairs - Since there is effectively infinite liquidity for WBTC / WETH and highly efficient markets outside of Berachain, the rebalance periods can be relatively low.  In general, rebalance swaps for volatile majors would ideally target TWAP over 1-2 weeks timeframe to get back within the target ratios, and the ranges are calibrated over time accounting for this, consistent with the volatility of each pair.

For BERA pairs - Per the framework above, even with a 60-day rebalancing period, only a ⅓ - 3.5x range is needed.  However, since there is almost no liquidity outside of Kodiak (since BEX liquidity is minimal), the target range is set conservatively wider for now.  As BEX liquidity grows with recent POL changes, the effective rebalancing period will shorten and Kodiak islands can become more concentrated and capital efficienty.&#x20;

**Volatile Pairs (Ecosystem Tokens)**

These include pairs like: YEET-BERA, OOGA-BERA, DOLO-BERA.

In general, these follow the same framework as majors, with the exception that oftentimes they have no price history, and no liquidity outside the Kodiak Island.  This makes it impossible to estimate the volatility and makes the rebalancing periods effectively infinity, so most of these islands are initially set to full range, and will only effectively use concentrated ranges if there is a commitment of baseline liquidity to rebalance with outside the Kodiak Island, or sufficient price history to determine floor / cap prices.

In some cases - for CEX listed tokens, the token project can request a specific concentrated liquidity range that could be used - examples include: BR-BERA, STG-HONEY.  Ultimately Kodiak Islands are tailored to each project's specific requests.


# Panda Factory

No-Code Token Deployer Factory

<div align="left"><figure><img src="/files/JegPJDgYFYBpon7PJmVE" alt=""><figcaption></figcaption></figure></div>

## What is Panda Factory?

Panda Factory is a protocol for token launches that uses bonding curves. It enables tokens to be launched and traded without requiring initial liquidity, using a mathematical price curve until graduation to DEX trading.

{% hint style="info" %}
The protocol uses a bonding curve that determines token prices based on supply. As tokens are bought, the price increases along the curve; as tokens are sold, the price decreases.
{% endhint %}

### Core Components

#### Panda Token Launch

Launch tokens with:

* 1B total supply
* Zero initial liquidity requirement
* Configurable price range (set starting and ending market cap)
* Configurable base token (ETH, stablecoin)
* Optional: deployer same-block buy (up to 50% of supply)

\~80-90% of the token supply will be supplied in the Panda Pool bonding curve.  When all of those are bought, the token will graduate to Uniswap-style DEX. The remaining token supply is paired with the funds raised on Uniswap, and LP tokens are burned.

{% hint style="info" %}
Uniswap style dex can be any compatible Uniswap V2 fork. On Berachain, that is Kodiak Dex. On Robinhood Chain, the DEX is deployed by Uniswap.
{% endhint %}

#### **Incentives and Fees**

Before Graduation:&#x20;

* Buy fee: 0 (there is no fee to buy tokens while on the Panda Pool bonding curve)
* Sell fee: 2%

Graduation:&#x20;

* Deployer + Protocol fees as share of funds raised

After Graduation:

* 0.3% swap fees: standard fee on Uniswap V2 DEX

#### Trading

Trade directly with the protocol:

* Buy tokens (price increases with purchases)
* Sell tokens (price decreases with sales)
* Price determined by current curve position

#### Graduation

Automatic transition to DEX when:

* All the tokens in the Panda Pool have been bought (< 0.25% tokens remaining)
* Liquidity moves to Uniswap-style V2 DEX pair
* Trading continues on Uniswap-style DEX, listed on Dexscreener, etc.
* Users can swap using either Panda Factory UI or DEX or Terminal UI!

{% hint style="warning" %}
Important Protocol Characteristics:

* All prices follow the bonding curve formula
* Trading incurs fees
* Graduation is automatic and irreversible
  {% endhint %}


# Baults

Kodiak's BGT auto-compounding vaults

<figure><img src="/files/C7NN8GAYG9aVC06CAQid" alt=""><figcaption></figcaption></figure>

### Introduction to BGT Auto-Compounding Vaults

For liquidity pools eligible for Berachain's Proof-of-Liquidity incentives, users can earn additional BGT rewards by staking their LP tokens (Kodiak Islands) in BGT reward vaults, or external vaults by liquid wrappers (Infrared vaults).  Users typically manually choose between "raw" BGT which is then staked to a validator, or choose a liquid wrapper (e.g. iBGT, LBGT, yBGT) based on which is the highest yield, then occasionally claim the rewards and sell them to acquire more LP tokens. &#x20;

Auto-compounding vaults simplify this process by automatically claiming BGT rewards and compounding them for more LP tokens!

### What are Baults?

Baults are ERC-4626 compatible smart yield-maximizing, yield-bearing vaults that help you automatically grow your Kodiak Island Tokens.

### How Do Baults Work?

#### 1. **Deposit Your Island Tokens**

* You deposit your Kodiak Island Tokens (Island tokens) into a Bault
* In return, you receive ERC-4626 Bault receipt tokens.
* Your Island tokens are automatically staked in Berachain's Proof-of-Liquidity (POL) reward vaults (<https://hub.berachain.com/vaults/>)

#### 2. **Earn Compounded Rewards in the same Island Tokens**

* The staked Island tokens continuously earn BGT rewards.
* These rewards in liquid BGT wrappers get **continuously auctioned** for underlying island tokens.
* The Island tokens are then staked back into the Reward Vault&#x20;

**3. Continuous Auction of BGT rewards maximizes yield**

* Anyone can trigger the claiming process by paying a small bounty. &#x20;
  * For example, assume the bounty is $100 worth of island tokens.  This means that when the Bault accrues $100 "worth of" BGT rewards, it will be compounded.
  * The determination of when $100 "worth of" BGT rewards is accrued is market-determined.
* The BGT rewards can be claimed as:
  * **Regular BGT**: Direct BGT tokens
  * **Liquid BGT Wrappers**: Infrared iBGT, BeraPaw LBGT, Bearn yBGT are currently supported.&#x20;
* Typically, "keepers" will permission-lessly claim and compound with the **highest value** Liquid BGT wrapper.  In general, Baults will always claim at least the highest value BGT wrapper (trading at a \~40% premium, as of May 2025).
* In certain cases, through special partnerships Baults can "beat" the highest value BGT wrapper:
  * Certain Baults may be eligible for "reduced mint fees" for liquid BGT wrappers (vs the 10% typical fee)
  * Baults are the \*only\* mechanism in Berachain where raw BGT can be purchased in < $100 lot auctions, continuously.  It is likely that protocols looking to raw BGT will pay a premium to the comparable value of the highest value BGT wrapper

4. **Eligible to stack incentives with Kodiak Farms**
   * Until now, you had to choose between BGT or Kodiak Farms with locking, multipliers, and xKDK (or other token incentives).  With Baults, you can do both!
   * Baults can be (re)staked into Kodiak Farms to earn additional xKDK and other token incentives, on top of BGT rewards.
   * Farms will be launched after an initial period of data collection.  Before the token is launched, incentives will generally be added for the top performing pools.  After token is launched, this will  plug into the xKDK flywheel&#x20;
5. **Transparent Metrics and Very Low Fees**
   * Every single compound is transparently displayed with Berascan links.  See [Bault Analytics](/protocol/baults/bault-analytics) &#x20;
   * Deposit Fee: 0
   * Exit Fee: effectively 0
     * Technically, value of one compound, that goes to remaining depositors to prevent "reward hijacking."  Typically, it's less than 0.01%, users will make it up in < 30 minutes.
   * Compound Fee: up to 4.2% (varies by Bault, some may be lower).  This is set lower than most other auto-compounders that charge 5-10% performance fee.&#x20;
     * Before the token is live, fees will be used to accumulate protocol owned liquidity and add incentives to the major pools.
     * After token is live, these fees will plug into the xKDK flywheel.

### Audits?

See [audits](/security/audits).

### How to Deposit or Migrate?

Check out the [user guide](/user-guide/baults-auto-compound)&#x20;

As a quick overview, you can see the eligible pools by enabling the **Baults** filter&#x20;

<figure><img src="/files/AbVf6pBSA7ZbdDTjeNO4" alt=""><figcaption></figcaption></figure>

### **Want to be a Keeper?**&#x20;

Currently Kodiak + some partners run a basic keeper bot, using the Enso API to compound.  This bot is fully open sourced here:&#x20;

```
https://github.com/kodiak-Finance/bault-compoundor/
```

However, compounding is completely permission-less - keepers / MEV bots can use their own routes.  Any excess amounts are sent to the specified address, and are profits for the keepers.  All the necessary Bounty amounts are pre-funded and accessible through the `BountyHelper` contract (no flash loan necessary).  Check out the [technical guide](/developers/baults) for compounding baults.

### **Integrator?**&#x20;

Get a list of all the Baults, APY, and TVL here:&#x20;

```
https://backend.kodiak.finance/baults
```


# Bault analytics

Each Bault provides detailed analytics to help you track performance and understand the auto-compounding activity.

**Analytics Overview**

<figure><img src="https://documentation.kodiak.finance/~gitbook/image?url=https%3A%2F%2F584145091-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FOSwqNrRJ9Xh6jO57yoLm%252Fuploads%252FTqbeWG8lgK0YV1dbyYvQ%252Fimage.png%3Falt%3Dmedia%26token%3D35c3f200-7e22-468f-a2fb-ad730aaa5965&#x26;width=768&#x26;dpr=4&#x26;quality=100&#x26;sign=8fce955a&#x26;sv=2" alt=""><figcaption></figcaption></figure>

**Key Metrics:**

* **Current APY** - Real-time annual percentage yield
* **TVL** - Total value locked in the Bault
* **Bault Price** - Current price per share
* **Total Compounds** - Number of compound events and daily frequency
* **Vault Age** - How long the Bault has been active

**Price Chart with Compound Events**

<figure><img src="https://documentation.kodiak.finance/~gitbook/image?url=https%3A%2F%2F584145091-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FOSwqNrRJ9Xh6jO57yoLm%252Fuploads%252FIAOEoSw6tJueJ9E9Zv3j%252Fimage.png%3Falt%3Dmedia%26token%3Da6dc5ffb-8ebb-4062-8baa-811a308cf915&#x26;width=768&#x26;dpr=4&#x26;quality=100&#x26;sign=a0145efa&#x26;sv=2" alt=""><figcaption></figcaption></figure>

The **Bault Price** chart shows how share value grows over time through compounding. Every action taken in the Bault is fully transparent to users.

**Compound Dots**: Each dot on the price line represents a compound event where rewards were automatically reinvested by a keeper.

**Hover for Details**: Hover over any compound dot to see:

* Compound number and timestamp
* Wrapper minted
* Staking Token amount added

**Click for Transaction**: Click any compound dot to view the transaction details on Berascan.

**APY History**

<figure><img src="https://documentation.kodiak.finance/~gitbook/image?url=https%3A%2F%2F584145091-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FOSwqNrRJ9Xh6jO57yoLm%252Fuploads%252FEfMtNsrdlUZUQYqduSsU%252Fimage.png%3Falt%3Dmedia%26token%3D6b0b1486-5401-4b9f-b750-29a0e9adc5e2&#x26;width=768&#x26;dpr=4&#x26;quality=100&#x26;sign=8c304a41&#x26;sv=2" alt=""><figcaption></figcaption></figure>

Track how the auto-compounding yield has changed over time. The APY calculation is annualized based on actual realized compounding data.

**BGT/BERA Cost**

<figure><img src="https://documentation.kodiak.finance/~gitbook/image?url=https%3A%2F%2F584145091-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FOSwqNrRJ9Xh6jO57yoLm%252Fuploads%252FZUFrVVoaFZ4u2IvCy1aZ%252Fimage.png%3Falt%3Dmedia%26token%3Dfe114b16-b7d0-4d55-80d0-b1c3dc369c10&#x26;width=768&#x26;dpr=4&#x26;quality=100&#x26;sign=34635f6b&#x26;sv=2" alt=""><figcaption></figcaption></figure>

Shows the cost relationship between BGT rewards and BERA over time, helping you understand the economics of the compounding process.

**Timeframe Options**

Choose your analysis period:

* **7d** - Week view for recent activity
* **30d** - Month view for medium-term trends
* **90d** - Quarter view for longer patterns
* **All time** - Complete Bault history

<br>


# kX

Kodiak's Swap Aggregator

<figure><img src="/files/L57RbD1Al4tnzIYquUIK" alt=""><figcaption></figcaption></figure>

#### What is kX? <a href="#what-are-baults" id="what-are-baults"></a>

kX is Kodiak's advanced swap aggregator and API.  It automatically finds the best route to swap,  whether or not it's in a Kodiak Liquidity Pool.

When trading on a dex, users swaps are routed through liquidity pools.  Until now, swapping on Kodiak would route through liquidity that's only on Kodiak.  With kX, users swapping on the Kodiak App's Front End are able to access liquidity outside of Kodiak and facilitate the best swaps, including:

* Liquidity on other DEX (e.g. BEX), even ones competitive to Kodiak
* Non-dex mint / redeem routes (e.g. minting HONEY with USDC)
* Unique "zap" routes (e.g. zapping into [Islands](/protocol/islands) or [Baults](/protocol/baults))
* Tokens and chains with no native Kodiak Liquidity
* External market maker quotes via RFQ / Hooks

#### How does kX work? <a href="#how-do-baults-work" id="how-do-baults-work"></a>

The kX router automatically finds the best route by quoting an upgraded version of the Kodiak Router and aggregating it with various external providers.  The current list of supported external providers is in the API docs: [Swap API (kX)](/developers/dex/swap-api-kx)

**Modular Infrastructure - single approval to immutable contract**

The kX router (KXRouter.sol) requires a single token approval to route through the best route everywhere.  Similar to the legacy Kodiak Router, the kX router is fully immutable and non-upgradeable.  It was specifically designed with a modular architecture of separating the main router and executor (KodiakExecutor.sol) contracts.  This ensures that there is no possibility of malicious upgrades that could pose a security concern with token approvals. &#x20;

This means users only have to approve once and always have access to the "best-execution" routing.

**"Best execution"**

The kX API returns the best, most reliable quotes.  In general, there is no preference for "Kodiak routes" over routes via "external providers" using default settings.  The Kodiak Frontend also quotes all possible routes and returns the quotes that result in the best output for users.

That said, there are few caveats to how the "best" quote is calculated:

1. Most external providers charge small, additional fees - if "Kodiak quote" is the very close to the next best quote, "Kodiak" will be selected as the best provider.  Currently, the threshold for this is around `1-2 basis points` , based on an analysis of the average cost of aggregation.
2. Optimize for speed with a timeout of `1-2 seconds`.  If a particular quote provider has slow response speed, it will be dropped (but only if other, good quotes are available). &#x20;
3. Small penalty for quote providers that have relatively high latency.  A penalty of `0-5 basis points` is charged when evaluating the best quote, based on the experienced volatility of the actual output vs the quote
4. Routes that consistently display expiring quotes and / or have low liquidity are excluded because of lack of reliability.  Certain routes (e.g. RFQ quotes) have quotes that expire in 10-15 seconds, these are typically excluded from the route search because it's not reliable for our broad user base, which includes users that need quotes to be live for several minutes (e.g. for multisig transactions).

#### Modern Design <a href="#audits" id="audits"></a>

<figure><img src="/files/EzvMN1vuHg8JRhtCG8vA" alt=""><figcaption></figcaption></figure>

#### Fees <a href="#audits" id="audits"></a>

In general, with default settings, fees are zero.&#x20;

That said, there are 2 forms of fees technically supported:

1. **Surplus Fees**: similar to most other aggregators, kX Router has the ability to charge when the actual output exceeds the quoted amount.  Unlike other aggregators, kX has special features:
   1. The overall surplus is capped at 1%.  This cannot be changed.  That is, no matter what, the evaluated surplus can never exceed 1% of the output amount, and this ensures users are never over-charged even user inputs high slippage.
   2. The share of surplus that is charged as fee is configurable between 0-100%.  Most other aggregators are hardcoded to take 100% of surplus as fees.  In kX, a fraction of the surplus can be charged.
   3. Surplus can be charge relative to a custom benchmark called `feeQuote`, rather than the actual final quote.  Even using a custom benchmark, the overall surplus is still capped at 1%.
2. **Frontend Fees**: the kX API supports referral codes to charge an optional frontend fee to facilitate integrators.  This requires registration of a referral code, each referral code comes with a maximum frontend fee that can be charged and a share to the referrer.  For example, a refCode could be configured with a maximum 1% fee, of which 90% is retained by the referrer.  Each referrer can specify a frontend fee with each API request (and it can be customized for each quote).

The default kX API sets surplus fee and frontend fee to 0%.  All kX API users on Berachain can swap using the API to achieve the best routing for free.

Kodiak Frontend also does not charge any frontend fees and generally does not charge surplus fees.  In certain routes where Kodiak is competitive (and would have otherwise gotten the flow via the frontend), a small fraction of the surplus can be charged, only on the degree a quote beats Kodiak, subject to the surplus caps described above.

#### Audits? <a href="#audits" id="audits"></a>

See [Audits](/security/audits).

#### **API user?** <a href="#integrator" id="integrator"></a>

See [Swap API (kX)](/developers/dex/swap-api-kx), and reach out to register a refCode.


# Perps

Kodiak's Perps DEX (Berps)

<figure><img src="/files/ObNMpdhfuv7hNEkruY0c" alt=""><figcaption></figcaption></figure>

Kodiak Perps is a decentralized Perpetuals trading platform.  Users can trade popular crypto tokens with up to 100x leverage.

Based on the user's preference for Berachain memes, Kodiak Perps can be accessed on:

* [berps.kodiak.finance](https://berps.kodiak.finance)
* [perps.kodiak.finance](https://perps.kodiak.finance)

Kodiak Perps are directly plugged into Orderly Network’s decentralized, permissionless liquidity layer with unified liquidity and market makers. Currently, there is >$50M of Open Interest, >$50M TVL, and >$500M of daily trading volume running through this unified liquidity layer.  Learn more about Orderly Network here: <https://orderly.network/>

Kodiak serves the role of a “Broker” in onboarding users to Kodiak Perps and driving incentive campaigns. Users onboarded from Berachain immediately trade against users from all other chains, liquidity vaults, and market makers.  Users on Kodiak Perps can immediately trade against perps users on Raydium, Quickswap, WooFi, Aden, and other leading perps dexes, while depositing and withdrawing on Berachain.

**Signup and Deposits**

Users can sign-up with their existing Web3 wallets.  Deposits are accepted in USDC.  Users can deposit from any supported chain (Berachain, Ethereum, ETH L2s, and Solana).  Deposits typically stay on the chain of deposit and get reflected as margin in the perps dex.&#x20;

{% hint style="info" %}
Currently, only USDC deposits are supported.  You can click "Get USDC" to access a selection of bridges and aggregators to easily swap into USDC.
{% endhint %}

Trading is authenticated with via the user's Web3 wallet.  Once authenticated, all future actions are "one-click" and don't require signing each transaction for the currently live session.  It's a similar experience to trading on Hyperliquid.

**Accounts**

Each user is assigned an account tied to their Web3 wallet.  Users can also create sub-accounts. &#x20;

**Withdrawals**

Users can withdraw USDC on any supported chain.  In most cases, withdrawals are fulfilled within 1-2 minutes; however, depending on available liquidity on a given chain, it might be delayed. In this case, users can withdraw instantly on a different chain.  There is a small withdrawal fee (1 USDC) to cover bridge and gas costs.

**Trading**

Contract specs, leverage, funding, etc are pretty standard and similar to most other perp dexes or CEX.  Funding rates are charged every 8h for most markets, and 1h or 4h for others. &#x20;

Details on mechanics can be seen within the Orderly Docs: <https://orderly.network/docs/introduction/trade-on-orderly/perpetual-futures/margin-leverage-and-pnl>

**Trading Fees**

Maker: ~~0.02%~~ 0.013%\
Taker: ~~0.055%~~ 0.04%\
Referral and volume based discounts apply.

**BGT Rewards**\
\
As of Oct 2025, 100% of all net fees earned by Kodiak (after paying referral discounts, volume based discounts, and platform and infrastructure fees) - will be used to incentivize a Kodiak Perps related BGT reward vault, and BGT earned will be used for Kodiak Perps growth.  Details of this reward vault is posted in this governance proposal: <https://hub.forum.berachain.com/t/reward-vault-request-for-kodiak-reserve-for-incentives-and-market-expansion/1466>.

As of Oct 2025, proceeds from BGT earned are directly distributed to Kodiak Perp trading accounts as trading competition rewards.

**Trading Competitions and Points**

See the latest competition statistics and points in the [leaderboard](https://perps.kodiak.finance/leaderboard).

Learn more about points [here](/protocol/perps/points) and trading competitions [here](/protocol/perps/trading-competitions).

Trades or abusive activity inconsistent with the spirit of fair competition may be excluded or disqualified from earning rewards and points.&#x20;

**Referrals**

Users can create their own referral codes after they've done $100 in trading volume. &#x20;

**Support**

For any support related questions, please submit a ticket on the Kodiak Discord and / or submit the Feedback form on the top of the site.

**API Trading**

Programmatic trading can be done using a API Key generated in the Kodiak Perps (Portfolio -> API Keys).  API Docs [here](https://orderly.network/docs/build-on-omnichain/evm-api/api-authentication).  Please fill out the feedback form or reach out on Kodiak Discord if you're a programmatic trader to ensure you're getting the best volume-based trading fee discounts.


# VIP

Perps users are eligible for fee discounts based on xKDK staked.

VIP Tiers follow a similar model as Hyperliquid, with tiers based on xKDK staked. Tiers and fee discounts are automatically updated daily based on the stake.

xKDK staked for VIP Tier fee discounts are also eligible for with other staking [Utilities](/tokens/utility-mechanics) (such as Protocol Rewards and participating in Governance).

<figure><img src="/files/IF8yZdhAxmfXDjQorAcn" alt=""><figcaption></figcaption></figure>

Similar to referrals, fee discounts based on VIP Tiers apply to the Kodiak portion of the fees, after base fees to Orderly are applied.  Base fees are always 0 for maker, and range between 1-3 bps for taker based on trading pair and overall Kodiak level trading volumes.

{% hint style="info" %}
Trading fee discount applies to the Kodiak portion of the fees.
{% endhint %}


# Points

Traders on Kodiak Perps are eligible to earn Points. Points can be viewed on the [Leaderboard](https://perps.kodiak.finance/leaderboard).

Points are awarded in Seasons and conclude with xKDK incentives. The allocation of xKDK incentives is based on the overall incentive portion in the [tokenomics](/tokens/distribution), in proportion to the relative contribution of Perps to the Kodiak protocol.

**Methodology (Season 2)**

Points are awarded according to the following formula:

```
points = broker_fee
```

That is, points are directly proportional to net fees generated by a trader:

```
broker_fee = maker_volume * (maker_fee_tier - maker_orderly_fee) + 
             taker_volume * (taker_fee_tier - taker_orderly_fee)
```

{% hint style="info" %}
Trader with VIP fee tiers will be eligible for points based on the fees generated (and will thus require higher volumes to earn the same amount of points as smaller traders).
{% endhint %}

**xKDK Distribution (Season 2)**

For Season 2, 1 xKDK token is claimable per point.  Eligible users must accept the [Claim Terms](/informational/claim-terms) and claim within the claim period (Jun 9, 2026 to Aug 8, 2026).

**Methodology (Season 1)**

Points are awarded according to the following formula:

```
points = broker_fee + 10% * referred_broker_fee
```

That is, points are directly proportional to net fees generated by a trader + 10% of the net fees generated by referred users:

```
broker_fee = maker_volume * (maker_fee_tier - maker_orderly_fee) + 
             taker_volume * (taker_fee_tier - taker_orderly_fee)
```

**Example**

* Bob does $5M of taker volume and $5M of maker volume.  Bob's fee tier is 0.04% for taker and 0.013% for maker
* Bob refers Alice, who does $1M of taker volume at a 0.04% taker fee tier.
* Let's assume that the orderly fee (fee paid by Kodiak to access the Orderly infrastructure, which varies based on overall Kodiak Perps metrics) is 0 for maker, and 0.01% for taker
* Thus, Bob's points are equal to:&#x20;

```
broker_fee = 5M * (0.013% - 0) + 5M * (0.04% - 0.01%) = 650 + 1500 = 2150
referred_broker_fee = 1M * (0.04% - 0.01%) = 300

points = 2150 * 10% * 300 = 2180
```

**xKDK Distribution (Season 1)**

For Season 1, 1 [xKDK pre-TGE Rewards](/tokens/kodiak-pre-tge-rewards) token was distributed per point.  Eligible users must accept the [Migration terms and conditions](/informational/migration-terms) and claim within the claim period (Dec 23, 2025 to Jan 23, 2026).


# Trading Competitions

Traders on Kodiak Perps are automatically eligible for Trading Competitions.&#x20;

Competition statistics and details can be viewed on the [Leaderboard](https://perps.kodiak.finance/leaderboard).<br>

**Rules**

Rules vary by competition. Generally speaking, rewards are based on Volume and realized PNL during the competition period. &#x20;

* Competition Dates: as announced in the competition rules (e.g. Nov 1 to 15)
* Timezone for snapshot: UTC
* Source of truth: leaderboard.&#x20;
* Unrealized PNL does not count.
* Realized PNL is gross of fees (i.e. impact of fees is not included).
* Liquidation volumes, liquidation fees, and PNL does not count towards Realized PNL.&#x20;

{% hint style="info" %}
Liquidation volumes and fees do not accrue to Kodiak, they go towards the liquidator and the Orderly insurance pool.
{% endhint %}


# Perp Bots

Automate grid-trading strategies for perpetual futures on Kodiak Perps and Hyperliquid

### What Are Perp Bots? <a href="#what-is-perp-bots" id="what-is-perp-bots"></a>

Perp Bots are persistent automated strategies that manage perpetual futures orders on Kodiak Perps and Hyperliquid.

The initial strategy uses a price grid: a selected market range is divided into levels where the bot can buy at lower prices and sell at higher prices. This approach is intended for markets that move repeatedly through the configured range. It does not predict price direction or guarantee profit, and strong directional movement may create an open long or short position.

Each bot trades through an existing exchange account. Its orders and positions share that account’s margin and leverage settings, so activity from other bots or manual trades can change the account’s available margin and total exposure.

### How it works

A user defines the grid’s price range, spacing method, order size, and activity limits. Arithmetic grids maintain equal price differences between levels, while geometric grids maintain equal percentage differences.

After deployment, the bot uses authorized trading credentials to manage orders on the selected exchange. Filled orders change the position held by that account, and the bot continues managing the grid according to its configuration. The automation runs independently after deployment, so the dashboard does not need to remain open.

The dashboard provides visibility into the running strategy, including its orders, fills, grid state, position, margin, PNL, and operational health. The bot can be paused, resumed, or stopped. When stopping it, the user can choose whether to retain the current position or request that it be closed.

### Security features

* Credential validation: Credentials are validated before an account is linked and checked periodically afterwards. Accounts with invalid or expired credentials cannot be used to deploy new bots.
* Passphrase-protected credential storage: Before linked account credentials are saved to Kodiak Bots, the stored credential record is encrypted in your browser using a key derived from your passphrase. The passphrase remains on your device and is not sent to the Kodiak Bots service.
* Separate trading credentials: Perp Bots use exchange-specific credentials, a Kodiak Perps API key or a Hyperliquid agent wallet, rather than your connected wallet's private key.

### Limitations

* 5 active bots per user - number of active bots a user can run across all accounts.
* 4 active bots per account - number of active bots that can run on a single exchange account .
* 3 active bots per trading pair per account - number of active bots that can run on the same exact trading pair for the same account.

### Support

For additional assistance or feature requests, please contact the Kodiak Finance support team via [Discord](https://discord.gg/vhZmNFNbCZ).

### User guide?

See [Perp Bots](/user-guide/perp-bots).


# KDK Foundation

The Steward of KDK & xKDK

The KDK Foundation serves as the steward of $KDK and $xKDK, including all governance, staking, and distribution mechanics. This section mirrors publicly released $KDK and $xKDK information from the [Kodiak Foundation](https://x.com/kdk_fdn) and is provided for technical reference only. All official information regarding the protocol’s economic and governance framework is considered canonical only when released via Foundation communications.


# KDK

Kodiak Token

**Details**

* **Token Name**: Kodiak Token
* **Ticker:** $KDK
* **Chain:** Berachain
* **Type:** Transferable
* **Max Supply:** 100,000,000
* **Contract Address:** 0xc0D1aC00A30fA4e30e44AFc7313d6312c87E21dF
* **Description:** The native protocol token of Kodiak Finance ($KDK) is a transferable representation of attributed governance and utility functions specified in the protocol/code of Kodiak Finance, and which is designed to be used solely as an interoperable utility token thereon.

**Token Generation Event**

The KDK Token Generation Event (TGE) occurred on Berachain December 23, 2025. KDK is issued as an ERC20 token on Berachain.


# xKDK

Kodiak Escrowed Token

* **Token Name:** Kodiak Escrowed Token
* **Ticker:** $xKDK
* **Chain:** Berachain
* **Type:** Non-transferrable ERC-20
* **Contract Address:** 0x040EA7D4B559357425407fdFC3c774c5DfC04677
* **Description:** xKDK is a non-transferable escrowed governance token. It can be earned from interacting with the Kodiak protocol or through direct KDK conversion. The main use case for xKDK is the ability to allocate it to Utility Modules. The operation consists of staking xKDK into the token contract and assigning the deposited amount to a specific Utility Module in exchange for various benefits.


# Utility / Mechanics

xKDK Staking

**xKDK Staking:** xKDK can be staked to earn Protocol Rewards and participate in governance.&#x20;

**Protocol Rewards:**

* xKDK holders can stake for protocol rewards through a recurring epoch-based system.

  Each epoch lasts 3 days. Users may stake xKDK at any point during an active epoch. Rewards accrue continuously proportional to the xKDK staked.
* Forfeited KDK (from redemptions shorter than max vesting) and xKDK penalties from deallocation/unstaking from the Staking Rewards Utility Module go into a Rewards Pool.
* Rewards Pool is distributed to xKDK stakers (in the form of xKDK) proportionally to their stake.
* This Utility Module will be initially seeded with rewards to incentivize and reward early stakers.
* Protocol Rewards can be distributed in multiple tokens.

**Governance:**

* Staked xKDK can participate in governing the Kodiak Protocol (upon sufficient decentralization).

**VIP Tiers:**

* Perps users staking xKDK are additionally eligible for fee discounts.  See [VIP](/protocol/perps/vip).


# Convertibility & Redemption

KDK and xKDK offer a unique mutual convertibility, but the conversion process varies depending on the direction chosen.

**KDK & xKDK Conversion:** At any given moment, KDK can be instantaneously converted into xKDK at a 1:1 ratio.\
\
**xKDK & KDK Redemption:** The redemption process for converting xKDK to KDK incorporates a vesting feature, allowing users to customize the vesting duration based on their preferences. The conversion ratio will increase proportionally with the vesting duration:

* The minimum vesting duration of 15 days will provide a 1:0.5 ratio.
* The maximum vesting duration of 6 months (180 days) will provide a 1:1 ratio.
* If the selected vesting duration is lower than the maximum (ratio < 1:1), the unclaimed excess KDK is forfeited by the user (and distributed to other users via the xKDK Staking Rewards Utility Module).


# Kodiak Reserve

The KDK Foundation oversees the allocation of approximately 90% of protocol revenue toward activities back into the ecosystem:

* Approximately 60% to the Kodiak Reserve: Used to systematically acquire $KDK on the open market, serving as a protocol insurance fund.
* Approximately 30% to Protocol-Owned Liquidity (POL): Growing deep liquidity for major assets on the Kodiak Protocol.
* Upon sufficient decentralization, the future growth and composition of the Kodiak Reserve will be governed directly by xKDK stakers.


# Distribution

KDK Token Distribution

### Token Distribution and Release Schedule

<figure><img src="/files/QTErYXzzsd2MVLWR5u06" alt=""><figcaption></figcaption></figure>

{% hint style="info" %}
***Note: Berachain Build-a-Bera has committed to holding their allocation indefinitely.***
{% endhint %}


# Kodiak Pre-TGE Rewards

Kodiak Pre-TGE Rewards (xKDK) were utilized for incentivisation prior to the token generation event of Kodiak's native token (KDK).

Eligible users must accept the [Migration terms and conditions](/informational/migration-terms) and claim within the claim period (Dec 23, 2025 to Jan 23, 2026).


# Berachain Panda Factory


# Launch a Token on Panda Factory

## Supported Base Tokens

Panda Factory on Berachain supports the following tokens for token launches:

| Token      | Description                   |
| ---------- | ----------------------------- |
| BERA/WBERA | Native blockchain token       |
| Honey      | Berachain's native stablecoin |
| SOL        | Wrapped Solana Token          |

{% hint style="info" %}
Each base token has specific minimum raise and minimum trade size requirements. These parameters are set by the protocol to ensure minimum raise and trade-size requirement are met.
{% endhint %}

## Launch Requirements

Before launching a token, you'll need:

* A connected wallet
* Make sure you have enough of the chosen base token if you want to buy with deployer wallet&#x20;
* Token information prepared

## Launch Process

#### 1. Basic Token Information

<figure><img src="/files/wvVUIocBglpVTGXfxhNK" alt=""><figcaption></figcaption></figure>

Configure your token's basic details:

* **Image**
  * Upload token logo
  * Supported formats: JPEG/PNG/WEBP/GIF
  * Maximum size: 4 MB
* **Token Name**
  * Enter your token's full name
  * Example: "Dogwifhat"
* **Token Symbol**
  * Enter your token's trading symbol
  * Example: "WIF"
* **Description**
  * Add token description (up to 250 characters)
  * Explain your token's purpose and features
* **Social Links (Optional)**
  * X (Twitter)
  * Telegram
  * Website

#### 2. Market Configuration

<figure><img src="/files/89wPJLiyjZ2hvvOT7NuU" alt=""><figcaption></figcaption></figure>

* **Choose Base Token**
  * Select from the supported base tokens
  * Each base token has specific minimum requirements
  * Affects trading pairs and liquidity
* **Define Market Cap Range**
  * Starting price
  * Ending price
  * View in USD or base token value

{% hint style="info" %}
The minimum starting market capitalization (MC) is set at USD 1,000, with a maximum potential of approximately 73x the initial MC. The default configuration enables the immediate deployment of tokens, typically within 1 minute; however, these settings can be adjusted according to your requirements.
{% endhint %}

#### 3. Token Economics

<figure><img src="/files/sEVDwriKTuO01AojoqSZ" alt=""><figcaption></figcaption></figure>

View your token's calculated metrics:

* **Raised amount for graduation**
  * Amount needed to reach graduation
  * Displayed in base token and USD
* **Supply Information**
  * Total token supply
  * Tokens in panda pool
  * Tokens added to LP
* **Deployer Incentives**
  * Incentives received upon graduation
  * Includes both graduation fee as well as KDK incentives \[subject to availability]

{% hint style="warning" %}
Review all parameters carefully before launching:

* Parameters cannot be modified after launch
* Base token selection is permanent
* Price range affects trading dynamics
  {% endhint %}

#### 4. D**eployer buy option**

<figure><img src="/files/WmAVPnVwe8bxEcmpFeqA" alt=""><figcaption></figcaption></figure>

* Optional token allocation for deployer
* Maximum 50% of total supply
* Configurable amount based on preferences

### Launch Confirmation

1. Review all parameters
2. Confirm transaction in wallet
3. Wait for deployment completion

{% hint style="info" %}
After launch:

* Token immediately available for trading
* Price starts at configured minimum
* Trading begins through bonding curve
* Base token pairing is permanent
  {% endhint %}


# Trading on Panda Factory

### Understanding Trading Mechanics

Trading on Panda Factory is pretty similar to Kodiak V3 DEX, with small differences.

{% hint style="info" %}
Key differences:

* Prices move along a predefined curve
* Trading is always against the Panda Pool liquidity
* Max buy is what's available in the Panda Pool bonding curve
* No token approvals needed to sell!
* Minimum trade requirement must be met
  {% endhint %}

### Trading Interface

<figure><img src="/files/jdzwyv3DBhkHaAXTbMZZ" alt=""><figcaption></figcaption></figure>

#### 1. Base Token Selection

* When base token is WBERA:
  * Toggle between BERA/WBERA for trading
  * Both use same liquidity pool
* Other tokens:
  * Trade with designated base token

{% hint style="info" %}
Do not have enough of the selected base token? Click Get some \[token] to open Relay and acquire it.
{% endhint %}

#### 2. Amount Input

* Enter amount to trade
* Quick selection options:
  * Min: Minimum trade size
  * 25%: Quarter of balance
  * 50%: Half of balance
  * Max: Maximum possible trade

#### 3. Balance Information

* Shows your available balance
* Updates based on selected token
* Displays in both tokens

{% hint style="info" %}
When using WBERA as base token, you can seamlessly switch between BERA and WBERA without affecting trade price or impact.
{% endhint %}

#### 4. Trade Details

* Timestamp relative to current time
* Green for buys, red for sells
* Volume in base token value
* Clickable transaction hashes

{% hint style="info" %}
All trades executed through the bonding curve are reflected immediately in the trade history.

All trades are subject to:

* Protocol fees
* Minimum trade size
  {% endhint %}

### Executing Trades

#### Buy Orders

1. Input amount to buy (token or base currency)
2. View calculated output
3. Check price impact
4. Confirm transaction

#### Sell Orders

1. Input amount to sell
2. View expected return
3. Review price impact
4. Confirm transaction

{% hint style="warning" %}
Important considerations:

* Larger trades have higher price impact
* Minimum trade size requirements apply
* Trading fees are applied to all transactions
  {% endhint %}

### Transaction History

View your trading activity:

* Recent transactions
* Buy/Sell orders
* Transaction status
* Price and amount details


# Robinhood Panda Factory


# Launch a Token on Panda Factory

## Supported Base Tokens

Panda Factory on Robinhood supports the following tokens for token launches:

| Token    | Description                             |
| -------- | --------------------------------------- |
| ETH/WETH | Native blockchain token                 |
| USDG     | US dollar-pegged stablecoin, backed 1:1 |
| CASHCAT  | Meme token                              |

{% hint style="info" %}
Each base token has specific minimum raise and minimum trade size requirements. These parameters are set by the protocol to ensure minimum raise and trade-size requirement are met.
{% endhint %}

## Launch Requirements

Before launching a token, you'll need:

* A connected wallet
* Make sure you have enough of the chosen base token if you want to buy with deployer wallet&#x20;
* Token information prepared

## Launch Process

#### 1. Basic Token Information

<figure><img src="/files/UxcEeTr1ybz4sz8cu0rt" alt=""><figcaption></figcaption></figure>

Configure your token's basic details:

* **Image**
  * Upload token logo
  * Supported formats: JPEG/PNG/WEBP/GIF
  * Maximum size: 4 MB
* **Token Name**
  * Enter your token's full name
  * Example: "Dogwifhat"
* **Token Symbol**
  * Enter your token's trading symbol
  * Example: "WIF"
* **Description**
  * Add token description (up to 250 characters)
  * Explain your token's purpose and features
* **Social Links (Optional)**
  * X (Twitter)
  * Telegram
  * Website

#### 2. Market Configuration

<figure><img src="/files/vCqW3FBTZwMywUmyKE4N" alt=""><figcaption></figcaption></figure>

* **Choose Base Token**
  * Select from the supported base tokens
  * Each base token has specific minimum requirements
  * Affects trading pairs and liquidity
* **Define Market Cap Range**
  * Starting price
  * Ending price
  * View in USD or base token value

{% hint style="info" %}
The minimum starting market capitalization (MC) is set at USD 1,000, with a maximum potential of approximately 73x the initial MC. The default configuration enables the immediate deployment of tokens, typically within 1 minute; however, these settings can be adjusted according to your requirements.
{% endhint %}

#### 3. Token Economics

<figure><img src="/files/ADa3rl0rR323XoPPhn71" alt=""><figcaption></figcaption></figure>

View your token's calculated metrics:

* **Raised amount for graduation**
  * Amount needed to reach graduation
  * Displayed in base token and USD
* **Supply Information**
  * Total token supply
  * Tokens in panda pool
  * Tokens added to LP
* **Deployer Incentives**
  * Incentives received upon graduation
  * Includes both graduation fee as well as KDK incentives \[subject to availability]

{% hint style="warning" %}
Review all parameters carefully before launching:

* Parameters cannot be modified after launch
* Base token selection is permanent
* Price range affects trading dynamics
  {% endhint %}

#### 4. D**eployer buy option**

<figure><img src="/files/4pP5pht0YEAin6mME76E" alt=""><figcaption></figcaption></figure>

* Optional token allocation for deployer
* Maximum 50% of total supply
* Configurable amount based on preferences

### Launch Confirmation

1. Review all parameters
2. Confirm transaction in wallet
3. Wait for deployment completion

{% hint style="info" %}
After launch:

* Token immediately available for trading
* Price starts at configured minimum
* Trading begins through bonding curve
* Base token pairing is permanent
  {% endhint %}


# Trading on Panda Factory

### Understanding Trading Mechanics

Trading on Panda Factory is pretty similar to Uniswap V3 DEX, with small differences.

{% hint style="info" %}
Key differences:

* Prices move along a predefined curve
* Trading is always against the Panda Pool liquidity
* Max buy is what's available in the Panda Pool bonding curve
* No token approvals needed to sell!
* Minimum trade requirement must be met
  {% endhint %}

### Trading Interface

<figure><img src="/files/aCGrA9sjOjS0vRGoooXE" alt=""><figcaption></figcaption></figure>

#### 1. Base Token Selection

* When base token is WETH:
  * Toggle between ETH/WETH for trading
  * Both use same liquidity pool
* Other tokens:
  * Trade with designated base token

{% hint style="info" %}
Do not have enough of the selected base token? Click Get some \[token] to open Relay and acquire it.
{% endhint %}

#### 2. Amount Input

* Enter amount to trade
* Quick selection options:
  * Min: Minimum trade size
  * 25%: Quarter of balance
  * 50%: Half of balance
  * Max: Maximum possible trade

#### 3. Balance Information

* Shows your available balance
* Updates based on selected token
* Displays in both tokens

{% hint style="info" %}
When using wETH as base token, you can seamlessly switch between ETH and wEth without affecting trade price or impact.
{% endhint %}

#### 4. Trade Details

* Timestamp relative to current time
* Green for buys, red for sells
* Volume in base token value
* Clickable transaction hashes

{% hint style="info" %}
All trades executed through the bonding curve are reflected immediately in the trade history.

All trades are subject to:

* Protocol fees
* Minimum trade size
  {% endhint %}

### Executing Trades

#### Buy Orders

1. Input amount to buy (token or base currency)
2. View calculated output
3. Check price impact
4. Confirm transaction

#### Sell Orders

1. Input amount to sell
2. View expected return
3. Review price impact
4. Confirm transaction

{% hint style="warning" %}
Important considerations:

* Larger trades have higher price impact
* Minimum trade size requirements apply
* Trading fees are applied to all transactions
  {% endhint %}

### Transaction History

View your trading activity:

* Recent transactions
* Buy/Sell orders
* Transaction status
* Price and amount details


# Swap

Get started trading on Kodiak

**Making your first swap:**

1. **Establish Connection**: Select `Connect Wallet` to begin your journey on Kodiak.

   <figure><img src="/files/k6N8hKetw0G5EEuPArU2" alt=""><figcaption><p>Connect Wallet</p></figcaption></figure>
2. **Token Selection**: Select the tokens you wish to exchange (input and output tokens).&#x20;

   * **Importing a custom token**: Can't find your token in the default list? Simply input the contract address of the token you're eyeing in the search field to import it.

   <figure><img src="/files/cjGN6nE6OwYoP4T9NziD" alt=""><figcaption><p>Select a Token</p></figcaption></figure>
3. **Swap Specifications:** Specify the amount you wish to exchange. The platform will automatically show the expected amount you'll receive, factoring in current market conditions and liquidity pool depth.

   * **Alternative Approach:** You can instead specify the amount of output tokens you'd like to receive.
   * **Adjust Slippage (o*****ptional)*****:** If desired, tap Transaction Settings (gear icon) and adjust the slippage tolerance.

   <figure><img src="/files/BmbYCIuPUw5kbqJDDArr" alt=""><figcaption><p>Transaction Settings, Input Token Amount &#x26; Output Token Amount buttons</p></figcaption></figure>

   <figure><img src="/files/F2EXOpzIuUFct1CjPWnt" alt=""><figcaption><p>Transaction Settings</p></figcaption></figure>
4. **Token Approval (if required):** If it's the first time you are trading a particular token on Kodiak, you will need to approve the token to be swapped on our router. Click on the `Allow Kodiak to use your [  ]` button and confirm the token approval in your wallet.

   <figure><img src="/files/osk6nrQlGjyONkheYOS8" alt=""><figcaption><p>Token Approval</p></figcaption></figure>
5. **Finalize Your Swap:** Select `Swap`. Take a moment to go over the transaction details, such as gas fees, price impact, and expected amount to be received. If everything checks out, click `Confirm Swap` and confirm the swap in your wallet.

   <figure><img src="/files/A1Md2GpgfomC3NHmbR3y" alt=""><figcaption><p>Swap</p></figcaption></figure>

   <figure><img src="/files/E0767vLo01FwzRM0hXEf" alt=""><figcaption><p>Confirm Swap</p></figcaption></figure>
6. **Wait for Confirmation**: Wait for the transaction to be confirmed on Berachain. This usually takes a few seconds.&#x20;

   <figure><img src="/files/YW2KF8eUVCfvchQqGwm0" alt=""><figcaption><p>Waiting for Confirmation</p></figcaption></figure>

   <figure><img src="/files/OdUfvEepB3LA66ZYkt85" alt=""><figcaption><p>Transaction Submitted</p></figcaption></figure>
7. **Transaction Complete**: Once confirmed, the tokens will be swapped according to your instructions, and the exchanged tokens will be reflected in your wallet.&#x20;

   <figure><img src="/files/EpYVgd5UvYcq5mo6aLAX" alt=""><figcaption><p>Transaction Complete</p></figcaption></figure>
8. **Congrats**: You've successfully navigated a DEX swap on Kodiak. Ready for more? Continue on to the next few pages to learn how to add liquidity and earn fees!


# Multiswap

#### What is Multiswap

Multiswap is a zero-fee, any-to-any token swap designed for best execution: pick what you want to end up with, and swap multiple tokens into it in a single action. It is powered by kX (Kodiak's advanced swap aggregator) and works with any ERC-20 token supported by kX, including memecoins, majors, LP tokens and Baults.

**Making your first swap:**

1. **Establish Connection**: Select `Connect Wallet` to begin your journey on Kodiak. <br>

   <figure><img src="/files/iaurkEvwIQz97Ut5KhCA" alt=""><figcaption><p>Connect Wallet</p></figcaption></figure>

2. **Token Selection**: Select the tokens you wish to exchange (input and output tokens).&#x20;

   * **Importing a custom token**: Can't find your token in the default list? Simply input the contract address of the token you're eyeing in the search field to import it.

   <figure><img src="/files/c76ryBykVjSMZXoKNG01" alt=""><figcaption><p>Select a token</p></figcaption></figure>

3. **Swap Specifications:** Specify the amount you wish to exchange. The platform will automatically show the expected amount you'll receive, factoring in current market conditions and liquidity pool depth.

   * **Alternative Approach:** You can instead specify the amount of output tokens you'd like to receive.
   * **Transaction settings&#x20;*****(optional)*****:** Tap the gear icon to adjust **slippage tolerance** and/or choose desired **providers**.

   <figure><img src="/files/rd2lQs04VQRZffXmYFB2" alt=""><figcaption><p>Transaction Settings, Input Token Amount &#x26; Output Token Amount buttons</p></figcaption></figure>

   <figure><img src="/files/vvoK5IliFV3tY6FXTqZh" alt=""><figcaption><p>Transaction Settings</p></figcaption></figure>

4. **Token Approval (if required):** If it's the first time you are trading a particular token on Kodiak, you will need to approve the token to be swapped on our router. Click on the `Approve` button and confirm the token approval in your wallet.<br>

   <figure><img src="/files/HamhGwa69DseZbimmpj9" alt=""><figcaption><p>Token Approval</p></figcaption></figure>

5. **Finalize Your Swap:** Take a moment to go over the transaction details, such as gas fees, price impact, and expected amount to be received. If everything checks out, click `Swap All` and confirm the swap in your wallet.<br>

   <figure><img src="/files/FQ7TUlXGFptA84LTYJP3" alt=""><figcaption><p>Swap</p></figcaption></figure>

6. **Wait for Confirmation**: Wait for the transaction to be confirmed on Berachain. This usually takes a few seconds. <br>

   <figure><img src="/files/YLXINxQ953s9wVrwvrIX" alt=""><figcaption><p>Waiting for confirmation</p></figcaption></figure>

   <figure><img src="/files/OGz6RSCi8Ef7hJYiwkz7" alt=""><figcaption><p>Transaction submitted</p></figcaption></figure>

7. **Transaction Complete**: Once confirmed, the tokens will be swapped according to your instructions, and the exchanged tokens will be reflected in your wallet.


# Limit Orders

#### What are Limit Orders

Limit Orders allow you to place orders and execute swaps at your desired price instead of swapping immediately at the current Market Price. \
This allows for efficient and precise swaps at your desired price with automated execution.

Kodiak integrates with Orbs protocol to bring you automated limit order execution with simple steps. You can find more information about Orbs protocol [here](https://www.orbs.com/dtwap-and-dlimit-faq/).

For Limit Orders to work, you must pre approve your tokens and maintain enough token balance in the wallet to facilitate pending limit orders.

A 17 BPS fee is applicable to faciliate your trades and is taken from the output token.

To Place limit orders navigate to [Swap Page](https://app.kodiak.finance/#/swap?inputCurrency=BERA\&outputCurrency=0xFCBD14DC51f0A4d49d5E53C2E0950e0bC26d0Dce)&#x20;

* Select Limit Order
* **Token to sell** - Select the input token from token list to sell and enter amount
* **Token to buy** - Select the output token from token list to buy, and you will see the expected output amount in box
* **Sell/Buy price** - Set the desired buy/sell price for execution. You can input an absolute price or a gain percentage offset from current price. \
  **Tip** - You can click on `Use Market Price` to set the current market price and then make adjustments to it. You can also click on the button highlighted in yellow to change swap quote token.
* **Expiry** - Set the timeframe for trade expiry after which the order cannot be executed, select from Minutes, hours or days.

#### Walkthrough

In This example we will create a limit order to sell BERA at a price of $5 when the mark price is around $2.34&#x20;

<figure><img src="/files/w8gdd92QBa5bGUmyeF0a" alt=""><figcaption></figcaption></figure>

* Set the Limit price to 5 or enter the gain percentage value, entering one automatically calculates and updates the other.

<figure><img src="/files/vY83xJ8msyImIA1zsGST" alt=""><figcaption></figcaption></figure>

* Click on Place order which opens the order summary pop-up. You must review the trade details carefully and accept the disclaimer to place your Limit orders

<figure><img src="/files/FHCrndmbUmrRlvCG5VIU" alt=""><figcaption></figcaption></figure>

* After clicking on Confirm order you will see the following transaction popup

  * If this is the first time using this input token with limit/TWAP orders on Kodiak you will need to approve your input tokens for swapping.

<figure><img src="/files/kPf3eyBCOfMZupTyw2kd" alt=""><figcaption></figcaption></figure>

* After approvals, you will see another transaction to create the limit orders.

<figure><img src="/files/NX1EnnMn5s8kKfXdAihO" alt=""><figcaption></figcaption></figure>

* Once signed, You have successfully created the limited order.

<figure><img src="/files/QpamSU23CvI1kuQUfXNm" alt=""><figcaption></figcaption></figure>

#### Order History

You can see all your created, pending, executed and cancelled orders, their status and manage them from this button

![](/files/eaBB1g2AZQVEnnun3tVv)

* You can filter the order history using this dropdown&#x20;

![](/files/bCIZhtfj7TXrIIJdtH4m)

We can see the latest order we created here.

<figure><img src="/files/YJuWVYNqsF1KZ7GLHWBY" alt=""><figcaption></figcaption></figure>

Click on any order to see its current execution status and order details. You can also cancel any pending orders from here

<figure><img src="/files/SUyaRj7DzA8US7KHkdbr" alt=""><figcaption></figcaption></figure>


# TWAP

#### What is TWAP

TWAP is used to buy or sell an asset over a period of time rather than an instant execution.

It divides a large order into smaller, equal-sized orders spread out over a set period to minimize market impact

**When and Why to use TWAP**

* **For large orders**
* **In less liquid tokens**
* **To reduce market impact**
* **Acquiring tokens at avg price to reduce short term price fluctuations**

#### TWAP Market vs TWAP Limit Orders

**TWAP Market Orders**

When placing TWAP orders you can choose to place market orders. Such orders execute at the set frequency at then Market Price of the token. This gurantees the execution at the set frequency

**TWAP Limit Orders**

When placing the TWAP orders, if you select a limit price, then your orders execute at the set frequency only if the market price is at or better than the limit price, which helps you control the buy/sell price.

#### **Important Things to Consider**

* Your trades are not instant but spread over multiple small trades
* When placing market TWAP orders the execution price can be significantly different from order placement time.
* Make sure to use Limit Prices if you want to execute trades only above a certain price.
* A 17 BPS fee is applicable to faciliate your trades and is taken from the output token
* You would also pay a small fee to cover the gas fee paid by takers to execute this swap on your behalf

#### How To Place TWAP Orders

To place TWAP orders navigate to [Swap Page](https://app.kodiak.finance/#/swap?inputCurrency=BERA\&outputCurrency=0xFCBD14DC51f0A4d49d5E53C2E0950e0bC26d0Dce) and select TWAP.

* Enter the tokens to buy and sell with input token amount.
* You will see the output token amount with current best market price
* Toggle between the market price and the limit price. In this example we are placing a TWAP order to execute at market price
* Enter the frequency and total number of trades you want to execute.&#x20;
* Check the amount of token traded per trade
* Click on Place Order

<figure><img src="/files/JVeUHIDlWB0QVdXZGm2F" alt=""><figcaption></figcaption></figure>

* You can also set a Limit price for execution by including the gain percentage or the absolute price. In this example we will use Market Price.

<figure><img src="/files/NuWcW7kM29BHs1Zwk94G" alt=""><figcaption></figcaption></figure>

* You will see a popup with order summary and a disclaimer you must read and accept to place your order.

* This will popup two transactions that you must sign

  * First is the Input Token allowance approval transaction
  * Place Order transaction

* You will see your submitted order like this.

<figure><img src="/files/rVbxiHXzUXT46HynuqWQ" alt=""><figcaption></figcaption></figure>

* You can also navigate to the Order History section to find the order and manage it.

<figure><img src="/files/CA2BSWIGKMZHWpHE84US" alt=""><figcaption></figcaption></figure>


# Stop Loss

#### What is Stop Loss

A **Stop Loss** order is an advanced trading tool that enables users to limit potential losses by selling a token if its price moves against their position. For example, suppose a token’s price drops by a predetermined percentage. A stop-loss order helps ensure it is sold at the best available price, protecting the user’s portfolio from further losses.

#### Walkthrough

In this example we will create a Stop Loss order to sell BERA at a price of $0.01 when the mark price is around $0.6.

To place Take Profit order navigate to [Swap Page](https://app.kodiak.finance/#/swap?inputCurrency=BERA\&outputCurrency=0xFCBD14DC51f0A4d49d5E53C2E0950e0bC26d0Dce\&chain=berachain_mainnet) and select the Advanced tab, then open the SL sub-tab.

<figure><img src="/files/NmezUwAXzcRNESt5gKP1" alt=""><figcaption></figcaption></figure>

* Set the Trigger Price to 0.01 or enter the gain percentage value, entering one automatically calculates and updates the other.

  * Limit Price *(optional)*:  Stop Loss limit orders protect against receiving a worse price than your specified limit. Once the stop price is triggered, the order will execute only at the limit price or better. The downside is that if the market price falls below your limit, the order may not execute at all.

  <figure><img src="/files/wja4jG8AGSOQjtDchboH" alt=""><figcaption></figcaption></figure>
* Click on Place order which opens the order summary pop-up. You must review the trade details carefully and accept the disclaimer to place your Stop Loss order.

<figure><img src="/files/YN5deFT94dk2Us9CMmVX" alt=""><figcaption></figcaption></figure>

* After clicking on Submit you will see the following transaction popup.
  * If this is the first time using this input token with advanced orders on Kodiak you will need to approve your input tokens for swapping.

<figure><img src="/files/xDZffIAdZAMt4Pzh9f2D" alt=""><figcaption></figcaption></figure>

* After approvals, you will see another transaction to create the Stop Loss order.

<figure><img src="/files/hxdeTrJYswyeZKTnjIyI" alt=""><figcaption></figcaption></figure>

* Once signed, You have successfully created the Stop Loss order.

<figure><img src="/files/srs4LMPsTdIriITKmP7F" alt=""><figcaption></figcaption></figure>

#### Order History

You can see all your created, pending, executed and cancelled orders, their status and manage them from the Orders button.

<figure><img src="/files/5uw1ppj9vCyrZABpVr3a" alt=""><figcaption></figcaption></figure>

* You can filter the order history using this dropdown.

<figure><img src="/files/dfqFb29O2z5PxfVxg2OI" alt=""><figcaption></figcaption></figure>

We can see the latest order we created here.

<figure><img src="/files/vU4PvSs62wA37AjJjvzc" alt=""><figcaption></figcaption></figure>

Click on desired order to see its current execution status and order details. You can also cancel any pending orders from here.

<figure><img src="/files/03QzjdxG4a232JhbsdIx" alt=""><figcaption></figcaption></figure>


# Take Profit

#### What is Take Profit

A **Take Profit** order is an advanced trading tool that enables traders to set a predefined price level at which to secure profits from an open position. When combined with stop-loss orders, it enables better trade management, helping optimize potential gains while controlling risk.

#### Walkthrough

In this example we will create a Take Profit order to sell BERA at a price of $5 when the mark price is around $0.6.\
\
To place Take Profit order navigate to [Swap Page](https://app.kodiak.finance/#/swap?inputCurrency=BERA\&outputCurrency=0xFCBD14DC51f0A4d49d5E53C2E0950e0bC26d0Dce\&chain=berachain_mainnet) and select the Advanced tab, then open the TP sub-tab.

<figure><img src="/files/PHp9Cqd5h0RjtYhvtBQd" alt=""><figcaption></figcaption></figure>

* Set the Trigger Price to 5 or enter the gain percentage value, entering one automatically calculates and updates the other.

<figure><img src="/files/nFi9V9UVZ2XJwsfAXhXy" alt=""><figcaption></figcaption></figure>

* Click on Place order which opens the order summary pop-up. You must review the trade details carefully and accept the disclaimer to place your Take Profit order.

<figure><img src="/files/7Z3GlUracOdLZ7VXGrZR" alt=""><figcaption></figcaption></figure>

* After clicking on Submit you will see the following transaction popup.

  * If this is the first time using this input token with advanced orders on Kodiak you will need to approve your input tokens for swapping.

  <figure><img src="/files/yvYiAHkgEEq6nNfTzn8a" alt=""><figcaption></figcaption></figure>
* After approvals, you will see another transaction to create the Take Profit order.

<figure><img src="/files/5LjIG239KKDAE2bN2akU" alt=""><figcaption></figcaption></figure>

* Once signed, You have successfully created the Take Profit order.

<figure><img src="/files/wu0cJwGcZJl9JfjAfwhR" alt=""><figcaption></figcaption></figure>

#### Order History

You can see all your created, pending, executed and cancelled orders, their status and manage them from the Orders button.

<figure><img src="/files/4WRCSbzajqFWUpP2Yu8L" alt=""><figcaption></figcaption></figure>

* You can filter the order history using this dropdown.

<figure><img src="/files/1rPinmB88zQ8zTdZ5dMg" alt=""><figcaption></figcaption></figure>

We can see the latest order we created here.

<figure><img src="/files/UcobWUxMcTI1WxbJIRG0" alt=""><figcaption></figcaption></figure>

Click on desired order to see its current execution status and order details. You can also cancel any pending orders from here.

<figure><img src="/files/izOvjIlwIsBRFxlXUylF" alt=""><figcaption></figcaption></figure>


# Create a V2 Position

Adding V2 Liquidity on Kodiak

### **Navigate to V2 Liquidity**

Click on the `Liquidity` option within the navigation bar. Within this section, select the `V2 Pools` tab to proceed. Any V2 positions you currently hold will be displayed here.

* ***Import:*** If your pool position is not listed, select `Import Pool`. Then choose the tokens you've paired to load your position into the Kodiak interface.

<figure><img src="/files/SE3V4cQQPnaUBy9Az2gk" alt=""><figcaption><p>V2 Pools Page</p></figcaption></figure>

### **Creating a Position**

To begin creating a position, click `Add V2 Liquidity` and choose the tokens you want to add liquidity for. You can provide liquidity for any pair of tokens supported on Kodiak.

<figure><img src="/files/NFrdmznk9RXP2ze2ZIKa" alt=""><figcaption><p>Add V2 Liquidity</p></figcaption></figure>

1. **Enter Amounts:** Enter the amount of each token you wish to deposit to the liquidity pool.&#x20;

   * ***For existing pools:*** If there is already an existing pool for your selected token pair, Kodiak will automatically calculate the proper token amount for the other side of the pair.&#x20;

   <figure><img src="/files/s1fnmMFG8SOM7CGRWhSv" alt=""><figcaption><p>Enter Amounts</p></figcaption></figure>
2. **Transaction Settings (optional):** You can select the gear icon to adjust slippage for the transaction (optional/as needed).

<figure><img src="/files/nqYyGBfknHejJHFSn6Gi" alt=""><figcaption><p>Transaction Settings</p></figcaption></figure>

3. **Approve Token(s):** If it's your first time providing V2 liquidity for the particular token(s), you will need to approve the token(s) to be used by Kodiak. You will see two `Approve [ ]` buttons if you have to approve both tokens for the pair.

<figure><img src="/files/YvOLK4QSuvpdUofSY4eQ" alt=""><figcaption><p>Approve Token</p></figcaption></figure>

4. **Supply Liquidity:** Carefully review the details of your transaction, including the token amounts and your ensuing share of the liquidity pool. Once ready, click `Supply` and confirm this transaction through your wallet. The transaction should be confirmed on Berachain within a few seconds.

<figure><img src="/files/5km8ca4o9S4IfkrEgbiD" alt=""><figcaption><p>Supply Liquidity</p></figcaption></figure>

5. **Transaction Complete:** Following confirmation, your liquidity is added to the Kodiak V2 pool. You'll receive LP tokens that represent your stake in the pool. You can view your position details both on this page, and back in the V2 Pools view.&#x20;
   * *Dive deeper*: For a more comprehensive view of your investment's performance, including fees earned, navigate to the analytics dashboard by selecting `Account Analytics and Accrued Fees ->`.


# Create a V3 Position

Adding V3 Liquidity

**Navigate to V3 Liquidity**

Click the `Liquidity` option within the navigation bar. Within this section, select the `V3 Pools` tab to proceed. Any V3 positions you currently hold will be displayed here.

* ***Closed Positions:*** You can click the toggle in the bottom to show/hide your closed positions.

<figure><img src="/files/SlxP5v4iQneXkTmN1Mbi" alt=""><figcaption><p>V3 Pools Page</p></figcaption></figure>

### **Creating a Position**

To begin creating a position, click `New Position` and choose the tokens you want to add liquidity for. You can provide liquidity for any pair of tokens supported on Kodiak.

<figure><img src="/files/VFZSdi6Vhcift1P9bOKp" alt=""><figcaption><p>New V3 Position Page</p></figcaption></figure>

1. **Select Fee Tier:** Choose your desired fee tier.

   <div align="left"><figure><img src="/files/4aRBFbEBBsiFl43g603M" alt=""><figcaption><p>Fee Tier Selection</p></figcaption></figure></div>
2. **Token Denomination Toggle (optional):** You can toggle between the two tokens for the pair to set which token you want the prices to be denominated in.

   <figure><img src="/files/IzCi2rqOScWKg36Xnxm0" alt=""><figcaption><p>Token Denomination Toggle</p></figcaption></figure>
3. **Choose a Price Range**: Select the price range you wish to provide liquidity for. You can also select `Full Range` to set the price range to full-range.

   <div align="left"><figure><img src="/files/5c2nuusS0gqe0Vdfbjdu" alt=""><figcaption><p>Set Price Range</p></figcaption></figure></div>
4. **Enter Amounts:** Enter the amount of each token you wish to deposit to the liquidity pool.&#x20;

   * ***For existing pools:*** Kodiak will automatically calculate the proper token amount for the other side of the pair based on the current price of the pair and the price range you've selected.

   <figure><img src="/files/6hNR2eTA42avKK8qSmC9" alt=""><figcaption><p>Deposit Amounts</p></figcaption></figure>
5. **Transaction Settings (optional):** You can select the gear icon to adjust slippage for the transaction (optional/as needed).

<figure><img src="/files/1fHulXqzRCyqdYao17jp" alt=""><figcaption><p>Transaction Settings</p></figcaption></figure>

6. **Approve Token(s):** If it's your first time providing V3 liquidity for the particular token(s), you will need to approve the token(s) to be used by Kodiak. You will see two `Approve [ ]` buttons if you have to approve both tokens for the pair.

<figure><img src="/files/dDHfEtgVyHnHfTrJ6ubL" alt=""><figcaption><p>Approve Token(s)</p></figcaption></figure>

7. **Preview Transaction & Add Liquidity:** Select `Preview` to carefully review the details of your transaction, including the token amounts and your ensuing share of the liquidity pool. If all checks out, click `Add` and confirm the transaction in your wallet. The transaction should be confirmed on Berachain within a few seconds.

<figure><img src="/files/13af80s45GIx6iwbjYqu" alt=""><figcaption><p>Add V3 Liquidity Transaction Preview</p></figcaption></figure>

8. **Transaction Complete:** Following confirmation, you have now created a Kodiak V3 Position. You'll receive an LP Non-Fungible Token that represents your position. You can view your position details back in the V3 Pools view.&#x20;


# Add/Stake Islands Liquidity

Depositing Liquidity with Kodiak Islands

**Navigate to the Top Pools Page**

Click on the `Liquidity` option within the navigation bar. Within this section, ensure the `Top Pools` tab is selected. This will display a list of the top Islands and V2 pools available on Kodiak.

<figure><img src="/files/VvY3xGvZDtuHW4UzO6zE" alt=""><figcaption></figcaption></figure>

## **Depositing into an Island**

To deposit into a Kodiak Island, begin by clicking on your desired island to navigate to that Island's management page.&#x20;

<figure><img src="/files/74i4ekpMn4XtX4Czjrdr" alt=""><figcaption></figcaption></figure>

When depositing into the Island, you have the following two options:

### **Deposit Only**

Selecting this option will mint Island shares that represent your position in the pool, giving you exposure to a portion of the trading fees within the Island's liquidity range.&#x20;

When supplying liquidity to the Island, you have two options depending upon the tokens you hold.

If you have both the Island tokens you can choose to deposit with both the tokens or if you have one of the Island tokens you can use the inbuilt zap feature to deposit with the single token.&#x20;

#### Deposit with Both Tokens

You should be holding both the island tokens and select Double-sided as shown below when providing this liquidity.&#x20;

<figure><img src="/files/Wgc70iHvVYqakfhuH76v" alt="" width="320"><figcaption></figcaption></figure>

1. **Enter Amounts:** Select your desired deposit amounts and click `Supply`.&#x20;
   * *Ensure that* `Deposit Only` *is selected.*
2. **Approve Token(s):** If it's your first time providing liquidity for this Island, you will need to approve the token(s) to be used by Kodiak.
3. **Confirm Transaction:** Carefully review the details of your transaction, including the token amounts and your estimated shares of the liquidity pool. If it looks good, click `Confirm` and approve the transaction in your wallet.

#### Deposit with a Single Token

Often, you would be holding one of the underlying tokens, you can choose to supply liquidity to the Island with a single token by selecting the option single-sided as shown below. Part of the token you want to deposit with, will be swapped for another token and both the tokens will be deposited into the Island. The final tokens deposited will be shown under `Deposit Details` and the Swap Details and slippage control is present in the `Sawp Details` section as shown below.

<figure><img src="/files/Il0Xqp5vBZIk8nVZhqHo" alt="" width="320"><figcaption></figcaption></figure>

* **Enter Amount:** Select the token you want to deposit with and input the desired deposit amount.
* Wait a while for the system to figure out the swap amount and get the quote.
* Verify the Swap Details and price impact warning.
* Once verified Click `Confirm Deposit with Zap`.&#x20;
  * *Ensure that* `Deposit Only` *is selected.*
* **Approve Token(s):** If it's your first time providing liquidity for this Island, you will need to approve the token(s) to be used by Kodiak.
* **Confirm Transaction:** Carefully review the details of your transaction, including the token amounts and your estimated shares of the liquidity pool. If it looks good, click `Confirm` and approve the transaction in your wallet.
* If the system detects that the liquidity cannot be provided with a swap, it shows an error on the button and asks you to deposit liquidity with both tokens. In such a case, acquire both tokens and deposit into the Island.

### **Deposit With Staking (Farms & Reward Vaults)**

To earn higher rewards, you can select to mint Island shares and, within the same transaction, deposit them into the Farm or Reward Vault (as applicable) where you will earn extra rewards in addition to trading fees for the respective pool.&#x20;

For Kodiak farms (separate from PoL Reward Vaults), there is a locking time period and selecting a higher lock time provides you with a higher multiplier to earn these rewards.&#x20;

However, for Islands that are whitelisted for BGT emissions, the Island shares can be staked into the respective Reward Vault.&#x20;

To stake your Island shares with the correspodning Farm or Reward Vault (as applicable), do the following:

1. **Enter Amounts:** Select your desired deposit amounts and click `Supply`.&#x20;
   * *Ensure that* `With Staking` *is selected.*
2. **Approve Token(s):** If it's your first time providing liquidity for a particular token, you will need to approve the token to be used by Kodiak.
3. **Select Lock Time (ONLY for Farms)**: Choose your desired lock-up period. The longer the lock, the higher your reward multiplier will be.&#x20;

   <figure><img src="/files/0pjV1bHiRnm0ThJhfqnS" alt=""><figcaption></figcaption></figure>
4. **Confirm Transaction:** Carefully review the details of your transaction, including the token amounts and your ensuing share of the liquidity pool. Confirm this transaction in your wallet. The transaction should be confirmed on Berachain within a few seconds.
5. **Approve Island Shares**: You'll now be asked to approve the Kodiak Island shares you've just minted, so that they can be deposited into the farm.&#x20;
6. **Confirm Stake:** Review the final details and deposit your shares into the Farm or Reward Vault (as applicable).&#x20;
   * Once you've deposited into a Farm or Reward Vault, you can view your stakes and their respective time remaining until unlock (only applicable for Farms, Reward Vaults do not have any lock-up period) by navigating to the `Unstake` tab.


# Baults (Auto-Compound)

### Table of Contents

1. [Overview](#overview)
2. [Quick Start Guide](#quick-start-guide)
3. [User Interface Guide](#user-interface-guide)
4. [FAQ](#frequently-asked-questions)

***

### Overview

**Baults** are auto-compounding vaults for your LP tokens. Instead of manually claiming BGT rewards and reinvesting them yourself, Baults handle this automatically.

Here's how it works: you deposit your LP tokens, and whenever BGT rewards accumulate, the vault automatically claims and reinvests them back into your position. Baults take care of always choosing the highest yielding BGT wrapper or raw BGT through a continuous auction mechanism.&#x20;

#### Key Benefits

{% hint style="success" %}
**✨ Auto-Compounding** - Your BGT rewards are automatically reinvested and compounded

**📈 Optimal Yield** - BGT rewards are continuously auctioned to highest bidder (including liquid wrappers)

**🔒 Secure** - Built on battle-tested ERC-4626 vault standards

:heavy\_dollar\_sign:  **Tokenized -** Bault shares are fully composable in DeFi (and can be stacked with Kodiak Farm)
{% endhint %}

***

### Quick Start Guide

### Find Baults

To see which pools support auto-compounding, enable the **Baults** filter

<figure><img src="/files/6NVgpzCnMDRX2qZCZFhN" alt=""><figcaption></figcaption></figure>

**Steps to find Baults:**

1. Check the **"Baults"** filter box
2. Browse the pool list for auto-compounding opportunities

### Identifying Auto-Compounding Pools

Pools eligible for Baults will show a **star icon** (🌟) in the APR column.<br>

<figure><img src="/files/4cVYTRUQY5TErQ2NXEaL" alt=""><figcaption></figcaption></figure>

**Hover over the star** to see Bault details:

* "This pool is eligible for auto-compounding"
* Specific APY rate (e.g., "Earn 27.28% APY in Bault")

<figure><img src="/files/SIauJxgg35Wj3ueQsxCN" alt=""><figcaption></figcaption></figure>

***

### User Interface Guide

### Depositing in Baults

There are several ways to get your tokens into auto-compounding Baults:

1. **Migration from BGT Reward Vault**

If you already have positions staked in BGT Reward Vaults, you'll see a migration prompt appear automatically.

<figure><img src="/files/e18Y1SggFSwRwvIjMEl6" alt=""><figcaption></figcaption></figure>

#### When Migration Appears

The **"Migrate to Auto-Compound"** prompt automatically appears when:

✅ **You have positions in BGT Reward Vault** (manual staking)

**Example**: "You have $0.28 staked in the Reward Vault. Migrate to baults to automatically reinvest your rewards and maximize your yield."

#### 3-Step Migration Process

{% hint style="info" %}
Migration is a **3-step process** that ensures everything transfers correctly and safely.
{% endhint %}

<figure><img src="/files/YPoX7bAiyd11o7FvUsth" alt=""><figcaption></figcaption></figure>

**Step 1: Review & Start Migration**

**Migration Setup Modal**:

* **Amount Selection**: Choose how much to migrate (can be partial)
* **Balance Check**: Shows available LP tokens in Reward Vault
* **Important Warning**: "Any unclaimed rewards in your current vault will not be automatically migrated. Make sure to claim them separately before or after migration."

**Example from Interface**:

* Available to migrate: 0.0838315 KODI WBERA-HONEY
* Current value: $0.28
* Buttons: "Cancel" or "Start Migration"

**Step 2: Unstake from Reward Vault**

<figure><img src="/files/4qxbh6sbuPXfXPTVBKk5" alt=""><figcaption></figcaption></figure>

**What Happens**:

* **Removes LP tokens** from BGT Reward Vault
* **Shows breakdown** of what gets unstaked vs rewards that remain
* **Transaction required** to unstake your position

**Interface Details**:

* **Total Value**: ($0.28) 0.0838315 KODI WBERA-HONEY
* **Accrued Rewards**: BGT (<$0.01) 0.00069908 (not included in unstake)
* **Action Button**: "Unstake 0.0838315 KODI WBERA-HONEY"

{% hint style="danger" %}
**Important**: BGT rewards remain unclaimed and are **not automatically claimed**. You can claim them before or after migration.
{% endhint %}

**Step 3: Approve & Deposit to Bault**

<figure><img src="/files/p7fkLA7T4iEXdlBtjfbG" alt=""><figcaption></figcaption></figure>

**Final Step**:

* **Token Approval**: Allow Bault contract to use your LP tokens (if needed)
* **Deposit to Bault**: Move LP tokens into auto-compounding vault
* **Receive Bault Shares**: Get auto-compound vault tokens

**Interface Shows**:

* **Final Amount**: 0.0838315203... KODI WBERA-HONEY
* **Value**: $0.28
* **Action Button**: "Confirm Deposit"

**Result**: Your LP tokens are now in the auto-compounding Bault, earning higher yields through auto-compounding.

2. **Using the Deposit Tab**

<figure><img src="/files/kEJFYsb5HyBUxkVG2iLq" alt=""><figcaption></figcaption></figure>

You are able to deposit directly to baults using the **Deposit Tab,** all you have to do is turn on the "Auto-compound rewards" toggle

<figure><img src="/files/mTONI1SD4xLXpaVesKDm" alt=""><figcaption></figcaption></figure>

The below table explains how the deposit tab flow works with the toggle turned on/off

{% tabs %}
{% tab title="Auto-Compound Strategy (Recommended)" %}
**🔄 Auto-Compound: ON**

**Deposit Only Flow**:

```
Your Tokens → Island LP → Bault Shares
```

* ✅ Add liquidity to Island pool
* ✅ Automatically deposit LP tokens into Bault
* ✅ Start earning auto-compounded BGT rewards
* ✅ Receive Bault shares (compound over time)
  {% endtab %}

{% tab title="⏸️ Auto-Compound: OFF" %}
**Deposit Only Flow**:

```
Your Tokens → Island LP (in wallet)
```

* ✅ Add liquidity to Island pool only
* ✅ Receive Island LP tokens in your wallet
* ✅ Manual control over what to do next
* ✅ Can stake manually later via Stake tab

**With Staking Flow**:

```
Your Tokens → Island LP → BGT Reward Vault
```

* ✅ Add liquidity to Island pool
* ✅ Immediately stake LP tokens in BGT Reward Vault
* ✅ Earn BGT rewards (requires manual claiming)
* ✅ Direct BGT rewards, no auto-compounding
  {% endtab %}
  {% endtabs %}

***

### 🎯 Stake Tab: Direct Staking

The **Stake Tab** is for users who already have lp tokens and want to stake them without adding new liquidity.

#### Real Example Walkthrough

<figure><img src="/files/R8UfGIqjTCjWCghTzpoG" alt=""><figcaption></figcaption></figure>

**From the Interface:**

* **Available**: 0.24194 KODI WBERA-HONEY (Island LP tokens)
* **Strategy**: Auto-Compound ON
* **Expected**: \~0.2409 Bault-KODI WBERA-HONEY shares
* **APY**: 52.88% (with auto-compounding)

**What Happens:**

1. Stakes your 0.24194 Island LP tokens
2. Deposits them into Bault auto-compounding vault
3. You receive \~0.2409 Bault shares
4. Starts earning 52.88% APY through automated BGT compounding

***

#### Unstake Tab

The **Unstake Tab** lets you remove tokens from staking positions without withdrawing liquidity entirely.

<figure><img src="/files/oDwdnDL2nE2rQHUnQ1QT" alt=""><figcaption></figcaption></figure>

#### Smart Toggle System

**When you have multiple staking positions**, a toggle appears to choose which one to unstake:

<table><thead><tr><th width="192.1875">Your Positions</th><th>Toggle Options</th></tr></thead><tbody><tr><td><strong>Reward Vault + Bault</strong></td><td>"Reward Vault" | "Auto-Compound"</td></tr></tbody></table>

***

### ❓ Frequently Asked Questions

<details>

<summary>Which strategy should I choose as a beginner</summary>

**Recommendation**: Start with **Auto-Compound + Deposit Only**

**Why this is best for beginners**:

* ✅ Hands-off management (set and forget)
* ✅ Higher long-term returns than manual

</details>

<details>

<summary>💸 When should I withdraw vs unstake?</summary>

**Withdraw When**:

* You need the actual tokens for other purposes
* You're completely exiting
* You want to sell the underlying assets

**Unstake (Keep LP Position) When**:

* You want to change staking strategies (e.g. moving to an Infrared Vault)
* You're optimizing your current position
* You might restake differently later
* You want to keep LP exposure but change reward method&#x20;

</details>

<details>

<summary>🔢 How is APY calculated?</summary>

APY is calculated by annualizing the share growth from the 10 most recent realized compounds.

</details>

<details>

<summary>⚡ How often does compounding happen?</summary>

You can see how often compound happens in the bault analytics section on the app, it shows detailed information about a specific baults

</details>

<details>

<summary>🎫 What are Bault shares?</summary>

**Bault Shares Explained**:

* **Representation**: Your proportional ownership of the vault
* **Growth**: Share value increases as rewards compound
* **Standard**: ERC-4626 vault token standard
* **Fungible**: Can be transferred like any ERC-20 token

**Example**: Start with 1 share worth 1 LP token. After compounding, 1 share might be worth 1.1 LP tokens.

</details>


# BGT Liquid Wrapper

### Overview

We now allows liquidity providers (LPs) staked in Berachain Reward Vaults to claim their BGT rewards and directly mint BGT liquid wrappers through the our UI. This feature enables users to choose from multiple liquid wrapper options and see real-time premium rates before minting.

### What are BGT Liquid Wrappers?

BGT liquid wrappers are tokenized versions of BGT that trade at different premiums and offer various utility features:

* **iBGT (Infrared Finance)** - Infrared BGT
* **yBGT (Bearn)** - Bearn BGT
* **LBGT (Berapaw)** - Liquid BGT
* **Additional wrappers** - More options coming soon

{% hint style="info" %}

### Prerequisites

Before you can mint BGT liquid wrappers, you must:

1. **Deposit into Kodiak Pools**: Provide liquidity to get LP tokens
2. **Stake LP Tokens**: Stake your LP tokens in the respective Berachain Reward Vault
3. **Accumulate BGT Rewards**: Wait for BGT rewards to accrue from your staked position
   {% endhint %}

### Step-by-Step Guide

#### Step 1: Deposit and Stake LP Tokens

1. Navigate to your desired Kodiak pool/Island page
2. Deposit liquidity to receive LP tokens
3. Go to the **"Stake"** tab on the pool page
4. Click **"Stake in BGT Reward Vault"**
5. Approve the LP token allowance
6. Confirm your stake transaction

<figure><img src="/files/vdv5y2vqloFoCQodsutB" alt=""><figcaption></figcaption></figure>

#### Step 2: Claim BGT Rewards

1. Once you have accumulated BGT rewards, return to your pool/Island page
2. Click **"Claim BGT Rewards"** button
3. A popup will appear showing your available rewards

<figure><img src="/files/AuQPKFZbfqyG6j0uPNNy" alt=""><figcaption></figcaption></figure>

#### Step 3: Select Liquid Wrapper Option

1. In the claim popup, click **"Mint Liquid Wrapper"** at the top
2. Review the available wrapper options:
   * Options are sorted by highest premium rates
   * Each option shows the current premium and estimated receive amount
   * Fee information is displayed for each wrapper

Step 4: Choose Your Wrapper

Current supported wrappers include:

* **iBGT (Infrared)** - Often has the highest premium
* **yBGT (Bearn)** - Alternative wrapper option
* **LBGT (Berapaw)** - Additional wrapper choice

{% hint style="info" %}
**Premium Comparison**: The UI displays real-time premium rates, allowing you to select the most valuable option at the time of minting.
{% endhint %}

<figure><img src="/files/Ezr65FATjXx9VCYxW9IN" alt=""><figcaption></figcaption></figure>

#### Step 5: Complete the Minting Process

1. Select your preferred wrapper (e.g., iBGT)
2. Review the transaction details:
   * Amount you're converting
   * Estimated tokens you'll receive
   * Associated fees
3. Click **"Mint Liquid Wrapper"** at the bottom
4. **Approve Operator** (one-time approval required)
5. **Confirm the mint transaction**
6. Wait for transaction confirmation

<figure><img src="/files/OXfvPpVRxWSpAE7dENtv" alt="" width="375"><figcaption></figcaption></figure>

<figure><img src="/files/ZAY7aQke6xR7ygMaJGHR" alt="" width="375"><figcaption></figcaption></figure>

{% hint style="info" %}
**Important Considerations**

* Premium rates fluctuate based on market conditions
* Higher premiums mean better value for your BGT
* Check current rates before selecting a wrapper
* First-time users need to approve the operator contract
* Approving a new liquid wrapper overwrites the approval for any previously approved wrapper
* Only one wrapper can be approved at a time - switching wrappers requires a new approval
* BGT rewards accrue over time based on your staked LP position
* You can claim and mint at any time once rewards are available
  {% endhint %}


# Migrating to a Reward Vault

Migrating your V2 pool LP token and/or your Island Shares from a Farm to a Reward Vault.

Throughout the lifecycle of many V2 and Island pools, it's common for a pool to transition from offering Farm rewards to being whitelisted for a Proof of Liquidity Reward Vault. When this happens, Kodiak makes it easy for users to seamlessly migrate their positions into the corresponding Reward Vault. Additionally, users with remaining lock-up periods in the original Kodiak Farms will now be able to unstake their positions at this time.

**Go to the Specific Pool's Management page**

Click on the `Liquidity` option within the navigation bar. Within this section, ensure the `Top Pools` tab is selected. Click on the specific pool you wish to migrate from a Farm to the Reward Vault.

<figure><img src="/files/VvY3xGvZDtuHW4UzO6zE" alt=""><figcaption></figcaption></figure>

## **Migrate to Reward Vault**

1. Click `Migrate to Reward Vault` to start the migration process on the respective Pool's management page.

<figure><img src="/files/ui7nfDZRj48yzPYH3WBI" alt=""><figcaption></figcaption></figure>

2. Read the disclaimer and steps detailed in the pop-up and click `Start Migration` if you would like to proceed.

<figure><img src="/files/vBCu2g7STHWD0x1dWNwL" alt=""><figcaption></figcaption></figure>

3. Approve the unstaking of the Island Share /  V2 LP tokens from the Kodiak Farm.

<figure><img src="/files/vw8vrIv0SWCcmoZ3mL90" alt=""><figcaption></figcaption></figure>

3. Approve the Island Shares / V2 LP tokens allowance.&#x20;

   <figure><img src="/files/5UCl7HWhZM4rYZrZupNI" alt=""><figcaption></figcaption></figure>
4. Approve the staking of the Island Shares / V2 LP tokens into the respective Reward Vault.

<figure><img src="/files/oUn6mbTpMrB1ZR0fjtfs" alt=""><figcaption></figcaption></figure>

3. Congratulations! You have staked your Island Shares / V2 LP tokens into the Reward Vault. You can also claim earned BGT rewards and boost your BGT with the Kodiak Validators within the Kodiak dApp.

<figure><img src="/files/gn7MztJ6zRKRjDwWZme2" alt=""><figcaption></figcaption></figure>


# Deploying new Permissonless Islands

User guide on how to deploy new permissionless islands

Kodiak provides a simple way to deploy [permissionless islands](/protocol/islands) on any v3 pool. This enables anyone to use this island to provide liquidity in the pre determined price range abstracting away all the v3 complexities and increased efficiency by auto compounding earned fee.

To deploy a new permissionless island you must understand the basics of providing liquidity to a Kodiak v3 pool and the mechanics behind concentrated liquidity provisioning.

Once you understand the concept of conc. liquidity, follow these steps to deploy a new permissionless island.

1. Navigate to V3 Pools section of the app and click on `New Position` from the bottom right of the screen.

<figure><img src="/files/Wcmg8kZrc9bXZcUXFMxC" alt=""><figcaption></figcaption></figure>

2. Select the token and fee tier. The order of tokens do not matter.

<figure><img src="/files/vpy7bcsEfHVStsSmmL7K" alt=""><figcaption></figcaption></figure>

3. Click on `Advanced Mode` and select the price range from the right hand section.

<figure><img src="/files/ZdNyWs9EyF3ODdymIGe9" alt=""><figcaption></figcaption></figure>

4. Carefully review and confirm the tick and the price range of the island. These cannot be changed once deployed. Click on `DeployIsland` and confirm the transaction in your wallet.
5. The island is now deployed but won't be visible on the kodiak UI yet. Reach out to the Kodiak team to get your island displayed on UI.

> This prevents an overload of islands from being displayed on UI and confusing for users to select from.


# Deploying and Configuring a Kodiak Farm

## Deploying and Configuring a Kodiak Farm

This guide will walk you through the process of deploying a new Kodiak Farm contract and configuring it to distribute rewards for staked tokens.

### Overview

Kodiak Farm is a DeFi staking solution that allows users to earn rewards by staking their tokens. As a farm creator, you can customize various parameters to determine how rewards are distributed, including reward rates, lock periods, and multipliers.

### Prerequisites

Before deploying a Kodiak Farm, ensure you have:

* An Ethereum-compatible wallet (like MetaMask) connected to the appropriate network
* The contract address of the token users will stake (LP token)
* The contract address of the token(s) you will distribute as rewards
* Sufficient reward tokens to fund the farm
* ETH/native tokens for transaction fees

### Deploying a Kodiak Farm Contract

#### Step 1: Access the Farm Deployment Interface

Navigate to the ["Create Farm" ](https://app.kodiak.finance/#/liquidity/farms?chain=berachain_mainnet)page in the Kodiak app.

<figure><img src="/files/bdpLdRpjDUqbGIwwNIm6" alt=""><figcaption></figcaption></figure>

Step 2: Enter Staking Token Details

1. **Staking Token Address**: Enter the LP token address (beginning with "0x...") that users will stake to earn rewards.

   > **Note**: This is typically a liquidity pool (LP) token or Kodiak Island token, but can be any ERC-20 compatible token.

#### Step 3: Configure Reward Token Settings

In the "Reward Token" section:

1. **Reward Token Address**: Either select a token from the dropdown menu or enter the contract address of your reward token.
2. **Reward Manager Address**: Enter the address that will have permission to manage reward distributions. This address will have special privileges to adjust reward parameters.

   > **Important**: The reward manager will have significant control over the reward token, being able to adjust reward rates and withdraw tokens. In most cases, this should be an address you control, or a team multi-sig.
3. **Monthly Reward Amount**: Specify the total amount of tokens to be distributed as rewards each month.

   > **Calculation**: The system will automatically calculate the per-second distribution rate based on this amount.
4. To add multiple reward tokens, click the "+ Add Reward Token" button in the top-right corner of the section.

<figure><img src="/files/0A0JlH2NPw5f77zaTIFL" alt=""><figcaption></figcaption></figure>

#### Step 4: Initialize Deployment

Click the "Deploy Farm" button at the bottom of the page to proceed to the deploying farm.

### Configuring Farm Parameters

After deploying the farm contract, you'll need to configure it before users can begin staking. The farm status will initially show as "Not Started".

<figure><img src="/files/fML2YAMBH5dWz6V5MXP8" alt=""><figcaption></figcaption></figure>

#### Step 1: Review Farm Configuration (Step 1/2)

The configuration page displays "Step 1/2" in the top-right corner, indicating this is the first of two configuration steps.

#### Step 2: Verify Reward Token Configuration

1. **Custom Token**: Confirm the reward token address is correct (e.g., 0x1319d21A0eC48F847C15823fc3e8bC7f5aae9ca2).
2. **Reward Rate**: Review the reward distribution rate. The interface displays this as:
   * Raw rate (e.g., 9999999.99999999999072)
   * Human-readable equivalent (e.g., 3.85802469/sec)

<figure><img src="/files/4Q3KlQtkJRyOClSsPI6Z" alt=""><figcaption></figcaption></figure>

1. **Reward Manager**: Verify the reward manager address is correct (e.g., 0x4f5F9dB14E195484cf7790fD3946CF6e66A166B0).

#### Step 3: Set Staking Token Cap

The staking token cap determines the maximum amount of tokens that can be staked in your farm.

<figure><img src="/files/MOhllui7o6t37cBu6Rwb" alt=""><figcaption></figcaption></figure>

> **Important**: Enter `-1` to set an unlimited cap (maximum uint256 value). This allows unlimited staking in your farm.

#### Step 4: Configure Reward Multipliers and Lock Periods

1. **Maximum Multiplier**: Use the slider to set the maximum reward multiplier (e.g., 3x). This value determines how much additional rewards users can earn by staking for longer periods.

<figure><img src="/files/NlyIRwPLCz9HmG2lzQHj" alt=""><figcaption></figcaption></figure>

1. **Minimum Lock Time**: Set the minimum required staking period in days. Users must stake for at least this duration before they can withdraw.

   * Set to `0 day(s)` if you don't want to enforce a minimum staking period
   * Higher values increase commitment but may deter some users

   <figure><img src="/files/Rgs7z6CiY5nMVqrmNZPG" alt=""><figcaption></figcaption></figure>
2. **Lock Time for Max Multiplier**: Set the staking duration (in days) required to receive the maximum reward multiplier.

   * In the example shown, users need to stake for 30 days to receive the 3x multiplier
   * Shorter lock periods will receive proportionally smaller multipliers

   <figure><img src="/files/EjZH4CVG3CnwYvRBB1nf" alt=""><figcaption></figcaption></figure>
3. **Rewards Duration**: Set the total period (in days) during which farming rewards will be distributed.

   * This determines how long your farm will be active
   * Ensure you have sufficient reward tokens to cover this entire period

   <figure><img src="/files/8coVsJDeQwGWrS9tUeaf" alt=""><figcaption></figcaption></figure>

#### Step 5: Review and Finalize Configuration

1. To reset all parameters to default values, click the "Reset" button.
2. When you're satisfied with all settings, click the "Review Changes" button to proceed to the final confirmation step.

### Starting the Farm

After completing the configuration, you'll need to start the farm to activate it.

#### Step 1: Final Review

Review all parameters one final time to ensure they're set correctly.

#### Step 2: Ensure Sufficient Reward Tokens

Before starting the farm, make sure:

* Your wallet or the contract has sufficient reward tokens to cover the entire rewards duration
* You have enough Bera to pay for the transaction fee

> **Critical**: If the contract or wallet doesn't have enough reward tokens, the farm cannot be started.

#### Step 3: Activate the Farm

Click the "Start Farm" button to activate your farm.

<figure><img src="/files/UjENNIHDVyKxeDCOtGnj" alt=""><figcaption></figcaption></figure>

After successful activation, the farm status will change from "Not Started" to "Active".

### Troubleshooting Common Issues

#### Farm Won't Start

* **Problem**: Clicking "Start Farm" doesn't activate the farm
* **Solution**: Verify you have sufficient reward tokens. Check both your wallet balance and any allowances granted to the farm contract.

#### Incorrect Parameters

* **Problem**: Parameters appear incorrect after configuration
* **Solution**: Use the "Reset" button during configuration and set them again. Double-check all values before finalizing.

#### Transaction Failures

* **Problem**: Transactions fail during deployment or configuration
* **Solution**: Ensure you have sufficient ETH/native tokens for gas. Verify all addresses are correctly formatted and valid on the network.

### Conclusion

Congratulations! You've successfully deployed and configured a Kodiak Farm. Users can now stake their tokens and earn rewards based on your configured parameters.

For additional assistance or feature requests, please contact the Kodiak Finance support team via [Discord](https://discord.gg/vhZmNFNbCZ)


# Add your token

Add your token to the default list

{% hint style="warning" %}
Note: The information on this page assumes that you are familiar with Git. If you are not, please familiarise yourself with Git first.
{% endhint %}

If you have any token of your own and would like to include it in the default list and add your logo, please create a Pull Request to this [repository](https://github.com/Kodiak-Finance/static-public/)

> Your token contract **must be verified** on the explorer for the pull request to be approved.

### Step 1. Fork repository

<figure><img src="/files/ZI7SxRQtr7Gtpf3K3r0G" alt=""><figcaption><p>static-public repository</p></figcaption></figure>

After this step, you will copy the entire repository to your personal library

### Step 2. Create a new branch and make the changes

Create your own branch, for example add-guide-token and make two changes:

1. Add your `.png` logo to the `src/tokens` directory (for example `src/tokens/guide.png`)
2. Modify `tokenLists/berachain_mainnet.json`

<figure><img src="/files/mKiVaswgDkcvAgpRr7MO" alt=""><figcaption></figcaption></figure>

<figure><img src="/files/gAI0cYOZpZGbS5biRrZ0" alt=""><figcaption></figcaption></figure>

{% hint style="warning" %}
Do not change the domain in `logoURI`!&#x20;

Your logo that you put in `src/tokens` will automatically be available at `static.kodiak.finance/tokens/[your_filename]`

This step also includes automatic image compression and resizing. But you must make sure that you provide a 1:1 square image, otherwise your image may be distorted.
{% endhint %}

\
Push these changes

### Step 3. Create pull request

<figure><img src="/files/h9LHGGMq92qLQ9GBomxl" alt=""><figcaption></figcaption></figure>

<figure><img src="/files/Ccy4qWaOPFzKauzB4rCO" alt=""><figcaption></figcaption></figure>

Finally, just create this Pull Request and expect a check from the team


# Add Your Project to the Ecosystem

{% hint style="warning" %}
The information on this page assumes that you are familiar with Git. If you are not, please familiarize yourself with Git first.
{% endhint %}

Kodiak Finance aims to showcase the vibrant ecosystem of projects building on Berachain. If you've developed a project that contributes to the Berachain ecosystem, we welcome you to submit it for inclusion in our ecosystem directory.

### Project Eligibility

For your project to be included in the Kodiak ecosystem, it should meet the following criteria:

* Live and operational on Berachain mainnet or testnet
* Provides clear value to the Berachain ecosystem
* Has a functional product, service, or platform (not just a concept)
* Maintains active development and community engagement

{% hint style="info" %}
Projects in various stages of development may be accepted, but priority is given to launched projects with verifiable activity.
{% endhint %}

### Step 1. Fork repository

Fork the [Kodiak static-public repository](https://github.com/kodiak-finance/static-public) to create your own copy of the repository.

<figure><img src="/files/dy3ijUlgc6v624dbPNmB" alt=""><figcaption><p>the kodiak static-public repository</p></figcaption></figure>

### Step 2. Create a new branch and make the changes

Create a new branch with a descriptive name related to your project:

```bash
git checkout -b add-your-project-name
```

You'll need to make the following additions:

1. Add your project logo to the `ecosystem/logo` directory
   * File must be in `.png` format with transparent background
   * Recommended dimensions: 256×256 pixels
   * Use lowercase for the filename (e.g., `yourproject.png`)
2. Add your project details to the `ecosystem/projects.json` file:

```json
{
  "name": "Your Project Name",
  "category": "Lending",
  "description": "A concise description of what your project does and its value proposition",
  "logoURI": "https://static.kodiak.finance/ecosystem/logo/yourproject.png",
  "link": "https://yourproject.com"
}
```

#### Available Categories

Choose the category that best represents your project:

* **Derivatives**: Projects focused on derivatives trading, synthetic assets, or options
* **Gamblefi**: Gaming, gambling, or prediction market platforms
* **Infrastructure**: Tools, APIs, indexers, oracles, or core infrastructure services
* **Launchpad**: Project incubators, IDO platforms, or fundraising solutions
* **Lending**: Lending and borrowing protocols or services
* **LST / LSD**: Liquid staking tokens or liquid staking derivatives
* **Structured Products**: Yield vaults, auto-compounders, or structured investment products

{% hint style="danger" %}
• Do not modify the `logoURI` domain - only change the filename portion • Keep your description informative but concise (maximum 100 characters) • Choose only one category that best represents your project's primary function&#x20;
{% endhint %}

### Step 3. Update Version Number

Update the version number in `ecosystem/projects.json` following semantic versioning principles:

* Increment **major** version when projects are removed (e.g., 1.0.0 → 2.0.0)
* Increment **minor** version when projects are added (e.g., 1.0.0 → 1.1.0)
* Increment **patch** version when existing projects are updated (e.g., 1.0.0 → 1.0.1)

Since you're adding a new project, you'll typically increment the minor version.

### Step 4. Commit and Push Your Changes

Commit your changes with a descriptive message:

```bash
git add ecosystem/logo/yourproject.png
git add ecosystem/projects.json

git commit -m "Add [Your Project Name] to ecosystem"
git push origin add-your-project-name
```

### Step 5. Create a Pull Request

Go to the original [Kodiak static-public repository](https://github.com/kodiak-finance/static-public) and create a new Pull Request from your branch.

* Title your PR: "Add \[Your Project Name] to ecosystem"
* In the description, briefly explain what your project does and why it would be valuable to the Kodiak ecosystem
* Link to your project's website, documentation, and social media (if applicable)

### Review Process

The Kodiak team will review your submission based on:

* Relevance to the Berachain ecosystem
* Project quality and usability
* Accuracy of information provided
* Compliance with the submission guidelines

This process typically takes 2-5 business days. You may be asked to provide additional information or make changes to your submission.

### Example Submission

Here's an example of a well-formatted project submission:

```json
{
  "name": "HoneySwap",
  "category": "Infrastructure",
  "description": "Decentralized exchange optimized for Berachain with concentrated liquidity and low fees",
  "logoURI": "https://static.kodiak.finance/ecosystem/logo/honeyswap.png",
  "link": "https://honeyswap.xyz"
}
```

For any questions or assistance with the submission process, please reach out to the Kodiak team via [Discord](https://discord.gg/vhZmNFNbCZ)


# Perp Bots

### Deploying your first bot <a href="#deploying-your-first-bot" id="deploying-your-first-bot"></a>

1. **Accept Terms of Service:** Review the Terms of Use and Privacy Policy, check the acknowledgement box, then select `Agree and Continue`.

<figure><img src="/files/erOYYah2I8kp6sQUlSJh" alt=""><figcaption></figcaption></figure>

2. **Connect Wallet:** Select `Connect Wallet` in the top-right corner of the app and choose your desired wallet provider.

<figure><img src="/files/avqozNyOhquqnbCWsnaj" alt="Connect Wallet"><figcaption></figcaption></figure>

3. **Sign in with your wallet:** After connecting, accept Terms of Service, select `Sign in` and confirm the signature request in your wallet.

<figure><img src="/files/nqG5PtzOYWeGKMUVD3Q7" alt=""><figcaption></figcaption></figure>

4. **Set your passphrase:**
   * Go to the Accounts page and select `Set passphrase` in the banner.

<figure><img src="/files/5lP7aG53bbhiNcHCIZON" alt=""><figcaption></figcaption></figure>

* In the modal window that opens, create a passphrase that will be used to encrypt your exchange API keys in your browser before they are stored.

{% hint style="info" %}
Keep this passphrase safe. If you lose it, you will need to reset your linked accounts and add them again.
{% endhint %}

<figure><img src="/files/HXKCwtx7pbbgf56mx92f" alt=""><figcaption></figcaption></figure>

5. **Add an account:** On the Accounts page select `Add Account`.

<figure><img src="/files/Uie7cHRpm179ggIM2PIe" alt=""><figcaption></figcaption></figure>

The app currently supports the following exchanges: Kodiak Perps and Hyperliquid. In this guide, we will use Kodiak Perps.

You will see then two options:

1. Generate new API Key: creates a new API Key for your exchange account through the app.
2. Use Existing: adds API credentials that were already created on the exchange side.

For this guide, we will continue with option 1.

<figure><img src="/files/xvm3lJlndzcS3jJX5Pxp" alt=""><figcaption></figcaption></figure>

Select an exchange account you want to use, enter a name for it, then click `Generate API Key` button and confirm the signature request in your wallet.

<figure><img src="/files/YL8bTdQDxblQimuYk83U" alt=""><figcaption></figcaption></figure>

Once an account is created, it appears in the accounts list with an Active status. Active account can be used to deploy and run bots. You can also deactivate an account from this page if you no longer want to use it.

6. **Deploy a bot:** Go to the Deploy page.&#x20;

At the top of the page, select exchange, account and trading pair for your bot.

The left side of the screen contains a chart for the selected market. After setting lower and upper grid bounds, grid levels will appear on the chart.\
\
Use the configuration panel on the right to define how your grid bot should trade.

* Grid Lower Bound: lowest price where the bot will place orders.
* Grid Upper Bound: highest price where the bot will place orders.
* Order Size per Grid Level:  USD amount used for each grid level.
* Number of levels: number of grid levels created between lower and upper grid bounds.
* Level type: spacing method for grid levels.

&#x20;   a) Arithmetic: equal price spacing between levels (e.g., $100 apart)

&#x20;   b) Geometric: equal percentage spacing between levels (e.g., 1% apart). Better for volatile assets.

* Max orders per side: maximum orders opened at a time per side of grid.
* Orders Frequency: update frequency for refreshing orders.

Below the configuration fields, review calculated summary below the configuration fields. It shows whether selected grid settings fit the free margin available in the account. If settings match your strategy and account has enough margin, click `Deploy Bot`.

<figure><img src="/files/ZFb4lE8CNVIaGAGq3H51" alt=""><figcaption></figcaption></figure>

7. **Monitor your bot:** After deployment, the app opens the bot details page.

At the top of the page, you can see the bot name, current status, exchange, trading pair, version and deployment time. Status badges show the current bot state and help you see whether the bot is active and trading within the configured range.

The chart shows the selected market together with bot data. You can use it to review grid levels, open orders, filled orders and current position.

<figure><img src="/files/HMpKTFdfFfElEyBwWIeC" alt=""><figcaption></figcaption></figure>

Below the chart, you can find detailed sections for margin, grid configuration, position, open orders, analytics, fills, error logs and API usage. These sections help you monitor how the bot is performing and check whether it is trading as expected.

8. **Manage your bot:** Use the action buttons at the top of the bot details page to control the bot.

* Pause: temporarily stops the bot from managing orders.
* Resume: starts a paused bot again.
* Stop: stops the bot completely. When stopping, you can choose whether to keep position open or close them.
* Copy: opens the deploy page with the same configuration so you can create a similar bot.

<figure><img src="/files/3T68mUj89B1WGDW60ZoJ" alt=""><figcaption></figcaption></figure>

9. **Find your bots later:** Go to Dashboard page to view your own bots.

The dashboard shows active and historical bots, along with performance metrics such as total PNL, grid PNL, unrealized PNL, fees and volume. From there you can open any bot details or deploy a new bot.

<figure><img src="/files/MqPxyif9G8tFlTrVFD8s" alt=""><figcaption></figcaption></figure>

### Common issues

<details>

<summary>I cannot deploy a bot</summary>

Make sure your wallet is connected, you are signed in, your passphrase is unclocked, and at least one account exists for selected exchange.

</details>

<details>

<summary>Margin required is too high</summary>

Reduce order size, reduce number of grid levels, narrow grid range, or add more funds to selected account.

</details>

<details>

<summary>Bot is out of range</summary>

Current market price is outside configured grid bounds. Stop the bot and deploy a new one with updated bounds.

</details>

<details>

<summary>I forgot my passphrase</summary>

Go to Settings page and reset your passphrase. After resetting it, you will need to add your accounts again.

</details>


# DEX


# Swap API (kX)

### Overview

This API allows fetching quotes for token swaps and provides transaction data (`calldata`) for execution if the parameters `slippageTolerance`, `deadline`, and `recipient` are specified. This enables direct interaction with smart contracts.

This API is an aggregator of various providers and selects the best ones.

Currently, the following external providers are supported:

1. [OpenOcean](https://openocean.finance/)
2. [Fly (prev MagPie)](https://www.fly.trade/)
3. [OogaBooga](https://www.oogabooga.io/)
4. [Enso](https://docs.enso.build/home)
5. [Kyberswap](https://kyberswap.com/)
6. Kodiak

### Endpoint

**URL:**\
`https://backend.kodiak.finance/quote`

**Method:**\
`GET`

**Content Type:**\
`application/json`

### Query Parameters

<table><thead><tr><th width="215">Parameter</th><th width="108">Required</th><th>Description</th></tr></thead><tbody><tr><td>tokenInAddress</td><td>✅</td><td>Address of the input token for the swap. For native use token = <code>BERA</code> , <code>ETH</code>, or address(0) <code>0x000000000000000000000000000000000000000000</code></td></tr><tr><td>tokenInChainId</td><td>✅</td><td>Chain ID of the input token.</td></tr><tr><td>tokenOutAddress</td><td>✅</td><td>Address of the output token for the swap. For native use token = <code>BERA</code> , <code>ETH</code>, or address(0) <code>0x000000000000000000000000000000000000000000</code></td></tr><tr><td>tokenOutChainId</td><td>✅</td><td>Chain ID of the output token.</td></tr><tr><td>amount</td><td>✅</td><td>Amount of tokens to swap in human terms</td></tr><tr><td>type</td><td>✅</td><td>Type of swap: <code>exactIn</code> (fixed input amount) or <code>exactOut</code> (fixed output amount). <code>exactOut</code> is not supported by most providers, so this is not a recommended method and may show you poor quotes</td></tr><tr><td>refCode</td><td>❌</td><td>Your referral code (received from the Kodiak team)</td></tr><tr><td>referrerFeeBps</td><td>❌</td><td>Your share of fees.  Each referral code has a maximum threshold. Example: 100 = 1%</td></tr><tr><td>recipient</td><td>❌</td><td>The address of the recipient of the swapped tokens. Required for generating <code>calldata</code></td></tr><tr><td>slippageTolerance</td><td>❌</td><td>Allowed slippage percentage as an integer (e.g., 1 for 1%).</td></tr><tr><td>providers</td><td>❌</td><td><p>Case insensitive list of providers separated by commas.</p><p>Available options:  <code>Kodiak</code> , <code>OpenOcean</code>,<code>Magpie</code>,<code>OogaBooga</code>,<code>Enso,Kyberswap</code></p><p></p><p>For example: <code>kodiak,openocean,oogabooga</code></p></td></tr><tr><td>debug</td><td>❌</td><td>Receive additional information on all underlying providers quoted by setting to <code>true</code></td></tr></tbody></table>

### Example Request

{% code overflow="wrap" %}

```
GET https://backend.kodiak.finance/quote?tokenInAddress=BERA&tokenInChainId=80094&tokenOutAddress=0xFCBD14DC51f0A4d49d5E53C2E0950e0bC26d0Dce&tokenOutChainId=80094&amount=100000000000000000000&type=exactIn&recipient=0x5a1e747482F8773fe52Cca9951E956F456EFd0Bf&slippageTolerance=1
```

{% endcode %}

### Example response

```json
{
  "id": "b5c7416a",
  "amountDecimalsUSD": "225.6878516369463",
  "quoteDecimalsUSD": "225.4646160925649",
  "tokenInPriceUSD": "2.256878516369463",
  "tokenOutPriceUSD": "1",
  "priceImpact": "-0.09891340750609146",
  "methodParameters":
    {
      "calldata": "0xd2644d14000000000000000000000000696969696969696969696969696969696969696900000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000056bc75e2d63100000000000000000000000000000fcbd14dc51f0a4d49d5e53c2e0950e0bc26d0dce000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000c19a91d0924faf6130000000000000000000000005a1e747482f8773fe52cca9951e956f456efd0bf000000000000000000000000000000000000000000000000000000000000018000000000000000000000000000000000000000000000000c38f339c60126deb3000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000e301e48f77963d3f7dbd2a4796962bd7f3867fb4000000000000000000000000000000000000000000000000000000000000004000000000000000000000000000000000000000000000000000000000000003245ae401dc0000000000000000000000000000000000000000000000000000000068823556000000000000000000000000000000000000000000000000000000000000004000000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000040000000000000000000000000000000000000000000000000000000000000016000000000000000000000000000000000000000000000000000000000000000e404e45aaf0000000000000000000000006969696969696969696969696969696969696969000000000000000000000000fcbd14dc51f0a4d49d5e53c2e0950e0bc26d0dce0000000000000000000000000000000000000000000000000000000000000bb800000000000000000000000043dac637c4383f91b4368041e7a8687da3806cae00000000000000000000000000000000000000000000000340aad21b3b70000000000000000000000000000000000000000000000000000742bd178e640a419f0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000124b858183f0000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000008000000000000000000000000043dac637c4383f91b4368041e7a8687da3806cae0000000000000000000000000000000000000000000000022b1c8c1227a00000000000000000000000000000000000000000000000000004d73b54569a90d2a100000000000000000000000000000000000000000000000000000000000000426969696969696969696969696969696969696969000bb8549943e04f40284185054145c6e4e9568c1d3241000064fcbd14dc51f0a4d49d5e53c2e0950e0bc26d0dce0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",
      "value": "0x56bc75e2d63100000",
      "to": "0x43Dac637c4383f91B4368041E7A8687da3806Cae",
      "decodedArgs":
        [
          {
            "token": "0x6969696969696969696969696969696969696969",
            "wrap": true,
            "amount": "100000000000000000000",
          },
          {
            "token": "0xFCBD14DC51f0A4d49d5E53C2E0950e0bC26d0Dce",
            "unwrap": false,
            "minAmountOut": "223209969931639256595",
            "receiver": "0x5a1e747482F8773fe52Cca9951E956F456EFd0Bf",
          },
          {
            "router": "0xe301E48F77963D3F7DbD2a4796962Bd7f3867Fb4",
            "data": "0x5ae401dc0000000000000000000000000000000000000000000000000000000068823556000000000000000000000000000000000000000000000000000000000000004000000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000040000000000000000000000000000000000000000000000000000000000000016000000000000000000000000000000000000000000000000000000000000000e404e45aaf0000000000000000000000006969696969696969696969696969696969696969000000000000000000000000fcbd14dc51f0a4d49d5e53c2e0950e0bc26d0dce0000000000000000000000000000000000000000000000000000000000000bb800000000000000000000000043dac637c4383f91b4368041e7a8687da3806cae00000000000000000000000000000000000000000000000340aad21b3b70000000000000000000000000000000000000000000000000000742bd178e640a419f0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000124b858183f0000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000008000000000000000000000000043dac637c4383f91b4368041e7a8687da3806cae0000000000000000000000000000000000000000000000022b1c8c1227a00000000000000000000000000000000000000000000000000004d73b54569a90d2a100000000000000000000000000000000000000000000000000000000000000426969696969696969696969696969696969696969000bb8549943e04f40284185054145c6e4e9568c1d3241000064fcbd14dc51f0a4d49d5e53c2e0950e0bc26d0dce00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",
          },
          {
            "feeQuote": "225464616092564905651",
            "surplusFeeBps": "0",
            "refCode": "0",
            "referrerFeeBps": "0",
          },
        ],
    },
  "blockNumber": "8160103",
  "amount": "100000000000000000000",
  "amountDecimals": "100",
  "quote": "225464616092564905651",
  "quoteDecimals": "225.464616092564905651",
  "gasUseEstimate": "306000",
  "gasUseEstimateUSD": "6.920697896398132e-13",
  "gasPriceWei": "501981",
  "route":
    [
      [
        {
          "type": "v3-pool",
          "address": "0x1127f801Cb3ab7BDF8923272949AA7Dba94B5805",
          "tokenIn":
            {
              "chainId": 80094,
              "decimals": "18",
              "address": "0x6969696969696969696969696969696969696969",
              "symbol": "WBERA",
            },
          "tokenOut":
            {
              "chainId": 80094,
              "decimals": "18",
              "address": "0xFCBD14DC51f0A4d49d5E53C2E0950e0bC26d0Dce",
              "symbol": "HONEY",
            },
          "fee": "3000",
          "liquidity": "4493725237081532474168574",
          "sqrtRatioX96": "119153151978651141127607820981",
          "tickCurrent": "8161",
          "amountIn": "60000000000000000000",
          "amountOut": "135275596737333603789",
        },
      ],
      [
        {
          "type": "v3-pool",
          "address": "0x4866Dd95a3bC4eb40Dd1B659489e3410dAe3287f",
          "tokenIn":
            {
              "chainId": 80094,
              "decimals": "18",
              "address": "0x6969696969696969696969696969696969696969",
              "symbol": "WBERA",
            },
          "tokenOut":
            {
              "chainId": 80094,
              "decimals": "6",
              "address": "0x549943e04f40284185054145c6E4e9568C1D3241",
              "symbol": "USDC",
            },
          "fee": "3000",
          "liquidity": "718444640825350202",
          "sqrtRatioX96": "52691600443445573726226992633074205",
          "tickCurrent": "268166",
          "amountIn": "40000000000000000000",
        },
        {
          "type": "v3-pool",
          "address": "0xb16fFD445d3c785476F87017b79423eC9057406b",
          "tokenIn":
            {
              "chainId": 80094,
              "decimals": "6",
              "address": "0x549943e04f40284185054145c6E4e9568C1D3241",
              "symbol": "USDC",
            },
          "tokenOut":
            {
              "chainId": 80094,
              "decimals": "18",
              "address": "0xFCBD14DC51f0A4d49d5E53C2E0950e0bC26d0Dce",
              "symbol": "HONEY",
            },
          "fee": "100",
          "liquidity": "1521993826513687995740",
          "sqrtRatioX96": "79246574896778039496813381592642346",
          "tickCurrent": "276328",
          "amountOut": "90189019355231301862",
        },
      ],
    ],
  "routeString": "[V3] 60.00% = WBERA -- 0.3% [0x1127f801Cb3ab7BDF8923272949AA7Dba94B5805] --> HONEY, [V3] 40.00% = WBERA -- 0.3% [0x4866Dd95a3bC4eb40Dd1B659489e3410dAe3287f] --> USDC -- 0.01% [0xb16fFD445d3c785476F87017b79423eC9057406b] --> HONEY",
  "quoteId": "616f5",
  "provider": "Kodiak",
  "params":
    {
      "tokenInAddress": "BERA",
      "tokenInChainId": 80094,
      "tokenOutAddress": "0xFCBD14DC51f0A4d49d5E53C2E0950e0bC26d0Dce",
      "tokenOutChainId": 80094,
      "amount": "100000000000000000000",
      "type": "exactIn",
      "slippageTolerance": 1,
      "recipient": "0x5a1e747482F8773fe52Cca9951E956F456EFd0Bf",
    },
  "refFee": "0",
  "otherQuote":
    {
      "amountDecimalsUSD": "225.6878516369463",
      "quoteDecimalsUSD": "225.4646160925649",
      "tokenInPriceUSD": "2.256878516369463",
      "tokenOutPriceUSD": "1",
      "priceImpact": "-0.09891340750609146",
      "methodParameters":
        {
          "calldata": "0x5ae401dc0000000000000000000000000000000000000000000000000000000068823556000000000000000000000000000000000000000000000000000000000000004000000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000040000000000000000000000000000000000000000000000000000000000000016000000000000000000000000000000000000000000000000000000000000000e404e45aaf0000000000000000000000006969696969696969696969696969696969696969000000000000000000000000fcbd14dc51f0a4d49d5e53c2e0950e0bc26d0dce0000000000000000000000000000000000000000000000000000000000000bb80000000000000000000000005a1e747482f8773fe52cca9951e956f456efd0bf00000000000000000000000000000000000000000000000340aad21b3b70000000000000000000000000000000000000000000000000000742bd178e640a419f0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000124b858183f000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000800000000000000000000000005a1e747482f8773fe52cca9951e956f456efd0bf0000000000000000000000000000000000000000000000022b1c8c1227a00000000000000000000000000000000000000000000000000004d73b54569a90d2a100000000000000000000000000000000000000000000000000000000000000426969696969696969696969696969696969696969000bb8549943e04f40284185054145c6e4e9568c1d3241000064fcbd14dc51f0a4d49d5e53c2e0950e0bc26d0dce00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",
          "value": "0x00",
          "to": "0xe301E48F77963D3F7DbD2a4796962Bd7f3867Fb4",
        },
      "blockNumber": "8160103",
      "amount": "100000000000000000000",
      "amountDecimals": "100",
      "quote": "225464616092564905651",
      "quoteDecimals": "225.464616092564905651",
      "gasUseEstimate": "306000",
      "gasUseEstimateUSD": "6.920697896398132e-13",
      "gasPriceWei": "501981",
      "route":
        [
          [
            {
              "type": "v3-pool",
              "address": "0x1127f801Cb3ab7BDF8923272949AA7Dba94B5805",
              "tokenIn":
                {
                  "chainId": 80094,
                  "decimals": "18",
                  "address": "0x6969696969696969696969696969696969696969",
                  "symbol": "WBERA",
                },
              "tokenOut":
                {
                  "chainId": 80094,
                  "decimals": "18",
                  "address": "0xFCBD14DC51f0A4d49d5E53C2E0950e0bC26d0Dce",
                  "symbol": "HONEY",
                },
              "fee": "3000",
              "liquidity": "4493725237081532474168574",
              "sqrtRatioX96": "119153151978651141127607820981",
              "tickCurrent": "8161",
              "amountIn": "60000000000000000000",
              "amountOut": "135275596737333603789",
            },
          ],
          [
            {
              "type": "v3-pool",
              "address": "0x4866Dd95a3bC4eb40Dd1B659489e3410dAe3287f",
              "tokenIn":
                {
                  "chainId": 80094,
                  "decimals": "18",
                  "address": "0x6969696969696969696969696969696969696969",
                  "symbol": "WBERA",
                },
              "tokenOut":
                {
                  "chainId": 80094,
                  "decimals": "6",
                  "address": "0x549943e04f40284185054145c6E4e9568C1D3241",
                  "symbol": "USDC",
                },
              "fee": "3000",
              "liquidity": "718444640825350202",
              "sqrtRatioX96": "52691600443445573726226992633074205",
              "tickCurrent": "268166",
              "amountIn": "40000000000000000000",
            },
            {
              "type": "v3-pool",
              "address": "0xb16fFD445d3c785476F87017b79423eC9057406b",
              "tokenIn":
                {
                  "chainId": 80094,
                  "decimals": "6",
                  "address": "0x549943e04f40284185054145c6E4e9568C1D3241",
                  "symbol": "USDC",
                },
              "tokenOut":
                {
                  "chainId": 80094,
                  "decimals": "18",
                  "address": "0xFCBD14DC51f0A4d49d5E53C2E0950e0bC26d0Dce",
                  "symbol": "HONEY",
                },
              "fee": "100",
              "liquidity": "1521993826513687995740",
              "sqrtRatioX96": "79246574896778039496813381592642346",
              "tickCurrent": "276328",
              "amountOut": "90189019355231301862",
            },
          ],
        ],
      "routeString": "[V3] 60.00% = WBERA -- 0.3% [0x1127f801Cb3ab7BDF8923272949AA7Dba94B5805] --> HONEY, [V3] 40.00% = WBERA -- 0.3% [0x4866Dd95a3bC4eb40Dd1B659489e3410dAe3287f] --> USDC -- 0.01% [0xb16fFD445d3c785476F87017b79423eC9057406b] --> HONEY",
      "quoteId": "616f5",
      "provider": "Kodiak",
      "params":
        {
          "tokenInAddress": "BERA",
          "tokenInChainId": 80094,
          "tokenOutAddress": "0xFCBD14DC51f0A4d49d5E53C2E0950e0bC26d0Dce",
          "tokenOutChainId": 80094,
          "amount": "100000000000000000000",
          "type": "exactIn",
          "slippageTolerance": 1,
          "recipient": "0x5a1e747482F8773fe52Cca9951E956F456EFd0Bf",
        },
    },
  "expl":
    [
      {
        "provider": "Magpie",
        "status": "success",
        "executionTime": "459",
        "output": "225.505910668219988287",
        "priority": "1.00000000",
        "gas": "1977503",
      },
      {
        "provider": "Kodiak",
        "status": "success",
        "executionTime": "687",
        "output": "225.464616092564905651",
        "priority": "1.00020000",
        "gas": "306000",
      },
      {
        "provider": "OogaBooga",
        "status": "success",
        "executionTime": "732",
        "output": "225.47857060392927232",
        "priority": "1.00000000",
        "gas": "1665117",
      },
      {
        "provider": "OpenOcean",
        "status": "success",
        "executionTime": "1110",
        "output": "225.480574764869379629",
        "priority": "0.99950000",
        "gas": "561020",
      },
      {
        "provider": "Enso",
        "status": "success",
        "executionTime": "1222",
        "output": "225.47857060392926899",
        "priority": "0.99900000",
        "gas": "1141033",
      },
    ],
}

```

{% hint style="info" %}
Please note the address in `methodParameters.to`, which may change depending on the quote (mainly to use legacy Kodiak router for tokens unsupported by kX). You must approve it yourself.
{% endhint %}

{% code overflow="wrap" %}

```bash
 cast send 0x43Dac637c4383f91B4368041E7A8687da3806Cae "0xd2644d14000000000000000000000000696969696969696969696969696969696969696900000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000056bc75e2d63100000000000000000000000000000fcbd14dc51f0a4d49d5e53c2e0950e0bc26d0dce000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000c19a91d0924faf6130000000000000000000000005a1e747482f8773fe52cca9951e956f456efd0bf000000000000000000000000000000000000000000000000000000000000018000000000000000000000000000000000000000000000000c38f339c60126deb3000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000e301e48f77963d3f7dbd2a4796962bd7f3867fb4000000000000000000000000000000000000000000000000000000000000004000000000000000000000000000000000000000000000000000000000000003245ae401dc0000000000000000000000000000000000000000000000000000000068823556000000000000000000000000000000000000000000000000000000000000004000000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000040000000000000000000000000000000000000000000000000000000000000016000000000000000000000000000000000000000000000000000000000000000e404e45aaf0000000000000000000000006969696969696969696969696969696969696969000000000000000000000000fcbd14dc51f0a4d49d5e53c2e0950e0bc26d0dce0000000000000000000000000000000000000000000000000000000000000bb800000000000000000000000043dac637c4383f91b4368041e7a8687da3806cae00000000000000000000000000000000000000000000000340aad21b3b70000000000000000000000000000000000000000000000000000742bd178e640a419f0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000124b858183f0000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000008000000000000000000000000043dac637c4383f91b4368041e7a8687da3806cae0000000000000000000000000000000000000000000000022b1c8c1227a00000000000000000000000000000000000000000000000000004d73b54569a90d2a100000000000000000000000000000000000000000000000000000000000000426969696969696969696969696969696969696969000bb8549943e04f40284185054145c6e4e9568c1d3241000064fcbd14dc51f0a4d49d5e53c2e0950e0bc26d0dce0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
```

{% endcode %}


# Swap API (Kodiak Router)

{% hint style="warning" %}
This is for the legacy Kodiak Router (SwapRouter02).  For most users, Swap API (kX) is the better option.  Kodiak Router is primarily used by automated bots that want low-latency, high quality API.&#x20;
{% endhint %}

### Overview

This API allows fetching quotes for token swaps and provides transaction data (`calldata`) for execution if the parameters `slippageTolerance`, `deadline`, and `recipient` are specified. This enables direct interaction with smart contracts.

{% hint style="info" %}
Make sure to use the api.kodiak.finance endpoint below - no other legacy endpoints.
{% endhint %}

**URL:**

`https://api.kodiak.finance/quote`

**Method:**\
`GET`

**Content Type:**\
`application/json`

### Query Parameters

<table><thead><tr><th width="239">Parameter</th><th width="104">Required</th><th>Description</th></tr></thead><tbody><tr><td>protocols</td><td>✅</td><td>The protocols used for the swap. Possible values: <code>v2</code>, <code>v3</code>, <code>mixed</code>.</td></tr><tr><td>tokenInAddress</td><td>✅</td><td>Address of the input token for the swap.</td></tr><tr><td>tokenInChainId</td><td>✅</td><td>Chain ID of the input token.</td></tr><tr><td>tokenOutAddress</td><td>✅</td><td>Address of the output token for the swap.</td></tr><tr><td>tokenOutChainId</td><td>✅</td><td>Chain ID of the output token.</td></tr><tr><td>amount</td><td>✅</td><td>Amount of tokens to swap in humman terms</td></tr><tr><td>type</td><td>✅</td><td>Type of swap: <code>exactIn</code> (fixed input amount) or <code>exactOut</code> (fixed output amount).</td></tr><tr><td>recipient</td><td>❌</td><td>The address of the recipient of the swapped tokens. Required for generating <code>calldata</code>.</td></tr><tr><td>deadline</td><td>❌</td><td>Time in seconds until the transaction expires.</td></tr><tr><td>slippageTolerance</td><td>❌</td><td>Allowed slippage percentage as an integer (e.g., 1 for 1%).</td></tr></tbody></table>

### Example Request

{% code overflow="wrap" %}

```
GET https://api.kodiak.finance/quote?protocols=v2,v3,mixed&tokenInAddress=0x7507c1dc16935B82698e4C63f2746A2fCf994dF8&tokenInChainId=80084&tokenOutAddress=0x1740F679325ef3686B2f574e392007A92e4BeD41&tokenOutChainId=80084&amount=40862354775778842528071&type=exactIn&recipient=0xA54e745BFf14816Ec6D323d894E7861b6Ef3F2aE&deadline=1000&slippageTolerance=1
```

{% endcode %}

### Example response

```json
{
  "blockNumber": "7067071",
  "amount": "1000000000000000000000",
  "amountDecimals": "1000",
  "quote": "55837913683147237796",
  "quoteDecimals": "55.837913683147237796",
  "quoteGasAdjusted": "55840267836750092796",
  "quoteGasAdjustedDecimals": "55.840267836750092796",
  "gasUseEstimateQuote": "2354153602855000",
  "gasUseEstimateQuoteDecimals": "0.002354153602855",
  "gasUseEstimate": "443000",
  "gasUseEstimateUSD": "0.041844",
  "gasPriceWei": "5314116485",
  "route": [
    [
      {
        "type": "v3-pool",
        "address": "0x8a960A6e5f224D0a88BaD10463bDAD161b68C144",
        "tokenIn": {
          "chainId": 80084,
          "decimals": "18",
          "address": "0x7507c1dc16935B82698e4C63f2746A2fCf994dF8",
          "symbol": "WBERA"
        },
        "tokenOut": {
          "chainId": 80084,
          "decimals": "18",
          "address": "0x0E4aaF1351de4c0264C5c7056Ef3777b41BD8e03",
          "symbol": "HONEY"
        },
        "fee": "3000",
        "liquidity": "2436507486332335185500775",
        "sqrtRatioX96": "18720675063184587718540484748",
        "tickCurrent": "-28856",
        "amountIn": "53049022487390937786",
        "amountOut": "950000000000000000000"
      }
    ],
    [
      {
        "type": "v3-pool",
        "address": "0xe49E094fe1679624C3981EB821fA6aB46c99E18E",
        "tokenIn": {
          "chainId": 80084,
          "decimals": "18",
          "address": "0x7507c1dc16935B82698e4C63f2746A2fCf994dF8",
          "symbol": "WBERA"
        },
        "tokenOut": {
          "chainId": 80084,
          "decimals": "18",
          "address": "0x0E4aaF1351de4c0264C5c7056Ef3777b41BD8e03",
          "symbol": "HONEY"
        },
        "fee": "500",
        "liquidity": "1785423513716355823391",
        "sqrtRatioX96": "18718672899386852222700719036",
        "tickCurrent": "-28858",
        "amountIn": "2788891195756300010",
        "amountOut": "50000000000000000000"
      }
    ]
  ],
  "routeString": "[V3] 95.00% = WBERA -- 0.3% [0x8a960A6e5f224D0a88BaD10463bDAD161b68C144] --\u003E HONEY, [V3] 5.00% = WBERA -- 0.05% [0xe49E094fe1679624C3981EB821fA6aB46c99E18E] --\u003E HONEY",
  "quoteId": "a6d10"
}
```

### Execution of swap

If you specified the parameters a, b, c then the answer will return the calldata property. To perform this swap you just need to use our `SwapRouter02`

`SwapRouter02` address: `0xe301E48F77963D3F7DbD2a4796962Bd7f3867Fb4`

{% hint style="warning" %}
Make sure you do the approve before the action in the example
{% endhint %}

{% code overflow="wrap" %}

```bash
 cast send 0x496e305C03909ae382974cAcA4c580E1BF32afBE "0x5ae401dc0000000000000000000000000000000000000000000000000000000067479f3a00000000000000000000000000000000000000000000000000000000000000400000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000e404e45aaf0000000000000000000000007507c1dc16935b82698e4c63f2746a2fcf994df80000000000000000000000001740f679325ef3686b2f574e392007a92e4bed410000000000000000000000000000000000000000000000000000000000000bb8000000000000000000000000a54e745bff14816ec6d323d894e7861b6ef3f2ae0000000000000000000000000000000000000000000008a72716c2895c8a4947000000000000000000000000000000000000000000005f726aca12c4ec97acd7000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
```

{% endcode %}


# Pricing with Subgraph

{% hint style="danger" %}
For current prices, subgraph pricing is deprecated. Please use [api pricing](/developers/backend-api)
{% endhint %}

As of May 2026, Kodiak provides a single combined subgraph endpoint for both V2, V3, and Kodiak Islands.  The V2 endpoint follows similar pattern to Uniswap V2 subgraph, and V3 endpoint follows similar pattern to Uniswap V3 subgraph.&#x20;

#### Endpoint:

```
https://api.subgraph.ormilabs.com/api/public/d7eed6cc-ad4a-4862-8017-89893c4095d3/subgraphs/kodiak-v3/latest/gn
```

1. **Understand the Basics of Subgraphs**:
   * Subgraphs index blockchain data and expose it through GraphQL endpoints.
   * Each subgraph has entities (e.g., `token`, `pool`, `transaction`) that define the structure of the data you can query.
2. **Read the Subgraph Documentation**:\
   Learn how subgraph works\
   [The Graph Doucmentation](https://thegraph.com/docs/en/querying/querying-the-graph/)
3. **Set Up a GraphQL Client**:
   * Use tools like Postman, Insomnia, or GraphQL playgrounds to send queries.
   * In your application, you can use libraries like `graphql-request` or Apollo Client.
4. **Know the Key Entities**:
   * **`token`**: Represents individual tokens, their metadata, and derived pricing.
   * **`bundle`**: Contains aggregate data like the current price of ETH in USD.

#### Query examples

1. Fetching a Specific Token’s Price in ETH and USD<br>

   ```graphql
   {
     token(id: "TOKEN_ADDRESS") {
       id
       symbol
       name
       derivedETH
     }
     bundle(id: "1") {
       ethPriceUSD
     }
   }
   ```

   * **Replace `TOKEN_ADDRESS`** with the contract address of the token you’re querying.
   * Use thie formula to calculate USD price:&#x20;
     * `Token Price (USD) = derivedETH * ethPrice`
2. Listing All Tokens with Derived Prices

   ```graphql
   {
     tokens(first: 10) {
       id
       symbol
       name
       derivedETH
     }
     bundle(id: "1") {
       ethPrice
     }
   }
   ```

   \
   **Example response:**

   ```graphql
   {
     "data": {
       "tokens": [
         { "id": "0x...123", "symbol": "USDT", "name": "Tether", "derivedETH": "0.0005" },
         { "id": "0x...456", "symbol": "USDC", "name": "USD Coin", "derivedETH": "0.0005" }
       ],
       "bundle": {
         "ethPrice": "2000"
       }
     }
   }
   ```

\ <br>


# Panda


# Technical Integration Guide

## Protocol Overview

The Panda factory Protocol implements a novel token launch mechanism using bonding curves with automatic liquidity provision. This guide will help you understand and integrate with the protocol's smart contracts.

#### Core Architecture

The protocol is built on three primary components that work together to provide token launch and trading functionality:

**1. PandaFactory**

The factory contract is the main entry point for deploying new tokens and pools. It:

* Manages protocol configurations
* Controls implementation versions
* Handles deployment permissions
* Manages protocol fees and incentives

> ⚠️ **Important**
>
> Always check if your implementation contract is approved by the factory using `isImplementationAllowed()` before attempting deployment.

**2. PandaToken**

Extends standard ERC20 functionality with bonding curve mechanics. Key features:

* ERC20 compliance with permit functionality
* Integrated bonding curve trading
* Automatic graduation to DEX trading
* Transfer restrictions pre-graduation

> 💡 **Note on Transfers**
>
> Transfers to the DEX pair address are blocked until graduation to maintain price curve integrity.

**3. PandaPool**

Implements the core bonding curve mechanics:

* Single-sided liquidity provisioning
* Price discovery mechanism
* Trading functionality
* Graduation handling

#### Protocol Mechanics

**Bonding Curve Mechanism**

The protocol uses a square root price model similar to Kodiak V3, but simplified for single-sided liquidity provision. The curve is defined by:

1. **Price Range**
   * `sqrtPa`: Lower bound of price range
   * `sqrtPb`: Upper bound of price range
   * Current price moves between these bounds

<img src="/files/8SQ8OrdR3eEyd0gC0MDW" alt="" class="gitbook-drawing">

2. **Token Distribution**
   * `tokensInPool`: Tokens available for bonding curve
   * `tokensForLp`: Tokens reserved for DEX liquidity
   * Distribution must satisfy pool share constraints

> ℹ️ **Mathematical Model**
>
> The price calculation follows: P = (sqrtP)² where sqrtP ranges from sqrtPa to sqrtPb Liquidity (L) remains constant: L = tokensInPool \* (sqrtPa \* sqrtPb) / (sqrtPb - sqrtPa)

**Graduation Process**

Graduation is the automatic transition from bonding curve to DEX trading. This occurs when:

1. Remaining tokens in pool ≤ 0.25% of initial pool tokens
2. Final price is used to set DEX pool ratio
3. Remaining tokens plus LP tokens are added to DEX

> ⚠️ **Critical**
>
> After graduation:
>
> * Trading switches to DEX pair
> * Bonding curve functions are disabled
> * Transfer restrictions are lifted

### Getting Started

#### Prerequisites

Before integrating with the protocol, ensure you have:

1. **Development Environment**
   * Solidity compiler v0.8.19
   * Web3 provider
   * Access to Berachain RPC
2. **Required Permissions**
   * Access to approved implementation contracts
   * Sufficient base tokens for deployment
   * Required approvals for trading
3. **Base Token Requirements**

   ```solidity
   interface IERC20 {
       function approve(address spender, uint256 amount) external returns (bool);
       function transfer(address to, uint256 amount) external returns (bool);
       function transferFrom(address from, address to, uint256 amount) external returns (bool);
   }
   ```

   Base tokens must:

   * Be ERC20 compliant
   * Return boolean for transfers/approvals
   * Have sufficient decimals (18 recommended)

> ⚠️ **Base Token Warning**
>
> Non-standard ERC20 tokens (e.g., fee-on-transfer, rebasing) are not supported and may cause unexpected behavior.

#### Network Requirements

| Requirement | Description               |
| ----------- | ------------------------- |
| Gas Limit   | Standard EVM operations   |
| Chain ID    | Berachain Mainnet/Testnet |
| RPC Support | Standard Web3 endpoints   |

### Key Concepts

#### Price Configuration

The protocol enforces strict bounds on price ranges to ensure proper functioning.

**Price Range Requirements**

```solidity
MIN_SQRTP_MULTIPLE = 11_000    // 1.1x minimum range
MAX_SQRTP_MULTIPLE = 100_000   // 10x maximum range
```

These translate to:

* Minimum price range: 1.21x (1.1² x)
* Maximum price range: 100x (10² x)

> 💡 **Price Range Tip**
>
> Choose price ranges that make sense for your token's economics. Wider ranges allow more price discovery but require more capital to complete.

**Example Price Calculations**

```javascript
// Convert display price to sqrt price
function displayToSqrtPrice(displayPrice) {
    return Math.sqrt(displayPrice * 1e18);
}

// Example price range setup
const minPrice = 1;   // 1 BASE per TOKEN
const maxPrice = 10;  // 10 BASE per TOKEN

const sqrtPa = displayToSqrtPrice(minPrice);
const sqrtPb = displayToSqrtPrice(maxPrice);

// Verify range is valid
const multiple = (sqrtPb * 10000) / sqrtPa;
if (multiple < MIN_SQRTP_MULTIPLE || multiple > MAX_SQRTP_MULTIPLE) {
    throw new Error('Invalid price range');
}
```

#### Token Distribution Parameters

The protocol enforces constraints on token distribution to ensure proper liquidity.

**Pool Share Requirements**

```solidity
MIN_TOKENSINPOOL_SHARE = 5000  // 50% minimum in pool
MAX_TOKENSINPOOL_SHARE = 9000  // 90% maximum in pool
```

Distribution visualization:

```
Total Supply (1B tokens)
|-------------------------------------------|
|    Pool Tokens     |     LP Tokens        |
|    (50-90%)       |     (10-50%)         |
|-------------------------------------------|
```

> ℹ️ **Pool Share Information**
>
> * Pool tokens: Available for bonding curve trading
> * LP tokens: Reserved for DEX liquidity after graduation
> * Ratios affect final DEX liquidity depth

#### Fee Structure

The protocol implements a comprehensive fee structure:

```solidity
struct PandaFees {
    uint16 buyFee;           // Fee on buy operations
    uint16 sellFee;          // Fee on sell operations
    uint16 graduationFee;    // Fee at graduation
    uint16 deployerFeeShare; // Share of fees to deployer
}
```

Fee considerations:

1. **Buy/Sell Fees**
   * Taken in base token
   * Calculated on input amount
   * Sent to treasury
2. **Graduation Fee**
   * Taken from final base token balance
   * Split between treasury and deployer
   * Affects final DEX liquidity

> 💡 **Fee Calculation Tip**
>
> When calculating required inputs, account for fees:
>
> ```javascript
> const totalInput = desiredAmount * (1 + buyFee / 10000);
> ```

### Integration Guide

#### 1. Token Deployment

Deploying a new token requires careful preparation and parameter selection.

**Pre-Deployment Checklist**

* [ ] Verify implementation is allowed
* [ ] Calculate valid price range
* [ ] Determine token distribution
* [ ] Prepare token metadata
* [ ] Check base token configuration

**Deployment Process**

1. **Calculate Parameters**

```javascript
const params = {
    baseToken: baseTokenAddress,
    sqrtPa: calculateSqrtPrice(minPrice),
    sqrtPb: calculateSqrtPrice(maxPrice),
    vestingPeriod: 0  // No vesting for standard deployment
};
```

2. **Deploy Token**

```javascript
// For ERC20 base tokens
const tx = await factory.deployPandaToken(
    implementation,
    params,
    "Token Name",
    "SYMBOL",
    deployerSupplyBps  // Optional deployer allocation
);

// For native BERA
const tx = await factory.deployPandaTokenWithBera(
    implementation,
    params,
    "Token Name",
    "SYMBOL",
    deployerSupplyBps,
    { value: beraAmount }
);
```

> ⚠️ **Deployment Warning**
>
> * Verify all parameters before deployment
> * Deployment cannot be reversed
> * Parameters cannot be changed after deployment

#### 2. Trading Integration

**Pre-Trading Requirements**

1. Base token approvals
2. Minimum trade size check
3. Price impact calculations
4. Slippage protection

**Trading Functions**

1. **Buy Tokens**

```javascript
// Calculate expected output
const [amountOut, fee, sqrtP] = await pandaToken.getAmountOutBuy(amountIn);

// Apply slippage tolerance
const minOut = amountOut * (1 - slippageTolerance);

// Execute trade
const tx = await pandaToken.buyTokens(amountIn, minOut, recipient);
```

2. **Sell Tokens**

```javascript
// Calculate expected output
const [amountOut, fee, sqrtP] = await pandaToken.getAmountOutSell(amountIn);

// Apply slippage tolerance
const minOut = amountOut * (1 - slippageTolerance);

// Execute trade
const tx = await pandaToken.sellTokens(amountIn, minOut, recipient);
```

> 💡 **Trading Tips**
>
> * Always use getAmountOut functions to estimate outputs
> * Include reasonable slippage tolerance
> * Monitor price impact on larger trades

**Price Monitoring**

```javascript
// Get current price
const currentPrice = await pandaToken.getCurrentPrice();

// Get remaining tokens
const remaining = await pandaToken.remainingTokensInPool();

// Check graduation proximity
const graduationThreshold = remaining * 25 / 10000;  // 0.25%
```

#### 3. Graduation Handling

**Graduation Detection**

1. **Event Monitoring**

```javascript
pandaToken.on('LiquidityMoved', (amountPanda, amountBase) => {
    // Handle graduation
    switchToDexTrading();
});
```

2. **State Checking**

```javascript
const graduated = await pandaToken.graduated();
if (graduated) {
    const dexPair = await pandaToken.dexPair();
    // Update trading logic
}
```

**Post-Graduation Integration**

After graduation:

1. Switch to DEX pair for trading
2. Update price feeds
3. Remove pre-graduation restrictions

> ℹ️ **Graduation Information**
>
> Graduation is permanent and irreversible. Always check graduated() state before operations.

### Error Handling

#### Common Errors

| Error                        | Description                | Solution                      |
| ---------------------------- | -------------------------- | ----------------------------- |
| `INVALID_IMPLEMENTATION`     | Implementation not allowed | Verify implementation address |
| `PRICES_TOO_CLOSE`           | Invalid price range        | Increase price range          |
| `PRICES_TOO_FAR`             | Invalid price range        | Decrease price range          |
| `INSUFFICIENT_OUTPUT_AMOUNT` | Slippage check failed      | Increase slippage tolerance   |
| `TRADE_BELOW_MIN`            | Trade size too small       | Increase trade size           |
| `GRADUATED`                  | Pool already graduated     | Switch to DEX trading         |

#### Error Recovery Strategies

1. **Deployment Failures**
   * Verify all parameters
   * Check implementation status
   * Ensure base token configuration
2. **Trading Failures**
   * Refresh price data
   * Adjust slippage tolerance
   * Check trade size requirements
3. **Graduation Issues**
   * Monitor graduation events
   * Handle state transitions
   * Update integration logic

> ⚠️ **Error Handling Best Practices**
>
> * Always wrap interactions in try-catch
> * Implement proper error recovery
> * Monitor transaction status
> * Handle reverted transactions

### Security Considerations

#### Important Checks

1. **Pre-deployment**
   * Implementation verification
   * Parameter validation
   * Base token compatibility
2. **Trading**
   * Slippage protection
   * Price impact monitoring
   * Balance checks
3. **Post-graduation**
   * State verification
   * DEX pair validation
   * Trading updates

> ⚠️ **Security Warnings**
>
> * Never expose private keys
> * Validate all input parameters
> * Monitor for unexpected state changes
> * Implement proper access controls


# Subgraph

### Overview

The Panda Protocol subgraph indexes and provides structured access to protocol data through a GraphQL API. This documentation will help you integrate with our data layer effectively.

### Understanding the Subgraph

The subgraph serves as the backbone for accessing Panda Protocol's on-chain data. It processes and indexes:

* Pool deployments and configurations
* Trading activities and price movements
* Liquidity positions and migrations
* Token holder balances and distributions

<img src="/files/jAMX8koVbHlJYJBBqdWn" alt="" class="gitbook-drawing">

### When to Use the Subgraph

#### Perfect For

* Building trading interfaces requiring real-time pool data
* Creating analytics dashboards with historical data
* Tracking pool performance and market metrics
* Monitoring token holder distributions

### Accessing the Subgraph

```typescript
https://api.goldsky.com/api/public/project_clpx84oel0al201r78jsl0r3i/subgraphs/kodiak-panda-berachain-mainnet/latest/gn
```

### Quick Example

```graphql
# Fetch active pools with their latest metrics
{
  pandaPools(
    where: { 
      graduated: false,
      volumeUSD_gt: "0"
    }
    orderBy: volumeUSD
    orderDirection: desc
  ) {
    id
    price
    volumeUSD
    swapsCount
  }
}
```

### Data Structure

The subgraph maintains several core entities:

* `PandaPool`: Pool state and metrics
* `Token`: Token details and statistics
* `Swap`: Trading activity records
* `Holder`: Token holder information

For detailed entity definitions, see our Entities documentation.

### Development Guides

1. Entity Relationships
   * Understanding data models
   * Entity relationships
   * Field references
2. Query Examples
   * Common queries
   * Filtering and sorting
   * Pagination patterns
3. Advanced Usage
   * Performance optimization
   * Error handling
   * Edge cases

### Next Steps

[→ Continue to Entity Documentation](/developers/panda/subgraph/entity-reference)


# Entity Reference

### Overview

The Panda Protocol subgraph defines several core entities that model the protocol's data. Each entity represents a specific aspect of the protocol's state and behavior.

### Core Entities

#### PandaPool

Represents an individual Panda liquidity pool. Each pool manages a pair of tokens and tracks trading activity.

```graphql
type PandaPool @entity {
    id: ID!                     # Pool contract address
    baseToken: Token!           # The base currency token
    pandaToken: Token!          # The Panda token being traded
    price: BigDecimal!         # Current token price
    volumeUSD: BigDecimal!     # Total USD volume
    marketCapBase: BigDecimal! # Market cap in base currency terms
    marketCapUSD: BigDecimal!  # Market cap in USD termes
    swapsCount: BigInt!        # Total number of swaps
    lastSwapTimestamp: BigInt! # Last swap timestamp
    graduated: Boolean!        # Graduation status
    raised: BigDecimal!       # amount of tokens raised
    tokensInPool: BigDecimal! # Total token in the pool
    pandaReserve: BigDecimal! # Panda token reserve
    baseReserve: BigDecimal!  # Base token reserve
    startPrice: BigDecimal!   # Initial token price
}
```

**Common Queries**

```graphql
# Get active pools with high volume
{
  pandaPools(
    where: {
      graduated: false,
      volumeUSD_gt: "100000"
    },
    orderBy: volumeUSD,
    orderDirection: desc
  ) {
    id
    price
    volumeUSD
    swapsCount
  }
}

# Get pool reserves
{
  pandaPool(id: "0x...") {
    pandaReserve
    baseReserve
    tokensInPool
  }
}
```

#### Token

Tracks both Panda and base tokens in the protocol.

```graphql
type Token @entity {
    id: ID!                    # Token contract address
    name: String!             # Token name
    symbol: String!           # Token symbol
    decimals: BigInt!        # Token decimals
    totalSupply: BigDecimal! # Total supply
    isPandaToken: Boolean!   # Token type identifier
    pools: [PandaPool!]!     # Associated pools
    holders: [Holder!]!      # Token holders
    holdersCount: BigInt!    # Number of holders
    lastSwapTimestamp: BigInt! # Last swap timestamp
    createdAtTimestamp: BigInt! # Creation timestamp
}
```

**Example Queries**

```graphql
# Get token details with holder metrics
{
  token(id: "0x...") {
    symbol
    totalSupply
    holdersCount
    holders(first: 10, orderBy: balance, orderDirection: desc) {
      balance
      sharePercentage
    }
  }
}
```

#### PandaPoolSwap

Records individual swap transactions within pools.

```graphql
type PandaPoolSwap @entity(immutable: true) {
    id: ID!                    # Unique swap identifier
    pool: PandaPool!          # Reference to pool
    timestamp: BigInt!        # Swap timestamp
    amountPandaIn: BigDecimal! # Panda tokens in
    amountPandaOut: BigDecimal! # Panda tokens out
    amountBaseIn: BigDecimal!  # Base tokens in
    amountBaseOut: BigDecimal! # Base tokens out
    from: Bytes!              # Sender address
    to: Bytes!                # Recipient address
    tx: String!               # Transaction hash
    origin: String!           # Transaction origin
    volumeUSD: BigDecimal!    # Volume in USD
    averagePrice: BigDecimal! # Average execution price
}
```

**Querying Swaps**

```graphql
# Get recent swaps for a pool
{
  pandaPoolSwaps(
    where: { pool: "0x..." }
    orderBy: timestamp
    orderDirection: desc
    first: 100
  ) {
    timestamp
    amountPandaIn
    amountPandaOut
    volumeUSD
    averagePrice
  }
}
```

#### PriceSnapshot

Time-based price aggregation for historical analysis.

```graphql
type PriceSnapshot @entity {
    id: ID!
    timestamp: BigInt!
    open: BigDecimal!
    close: BigDecimal!
    high: BigDecimal!
    low: BigDecimal!
    volume: BigDecimal!
    pool: PandaPool!
    timeframe: PriceSnapshotTimeframe!
}

enum PriceSnapshotTimeframe {
    SECOND10
    MINUTE
    MINUTE5
    MINUTE15
    HOUR
    HOUR3
    DAY
}
```

**Historical Data Queries**

```graphql
# Get hourly price data
{
  priceSnapshots(
    where: {
      pool: "0x...",
      timeframe: HOUR
    }
    orderBy: timestamp
    orderDirection: desc
    first: 24
  ) {
    timestamp
    open
    high
    low
    close
    volume
  }
}
```

### Entity Relationships

#### Primary Relationships

<img src="/files/0PKfrLCPAofFH0HZImTK" alt="" class="gitbook-drawing">

#### Key Points

* Each `PandaPool` has exactly two `Token` entities (base and Panda)
* `PriceSnapshot` entities are created for specific timeframes
* `Holder` entities track token ownership
* `PandaPoolSwap` entities are immutable records

### Best Practices

#### Querying Efficiently

1. **Use Specific Fields**

```graphql
# Good
{
  pandaPools {
    id
    price
  }
}

# Avoid
{
  pandaPools {
    ...allFields # Fetching unnecessary data
  }
}
```

2. **Pagination**

```graphql
# Use skip/first for large datasets
{
  pandaPoolSwaps(
    skip: 100,
    first: 100,
    orderBy: timestamp,
    orderDirection: desc
  ) {
    id
    timestamp
  }
}
```

3. **Field Selection**

* Request only needed fields
* Use fragments for common field sets
* Consider query complexity

#### Error Handling

1. **Entity Not Found**

```graphql
# Handle null responses
{
  pandaPool(id: "0x...") {
    id # Will be null if not found
    price
  }
}
```

2. **Invalid Queries**

* Validate entity existence
* Check field value ranges
* Handle pagination edges

### Next Steps

Continue to:

* Queries Documentation for advanced query patterns
* Advanced Usage for optimization techniques

### Support

Need help with entities?

* Check Known Issues
* Join our [Developer Discord](https://discord.gg/vhZmNFNbCZ)


# Query Guide

### Introduction

This guide covers common query patterns, optimization techniques, and best practices for retrieving data from the Panda Protocol subgraph.

### Basic Queries

#### Pool Data

```graphql
# Get basic pool information
{
  pandaPool(id: "0x123...") {
    id
    price
    volumeUSD
    swapsCount
    graduated
  }
}

# List active pools with high volume
{
  pandaPools(
    where: {
      volumeUSD_gt: "100000",
      graduated: false
    }
    orderBy: volumeUSD
    orderDirection: desc
    first: 10
  ) {
    id
    price
    volumeUSD
  }
}
```

#### Trading Activity

```graphql
# Recent swaps for a pool
{
  pandaPoolSwaps(
    where: { pool: "0x123..." }
    orderBy: timestamp
    orderDirection: desc
    first: 100
  ) {
    timestamp
    amountPandaIn
    amountPandaOut
    volumeUSD
    averagePrice
  }
}
```

### Advanced Queries

#### Time-Based Queries

```graphql
# Get pools with recent activity
{
  pandaPools(
    where: {
      lastSwapTimestamp_gt: "1634567890"
    }
  ) {
    id
    price
    lastSwapTimestamp
  }
}

# Get hourly price data
{
  priceSnapshots(
    where: {
      pool: "0x123...",
      timeframe: HOUR,
      timestamp_gt: "1634567890"
    }
    orderBy: timestamp
    orderDirection: asc
  ) {
    timestamp
    open
    high
    low
    close
  }
}
```

#### Market Analysis

```graphql
# Top pools by volume
{
  pandaPools(
    orderBy: volumeUSD
    orderDirection: desc
    first: 5
  ) {
    id
    volumeUSD
    marketCapUSD
    swapsCount
  }
}

# Token holder distribution
{
  token(id: "0x123...") {
    symbol
    holdersCount
    holders(
      orderBy: balance
      orderDirection: desc
      first: 10
    ) {
      address
      balance
      sharePercentage
    }
  }
}
```

### Query Optimization

#### Pagination

```graphql
# Using skip/first for pagination
{
  pandaPoolSwaps(
    skip: 100    # Skip first 100 results
    first: 50    # Get next 50 results
    orderBy: timestamp
    orderDirection: desc
  ) {
    id
    timestamp
  }
}
```

#### Field Selection

```graphql
# Good: Specific fields
{
  pandaPools {
    id
    price
    volumeUSD
  }
}

# Bad: Overfetching
{
  pandaPools {
    id
    price
    volumeUSD
    swapsCount
    lastSwapTimestamp
    graduated
    raised
    # ... unnecessary fields
  }
}
```

#### Using Fragments

```graphql
# Define reusable fragments
fragment PoolBasics on PandaPool {
  id
  price
  volumeUSD
  swapsCount
}

# Use in queries
{
  activePools: pandaPools(
    where: { graduated: false }
  ) {
    ...PoolBasics
  }
  
  graduatedPools: pandaPools(
    where: { graduated: true }
  ) {
    ...PoolBasics
  }
}
```

### Common Use Cases

#### Trading Interface Data

```graphql
# Get pool trading data
{
  pandaPool(id: "0x123...") {
    price
    pandaReserve
    baseReserve
    swapsCount
    lastSwapTimestamp
    recentSwaps: swaps(
      first: 50
      orderBy: timestamp
      orderDirection: desc
    ) {
      timestamp
      amountPandaIn
      amountPandaOut
      averagePrice
    }
  }
}
```

#### Analytics Dashboard

```graphql
# Get market overview
{
  statistics(id: "global") {
    totalVolumeUSD
    totalMarketCapUSD
    totalPandaPoolsCount
    totalGraduatedPandaPoolsCount
  }
  
  topPools: pandaPools(
    first: 5
    orderBy: volumeUSD
    orderDirection: desc
  ) {
    id
    volumeUSD
    marketCapUSD
    swapsCount
  }
}
```

### Real-time Data Updates

#### Polling Strategy

```graphql
# Efficient polling query
{
  pandaPool(id: "0x123...") {
    price
    lastSwapTimestamp
    pandaReserve
    baseReserve
  }
}
```

#### Using Block Numbers

```graphql
# Query at specific block
{
  pandaPool(id: "0x123...", block: { number: 15000000 }) {
    price
    volumeUSD
  }
}
```

### Error Handling

#### Null Checks

```graphql
# Handle potential null values
{
  pandaPool(id: "0x123...") {
    id # Will be null if pool doesn't exist
    price
    # Always check optional relationships
    swaps(first: 1) {
      id
    }
  }
}
```

#### Block Timestamps

```graphql
# Use block timestamps for time ranges
{
  pandaPoolSwaps(
    where: {
      timestamp_gt: "1634567890",
      timestamp_lt: "1634567990"
    }
  ) {
    timestamp
    averagePrice
  }
}
```

### Best Practices

1. **Query Performance**
   * Use pagination for large datasets
   * Select only needed fields
   * Optimize sorting and filtering
2. **Data Freshness**
   * Consider indexing delays
   * Implement proper polling intervals
   * Use block numbers for consistency
3. **Error Recovery**
   * Handle null entities gracefully
   * Validate data ranges
   * Implement retry logic

### Next Steps

Continue to Advanced Usage for:

* Complex query patterns
* Performance optimization
* Edge case handling


# Advanced Usage Guide

### Complex Integration Patterns

#### Real-time Market Making

Track pool state changes and price movements in real-time:

```typescript
import { createClient, gql } from '@apollo/client';

const POOL_STATE = gql`
  query GetPoolState($poolId: ID!, $lastTimestamp: Int!) {
    pandaPool(id: $poolId) {
      price
      pandaReserve
      baseReserve
      swaps(
        where: { timestamp_gt: $lastTimestamp }
        orderBy: timestamp
        orderDirection: desc
        first: 1
      ) {
        timestamp
        amountPandaIn
        amountPandaOut
        averagePrice
      }
    }
  }
`;

class MarketMaker {
  private lastPoll: number = 0;
  private readonly POLL_INTERVAL = 1000; // 1 second

  async monitorPool(poolId: string) {
    while (true) {
      const { data } = await client.query({
        query: POOL_STATE,
        variables: {
          poolId,
          lastTimestamp: this.lastPoll
        },
        fetchPolicy: 'network-only' // Bypass cache
      });

      this.updateStrategy(data.pandaPool);
      this.lastPoll = Math.floor(Date.now() / 1000);
      await new Promise(resolve => setTimeout(resolve, this.POLL_INTERVAL));
    }
  }

  private updateStrategy(poolData: any) {
    // Implement your market making strategy
  }
}
```

#### Historical Analysis Engine

Efficiently process historical data for analytics:

```typescript
const HISTORICAL_DATA = gql`
  query GetHistoricalData($startTime: Int!, $endTime: Int!) {
    priceSnapshots(
      where: {
        timestamp_gte: $startTime,
        timestamp_lte: $endTime,
        timeframe: HOUR
      }
      orderBy: timestamp
      orderDirection: asc
    ) {
      timestamp
      open
      high
      low
      close
      volume
    }
  }
`;

class AnalysisEngine {
  async analyzeTimeframe(startTime: number, endTime: number) {
    const batchSize = 1000;
    let currentStart = startTime;
    const results = [];

    while (currentStart < endTime) {
      const batchEnd = Math.min(currentStart + batchSize * 3600, endTime);
      const { data } = await client.query({
        query: HISTORICAL_DATA,
        variables: {
          startTime: currentStart,
          endTime: batchEnd
        }
      });
      
      results.push(...data.priceSnapshots);
      currentStart = batchEnd + 1;
    }

    return this.processResults(results);
  }

  private processResults(snapshots: any[]) {
    // Implement your analysis logic
  }
}
```

### Performance Optimization

#### Caching Strategies

Implement efficient caching for frequently accessed data:

```typescript
class SubgraphCache {
  private cache: Map<string, {
    data: any,
    timestamp: number
  }> = new Map();

  private readonly TTL = 60 * 1000; // 1 minute

  async getCachedData(key: string, fetchFn: () => Promise<any>) {
    const cached = this.cache.get(key);
    
    if (cached && Date.now() - cached.timestamp < this.TTL) {
      return cached.data;
    }

    const data = await fetchFn();
    this.cache.set(key, {
      data,
      timestamp: Date.now()
    });

    return data;
  }

  invalidateCache(key?: string) {
    if (key) {
      this.cache.delete(key);
    } else {
      this.cache.clear();
    }
  }
}
```

#### Batch Processing

Efficiently handle multiple queries:

```typescript
class BatchProcessor {
  private queue: Set<string> = new Set();
  private processing = false;
  private readonly BATCH_SIZE = 100;

  async queuePool(poolId: string) {
    this.queue.add(poolId);
    if (!this.processing) {
      await this.processBatch();
    }
  }

  private async processBatch() {
    this.processing = true;
    
    while (this.queue.size > 0) {
      const batch = Array.from(this.queue).slice(0, this.BATCH_SIZE);
      batch.forEach(id => this.queue.delete(id));

      const { data } = await client.query({
        query: POOL_DATA,
        variables: { poolIds: batch }
      });

      await this.handleBatchResults(data);
    }

    this.processing = false;
  }
}
```

### Error Handling & Recovery

#### Robust Query Handler

Handle network issues and retry failed queries:

```typescript
class RobustQueryHandler {
  private readonly MAX_RETRIES = 3;
  private readonly BACKOFF_BASE = 1000; // 1 second

  async executeQuery(query: any, variables: any) {
    for (let attempt = 0; attempt < this.MAX_RETRIES; attempt++) {
      try {
        return await client.query({ query, variables });
      } catch (error) {
        if (!this.shouldRetry(error) || attempt === this.MAX_RETRIES - 1) {
          throw error;
        }

        await this.sleep(this.getBackoffTime(attempt));
      }
    }
  }

  private shouldRetry(error: any): boolean {
    // Implement retry logic based on error type
    return error.message.includes('network')
      || error.message.includes('timeout');
  }

  private getBackoffTime(attempt: number): number {
    return this.BACKOFF_BASE * Math.pow(2, attempt);
  }

  private sleep(ms: number): Promise<void> {
    return new Promise(resolve => setTimeout(resolve, ms));
  }
}
```

### Edge Cases

#### Handling Network Upgrades

```typescript
class NetworkUpgradeHandler {
  private lastKnownBlock: number = 0;

  async checkNetworkContinuity() {
    const { data } = await client.query({
      query: gql`
        {
          _meta {
            block {
              number
            }
          }
        }
      `
    });

    const currentBlock = data._meta.block.number;
    
    if (this.lastKnownBlock > 0) {
      const gap = currentBlock - this.lastKnownBlock;
      if (gap > 100) { // Potential network upgrade
        await this.handleNetworkUpgrade(this.lastKnownBlock, currentBlock);
      }
    }

    this.lastKnownBlock = currentBlock;
  }

  private async handleNetworkUpgrade(lastBlock: number, currentBlock: number) {
    // Implement upgrade handling logic
  }
}
```

### Best Practices & Tips

#### 1. Query Optimization

```typescript
// Efficient field selection
const OPTIMIZED_QUERY = gql`
  query GetPoolData($poolId: ID!) {
    pandaPool(id: $poolId) {
      price   # Only request needed fields
      volumeUSD
      # Avoid requesting unnecessary relationships
    }
  }
`;
```

#### 2. Rate Limiting

```typescript
class RateLimiter {
  private timestamps: number[] = [];
  private readonly WINDOW_MS = 1000; // 1 second
  private readonly MAX_REQUESTS = 10;

  async executeWithRateLimit(fn: () => Promise<any>) {
    this.timestamps = this.timestamps.filter(
      ts => Date.now() - ts < this.WINDOW_MS
    );

    if (this.timestamps.length >= this.MAX_REQUESTS) {
      const oldestTimestamp = this.timestamps[0];
      const waitTime = this.WINDOW_MS - (Date.now() - oldestTimestamp);
      await new Promise(resolve => setTimeout(resolve, waitTime));
    }

    this.timestamps.push(Date.now());
    return fn();
  }
}
```

### Monitoring & Debugging

#### Performance Monitoring

```typescript
class QueryMonitor {
  private metrics: {
    [key: string]: {
      count: number;
      totalTime: number;
      errors: number;
    }
  } = {};

  async trackQuery(name: string, query: Promise<any>) {
    const start = Date.now();
    try {
      const result = await query;
      this.recordSuccess(name, Date.now() - start);
      return result;
    } catch (error) {
      this.recordError(name);
      throw error;
    }
  }

  getMetrics() {
    return Object.entries(this.metrics).map(([name, data]) => ({
      name,
      averageTime: data.totalTime / data.count,
      errorRate: data.errors / data.count,
      totalCalls: data.count
    }));
  }
}
```


# Smart Contract Reference

This reference guide details the core smart contracts of the Kodiak Panda protocol and their interactions.

**Overview**

The Kodiak Panda protocol consists of three main smart contracts that work together to provide token creation and liquidity management functionality.

{% content-ref url="/pages/lHhPCqULbDzZyGMWiUxs" %}
[Panda Factory](/developers/panda/smart-contract-reference/panda-factory)
{% endcontent-ref %}

{% content-ref url="/pages/lUgWkQsqTGFhXhKiGRyB" %}
[Panda Pool](/developers/panda/smart-contract-reference/panda-pool)
{% endcontent-ref %}

{% content-ref url="/pages/RvNSrTNxa0pPjXEyFQP6" %}
[Panda Token](/developers/panda/smart-contract-reference/panda-token)
{% endcontent-ref %}


# Panda Factory

The core factory contract for deploying and managing Panda tokens and pools.

### Deployment Functions

**`deployPandaToken`**

```solidity
function deployPandaToken(
    address implementation,
    PandaPoolParams calldata pp,
    string calldata name,
    string calldata symbol,
    uint16 deployerSupplyBps
) external nonReentrant returns (address pandaToken)
```

Deploys a new PandaToken with optional deployer buy.

**Parameters:**

* `implementation`: Address of the implementation contract
* `pp`: PandaPoolParams struct containing:
  * `baseToken`: Address of the base token
  * `sqrtPa`: Lower bound sqrt price
  * `sqrtPb`: Upper bound sqrt price
  * `vestingPeriod`: Vesting duration for deployer incentives
* `name`: Token name
* `symbol`: Token symbol
* `deployerSupplyBps`: Basis points of supply for deployer (max 5000)

**Returns:**

* `pandaToken`: Address of the deployed token

**Emits:** `PandaDeployed`

**Errors:**

* `PandaFactory: INVALID_DEPLOYER_BUY` - When deployerSupplyBps > 5000
* `PandaFactory: INVALID_IMPLEMENTATION` - When implementation not whitelisted
* `PandaFactory: INVALID_BASE` - When base token not configured
* `PandaFactory: PRICES_TOO_CLOSE` - When price range too narrow
* `PandaFactory: PRICES_TOO_FAR` - When price range too wide
* `PandaFactory: RAISE_TOO_LOW` - When minimum raise not met

**`deployPandaTokenWithBera`**

```solidity
function deployPandaTokenWithBera(
    address implementation,
    PandaPoolParams calldata pp,
    string calldata name,
    string calldata symbol,
    uint16 deployerSupplyBps
) external payable nonReentrant returns (address pandaToken)
```

Deploys a new PandaToken using native BERA with optional deployer buy.

**Parameters:**

* `implementation`: Address of the implementation contract
* `pp`: PandaPoolParams struct containing:
  * `baseToken`: Must be WBERA address
  * `sqrtPa`: Lower bound sqrt price
  * `sqrtPb`: Upper bound sqrt price
  * `vestingPeriod`: Vesting duration for deployer incentives
* `name`: Token name
* `symbol`: Token symbol
* `deployerSupplyBps`: Basis points of supply for deployer (max 5000)

**Returns:**

* `pandaToken`: Address of the deployed token

**Errors:**

* `PandaFactory: INVALID_BERA` - When baseToken is not WBERA
* All errors from deployPandaToken

`deployPandaPool`

```solidity
function deployPandaPool(
    address implementation,
    IPandaFactory.PandaPoolParams calldata pp,
    uint256 totalTokens,
    address pandaToken,
    bytes calldata data
) external nonReentrant returns (address)
```

Deploy a standalone PandaPool implementation.

**Parameters:**

* `implementation`: Address of the pool implementation
* `pp`: PandaPoolParams struct (see above)
* `totalTokens`: Total tokens to be managed by pool
* `pandaToken`: Address of existing Panda token
* `data`: Additional initialization data

**Returns:**

* Address of the deployed pool

**Errors:**

* `PandaFactory: INVALID_IMPLEMENTATION` - When implementation not whitelisted
* `PandaFactory: IS_PANDATOKEN` - When implementation is a token type
* `PandaFactory: INVALID_PANDATOKEN` - When token address is zero

### Incentive Functions

**`claimIncentive`**

```solidity
claimIncentive(
    address _pandaPool
) external
```

Claims deployment incentives after pool graduation.

**Parameters:**

* `_pandaPool`: Address of the graduated pool

**Errors:**

* `PandaFactory: Invalid pool` - When pool not deployed by factory
* `PandaFactory: Incentive already claimed` - When incentive already claimed
* `PandaFactory: Pool not graduated` - When pool hasn't graduated

### View Functions

**`predictPoolAddress`**

```solidity
predictPoolAddress(
    address implementation,
    address deployer
) external view returns (address)
```

Predicts pool address before deployment.

**Parameters:**

* `implementation`: Implementation contract address
* `deployer`: Address of the deployer

**Returns:**

* Predicted address of the pool

**`getSqrtP`**

```solidity
getSqrtP(
    uint256 scaledPrice
) external pure returns (uint256)
```

Converts price to square root format.

**Parameters:**

* `scaledPrice`: Price to convert (scaled by 1e18)

**Returns:**

* Square root price in correct scale

**`getPoolFees`**

```solidity
getPoolFees()
external view returns (PandaFees memory)
```

Get current fee configuration.

**Returns:**

* PandaFees struct containing:
  * `buyFee`: Fee for buying tokens
  * `sellFee`: Fee for selling tokens
  * `graduationFee`: Fee taken at graduation
  * `deployerFeeShare`: Share of graduation fee for deployer

**`isLegitPool`**

```solidity
isLegitPool(
    address _pandaPool
) public view returns (bool)
```

Verify if pool was deployed by factory.

**Parameters:**

* `_pandaPool`: Address to check

**Returns:**

* `true` if pool was deployed by factory

**`allPoolsLength`**

```solidity
allPoolsLength() external view returns (uint)
```

Get total number of deployed pools.

**Returns:**

* Count of all deployed pools

### Constants

```solidity
public constant MIN_TOKENSINPOOL_SHARE = 5000;    // 50%
uint256 public constant MAX_TOKENSINPOOL_SHARE = 9000;    // 90%
uint256 public constant MIN_SQRTP_MULTIPLE = 11_000;      // 1.1x
uint256 public constant MAX_SQRTP_MULTIPLE = 10*10_000;   // 10x
uint256 public constant TOKEN_SUPPLY = 1_000_000_000 * 1e18;
uint16 public constant DEPLOYER_MAX_BPS = 5000;           // 50%
```

### Events

```solidity
PandaDeployed(
    address indexed pandaPool,
    address indexed implementation
)
```

Emitted when new pool is deployed.

```solidity
IncentiveClaimed(
    address indexed pandaPool,
    uint256 amount
)
```

Emitted when deployment incentive is claimed.


# Panda Pool

Abstract base contract implementing bonding curve mechanics.

#### Functions

**Trading**

**`buyTokens`**

```solidity
function buyTokens(
    uint256 amountIn,
    uint256 minAmountOut,
    address to
) external nonReentrant returns (uint256 amountOut, uint256 fee)
```

Purchase tokens with the base token.

**Parameters:**

* `amountIn`: Amount of base tokens to spend
* `minAmountOut`: Minimum tokens to receive
* `to`: Recipient address

**Returns:**

* `amountOut`: Amount of tokens received
* `fee`: Fee paid in base tokens

**Errors:**

* `PandaPool: INSUFFICIENT_OUTPUT_AMOUNT` - When amountOut is less than minAmountOut
* `PandaPool: TRADE_BELOW_MIN` - When trade size is below minimum threshold
* `PandaPool: INVALID_TO` - When recipient address is zero
* `PandaPool: GRADUATED` - When pool has already graduated

**`buyTokensWithBera`**

```solidity
function buyTokensWithBera(
    uint256 minAmountOut,
    address to
) external payable returns (uint256 amountOut, uint256 fee)
```

Purchase tokens using native BERA.

**Parameters:**

* `minAmountOut`: Minimum tokens to receive
* `to`: Recipient address

**Returns:**

* `amountOut`: Amount of tokens received
* `fee`: Fee paid in BERA

**Errors:**

* `PandaPool: NOT_BERA_PAIR` - When base token is not WBERA
* `PandaPool: INSUFFICIENT_OUTPUT_AMOUNT` - When amountOut is less than minAmountOut
* `PandaPool: INVALID_TO` - When recipient address is zero
* `PandaPool: GRADUATED` - When pool has already graduated

**`buyAllTokens`**

```solidity
function buyAllTokens(
    address to
) external returns (uint256 amountOut, uint256 fee)
```

Purchase all remaining tokens in the pool.

**Parameters:**

* `to`: Recipient address

**Returns:**

* `amountOut`: Amount of tokens received
* `fee`: Fee paid in base tokens

**Errors:**

* `PandaPool: INVALID_TO` - When recipient address is zero
* `PandaPool: INSUFFICIENT_LIQUIDITY` - When not enough liquidity for trade
* `PandaPool: GRADUATED` - When pool has already graduated

**`sellTokens`**

```solidity
function sellTokens(
    uint256 amountIn,
    uint256 minAmountOut,
    address to
) external nonReentrant returns (uint256 amountOut, uint256 fee)
```

Sell tokens for the base token.

**Parameters:**

* `amountIn`: Amount of tokens to sell
* `minAmountOut`: Minimum base tokens to receive
* `to`: Recipient address

**Returns:**

* `amountOut`: Amount of base tokens received
* `fee`: Fee paid in base tokens

**Errors:**

* `PandaPool: INSUFFICIENT_BUYING` - When selling more than bought
* `PandaPool: INSUFFICIENT_OUTPUT_AMOUNT` - When amountOut is less than minAmountOut
* `PandaPool: INVALID_TO` - When recipient address is zero
* `PandaPool: GRADUATED` - When pool has already graduated

**`sellTokensForBera`**

```solidity
function sellTokensForBera(
    uint256 amountIn,
    uint256 minAmountOut,
    address to
) external returns (uint256 amountOut, uint256 fee)
```

Sell tokens for native BERA.

**Parameters:**

* `amountIn`: Amount of tokens to sell
* `minAmountOut`: Minimum amount of BERA to receive
* `to`: Recipient address for BERA

**Returns:**

* `amountOut`: Amount of BERA received
* `fee`: Fee paid in BERA

**Errors:**

* `PandaPool: NOT_BERA_PAIR` - When base token is not WBERA
* `PandaPool: INSUFFICIENT_BUYING` - When selling more than bought
* `PandaPool: INSUFFICIENT_OUTPUT_AMOUNT` - When amountOut is less than minAmountOut
* `PandaPool: INVALID_TO` - When recipient address is zero

#### Price Discovery Functions

**`getAmountOutBuy`**

```solidity
function getAmountOutBuy(
    uint256 amountIn
) public view returns (
    uint256 amountOut,
    uint256 fee,
    uint256 sqrtP_new
)
```

Calculate expected output for buying tokens.

**Returns:**

* `amountOut`: Expected amount of tokens to receive
* `fee`: Expected fee in base tokens
* `sqrtP_new`: New square root price after the trade

**Errors:**

* `PandaPool: TRADE_BELOW_MIN` - When trade size is below minimum threshold
* `PandaPool: INSUFFICIENT_LIQUIDITY` - When not enough liquidity for trade
* `PandaPool: GRADUATED` - When pool has already graduated

**`getAmountOutSell`**

```solidity
function getAmountOutSell(
    uint256 amountIn
) public view returns (
    uint256 amountOut,
    uint256 fee,
    uint256 sqrtP_new
)
```

Calculate expected output for selling tokens.

**Parameters:**

* `amountIn`: Amount of tokens to sell

**Returns:**

* `amountOut`: Expected amount of base tokens to receive
* `fee`: Expected fee in base tokens
* `sqrtP_new`: New square root price after the trade

**Errors:**

* `PandaPool: TRADE_BELOW_MIN` - When trade size is below minimum threshold
* `PandaPool: INSUFFICIENT_LIQUIDITY` - When not enough liquidity for trade
* `PandaPool: GRADUATED` - When pool has already graduated

**`getAmountInBuy`**

```solidity
function getAmountInBuy(
    uint256 amountOut
) public view returns (
    uint256 amountIn,
    uint256 fee,
    uint256 sqrtP_new
)
```

Calculate required input for desired token output.

**Parameters:**

* `amountOut`: Desired amount of tokens to receive

**Returns:**

* `amountIn`: Required amount of base tokens to spend
* `fee`: Expected fee in base tokens
* `sqrtP_new`: New square root price after the trade

**Errors:**

* `PandaPool: TRADE_BELOW_MIN` - When trade size is below minimum threshold
* `PandaPool: INSUFFICIENT_LIQUIDITY` - When not enough tokens available
* `PandaPool: GRADUATED` - When pool has already graduated

**`getAmountInBuyRemainingTokens`**

```solidity
getAmountInBuyRemainingTokens() 
public view returns (uint256 amountIn)
```

Calculate amount needed to buy all remaining tokens.

**Returns:**

* `amountIn`: Amount of base tokens needed to buy all remaining tokens

#### Balance & Vesting Functions

**`totalBalanceOf`**

```solidity
totalBalanceOf(
    address user
) external view returns (uint256)
```

Get total balance including unvested tokens.

**Parameters:**

* `user`: Address to check balance for

**Returns:**

* Total balance including both vested and unvested tokens

**`vestedBalanceOf`**

```solidity
 vestedBalanceOf(
    address user
) external view returns (uint256)
```

Get available/vested balance.

**Parameters:**

* `user`: Address to check vested balance for

**Returns:**

* Currently vested token balance

**`claimableTokens`**

```solidity
claimableTokens(
    address user
) public view returns (uint256)
```

Get amount of tokens available to claim.

**Parameters:**

* `user`: Address to check claimable tokens for

**Returns:**

* Amount of tokens currently available to claim

**Errors:**

* `PandaPool: VESTING_OFF` - When vesting is not enabled
* `PandaPool: NOT_GRADUATED` - When pool hasn't graduated yet

**`claimTokens`**

```solidity
claimTokens(
    address user
) external returns (uint256)
```

Claim vested tokens.

**Parameters:**

* `user`: Address to claim tokens for

**Returns:**

* Amount of tokens claimed

**Errors:**

* `PandaPool: VESTING_OFF` - When vesting is not enabled
* `PandaPool: NO_CLAIMABLE` - When no tokens are available to claim

#### Pool State Functions

**`remainingTokensInPool`**

```solidity
remainingTokensInPool()
public view returns (uint256)
```

Get remaining tokens available in pool.

**Returns:**

* Amount of tokens remaining in the pool

**`viewExcessTokens`**

```solidity
viewExcessTokens()
public view returns (
    uint256 excessPandaTokens,
    uint256 excessBaseTokens
)
```

View excess tokens in contract.

**Returns:**

* `excessPandaTokens`: Amount of excess Panda tokens
* `excessBaseTokens`: Amount of excess base tokens

**`collectExcessTokens`**

```solidity
collectExcessTokens()
external
```

Transfer excess tokens to treasury.

**Emits:** `ExcessCollected`

#### Events

```solidity
PoolInitialized(
    address pandaToken,
    address baseToken,
    uint256 sqrtPa,
    uint256 sqrtPb,
    uint256 vestingPeriod,
    address deployer,
    bytes data
)
```

Emitted when pool is initialized.

```solidity
Swap(
    address indexed sender,
    uint amount0In,
    uint amount1In,
    uint amount0Out,
    uint amount1Out,
    address indexed to
)
```

Emitted on each swap operation.

```solidity
Sync(
    uint256 pandaReserve,
    uint256 baseReserve,
    uint256 sqrtPrice
)
```

Emitted when pool reserves are synchronized.

```solidity
TokensClaimed(
    address indexed user,
    uint256 amount
)
```

Emitted when tokens are claimed from vesting.

```solidity
ExcessCollected(
    uint256 excessPandaTokens,
    uint256 excessBaseTokens
)
```

Emitted when excess tokens are collected.


# Panda Token

## PandaToken

ERC20-compliant token with bonding curve mechanics and permit functionality.

### Core Functions

#### Token Information

**`name`**

```solidity
function name() public view returns (string memory)
```

Returns the token name.

**`symbol`**

```solidity
function symbol() public view returns (string memory)
```

Returns the token symbol.

#### Token Operations

**`transfer`**

```solidity
function transfer(
    address to,
    uint256 amount
) public returns (bool)
```

Transfer tokens to a specified address.

**Parameters:**

* `to`: Recipient address
* `amount`: Amount of tokens to transfer

**Returns:**

* `true` if transfer successful

**Errors:**

* `PandaToken: INVALID_TRANSFER` - When transferring to DEX pair before graduation

**`approve`**

```solidity
function approve(
    address spender,
    uint256 amount
) public returns (bool)
```

Approve address to spend tokens.

**Parameters:**

* `spender`: Address to approve
* `amount`: Amount of tokens to approve

**Returns:**

* `true` if approval successful

**`permit`**

```solidity
function permit(
    address owner,
    address spender,
    uint256 value,
    uint256 deadline,
    uint8 v,
    bytes32 r,
    bytes32 s
) public
```

Approve spending using a signature (EIP-2612).

**Parameters:**

* `owner`: Token owner address
* `spender`: Spender address
* `value`: Amount to approve
* `deadline`: Timestamp after which permit is invalid
* `v`, `r`, `s`: Signature components

#### DEX Information

**`dexPair`**

```solidity
function dexPair() public view returns (address)
```

Returns the DEX pair address for this token.

**Returns:**

* Address of the token's DEX trading pair

#### State Information

**`graduated`**

```solidity
function graduated() public view returns (bool)
```

Returns whether the token has graduated to DEX trading.

**`getCurrentPrice`**

```solidity
function getCurrentPrice() public view returns (uint256)
```

Returns the current price from the bonding curve.

#### Trading Functions

Inherits all trading functions from PandaPool:

* `buyTokens`
* `buyTokensWithBera`
* `sellTokens`
* `sellTokensForBera`

See PandaPool documentation for detailed trading function specifications.

### Events

#### Standard ERC20 Events

```solidity
event Transfer(
    address indexed from,
    address indexed to,
    uint256 value
)
```

```solidity
event Approval(
    address indexed owner,
    address indexed spender,
    uint256 value
)
```

#### Graduation Event

```solidity
event LiquidityMoved(
    uint256 amountPanda,
    uint256 amountBase
)
```

Emitted when the token graduates to DEX trading.


# Api

Kodiak provides a way to get all the tokens created using the panda factory. The REST API is used for this purpose

## Base API url

```
https://api.panda.kodiak.finance
```

## How to use

First of all, any routes with the panda api assume that you specify a chainId,&#x20;

```
https://api.panda.kodiak.finance/80094/endpoints.....
```

There are no other requirements at this time, the API is fully public and does not require a API key

***

## Endpoints

#### Get a list of tokens (`GET /tokens`)

<table><thead><tr><th width="175">Query argument</th><th width="159">Required</th><th>Description</th></tr></thead><tbody><tr><td>limit</td><td>No</td><td>Maximum number of tokens in the response (Up to 100)</td></tr><tr><td>page</td><td>No</td><td>Current Page</td></tr><tr><td>addresses</td><td>No</td><td>A list of addresses separated by commas. If specified, you will only receive tokens from this list</td></tr></tbody></table>

Example:

```
https://api.panda.kodiak.finance/80084/tokens?limit=20&page=2
```

#### Get a specific tokens (`GET /tokens/<address>`)

Example:

```
https://api.panda.kodiak.finance/80084/tokens/0xc22212eba66997d6bb9d006f4e61d2da0a17fe35
```

Response:

```
{
  "address": "0xc22212eba66997d6bb9d006f4e61d2da0a17fe35",
  "chainId": 80084,
  "name": "Harry The Bera",
  "decimals": 18,
  "symbol": "HTB",
  "status": "ACTIVE",
  "socials": [
    {
      "url": "",
      "type": "website"
    },
    {
      "url": "",
      "type": "twitter"
    },
    {
      "url": "",
      "type": "telegram"
    }
  ],
  "description": "Harry's Token, Do You Want To Be Skem?",
  "logoURI": "https://d341uglbp0q7i.cloudfront.net/0xc22212eba66997d6bb9d006f4e61d2da0a17fe35.png"
}
```

#### Get a tokenList (`GET /tokenList.json`)

Example:&#x20;

```
https://api.panda.kodiak.finance/80094/tokenList.json
```

Provides a list of all tokens in a token list compatible format. It is envisioned that this list may be required by other platforms to export all tokens for display in the interface that have been graduated.

{% hint style="info" %}
Tokens in this list do not contain description and socials
{% endhint %}

{% hint style="info" %}
This list only includes tokens that have been **graduated**
{% endhint %}


# Farms

{% content-ref url="/pages/uHy5eKufDxYHwfJDaIQF" %}
[Technical Integration Guide](/developers/farms/technical-integration-guide)
{% endcontent-ref %}


# Technical Integration Guide

### Overview

KodiakFarm is an advanced staking protocol that implements a dynamic reward system with time-locked staking mechanisms. The protocol enables users to stake ERC20 tokens and earn multiple reward types simultaneously, with rewards amplified through a duration-based multiplier system. This implementation focuses on flexibility, security, and capital efficiency through its sophisticated architecture:

* Dynamic Multi-Token Reward System: Supports multiple reward tokens that can be added or modified post-deployment
* Time-Weighted Multipliers: Rewards scale with lock duration, incentivizing longer-term commitment
* Advanced Security Architecture: Multi-layered access control system with distinct roles and permissions
* Adaptive Reward Management: Intelligent reward rate adjustment based on token availability and distribution metrics
* Risk Mitigation Features: Comprehensive safety controls including emergency withdrawals, staking caps, and granular pause mechanisms
* Capital Efficiency: Optimized reward distribution with configurability for different token economics models

#### Technical Details

**Initialization and Setup**

1. **Deployment Flow**
   * Deploy the contract through the FarmFactory
   * Initialize with owner, staking token, reward tokens, managers, and rates
   * Fund the contract with reward tokens
   * Call `startFarm()` to begin operations
2. **Reward Configuration**

   ```solidity
   struct RewardConfig {
       address token;
       address manager;
       uint256 rate;
   }
   ```

   * Multiple reward tokens can be configured
   * Each token has its own manager and rate
   * Additional reward tokens can be added post-deployment
3. **Staking Mechanism**

   ```solidity
   struct LockedStake {
       bytes32 kek_id;
       uint256 start_timestamp;
       uint256 liquidity;
       uint256 ending_timestamp;
       uint256 lock_multiplier;
   }
   ```

   * Users lock tokens for a specified duration
   * Lock duration affects reward multiplier
   * Multiplier ranges from 1x to 3x (configurable)

**Integration Steps**

1. **Contract Setup**

   ```javascript
   const farm = await KodiakFarm.deploy();
   await farm.initialize(
       owner,
       stakingToken,
       rewardTokens,
       rewardManagers,
       rewardRates
   );
   ```
2. **Token Approvals**

   ```javascript
   // Approve staking token
   await stakingToken.approve(farmAddress, amount);
   // Approve reward tokens (for managers)
   await rewardToken.approve(farmAddress, rewardAmount);
   ```
3. **Staking Integration**

   ```javascript
   // Lock tokens
   await farm.stakeLocked(amount, lockDuration);

   // Withdraw tokens
   await farm.withdrawLocked(kekId);

   // Claim rewards
   await farm.getReward();
   ```
4. **Event Handling**

   ```javascript
   farm.on('StakeLocked', (user, amount, secs, kekId) => {
       // Handle stake locked event
   });

   farm.on('RewardPaid', (user, reward, tokenAddress) => {
       // Handle reward payment
   });
   ```

#### Best Practices

1. **Security Considerations**
   * Always verify reward token balances before setting rates
   * Implement frontend checks for lock duration limits
   * Monitor total staked amounts against cap
   * Handle emergency scenarios through proper channels
2. **Gas Optimization**
   * Batch withdrawals using `withdrawLockedMultiple`
   * Use `withdrawLockedAll` for mass withdrawals
   * Consider gas costs when setting reward periods
3. **Error Handling**
   * Implement proper error handling for failed transactions
   * Monitor for paused states (staking, withdrawals, rewards)
   * Handle grey-listed address scenarios


# Smart Contract Reference

### Smart Contract Reference

#### Core Functions

`initialize`

```solidity
function initialize(
    address _owner,
    address _stakingToken,
    address[] memory _rewardTokens,
    address[] memory _rewardManagers,
    uint256[] memory _rewardRates,
    bytes calldata _data
) external nonReentrant
```

Initializes a new KodiakFarm instance.

**Parameters:**

* `_owner`: Address that will own the farm
* `_stakingToken`: Address of the token that can be staked
* `_rewardTokens`: Array of reward token addresses
* `_rewardManagers`: Array of managers for each reward token
* `_rewardRates`: Array of reward rates for each token
* `_data`: Additional initialization data (unused)

**Errors:**

* `Farm: Already initialized` - When farm already initialized
* `Farm: Array lengths do not match` - When input arrays have different lengths
* `Token already added` - When duplicate reward tokens provided

**Events:** None

***

`stakeLocked`

```solidity
function stakeLocked(
    uint256 liquidity,
    uint256 secs
) public nonReentrant
```

Stakes tokens with a time lock.

**Parameters:**

* `liquidity`: Amount of tokens to stake
* `secs`: Duration of the lock in seconds

**Emits:** `StakeLocked`

**Errors:**

* `Staking paused` - When staking is paused
* `Must stake more than zero` - When liquidity is 0
* `Farm cap exceeded` - When total staked would exceed cap
* `Address has been greylisted` - When user is greylisted
* `Minimum stake time not met` - When secs < lock\_time\_min
* `Trying to lock for too long` - When secs > lock\_time\_for\_max\_multiplier

***

`withdrawLocked`

```solidity
function withdrawLocked(
    bytes32 kek_id
) public nonReentrant withdrawalsNotPaused
```

Withdraws a specific locked stake.

**Parameters:**

* `kek_id`: Unique identifier of the stake to withdraw

**Emits:** `WithdrawLocked`

**Errors:**

* `Withdrawals paused` - When withdrawals are paused
* `Stake not found` - When kek\_id doesn't exist
* `Stake is still locked!` - When lock duration hasn't expired

***

`getReward`

```solidity
function getReward() 
external nonReentrant 
returns (uint256[] memory)
```

Claims all available reward tokens.

**Returns:**

* Array of claimed reward amounts for each reward token

**Emits:** `RewardPaid`

**Errors:**

* `Rewards collection paused` - When rewards collection is paused

***

`addNewRewardToken`

```solidity
function addNewRewardToken(
    address _rewardToken,
    address _rewardManager,
    uint256 _rewardRate
) external onlyOwnerOrFactoryOwner
```

Adds a new reward token to the farm.

**Parameters:**

* `_rewardToken`: Address of the new reward token
* `_rewardManager`: Address of the token's reward manager
* `_rewardRate`: Initial reward rate for the token

**Emits:**

* `RewardTokenAdded`
* `RewardRateUpdated`

**Errors:**

* `Zero address detected` - When \_rewardToken is zero address
* `Token already added` - When token already exists in farm

***

`setRewardRate`

```solidity
function setRewardRate(
    address _rewardToken,
    uint256 _rewardRate,
    bool sync_too
) external onlyTknMgrs(_rewardToken)
```

Updates the reward rate for a specific token.

**Parameters:**

* `_rewardToken`: Address of the reward token
* `_rewardRate`: New reward rate
* `sync_too`: Whether to sync rewards after rate change

**Emits:** `RewardRateUpdated`

**Errors:**

* `Farm: Not owner, factory owner, or tkn mgr` - When caller lacks permission

***

`emergencyWithdraw`

```solidity
function emergencyWithdraw(
    bytes32 kek_id
) public nonReentrant withdrawalsNotPaused
```

Emergency withdraws a stake without claiming rewards.

**Parameters:**

* `kek_id`: Unique identifier of the stake to withdraw

**Emits:** `WithdrawLocked`

**Errors:**

* `Withdrawals paused` - When withdrawals are paused
* `Stake not found` - When kek\_id doesn't exist

***

`recoverERC20`

```solidity
function recoverERC20(
    address tokenAddress,
    uint256 tokenAmount
) external onlyTknMgrs(tokenAddress)
```

Recovers mistakenly sent tokens from the contract.

**Parameters:**

* `tokenAddress`: Address of token to recover
* `tokenAmount`: Amount to recover

**Emits:**

* `Recovered`
* `RewardRateUpdated` (if reward token)

**Errors:**

* `Cannot rug staking / LP tokens` - When attempting to withdraw stake token
* `No valid tokens to recover` - When caller lacks permission for token

```solidity
function stakeLocked(uint256 liquidity, uint256 secs) public nonReentrant
```

Stakes tokens for a specified duration.

* `liquidity`: Amount of tokens to stake
* `secs`: Lock duration in seconds
* Requirements:
  * Staking not paused
  * Duration within min/max bounds
  * Address not greylisted
  * Within staking cap

```solidity
function withdrawLocked(bytes32 kek_id) public nonReentrant withdrawalsNotPaused
```

Withdraws a specific stake after lock period.

* `kek_id`: Unique identifier of the stake
* Requirements:
  * Lock period expired
  * Withdrawals not paused

**Reward Management**

```solidity
function getReward() external nonReentrant returns (uint256[] memory)
```

Claims all available rewards.

* Requirements:
  * Rewards collection not paused
* Returns array of claimed reward amounts

```solidity
function setRewardRate(
    address _rewardToken,
    uint256 _rewardRate,
    bool sync_too
) external onlyTknMgrs(_rewardToken)
```

Updates reward rate for a specific token.

* Requires manager privileges
* Auto-funds if rate increases
* Optionally syncs rewards

#### Administrative Functions

```solidity
function setMultipliers(uint256 _lock_max_multiplier) external onlyOwnerOrFactoryOwner
```

Updates the maximum lock multiplier.

* Must be >= 1e18 (1x)

```solidity
function addNewRewardToken(
    address _rewardToken,
    address _rewardManager,
    uint256 _rewardRate
) external onlyOwnerOrFactoryOwner
```

Adds a new reward token to the farm.

* Cannot add duplicate tokens
* Auto-funds rewards if farm active

#### Events

```solidity
event StakeLocked(address indexed user, uint256 amount, uint256 secs, bytes32 kek_id)
event WithdrawLocked(address indexed user, uint256 amount, bytes32 kek_id)
event RewardPaid(address indexed user, uint256 reward, address token_address)
```

#### Modifiers

```solidity
modifier onlyOwnerOrFactoryOwner()
modifier onlyTknMgrs(address reward_token_address)
modifier onlyFactoryOwner()
modifier notStakingPaused()
modifier withdrawalsNotPaused()
```

#### Role-Based Access Control

1. **Owner**
   * Set multipliers and durations
   * Add new reward tokens
   * Configure staking caps
   * Manage greylist
2. **Factory Owner**
   * Emergency controls
   * Pause withdrawals/rewards
   * Override lock restrictions
3. **Token Managers**
   * Manage specific reward tokens
   * Set reward rates
   * Recover mistaken tokens

#### Error Handling

Common error scenarios and their meanings:

```solidity
"Farm: not started yet" // Farm needs initialization
"Staking paused" // Administrative pause active
"Farm cap exceeded" // Total stake limit reached
"Stake is still locked!" // Lock duration not met
"Rewards collection paused" // Emergency pause on rewards
```

#### State Variables

Key state tracking:

```solidity
uint256 public stakingTokenCap;
uint256 public lock_max_multiplier;
uint256 public lock_time_for_max_multiplier;
uint256 private _total_liquidity_locked;
mapping(address => LockedStake[]) private lockedStakes;
```

#### Security Features

1. **Emergency Controls**
   * Pause staking/withdrawals/rewards
   * Emergency withdrawal option
   * Factory owner override
2. **Access Controls**
   * Multi-role system
   * Greylist functionality
   * Manager-specific permissions
3. **Economic Safety**
   * Dynamic reward adjustment
   * Staking caps
   * Lock time restrictions


# Kodiak Islands

Technical documentation for kodiak islands

{% content-ref url="/pages/rNtD63NABWTq5oXxnhwK" %}
[Islands](/protocol/islands)
{% endcontent-ref %}

{% content-ref url="/pages/9ED6ebNyw7yomAngH9gk" %}
[Technical Integration Guide](/developers/kodiak-islands/technical-integration-guide)
{% endcontent-ref %}

{% content-ref url="/pages/HdOjaCarVDUslDUNiUsO" %}
[Smart Contract Reference](/developers/kodiak-islands/smart-contract-reference)
{% endcontent-ref %}


# Technical Integration Guide

Smart contract integration guide and examples

### Overview

Kodiak Islands are concentrated liquidity management vaults built on top of Kodiak V3 pools. This guide covers the technical aspects of integrating with Kodiak Islands from a smart contract perspective.

### 1. Usage with existing/Deployed Islands

#### What can be achieved

1. Depositing into existing Islands
2. Withdrawing from existing Islands
3. Checking current island position
4. Checking current fee earned
5. Calling rebalance to invest any pending fees

#### Prerequisites

Before integrating with Kodiak Islands, you should understand:

1. Kodiak V3 concentrated liquidity concepts
2. ERC20 token standards and approvals
3. Basic understanding of what's slippage and slippage protection mechanisms
4. Deployed contract addresses
5. Understanding of token ratio that is needed to deposit tokens into the island.
6. Finding the correct deposit params for double sided token deposits.
7. Finding the correct deposit and swap params for single sided token deposits.

Refer the section on [Understanding Token Deposit Ratio](https://app.gitbook.com/o/XDFALXDrtEzw6m888LZh/s/OSwqNrRJ9Xh6jO57yoLm/~/changes/39/developers/kodiak-islands/technical-integration-guide/understanding-token-deposit-ratio) for in dept guide.

#### Core Contracts

The main contracts involved for integration with existing islands are:

1. **Island Router Contract**: Handles complex operations like zaps and slippage protection
2. **Island Contract**: The actual vault contract managing the Kodiak V3 position

#### Integration Examples

**1. Basic Position Information**

```solidity
interface IKodiakIsland {
    function getUnderlyingBalances() external view returns (uint256 amount0Current, uint256 amount1Current);
    function token0() external view returns (IERC20);
    function token1() external view returns (IERC20);
    function pool() external view returns (IUniswapV3Pool);
    function lowerTick() external view returns (int24);
    function upperTick() external view returns (int24);
}
```

**2. Depositing with Both Tokens**

```solidity
interface IKodiakIslandRouter {
    function addLiquidity(
        IKodiakIsland island,
        uint256 amount0Max,
        uint256 amount1Max,
        uint256 amount0Min,
        uint256 amount1Min,
        uint256 amountSharesMin,
        address receiver
    ) external returns (uint256 amount0, uint256 amount1, uint256 mintAmount);
}

contract IslandDepositor {
    IKodiakIslandRouter public immutable router;
    
    constructor(address _router) {
        router = IKodiakIslandRouter(_router);
    }
    
    function deposit(
        IKodiakIsland island,
        uint256 amount0,
        uint256 amount1,
        uint256 slippageBPS,
        uint minShares
    ) external returns (uint256 mintAmount) {
        // Transfer tokens to this contract
        IERC20(island.token0()).transferFrom(msg.sender, address(this), amount0);
        IERC20(island.token1()).transferFrom(msg.sender, address(this), amount1);
        
        // Approve router
        IERC20(island.token0()).approve(address(router), amount0);
        IERC20(island.token1()).approve(address(router), amount1);
        
        // Calculate minimum amounts with slippage
        uint256 amount0Min = amount0 * (10000 - slippageBPS) / 10000;
        uint256 amount1Min = amount1 * (10000 - slippageBPS) / 10000;
        
        // Add liquidity
        (,, mintAmount) = router.addLiquidity(
            island,
            amount0,
            amount1,
            amount0Min,
            amount1Min,
            minShares, // Min shares, can be calculated based on simulation before calling this
            msg.sender
        );
    }
}
```

**3. Single Token Deposits (Zaps)**

For single token deposits, the swap calldata needs to be prepared off-chain using the Kodiak Quoter API. The process involves:

1. Getting the optimal swap amount using the formula:

```solidity
// Pseudo-code for swap amount calculation
function calculateSwapAmount(
    uint256 totalAmount,
    uint256 price,
    uint256 ratio0,
    uint256 ratio1
) pure returns (uint256) {
    // If depositing token0
    return (ratio1 * totalAmount * 1e18) / (ratio0 * price + (ratio1 * 1e18));
    
    // If depositing token1
    // return (ratio0 * totalAmount * 1e18) / (ratio1 * price + ratio0 * 1e18);
}
```

2. Using the Kodiak Quoter API to get the swap calldata (refer to the[ Kodiak API Documentation)](https://documentation.kodiak.finance/developers/quotes)
3. Implementing the deposit:

```solidity
interface IKodiakIslandRouter {
    struct RouterSwapParams {
        bool zeroForOne;
        uint256 amountIn;
        uint256 minAmountOut;
        bytes routeData;
    }
    
    function addLiquiditySingle(
        IKodiakIsland island,
        uint256 totalAmountIn,
        uint256 amountSharesMin,
        uint256 maxStakingSlippageBPS,
        RouterSwapParams calldata swapData,
        address receiver
    ) external returns (uint256 amount0, uint256 amount1, uint256 mintAmount);
}

contract IslandZapper {
    IKodiakIslandRouter public immutable router;
    
    constructor(address _router) {
        router = IKodiakIslandRouter(_router);
    }
    
    function zapIn(
        IKodiakIsland island,
        uint256 amountIn,
        RouterSwapParams calldata swapData,
        uint256 slippageBPS,
        uint256 minShares
    ) external returns (uint256 mintAmount) {
        // Transfer input token
        IERC20 inputToken = swapData.zeroForOne ? island.token0() : island.token1();
        inputToken.transferFrom(msg.sender, address(this), amountIn);
        
        // Approve router
        inputToken.approve(address(router), amountIn);
        
        // Execute zap
        (,, mintAmount) = router.addLiquiditySingle(
            island,
            amountIn,
            minShares, // Min shares, should be calculated based on simulation
            slippageBPS, // This ensures the target pool's price does not move dramatically before your deposit goes through
            swapData,
            msg.sender
        );
    }
}
```

**4. Withdrawing Liquidity**

```solidity
interface IKodiakIslandRouter {
    function removeLiquidity(
        IKodiakIsland island,
        uint256 burnAmount,
        uint256 amount0Min,
        uint256 amount1Min,
        address receiver
    ) external returns (uint256 amount0, uint256 amount1, uint128 liquidityBurned);
}

contract IslandWithdrawer {
    IKodiakIslandRouter public immutable router;
    
    constructor(address _router) {
        router = IKodiakIslandRouter(_router);
    }
    
    function withdraw(
        IKodiakIsland island,
        uint256 burnAmount,
        uint256 slippageBPS
    ) external returns (uint256 amount0, uint256 amount1) {
        // Get expected amounts
        (uint256 expectedAmount0, uint256 expectedAmount1) = island.getUnderlyingBalances();
        expectedAmount0 = expectedAmount0 * burnAmount / island.totalSupply();
        expectedAmount1 = expectedAmount1 * burnAmount / island.totalSupply();
        
        // Calculate minimum amounts with slippage
        uint256 amount0Min = expectedAmount0 * (10000 - slippageBPS) / 10000;
        uint256 amount1Min = expectedAmount1 * (10000 - slippageBPS) / 10000;
        
        // Transfer LP tokens and approve router
        IERC20(address(island)).transferFrom(msg.sender, address(this), burnAmount);
        IERC20(address(island)).approve(address(router), burnAmount);
        
        // Remove liquidity
        (amount0, amount1,) = router.removeLiquidity(
            island,
            burnAmount,
            amount0Min,
            amount1Min,
            msg.sender
        );
    }
}
```

**5. Rebalancing and Fee Collection**

```solidity
contract IslandRebalancer {
    function rebalanceIsland(IKodiakIsland island) external {
        // Anyone can call rebalance to reinvest fees
        island.rebalance();
    }
    
    function collectManagerFees(IKodiakIsland island) external {
        // Only manager can collect fees
        require(island.manager() == msg.sender, "Not manager");
        island.withdrawManagerBalance();
    }
}
```

### 2. Deploying new Islands

#### What can be achieved

1. Deploying new managed Islands
2. Deploying new Permissionless Islands
3. Enabling mint for everyone for deployed Islands
4. Managing deployed Island parameters and position
5. Collecting Fees
6. Giving up ownership of deployed Islands

#### Prerequisites

Before deploying new Islands, you should understand:

1. Kodiak V3 concentrated liquidity concepts
2. Openzeppelin Minimal Proxy Contracts
3. Island management parameters and fee structures

#### Core Contracts

The main contracts involved in deployment are:

1. **Island Factory Contract**: Creates new Island instances
2. **Island Implementation Contract**: The base contract that gets cloned

#### Deployment Examples

**1. Deploying a Managed Island**

```solidity
interface IKodiakIslandFactory {
    function deployVault(
        address tokenA,
        address tokenB,
        uint24 uniFee,
        address manager,
        address managerTreasury,
        uint16 managerFee,
        int24 lowerTick,
        int24 upperTick
    ) external returns (address island);
}

contract IslandDeployer {
    IKodiakIslandFactory public immutable factory;
    
    constructor(address _factory) {
        factory = IKodiakIslandFactory(_factory);
    }
    
    function deployManagedIsland(
        address tokenA,
        address tokenB,
        uint24 uniFee,
        address manager,
        address treasury,
        uint16 managerFeeBPS,
        int24 lowerTick,
        int24 upperTick
    ) external returns (address) {
        // Validate parameters
        require(manager != address(0), "Invalid manager"); // this is address zero for permissionless islands only
        require(treasury != address(0), "Invalid treasury"); // You need to set a treasury for managed islands to collect fees
        require(managerFeeBPS <= 10000, "Invalid fee"); // Manager fee cannot exceed 10000 BPS (100%)
        
        // Deploy island
        return factory.deployVault(
            tokenA,
            tokenB,
            uniFee,
            manager,
            treasury,
            managerFeeBPS,
            lowerTick,
            upperTick
        );
    }
}
```

**2. Deploying a Permissionless Island**

```solidity
contract PermissionlessIslandDeployer {
    IKodiakIslandFactory public immutable factory;
    
    constructor(address _factory) {
        factory = IKodiakIslandFactory(_factory);
    }
    
    function deployPermissionlessIsland(
        address tokenA,
        address tokenB,
        uint24 uniFee,
        int24 lowerTick,
        int24 upperTick
    ) external returns (address) {
        // For permissionless islands:
        // - manager must be address(0)
        // - treasury must be address(0)
        // - managerFee must be 0
        return factory.deployVault(
            tokenA,
            tokenB,
            uniFee,
            address(0), // No manager
            address(0), // No treasury
            0, // No manager fee
            lowerTick,
            upperTick
        );
    }
}
```

#### Important Notes

1. **Tick Spacing**: Ensure ticks align with pool's tick spacing otherwise an error will be thrown
2. **Token Ordering**: Factory handles token ordering internally
3. **Fee Limits**: Manager fees cannot exceed 10000 BPS (100%)
4. **Permissionless vs Managed**: Understand the differences in parameters to deploy managed vs permissionless islands
5. **Enabling Minting**: You need to enable minting for everyone for managed islands
6. **Rebalance**: You need to call rebalance on the island for compounding earned fee back into the position.
7. **Permissionless Islands Frontend listing**: You need to contact the Kodiak team to get your permissionless island listed on the kodiak frontend.

#### Security Considerations

1. Always use the router for deposits/withdrawals to ensure proper slippage protection
2. Validate all parameters before deployment
3. Test with small amounts first
4. Be cautious with manager permissions, use islands only from trusted managers.
5. Implement proper access control in integrating contracts
6. Monitor gas costs, especially for operations involving swaps


# Understanding Token Deposit Ratio

This guide outlines the token Deposit ratio, how to find it, and how to reach there with a single token

## Overview

When providing liquidity to a Kodiak Island, tokens must be deposited in a specific ratio determined by the current price and position of the underlying Kodiak V3 pool.&#x20;

### Core Concepts

* Island Token Ratio: Each Island has a target ratio of its underlying tokens (token0 and token1). This ratio is determined by the current price of the tokens and the position's boundaries.
* Single-Sided Deposits: Users often want to deposit a single token. In this case, a portion of the input token must be swapped for the other token to match the Island's target ratio.
* Price Impact: Swapping tokens can cause price impact, which is the change in price due to the size of the trade. We want to minimize this impact while still achieving the desired token ratio.
* Optimal Swap Amount: The goal is to find the swap amount that results in the most efficient deposit into the Island, considering the target ratio and minimizing price impact.
* Make sure to account for difference in token decimals in all calculations carried out.

### Depositing with Both Tokens

The ratio of tokens to be deposited in an island can be found by calling the function `island.getMintAmounts(amount0Max, amount1Max)` on the particular island with the max amounts of token0 and token1 the user is willing to deposit. This returns `(amount0, amount1, liquidityMinted)` where amount0 and amount1 correspond to the amount of tokens that will be used by the island and the amount of liquidity that is minted using `(amount0, amount1)`. This is the ratio of tokens that needs to be deposited into the island based on the current island position and the underlying Kodiak pool's current token price.&#x20;

```solidity
function getMintAmounts(
    uint256 amount0Max,
    uint256 amount1Max
) external view returns (
    uint256 amount0,
    uint256 amount1,
    uint256 mintAmount
)
```

### Finding Deposit Ratio and Swap Data for Zaps

We will describe below the process of finding the swap amount and to keep it simple we will assume that the liquidity is high and swap does not have a large price impact thus ignoring it for the following example.

#### Step 1 - Finding the correct ratio of tokens to deposit

We use one unit of both tokens and call the `getMintAmounts` function on the island to check the amounts of tokens deposited thus giving us a ratio. We then normalize it to 18 decimals to remove all decimal discrepancy

```typescript
async function getIslandRatio(islandContract: ethers.Contract, token0: Token, token1: Token): Promise<IslandState> {
    const amount0 = parseUnits('1', token0Decimals);
    const amount1 = parseUnits('1', token1Decimals);
    const rawMintAmounts = await islandContract.getMintAmounts(amount0.toString(), amount1.toString());
    const amount0Used = BigNumber.from(rawMintAmounts[0]);
    const amount1Used = BigNumber.from(rawMintAmounts[1]);

    const normalizedAmount0 = amount0Used.mul(BigNumber.from(10).pow(18 - (token0?.decimals || 18)));
    const normalizedAmount1 = amount1Used.mul(BigNumber.from(10).pow(18 - (token1?.decimals || 18)));
    const ratio = normalizedAmount1.mul(10000).div(normalizedAmount0);

    return { amount0: normalizedAmount0, amount1: normalizedAmount1, ratio };
}
```

#### Step 2 - We get the swap price of inputToken -> OutputToken from the Swap router(KodiakRouter)

We use the kodiak quoter api to fetch the current price of the input token in terms of the output token.&#x20;

The response returns the `quote` which is the amount of output token you would receive for 1 unit of input token. We normalize this to 18 decimals to correspond to step1 and bring everything normalized to 18 decimals

```typescript
async function getKodiakQuote(
    kodiakApiUrl: string,
    baseToken: Token, // inputToken
    quoteToken: Token, // outputToken
    inputAmount: BigNumber, // we use 1 unit (i.e 1e18 for honey or 1e6 for usdc)
    // of inputToken
    chainId: number,
    slippage: string,
    deadline: number,
    receiver?: string // should be kodiak router
): Promise<QuoteResult> {
    const publicApiUrl = new URL(kodiakApiUrl);
    publicApiUrl.searchParams.set('tokenInAddress', baseToken.address);
    publicApiUrl.searchParams.set('tokenInChainId', chainId.toString());
    publicApiUrl.searchParams.set('tokenOutAddress', quoteToken.address);
    publicApiUrl.searchParams.set('tokenOutChainId', chainId.toString());
    publicApiUrl.searchParams.set('amount', inputAmount.toString());
    publicApiUrl.searchParams.set('type', 'exactIn');
    publicApiUrl.searchParams.set('slippageTolerance', slippage);
    publicApiUrl.searchParams.set('deadline', deadline.toString());
    if (receiver) publicApiUrl.searchParams.set('recipient', receiver);

    const response = await fetch(publicApiUrl.toString());
    const json: QuoteResult = await response.json();
    return json;
}

// This is what the API returns.
export interface GetQuoteResult {
  quoteId?: string
  blockNumber: string
  amount: string
  amountDecimals: string
  gasPriceWei: string
  gasUseEstimate: string
  gasUseEstimateQuote: string
  gasUseEstimateQuoteDecimals: string
  gasUseEstimateUSD: string
  methodParameters?: { calldata: string; value: string }
  quote: string
  quoteDecimals: string
  quoteGasAdjusted: string
  quoteGasAdjustedDecimals: string
  route: Array<(V3PoolInRoute | V2PoolInRoute)[]>
  routeString: string
}
```

#### Step 3 - Calculate the swap amount based on the information from step 1 and step 2

This step calculates the ideal swap amount assuming no price impact.

The formula depends on whether the input token is token0 or token1.

If input token is token0:

```
swapAmount = (i1 * amount * 1 ether) / (i0 * exchangePriceX18 + (i1 * 1 ether))
```

If input token is token1:

```
swapAmount = (i0 * amount * 1 ether) / (i1 * exchangePriceX18 + i0 * 1 ether)        
```

Where:

```
- i0 is the amount of token0 normalized to 18 decimals,
   deposited in the island from step1
- i1 is the amount of token1 normalized to 18 decimals,
   deposited in the island from step1
- amount is the total amount of the input token the user wants to deposit
- exchangePriceX18 is the price of the input token in terms of the output token,
  normalized to 18 decimals.
```

#### 4. Get Final Swap Data&#x20;

Now fetch the final swap data using the amount from step3, this returns the outputQuote and the calldata for the transaction which need to be used for constructing the `RouterSwapParams` passed to the IslandRouter.


# Subgraph

### Overview

The Kodiak Islands subgraph indexes and tracks data from the Kodiak Islands protocol, a DeFi liquidity management system focusing on automated vault strategies. This subgraph captures essential metrics, events, and state changes from the protocol's smart contracts, making the data easily accessible for analysis and integration with other applications.

#### Purpose

The Kodiak Islands subgraph serves several key purposes:

1. **Track Protocol Performance** - Monitor TVL, fees earned, APR, and other financial metrics across all vaults
2. **User Activity Analysis** - Track deposits, withdrawals, and user engagement metrics
3. **Vault Strategy Insights** - Monitor position ticks, rebalances, and strategy changes
4. **Historical Data Access** - Access time-series data through hourly and daily snapshots

#### Key Features

* **Comprehensive Vault Tracking**: Monitor the creation, performance, and activity of all Kodiak vaults
* **Financial Metrics**: Track TVL, fees (LP fees and manager fees), volumes, and APR for vaults
* **Detailed Event Logging**: Record deposits, withdrawals, fee earnings, rebalances, and other protocol events
* **Time-Series Data**: Access historical data through hourly and daily snapshots for both vaults and protocol metrics
* **Position Management**: Monitor liquidity positions through lower and upper tick tracking

#### Architecture

The Kodiak Islands subgraph is structured around several core entities:

* **KodiakIslandProtocol**: The parent entity representing the entire protocol
* **KodiakVault**: Individual vault instances managed by the protocol
* **Events**: Transactions like deposits and withdrawals made to vaults
* **Snapshots**: Time-based records of protocol and vault metrics (hourly and daily)
* **Token Information**: Details about the tokens managed within vaults

#### Data Flow

Data is captured through event handlers that process blockchain events emitted by the Kodiak Islands smart contracts. Key events include:

1. **Island Creation**: When a new vault is created
2. **Minting/Burning**: When users deposit or withdraw funds
3. **Rebalancing**: When vaults adjust their position ranges
4. **Fee Collection**: When fees are earned by vaults

#### Getting Started

To start using the Kodiak Islands subgraph:

1. Query the subgraph endpoint using GraphQL
2. Explore available entities and their relationships
3. Build custom queries to extract the specific data you need

See the Query Guide section for examples of common queries and usage patterns.


# Entity Reference

### Overview

This section provides a comprehensive reference for all entities in the Kodiak Islands subgraph, including their fields, relationships, and purpose.

### Core Entities

**KodiakVault**

Represents an individual vault in the Kodiak Islands protocol.

| Field                    | Type                 | Description                                          |
| ------------------------ | -------------------- | ---------------------------------------------------- |
| id                       | ID                   | Smart contract address of the vault                  |
| protocol                 | KodiakIslandProtocol | The protocol this vault belongs to                   |
| name                     | String               | Name of the liquidity pool                           |
| symbol                   | String               | Symbol of the liquidity pool                         |
| inputToken               | Token                | Token that needs to be deposited to take a position  |
| outputToken              | Token                | Token that is minted to track ownership of position  |
| manager                  | Bytes                | Manager of the vault                                 |
| managerFee               | BigDecimal           | Manager fee (in percentage) of the vault             |
| managerTreasury          | Bytes                | Manager treasury address                             |
| implementation           | Bytes                | Implementation address of the vault                  |
| createdTimestamp         | BigInt               | Creation timestamp                                   |
| createdBlockNumber       | BigInt               | Creation block number                                |
| totalValueLockedUSD      | BigDecimal           | Current TVL of this pool in USD                      |
| cumulativeLpFeesUSD      | BigDecimal           | All revenue generated, accrued to the supply side    |
| cumulativeManagerFeesUSD | BigDecimal           | All revenue generated, accrued to the protocol       |
| cumulativeTotalFeesUSD   | BigDecimal           | All revenue generated by the vault                   |
| inputTokenBalance        | BigInt               | Amount of input token in the pool                    |
| outputTokenSupply        | BigInt               | Total supply of output token                         |
| outputTokenPriceUSD      | BigDecimal           | Price per share of output token in USD               |
| pricePerShare            | BigDecimal           | Amount of input token per full share of output token |
| volumeToken0             | BigDecimal           | Volume of token0                                     |
| volumeToken1             | BigDecimal           | Volume of token1                                     |
| volumeUSD                | BigDecimal           | Volume in USD                                        |
| weeklyVolumeUSD          | BigDecimal           | Weekly volume in USD                                 |
| weeklyFeesEarnedUSD      | BigDecimal           | Weekly fees earned in USD                            |
| lowerTick                | BigInt               | Lower price tick of current position                 |
| upperTick                | BigInt               | Upper price tick of current position                 |
| \_token0                 | Token                | token0 of vault                                      |
| \_token1                 | Token                | token1 of vault                                      |
| \_token0Amount           | BigInt               | token0 amount                                        |
| \_token1Amount           | BigInt               | token1 amount                                        |
| \_token0AmountUSD        | BigDecimal           | token0 amount in USD                                 |
| \_token1AmountUSD        | BigDecimal           | token1 amount in USD                                 |

**KodiakApr**

Tracks APR (Annual Percentage Rate) information for vaults.

| Field      | Type       | Description              |
| ---------- | ---------- | ------------------------ |
| id         | ID         | Unique identifier        |
| averageApr | BigDecimal | Average APR of the vault |

**KodiakAprAccumulated**

Tracks accumulated APR data over time.

| Field        | Type                        | Description                                 |
| ------------ | --------------------------- | ------------------------------------------- |
| id           | ID                          | Unique identifier                           |
| vault        | KodiakVault                 | The vault this APR data belongs to          |
| accumulated  | BigDecimal                  | Accumulated APR value                       |
| count        | BigInt                      | Count of data points                        |
| lastSnapshot | KodiakVaultDailySnapshot    | Last snapshot used for calculation          |
| snapshots    | \[KodiakVaultDailySnapshot] | Array of snapshots used for APR calculation |

#### Events

**Event Interface**

Base interface for all events in the protocol.

| Field       | Type                 | Description                              |
| ----------- | -------------------- | ---------------------------------------- |
| id          | ID                   | Transaction hash + Log index             |
| hash        | String               | Transaction hash                         |
| logIndex    | Int                  | Event log index                          |
| protocol    | KodiakIslandProtocol | The protocol this transaction belongs to |
| to          | String               | Address that received tokens             |
| from        | String               | Address that sent tokens                 |
| blockNumber | BigInt               | Block number of this event               |
| timestamp   | BigInt               | Timestamp of this event                  |

**KodiakDeposit**

Records deposit events to vaults.

| Field                                  | Type        | Description                               |
| -------------------------------------- | ----------- | ----------------------------------------- |
| asset                                  | Token       | Token deposited                           |
| amount                                 | BigInt      | Amount of token deposited in native units |
| amountUSD                              | BigDecimal  | Amount of token deposited in USD          |
| amount0                                | BigDecimal  | Amount of token0                          |
| amount1                                | BigDecimal  | Amount of token1                          |
| vault                                  | KodiakVault | The vault involving this transaction      |
| *Plus all fields from Event interface* |             |                                           |

**KodiakWithdraw**

Records withdrawal events from vaults.

| Field                                  | Type        | Description                               |
| -------------------------------------- | ----------- | ----------------------------------------- |
| asset                                  | Token       | Token withdrawn                           |
| amount                                 | BigInt      | Amount of token withdrawn in native units |
| amountUSD                              | BigDecimal  | Amount of token withdrawn in USD          |
| vault                                  | KodiakVault | The vault involving this transaction      |
| *Plus all fields from Event interface* |             |                                           |

**KodiakStrategyChange**

Records changes to vault strategies.

| Field     | Type   | Description             |
| --------- | ------ | ----------------------- |
| id        | ID     | Unique identifier       |
| lowerTick | BigInt | New lower tick boundary |
| upperTick | BigInt | New upper tick boundary |
| timestamp | BigInt | Timestamp of the change |

#### Snapshots

**KodiakUsageMetricsDailySnapshot**

Daily snapshot of protocol usage metrics.

| Field                 | Type                 | Description                               |
| --------------------- | -------------------- | ----------------------------------------- |
| id                    | ID                   | Days since Unix epoch time                |
| protocol              | KodiakIslandProtocol | Protocol this snapshot is associated with |
| dailyActiveUsers      | Int                  | Number of unique daily active users       |
| cumulativeUniqueUsers | Int                  | Number of cumulative unique users         |
| dailyTransactionCount | Int                  | Total number of transactions in a day     |
| dailyDepositCount     | Int                  | Total number of deposits in a day         |
| dailyWithdrawCount    | Int                  | Total number of withdrawals in a day      |
| totalPoolCount        | Int                  | Total number of pools                     |
| blockNumber           | BigInt               | Block number of this snapshot             |
| timestamp             | BigInt               | Timestamp of this snapshot                |

**KodiakUsageMetricsHourlySnapshot**

Hourly snapshot of protocol usage metrics.

| Field                  | Type                 | Description                               |
| ---------------------- | -------------------- | ----------------------------------------- |
| id                     | ID                   | Hours since Unix epoch time               |
| protocol               | KodiakIslandProtocol | Protocol this snapshot is associated with |
| hourlyActiveUsers      | Int                  | Number of unique hourly active users      |
| cumulativeUniqueUsers  | Int                  | Number of cumulative unique users         |
| hourlyTransactionCount | Int                  | Total number of transactions in an hour   |
| hourlyDepositCount     | Int                  | Total number of deposits in an hour       |
| hourlyWithdrawCount    | Int                  | Total number of withdrawals in an hour    |
| blockNumber            | BigInt               | Block number of this snapshot             |
| timestamp              | BigInt               | Timestamp of this snapshot                |

**KodiakFinancialsDailySnapshot**

Daily snapshot of protocol financial metrics.

| Field                    | Type                 | Description                                      |
| ------------------------ | -------------------- | ------------------------------------------------ |
| id                       | ID                   | Days since Unix epoch time                       |
| protocol                 | KodiakIslandProtocol | Protocol this snapshot is associated with        |
| totalValueLockedUSD      | BigDecimal           | Current TVL of the entire protocol               |
| dailyLpFeesUSD           | BigDecimal           | Daily revenue claimed by suppliers               |
| cumulativeLpFeesUSD      | BigDecimal           | Cumulative revenue claimed by suppliers          |
| dailyManagerFeesUSD      | BigDecimal           | Daily revenue claimed by protocol                |
| cumulativeManagerFeesUSD | BigDecimal           | Cumulative revenue claimed by protocol           |
| dailyTotalFeesUSD        | BigDecimal           | All daily revenue generated by the protocol      |
| cumulativeTotalFeesUSD   | BigDecimal           | All cumulative revenue generated by the protocol |
| blockNumber              | BigInt               | Block number of this snapshot                    |
| timestamp                | BigInt               | Timestamp of this snapshot                       |

**KodiakVaultDailySnapshot**

Daily snapshot of vault metrics.

| Field                    | Type                    | Description                                          |
| ------------------------ | ----------------------- | ---------------------------------------------------- |
| id                       | ID                      | Vault address + Days since Unix epoch time           |
| protocol                 | KodiakIslandProtocol    | The protocol this snapshot belongs to                |
| vault                    | KodiakVault             | The vault this snapshot belongs to                   |
| totalValueLockedUSD      | BigDecimal              | Current TVL of this pool in USD                      |
| cumulativeLpFeesUSD      | BigDecimal              | All revenue generated, accrued to the supply side    |
| dailyLpFeesUSD           | BigDecimal              | Daily revenue generated, accrued to the supply side  |
| cumulativeManagerFeesUSD | BigDecimal              | All revenue generated, accrued to the protocol       |
| dailyManagerFeesUSD      | BigDecimal              | Daily revenue generated, accrued to the protocol     |
| cumulativeTotalFeesUSD   | BigDecimal              | All revenue generated by the vault                   |
| dailyTotalFeesUSD        | BigDecimal              | Daily revenue generated by the vault                 |
| inputTokenBalance        | BigInt                  | Amount of input token in the pool                    |
| outputTokenSupply        | BigInt                  | Total supply of output token                         |
| outputTokenPriceUSD      | BigDecimal              | Price per share of output token in USD               |
| pricePerShare            | BigDecimal              | Amount of input token per full share of output token |
| volumeUSD                | BigDecimal              | Volume in USD                                        |
| volumeToken0             | BigDecimal              | Volume of token0                                     |
| volumeToken1             | BigDecimal              | Volume of token1                                     |
| apr                      | BigDecimal              | Annual Percentage Rate                               |
| blockNumber              | BigInt                  | Block number of this snapshot                        |
| timestamp                | BigInt                  | Timestamp of this snapshot                           |
| lowerTick                | BigInt                  | Lower price tick of current position                 |
| upperTick                | BigInt                  | Upper price tick of current position                 |
| tickChanges              | \[KodiakStrategyChange] | Array of strategy changes                            |
| \_baseLowerTick          | BigInt                  | Base lower tick                                      |
| \_baseUpperTick          | BigInt                  | Base upper tick                                      |
| \_token0                 | Token                   | token0 of vault                                      |
| \_token1                 | Token                   | token1 of vault                                      |
| \_token0Amount           | BigInt                  | token0 amount                                        |
| \_token1Amount           | BigInt                  | token1 amount                                        |
| \_token0AmountUSD        | BigDecimal              | token0 amount in USD                                 |
| \_token1AmountUSD        | BigDecimal              | token1 amount in USD                                 |

**KodiakVaultHourlySnapshot**

Hourly snapshot of vault metrics.

| Field                    | Type                    | Description                                          |
| ------------------------ | ----------------------- | ---------------------------------------------------- |
| id                       | ID                      | Vault address + Hours since Unix epoch time          |
| protocol                 | KodiakIslandProtocol    | The protocol this snapshot belongs to                |
| vault                    | KodiakVault             | The vault this snapshot belongs to                   |
| totalValueLockedUSD      | BigDecimal              | Current TVL of this pool in USD                      |
| cumulativeLpFeesUSD      | BigDecimal              | All revenue generated, accrued to the supply side    |
| hourlyLpFeesUSD          | BigDecimal              | Hourly revenue generated, accrued to the supply side |
| cumulativeManagerFeesUSD | BigDecimal              | All revenue generated, accrued to the protocol       |
| hourlyManagerFeesUSD     | BigDecimal              | Hourly revenue generated, accrued to the protocol    |
| cumulativeTotalFeesUSD   | BigDecimal              | All revenue generated by the vault                   |
| hourlyTotalFeesUSD       | BigDecimal              | Hourly revenue generated by the vault                |
| inputTokenBalance        | BigInt                  | Amount of input token in the pool                    |
| outputTokenSupply        | BigInt                  | Total supply of output token                         |
| outputTokenPriceUSD      | BigDecimal              | Price per share of output token in USD               |
| pricePerShare            | BigDecimal              | Amount of input token per full share of output token |
| volumeUSD                | BigDecimal              | Volume in USD                                        |
| volumeToken0             | BigDecimal              | Volume of token0                                     |
| volumeToken1             | BigDecimal              | Volume of token1                                     |
| blockNumber              | BigInt                  | Block number of this snapshot                        |
| timestamp                | BigInt                  | Timestamp of this snapshot                           |
| lowerTick                | BigInt                  | Lower price tick of current position                 |
| upperTick                | BigInt                  | Upper price tick of current position                 |
| tickChanges              | \[KodiakStrategyChange] | Array of strategy changes                            |
| \_baseLowerTick          | BigInt                  | Base lower tick                                      |
| \_baseUpperTick          | BigInt                  | Base upper tick                                      |

#### Entity Relationships

The Kodiak Islands subgraph entities have the following key relationships:

1. **Protocol to Vaults**: One-to-many relationship where KodiakIslandProtocol has multiple KodiakVault entities.
2. **Vaults to Events**: One-to-many relationship where each KodiakVault can have multiple deposit and withdrawal events.
3. **Vaults to Snapshots**: One-to-many relationship where each KodiakVault has multiple daily and hourly snapshots.
4. **Protocol to Snapshots**: One-to-many relationship where the protocol has multiple usage and financial snapshots.
5. **Vault to APR**: One-to-one relationship where each vault has associated APR data.

This comprehensive entity structure allows for detailed tracking of all aspects of the Kodiak Islands protocol and its activities.


# Query Guide

### Introduction

This guide provides examples and best practices for querying the Kodiak Islands subgraph using GraphQL. Whether you're building a dashboard, analysis tool, or integrating with another application, these queries will help you extract the data you need.

#### Getting Started

To query the Kodiak Islands subgraph, you'll need to:

1. Know the subgraph endpoint URL ([sugraph-endpoint](https://api.goldsky.com/api/public/project_clpx84oel0al201r78jsl0r3i/subgraphs/kodiak-v3-berachain-mainnet/latest/gn))
2. Have a basic understanding of GraphQL query syntax
3. Use a GraphQL client (like Apollo Client) or make HTTP requests to the endpoint

#### Basic Query Structure

All GraphQL queries for the Kodiak Islands subgraph follow this basic structure:

```graphql
query {
  entity(where: { filter conditions }) {
    field1
    field2
    nestedEntity {
      nestedField1
      nestedField2
    }
  }
}
```

#### Common Query Examples

**1. Protocol Overview**

Get basic information about the protocol:

```graphql
query {
  kodiakIslandProtocols {
    id
    totalValueLockedUSD
    cumulativeTotalFeesUSD
    totalPoolCount
  }
}
```

**2. List All Vaults**

Retrieve all vaults with basic information:

```graphql
query {
  kodiakVaults(first: 100) {
    id
    name
    symbol
    totalValueLockedUSD
    inputToken {
      id
      symbol
      decimals
    }
    outputToken {
      id
      symbol
      decimals
    }
    manager
    managerFee
    createdTimestamp
  }
}
```

**3. Get Vault Details**

Get detailed information about a specific vault:

```graphql
query {
  kodiakVault(id: "0x1234567890abcdef1234567890abcdef12345678") {
    id
    name
    symbol
    totalValueLockedUSD
    cumulativeTotalFeesUSD
    cumulativeLpFeesUSD
    cumulativeManagerFeesUSD
    inputTokenBalance
    outputTokenSupply
    pricePerShare
    volumeUSD
    weeklyVolumeUSD
    weeklyFeesEarnedUSD
    lowerTick
    upperTick
    apr {
      averageApr
    }
    _token0 {
      symbol
    }
    _token1 {
      symbol
    }
    _token0Amount
    _token1Amount
    _token0AmountUSD
    _token1AmountUSD
  }
}
```

**4. Recent Deposits**

Query recent deposit events for a specific vault:

```graphql
query {
  kodiakDeposits(
    first: 10
    orderBy: timestamp
    orderDirection: desc
    where: { vault: "0x1234567890abcdef1234567890abcdef12345678" }
  ) {
    id
    timestamp
    from
    amount
    amountUSD
    amount0
    amount1
  }
}
```

**5. Recent Withdrawals**

Query recent withdrawal events for a specific vault:

```graphql
query {
  kodiakWithdraws(
    first: 10
    orderBy: timestamp
    orderDirection: desc
    where: { vault: "0x1234567890abcdef1234567890abcdef12345678" }
  ) {
    id
    timestamp
    to
    amount
    amountUSD
  }
}
```

**6. Daily Vault Performance**

Query daily snapshots for a vault to analyze performance over time:

```graphql
query {
  kodiakVaultDailySnapshots(
    first: 30
    orderBy: timestamp
    orderDirection: desc
    where: { vault: "0x1234567890abcdef1234567890abcdef12345678" }
  ) {
    id
    timestamp
    totalValueLockedUSD
    dailyTotalFeesUSD
    dailyLpFeesUSD
    dailyManagerFeesUSD
    volumeUSD
    volumeToken0
    volumeToken1
    apr
    pricePerShare
    lowerTick
    upperTick
  }
}
```

**7. Protocol Usage Metrics**

Query daily protocol usage metrics:

```graphql
query {
  kodiakUsageMetricsDailySnapshots(
    first: 30
    orderBy: timestamp
    orderDirection: desc
  ) {
    id
    timestamp
    dailyActiveUsers
    cumulativeUniqueUsers
    dailyTransactionCount
    dailyDepositCount
    dailyWithdrawCount
    totalPoolCount
  }
}
```

**8. Protocol Financial Metrics**

Query daily protocol financial metrics:

```graphql
query {
  kodiakFinancialsDailySnapshots(
    first: 30
    orderBy: timestamp
    orderDirection: desc
  ) {
    id
    timestamp
    totalValueLockedUSD
    dailyLpFeesUSD
    dailyManagerFeesUSD
    dailyTotalFeesUSD
  }
}
```

**9. Strategy Changes**

Track strategy changes for a specific vault:

```graphql
query {
  kodiakStrategyChanges(
    first: 20
    orderBy: timestamp
    orderDirection: desc
    where: { vault: "0x1234567890abcdef1234567890abcdef12345678" }
  ) {
    id
    timestamp
    lowerTick
    upperTick
  }
}
```

**10. Vault APR History**

Query APR history for a vault:

```graphql
query {
  kodiakVaultDailySnapshots(
    first: 90
    orderBy: timestamp
    orderDirection: desc
    where: { vault: "0x1234567890abcdef1234567890abcdef12345678" }
  ) {
    timestamp
    apr
  }
}
```

#### Filtering and Sorting

**Time-Based Filtering**

Filter snapshots within a specific time range:

```graphql
query {
  kodiakVaultDailySnapshots(
    where: {
      timestamp_gte: "1640995200" # Jan 1, 2022
      timestamp_lt: "1672531200"  # Jan 1, 2023
    }
  ) {
    timestamp
    totalValueLockedUSD
    dailyTotalFeesUSD
  }
}
```

**Value-Based Filtering**

Filter vaults by TVL:

```graphql
query {
  kodiakVaults(
    where: {
      totalValueLockedUSD_gt: "1000000" # > $1M TVL
    }
  ) {
    id
    name
    totalValueLockedUSD
  }
}
```

**Sorting Results**

Sort vaults by TVL in descending order:

```graphql
query {
  kodiakVaults(
    orderBy: totalValueLockedUSD
    orderDirection: desc
  ) {
    id
    name
    totalValueLockedUSD
  }
}
```

#### Pagination

For large result sets, use pagination with `first` and `skip`:

```graphql
query {
  kodiakVaults(
    first: 20  # Get 20 records
    skip: 20   # Skip first 20 records (for page 2)
    orderBy: totalValueLockedUSD
    orderDirection: desc
  ) {
    id
    name
    totalValueLockedUSD
  }
}
```

#### Advanced Queries

**Get User Activity Across Vaults**

Find all deposits and withdrawals for a specific user:

```graphql
query {
  deposits: kodiakDeposits(
    where: { from: "0xuser_address_here" }
  ) {
    timestamp
    vault {
      id
      name
    }
    amountUSD
  }
  withdraws: kodiakWithdraws(
    where: { to: "0xuser_address_here" }
  ) {
    timestamp
    vault {
      id
      name
    }
    amountUSD
  }
}
```

**Compare Multiple Vaults**

Compare performance metrics for multiple vaults:

```graphql
query {
  vault1: kodiakVault(id: "0xvault1_address_here") {
    id
    name
    totalValueLockedUSD
    weeklyFeesEarnedUSD
    apr {
      averageApr
    }
  }
  vault2: kodiakVault(id: "0xvault2_address_here") {
    id
    name
    totalValueLockedUSD
    weeklyFeesEarnedUSD
    apr {
      averageApr
    }
  }
}
```

#### Best Practices

1. **Query Only What You Need**: Only request the fields you actually need to minimize response size.
2. **Use Pagination**: For large collections, always use pagination to prevent timeouts.
3. **Filter Efficiently**: Apply filters at the query level rather than filtering results in your application.
4. **Optimize Sorting**: Sort at the query level for better performance.
5. **Cache Results**: GraphQL responses are highly cacheable. Implement client-side caching for better performance.
6. **Handle Time Data Correctly**: Remember that timestamps are in seconds since Unix epoch.

#### Error Handling

The subgraph may return errors for various reasons:

* Invalid query syntax
* Non-existent entities or fields
* Server timeouts for complex queries

Always implement proper error handling in your application to handle these cases gracefully.

#### Real-World Use Cases

**Building a Dashboard**

For a vault performance dashboard, you might combine protocol metrics with vault-specific data:

```graphql
query DashboardData {
  protocol: kodiakIslandProtocols(first: 1) {
    totalValueLockedUSD
    totalPoolCount
  }
  vaults: kodiakVaults(
    first: 10
    orderBy: totalValueLockedUSD
    orderDirection: desc
  ) {
    id
    name
    totalValueLockedUSD
    apr {
      averageApr
    }
  }
  recentActivity: kodiakDeposits(
    first: 5
    orderBy: timestamp
    orderDirection: desc
  ) {
    timestamp
    vault {
      name
    }
    amountUSD
  }
}
```

**Historical Analysis**

For analyzing a vault's performance over time:

```graphql
query VaultHistoricalAnalysis($vaultId: ID!, $days: Int!) {
  dailySnapshots: kodiakVaultDailySnapshots(
    first: $days
    orderBy: timestamp
    orderDirection: desc
    where: { vault: $vaultId }
  ) {
    timestamp
    totalValueLockedUSD
    dailyTotalFeesUSD
    dailyLpFeesUSD
    dailyManagerFeesUSD
    volumeUSD
    apr
  }
}
```

With these query examples and best practices, you should be well-equipped to extract valuable data from the Kodiak Islands subgraph for your applications.


# Advanced Usage Guide

This guide covers advanced topics and strategies for working with the Kodiak Islands subgraph, including complex querying patterns, integration strategies, performance optimization, and custom analytics.

#### Complex Querying Patterns

**Fragment Reuse**

For complex applications that frequently query similar fields, use GraphQL fragments to reduce duplication:

```graphql
fragment VaultBasicInfo on KodiakVault {
  id
  name
  symbol
  totalValueLockedUSD
  apr {
    averageApr
  }
}

fragment VaultDetailedInfo on KodiakVault {
  ...VaultBasicInfo
  inputToken {
    symbol
    decimals
  }
  outputToken {
    symbol
    decimals
  }
  pricePerShare
  _token0Amount
  _token1Amount
  _token0AmountUSD
  _token1AmountUSD
}

query {
  topVaults: kodiakVaults(
    first: 5
    orderBy: totalValueLockedUSD
    orderDirection: desc
  ) {
    ...VaultBasicInfo
  }
  
  specificVault: kodiakVault(id: "0x1234567890abcdef") {
    ...VaultDetailedInfo
  }
}
```

**Dynamic Querying with Variables**

Use GraphQL variables for dynamic queries:

```graphql
query GetVaultPerformance($vaultId: ID!, $startTime: BigInt!, $endTime: BigInt!) {
  snapshots: kodiakVaultDailySnapshots(
    where: {
      vault: $vaultId
      timestamp_gte: $startTime
      timestamp_lte: $endTime
    }
    orderBy: timestamp
  ) {
    timestamp
    totalValueLockedUSD
    dailyTotalFeesUSD
    apr
  }
}
```

This query can be executed with variables:

```json
{
  "vaultId": "0x1234567890abcdef",
  "startTime": "1640995200",
  "endTime": "1672531200"
}
```

**Advanced Filtering Combinations**

Combine multiple filters for complex data selection:

```graphql
query HighPerformingVaults {
  kodiakVaultDailySnapshots(
    where: {
      apr_gt: "20"                      # APR > 20%
      totalValueLockedUSD_gt: "500000"  # TVL > $500,000
      dailyTotalFeesUSD_gt: "1000"      # Daily fees > $1,000
      timestamp_gt: "1648771200"        # After April 1, 2022
    }
    orderBy: apr
    orderDirection: desc
  ) {
    vault {
      id
      name
    }
    timestamp
    apr
    totalValueLockedUSD
    dailyTotalFeesUSD
  }
}
```

#### Time Series Analysis

**Calculating Period-over-Period Changes**

To calculate weekly changes in vault performance:

```graphql
query WeeklyPerformanceChange($vaultId: ID!) {
  thisWeek: kodiakVaultDailySnapshots(
    first: 7
    orderBy: timestamp
    orderDirection: desc
    where: { vault: $vaultId }
  ) {
    timestamp
    totalValueLockedUSD
    dailyTotalFeesUSD
    volumeUSD
    apr
  }
  
  previousWeek: kodiakVaultDailySnapshots(
    first: 7
    skip: 7
    orderBy: timestamp
    orderDirection: desc
    where: { vault: $vaultId }
  ) {
    timestamp
    totalValueLockedUSD
    dailyTotalFeesUSD
    volumeUSD
    apr
  }
}
```

With this data, you can calculate week-over-week changes for key metrics in your application:

```typescript
function calculateChangePercentage(current: number, previous: number): number {
  if (previous === 0) return 0;
  return ((current - previous) / previous) * 100;
}

// Calculate aggregate values for each week
const thisWeekTVL = average(thisWeekData.map(d => parseFloat(d.totalValueLockedUSD)));
const prevWeekTVL = average(previousWeekData.map(d => parseFloat(d.totalValueLockedUSD)));

const thisWeekFees = sum(thisWeekData.map(d => parseFloat(d.dailyTotalFeesUSD)));
const prevWeekFees = sum(previousWeekData.map(d => parseFloat(d.dailyTotalFeesUSD)));

// Calculate percentage changes
const tvlChange = calculateChangePercentage(thisWeekTVL, prevWeekTVL);
const feesChange = calculateChangePercentage(thisWeekFees, prevWeekFees);
```

**Analyzing APR Trends**

Track APR trends over longer periods to identify patterns:

```graphql
query AprTrends($vaultId: ID!) {
  daily: kodiakVaultDailySnapshots(
    first: 90  # Last 90 days
    orderBy: timestamp
    orderDirection: desc
    where: { vault: $vaultId }
  ) {
    timestamp
    apr
    totalValueLockedUSD
  }
}
```

You can use this data to:

* Calculate moving averages (7-day, 30-day)
* Identify seasonal patterns
* Correlate APR changes with TVL or other metrics
* Build predictive models for APR forecasting

#### Integration Strategies

**Real-time Data Updates**

For applications requiring real-time data, implement a polling strategy:

```typescript
// Fetch latest vault data every 60 seconds
function setupPolling(vaultId: string) {
  const query = `
    query GetVaultData($id: ID!) {
      kodiakVault(id: $id) {
        totalValueLockedUSD
        pricePerShare
        apr {
          averageApr
        }
      }
    }
  `;
  
  setInterval(() => {
    executeQuery(query, { id: vaultId })
      .then(data => updateUI(data.kodiakVault))
      .catch(error => handleError(error));
  }, 60000);
}
```

**Combining with On-chain Data**

For some advanced use cases, you may need to combine subgraph data with direct on-chain calls:

```typescript
async function getCompleteVaultData(vaultId: string) {
  // Get historical and aggregated data from subgraph
  const subgraphData = await fetchFromSubgraph(vaultId);
  
  // Get real-time position data from the blockchain
  const provider = new ethers.providers.JsonRpcProvider(RPC_URL);
  const vaultContract = new ethers.Contract(vaultId, VAULT_ABI, provider);
  const currentPosition = await vaultContract.getCurrentPosition();
  
  // Combine the data
  return {
    ...subgraphData,
    currentPosition: {
      lowerTick: currentPosition.lowerTick.toString(),
      upperTick: currentPosition.upperTick.toString(),
      liquidity: currentPosition.liquidity.toString()
    }
  };
}
```

**Building Custom Analytics**

Create custom analytics by combining multiple queries:

```typescript
async function vaultPerformanceAnalytics(vaultId: string) {
  // Fetch basic vault info
  const vaultInfo = await fetchVaultInfo(vaultId);
  
  // Fetch historical data
  const dailyData = await fetchDailySnapshots(vaultId, 90); // Last 90 days
  
  // Fetch user activity
  const deposits = await fetchDeposits(vaultId);
  const withdrawals = await fetchWithdrawals(vaultId);
  
  // Calculate custom metrics
  const userRetentionRate = calculateUserRetention(deposits, withdrawals);
  const volatilityScore = calculateVolatility(dailyData.map(d => d.apr));
  const performanceScore = calculatePerformanceScore(
    vaultInfo.apr.averageApr,
    volatilityScore,
    userRetentionRate
  );
  
  return {
    vaultInfo,
    userRetentionRate,
    volatilityScore,
    performanceScore,
    dailyTrends: processDailyTrends(dailyData)
  };
}
```

#### Performance Optimization

**Query Optimization**

Optimize your queries to reduce response time and load on the subgraph:

1. **Select only necessary fields**:

   ```graphql
   # Instead of this
   {
     kodiakVaults {
       id
       name
       symbol
       # ... many more fields
     }
   }

   # Do this
   {
     kodiakVaults {
       id
       name
       totalValueLockedUSD
       # Only the fields you need
     }
   }
   ```
2. **Limit result sizes**:

   ```graphql
   {
     kodiakVaults(first: 20) {
       # fields
     }
   }
   ```
3. **Use efficient filtering**:

   ```graphql
   # Instead of fetching all and filtering client-side
   {
     kodiakVaults(where: { totalValueLockedUSD_gt: "1000000" }) {
       # fields
     }
   }
   ```

**Client-Side Caching**

Implement caching to reduce redundant queries:

```typescript
// Simple in-memory cache example
const cache = new Map();

async function fetchWithCache(query, variables, maxAge = 60000) {
  const cacheKey = JSON.stringify({ query, variables });
  
  if (cache.has(cacheKey)) {
    const { data, timestamp } = cache.get(cacheKey);
    if (Date.now() - timestamp < maxAge) {
      return data;
    }
  }
  
  const result = await executeQuery(query, variables);
  cache.set(cacheKey, {
    data: result,
    timestamp: Date.now()
  });
  
  return result;
}
```

**Batching Queries**

For applications that need multiple related pieces of data, batch your queries:

```graphql
query BatchedData($vaultId: ID!) {
  vault: kodiakVault(id: $vaultId) {
    id
    name
    totalValueLockedUSD
    apr {
      averageApr
    }
  }
  
  recentDeposits: kodiakDeposits(
    first: 5,
    orderBy: timestamp,
    orderDirection: desc,
    where: { vault: $vaultId }
  ) {
    timestamp
    amountUSD
  }
  
  dailyStats: kodiakVaultDailySnapshots(
    first: 7,
    orderBy: timestamp,
    orderDirection: desc,
    where: { vault: $vaultId }
  ) {
    timestamp
    dailyTotalFeesUSD
  }
}
```

#### Advanced Use Cases

**Strategy Analysis**

Analyze the effectiveness of different vault strategies by tracking changes to tick ranges:

```graphql
query StrategyEffectiveness($vaultId: ID!) {
  # Get all snapshots and process client-side
  snapshots: kodiakVaultDailySnapshots(
    orderBy: timestamp
    where: { vault: $vaultId }
  ) {
    timestamp
    lowerTick
    upperTick
    # If tickChanges is available in your snapshots, include it
    tickChanges {
      timestamp
      lowerTick
      upperTick
    }
    dailyTotalFeesUSD
    apr
  }
}
```

This data can be used to:

* Compare APR before and after strategy changes
* Identify optimal tick ranges for different market conditions
* Evaluate the effectiveness of strategy adjustments

**Portfolio Analysis**

For users with positions across multiple vaults, build portfolio analytics:

```graphql
query UserPortfolio($userAddress: String!) {
  # Get all user deposits
  deposits: kodiakDeposits(
    where: { from: $userAddress }
    orderBy: timestamp
  ) {
    vault {
      id
      name
      _token0 { 
        symbol 
      }
      _token1 { 
        symbol 
      }
    }
    timestamp
    amount
    amountUSD
  }
  
  # Get all user withdrawals
  withdrawals: kodiakWithdraws(
    where: { to: $userAddress }
    orderBy: timestamp
  ) {
    vault {
      id
      name
    }
    timestamp
    amount
    amountUSD
  }
}
```

With this data, you can:

* Calculate user's net position in each vault
* Estimate their portfolio value over time
* Calculate portfolio-wide performance metrics

**Vault Comparison Tool**

Build a tool to compare performance across vaults:

```graphql
query CompareVaults($vaultIds: [ID!]!) {
  vaults: kodiakVaults(
    where: { id_in: $vaultIds }
  ) {
    id
    name
    _token0 { 
      symbol 
    }
    _token1 { 
      symbol 
    }
    totalValueLockedUSD
    apr { 
      averageApr 
    }
    weeklyFeesEarnedUSD
  }
  
  # Get daily performance for each vault (last 30 days)
  dailyPerformance: kodiakVaultDailySnapshots(
    first: 30
    orderBy: timestamp
    orderDirection: desc
    where: { vault_in: $vaultIds }
  ) {
    vault { 
      id 
    }
    timestamp
    apr
    dailyTotalFeesUSD
    totalValueLockedUSD
  }
}
```

#### Working with Time Series Data

When working with time series data from the Kodiak Islands subgraph, consider these strategies:

1. **Handling Missing Data Points**: Daily and hourly snapshots may have missing data points. Implement interpolation strategies in your application to handle these gaps.
2. **Normalizing Timestamps**: Convert Unix timestamps to your local timezone for display:

   ```typescript
   function formatTimestamp(unixTimestamp) {
     return new Date(unixTimestamp * 1000).toLocaleString();
   }
   ```
3. **Grouping Data**: For longer time ranges, group data into periods (weekly, monthly):

   ```typescript
   function groupDataByWeek(dailyData) {
     const weeklyData = {};
     dailyData.forEach(day => {
       const weekNumber = getWeekNumber(day.timestamp);
       if (!weeklyData[weekNumber]) {
         weeklyData[weekNumber] = {
           totalFeesUSD: 0,
           avgTVL: 0,
           daysCount: 0
         };
       }
       weeklyData[weekNumber].totalFeesUSD += parseFloat(day.dailyTotalFeesUSD);
       weeklyData[weekNumber].avgTVL += parseFloat(day.totalValueLockedUSD);
       weeklyData[weekNumber].daysCount += 1;
     });
     
     // Calculate averages
     Object.keys(weeklyData).forEach(week => {
       weeklyData[week].avgTVL /= weeklyData[week].daysCount;
     });
     
     return weeklyData;
   }
   ```

#### Conclusion

This advanced guide has covered complex querying patterns, integration strategies, performance optimization, and various use cases for the Kodiak Islands subgraph. By leveraging these techniques, you can build sophisticated applications that provide powerful insights into the Kodiak Islands protocol and its vaults.

Remember that subgraph queries can be resource-intensive, so always optimize your queries and implement appropriate caching strategies. For very large-scale applications, consider implementing additional middleware to handle complex data processing and caching.

For any questions or issues with the subgraph, refer to the official Kodiak Islands documentation or contact the protocol team for support.


# Smart Contract Reference

## Overview

Kodiak Islands are Automated Liquidity Managers that abstract away all the complexities of liquidity provisioning to a Kodiak v3 pool while also maximising the fee returns. Users can provide liquidity to their favourite Kodiak v3 pools and get fungible receipt ERC-20 tokens that represent their share of the liquidity provided by the island.

## Core Architecture

There are 3 main smart contracts that help create new islands one of them handles creation of new islands, the other is island itself and thirdly a router that helps with provisioning liquidity to these islands securely.

### 1. Kodiak Island Factory

The KodiakIslandFactory contract is responsible for deploying and managing instances of KodiakIsland vaults. This factory contract is designed to be non-upgradeable, and it deploys KodiakIsland vaults as ERC1967 minimal clones. Each factory maintains only one island implementation at a time and deploys clones of that implementation.

### **2. Kodiak Island**

Kodiak Islands are ERC20-wrapped Kodiak V3 positions that enable simplified liquidity provision through a fungible token interface. When users add liquidity to an Island, they receive Kodiak Island tokens representing their proportional ownership of the underlying Kodiak V3 position. These tokens can be freely transferred, traded, or redeemed for the underlying assets at any time. For more info visit the kodiakIslands section of documentation or the smart contract reference

### **3. Island Router**

The IslandRouter contract serves as a helper contract for users to easily provide liquidity to Kodiak Islands. It handles the complexities of depositing tokens, slippage protection, and token swaps when needed, while ensuring optimal liquidity provision.


# Kodiak Island Factory

The core factory contract that manages deploying new islands and central shared setting between these islands for permission-less islands

## Deploying New Islands

```solidity
function deployVault(
    address tokenA,
    address tokenB,
    uint24 uniFee,
    address manager,
    address managerTreasury,
    uint16 managerFee,
    int24 lowerTick,
    int24 upperTick
) external returns (address island)
```

Creates a new Kodiak Island using these parameters. Get the tokens and fee tier for the pool you want to deploy the island for.

Deployment process - The tokens are sorted and the kodiak pool is fetched, if the kodiak pool does not exist it throws an error.

**Parameters:**

* `tokenA`: First token in the pool pair
* `tokenB`: Second token in the pool pair
* `uniFee`: Underlying pool fee tier (eg: 100, 500, 3000, 10000)
* `manager`: Manager address (0x0 for unmanaged/permisionless islands)
* `managerTreasury`: The address that will receive the manager's fee share
* `managerFee`: Manager fee in basis points (0 - 10000)
* `lowerTick`: lower tick of the island's position
* `upperTick`: upper tick of the islnad's position

**Returns**:

* island (address): The address of the newly deployed KodiakIsland vault.

**Deployment** **Process**:

* The function sorts the tokens (tokenA, tokenB) to ensure consistent ordering.
* It fetches the corresponding Kodiak V3 pool address using the provided tokens and fee tier.
* It validates that the Kodiak V3 pool exists and that the provided ticks align with the pool's tick spacing.
* It clones the islandImplementation contract to create a new KodiakIsland vault.
* It initializes the new vault with the provided parameters.
* It adds the deployer to the list of deployers and the island to the list of islands deployed by the manager.

**Emits**: `IslandCreated` on successful deployment

```solidity
event IslandCreated(address indexed uniPool, address indexed manager, address indexed island, address implementation);
```

### Requirements for deploying a permissionless Island

1. The `manager` address must be set to zero address.
2. The `managerTreasury` must be set to zero address.
3. The `managerFee` must be set to 0.
4. The deployed island refers the `managerFee` and `managerTreasury` from the factory for permissionless islands

## Querying Deployed Islands and related data

**Get All Deployers**

```solidity
function getDeployers() public view returns (address[] memory)
```

Returns array of all addresses that have deployed at least one island.

Returns:

* `address[]`: Array of deployer addresses

**Get Islands by Deployer**

```solidity
function getIslands(address deployer) public view returns (address[] memory islands)
```

Returns array of all islands deployed by a specific address.

Parameters:

* `deployer`: Address to query islands for

Returns:

* `islands`: Array of island addresses deployed by specified deployer
* Returns empty array if no islands deployed

**Count Functions**

```solidity
function numIslands() public view returns (uint256)
```

Returns total number of islands deployed through factory.

```solidity
function numDeployers() public view returns (uint256)
```

Returns total number of unique deployer addresses.

```solidity
function numIslands(address deployer) public view returns (uint256)
```

Returns number of islands deployed by specific address.

Parameters:

* `deployer`: Address to query island count for

## Factory Management

Only the factory owner can call these functions.

**Set Island Implementation**

```solidity
function setIslandImplementation(address _implementation) external
```

Updates the implementation contract used for new island deployments.

Parameters:

* `_implementation`: Address of new implementation contract
  * Must be non-zero address
  * Must be a valid KodiakIsland contract

Requirements:

* Caller must be factory owner
* Implementation address cannot be zero

Emits: `UpdateIslandImplementation(address implementation)`

**Set Treasury**

```solidity
function setTreasury(address _treasury) external
```

Updates the treasury address that receives protocol fees.

Parameters:

* `_treasury`: New treasury address
  * Must be non-zero address
  * Will receive protocol fees from permissionless islands

Requirements:

* Caller must be factory owner
* Treasury address cannot be zero

Emits: `TreasurySet(address treasury)`

**Set Island Fee**

```solidity
function setIslandFee(uint16 _islandFee) external
```

Updates the protocol fee for permissionless islands.

Parameters:

* `_islandFee`: New protocol fee in basis points
  * Must be between 0-2000 (0-20%)
  * Applied to all permissionless islands

Requirements:

* Caller must be factory owner
* Fee cannot exceed 2000 (20%)

Emits: `IslandFeeSet(uint16 islandFee)`

## ABI

```json
[
        {
            "type": "function",
            "name": "deployVault",
            "inputs": [
                {
                    "name": "tokenA",
                    "type": "address",
                    "internalType": "address"
                },
                {
                    "name": "tokenB",
                    "type": "address",
                    "internalType": "address"
                },
                {
                    "name": "uniFee",
                    "type": "uint24",
                    "internalType": "uint24"
                },
                {
                    "name": "manager",
                    "type": "address",
                    "internalType": "address"
                },
                {
                    "name": "managerTreasury",
                    "type": "address",
                    "internalType": "address"
                },
                {
                    "name": "managerFee",
                    "type": "uint16",
                    "internalType": "uint16"
                },
                {
                    "name": "lowerTick",
                    "type": "int24",
                    "internalType": "int24"
                },
                {
                    "name": "upperTick",
                    "type": "int24",
                    "internalType": "int24"
                }
            ],
            "outputs": [
                {
                    "name": "island",
                    "type": "address",
                    "internalType": "address"
                }
            ],
            "stateMutability": "nonpayable"
        },
        {
            "type": "function",
            "name": "islandFee",
            "inputs": [],
            "outputs": [
                {
                    "name": "",
                    "type": "uint16",
                    "internalType": "uint16"
                }
            ],
            "stateMutability": "view"
        },
        {
            "type": "function",
            "name": "islandImplementation",
            "inputs": [],
            "outputs": [
                {
                    "name": "",
                    "type": "address",
                    "internalType": "address"
                }
            ],
            "stateMutability": "view"
        },
        {
            "type": "function",
            "name": "setIslandImplementation",
            "inputs": [
                {
                    "name": "newImplementation",
                    "type": "address",
                    "internalType": "address"
                }
            ],
            "outputs": [],
            "stateMutability": "nonpayable"
        },
        {
            "type": "function",
            "name": "treasury",
            "inputs": [],
            "outputs": [
                {
                    "name": "",
                    "type": "address",
                    "internalType": "address"
                }
            ],
            "stateMutability": "view"
        },
        {
            "type": "event",
            "name": "IslandCreated",
            "inputs": [
                {
                    "name": "uniPool",
                    "type": "address",
                    "indexed": true,
                    "internalType": "address"
                },
                {
                    "name": "manager",
                    "type": "address",
                    "indexed": true,
                    "internalType": "address"
                },
                {
                    "name": "island",
                    "type": "address",
                    "indexed": true,
                    "internalType": "address"
                },
                {
                    "name": "implementation",
                    "type": "address",
                    "indexed": false,
                    "internalType": "address"
                }
            ],
            "anonymous": false
        },
        {
            "type": "event",
            "name": "IslandFeeSet",
            "inputs": [
                {
                    "name": "fee",
                    "type": "uint16",
                    "indexed": false,
                    "internalType": "uint16"
                }
            ],
            "anonymous": false
        },
        {
            "type": "event",
            "name": "TreasurySet",
            "inputs": [
                {
                    "name": "treasury",
                    "type": "address",
                    "indexed": true,
                    "internalType": "address"
                }
            ],
            "anonymous": false
        },
        {
            "type": "event",
            "name": "UpdateIslandImplementation",
            "inputs": [
                {
                    "name": "newImplementation",
                    "type": "address",
                    "indexed": false,
                    "internalType": "address"
                }
            ],
            "anonymous": false
        }
    ]
```


# Kodiak Island

The implementation of kodiak Island contract

The Kodiak Island contracts provide a framework for creating and managing concentrated liquidity positions on Kodiak V3. They enable users to deposit tokens into a managed Kodiak V3 position, receiving shares in return. They allow managers to rebalance the position, collect fees, and adjust the position and management parameters. The contracts support minting, burning, rebalancing, and integration with external routers for complex strategies.

## Adding/Removing Liquidity

These functions are used to mint/burn island shares resulting in adding/removing liquidity from the island's underlying v3 pool position. It is highly recommended to use the [Island Router](https://app.gitbook.com/o/XDFALXDrtEzw6m888LZh/s/OSwqNrRJ9Xh6jO57yoLm/~/changes/39/developers/kodiak-islands/smart-contract-reference/kodiak-island-router) to add/remove liquidity as it handles slippage settings.

#### Adding Liquidity

```solidity
function mint(
    uint256 mintAmount,
    address receiver
) external returns (
    uint256 amount0,
    uint256 amount1,
    uint128 liquidityMinted
)
```

Mints new Island tokens by providing liquidity to the underlying Kodiak V3 position.

* `mintAmount`: Number of Island tokens to mint
* `receiver`: Address to receive the minted tokens
* Returns amounts of token0/token1 used and liquidity added

#### Removing Liquidity

```solidity
function burn(
    uint256 burnAmount,
    address receiver
) external returns (
    uint256 amount0,
    uint256 amount1,
    uint128 liquidityBurned
)
```

Burns Island tokens to withdraw underlying assets.

* `burnAmount`: Number of Island tokens to burn
* `receiver`: Address to receive the underlying tokens
* Returns amounts of token0/token1 received and liquidity removed

#### Compounding collected fee

```solidity
function rebalance() external {}
```

Collects the fee earned by the island's position and reinvests as much of token0 and token1 into the position as possible after deducting the manager fee from the collected fee.

## View Functions

**Get Underlying Balances**

```solidity
function getUnderlyingBalances() external view returns (
    uint256 amount0Current,
    uint256 amount1Current
)
```

Returns:

* `amount0Current`: The total amounts of underlying tokens represented by the entire Island supply. This includes deployed liqudity (uni v3 pool tokens), any unclaimed earned fee, and any undeployed tokens
* `amount1Current`: The total amounts of underlying tokens represented by the entire Island supply. This includes deployed liqudity (uni v3 pool tokens), any unclaimed earned fee, and any undeployed tokens resulting from fee imbalance

**Get Mint Amounts**

```solidity
function getMintAmounts(
    uint256 amount0Max,
    uint256 amount1Max
) external view returns (
    uint256 amount0,
    uint256 amount1,
    uint256 mintAmount
)
```

This function allows you to find the optimal deposit amounts for token0 and token1 in correct ratio to deposit maximally into the underlying island position Arguments:

* `amount0Max`: Max amount of token0 the user is willing to deposit
* `amount1Max`: Max amount of token1 the user is willing to deposit Returns:
* `amount0`: The amount of token0 used from the max
* `amount1`: The amount of token1 used from the max
* `mintAmount`: The number of island tokens minted using amount0 and amount1

**Get Underlying Balances At Price**

```solidity
function getUnderlyingBalancesAtPrice(
    uint160 sqrtRatioX96
) external view returns (
    uint256 amount0Current,
    uint256 amount1Current
)
```

This function calculates the underlying token balances at a specific price point Arguments:

* `sqrtRatioX96`: The sqrt price to calculate balances at, in Q96 format Returns:
* `amount0Current`: Amount of token0 at the specified price
* `amount1Current`: Amount of token1 at the specified price

**Get Position ID**

```solidity
function getPositionID() external view returns (bytes32 positionID)
```

Returns the unique identifier for the current Kodiak V3 position Returns:

* `positionID`: Keccak256 hash of packed (island address, lowerTick, upperTick)

**Get Token0**

```solidity
function token0() external view returns (IERC20)
```

Returns the address of token0

**Get Token1**

```solidity
function token1() external view returns (IERC20)
```

Returns the address of token1

**Get Upper Tick**

```solidity
function upperTick() external view returns (int24)
```

Returns the upper tick of the island's position

**Get Lower Tick**

```solidity
function lowerTick() external view returns (int24)
```

Returns the lower tick of the island's position

**Get Pool**

```solidity
function pool() external view returns (IUniswapV3Pool)
```

Returns the address of the Kodiak V3 pool

**Get Total Supply**

```solidity
function totalSupply() external view returns (uint256)
```

Returns the total supply of the island tokens

**Get Balance Of**

```solidity
function balanceOf(address account) external view returns (uint256)
```

Returns the balance of the specified account

**Get Manager Fee BPS**

```solidity
function managerFeeBPS() external view returns (uint16)
```

Returns the manager fee in basis points

**Get Manager Treasury**

```solidity
function managerTreasury() external view returns (address)
```

Returns the manager treasury address

**Get Manager Balance 0**

```solidity
function managerBalance0() external view returns (uint256)
```

Returns the manager balance of token0

**Get Manager Balance 1**

```solidity
function managerBalance1() external view returns (uint256)
```

Returns the manager balance of token1

**Get Manager**

```solidity
function manager() external view returns (address)
```

Returns the current manager address. Should be address(0) for unmanaged islands

## Island Management

This is applicable only for managed islands. Permissionless islands only expose the functionality to compound the fee collected.

### Admin roles involved

* `manager` - can alter island position bounds to manage liquidity optimally
* `pauser` - can pause operations in case of a security breach

### Island Configuration Parameters

**Manager Parameters**

* `manager`: The address authorized to perform management operations like rebalancing
* `managerTreasury`: Address where manager fees are sent
* `managerFeeBPS`: Percentage of earned fees that go to the manager (in basis points, max 10000)
* `restrictedMint`: When true, only the manager can mint new Island tokens
* `compounderSlippageBPS`: Maximum allowed slippage for rebalance operations (in basis points)
* `compounderSlippageInterval`: Time window for TWAP price calculation using kodiak pool observations (in seconds)

**Island Position Parameters**

* `lowerTick`: Lower price bound of the Kodiak V3 position
* `upperTick`: Upper price bound of the Kodiak V3 position
* `pool`: The underlying Kodiak V3 pool address
* `token0`: First token in the uni pool pair
* `token1`: Second token in the uni pool pair

**Manager Fee**

For active management of the island, the manager fee is collected from the UniV3 earned fees. For Kodiak team managed islands the manager fee is 0.

* Fee = (Total Fees Earned \* managerFeeBPS) / 10000
* Unmanaged/Permissionless Islands use the Island factory's default fee settings

**Restricted Minting**

When `restrictedMint` is enabled:

* Only the manager can mint new Island tokens
* The first mint needs to atleast add INITIAL\_MINT amount of liquidity.After the first mint this liquidity is burned.

### Manager Functions

**Update Manager Parameters**

```solidity
function updateManagerParams(
    int16 newManagerFeeBPS,
    address newManagerTreasury,
    int16 newSlippageBPS,
    int32 newSlippageInterval
) external
```

Updates the manager configuration parameters for the island Arguments:

* `newManagerFeeBPS`: New manager fee in basis points (-1 to keep current)
* `newManagerTreasury`: New treasury address (address(0) to keep current)
* `newSlippageBPS`: New slippage tolerance in basis points (-1 to keep current)
* `newSlippageInterval`: New TWAP interval in seconds (-1 to keep current)

**Executive Rebalance**

```solidity
function executiveRebalance(
    int24 newLowerTick,
    int24 newUpperTick,
    uint160 swapThresholdPrice,
    uint256 swapAmountBPS,
    bool zeroForOne
) external
```

Rebalances the position by changing price range and optionally performing underlying pool swaps Arguments:

* `newLowerTick`: New lower price bound of the position
* `newUpperTick`: New upper price bound of the position
* `swapThresholdPrice`: Maximum/minimum price for the swap in sqrtPriceX96 for uni v3 slippage protection
* `swapAmountBPS`: Percentage of excess available tokens to swap in BPS
* `zeroForOne`: True to swap token0 for token1, false for opposite

Notes: In order to generate the parameters for an executive rebalance one has to understand the flow of this operation. First, the Kodiak island removes all the liquidity and fees earned. Then, it tries to deposit as much liquidity as possible around the new price range. Next, whatever is leftover is then swapped based on the swap parameters. Finally, another deposit of maximal liquidity to the position is attempted and any leftover sits in the contract balance waiting to be reinvested.

1. Call getUnderlyingBalances on the ArrakisVault to obtain amount0Current and amount1Current
2. Compute amount0Liquidity and amount1Liquidity using LiquidityAmounts.sol library, the new position bounds, the current price and the current amounts from step 1.
3. Compute amount0Leftover and amount1Leftover with formula amount0Leftover = amount0Current - amount0Liquidity. In most cases one of these values will be 0 (or very close to 0).
4. Use amount0Liquidity and amount1Liquidity to compute the current proportion of each asset needed.
5. Use the amount0Leftover and amount1Leftover and the proportion from previous step to compute which token to swap and the swapAmount.
6. Convert swapAmount to swapAmountBPS by doing swapAmount \* 10000 / amountLeftover for the token being swapped.

**Executive Rebalance With Router**

```solidity
function executiveRebalanceWithRouter(
    int24 newLowerTick,
    int24 newUpperTick,
    SwapData calldata swapData
) external
```

Rebalances using an external router for optimized swaps across all available liquidity. Arguments:

* `newLowerTick`: New lower price bound of the position
* `newUpperTick`: New upper price bound of the position
* `swapData`: Struct containing:
  * `router`: Address of whitelisted router to use
  * `amountIn`: Amount of tokens to swap
  * `minAmountOut`: Minimum tokens to receive
  * `zeroForOne`: Swap direction
  * `routeData`: Encoded swap route data

**Set Restricted Mint**

```solidity
function setRestrictedMint(bool _status) external
```

Restricts minting to only the manager address Arguments:

* `_status`: True to restrict minting, false to allow public minting

**Set Pauser**

```solidity
function setPauser(address _pauser, bool _status) external
```

Adds or removes an address from the pauser role Arguments:

* `_pauser`: Address to modify pauser status for
* `_status`: True to add as pauser, false to remove

**Pause/Unpause**

```solidity
function pause() external
function unpause() external
```

Emergency functions to pause/unpause all island operations

* `pause`: Can be called by manager or pauser
* `unpause`: Can only be called by manager

#### Fee Management

**Withdraw Manager Balance**

```solidity
function withdrawManagerBalance() external
```

Withdraws accumulated manager fees to the manager treasury

* Transfers all accumulated token0 and token1 fees
* Resets manager balance tracking to zero

**Sync To Factory**

```solidity
function syncToFactory() public
```

Updates unmanaged island parameters to match factory settings when updated.

* Updates manager treasury to factory treasury
* Updates manager fee to factory default fee
* Only affects islands with no active manager

## ABI

```json
[
    {
        "type": "function",
        "name": "DOMAIN_SEPARATOR",
        "inputs": [],
        "outputs": [
            {
                "name": "result",
                "type": "bytes32",
                "internalType": "bytes32"
            }
        ],
        "stateMutability": "view"
    },
    {
        "type": "function",
        "name": "allowance",
        "inputs": [
            {
                "name": "owner",
                "type": "address",
                "internalType": "address"
            },
            {
                "name": "spender",
                "type": "address",
                "internalType": "address"
            }
        ],
        "outputs": [
            {
                "name": "result",
                "type": "uint256",
                "internalType": "uint256"
            }
        ],
        "stateMutability": "view"
    },
    {
        "type": "function",
        "name": "approve",
        "inputs": [
            {
                "name": "spender",
                "type": "address",
                "internalType": "address"
            },
            {
                "name": "amount",
                "type": "uint256",
                "internalType": "uint256"
            }
        ],
        "outputs": [
            {
                "name": "",
                "type": "bool",
                "internalType": "bool"
            }
        ],
        "stateMutability": "nonpayable"
    },
    {
        "type": "function",
        "name": "balanceOf",
        "inputs": [
            {
                "name": "owner",
                "type": "address",
                "internalType": "address"
            }
        ],
        "outputs": [
            {
                "name": "result",
                "type": "uint256",
                "internalType": "uint256"
            }
        ],
        "stateMutability": "view"
    },
    {
        "type": "function",
        "name": "burn",
        "inputs": [
            {
                "name": "burnAmount",
                "type": "uint256",
                "internalType": "uint256"
            },
            {
                "name": "receiver",
                "type": "address",
                "internalType": "address"
            }
        ],
        "outputs": [
            {
                "name": "amount0",
                "type": "uint256",
                "internalType": "uint256"
            },
            {
                "name": "amount1",
                "type": "uint256",
                "internalType": "uint256"
            },
            {
                "name": "liquidityBurned",
                "type": "uint128",
                "internalType": "uint128"
            }
        ],
        "stateMutability": "nonpayable"
    },
    {
        "type": "function",
        "name": "compounderSlippageBPS",
        "inputs": [],
        "outputs": [
            {
                "name": "",
                "type": "uint16",
                "internalType": "uint16"
            }
        ],
        "stateMutability": "view"
    },
    {
        "type": "function",
        "name": "compounderSlippageInterval",
        "inputs": [],
        "outputs": [
            {
                "name": "",
                "type": "uint32",
                "internalType": "uint32"
            }
        ],
        "stateMutability": "view"
    },
    {
        "type": "function",
        "name": "decimals",
        "inputs": [],
        "outputs": [
            {
                "name": "",
                "type": "uint8",
                "internalType": "uint8"
            }
        ],
        "stateMutability": "view"
    },
    {
        "type": "function",
        "name": "executiveRebalance",
        "inputs": [
            {
                "name": "newLowerTick",
                "type": "int24",
                "internalType": "int24"
            },
            {
                "name": "newUpperTick",
                "type": "int24",
                "internalType": "int24"
            },
            {
                "name": "swapThresholdPrice",
                "type": "uint160",
                "internalType": "uint160"
            },
            {
                "name": "swapAmountBPS",
                "type": "uint256",
                "internalType": "uint256"
            },
            {
                "name": "zeroForOne",
                "type": "bool",
                "internalType": "bool"
            }
        ],
        "outputs": [],
        "stateMutability": "nonpayable"
    },
    {
        "type": "function",
        "name": "executiveRebalanceWithRouter",
        "inputs": [
            {
                "name": "newLowerTick",
                "type": "int24",
                "internalType": "int24"
            },
            {
                "name": "newUpperTick",
                "type": "int24",
                "internalType": "int24"
            },
            {
                "name": "swapData",
                "type": "tuple",
                "internalType": "struct SwapData",
                "components": [
                    {
                        "name": "router",
                        "type": "address",
                        "internalType": "address"
                    },
                    {
                        "name": "amountIn",
                        "type": "uint256",
                        "internalType": "uint256"
                    },
                    {
                        "name": "minAmountOut",
                        "type": "uint256",
                        "internalType": "uint256"
                    },
                    {
                        "name": "zeroForOne",
                        "type": "bool",
                        "internalType": "bool"
                    },
                    {
                        "name": "routeData",
                        "type": "bytes",
                        "internalType": "bytes"
                    }
                ]
            }
        ],
        "outputs": [],
        "stateMutability": "nonpayable"
    },
    {
        "type": "function",
        "name": "getAvgPrice",
        "inputs": [
            {
                "name": "interval",
                "type": "uint32",
                "internalType": "uint32"
            }
        ],
        "outputs": [
            {
                "name": "avgSqrtPriceX96",
                "type": "uint160",
                "internalType": "uint160"
            }
        ],
        "stateMutability": "view"
    },
    {
        "type": "function",
        "name": "getMintAmounts",
        "inputs": [
            {
                "name": "amount0Max",
                "type": "uint256",
                "internalType": "uint256"
            },
            {
                "name": "amount1Max",
                "type": "uint256",
                "internalType": "uint256"
            }
        ],
        "outputs": [
            {
                "name": "amount0",
                "type": "uint256",
                "internalType": "uint256"
            },
            {
                "name": "amount1",
                "type": "uint256",
                "internalType": "uint256"
            },
            {
                "name": "mintAmount",
                "type": "uint256",
                "internalType": "uint256"
            }
        ],
        "stateMutability": "view"
    },
    {
        "type": "function",
        "name": "getPositionID",
        "inputs": [],
        "outputs": [
            {
                "name": "positionID",
                "type": "bytes32",
                "internalType": "bytes32"
            }
        ],
        "stateMutability": "view"
    },
    {
        "type": "function",
        "name": "getUnderlyingBalances",
        "inputs": [],
        "outputs": [
            {
                "name": "amount0Current",
                "type": "uint256",
                "internalType": "uint256"
            },
            {
                "name": "amount1Current",
                "type": "uint256",
                "internalType": "uint256"
            }
        ],
        "stateMutability": "view"
    },
    {
        "type": "function",
        "name": "getUnderlyingBalancesAtPrice",
        "inputs": [
            {
                "name": "sqrtRatioX96",
                "type": "uint160",
                "internalType": "uint160"
            }
        ],
        "outputs": [
            {
                "name": "amount0Current",
                "type": "uint256",
                "internalType": "uint256"
            },
            {
                "name": "amount1Current",
                "type": "uint256",
                "internalType": "uint256"
            }
        ],
        "stateMutability": "view"
    },
    {
        "type": "function",
        "name": "initialize",
        "inputs": [
            {
                "name": "_name",
                "type": "string",
                "internalType": "string"
            },
            {
                "name": "_symbol",
                "type": "string",
                "internalType": "string"
            },
            {
                "name": "_pool",
                "type": "address",
                "internalType": "address"
            },
            {
                "name": "_managerFeeBPS",
                "type": "uint16",
                "internalType": "uint16"
            },
            {
                "name": "_lowerTick",
                "type": "int24",
                "internalType": "int24"
            },
            {
                "name": "_upperTick",
                "type": "int24",
                "internalType": "int24"
            },
            {
                "name": "_manager_",
                "type": "address",
                "internalType": "address"
            },
            {
                "name": "_managerTreasury",
                "type": "address",
                "internalType": "address"
            }
        ],
        "outputs": [],
        "stateMutability": "nonpayable"
    },
    {
        "type": "function",
        "name": "isManaged",
        "inputs": [],
        "outputs": [
            {
                "name": "",
                "type": "bool",
                "internalType": "bool"
            }
        ],
        "stateMutability": "view"
    },
    {
        "type": "function",
        "name": "islandFactory",
        "inputs": [],
        "outputs": [
            {
                "name": "",
                "type": "address",
                "internalType": "contract IKodiakIslandFactory"
            }
        ],
        "stateMutability": "view"
    },
    {
        "type": "function",
        "name": "lowerTick",
        "inputs": [],
        "outputs": [
            {
                "name": "",
                "type": "int24",
                "internalType": "int24"
            }
        ],
        "stateMutability": "view"
    },
    {
        "type": "function",
        "name": "manager",
        "inputs": [],
        "outputs": [
            {
                "name": "",
                "type": "address",
                "internalType": "address"
            }
        ],
        "stateMutability": "view"
    },
    {
        "type": "function",
        "name": "managerBalance0",
        "inputs": [],
        "outputs": [
            {
                "name": "",
                "type": "uint256",
                "internalType": "uint256"
            }
        ],
        "stateMutability": "view"
    },
    {
        "type": "function",
        "name": "managerBalance1",
        "inputs": [],
        "outputs": [
            {
                "name": "",
                "type": "uint256",
                "internalType": "uint256"
            }
        ],
        "stateMutability": "view"
    },
    {
        "type": "function",
        "name": "managerFeeBPS",
        "inputs": [],
        "outputs": [
            {
                "name": "",
                "type": "uint16",
                "internalType": "uint16"
            }
        ],
        "stateMutability": "view"
    },
    {
        "type": "function",
        "name": "managerTreasury",
        "inputs": [],
        "outputs": [
            {
                "name": "",
                "type": "address",
                "internalType": "address"
            }
        ],
        "stateMutability": "view"
    },
    {
        "type": "function",
        "name": "mint",
        "inputs": [
            {
                "name": "mintAmount",
                "type": "uint256",
                "internalType": "uint256"
            },
            {
                "name": "receiver",
                "type": "address",
                "internalType": "address"
            }
        ],
        "outputs": [
            {
                "name": "amount0",
                "type": "uint256",
                "internalType": "uint256"
            },
            {
                "name": "amount1",
                "type": "uint256",
                "internalType": "uint256"
            },
            {
                "name": "liquidityMinted",
                "type": "uint128",
                "internalType": "uint128"
            }
        ],
        "stateMutability": "nonpayable"
    },
    {
        "type": "function",
        "name": "name",
        "inputs": [],
        "outputs": [
            {
                "name": "",
                "type": "string",
                "internalType": "string"
            }
        ],
        "stateMutability": "view"
    },
    {
        "type": "function",
        "name": "nonces",
        "inputs": [
            {
                "name": "owner",
                "type": "address",
                "internalType": "address"
            }
        ],
        "outputs": [
            {
                "name": "result",
                "type": "uint256",
                "internalType": "uint256"
            }
        ],
        "stateMutability": "view"
    },
    {
        "type": "function",
        "name": "pause",
        "inputs": [],
        "outputs": [],
        "stateMutability": "nonpayable"
    },
    {
        "type": "function",
        "name": "paused",
        "inputs": [],
        "outputs": [
            {
                "name": "",
                "type": "bool",
                "internalType": "bool"
            }
        ],
        "stateMutability": "view"
    },
    {
        "type": "function",
        "name": "pauser",
        "inputs": [
            {
                "name": "",
                "type": "address",
                "internalType": "address"
            }
        ],
        "outputs": [
            {
                "name": "",
                "type": "bool",
                "internalType": "bool"
            }
        ],
        "stateMutability": "view"
    },
    {
        "type": "function",
        "name": "permit",
        "inputs": [
            {
                "name": "owner",
                "type": "address",
                "internalType": "address"
            },
            {
                "name": "spender",
                "type": "address",
                "internalType": "address"
            },
            {
                "name": "value",
                "type": "uint256",
                "internalType": "uint256"
            },
            {
                "name": "deadline",
                "type": "uint256",
                "internalType": "uint256"
            },
            {
                "name": "v",
                "type": "uint8",
                "internalType": "uint8"
            },
            {
                "name": "r",
                "type": "bytes32",
                "internalType": "bytes32"
            },
            {
                "name": "s",
                "type": "bytes32",
                "internalType": "bytes32"
            }
        ],
        "outputs": [],
        "stateMutability": "nonpayable"
    },
    {
        "type": "function",
        "name": "pool",
        "inputs": [],
        "outputs": [
            {
                "name": "",
                "type": "address",
                "internalType": "contract IUniswapV3Pool"
            }
        ],
        "stateMutability": "view"
    },
    {
        "type": "function",
        "name": "rebalance",
        "inputs": [],
        "outputs": [],
        "stateMutability": "nonpayable"
    },
    {
        "type": "function",
        "name": "renounceOwnership",
        "inputs": [],
        "outputs": [],
        "stateMutability": "nonpayable"
    },
    {
        "type": "function",
        "name": "restrictedMint",
        "inputs": [],
        "outputs": [
            {
                "name": "",
                "type": "bool",
                "internalType": "bool"
            }
        ],
        "stateMutability": "view"
    },
    {
        "type": "function",
        "name": "setPauser",
        "inputs": [
            {
                "name": "_pauser",
                "type": "address",
                "internalType": "address"
            },
            {
                "name": "_status",
                "type": "bool",
                "internalType": "bool"
            }
        ],
        "outputs": [],
        "stateMutability": "nonpayable"
    },
    {
        "type": "function",
        "name": "setRestrictedMint",
        "inputs": [
            {
                "name": "_status",
                "type": "bool",
                "internalType": "bool"
            }
        ],
        "outputs": [],
        "stateMutability": "nonpayable"
    },
    {
        "type": "function",
        "name": "setRouter",
        "inputs": [
            {
                "name": "_router",
                "type": "address",
                "internalType": "address"
            },
            {
                "name": "_status",
                "type": "bool",
                "internalType": "bool"
            }
        ],
        "outputs": [],
        "stateMutability": "nonpayable"
    },
    {
        "type": "function",
        "name": "swapRouter",
        "inputs": [
            {
                "name": "",
                "type": "address",
                "internalType": "address"
            }
        ],
        "outputs": [
            {
                "name": "",
                "type": "bool",
                "internalType": "bool"
            }
        ],
        "stateMutability": "view"
    },
    {
        "type": "function",
        "name": "symbol",
        "inputs": [],
        "outputs": [
            {
                "name": "",
                "type": "string",
                "internalType": "string"
            }
        ],
        "stateMutability": "view"
    },
    {
        "type": "function",
        "name": "syncToFactory",
        "inputs": [],
        "outputs": [],
        "stateMutability": "nonpayable"
    },
    {
        "type": "function",
        "name": "token0",
        "inputs": [],
        "outputs": [
            {
                "name": "",
                "type": "address",
                "internalType": "contract IERC20"
            }
        ],
        "stateMutability": "view"
    },
    {
        "type": "function",
        "name": "token1",
        "inputs": [],
        "outputs": [
            {
                "name": "",
                "type": "address",
                "internalType": "contract IERC20"
            }
        ],
        "stateMutability": "view"
    },
    {
        "type": "function",
        "name": "totalSupply",
        "inputs": [],
        "outputs": [
            {
                "name": "result",
                "type": "uint256",
                "internalType": "uint256"
            }
        ],
        "stateMutability": "view"
    },
    {
        "type": "function",
        "name": "transfer",
        "inputs": [
            {
                "name": "to",
                "type": "address",
                "internalType": "address"
            },
            {
                "name": "amount",
                "type": "uint256",
                "internalType": "uint256"
            }
        ],
        "outputs": [
            {
                "name": "",
                "type": "bool",
                "internalType": "bool"
            }
        ],
        "stateMutability": "nonpayable"
    },
    {
        "type": "function",
        "name": "transferFrom",
        "inputs": [
            {
                "name": "from",
                "type": "address",
                "internalType": "address"
            },
            {
                "name": "to",
                "type": "address",
                "internalType": "address"
            },
            {
                "name": "amount",
                "type": "uint256",
                "internalType": "uint256"
            }
        ],
        "outputs": [
            {
                "name": "",
                "type": "bool",
                "internalType": "bool"
            }
        ],
        "stateMutability": "nonpayable"
    },
    {
        "type": "function",
        "name": "transferOwnership",
        "inputs": [
            {
                "name": "newOwner",
                "type": "address",
                "internalType": "address"
            }
        ],
        "outputs": [],
        "stateMutability": "nonpayable"
    },
    {
        "type": "function",
        "name": "uniswapV3MintCallback",
        "inputs": [
            {
                "name": "amount0Owed",
                "type": "uint256",
                "internalType": "uint256"
            },
            {
                "name": "amount1Owed",
                "type": "uint256",
                "internalType": "uint256"
            },
            {
                "name": "",
                "type": "bytes",
                "internalType": "bytes"
            }
        ],
        "outputs": [],
        "stateMutability": "nonpayable"
    },
    {
        "type": "function",
        "name": "uniswapV3SwapCallback",
        "inputs": [
            {
                "name": "amount0Delta",
                "type": "int256",
                "internalType": "int256"
            },
            {
                "name": "amount1Delta",
                "type": "int256",
                "internalType": "int256"
            },
            {
                "name": "",
                "type": "bytes",
                "internalType": "bytes"
            }
        ],
        "outputs": [],
        "stateMutability": "nonpayable"
    },
    {
        "type": "function",
        "name": "unpause",
        "inputs": [],
        "outputs": [],
        "stateMutability": "nonpayable"
    },
    {
        "type": "function",
        "name": "updateManagerParams",
        "inputs": [
            {
                "name": "newManagerFeeBPS",
                "type": "int16",
                "internalType": "int16"
            },
            {
                "name": "newManagerTreasury",
                "type": "address",
                "internalType": "address"
            },
            {
                "name": "newSlippageBPS",
                "type": "int16",
                "internalType": "int16"
            },
            {
                "name": "newSlippageInterval",
                "type": "int32",
                "internalType": "int32"
            }
        ],
        "outputs": [],
        "stateMutability": "nonpayable"
    },
    {
        "type": "function",
        "name": "upperTick",
        "inputs": [],
        "outputs": [
            {
                "name": "",
                "type": "int24",
                "internalType": "int24"
            }
        ],
        "stateMutability": "view"
    },
    {
        "type": "function",
        "name": "version",
        "inputs": [],
        "outputs": [
            {
                "name": "",
                "type": "string",
                "internalType": "string"
            }
        ],
        "stateMutability": "view"
    },
    {
        "type": "function",
        "name": "withdrawManagerBalance",
        "inputs": [],
        "outputs": [],
        "stateMutability": "nonpayable"
    },
    {
        "type": "function",
        "name": "worstAmountOut",
        "inputs": [
            {
                "name": "amountIn",
                "type": "uint256",
                "internalType": "uint256"
            },
            {
                "name": "slippageBPS",
                "type": "uint16",
                "internalType": "uint16"
            },
            {
                "name": "avgSqrtPriceX96",
                "type": "uint160",
                "internalType": "uint160"
            },
            {
                "name": "zeroForOne",
                "type": "bool",
                "internalType": "bool"
            }
        ],
        "outputs": [
            {
                "name": "",
                "type": "uint256",
                "internalType": "uint256"
            }
        ],
        "stateMutability": "pure"
    },
    {
        "type": "event",
        "name": "Approval",
        "inputs": [
            {
                "name": "owner",
                "type": "address",
                "indexed": true,
                "internalType": "address"
            },
            {
                "name": "spender",
                "type": "address",
                "indexed": true,
                "internalType": "address"
            },
            {
                "name": "amount",
                "type": "uint256",
                "indexed": false,
                "internalType": "uint256"
            }
        ],
        "anonymous": false
    },
    {
        "type": "event",
        "name": "Burned",
        "inputs": [
            {
                "name": "receiver",
                "type": "address",
                "indexed": false,
                "internalType": "address"
            },
            {
                "name": "burnAmount",
                "type": "uint256",
                "indexed": false,
                "internalType": "uint256"
            },
            {
                "name": "amount0Out",
                "type": "uint256",
                "indexed": false,
                "internalType": "uint256"
            },
            {
                "name": "amount1Out",
                "type": "uint256",
                "indexed": false,
                "internalType": "uint256"
            },
            {
                "name": "liquidityBurned",
                "type": "uint128",
                "indexed": false,
                "internalType": "uint128"
            }
        ],
        "anonymous": false
    },
    {
        "type": "event",
        "name": "FeesEarned",
        "inputs": [
            {
                "name": "feesEarned0",
                "type": "uint256",
                "indexed": false,
                "internalType": "uint256"
            },
            {
                "name": "feesEarned1",
                "type": "uint256",
                "indexed": false,
                "internalType": "uint256"
            }
        ],
        "anonymous": false
    },
    {
        "type": "event",
        "name": "Minted",
        "inputs": [
            {
                "name": "receiver",
                "type": "address",
                "indexed": false,
                "internalType": "address"
            },
            {
                "name": "mintAmount",
                "type": "uint256",
                "indexed": false,
                "internalType": "uint256"
            },
            {
                "name": "amount0In",
                "type": "uint256",
                "indexed": false,
                "internalType": "uint256"
            },
            {
                "name": "amount1In",
                "type": "uint256",
                "indexed": false,
                "internalType": "uint256"
            },
            {
                "name": "liquidityMinted",
                "type": "uint128",
                "indexed": false,
                "internalType": "uint128"
            }
        ],
        "anonymous": false
    },
    {
        "type": "event",
        "name": "OwnershipTransferred",
        "inputs": [
            {
                "name": "previousManager",
                "type": "address",
                "indexed": true,
                "internalType": "address"
            },
            {
                "name": "newManager",
                "type": "address",
                "indexed": true,
                "internalType": "address"
            }
        ],
        "anonymous": false
    },
    {
        "type": "event",
        "name": "Paused",
        "inputs": [
            {
                "name": "account",
                "type": "address",
                "indexed": false,
                "internalType": "address"
            }
        ],
        "anonymous": false
    },
    {
        "type": "event",
        "name": "PauserSet",
        "inputs": [
            {
                "name": "pauser",
                "type": "address",
                "indexed": true,
                "internalType": "address"
            },
            {
                "name": "status",
                "type": "bool",
                "indexed": false,
                "internalType": "bool"
            }
        ],
        "anonymous": false
    },
    {
        "type": "event",
        "name": "Rebalance",
        "inputs": [
            {
                "name": "compounder",
                "type": "address",
                "indexed": true,
                "internalType": "address"
            },
            {
                "name": "lowerTick_",
                "type": "int24",
                "indexed": false,
                "internalType": "int24"
            },
            {
                "name": "upperTick_",
                "type": "int24",
                "indexed": false,
                "internalType": "int24"
            },
            {
                "name": "liquidityBefore",
                "type": "uint128",
                "indexed": false,
                "internalType": "uint128"
            },
            {
                "name": "liquidityAfter",
                "type": "uint128",
                "indexed": false,
                "internalType": "uint128"
            }
        ],
        "anonymous": false
    },
    {
        "type": "event",
        "name": "RestrictedMintSet",
        "inputs": [
            {
                "name": "status",
                "type": "bool",
                "indexed": false,
                "internalType": "bool"
            }
        ],
        "anonymous": false
    },
    {
        "type": "event",
        "name": "RouterSet",
        "inputs": [
            {
                "name": "router",
                "type": "address",
                "indexed": true,
                "internalType": "address"
            },
            {
                "name": "status",
                "type": "bool",
                "indexed": false,
                "internalType": "bool"
            }
        ],
        "anonymous": false
    },
    {
        "type": "event",
        "name": "Transfer",
        "inputs": [
            {
                "name": "from",
                "type": "address",
                "indexed": true,
                "internalType": "address"
            },
            {
                "name": "to",
                "type": "address",
                "indexed": true,
                "internalType": "address"
            },
            {
                "name": "amount",
                "type": "uint256",
                "indexed": false,
                "internalType": "uint256"
            }
        ],
        "anonymous": false
    },
    {
        "type": "event",
        "name": "Unpaused",
        "inputs": [
            {
                "name": "account",
                "type": "address",
                "indexed": false,
                "internalType": "address"
            }
        ],
        "anonymous": false
    },
    {
        "type": "event",
        "name": "UpdateManagerParams",
        "inputs": [
            {
                "name": "managerFeeBPS",
                "type": "uint16",
                "indexed": false,
                "internalType": "uint16"
            },
            {
                "name": "managerTreasury",
                "type": "address",
                "indexed": false,
                "internalType": "address"
            },
            {
                "name": "compounderSlippageBPS",
                "type": "uint16",
                "indexed": false,
                "internalType": "uint16"
            },
            {
                "name": "compounderSlippageInterval",
                "type": "uint32",
                "indexed": false,
                "internalType": "uint32"
            }
        ],
        "anonymous": false
    },
    {
        "type": "error",
        "name": "AllowanceOverflow",
        "inputs": []
    },
    {
        "type": "error",
        "name": "AllowanceUnderflow",
        "inputs": []
    },
    {
        "type": "error",
        "name": "InsufficientAllowance",
        "inputs": []
    },
    {
        "type": "error",
        "name": "InsufficientBalance",
        "inputs": []
    },
    {
        "type": "error",
        "name": "InvalidPermit",
        "inputs": []
    },
    {
        "type": "error",
        "name": "Permit2AllowanceIsFixedAtInfinity",
        "inputs": []
    },
    {
        "type": "error",
        "name": "PermitExpired",
        "inputs": []
    },
    {
        "type": "error",
        "name": "Reentrancy",
        "inputs": []
    },
    {
        "type": "error",
        "name": "TotalSupplyOverflow",
        "inputs": []
        }
]
```


# Kodiak Island Router

A helper contract that enables easy, secure liquidity provisioning and withdrawals

## Overview

The IslandRouter contract serves as a helper contract for users to easily provide liquidity to Kodiak Islands. It handles the complexities of depositing tokens, slippage protection, and token swaps when needed, while ensuring optimal liquidity provision.

Kodiak Islands require liquidity providers to deposit tokens in specific ratios that match the Island's underlying Kodiak V3 position. The router provides several key protections:

* Minimum output amount protection for swaps when providing liquidity with single token.
* Deposit ratio slippage protection
* Minimum LP token (shares) protection

## Managing Liquidity

#### Token Deposit Ratio

The router handles liquidity addition by:

1. Calculating the optimal deposit amounts using `island.getMintAmounts()`
2. Ensuring the amounts meet minimum requirements
3. Transferring tokens and minting LP tokens

#### Steps to Add Liquidity

1. Approve the router to spend your tokens (both tokens or one token in case of singleSided
2. Choose the appropriate liquidity addition method based on your tokens
3. If the liquidity addition is using a single token, find the appropriate swap data and use Kodiak Quoter api to get the calldata according to the swap params.
4. Set reasonable slippage parameters
5. Execute transaction
6. Kodiak Island LP tokens sent to the receiver as passed in params
7. In case of zaps msg.sender receives back any unused token0 or token1

### Adding liquidity with both tokens

#### 1. Standard Two Token Deposit

#### Prerequisites

* Token0 and Token1 balances sufficient for desired liquidity.
* Approved router contract to spend both tokens.

```solidity
function addLiquidity(
    IKodiakIsland island,     // Address of the Kodiak Island
    uint256 amount0Max,       // Maximum amount of token0 willing to deposit
    uint256 amount1Max,       // Maximum amount of token1 willing to deposit
    uint256 amount0Min,       // Minimum acceptable token0 deposit (slippage protection)
    uint256 amount1Min,       // Minimum acceptable token1 deposit (slippage protection)
    uint256 amountSharesMin,  // Minimum IslandTokens to receive
    address receiver          // Address to receive LP tokens
) external returns (
    uint256 amount0,         // Actual token0 amount deposited
    uint256 amount1,         // Actual token1 amount deposited
    uint256 mintAmount       // LP tokens received
)
```

#### Implementation Example

<pre class="language-javascript"><code class="lang-javascript"><strong>// 1. Start with maximum amounts to deposit, for example 10 token0 and 10 token1
</strong>const amount0Max = ethers.parseUnits("10", token0Decimals);
const amount1Max = ethers.parseUnits("10", token1Decimals);

// 2. Find the appropriate ratio of tokens to deposit
(amount0Used, amount1Used, ) = await island.getMintAmounts(amount0Max, amount1Max)

amount0Max = amount0Used
amount1Max = amount1Used

// 3. Set slippage tolerance for the minimum amounts of token0 and token1 
// (e.g. 1% slippage). This means that atleast 99% of these tokens should 
// be deposited in the pool. This gives you a protection from the pool price
// deviating a lot before your transaction goes through
//  which affects the tokens and ratio they are deposited in
const amount0Min = amount0Max.mul(99).div(100);
const amount1Min = amount1Max.mul(99).div(100);
const amountSharesMin = 0; // Set based on expected shares

// 4. Approve router
await token0.approve(routerAddress, amount0Max);
await token1.approve(routerAddress, amount1Max);

// 5. Callstatic deposit to get the amountShares minted
const simulationResult = await router.callStatic.addLiquidity(
    islandAddress,
    amount0Max,
    amount1Max,
    amount0Min,
    amount1Min,
    amountSharesMin,
    receiverAddress
);

// 6. Mint Island tokens, Use the mintAmount from above
// add a comfortable slippage (ex 1%) to this and use this for amountSharesMin
// Use BPS for higher precision.
amountSharesMin = simulationResult[2]
       .mul(99).div(100).toString()

<strong>const tx = await router.addLiquidity(
</strong>    islandAddress,
    amount0Max,
    amount1Max,
    amount0Min,
    amount1Min,
    amountSharesMin,
    receiverAddress
);

</code></pre>

#### 2. Native BERA + Token Deposit

> It is important that one of the tokens in the underlying pool is WBERA for depositing with native BERA.

#### Prerequisites

* Sender must have sufficient NativeToken and Token1 balances for desired liquidity.
* Approve router contract to spend Token1 tokens.
* Send required bera as msg.value&#x20;

```solidity
// Assuming token0 is WBERA
function addLiquidityNative(
    IKodiakIsland island,     // Address of the Kodiak Island
    uint256 amount0Max,       // Maximum BERA amount
    uint256 amount1Max,       // Maximum token amount
    uint256 amount0Min,       // Minimum BERA deposit
    uint256 amount1Min,       // Minimum token deposit
    uint256 amountSharesMin,  // Minimum LP tokens to receive
    address receiver          // Address to receive LP tokens
) external payable returns (
    uint256 amount0,         // Actual BERA amount deposited
    uint256 amount1,         // Actual token amount deposited
    uint256 mintAmount       // LP tokens received
)
```

Implementation is same as above except for sending native token BERA as msg.value

<pre class="language-javascript"><code class="lang-javascript"><strong>const tx = await router.addLiquidityNative(
</strong>    islandAddress,
    amount0Max,
    amount1Max,
    amount0Min,
    amount1Min,
    amountSharesMin,
    receiverAddress,
    {
        value: amount0Max // assuming island.token0() is WBERA
    }
);
</code></pre>

### Adding Liquidity with a single token

When depositing into a concentrated liquidity position like an Island, it's crucial to understand that the underlying tokens need to be in a specific ratio to maximize the value of the position. If a user wants to deposit a single token, a swap is required to balance the tokens before adding liquidity to the position. This process involves calculating the ideal amount of the input token to swap for the other token in the pair.

The IslandRouter uses a external swap Routers to swap this token to achieve maximal efficiency during the swap. The kodiak router is whitelisted to begin with and other routers will be whitelisted later to further increase this swap efficiency.

#### Prerequisites

* Sufficient balance of input token or native token.
* Approved router for input token amount
* Understanding on how to find the swap params such that after the swap the token0 and token1 are in correct ratio to deposit into the island
* Understanding on how to generate swap calldata using Kodiak Router.

#### Single Token Deposit Implementation

```solidity
function addLiquiditySingle(
    IKodiakIsland island,              // Island address
    uint256 totalAmountIn,             // Total input token amount
    uint256 amountSharesMin,           // Minimum LP tokens to receive
    uint256 maxStakingSlippageBPS,     // Max slippage in basis points (100 = 1%)
    RouterSwapParams calldata swapData, // Swap parameters for converting portion of input
    address receiver                    // LP token recipient
) external returns (
    uint256 amount0,                   // Final token0 amount deposited
    uint256 amount1,                   // Final token1 amount deposited
    uint256 mintAmount                 // LP tokens received
)

struct RouterSwapParams {
    bool zeroForOne;        // Swap direction
    uint256 amountIn;       // Amount to swap
    uint256 minAmountOut;   // Minimum output from swap
    bytes routeData;        // Encoded swap route data
}
```

#### Implementation Example

```javascript
// 1. Prepare swap parameters. refer the section on finding the swap amounts
const swapParams = {
    zeroForOne: true, // true if swapping token0 for token1
    amountIn: swapAmount,
    minAmountOut: minimumSwapOutput,
    routeData: swapCalldata
};

// 2. Set slippage parameters
const maxStakingSlippageBPS = 100; // 1% slippage
const minShares = minShares; // find the min shares by making a static call 
// and adding a 1% slippage to it as demonstrated in previous examples

// 3. Approve island router to spend your inputToken
await token0.approve(islandRouterAddress, totalAmount);

// 3. Execute single token deposit
const tx = await islandRouter.addLiquiditySingle(
    islandAddress,
    totalAmount,
    minShares,
    maxStakingSlippageBPS,
    swapParams,
    receiverAddress
);
```

### Adding Liquidity with Native BERA

When you want to provide liquidity to an island with native token BERA.

#### Prerequisites

* Native BERA balance
* Island must have WBERA as one of its tokens

#### Single Native Token Deposit

```solidity
function addLiquiditySingleNative(
    IKodiakIsland island,              // Island address (must include WBERA)
    uint256 amountSharesMin,           // Minimum LP tokens to receive
    uint256 maxStakingSlippageBPS,     // Max slippage in basis points
    RouterSwapParams calldata swapData, // Swap parameters
    address receiver                    // LP token recipient
) external payable returns (
    uint256 amount0,                   // Final token0 amount deposited
    uint256 amount1,                   // Final token1 amount deposited
    uint256 mintAmount                 // LP tokens received
)
```

#### Implementation Example

```typescript
// 1. Calculate BERA amount to send
const beraAmount = ethers.parseEther("1.0");

// 2. Prepare swap parameters
const swapParams = {
    zeroForOne: true,
    amountIn: swapAmount,
    minAmountOut: minOutput,
    routeData: swapCalldata
};

// 3. Execute native deposit
const tx = await islandRouter.addLiquiditySingleNative(
    islandAddress,
    minimumShares,
    100, // 1% max slippage
    swapParams,
    receiverAddress,
    { value: beraAmount }
);
```

### Important Notes

* For native BERA deposits, one token in the Island pair must be WBERA
* Unused BERA is automatically returned to sender as native tokens when performing single sided deposits with native BERA
* If the msg.sender is a contract, it must handle both type of unused tokens i.e ERC20 tokens and native tokens when depositing with single token or native token
* Set appropriate slippage parameters based on market conditions
* Monitor gas costs, especially for operations involving swaps
* Verify all addresses and amounts before execution
* Consider using view functions to estimate outputs before executing transactions

## Removing Liquidity

The router exposes two functions for removing liquidity with slippage control

**`removeLiquidity`**

```solidity
function removeLiquidity(
    IKodiakIsland island,
    uint256 burnAmount,
    uint256 amount0Min,
    uint256 amount1Min,
    address receiver
) external returns (uint256 amount0, uint256 amount1, uint128 liquidityBurned)
```

**Purpose**: Removes liquidity from a Kodiak Island position by burning LP tokens and getting the underlying tokens.

**Parameters**:

* `island`: The address of the Kodiak Island position to withdraw from
* `burnAmount`: The quantity of Kodiak Island LP tokens to burn
* `amount0Min`: Minimum amount of token0 that must be received (slippage protection)
* `amount1Min`: Minimum amount of token1 that must be received (slippage protection)
* `receiver`: The address that will receive the withdrawn tokens

**Returns**:

* `amount0`: The actual amount of token0 received
* `amount1`: The actual amount of token1 received
* `liquidityBurned`: The amount of liquidity removed from the underlying Kodiak V3 position

**Important Notes**:

* Caller must approve the router contract to spend their Kodiak Island LP tokens
* Transaction will revert if received amounts are less than specified minimums
* Useful for standard token pairs where wrapped native token conversion isn't needed

***

**`removeLiquidityNative`**

```solidity
function removeLiquidityNative(
    IKodiakIsland island,
    uint256 burnAmount,
    uint256 amount0Min,
    uint256 amount1Min,
    address payable receiver
) external returns (uint256 amount0, uint256 amount1, uint128 liquidityBurned)
```

**Purpose**: Similar to `removeLiquidity` but specifically handles positions involving WBERA (wrapped BERA), automatically unwrapping it to native BERA before returning it to the user.

**Parameters**:

* `island`: The address of the Kodiak Island position to withdraw from
* `burnAmount`: The quantity of Kodiak Island LP tokens to burn
* `amount0Min`: Minimum amount of token0 that must be received (slippage protection)
* `amount1Min`: Minimum amount of token1 that must be received (slippage protection)
* `receiver`: The address that will receive the withdrawn tokens (must be payable to receive native BERA)

**Returns**:

* `amount0`: The actual amount of token0 received
* `amount1`: The actual amount of token1 received
* `liquidityBurned`: The amount of liquidity removed from the underlying Kodiak V3 position

**Important Notes**:

* Caller must approve the router contract to spend their Kodiak Island LP tokens
* One of the tokens in the pair must be WBERA
* WBERA portion will be automatically unwrapped and sent as native BERA to the receiver
* The non-WBERA token will be sent as is to the receiver
* Transaction will revert if received amounts are less than specified minimums
* Receiver address must be payable to receive native BERA
* Particularly useful for positions involving native BERA pairs

For both functions, it's recommended to:

1. Calculate expected output amounts before calling
2. Include reasonable slippage protection via `amount0Min` and `amount1Min`
3. Ensure sufficient approvals are in place
4. Handle both success and failure cases in your integration
5. Verify received amounts match expectations after the transaction

## ABI

````json
```json
[
        {
            "type": "constructor",
            "inputs": [
                {
                    "name": "_wBera",
                    "type": "address",
                    "internalType": "contract IWETH"
                },
                {
                    "name": "_kodiakRouter",
                    "type": "address",
                    "internalType": "address"
                }
            ],
            "stateMutability": "nonpayable"
        },
        {
            "type": "receive",
            "stateMutability": "payable"
        },
        {
            "type": "function",
            "name": "addLiquidity",
            "inputs": [
                {
                    "name": "island",
                    "type": "address",
                    "internalType": "contract IKodiakIsland"
                },
                {
                    "name": "amount0Max",
                    "type": "uint256",
                    "internalType": "uint256"
                },
                {
                    "name": "amount1Max",
                    "type": "uint256",
                    "internalType": "uint256"
                },
                {
                    "name": "amount0Min",
                    "type": "uint256",
                    "internalType": "uint256"
                },
                {
                    "name": "amount1Min",
                    "type": "uint256",
                    "internalType": "uint256"
                },
                {
                    "name": "amountSharesMin",
                    "type": "uint256",
                    "internalType": "uint256"
                },
                {
                    "name": "receiver",
                    "type": "address",
                    "internalType": "address"
                }
            ],
            "outputs": [
                {
                    "name": "amount0",
                    "type": "uint256",
                    "internalType": "uint256"
                },
                {
                    "name": "amount1",
                    "type": "uint256",
                    "internalType": "uint256"
                },
                {
                    "name": "mintAmount",
                    "type": "uint256",
                    "internalType": "uint256"
                }
            ],
            "stateMutability": "nonpayable"
        },
        {
            "type": "function",
            "name": "addLiquidityNative",
            "inputs": [
                {
                    "name": "island",
                    "type": "address",
                    "internalType": "contract IKodiakIsland"
                },
                {
                    "name": "amount0Max",
                    "type": "uint256",
                    "internalType": "uint256"
                },
                {
                    "name": "amount1Max",
                    "type": "uint256",
                    "internalType": "uint256"
                },
                {
                    "name": "amount0Min",
                    "type": "uint256",
                    "internalType": "uint256"
                },
                {
                    "name": "amount1Min",
                    "type": "uint256",
                    "internalType": "uint256"
                },
                {
                    "name": "amountSharesMin",
                    "type": "uint256",
                    "internalType": "uint256"
                },
                {
                    "name": "receiver",
                    "type": "address",
                    "internalType": "address"
                }
            ],
            "outputs": [
                {
                    "name": "amount0",
                    "type": "uint256",
                    "internalType": "uint256"
                },
                {
                    "name": "amount1",
                    "type": "uint256",
                    "internalType": "uint256"
                },
                {
                    "name": "mintAmount",
                    "type": "uint256",
                    "internalType": "uint256"
                }
            ],
            "stateMutability": "payable"
        },
        {
            "type": "function",
            "name": "addLiquiditySingle",
            "inputs": [
                {
                    "name": "island",
                    "type": "address",
                    "internalType": "contract IKodiakIsland"
                },
                {
                    "name": "totalAmountIn",
                    "type": "uint256",
                    "internalType": "uint256"
                },
                {
                    "name": "amountSharesMin",
                    "type": "uint256",
                    "internalType": "uint256"
                },
                {
                    "name": "maxStakingSlippageBPS",
                    "type": "uint256",
                    "internalType": "uint256"
                },
                {
                    "name": "swapData",
                    "type": "tuple",
                    "internalType": "struct RouterSwapParams",
                    "components": [
                        {
                            "name": "amountIn",
                            "type": "uint256",
                            "internalType": "uint256"
                        },
                        {
                            "name": "minAmountOut",
                            "type": "uint256",
                            "internalType": "uint256"
                        },
                        {
                            "name": "zeroForOne",
                            "type": "bool",
                            "internalType": "bool"
                        },
                        {
                            "name": "routeData",
                            "type": "bytes",
                            "internalType": "bytes"
                        }
                    ]
                },
                {
                    "name": "receiver",
                    "type": "address",
                    "internalType": "address"
                }
            ],
            "outputs": [
                {
                    "name": "amount0",
                    "type": "uint256",
                    "internalType": "uint256"
                },
                {
                    "name": "amount1",
                    "type": "uint256",
                    "internalType": "uint256"
                },
                {
                    "name": "mintAmount",
                    "type": "uint256",
                    "internalType": "uint256"
                }
            ],
            "stateMutability": "nonpayable"
        },
        {
            "type": "function",
            "name": "addLiquiditySingleNative",
            "inputs": [
                {
                    "name": "island",
                    "type": "address",
                    "internalType": "contract IKodiakIsland"
                },
                {
                    "name": "amountSharesMin",
                    "type": "uint256",
                    "internalType": "uint256"
                },
                {
                    "name": "maxStakingSlippageBPS",
                    "type": "uint256",
                    "internalType": "uint256"
                },
                {
                    "name": "swapData",
                    "type": "tuple",
                    "internalType": "struct RouterSwapParams",
                    "components": [
                        {
                            "name": "amountIn",
                            "type": "uint256",
                            "internalType": "uint256"
                        },
                        {
                            "name": "minAmountOut",
                            "type": "uint256",
                            "internalType": "uint256"
                        },
                        {
                            "name": "zeroForOne",
                            "type": "bool",
                            "internalType": "bool"
                        },
                        {
                            "name": "routeData",
                            "type": "bytes",
                            "internalType": "bytes"
                        }
                    ]
                },
                {
                    "name": "receiver",
                    "type": "address",
                    "internalType": "address"
                }
            ],
            "outputs": [
                {
                    "name": "amount0",
                    "type": "uint256",
                    "internalType": "uint256"
                },
                {
                    "name": "amount1",
                    "type": "uint256",
                    "internalType": "uint256"
                },
                {
                    "name": "mintAmount",
                    "type": "uint256",
                    "internalType": "uint256"
                }
            ],
            "stateMutability": "payable"
        },
        {
            "type": "function",
            "name": "kodiakRouter",
            "inputs": [],
            "outputs": [
                {
                    "name": "",
                    "type": "address",
                    "internalType": "address"
                }
            ],
            "stateMutability": "view"
        },
        {
            "type": "function",
            "name": "removeLiquidity",
            "inputs": [
                {
                    "name": "island",
                    "type": "address",
                    "internalType": "contract IKodiakIsland"
                },
                {
                    "name": "burnAmount",
                    "type": "uint256",
                    "internalType": "uint256"
                },
                {
                    "name": "amount0Min",
                    "type": "uint256",
                    "internalType": "uint256"
                },
                {
                    "name": "amount1Min",
                    "type": "uint256",
                    "internalType": "uint256"
                },
                {
                    "name": "receiver",
                    "type": "address",
                    "internalType": "address"
                }
            ],
            "outputs": [
                {
                    "name": "amount0",
                    "type": "uint256",
                    "internalType": "uint256"
                },
                {
                    "name": "amount1",
                    "type": "uint256",
                    "internalType": "uint256"
                },
                {
                    "name": "liquidityBurned",
                    "type": "uint128",
                    "internalType": "uint128"
                }
            ],
            "stateMutability": "nonpayable"
        },
        {
            "type": "function",
            "name": "removeLiquidityNative",
            "inputs": [
                {
                    "name": "island",
                    "type": "address",
                    "internalType": "contract IKodiakIsland"
                },
                {
                    "name": "burnAmount",
                    "type": "uint256",
                    "internalType": "uint256"
                },
                {
                    "name": "amount0Min",
                    "type": "uint256",
                    "internalType": "uint256"
                },
                {
                    "name": "amount1Min",
                    "type": "uint256",
                    "internalType": "uint256"
                },
                {
                    "name": "receiver",
                    "type": "address",
                    "internalType": "address payable"
                }
            ],
            "outputs": [
                {
                    "name": "amount0",
                    "type": "uint256",
                    "internalType": "uint256"
                },
                {
                    "name": "amount1",
                    "type": "uint256",
                    "internalType": "uint256"
                },
                {
                    "name": "liquidityBurned",
                    "type": "uint128",
                    "internalType": "uint128"
                }
            ],
            "stateMutability": "nonpayable"
        },
        {
            "type": "function",
            "name": "wBera",
            "inputs": [],
            "outputs": [
                {
                    "name": "",
                    "type": "address",
                    "internalType": "contract IWETH"
                }
            ],
            "stateMutability": "view"
        }
    ]
```
````


# API

### Pools & Farms API

This documentation covers the REST API endpoints for kodiak pools.

#### Base URL

```
https://backend.kodiak.finance
```

#### Pools Endpoint

```
GET /vaults
```

Retrieves information about liquidity positions (pools) with comprehensive filtering, sorting, and pagination options.

#### Request Parameters

| Parameter        | Type    | Required | Description                                                  |
| ---------------- | ------- | -------- | ------------------------------------------------------------ |
| `chainId`        | number  | Yes      | Blockchain network ID (e.g., 80094)                          |
| `limit`          | number  | No       | Maximum number of results to return (default: 20)            |
| `offset`         | number  | No       | Number of results to skip for pagination (default: 0)        |
| `orderBy`        | string  | No       | Field to sort results by (see Sorting Options)               |
| `orderDirection` | string  | No       | Sort direction: `asc` or `desc` (default: `desc`)            |
| `user`           | string  | No       | Address to filter positions by user holdings                 |
| `search`         | string  | No       | Search term to filter results by token names or symbols      |
| `rewardVault`    | boolean | No       | When `true`, filters for positions with reward vaults        |
| `sweetened`      | boolean | No       | When `true`, filters for incentivized/sweetened positions    |
| `volatile`       | boolean | No       | Filter for volatile (`true`) or stable (`false`) pairs       |
| `minimumTvl`     | number  | No       | Minimum total value locked threshold (e.g., 10000 = $10,000) |

#### Sorting Options

The API supports sorting by the following fields:

| `orderBy` value | Description                                                                      |
| --------------- | -------------------------------------------------------------------------------- |
| `tvl`           | Total value locked in the position                                               |
| `farmTvl`       | Total value locked in associated farms                                           |
| `apr`           | Base APR from trading fees                                                       |
| `farmApr`       | Farm/incentive APR                                                               |
| `totalApr`      | Combined APR (base + farm)                                                       |
| `balance`       | User's balance in the position (requires `user` parameter)                       |
| `farmBalance`   | User's balance in associated farms/reward vaults (requires `user` parameter)     |
| `vaultBalance`  | User's balance in associated pools that are unstaked (requires `user` parameter) |

#### Filter Combinations

The API supports multiple filter combinations:

1. **Incentivized Positions**
   * Set both `rewardVault=true` and `sweetened=true`
2. **Volatility Filters**
   * For volatile pairs: `volatile=true`
   * For stable pairs: `volatile=false`
3. **TVL Threshold**
   * Hide low TVL positions: `minimumTvl=10000` (filters out positions with less than $10,000 TVL)
4. **Search**
   * Filter by token names or symbols: `search=ETH` or `search=Ethereum`

#### Pagination

The API uses offset-based pagination:

* `limit`: Number of results per page (default: 20)
* `offset`: Starting position for results (default: 0)

Example pagination:

* Page 1: `offset=0&limit=20`
* Page 2: `offset=20&limit=20`
* Page 3: `offset=40&limit=20`

#### Response Format

The API returns a JSON object with the following structure:

```json
{
  "data": [IslandApiResponse],
  "count": number
}
```

Where `count` is the total number of results matching the query (before pagination), and `data` is an array of `IslandApiResponse` objects.

#### IslandApiResponse Object

Each island position is represented by an object with the following structure:

```typescript
interface IslandApiResponse {
  id: string                   // Unique identifier for the position
  provider: string             // Provider of the liquidity pool
  lowerTick: number            // Lower price bound tick
  upperTick: number            // Upper price bound tick
  currentTick: number          // Current price tick
  tvl: number                  // Total value locked in USD
  farmTvl: number              // Total value locked in associated farms in USD
  apr: number                  // Annual percentage rate from fees
  weeklyFeesEarnedUSD: number  // Weekly fees earned in USD
  feeTier: number              // Fee tier of the pool
  totalApr: number             // Combined APR (base + farm)
  lastUpdated: string          // Timestamp of last data update
  isSweetened: boolean         // Whether position has additional incentives
  isRewardVault: boolean       // Whether position has a reward vault
  isVolatile: boolean          // Whether position is for volatile pairs
  
  // First token in the pair
  token0: {
    id: string                 // Token address
    symbol: string             // Token symbol
    name: string               // Token name
    decimals: number           // Token decimals
    price: number              // Current token price in USD
  }
  
  // Second token in the pair
  token1: {
    id: string                 // Token address
    symbol: string             // Token symbol
    name: string               // Token name
    decimals: number           // Token decimals
    price: number              // Current token price in USD
  }
  
  // Associated farm information (if applicable)
  farm: {
    id: string                 // Farm identifier
    provider: string           // Farm provider
    tvl: number                // Total value locked in farm
    apr: number                // Farm APR
    rewardRates: BigNumber[]   // Reward rates
    rewardTokens: {            // Reward tokens
      id: string               // Token address
      symbol: string           // Token symbol
      name: string             // Token name
      decimals: number         // Token decimals
      price: number            // Current token price in USD
    }[]
  } | null                     // Can be null if no farm exists
  
  // User-specific fields (only present when 'user' parameter is provided)
  balanceUSD?: number          // User's total position balance (vault + farm) in USD
  farmBalanceUSD?: number      // User's kodiak_farm/reward_vaults balance in USD
  vaultBalanceUSD?: number     // User's pool balance that is unstaked in USD
}
```

#### Example Requests

1. **Basic request for all positions on a specific chain**

   ```
   GET /vaults?chainId=80094&limit=20&offset=0
   ```
2. **Filter for high TVL, incentivized positions**

   ```
   GET /vaults?chainId=80094&rewardVault=true&sweetened=true&minimumTvl=10000
   ```
3. **Sort by highest APR descending**

   ```
   GET /vaults?chainId=80094&orderBy=totalApr&orderDirection=desc
   ```
4. **Get positions for a specific user, ordered by balance**

   ```
   GET /vaults?chainId=80094&user=0x836966B09854d7a9c6C8a978ea72e0d906cBdfB4&orderBy=balance&orderDirection=desc
   ```
5. **Filter for stable pools with minimum TVL**

   ```
   GET /vaults?chainId=80094&volatile=false&minimumTvl=10000
   ```
6. **Search for a specific token**

   ```
   GET /vaults?chainId=80094&search=BM
   ```

#### Error Handling

The API returns standard HTTP status codes:

* `200 OK`: Request successful
* `400 Bad Request`: Invalid parameters
* `404 Not Found`: Resource not found
* `500 Internal Server Error`: Server-side error

#### Notes on Chain IDs

Ensure you're using the correct chain ID for the network you wish to query. For example:

* 80094: BERA Mainnet
* (Add other supported chains as needed, only BERA mainnet supported for now)

***

For support or questions regarding the API,  join our Discord community at <https://discord.gg/vhZmNFNbCZ>.


# Baults

## Bault API

Get a list of all the Baults, their TVL and APY here:&#x20;

[https://backend.kodiak.finance/baults](https://staging.backend.kodiak.finance/baults)

## Bault Compounding Guide

This guide explains how compounding works in Baults, including the BGT auction mechanism, optimal usage patterns, and integration with the BountyHelper contract which is designed to make compounding free and effectively available for anyone to call.

### How Compounding Works

Baults are ERC4626-compliant vaults that stake tokens in reward vaults to earn BGT rewards. Over time, these BGT rewards accumulate but remain unclaimed in the reward vault. Compounding is the process of claiming these BGT rewards and either:

1. Receiving them directly as BGT tokens
2. Converting them to wrapped BGT tokens (like iBGT, yBGT, LBGT etc.)

### The Bounty Mechanism

Baults use a bounty-based auction system that:

1. Allows anyone to trigger the compounding process
2. Requires the caller to provide the configured "bounty" in bault asset (the staking tokens)
3. Gives the caller all the accumulated BGT rewards as either BGT or wrappedBGT of choice.

#### How the Bounty System Works

1. The caller pays a fixed amount of staking tokens (the bounty)
2. A small portion of the bounty (set by `compoundFeeBps`) goes to the protocol treasury
3. The rest of the bounty is staked in the reward vault, benefiting all vault users effectively increasing the share price for each user.
4. The caller receives all accumulated BGT rewards or a wrapped version

This creates a market-driven incentive for compounding - when the value of unclaimed BGT exceeds the bounty cost, someone will claim it.

This is a significant improvement over traditional compounding methods where the rewards are claimed and swapped for the asset, which can lead to slippage and loss of value while compounding. Additionally the swap system requires gatekeeping the compounding process and integration of swap routers for effective and secured compounding which limits the flexibility and accessibility of the compounding process.\
The bounty system allows anyone to compound and benefit from the compounding process while also giving the bault users maximal compounding value.

### Cost-Effective Compounding

With the introduction of the bounty system, you can benefit from the compounding process and claim the rewards. To compound cost-effectively:

1. **Monitor BGT accrual**: Wait until enough BGT has accumulated to justify the bounty cost
2. **Calculate break-even point**: Compare the value of claimable BGT against the bounty cost
3. **Choose the right wrapper**: Different wrappers have different valuations for BGT and are generally a better choice against BGT itself. So find the best wrapper that maximizes the value of the BGT rewards.
4. **Executing Claims**: Once the breakeven point has been reached, execute the claim transaction to receive the rewards as soon as possible to benefit from any excess rewards that accumulate.

Remember you are racing against other bots for the bounty, so act quickly while keeping a minimal profit margin to claim the rewards before someone else does.

### Previewing Potential Claims

Before executing a compound transaction, you can preview the expected outcome:

```solidity
// Preview the amount of BGT that would be claimed
uint256 bgtAmount = bault.earned();

// Preview the amount of wrapped BGT tokens that would be minted
uint256 wrappedAmount = bault.previewClaimBgtWrapper(wrapperAddress);
```

```typescript
import { createPublicClient, http } from 'viem';
import { berachain } from 'viem/chains';
import { BAULT_ABI } from './abis'; // Import your ABI

const client = createPublicClient({
  chain: berachain,
  transport: http()
});

// Preview the amount of BGT that would be claimed
const earnedBgt = await client.readContract({
  address: baultAddress,
  abi: BAULT_ABI,
  functionName: 'earned',
});

// Preview the amount of wrapped BGT tokens that would be minted
const wrappedAmount = await client.readContract({
  address: baultAddress,
  abi: BAULT_ABI,
  functionName: 'previewClaimBgtWrapper',
  args: [wrapperAddress],
});
```

```typescript

const client = createPublicClient({
  chain: berachain,
  transport: http()
});

// Preview the amount of BGT that would be claimed
const earnedBgt = await client.readContract({
  address: baultAddress,
  abi: BAULT_ABI,
  functionName: 'earned',
});

// Preview the amount of wrapped BGT tokens that would be minted
const wrappedAmount = await client.readContract({
  address: baultAddress,
  abi: BAULT_ABI,
  functionName: 'previewClaimBgtWrapper',
  args: [wrapperAddress],
});
```

### Performing Compounding

Always correctly set the minAmountOut after previewing to ensure you do not get frontrun.

#### Direct BGT Claim

```typescript
// Simple TypeScript with Viem - Direct BGT claim
import { createWalletClient, http } from 'viem';
import { privateKeyToAccount } from 'viem/accounts';
import { berachain } from 'viem/chains';
import { BAULT_ABI, ERC20_ABI } from './abis';

// Setup account and client
const account = privateKeyToAccount(PRIVATE_KEY);
const client = createWalletClient({
  account,
  chain: berachain,
  transport: http()
});

// Basic claim process
async function claimBgt(baultAddress) {
  // 1. Get staking token and bounty
  const stakingToken = await client.readContract({
    address: baultAddress,
    abi: BAULT_ABI,
    functionName: 'stakingToken',
  });

  const bounty = await client.readContract({
    address: baultAddress,
    abi: BAULT_ABI,
    functionName: 'bounty',
  });

  // 2. Approve the bounty transfer
  await client.writeContract({
    address: stakingToken,
    abi: ERC20_ABI,
    functionName: 'approve',
    args: [baultAddress, bounty],
  });
  
  // 3. Preview the amount of BGT that would be claimed
  // and make sure you pass it in as minAmountOut while claiming
  // to avoid getting frontrun
  const minAmountOut = await client.readContract({
    address: baultAddress,
    abi: BAULT_ABI,
    functionName: 'earned',
  });

  // 4. Execute the claim
  await client.writeContract({
    address: baultAddress,
    abi: BAULT_ABI,
    functionName: 'claimBgt',
    args: [account.address, minAmountOut],
  });
}
```

#### Wrapped BGT Claim (iBGT, LBGT, yBGT)

```typescript
// Simple TypeScript with Viem - Claim wrapped BGT
import { createWalletClient, http } from 'viem';
import { privateKeyToAccount } from 'viem/accounts';
import { berachain } from 'viem/chains';
import { BAULT_ABI, ERC20_ABI } from './abis';

// Setup account and client
const account = privateKeyToAccount(PRIVATE_KEY);
const client = createWalletClient({
  account,
  chain: berachain,
  transport: http()
});

// Function to claim wrapped BGT tokens
async function claimWrappedBgt(baultAddress, wrapperAddress) {
  // 1. Get required data from the bault
  const stakingToken = await client.readContract({
    address: baultAddress,
    abi: BAULT_ABI,
    functionName: 'stakingToken',
  });

  const bounty = await client.readContract({
    address: baultAddress,
    abi: BAULT_ABI,
    functionName: 'bounty',
  });

  // 2. Preview expected amount of wrapper tokens
  const minAmountOut = await client.readContract({
    address: baultAddress,
    abi: BAULT_ABI,
    functionName: 'previewClaimBgtWrapper',
    args: [wrapperAddress],
  });

  // 3. Approve and claim
  await client.writeContract({
    address: stakingToken,
    abi: ERC20_ABI,
    functionName: 'approve',
    args: [baultAddress, bounty],
  });

  const amountMinted = await client.writeContract({
    address: baultAddress,
    abi: BAULT_ABI,
    functionName: 'claimBgtWrapper',
    args: [wrapperAddress, account.address, minAmountOut],
  });

  return amountMinted;
}
```

#### BountyHelper: Zero-Capital Compounding (Recommended)

The BountyHelper is a specialized contract that enables anyone to compound Baults without needing the bounty payment upfront. It uses a clever mechanism to make compounding easy and accessible for everyone without need of the bounty.

#### How BountyHelper Works

1. **Pre-funding mechanism**: The helper maintains a balance of staking tokens that can be used for bounties
2. **Swap integration**: When using bounty helper, the claimed wrappers must be swapped for the staking token to return the bounty amount back to the contract. You can use any contract that can swap/exchange the bgtWrapper for the underlying staking token. We recommend using the Enso Router for swapping directly from the liquid wrapper to the underlying staking token.
3. **Refund system**: Returns any excess tokens to the caller after returning the free bounty amount accessed by the compounder and additionally rewards the compounder by transferring any amount of remaining staking token/bgt wrapper back to the user.

### Compounding Algorithm Overview using the BountyHelper

The compounding process follows these key steps:

1. **Discovery**: Find baults that are ready to compound
2. **Wrapper Selection**: Determine the best BGT wrapper (iBGT, YBGT, LBGT) for maximum value
3. **Quote Generation**: Get swap quote to convert wrapper to underlying staking token
4. **Profitability Check**: Ensure the swap output covers the required bounty
5. **Execution**: Send the compound transaction via BountyHelper

### Step 1: Check if Bault is Ready to Compound

```typescript
import { createPublicClient, http, getContract, parseAbi } from "viem";

const BAULT_ABI = parseAbi([
  "function bounty() external view returns (uint256)",
  "function earned() external view returns (uint256)",
  "function previewClaimBgtWrapper(address wrapper) external view returns (uint256)"
]);

async function checkBault(baultAddress: string) {
  const bault = getContract({
    address: baultAddress,
    abi: BAULT_ABI,
    client: publicClient
  });

  // Get current bounty requirement
  const bounty = await bault.read.bounty();

  // Get earned BGT available to claim
  const earnedBGT = await bault.read.earned();

  // Preview how much wrapper we'd get (using iBGT as example)
  const wrapperAmount = await bault.read.previewClaimBgtWrapper([wrapperOfChoice]); // ibgt for example

  console.log(`Bounty required: ${bounty}`);
  console.log(`BGT earned: ${earnedBGT}`);
  console.log(`Wrapper amount: ${wrapperAmount}`);

  return { bounty, earnedBGT, wrapperAmount };
}
```

### Step 2: Check Profitability

```typescript
async function isProfitable(baultAddress: string) {
  const { bounty, wrapperAmount } = await checkBault(baultAddress);

  // Get staking token address
    const stakingToken = await client.readContract({
      address: baultAddress,
      abi: BAULT_ABI,
      functionName: 'stakingToken',
    });

  // Get swap quote: wrapper -> staking token (enso router preffered)
  const quote = await getSwapQuote(
    iBGT_ADDRESS,
    stakingToken,
    wrapperAmount.toString()
  );

  // Check if swap output covers the bounty
  const isReady = BigInt(quote.amountOut) >= bounty;

  console.log(`Swap will give us: ${quote.amountOut}`);
  console.log(`Bounty required: ${bounty}`);
  console.log(`Ready to compound: ${isReady}`);

  return { isReady, quote };
}

// Helper function for getting swap quotes in desired format
async function getSwapQuote(fromToken: string, toToken: string, amount: string) {
  // This is where you'd integrate with:
  // - Enso Router (recommended)
  // - Your custom routing functions.
  // - Any other swap router
  // Your goal is to swap/exchange the claimed bgt wrapper into the underlying staking token (Kodiak island tokens)

  const quote = await fetch('/api/swap-quote', {
    method: 'POST',
    body: JSON.stringify({
      fromToken,    // iBGT address
      toToken,      // Staking token address
      amount,       // Wrapper amount to swap
      slippage: 500 // 5%
    })
  });

  return await quote.json(); // { amountOut, calldata, to }
}
```

### Step 3: Execute Compound Transaction

```typescript
const BOUNTY_HELPER_ABI = parseAbi([
  `function claimBgtWrapper(
    address bault,
    address bgtWrapper,
    address swapTarget,
    bytes calldata swapData,
    uint256 wrapperAmount,
    address bountyReceiver
  ) external`
]);

async function compoundBault(baultAddress: string) {
  // Get all the data we need
  const { wrapperAmount } = await checkBault(baultAddress);
  const { quote, isProfitable } = await isProfitable(baultAddress);

  const BOUNTY_HELPER_ADDRESS = "0x..."; // BountyHelper contract
  const PROFIT_RECEIVER = "0x..."; // Any address that should get the excess bgt claimed/staking token left after repaying bounty

  // Execute the compound transaction
  const txHash = await walletClient.writeContract({
    address: BOUNTY_HELPER_ADDRESS,
    abi: BOUNTY_HELPER_ABI,
    functionName: 'claimBgtWrapper',
    args: [
      baultAddress,        // Which bault to compound
      iBGT_ADDRESS,        // BGT wrapper to use
      quote.to,            // Swap router address
      quote.calldata,      // Swap transaction data
      wrapperAmount,       // Amount of wrapper to claim
      PROFIT_RECEIVER         // Where to send the bounty profit
    ]
  });

  console.log(`Compound transaction sent: ${txHash}`);
  return txHash;
}
```

### Key Points

#### What You Need

* A wallet with some BERA for gas
* Access to a swap router (Enso recommended).
  * Get your enso api key here (<https://shortcuts.enso.finance/developers>)
  * Look at how to use the api here (<https://docs.enso.build/api-reference/defi-shortcuts/optimal-route-between-two-tokens>)
* RPC endpoint for Berachain (<https://rpc.kodiak.finance>)

#### How You Profit

* You earn the excess **bounty** (mostly in staking tokens) for each successful compound
* No upfront capital required - BountyHelper funds the bounty
* Profit = `stakingTokenSwapOutput - baultBounty`

#### BGT Wrappers

Choose the best wrapper for maximum value:

* **iBGT**: Infrared liquid staking token
* **YBGT**: Yeet liquid staking token
* **LBGT**: Another liquid staking option

#### When to Compound

* `stakingTokenSwapOutput >= baultBounty` (profitable)
* Gas costs(generally dust) < expected profit

This simple flow shows how anyone can participate in bault compounding and earn rewards by helping optimize DeFi yields!


# Backend API

We provide an additional way to retrieve certain data using our api

## Base API url

```
https://backend.kodiak.finance
```

## Endpoints

#### Get a list of users by token (`GET /balances/<TOKEN_ADDRESS>`)

<table><thead><tr><th width="175">Query argument</th><th width="159">Required</th><th>Description</th></tr></thead><tbody><tr><td>blockNumber</td><td>Yes</td><td>Block number to which you need data</td></tr><tr><td>users</td><td>No</td><td>Comma-separated list of users to filter</td></tr></tbody></table>

Example:

```
http://backend.kodiak.finance/balances/0x7DCC39B4d1C53CB31e1aBc0e358b43987FEF80f7?blockNumber=99999999999&users=0xb83742330443f7413dbd2abdfc046db0474a944e
```

As an answer you will get a list of users and their total balances, including islands balances, farms, some external farms, as well as v3 positions and normal balances.  A description of all sources can be found in the sources

Response example:

<pre class="language-json"><code class="lang-json"><strong>{
</strong>  "results": [
    {
      "account": "0xb83742330443f7413dbd2abdfc046db0474a944e",
      "total": 42175.929775565106,
      "sources": [
        {
          "source": "balance",
          "value": 23378.656358324366
        },
        {
          "source": "island",
          "value": 1.1062169805412183,
          "extraData": {
            "islandId": "0xa0cabfc04fc420b3d31ba431d18eb5bd33b3f334"
          }
        },
        {
          "source": "external_vaults",
          "value": 10485.409406599369
        },
        {
          "source": "v3-position",
          "value": 0.015593277755401007,
          "extraData": {
            "positionId": "1917"
          }
        },
        {
          "source": "v3-position",
          "value": 8310.742200383076,
          "extraData": {
            "positionId": "1942"
          }
        }
      ],
      "expanded": "balance: 23378.656358324366, island: 1.1062169805412183, external_vaults: 10485.409406599369, v3-position: 0.015593277755401007, v3-position: 8310.742200383076"
    }
  ],
  "lastSyncedBlock": 4726990
}
</code></pre>

#### **Get token pricing information (**`GET /tokens`)

<table><thead><tr><th width="175">Query argument</th><th width="159">Required</th><th>Description</th></tr></thead><tbody><tr><td>addresses</td><td>Yes</td><td>Comma-separated list of token addresses</td></tr></tbody></table>

Example:

```
https://backend.kodiak.finance/tokens?addresses=0xC60Ea9801B3F1B01dA373C05381e6cE8ff94d76f
```

As an answer you will get an array of token objects containing pricing and metadata information for each requested token address.\
\
Response example:

```
[
  {
    "id": "0xc60ea9801b3f1b01da373c05381e6ce8ff94d76f",
    "symbol": "KODI SolvBTC.BNB-SolvBTC",
    "name": "Kodiak Island SolvBTC.BNB-SolvBTC-2%",
    "decimals": 18,
    "price": 92597.7754576649,
    "totalSupply": 594.801589203266,
    "priceStrategy": "vault",
    "lastIndexed": "2025-08-25T17:55:46.716Z"
  }
]
```


# Audits

Kodiak has done 3 rounds of audits on the core protocols, as well as rounds of audits focused on different new products (Panda Factory, Bault, Meta-Aggregator, Fungible, etc).  In all audits - all issues raised have been addressed and no critical issues were found.<br>

**Core Protocol**

December 2024, 0xMacro: focused audit on Kodiak Islands and Farms

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

April 2024, 0xMacro: Dex Core and Periphery, Islands, Farms, Tokens

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

February 2024, Kalos: Dex Core and Periphery, Islands, Farms, Tokens

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

**Panda Factory**

October 2024, 0xMacro: Panda Factory

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

**Bault**

May 2025, AstraSec: Bault (auto-compounding vaults)

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

**kX, Fungible**

May 2025, AstraSec: kX (aggregator), Fungible (NFT tokenization)

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

For technical reference, here is a brief technical overview of the various parts of the protocol:

* Dex V2: Exact fork of Uniswap V2
* Dex V3: Fork of Uniswap V3 with one small difference:&#x20;
  * Modified feeProtocol to uint32 in slot0 (only relevant for integrators, not normal users)
* Kodiak Island: "Modified from" Arrakis V1 vaults (ArrakisFinance/vault-v1-core). Key differences:&#x20;
  * Vaults are non-upgradeable after deployment (vs upgradeable in original implementation)
  * Simplified rebalances to enable "permissionless" fixed vault creation with no ownership
  * For managed vaults, rebalancing can route through liquidity throughout Berachain
* Kodiak Farm: "Modified from" Frax Communal Farm (FraxFinance/frax-solidity). Key differences:
  * Farms can be deployed permissionlessly via FarmFactory
* Panda Factory: Fully built in-house, very loosely "inspired by" pump.fun on Solana
* Bault: Fully built in-house, ERC-4626 compliant vaults that compound BGT with bounty mechanism
* Meta-Aggregator: Fully built in-house, Dex router that can call aggregator APIs
* Fungible: Fully built in-house, NFT tokenization product


# Brand Kit

Please find the Kodiak Brand Kit [here](https://drive.google.com/drive/folders/1JrcGoUzN1D0rdZ4kkxBAD2lghTgwj6HJ)&#x20;


# Terms of Use

**TERMS OF USE**

Last updated on July 7, 2026

OUR SERVICES ARE NOT OFFERED TO PERSONS OR ENTITIES WHO RESIDE IN, ARE CITIZENS OF, ARE LOCATED IN, ARE INCORPORATED IN, OR HAVE A REGISTERED OFFICE IN THE UNITED STATES OR ANY RESTRICTED TERRITORY (AS DEFINED BELOW) (ANY SUCH PERSON OR ENTITY FROM A RESTRICTED TERRITORY BEING A “RESTRICTED PERSON”). USE OF A VIRTUAL PRIVATE NETWORK (“VPN”) TO CIRCUMVENT THESE RESTRICTIONS IS PROHIBITED.

These terms of use, together with any additional agreements, documents and terms incorporated by reference, which includes any other terms and conditions or other agreement that KDK Protocol Labs S.A. (“Kodiak”, “we”, “us” and “our”) posts publicly or makes available to you or the person or entity you represent (“you” or “your”) (collectively, these “Terms”), are entered into between Kodiak and you concerning your use of, and access to, our (a) websites, including kodiak.finance; (b) web applications; mobile applications and (c) all associated sites linked thereto by Kodiak or its affiliates (collectively with any materials and services available therein, and successor website(s) or application(s) thereto, the “Site”).

As part of the Site, we provide a user interface (the “Platform”) to access (a) Kodiak DEX, a decentralized exchange platform for trading cryptocurrencies and other blockchain-based assets (“Digital Assets”) in a decentralized, peer-to-peer manner, (b) Kodiak Islands and Permissionless Islands,  automated liquidity management vaults, (c) Kodiak Sweetened Islands, an integrated incentive layer, (d) Panda Factory, a no-code token deployer factory, (e) kX, an advanced swap aggregator and API, (f) Baults, ERC-4626 compatible smart yield-maximizing, yield-bearing vaults, (g) Perps, a perpetuals exchange powered by the [Orderly One perpetual contract service](https://dex.orderly.network/), (h) Perp Bots, automated grid and copy trading bots for perpetual futures and (i) any other interfaces may be provided by Kodiak from time to time (collectively, the “Protocol”). These Terms expressly cover your rights and obligations, and our disclaimers and limitations of legal liability, relating to your use of, and access to, the Site, the Platform, the Protocol and all related tools, applications, data, software and other services provided by us (collectively, the “Services”). By accessing or using the Site or the Services, you accept and agree to be bound by and to comply with these Terms. If you do not agree to these Terms, then you must not access or use the Site or the Services.&#x20;

By accessing or using the Site or the Services, you agree that Kodiak does not provide execution, settlement, or clearing services of any kind and is not responsible for the execution, settlement, or clearing of transactions automated through the Services.

1. **Use of the Services**
   1. Eligibility. As a condition to accessing or using the Services or the Site, you represent and warrant that:
      1. if you are an individual, you are of legal age in the jurisdiction in which you reside and you have the legal capacity to enter into these Terms and be bound by them;
      2. if you are an entity, then you have the legal authority to accept these Terms;
      3. you are not a resident, national, or agent of, located in, incorporated or otherwise formed in, or have a registered office in, the United States;
      4. you are not a resident, national, or agent of, located in, incorporated or otherwise formed in, or have a registered office in, Antigua and Barbuda, Algeria, Bangladesh, Bolivia, Belarus, Burundi, Burma (Myanmar), Cote D'Ivoire (Ivory Coast), the regions of Crimea, Donetsk or Luhansk, Cuba, Democratic Republic of Congo, Ecuador, Iran, Iraq, Liberia, Libya, Magnitsky, Mali, Morocco, Nepal, North Korea, Somalia, Sudan, Syria, Venezuela, Yemen, Zimbabwe or any other country to which the United States, the United Kingdom or the European Union embargoes goods or imposes similar sanctions (collectively, “Restricted Territories”);
      5. you are not a member of any sanctions list or equivalent maintained by the United States government, the United Kingdom government, the European Union or the United Nations (a “Sanctioned Person”);
      6. you do not transact with or intend to transact with any Restricted Person or Sanctioned Person;
      7. you do not, and will not, use VPN software or any other privacy or anonymization tools or techniques to circumvent, or attempt to circumvent, any restrictions that apply to the Services; and
      8. your access to the Services (A) is not prohibited by and does not otherwise violate or assists you to violate any (1) laws, constitutions, treaties, statutes, codes, ordinances, principles of common and civil law and equity, orders, decrees, rules, regulations and municipal by-laws, whether domestic, foreign or international; (2) judicial, arbitral, administrative, ministerial, departmental and regulatory judgments, orders, writs, injunctions, decisions, rulings, decrees and awards of any (a) multinational or supranational body or organization, nation, government, state, province, country, territory, municipality, quasi-government, administrative, judicial or regulatory authority, agency, board, body, bureau, commission, instrumentality, court or tribunal or any political subdivision thereof, or any central bank (or similar monetary or regulatory authority) thereof, any taxing authority, any ministry or department or agency of any of the foregoing; (b) self-regulatory organization or stock exchange; (c) entity exercising executive, legislative, judicial, regulatory or administrative functions of or pertaining to government; or (d) any corporation or other entity owned or controlled, through stock or capital ownership or otherwise, by any of such entities or other bodies pursuant to the foregoing (each, a “Governmental Authority”); or (3) policies, practices and guidelines of, or contracts with, any Governmental Authority, which, although not actually having the force of law, are considered by such Governmental Authority as requiring compliance as if having the force of law, as the same may be amended from time to time and any successor thereto and in each case binding on, affecting or having jurisdiction over Kodiak, you, the Site or the Services (collectively, “Applicable Laws”); and (B) does not contributes to or facilitates any illegal activity.
   2. Acknowledgements. As a condition to accessing or using the Services or the Site, you acknowledge and agree that:
      1. from time to time the Site and the Services may be inaccessible or inoperable for any reason, including without limitation: (A) equipment malfunctions; (B) periodic maintenance procedures or repairs that we or any of its suppliers or contractors may undertake from time to time; (C) causes beyond our control or that we could not reasonably foresee; (D) disruptions and temporary or permanent unavailability of underlying software, including without limitation blockchain infrastructure; or (E) unavailability of third-party service providers or external partners for any reason;
      2. we reserve the right to suspend, restrict or modify access to the Site and the Services at any time in the event of any breach of these Terms, including, without limitation, if we reasonably believe any of your representations and warranties may be untrue or inaccurate, and we will not be liable to you, and you will hold us harmless from, any losses or damages you may suffer as a result of or in connection with the Site or the Services being inaccessible to you at any time or for any reason;
      3. we may change, replace, or discontinue (temporarily or permanently) some or all of the Services at any time in our sole discretion;
      4. the pricing information provided on the Site does not represent an offer, a solicitation of an offer, or any advice regarding, or recommendation to enter into, a transaction with Kodiak;
      5. Kodiak does not act as an agent for you or any other user of the Site or the Services;
      6. you are solely responsible for your use of the Services, including all of your transfers of Digital Assets;
      7. to the fullest extent not prohibited by Applicable Laws, we owe no fiduciary duties or liabilities to you or any other party, and that to the extent any such duties or liabilities may exist under Applicable Laws, you hereby irrevocably disclaim and waive all of such duties and liabilities and hold us harmless from any of the foregoing;
      8. you are solely responsible for reporting and paying any taxes applicable to your use of the Services;
      9. we have no control over, or liability for, the delivery, quality, safety, legality, or any other aspect of any Digital Assets that you may transfer to or from a third party and we are not responsible for ensuring that an entity with whom you transact with completes the transaction or is authorized to do so; and
      10. you bear the entire risk with any transactions in Digital Assets and in using the Services.
   3. User Responsibilities. As a condition to accessing or using the Services or the Site, you covenant to Kodiak the following:
      1. you (A) must provide all equipment, connectivity, and software necessary to connect to the Services and (B) are solely responsible for any costs and expenses, including Internet connection or mobile fees, which you incur when accessing the Services;
      2. in connection with using the Services, you will only transfer legally-obtained Digital Assets;
      3. you will comply with all Applicable Laws and obtain and maintain all applicable registrations or licenses under Applicable Laws in connection with using the Services, and you will not use the Site or the Services if the laws of your country, or any other Applicable Laws, prohibit you from doing so;
      4. any Digital Assets you use in connection with the Services are either (A) owned by you or (B) you are validly authorized to carry out actions using such Digital Assets; and
      5. in addition to complying with all restrictions, prohibitions, and other provisions of these Terms, you will (A) ensure that, at all times, all information that you provide on the Site and during your use of the Services is current, complete, and accurate and (B) maintain the security and confidentiality of your private keys associated with your Wallet (as defined below), passwords, API keys and other related credentials.
   4. Digital Wallet; Non-Custodial Services.&#x20;
      1. In order to use certain features of the Site and Services, you may be required to connect your digital asset wallet(s) or address(es) (collectively, “Wallet”) to the Platform.  You acknowledge that we are not responsible for transferring, safeguarding, or maintaining your private keys or any assets associated with your Wallet.  If you lose, mishandle or have stolen your Wallet private keys, you acknowledge that you may not be able to recover associated assets and that we are not responsible for such loss.&#x20;
      2. You acknowledge that you may disconnect your Wallet from the Platform at any time.
      3. You agree to notify us immediately if you suspect your linked Wallet has been compromised or otherwise suspect any security issues related to your use of the Services.
      4. You agree that you will not use the Services to transact with any digital currency that may be considered a security under Applicable Laws.&#x20;
      5. You acknowledge and agree that we may restrict, suspend or close your Wallet and access to the Platform for any reason or no reason, including if we reasonably believe that you have breached any of the terms of this Agreement.
      6. Digital Assets that you purchase or use in relation to the Services may be held in one or more Wallets of yours. We do not operate, maintain, control or have custody over any contents of your Wallet. We accept no responsibility for, or liability to, you in connection with your Wallet and make no representations or warranties regarding how the Platform or the Services will operate with any specific Wallet. Any issues relating to your Wallet should be addressed to your Wallet provider.&#x20;
      7. You acknowledge that we are not responsible for, and you agree to indemnify us for, any loss or damage arising from your failure to comply with the requirements hereunder.
2. **No Professional Advice or Fiduciary Duties**                                                                                                                       All information provided in connection with your access and use of the Site and the Services is for informational purposes only and should not be construed as professional advice. You should not take, or refrain from taking, any action based on any information contained on the Site or any other information that we make available at any time, including, without limitation, blog posts, articles, links to third-party content, Discord content, Telegram content, news feeds, tutorials, tweets, and videos. Before you make any financial, legal, or other decisions involving the Services, you should seek independent professional advice from an individual who is licensed and qualified in the area for which such advice would be appropriate. The Terms are not intended to, and do not, create or impose any fiduciary duties on us. You further agree that the only duties and obligations that we owe you are those set out expressly in these Terms.
3. **Prohibited Activities**                                                                                                                                                               By using the Site or the Services, you confirm that you will not use the Site or the Services to do any of the following (collectively, “Prohibited Uses”):

   1. violate any Applicable Laws including, without limitation, any applicable anti-money laundering and anti-terrorist financing laws and sanctions programs;
   2. engage in transactions involving items that infringe or violate any copyright, trademark, right of publicity or privacy or any other proprietary right under Applicable Laws, including but not limited to (i) sales, distribution, or access to counterfeit music, movies, software, or other licensed materials without the appropriate authorization from the rights holder (ii) use of Kodiak’s intellectual property, name, or logo, including use of Kodiak’s trade marks or service marks, without express consent from Kodiak or in a manner that otherwise harms Kodiak and (iii) any action that implies an untrue endorsement by or affiliation with Kodiak;
   3. use the Site and/or the Services in any manner that could interfere with, disrupt, negatively affect, or inhibit other users from fully enjoying the Site and/or the Services, or that could damage, disable, overburden, or impair the functioning of the Site or the Services in any manner;
   4. circumvent any content-filtering techniques, security measures or access controls that Kodiak employs on the Site, including without limitation through the use of a VPN;
   5. use any robot, spider, crawler, scraper, or other automated means or interface not provided by us to access the Site or the Services or to extract data, or introduce any malware, virus, Trojan horse, worm, logic bomb, drop-dead device, backdoor, shutdown mechanism or other harmful material into the Site or the Services;
   6. provide false, inaccurate, or misleading information while using the Site or the Services or engage in activity that operates to defraud Kodiak, other users of the Services, or any other person;
   7. engage in improper or abusive trading practices, including (i) any fraudulent act or scheme to defraud, deceive, trick or mislead; (ii) trading ahead of another user of the Services or front-running; (iii) fraudulent trading; (iv) accommodation trading; (v) fictitious transactions; (vi) pre-arranged or non-competitive transactions; (vii) violations of bids or offers; (viii) cornering, or attempted cornering, of any Digital Assets; (ix) wash trading (i.e. entering buy and sell orders at the same or similar prices, volumes, and times for the purpose of generating trading volume); (x) spoofing (i.e. entering buy or sell orders without a bona fide intent to execute such orders and with the intent to cancel such orders before execution); (xi) manipulation (i.e. trading for the purpose of affecting the prices of Digital Assets and generating artificial prices); (xii) knowingly making any bid or offer for the purpose of making a market price that does not reflect the true state of the market; (xiii) entering orders for the purpose of entering into transactions without a net change in either party’s open positions but a resulting profit to one party and a loss to the other party, commonly known as a “money pass”; or (xiv) any other trading activity that, we have, in our sole discretion, determined to be abusive, improper or disruptive to the operation of the Services.
   8. use or access the Site or Services to transmit, stake, wrap, exchange or otherwise interact with Digital Assets that are the direct or indirect proceeds of any criminal or fraudulent activity, including without limitation terrorism or tax evasion;
   9. use the Site or the Services in any way that is, in our sole discretion, libelous, defamatory, profane, obscene, pornographic, sexually explicit, indecent, lewd, vulgar, suggestive, harassing, stalking, hateful, threatening, offensive, discriminatory, bigoted, abusive, inflammatory, fraudulent, deceptive, or otherwise objectionable or likely or intended to incite, threaten, facilitate, promote, or encourage hate, racial intolerance, or violent acts against others;
   10. use the Site or the Services from a jurisdiction that we have, in our sole discretion, determined is a jurisdiction where the use of the Site or the Services is prohibited;
   11. harass, abuse, or harm of another person or entity, including Kodiak’s employees and service providers;
   12. impersonate another user of the Site or the Services or otherwise misrepresent yourself;&#x20;
   13. use the Site or the Platform for any purposes other than using the Services; or
   14. encourage, induce or assist any third party to engage in any of the activities prohibited under this Section 3 or any other provision of these Terms.

   The foregoing activities are representative, but not exhaustive, of Prohibited Uses. If you are uncertain as to whether or not your use of the Site or the Services involves a Prohibited Use or have other questions about how these requirements apply to you, then please contact us at <admin@kodiak.finance>.
4. **Your Content**                                                                                                                                                                    You hereby grant to us a royalty-free, fully paid-up, sublicensable, transferable, perpetual, irrevocable, non-exclusive, worldwide license to use, copy, modify, create derivative works of, display, perform, publish and distribute, in any form, medium, or manner, any content that is available to other users as a result of your use of the Site or the Services (collectively, “Your Content”), including, without limitation, for promoting Kodiak, its affiliates, the Services or the Site. You represent and warrant that (a) you own Your Content or have the right to grant the rights and licenses in these Terms and (b) Your Content and our use of Your Content, as licensed herein, does not and will not violate, misappropriate or infringe on any third party’s rights.
5. **Minting Digital Assets**
   1. **Minting**                                                                                                                                                                                  &#x20;

      You are permitted, but not required, to use the Services to facilitate Digital Asset minting and launch transactions. To mint Digital Assets through the Services you must, among other things, authenticate a request through your Wallet provider to effectuate a minting transaction through the Services. We reserve the absolute right to modify or impose additional minting terms through use of the Services. You expressly represent and warrant that you have the agency, authority, and capacity to perform the foregoing transactions from your Wallet. You represent, warrant, acknowledge and agree that you shall be deemed the creator or issuer of any Digital Assets issued through the use of the Services.
   2. **Original, Authorized, and Non-Infringing Content**                                                                                                &#x20;

      By minting Digital Assets through the Services, you represent and warrant that: Your Content, associated with the minted Digital Assets does not infringing on any intellectual property rights of any third party. To the extent Your Content contains any unoriginal material not owned or originally developed exclusively by you, including without limitation visual content, brand names, logos, third party trademarks, likenesses, material contributed by collaborators, content generated by algorithms or artificial intelligence (collectively, "Third Party Content") you further represent and warrant that you have the necessary licenses or permission to use such Third Party Content, or otherwise that you have a clear and compelling "fair use" defense in relation to their use of such Third Party Content. You are expressly prohibited from minting Digital Assets associated with or connected or related to unlicensed, unauthorized, unlawful, pornographic or infringing content.&#x20;
   3. **Limited License to Us of the NFTs You Create**                                                                                                      &#x20;

      You hereby acknowledge, understand, and agrees that minting Digital Assets through the Services constitutes an express and affirmative grant to us, our affiliates and successors a non-exclusive, world-wide, assignable, sublicensable, perpetual, and royalty-free license to make copies of, display, perform, reproduce, download, upload, and distribute Your Content associated with the Digital Assets on any media whether now known or later discovered for the general purpose of operating, promoting, sharing, developing, marketing, and advertising the Services or such Digital Assets, or any other lawful purpose related to our Services, including without limitation, the express right to: (i) display or perform Your Content on the Services, a third-party platform, social media posts, blogs, editorials, advertising, market reports, documentaries, virtual galleries, private galleries, museums, virtual environments, editorials, or to the public; (ii) indexing and storing Your Content in electronic databases, indexes, catalogues, smart contracts, or ledgers; and (iii) hosting, storing, distributing, uploading and reproducing one or more copies of Your Content.&#x20;
   4. **You Agree to indemnify the Company for Your Infringements**                                                                       &#x20;

      You agree to indemnify and hold harmless the Indemnified Parties (as defined below) for the minting, creation, promotion, publication, advertising, marketing, sale, or distribution of the Digital Assets that you mint (or any of Your Content that you contribute to the Services), including, without limitation, claims involving the actual or alleged infringement of any third party intellectual property or contractual rights.
6. **Proprietary Rights**
   1. You acknowledge that the Site or the Services may use, incorporate or link to certain open-source components and that your use of the Site or Services is subject to, and you will comply with, any applicable open-source licenses that govern any such open-source components (collectively, “Open-Source Licenses”). Without limiting the generality of the foregoing, you may not (i) resell, lease, lend, share, distribute, or otherwise permit any third party to use the Site or the Services; (ii) use the Site or the Services for time-sharing or service bureau purposes; or (iii) otherwise use the Site or the Services in a manner that violates any Open-Source Licenses.
   2. Excluding the open-source software described in Section 5(a), Your Content or third-party software that the Site or the Services incorporates you acknowledge and agree that Kodiak owns the Site and the Services, including all technology, content, software, images, text, graphics, illustrations, logos, patents, trademarks, service marks, copyrights, photographs, audio, videos and music and all intellectual property rights related thereto and other materials used, displayed, or provided on the Site or in connection with the Services but excluding Your Content (the “Company Content”) including all intellectual property rights subsisting therein. Kodiak hereby grants you a limited, revocable, transferable, license to access and use those portions of the Site and the Services that are proprietary to Kodiak solely in accordance with these Terms. Except as explicitly provided herein, nothing in these Terms shall be deemed to create a license in or under any Company Content or intellectual property rights, and you agree not to sell, license, rent, modify, distribute, copy, reproduce, transmit, publicly display, publicly perform, publish, adapt, edit or create derivative works from any Company Content. Use of the Company Content for any purpose not expressly permitted by these Terms is strictly prohibited. Company Content is made available solely for your personal, non-commercial use and may not be copied, reproduced, published, republished, modified, mirrored, uploaded, posted, transmitted, displayed, encoded, translated or distributed in any form or in way, including by e-mail or other electronic means, or stored in any retrieval system of any nature in any way, without the express prior written consent of us or such third party that may own such Company Content in each instance. You agree to abide by all copyright and other proprietary notices, information and restrictions contained in the Company Content and any other material accessed through the Site.
   3. Any of Kodiak’s product or service names, logos, and other marks used on the Site or as a part of the Services, including Kodiak's name and logo are trademarks owned by Kodiak, its affiliates, or its applicable licensors (collectively, the “Kodiak Trademarks”). You may not copy, imitate, or use them without the prior written consent of Kodiak or the applicable licensors, and notwithstanding to the contrary these Terms do not grant you any rights in the Kodiak Trademarks. You may not remove, obscure, or alter any legal notices displayed in or along with the Services.
   4. You may choose to, or we may invite you to submit comments, feedback, or ideas about the Site and the Services, including without limitation about how to improve the Site or our Services (“Feedback”). By submitting any Feedback, you agree that (i) your disclosure is non-confidential, gratuitous, unsolicited and without restriction and will not place us under any fiduciary or other obligation, (ii) you grant to us a perpetual, worldwide, royalty-free, irrevocable, transferable, sublicensable, non-exclusive and fully paid-up right to copy, use, reproduce, modify, adapt, publish, create derivative works from, translate, transmit, display, distribute, market, promote, sell or offer for sale, rent or lease such information or materials or any portions thereof (including any ideas for new products or Services or modifications to existing products or Services) and/or products or Services which practice or embody, or are configured for use in practicing, such information or materials or any portion thereof, in any form or medium known or later developed, in furtherance of these Terms and the actions and transactions contemplated hereby, including the right to bring an action for infringement of these rights, (iii)  we are free to use the Feedback without any additional compensation to you, and/or to disclose the Feedback on a non-confidential basis or otherwise to anyone and (iv) you will have no claim against for any actual or alleged infringement of any proprietary rights, rights of privacy or publicity, moral rights or rights of attribution in connection with our use of any Feedback you provide. You further acknowledge that, by acceptance of your submission, we do not waive any rights to use similar or related comments, feedback and ideas previously known to us, or developed by our employees, or obtained from sources other than you.
   5. You acknowledge and understand that the Services are non-custodial. When you deposit Digital Assets into any Kodiak-developed smart contract, you retain control over those Digital Assets at all times. The private key associated with the Wallet from which you transfer Digital Assets is the only private key that can control the Digital Assets you transfer into Kodiak-developed smart contracts. In some cases, you may withdraw Digital Assets from any Kodiak-developed smart contract only to the digital address from which you deposited the Digital Assets.
7. **Third Party Links**                                                                                                                                                           The Site or the Services may provide, or third parties may provide, links to other external sites, applications or resources. You acknowledge and agree that we are not responsible for the availability of such external sites, applications or resources, does not endorse and is not responsible or liable for any content, advertising, products, or other materials on or available from such sites or resources. You further acknowledge and agree that we shall not be responsible or liable, directly or indirectly, for any damage or loss caused or alleged to be caused by or in connection with use of or reliance on any such content, goods, or services available on or through any such site or resource.
8. **Modification, Suspension and Termination**                                                                                                              We may, at our sole discretion, from time to time and with or without prior notice to you, modify, suspend or disable (temporarily or permanently) the Site or the Services, in whole or in part, for any reason whatsoever. Upon termination of your access, your right to use the Services will immediately cease. We will not be liable for, and you agree to indemnify us for, any losses suffered by you resulting from any modification to any Services or from any modification, suspension, or termination, for any reason, of your access to all or any portion of the Site or the Services.&#x20;
9. **Risks**
   1. By using the Services or interacting with the Site in any way, you represent and warrant that you understand the inherent risks associated with cryptographic systems and blockchain-based networks; Digital Assets, including the usage and intricacies of native Digital Assets, smart contract-based tokens, and systems that interact with blockchain-based networks. Kodiak does not own or control any of the underlying software through which blockchain networks are formed. In general, the software underlying blockchain networks is open source, such that anyone can use, copy, modify, and distribute it. By using the Services, you acknowledge and agree that (i) Kodiak is not responsible for the operation of the software and networks underlying the Services, (ii) there exists no guarantee of the functionality, security, or availability of such software and such networks, and (iii) the underlying networks are subject to sudden changes in operating rules, such as those commonly referred to as “forks,” which may materially affect the Services.&#x20;
   2. You acknowledge and agree that (i) blockchain networks use public/private key cryptography, (ii) you alone are responsible for securing your private keys, (iii) we do not have access to your private keys, (iv) losing control of your private keys will permanently and irreversibly deny you access to your Digital Assets, (v) neither Kodiak nor any other person or entity will be able to retrieve or protect your Digital Assets and (vi) if your private keys are lost, then you will not be able to transfer your Digital Assets to any other blockchain address or wallet and if this occurs, then you will not be able to realize any value or utility from the Digital Assets that you may hold.
   3. The Services and your Digital Assets could be impacted by one or more regulatory inquiries or regulatory actions, which could impede or limit the ability of Kodiak to continue to make available its proprietary software and, thus, could impede or limit your ability to access or use the Services.
   4. You acknowledge and understand that cryptography is a progressing field with advances in code cracking or other technical advancements, such as the development of quantum computers, which may present risks to Digital Assets and the Services, and could result in the theft or loss of your Digital Assets. To the extent possible, we intend to use commercially reasonable efforts to update or cause to be updated Kodiak-developed smart contracts related to the Services to account for any advances in cryptography and to incorporate additional security measures necessary to address risks presented from technological advancements, but you agree that such intention does not guarantee or otherwise ensure full security of the Services.
   5. You acknowledge that the Services are subject to flaws and that you are solely responsible for evaluating any code provided by the Services or Site. This warning and others we provide in these Terms in no way evidence or represent an ongoing duty to alert you to all of the potential risks of utilizing the Services or accessing the Site.
   6. Although we intend to provide accurate and timely information on the Site and during your use of the Services, the Site and other information available when using the Services may not always be entirely accurate, complete, or current and may also include technical inaccuracies or typographical errors. To continue to provide you with as complete and accurate information as possible, information may be changed or updated from time to time without notice, including, without limitation, information regarding our policies. Accordingly, you should verify all information before relying on it, and all decisions based on information contained on the Site or as part of the Services are your sole responsibility. No representation is made as to the accuracy, completeness, or appropriateness for any particular purpose of any information distributed via the Site or otherwise when using the Services. Prices and pricing information may be higher or lower than prices available on platforms providing similar services.
   7. Any use or interaction with the Services requires a comprehensive understanding of applied cryptography and computer science to appreciate the inherent risks, including those listed above. You represent and warrant that you possess relevant knowledge and skills to appreciate and understand such risks. Any reference to a type of Digital Asset on the Site or otherwise during the use of the Services does not indicate our approval or disapproval of the technology on which the Digital Asset relies and should not be used as a substitute for your understanding of the risks specific to each type of Digital Asset.
   8. Use of the Services may carry financial risk. Digital Assets are, by their nature, highly experimental, risky, and volatile. Transactions entered in connection with the Services are irreversible, final and there are no refunds. You acknowledge and agree that you will access and use the Site and the Services at your own risk. The risk of loss in trading, staking, locking or otherwise interacting with Digital Assets can be substantial. You should, therefore, carefully consider whether such activities are suitable for you in light of your circumstances and financial resources. By using the Services, you represent and warrant that you have been, are, and will be solely responsible for making your independent appraisal and investigations into the risks of a given transaction and the underlying Digital Assets. You represent that you have sufficient knowledge, market sophistication, professional advice, and experience to make your evaluation of the merits and risks of any transaction conducted in connection with the Services or any Digital Asset. You accept all consequences of using the Services, including the risk that you may lose access to your Digital Assets indefinitely. All transaction decisions are made solely by you. Notwithstanding anything in these Terms, we accept no responsibility whatsoever for, and will in no circumstances be liable to you in connection with, your use of the Services.
   9. You and we agree to comply with all Applicable Laws and acknowledge that such compliance may require us to, upon request by government agencies, take certain actions or provide information, including without limitation information about you, which may not be in your best interests.
   10. You are responsible for all trades and transfer you place, including any erroneous orders that may be filled. We do not take any action to resolve erroneous trades or transfers that result from your errors.&#x20;
   11. Any Services you interact with are entirely your own responsibility and liability, and we are not a party to the Protocol.
   12. At any time, your access to your Digital Assets may be suspended or terminated or there may be a delay in your access or use of your Digital Assets which may result in the Digital Assets diminishing in value.
   13. The Services may be suspended or terminated for any reason or no reason, which may limit your access to your Digital Assets.
   14. You hereby assume, and agree that Kodiak will have no responsibility or liability for, the risks set forth in this Section 8. You hereby irrevocably waive, release and discharge all claims, whether known or unknown to you, against Kodiak, its affiliates, and each of their respective shareholders, members, directors, officers, managers, employees, lawyers, accountants, advisors, agents, representatives, suppliers and contractors related to any of the risks set forth in this Section 8.
10. **Indemnification**                                                                                                                                                     You agree you will defend, indemnify, and hold harmless Kodiak, its affiliates, and each of their respective shareholders, members, directors, officers, managers, employees, lawyers, agents, accountants, advisors, representatives, suppliers, and contractors (collectively, “Indemnified Parties”) from any claim, demand, lawsuit, action, proceeding, investigation, liability, damage, loss, cost or expense, including without limitation legal fees and expenses, arising out of or relating to: (a) your use of, access to or conduct in connection with, the Site, the Platform, Company Content, the Services or Digital Assets; (b) Digital Assets associated with your Wallets; (c) any Feedback, Your Content or user content you provide to Kodiak including without limitation misleading, false, or inaccurate information; (d) your violation of these Terms; (e) your infringement or misappropriation of the rights of any other person or entity; (f) your wilful misconduct; (g) your violation of any Applicable Laws; or (h) any other party’s access and use of the Site, the Platform, Company Content or the Services with your Wallet, unique username, password or other appropriate security code. If you are obligated to indemnify any Indemnified Party, we (or, at its discretion, the applicable Indemnified Party) will have the right, in our sole discretion, to control any action or proceeding and to determine whether we wish to settle, and if so, on what terms, and you agree to corporate with us in connection with the foregoing.
11. **Disclaimers**
    1. We are a developer of open-source software. Kodiak does not operate a Digital Asset exchange platform or offer trade execution or clearing services and, therefore, has no oversight, involvement, or control concerning your transactions using the Services. All transactions between users of Kodiak-developed open-source software are executed peer-to-peer directly between the users’ digital addresses through a smart contract. You are responsible for complying with all Applicable Laws.
    2. You understand that Kodiak is not registered or licensed by the U.S. Commodity Futures Trading Commission, the U.S. Securities and Exchange Commission or any other financial regulatory authority. No financial regulatory authority has reviewed or approved the use of the Kodiak-developed open-source software. The Site and the Kodiak-developed open-source software do not constitute advice or a recommendation concerning any commodity, security, or other Digital Asset or instrument. Kodiak is not acting as an investment adviser or commodity trading adviser to any person or entity.
    3. Kodiak does not own or control the underlying software protocols that are used in connection with the Services. In general, the underlying protocols are open source and anyone can use, copy, modify, and distribute them. Kodiak is not responsible for the operation of the underlying protocols, and Kodiak makes no guarantee of their functionality, security, or availability.
    4. TO THE MAXIMUM EXTENT PERMITTED UNDER APPLICABLE LAWS, YOU UNDERSTAND AND AGREE THAT THE SITE, THE PLATFORM AND THE SERVICES (AND ANY OF THEIR CONTENT OR FUNCTIONALITY) PROVIDED BY OR ON BEHALF OF US ARE PROVIDED ON AN “AS IS” AND “AS AVAILABLE” BASIS, AND WE EXPRESSLY DISCLAIM, AND YOU HEREBY WAIVE, ANY REPRESENTATIONS, CONDITIONS OR WARRANTIES OF ANY KIND, WHETHER EXPRESS OR IMPLIED, LEGAL, STATUTORY OR OTHERWISE, OR ARISING FROM STATUTE, OTHERWISE IN LAW, COURSE OF DEALING, OR USAGE OF TRADE, INCLUDING, WITHOUT LIMITATION, IMPLIED OR LEGAL WARRANTIES AND CONDITIONS OF MERCHANTABILITY, MERCHANTABLE QUALITY, QUALITY OR FITNESS FOR A PARTICULAR PURPOSE, TITLE, SECURITY, AVAILABILITY, RELIABILITY, ACCURACY, QUIET ENJOYMENT AND NON-INFRINGEMENT OF THIRD PARTY RIGHTS. WITHOUT LIMITING THE FOREGOING, WE DO NOT REPRESENT OR WARRANT THAT THE SITE, THE PLATFORM OR THE SERVICES (INCLUDING ANY DATA RELATING THERETO) WILL BE UNINTERRUPTED, AVAILABLE AT ANY PARTICULAR TIME, OR ERROR-FREE. FURTHER, WE DO NOT WARRANT THAT ERRORS IN THE SITE OR THE SERVICE ARE CORRECTABLE OR WILL BE CORRECTABLE.
    5. You acknowledge that your data on the Site or the Services may become irretrievably lost or corrupted or temporarily unavailable due to a variety of causes, and agree that, to the maximum extent permitted under Applicable Laws, we will not be liable for any loss or damage caused by denial-of-service attacks, software failures, viruses or other technologically harmful materials (including those which may infect your computer equipment), protocol changes by third-party providers, Internet outages, force majeure events or other disasters, scheduled or unscheduled maintenance, or other causes either within or outside our control.
    6. The disclaimer of implied warranties contained herein may not apply if and to the extent such warranties cannot be excluded or limited under the Applicable Law of the jurisdiction in which you reside.
12. **Exclusion of Consequential Damages**                                                                                                                            You acknowledge and agree that in no event shall the Indemnified Parties be liable for any incidental, indirect, special, punitive, consequential or similar damages or liabilities whatsoever (including, without limitation, damages for loss of fiat, assets, data, information, revenue, opportunities, use, goodwill, profits or other business or financial benefit) arising out of or in connection with the Site, the Platform, Company Content or the Services and any of their content and functionality, any execution or settlement of a transaction, any performance or non-performance of the Site, the Services, the Platform, your Digital Assets or any other product, service or other item provided by or on behalf of Kodiak, whether under contract, tort (including negligence), civil liability, statute, strict liability, breach of warranties, or under any other theory of liability, and whether or not the Indemnified Parties have been advised of, knew of or should have known of the possibility of such damages and notwithstanding any failure of the essential purpose of these Terms or any limited remedy hereunder. In addition, you acknowledge and agree that Kodiak shall not be in any way responsible for the execution or settlement of transactions between users of Kodiak-developed open-source software.
13. **Limitation of Liability**
    1. Under no circumstances will any Indemnified Party be responsible for any damage, loss or injury resulting from hacking, tampering or other unauthorized access or use of the Site, the Platform, the Services or the Company Content and other information contained therein. To the maximum extent permitted by Applicable Laws, we assume no liability or responsibility for any (i) errors, mistakes, or inaccuracies of content; (ii) personal injury or property damage, of any nature whatsoever, resulting from your access to or use of our Site, the Platform, Company Content or the Services; (iii) any unauthorized access to or use of our secure servers and/or any and all personal information stored therein; (iv) any interruption or cessation of transmission to or from the Site, the Platform or the Services; (v) any bugs, viruses, trojan horses, or the like that may be transmitted to or through our Site, the Platform, Company Content or the Services by any third party; (vi) any errors or omissions in any content or for any loss or damage incurred as a result of the use of any content posted, emailed, transmitted, or otherwise made available through the Site, the Platform or the Services; and/or (vii) Your Content or the defamatory, offensive, or illegal conduct of any third party You agree that if, notwithstanding the other provisions of these Terms, an Indemnified Party is found to be liable for any claim, demand, lawsuit, action, proceeding, investigation, liability, damage, loss, cost or expense, such Indemnified Party’s liability shall in no event exceed the amount of the fees paid by you to Kodiak under these Terms, if any, in the one-month period immediately preceding the event giving rise to the claim for liability, if any.
    2. This limitation of liability section applies whether the alleged liability is based on contract, tort, negligence, strict liability, or any other basis, even if we have been advised of the possibility of such damage. The foregoing limitation of liability shall apply to the fullest extent permitted by Applicable Laws.
14. **Force Majeure**                                                                                                                                                 We will have no responsibility or liability for any failure or delay in performance of the Site, the Platform or any of the Services, or any loss or damage that you may incur, due to any circumstance or event beyond our control, including any (a) flood, extraordinary weather conditions, earthquake, or other act of God, (b) fire, (c) war, (d) insurrection, (e) riot, (f) labour dispute, (g) accident, (h) epidemic or pandemic, (i) action of government, (j) new laws or regulations or change in existing laws or regulations or the interpretation or enforcement of any of the foregoing, (k) communications, (l) power failure, (m) equipment or software unavailability, disruption or malfunction, (n) hacking or other attack on the Site, the Platform or the Services, (o) the unavailability, disruption or malfunction of any network or blockchains or (p) the unavailability, disruption or malfunction of the Internet.
15. **Survival**                                                                                                                                                                               The following sections of these Terms will survive any termination of your access to the Site or the Services, regardless of the reasons for its expiration or termination, in addition to any other provision which by law or by its nature should survive: Sections 4 through 18.
16. **Governing Law**                                                                                                                                                                 The interpretation and enforcement of these Terms, and any dispute related to these Terms, the Site or the Services, will be governed by and construed and enforced under the laws of Panama without regard to conflict of law rules or principles (whether of Panama or any other jurisdiction) that would cause the application of the laws of any other jurisdiction. You agree that we may initiate a proceeding related to the enforcement or validity of our intellectual property rights in any court having jurisdiction. For any other proceeding that is not subject to arbitration under these Terms, the courts located in Panama will have exclusive jurisdiction. You waive any objection to venue in any such courts.
17. **Dispute Resolution and Arbitration**                                                                                                                        PLEASE READ THE FOLLOWING SECTION CAREFULLY BECAUSE IT REQUIRES YOU TO ARBITRATE CERTAIN DISPUTES AND CLAIMS WITH KODIAK AND LIMITS HOW YOU CAN SEEK RELIEF FROM KODIAK. ALSO, ARBITRATION PRECLUDES YOU FROM SUING IN COURT OR HAVING A JURY TRIAL.
    1. You and we agree that any dispute arising out of or related to these Terms, the Site or the Services is personal to you and us and that any dispute will be resolved solely through individual action, and will not be brought as a class arbitration, class action, or any other type of representative proceeding.
    2. Except for disputes in which you or we seek injunctive or other equitable relief for the alleged unlawful use of intellectual property, you and we waive all rights to a jury trial and to have any dispute arising out of or related to these Terms or the Services resolved in court. Instead, for any dispute or claim that you have against us or relating in any way to the Site or the Services, you agree to first contact us and attempt to resolve the claim informally by sending a written notice of your claim (“Notice”) to us by email at <admin@kodiak.finance>. The Notice must: (i) include your name, residence address, email address, and telephone number; (ii) describe the nature and basis of the claim; and (iii) set forth the specific relief sought. Our notice to you will be similar in form to that described above. If you and Kodiak cannot reach an agreement to resolve the claim within thirty (30) days after such Notice is received, then either party may submit the dispute to binding arbitration administered by the Centro de Conciliación y Arbitraje de PanamáCentre (“CeCAP”) or, under the limited circumstances set forth above, in court. All disputes submitted to the CeCAP will be resolved through confidential, binding arbitration before one arbitrator (the “Arbitrator”). The place of arbitration shall be Panama unless the parties agree otherwise and shall be conducted under CeCAP’s Arbitration Regulation (the “CeCAP Rules”). The language to be used in the arbitral proceedings shall be English. The most recent version of the CeCAP Rules are available on the CeCAP website and are hereby incorporated by reference. You either acknowledge and agree that you have read and understand the CeCAP Rules or waive your opportunity to read the CeCAP Rules and waive any claim that the CeCAP Rules are unfair or should not apply for any reason.
    3. The Arbitrator will have exclusive authority to make all procedural and substantive decisions regarding any dispute and to grant any remedy that would otherwise be available in court, including the power to determine the question of arbitrability. The Arbitrator may conduct only an individual arbitration and may not consolidate more than one individual’s claims, preside over any type of class or representative proceeding or preside over any proceeding involving more than one individual.
    4. The Arbitrator, Kodiak, and you will maintain the confidentiality of any arbitration proceedings, judgments and awards, including, but not limited to, all information gathered, prepared, and presented for purposes of the arbitration or related to the dispute(s) therein. The Arbitrator will have the authority to make appropriate rulings to safeguard confidentiality unless the law provides to the contrary. The duty of confidentiality does not apply to the extent that disclosure is necessary to prepare for or conduct the arbitration hearing on the merits, in connection with a court application for a preliminary remedy or in connection with a judicial challenge to an arbitration award or its enforcement, or to the extent that disclosure is otherwise required by law or judicial decision.
    5. You and Kodiak agree that for any arbitration you initiate, you will pay the filing fee and all other CeCAP fees and costs. For any arbitration initiated by Kodiak, Kodiak will pay all CeCAP fees and costs. You and Kodiak agree that the courts of Panama have exclusive jurisdiction over the enforcement of an arbitration award.
    6. Any claim arising out of or related to these Terms or the Services must be filed within one year after such claim arose; otherwise, the claim is permanently barred, which means that you and Kodiak will not have the right to assert the claim.
    7. If any portion of this Section 16 is found to be unenforceable or unlawful for any reason: (i) the unenforceable or unlawful provision shall be severed from these Terms; (ii) severance of the unenforceable or unlawful provision shall have no impact whatsoever on the remainder of this Section 16 or the parties’ ability to compel arbitration of any remaining claims on an individual basis under this Section 16; and (iii) to the extent that any claims must therefore proceed on a class, collective, consolidated, or representative basis, such claims must be litigated in a civil court of competent jurisdiction and not in arbitration, and the parties agree that litigation of those claims shall be stayed pending the outcome of any individual claims in arbitration. Further, if any part of this Section 16 is found to prohibit an individual claim seeking injunctive relief, then that provision will have no effect to the extent such relief is allowed to be sought out of arbitration, and the remainder of this Section 16 will be enforceable.
18. **Amendments**                                                                                                                                                                     We reserve the right, at our sole discretion, to amend these Terms from time to time. If we make changes, we will provide you with notice of such changes, which may include providing notice through the Services or updating the date at the top of these Terms. Unless we state otherwise in our notice, all such modifications are effective immediately, and your continued use of the Site and the Services after we provide that notice will confirm your acceptance of the changes. If you do not agree to the amended Terms, then you must stop using the Site and the Services.
19. **General**
    1. You acknowledge and agree that our privacy policy, which is available at [Privacy Policy](https://documentation.kodiak.finance/informational/privacy-policy), is incorporated herein by reference and forms part of these Terms.
    2. You consent to receive all communications, agreements, documents, receipts, notices, and disclosures electronically (collectively, our “Communications”) that we provide in connection with these Terms, the Site or any Services. You agree that we may provide our Communications to you by posting them on the Site or by emailing them to you at the email address you provide in connection with using the Services, if any.&#x20;
    3. Any right or remedy of any Indemnified Party set forth in these Terms is in addition to, and not in lieu of, any other right or remedy whether described in these Terms or under Applicable Laws, whether at law or in equity. The failure or delay of such Indemnified Party in exercising any right, power, or privilege under these Terms shall not operate as a waiver thereof.
    4. The invalidity or unenforceability of any provision of these Terms shall not affect the validity or enforceability of any other provision of these Terms, all of which shall remain in full force and effect.
    5. You acknowledge and agree that we will have no responsibility or liability for any failure or delay in performance of the Site or any of the Services, or any loss or damage that you may incur, due to any circumstance or event beyond our control, including without limitation any flood, extraordinary weather conditions, earthquake, or other act of God, fire, war, insurrection, riot, labor dispute, accident, action of government, communications, power failure, or equipment or software malfunction.
    6. You agree that you may not assign or transfer any right to use the Site or the Services, or any of your rights or obligations under these Terms, without our express prior written consent, including by operation of law or in connection with any change of control, which may be withheld at our sole discretion. We may assign or transfer any or all of our rights or obligations under these Terms, in whole or in part, without notice or obtaining your consent or approval.
    7. Headings of sections are for convenience only and shall not be used to limit or construe such sections.
    8. These Terms contain the entire agreement between you and Kodiak and supersede all prior and contemporaneous understandings between the parties regarding the Site and the Services.
    9. In the event of any conflict between these Terms and any other agreement you may have with us, these Terms will control unless the other agreement specifically identifies these Terms and declares that the other agreement supersedes these Terms.
    10. You agree that, except as otherwise expressly provided in this Agreement, there shall be no third-party beneficiaries to the Agreement other than the Indemnified Parties.


# Privacy Policy

KODIAK PRIVACY POLICY

Last updated March 13, 2024

This privacy policy (the “Privacy Policy”) explains how KDK Protocol Labs S.A. (“Kodiak”, “we”, “us” and “our”) collects, uses, and discloses information about you or the person or entity you represent (“you” or “your”) through our websites, web applications, and other online products and services (collectively, the “Services”) or when you otherwise interact with us. We may change this Privacy Policy from time to time. If we make changes, we will notify you by revising the date at the top of the Privacy Policy and, in some cases, we may provide you with additional notice (such as adding a statement to our homepage or sending you a notification). We encourage you to review the Privacy Policy whenever you access the Services or otherwise interact with us to stay informed about our information practices and the choices available to you.

By using the Sites or the Services, you accept the terms of this Privacy Policy and our terms of use (the “Terms”), and consent to our collection, use, disclosure, and retention of your information as described in this Privacy Policy.  If you have not done so already, please also review our Terms. If you do not agree with any part of this Privacy Policy or our Terms, then please do not use the Sites or any of the Services.

1\.                   Information We Collect

*(a)                Information You Provide to Us*

We collect information you provide directly to us. For example, we collect information when you access or use the Services, fill out a form, engage in a transaction, request customer support or otherwise communicate with us. The types of information we may collect include your email address and any other information you choose to provide.

*(b)                Automatically Collected Information*

When you access or use the Services, we automatically collect information about you, which may include the following:

(i)                  Contact Information: This may include your name, email address, physical address and country information.

(ii)                Financial Information: This may include your blockchain protocol network address, cryptocurrency wallet information, transaction history, trading data and associated fees paid.

(iii)               Transaction Information: This may include information about the transactions you make using the Services, such as the type of transaction, transaction amount and timestamp.

(iv)               Correspondence: This may include your feedback, questionnaire and other survey responses and information you provide to our support teams, including via our help chat or social media messaging channels.

(v)                 Online Identifiers Log Information: We collect identifier and log information about your use of the Services, including username, geolocation or tracking details, the type of browser you use, access times, pages viewed, your IP address, and the page you visited before navigating to our Services.

(vi)               Usage Data: This may include conversion events, user preferences, crash logs and other data collected via cookies and similar technologies.

(vii)             Device Information: We collect information about the computer or mobile device you use to access our Services, including the hardware model, operating system and version, unique device identifiers, and mobile network information.

(viii)           Information Collected by Cookies and Other Tracking Technologies: We and third parties we authorize may use various technologies to collect information, including cookies and web beacons. Cookies are small data files stored on your hard drive or in device memory that help us improve our Services and your experience, see which areas and features of our Services are popular, and count visits. Web beacons are electronic images that may be used in our Services or emails and help deliver cookies, count visits, and understand usage and campaign effectiveness. For more information about cookies and how to disable them, please see Section 9 below.

*(c)                 Information We Collect from Other Sources*

We may obtain information from other sources, including third parties, and combine that with information we collect through our Services.

*(d)                Information We Will Never Collect*

We will never ask you to share your private keys or wallet seed. Never trust anyone or any site that asks you to enter your private keys or wallet seed.

2\.                   How We Use Information

We use the information we collect to provide, maintain, and improve the Services, including as described in the Terms. We may also use the information we collect to:

(a)                send you technical notices, updates, security alerts and support and administrative messages, and to respond to your comments, questions and customer service requests;

(b)                communicate with you about products, services, offers, and events offered by us and others, and provide news and information we think will be of interest to you, which may be provided by any means, including by e-mail, in-app notifications, push notifications and display advertising;

(c)                 personalize your experience when you visit or use the Sites or our Services;

(d)                administer contests, promotions, surveys and other Service features;

(e)                monitor and analyze trends, usage, and activities in connection with the Services;

(f)                  comply with applicable laws, lawful requests and legal processes, including responding to court orders or requests from regulatory authorities;

(g)                generate aggregate or de-identified data and use such data for any lawful purpose, including research and analytics;

(h)                testing, research, analysis, product development and improve your experience;

(i)                  detect, investigate and prevent fraudulent transactions and other illegal activities and protect the rights and property of Kodiak and others;

(j)                  monitor and verify identity or service access, combat spam, malware or security risks;

(k)                 investigate and address user concerns;

(l)                  monitor and improve customer support responses and processes;

(m)              perform internal operations necessary to provide the Services, including to troubleshoot software bugs and operational problems; and

(n)                enforce our agreements with third parties and address violations of our Terms or agreements for other products or services.

3\.                   Sharing of Information

We do not share or sell the personal information that you provide us with other organizations without your express consent, except as described in this Privacy Policy. We may share information about you as follows or as otherwise described in this Privacy Policy:

(a)                with vendors, consultants and other service providers who need access to such information to carry out work on our behalf, including hosting, email and database services;

(b)                in response to a request for information if we believe disclosure is in accordance with, or required by, any applicable law, regulation, or legal process;

(c)                 if we believe your actions are inconsistent with our user agreements or policies, or to protect the rights, property and safety of Kodiak or others;

(d)                if we believe in good faith that the disclosure of personal information is necessary to prevent harm to another person;

(e)                to report suspected illegal activity;

(f)                  to investigate violations of our Terms, agrees for other products or services, or any other applicable policies;

(g)                in connection with, or during negotiations of, any merger, sale of company assets, financing, or acquisition of all or a portion of our business by another company or bankruptcy transaction or proceeding;

(h)                between and among Kodiak and our current and future parents, affiliates, subsidiaries, and other companies under common control and ownership; and

(i)                  with your consent or at your direction.

4\.                   Advertising and Analytics Services Provided by Others

We may allow others to provide analytics services and serve advertisements on our behalf across the Internet and in applications. These entities may use cookies, web beacons, device identifiers, and other technologies to collect information about your use of the Services and other websites and applications, including your IP address, web browser, mobile network information, pages viewed, time spent on pages or in apps, links clicked, and conversion information. This information may be used by Kodiak and others to, among other things, analyze and track data, determine the popularity of certain content, deliver advertising and content targeted to your interests on the Services and other websites, and better understand your online activity. For more information about interest-based ads, or to opt out of having your web browsing information used for behavioral advertising purposes, please visit [www.aboutads.info/choices](http://www.aboutads.info/choices) (or <http://www.youronlinechoices.eu/if> you are a resident of the European Economia Area).

5\.                   Retention of Data

We store the information we collect about you for as long as is necessary for the purposes for which we originally collected it, or for other legitimate business purposes, including to meet our legal or other regulatory obligations, prevent fraud, resolve disputes, troubleshoot problems, assist with any investigation, enforce our Terms of Service, and other actions permitted by law. There is no single retention period applicable to the various types of personal information collected. Please contact us if you would like to delete any personal information we hold about you. We also reserve the right to continue to hold personal information about you to the extent it is required to be held by us by law, rule, or regulation.

6\.                   Security Measures

We use commercially reasonable physical, managerial, and technical safeguards to preserve the integrity of, and to help protect information about you from, loss, theft, misuse and unauthorized access, disclosure, alteration and destruction. However, we cannot guarantee that unauthorized third parties will never be able to defeat our security measures or use your personal information for improper purposes. You acknowledge that you provide your personal information at your own risk.

7\.                   Disclaimer About Sharing Personal Information Online

You acknowledge that when sharing personal information online, there is always a risk of data breaches, including data breaches in which third parties unlawfully access our systems or the systems of our third-party providers, which store personal information.

8\.                   Limitation on Liability

While we take measures to protect personal information, you agree that in no event will Kodiak, its affiliates, and each of their respective shareholders, members, directors, officers, managers, employees, lawyers, agents, accountants, advisors, representatives, suppliers, and contractors (collectively, the “Company Parties”) be liable to you or any other person in any way in contract, tort (including negligence), civil liability or otherwise for any claims, damages, obligations, losses, liabilities, costs, debts or expenses (including but not limited to lawyer’s fees and disbursements), whether direct, indirect, special, economic, incidental, consequential, punitive or exemplary, including without limitation loss of revenue, data, anticipated profits or lost business, howsoever caused, including by way of negligence, arising from, related to or connect with the loss or theft of your personal information. You agree that if, notwithstanding the other provisions of this Privacy Policy, a Company Party is found to be liable for any claims, proceedings, liabilities, obligations, damages, losses or costs, such Company Party’s liability shall in no event exceed the amount you paid to us hereunder during the one-month period prior to the date on which such claim arose, if any.

9\.                   Transfer of Information to Other Countries

We are based in Panama. However, we may transfer personal information to outside agents or service providers (including our affiliates acting in this capacity) that perform services on our behalf, such as customer service and support, marketing and analytics, data hosting or processing services, or similar services.  Some of these service providers may be located outside of Panama, including the United States, and as a result your personal information may be processed in the United States or elsewhere outside of Panama, where local laws may permit foreign government and national security authorities to access personal information in certain circumstances.

10\.               Residents of The European Economic Area

If you are a resident of the European Economic Area (“EEA”), you have certain rights and protections under the law regarding the processing of your personal data. Any reference to “personal information” in this Privacy Policy should be understood as referring to “personal data”,  defined under the General Data Protection Regulation (“GDPR”) as “any information relating to an identified or identifiable natural person (‘data subject’); an identifiable natural person is one who can be identified, directly or indirectly, in particular by reference to an identifier such as a name, an identification number, location data, an online identifier or to one or more factors specific to the physical, physiological, genetic, mental, economic, cultural or social identity of that natural person”.

*(a)                Legal Basis for Processing*

If you are a resident of the EEA, when we process your personal data we will only do so where we need to use your personal data to perform our responsibilities under our agreement with you (e.g., providing the Services you have requested). We have a legitimate interest in processing your personal data. For example, we may process your personal data to send you marketing communications, to communicate with you about changes to the Services, and to provide, secure, and improve the Services. You have consented to the processing of your personal data for one or more specific purposes. We consider that our legitimate interests are in compliance with the GDPR and your legal rights and freedoms. You have the right to object to any of this processing and, if you wish, please contact us at the contact details indicated below.

*(b)                Data Subject Requests*

If you are a resident of the EEA, you have the right to access personal data we hold about you and to ask that your personal data be corrected, erased, or transferred. You may also have the right to object to, or request that we restrict, certain processing. If you would like to exercise any of these rights, you can contact us as indicated below. Please note that the limitation or deletion of your personal data may mean we will be unable to provide our Services to you. You also have the right to receive your personal data in a machine-readable format and have the data transferred to another party responsible for data processing.

*(c)                 Questions or Complaints*

If you are a resident of the EEA and have a concern about our processing of personal data that we are not able to resolve, you have the right to lodge a complaint with the data privacy authority where you reside. For contact details of your local Data Protection Authority, please see: <http://ec.europa.eu/justice/data-protection/article-29/structure/data-protection-authorities/index_en.htm>.

11\.               Your Choices

*(a)                Account Information*

You may update, correct, or delete information about you at any time by emailing us at <admin@kodiak.finance>. Please note that we may retain cached or archived copies of information about you for a certain period of time.

*(b)                Cookies*

Most web browsers are set to accept cookies by default. If you prefer, you can usually choose to set your browser to remove or reject browser cookies. Please note that if you choose to remove or reject cookies, this could affect the availability and functionality of the Services.

*(c)                 Promotional Communications*

You may opt out of receiving promotional communications from us by following the instructions in those communications or by emailing us at <admin@kodiak.finance>. If you opt out, we may still send you non-promotional emails, such as those about your account or our ongoing business relations.

*(d)                Mobile Push Notifications/Alerts*

With your consent, we may send promotional and non-promotional push notifications or alerts to your mobile device. You can deactivate these messages at any time by changing the notification settings on your mobile device.

12\.               Contact

If you have any questions about this Privacy Policy, please contact us at: <admin@kodiak.finance>.


# TradingView Advanced License

Kodiak leverages [TradingView](https://tradingview.com/) technology for its market quotes, presenting them through sophisticated charts. This integration offers a broad spectrum of analytical tools for monitor cryptocurrency prices such as the [price of BTCUSD](https://www.tradingview.com/symbols/BTCUSD/) and accessing the latest market insights.


# Migration Terms

Last Updated: December 23, 2025

**TOKEN MIGRATION TERMS AND CONDITIONS**

These Token Migration Terms and Conditions (the “**Terms**”) sets out the terms and conditions by which you may swap Kodiak Finance protocol (the “**Protocol**”) pre-token generation event reward tokens called xKDK (“**Old xKDK**”) for a new digital token called xKDK (“**New xKDK**”), which is the escrowed version of the Protocol’s native token called KDK (“**KDK**”). By checking the box and signing the message with your wallet, you agree to these Terms at <https://app.kodiak.finance/#/claim?chain=berachain_mainnet> (the “**Site**”), accessing or using the user interface available at the Site made available by KDK Protocol Labs S.A. (“**we**”, “**us**” or “**our**”) or interacting with the smart contract deployed by us for the purposes of facilitating the migration of Old xKDK for New xKDK (the “**Smart Contract**”), you signify on your behalf and any person or entity that you represent that you have read, understood, and agree to be bound by these Terms. We reserve the right to make unilateral modifications to these Terms and will provide notice of these changes as described below. These Terms applies to all visitors, users, and others who access the Site or the Smart Contract (“**you**” and “**your**”).

If you have any questions regarding these Terms, please contact us by email at <admin@kodiak.finance>.&#x20;

1. **Eligibility.**&#x20;

   You represent, warrant, acknowledge and agree that:

   1. Only users holding Old xKDK are eligible to claim an amount of New xKDK equal to the number of Old xKDK transferred to the Smart Contract on a 1:1 conversion ratio (the "**Migration Amount**"), subject to these Terms. We have determined those users who are eligible to receive a Migration Amount ("**Eligible Users**") as well as the amount of such Migration Amount. You agree that our determination of who is an Eligible User to receive a Migration Amount is conclusive;
   2. the New xKDK representing the Migration Amount will be distributed to Eligible Users by accessing or using the user interface available at the Site or interacting with the Smart Contract, subject to the Terms;
   3. the Migration Amounts are offered only to Eligible Users that are not a Restricted Person or Sanctioned Person or acting on behalf or under the authority, instruction or employment of a Restricted Person or Sanctioned Person. For purposes of the Terms: (i) a “**Restricted Person**” is a person or entity resident in, a citizen of, located in, incorporated, formed or organized in or have a registered office in Iran, Cuba, North Korea, Syria, Myanmar (Burma), the regions of Crimea, Donetsk or Luhansk or any other country, region, territory or jurisdiction which has been sanctioned or embargoed by the United States, the United Kingdom or the European Union, the United Nations, North Atlantic Treaty Organisation,&#x20;

      Organisation for Economic Cooperation and Development, Financial Action Task Force, or any other applicable governmental authority; and (ii) a “**Sanctioned Person**” is a person or entity subject to sanctions administered or enforced by any applicable governmental authority or otherwise designated on any list of prohibited or restricted parties by any applicable Governmental Authority, including without limitation the Office of Foreign Assets Control of the United States Department of the Treasury (“**OFAC**”). If you are a Restricted Person or Sanctioned Person or acting on behalf or under the authority, instruction or employment of a Restricted Person or Sanctioned Person, you are not an Eligible User and may not participate in the matters described in these Terms.
   4. you have the right, authority and capacity to enter into these Terms on behalf of yourself and the person or entity that you represent (if applicable);
   5. you are not prohibited from entering or using this Site or transacting with the Smart Contract under any and all applicable (i) laws, constitutions, treaties, statutes, codes, ordinances, principles of common and civil law and equity, orders, decrees, rules, regulations and municipal by-laws, whether domestic, foreign or international; (ii) judicial, arbitral, administrative, ministerial, departmental and regulatory judgments, orders, writs, injunctions, decisions, rulings, decrees and awards of any: (A) multinational or supranational body or organization, nation, government, state, province, country, territory, municipality, quasi-government, administrative, judicial or regulatory authority, agency, board, body, bureau, commission, instrumentality, court or tribunal or any political subdivision thereof, or any central bank (or similar monetary or regulatory authority) thereof, any taxing authority, any ministry or department or agency of any of the foregoing; (B) self-regulatory organization or stock exchange; (C) entity exercising executive, legislative, judicial, regulatory or administrative functions of or pertaining to government; and (D) corporation or other entity owned or controlled, through stock or capital ownership or otherwise, by any of such entities or other bodies pursuant to the foregoing (collectively, “**Governmental Authority**”); and(iii) policies, practices and guidelines of, or contracts with, any Governmental Authority, which, although not actually having the force of law, are considered by such Governmental Authority as requiring compliance as if having the force of law, as the same may be amended from time to time and any successor thereto and in each case binding on or affecting the person or entity, or the assets of the person or entity, referred to in the context in which such word is used (collectively, “**Applicable Laws**”);
   6. you understand the risks associated with using our Site and the Smart Contract;
   7. these Terms shall not be construed as an invitation to the public to subscribe for any securities, and you understand and acknowledge that no actions of, or documentation issued by, the Company shall be construed as such; and
   8. we are not registered with or licensed by any financial regulatory or securities authority in Panama or elsewhere. Accordingly, no Panama or other financial regulatory or securities authority has passed upon the contents of these Terms or the merits of receiving the Migration Amount, nor have these Terms been filed with, or reviewed by, any Panama or other financial regulatory or securities authority.

2. **User Responsibilities**

   1. You are responsible for implementing reasonable measures for securing the wallet, vault, or other storage mechanism (“**Wallet**”) you use to transfer Old xKDK to the Smart Contract and to receive and hold the Migration Amount, including any requisite private keys or other credentials necessary to access such Wallet. You acknowledge that we are not responsible for transferring, safeguarding, or maintaining your private keys or any assets associated with your Wallet, including without limitation the Migration Amount. If you lose, mishandle or have stolen your Wallet private keys, you acknowledge that you may not be able to recover associated assets (including without limitation the Migration Amount) and that we are not responsible for such loss. You will implement reasonable and appropriate measures designed to secure access to (i) any device connected with the email address associated with your Wallet, (ii) private keys required to access your Wallet and/or the Migration Amount, and (iii) your username, password, and any other login or identifying credentials.
   2. The Smart Contract is accessible directly through compatible third-party wallet software and services (“**Third Party Services**”). Interacting with the Smart Contract does not require use of the Site or the user interface on such Site; the Site merely provides a convenient and user-friendly method of reading and displaying data from the Smart Contract and generating standard transaction messages compatible with the Smart Contract. The Site does not interact with the Smart Contract and does not conduct any transaction on your behalf. Because the Site does not provide compatible wallet software, such Third Party Services constitute an essential third party or user dependency without which the transactions to receive the Migration Amount cannot be exercised. There is no guarantee of the continued operation, maintenance, availability, or security of any of such Third Party Services. You expressly relieve the Company Parties (as defined below) from any and all liability arising from your use of such Third Party Services and agree the Company Parties shall not be responsible for any loss or damage of any sort arising from or related to such Third Party Services.
   3. You will provide to us, or to our nominee, immediately upon our request, information that we, in our sole discretion, deem to be required to maintain compliance with any Applicable Laws and we, or our nominee, may keep a copy of such information for our records. Such information will be used by us, or our nominee, to confirm compliance with such federal, state, local, domestic or foreign laws, regulations, and policies before any delivery of the Migration Amount to you.

3. **Delivery of Migration Amount**

   1. You agree to transfer all of your Old xKDK to the Smart Contract in exchange for delivery of the Migration Amount to your Wallet. You agree that you will be responsible for all transaction fees or gas fees payable in connection with interacting with the Smart Contract, transfer of your Old xKDK and/or receipt of the Migration Amount. You understand and agree that delivery of the Migration Amount will be made only to the Wallet used to transfer your Old xKDK to the Smart Contract. We reserve the right, in our sole discretion, to prescribe additional conditions relating to specific Wallet requirements for the delivery of the Migration Amount.
   2. Without limiting the grounds upon which we may refuse to deliver the Migration Amount, if the delivery of the Migration Amount becomes impossible or a violation of any Applicable Laws, or if we suspect such, then, in addition to any other remedies available to us we will not be required to deliver any Migration Amount to you or any other person or entity acting on your behalf we reserve the right to take any actions considered necessary or desirable for us to meet our legal and regulatory obligations.
   3. By providing access to the Smart Contract for transfer of your Old xKDK and distribution of the Migration Amount, we are solely providing a technical service to you. We are not distributing or selling any digital assets to you or a party to any arrangement for sale or investment in respect of any digital assets, nor are we acting as an exchange, broker, trustee, custodian, bailee, manager or administrator in respect of any digital assets. No form of partnership, joint venture, agency or any similar relationship between you and us and/or other individuals or entities involved with the deployment or operation of the Smart Contract is created hereunder.
   4. The Smart Contract and all related facts and circumstances relating to the distribution of the Migration Amount have not been reviewed, approved, endorsed or registered with any Governmental Authority. We and the developers or creators of the Smart Contract are not licensed by any regulator or other authority to provide any legal, financial, accounting, investment or other advice or services. You are advised to seek your own advice in this regard before interacting with the Smart Contract.

4. **Taxes**

   You are responsible for determining what, if any, taxes apply to your receipt of the Migration Amount, including, for example, sales, use, value added, and similar taxes. It is also your responsibility to withhold, collect, report, and remit the correct taxes to the appropriate tax authorities. We are not responsible for withholding, collecting, reporting, or remitting any sales, use, value added, or other tax arising from your receipt of the Migration Amount. You agree not to hold us or any of the Company Parties liable for any tax liability associated with or arising from the ownership, use, or liquidation of the Migration Amount, or any other action or transaction related to the Migration Amount.<br>

5. **Representations and Warranties**

   You represent, warrant, and covenant that:

   1. you are an Eligible Person and not a Restricted Person;
   2. you have sufficient understanding of cryptographic tokens, token storage mechanisms (such as digital wallets), and blockchain technology to understand these Terms and to appreciate the risks and implications of interacting with the Site and Smart Contract and receiving the Migration Amount;
   3. you have read and understand these Terms and are agreeing to these Terms voluntarily and based on your own independent judgment and on advice from independent advisors as you have considered to be necessary or appropriate, after due inquiry;
   4. your receipt of the Migration Amount complies with Applicable Laws, including but not limited to (i) legal capacity and any other threshold or eligibility requirements in your jurisdiction for receipt of the Migration Amount and entering into legally binding contracts with us, (ii) any foreign exchange or regulatory restrictions applicable to the Migration Amount, and (iii) any governmental or other consents that may need to be obtained;
   5. you are legally permitted to receive, hold and use the Migration Amount;
   6. you will comply with applicable tax obligations, if any, in your jurisdiction arising from your receipt of the Migration Amount;
   7. you are not receiving the Migration Amount from countries or regions comprehensively sanctioned by any applicable sanctions laws such as OFAC (including countries such as Iran, North Korea, Sudan, and Syria), or on behalf of the governments of these countries or regions, nor will you conduct or facilitate any transactions with persons or entities located in these countries or regions; and
   8. you waive the right to participate in a class action lawsuit or a class wide arbitration against any entity or individual involved with the delivery of the Migration Amount.

6. **Indemnification**

   1. To the fullest extent permitted by Applicable Laws, you will indemnify, defend, and hold harmless us and our past, present and future predecessors in interest, successors in interest, successors, predecessors, acquirors, parent companies, subsidiaries and affiliates, and each of our and their respective past, present, and future employees, officers, directors, managers, contractors, consultants, equity holders, suppliers, vendors, service providers, agents, representatives, predecessors, successors, acquirors, heirs, executors, administrators, fiduciaries, trustees, conservators and assigns (collectively, the "**Company Parties**"), on demand from and against all claims, demands, actions, damages, losses, costs, and expenses (including legal fees, court costs, investigative costs, amounts paid in settlement, and other costs and expenses) that arise from or relate to: (i) your transfer of your Old xKDK, (ii) your receipt of the Migration Amount, (iii) your violation of these Terms, or (iv) your violation of any rights of any other person or entity.
   2. The rights of the Company Parties under Section 6(a) are in addition to, and not in lieu of, (i) any other indemnities set forth in any other written agreement between you and us, and (ii) any other remedies that may be available to us under Applicable Laws or in equity.
   3. We reserve the right to exercise sole control over the defence, at your cost and expense, of any claim subject to indemnification under this Section 6.

7. **No Warranty**
   1. TO THE FULLEST EXTENT PERMITTED BY APPLICABLE LAWS, THE SITE AND SMART CONTRACT IS PROVIDED ON AN "AS IS" AND "AS AVAILABLE" BASIS WITHOUT WARRANTIES OF ANY KIND, WHETHER EXPRESS OR IMPLIED, AND WE EXPRESSLY DISCLAIM ALL SUCH WARRANTIES INCLUDING WITHOUT LIMITATION IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT. NO ADVICE OR INFORMATION, WHETHER ORAL OR WRITTEN, OBTAINED BY YOU FROM A COMPANY PARTY OR THROUGH THE SITE OR THE SMART CONTRACT WILL CREATE ANY WARRANTY NOT EXPRESSLY STATED HEREIN. WITHOUT LIMITING THE FOREGOING, THE COMPANY PARTIES DO NOT WARRANT THAT THE SITE OR THE SMART CONTRACT WILL MEET YOUR REQUIREMENTS; THAT THE SITE AND THE SMART CONTRACT WILL BE AVAILABLE AT ANY PARTICULAR TIME OR LOCATION, UNINTERRUPTED OR SECURE; THAT ANY DEFECTS OR ERRORS WILL BE CORRECTED; OR THAT THE SITE AND THE SMART CONTRACT ARE FREE OF VIRUSES OR OTHER HARMFUL COMPONENTS.\
      ANY CONTENT DOWNLOADED OR OTHERWISE OBTAINED THROUGH THE USE OF THE SITE OR THE SMART CONTRACT IS DOWNLOADED AT YOUR OWN RISK AND YOU WILL BE SOLELY RESPONSIBLE FOR ANY DAMAGE TO YOUR COMPUTER SYSTEM OR MOBILE DEVICE OR LOSS OF DATA THAT RESULTS FROM SUCH DOWNLOAD OR YOUR USE OF THE SITE OR THE SMART CONTRACT.
   2. YOU UNDERSTAND THAT BLOCKCHAIN TECHNOLOGY, THE SMART CONTRACT, AND OTHER CRYPTOCURRENCY ARE NEW AND UNTESTED TECHNOLOGIES OUTSIDE OF OUR CONTROL AND, THEREFORE, ADVERSE CHANGES IN MARKET FORCES, LAW, OR TECHNOLOGY WILL EXCUSE OUR PERFORMANCE UNDER THESE TERMS.
   3. TRANSACTIONS USING BLOCKCHAIN TECHNOLOGY, SUCH AS THOSE INVOLVING THE SMART CONTRACT, ARE AT RISK TO MULTIPLE POTENTIAL FAILURES, INCLUDING HIGH VOLUME ON THE PROTOCOL, COMPUTER FAILURE, PROTOCOL FAILURE OF ANY KIND, USER FAILURE, TOKEN THEFT, HACKING OF THE SMART CONTRACT, AND TELECOMMUNICATIONS OR INTERNET FAILURE OR DISRUPTION. WE ARE NOT RESPONSIBLE FOR ANY LOSS OF DATA, TOKENS (INCLUDING WITHOUT LIMITATION OLD XKDK), MIGRATION AMOUNT OR OTHER CRYPTOCURRENCY, HARDWARE, OR SOFTWARE RESULTING FROM ANY TYPES OF FAILURES, THEFT OR HACK.<br>

8. **Limitation of Liability**
   1. You agree that to the maximum extent permitted by Applicable Laws, in no event shall any Company Party be liable for any direct, indirect, punitive, incidental, special, consequential or exemplary damages, including without limitation damages for loss of profits, goodwill, use, data or other intangible losses, arising out of or relating to these Terms, the Site, the Smart Contract or the Migration Amount or the use of, or inability to use, the Site or the Smart Contract. Under no circumstances will any Company Party be responsible for any damage, loss or injury resulting from hacking, tampering or other unauthorized access or use of the Site, the Smart Contract and other information contained therein. To the maximum extent permitted by Applicable Laws, the Company Parties assume no liability or responsibility for any (i) errors, mistakes, or inaccuracies of content; (ii) personal injury or property damage, of any nature whatsoever, resulting from your access to, interaction with or use of our Site or the Smart Contract; (iii) any unauthorized access to or use of our secure servers and/or any and all personal information stored therein; (iv) any interruption or cessation of transmission to or from the Site or the Smart Contract; (v) any bugs, viruses, trojan horses, or the like that may be transmitted to or through our Site or the Smart Contract by any third party; (vi) any errors or omissions in any content or for any loss or damage incurred as a result of the use of any content posted, emailed, transmitted, or otherwise made available through the Site or the Smart Contract; and/or (vii) the defamatory, offensive, or illegal conduct of any third party. You agree that if, notwithstanding the other provisions of these Terms, a Company Party is found to be liable for any claims, proceedings, liabilities, obligations, damages, losses or costs, such Company Party’s liability shall in no event exceed US$100.
   2. This limitation of liability section applies whether the alleged liability is based on contract, tort, negligence, strict liability, or any other basis, even if we have been advised of the possibility of such damage. The foregoing limitation of liability shall apply to the fullest extent permitted by Applicable Laws.<br>

9. **Limitations as Allowed by Law**

   Some states, provinces and other jurisdictions do not allow the exclusion and limitations of certain implied warranties, or the exclusion or limitation of incidental or consequential damages, so the above limitations or exclusions may not apply to you. The Terms gives you specific legal rights, and you may also have other rights which vary from jurisdiction to jurisdiction. The disclaimers, exclusions, and limitations of liability under the Terms will not apply to the extent prohibited by Applicable Laws.

10. **Release**

    To the fullest extent permitted by Applicable Laws, you release the Company Parties from any and all past, present, or future claims, actions, causes of action, class actions, costs, demands, obligations, expenses, injuries, judgments, losses, suits, damages, fees, interest, expenses, compensation, class actions, or causes of action for declaratory or injunctive relief, restitution, compensatory, general, special, statutory, or punitive damages of any kind or nature whatsoever, whether known or unknown, foreseen or unforeseen, liquidated or unliquidated, anticipated or unanticipated, suspected or unsuspected, past, present, or future, direct or indirect, contingent or absolute, whether individual, collective, or representative, and whether based on tort, contract, or other theories of recovery, including, without limitation, legal fees and other costs of defense arising out of, or in any way related to (i) any act or omission of the Company Parties in connection with the development, operation or management of the Site, Smart Contract or Migration Amount process, (ii) your access to, interaction with or use of the Site or the Smart Contract, (iii) your transfer of your Old xKDK to the Smart Contract, and/or (iv) your receipt of the Migration Amount (each a "**Claim**" and collectively "**Claims**"), notwithstanding that any such Claim may have been contributed to or occasions by the negligence of any of the Company Parties.<br>

11. **Governing Law and Jurisdiction**

    These Terms are entered into in Panama and shall be governed by, and construed in accordance with, the laws of Panama. You agree that we may initiate a proceeding related to the enforcement or validity of our intellectual property rights in any court having jurisdiction. For any other proceeding that is not subject to arbitration under these Terms, the courts located in Panama will have exclusive jurisdiction. You waive any objection to venue in any such courts.<br>

12. **Dispute Resolution and Arbitration**

    PLEASE READ THE FOLLOWING SECTION CAREFULLY BECAUSE IT REQUIRES YOU TO ARBITRATE CERTAIN DISPUTES AND CLAIMS WITH US AND LIMITS HOW YOU CAN SEEK RELIEF FROM US. ALSO, ARBITRATION PRECLUDES YOU FROM SUING IN COURT OR HAVING A JURY TRIAL.

    1. You and we agree that subject to Section 11 above, any Claim is personal to you and us and that any dispute will be resolved solely through individual action, and will not be brought as a class arbitration, class action, or any other type of representative proceeding.
    2. Except for disputes in which you or we seek injunctive or other equitable relief for the alleged unlawful use of intellectual property, you and we waive all rights to a jury trial and to have any Claim resolved in court. Instead, for any Claim you agree to first contact us and attempt to resolve the Claim informally by sending a written notice of your Claim (“**Notice**”) to us by email at <admin@kodiak.finance>. The Notice must: (i) include your name, residence address, email address, and telephone number; (ii) describe the nature and basis of the Claim; and (iii) set forth the specific relief sought. Our notice to you will be similar in form to that described above. If you and we cannot reach an agreement to resolve the Claim within thirty (30) days after such Notice is received, then either party may submit the dispute to binding arbitration administered by the Centro de Conciliación y Arbitraje de PanamáCentre (“**CeCAP**”) before one arbitrator (the "**Arbitrator**"). The place of arbitration shall be Panama unless you and we agree otherwise and shall be conducted under CeCAP's Arbitration Regulation (the "**CeCAP Rules**"). The language to be used in the arbitral proceedings shall be English. The most recent version of the CeCAP Rules is available on the CeCAP website and are hereby incorporated by reference. You either acknowledge and agree that you have read and understand the CeCAP Rules or waive your opportunity to read the CeCAP Rules and waive any claim that the CeCAP Rules are unfair or should not apply for any reason.
    3. The Arbitrator will have exclusive authority to make all procedural and substantive decisions regarding any dispute and to grant any remedy that would otherwise be available in court, including the power to determine the question of arbitrability. The Arbitrator may conduct only an individual arbitration and may not consolidate more than one individual’s Claims, preside over any type of class or representative proceeding or preside over any proceeding involving more than one individual.
    4. The Arbitrator, we and you will maintain the confidentiality of any arbitration proceedings, judgments and awards, including, but not limited to, all information gathered, prepared, and presented for purposes of the arbitration or related to the dispute(s) therein. The Arbitrator will have the authority to make appropriate rulings to safeguard confidentiality unless the law provides to the contrary. The duty of confidentiality does not apply to the extent that disclosure is necessary to prepare for or conduct the arbitration hearing on the merits, in connection with a court application for a preliminary remedy or in connection with a judicial challenge to an arbitration award or its enforcement, or to the extent that disclosure is otherwise required by law or judicial decision.
    5. You and we agree that for any arbitration you or we initiate, you will pay the filing fee and all other CeCAP fees and costs. You and we agree that the courts of Panama have exclusive jurisdiction over the enforcement of an arbitration award.
    6. You further agree as follows: (i) any Claim brought by you must be filed within one year after your receipt of the Migration Amount; otherwise, the Claim is permanently barred, which means that you will not have the right to assert the Claim; (ii) no recovery by you may be sought or received for damages other than out-of-pocket expenses, except that the prevailing party will be entitled to costs and legal fees; and (iii) any Claim must be brought by you individually and not consolidated as part of a group or class action complaint.
    7. If any portion of this Section 12 is found to be unenforceable or unlawful for any reason: (i) the unenforceable or unlawful provision shall be severed from the Terms; (ii) severance of the unenforceable or unlawful provision shall have no impact whatsoever on the remainder of this Section 12 or the parties’ ability to compel arbitration of any remaining Claims on an individual basis under this Section 12; and (iii) to the extent that any Claims must proceed on a class, collective, consolidated, or representative basis, such claims must be litigated in a civil court of competent jurisdiction and not in arbitration, and the parties agree that litigation of those claims shall be stayed pending the outcome of any individual claims in arbitration. Further, if any part of this Section 12 is found to prohibit an individual claim seeking injunctive relief, then that provision will have no effect to the extent such relief is allowed to be sought out of arbitration, and the remainder of this Section 12 will be enforceable.<br>

13. **Severability**

    If a court of competent jurisdiction holds any provision of these Terms to be invalid or unenforceable, the remaining provisions of these Terms will remain in full force and effect. You and we intend that any invalid or unenforceable provisions will be interpreted to give effect the intent of the original provisions. If such construction is not possible, the invalid or unenforceable provision will be severed from these Terms, but the rest of these Terms will remain in full force and effect.<br>

14. **Modification to these Terms**

    We reserve the right, in our sole discretion, to modify the Terms from time to time. If we make changes, we will provide you with notice of such changes, such as by providing notice through the Site or updating the “Last Updated” date at the top of the Terms. You waive any right to receive specific notice of each such change. It is your responsibility to periodically review these Terms to stay informed of any changes. You will be subject to and will be deemed to have been made aware of and to have accepted the changes in any revised Terms by your receipt of the Migration Amount, whether such changes occurred before or after your receipt of the Migration Amount.<br>

15. **Force Majeure**\
    The Company Parties will have no responsibility or liability for any failure or delay in performance any obligation under these Terms or any loss or damage that you may incur, due to any circumstance or event beyond our control, including any (a) flood, extraordinary weather conditions, earthquake, or other act of God, (b) fire, (c) war, (d) insurrection, (e) riot, (f) labour dispute, (g) accident, (h) epidemic or pandemic, (i) action of government, (j) new laws or regulations or change in existing laws or regulations or the interpretation or enforcement of any of the foregoing, (k) communications, (l) power failure, (m) equipment or software unavailability, disruption or malfunction, (n) hacking or other attack on the Site or the Smart Contract, (o) the unavailability, disruption or malfunction of any network or blockchains or (p) the unavailability, disruption or malfunction of the Internet.<br>

16. **Collection of Information**

    You acknowledge and agree that we will collect and store your Wallet address, IP address, and information regarding activity on the Site. The purpose of this data collection is to enable us to track your agreement to these Terms and to enforce the Terms if necessary. We do not intend to sell, share, transfer, or commercialize this information or use it in any automated decision-making process. You hereby authorize us to collect and store the your Wallet, IP address, and activity on the Site for the purposes above, which include enforcing the Term.<br>

17. **Miscellaneous**
    1. You agree that we and you are independent contractors, and neither Party, nor any of their respective affiliates, is an agent of the other for any purpose or has the authority to bind the other.
    2. You acknowledge and agree that the Company Parties other than the Parties are third party beneficiaries of these Terms and that your the obligations under these Terms are expressly intended to benefit all of the Company Parties despite not being signatories to these Terms.
    3. In connection with these Terms, you will comply with all applicable import, re-import, export, and re-export control and laws, regulations, guidance and programs, including the Export Administration Regulations, the International Traffic in Arms Regulations, and country or individual-specific economic sanctions programs implemented by OFAC or any equivalent applicable regimes. You are solely responsible for legal compliance related to your acquisition, use, exchange, and transfer of the Migration Amount.
    4. All communications and notices to be made or given pursuant to these Terms must be in the English language.
    5. You will not assign these Terms, or delegate or sublicense any of your rights under these Terms, without our prior written consent. Any assignment or transfer in violation of this Section 16(e) will be void. We may assign these Terms or any of its provisions without your consent. Subject to the foregoing, these Terms will be binding upon, and enure to the benefit of, the parties and their respective successors and permitted assigns.
    6. The failure by us to enforce any provision of these Terms will not constitute a present or future waiver of such provision, and will not limit our right to enforce such provision at a later time. All waivers by us must be in writing to be effective.
    7. These Terms (including the web links and other agreements and instruments referred to in these Terms) constitute the entire agreement among the parties and supersede all prior agreements and understandings, both written and oral, among the parties with respect to the subject matter hereof and thereof.
    8. You confirm to have carefully reviewed these Terms and fully understand all the risks set out herein.
    9. You agree that upon termination or expiry of these Terms or completion of the transactions contemplated herein, you shall continue to be bound by these Terms and such obligations survive such termination or expiry.
    10. Unless advised in writing of a different name and address, all notices, submissions and communications of any kind required or otherwise made under the Terms shall be sent (as required), and you and we each agree to accept service of any process for claims arising out of or related to the Terms via the following methods:
        1. If to you, via a message sent to your Wallet; and
        2. If to the Company Parties, to the following email address: <admin@kodiak.finance>.


# Claim Terms

Last Updated: June 9, 2026

**TOKEN CLAIM TERMS AND CONDITIONS**

These Token Claim Terms and Conditions (the “**Terms**”) set out the terms and conditions by which you may claim Kodiak Finance protocol (the “**Protocol**”) rewards, consisting of the Protocol’s native token called KDK (“**KDK**”), or an escrowed version of KDK ("**xKDK**"), collectively referred to as "**Tokens**." By checking the box and signing the message with your wallet, you agree to these Terms at <https://app.kodiak.finance/#/claim?chain=berachain_mainnet> (the “**Site**”), accessing or using the user interface available at the Site made available by KDK Protocol Labs S.A. (“**we**”, “**us**” or “**our**”) or interacting with the smart contract deployed by us for the purposes of facilitating the Token Claim (the “**Smart Contract**”), you signify on your behalf and any person or entity that you represent that you have read, understood, and agree to be bound by these Terms. We reserve the right to make unilateral modifications to these Terms and will provide notice of these changes as described below. These Terms applies to all visitors, users, and others who access the Site or the Smart Contract (“**you**” and “**your**”).

If you have any questions regarding these Terms, please contact us by email at <admin@kodiak.finance>.&#x20;

1. **Eligibility.**&#x20;

   You represent, warrant, acknowledge and agree that:

   1. Only users designated as having earned rewards are eligible to claim their allocated Tokens (the "**Claim Amount**"), subject to these Terms. We have determined those users who are eligible to receive a Claim Amount ("**Eligible Users**") as well as the amount of such Claim Amount. You agree that our determination of who is an Eligible User to receive a Claim Amount is conclusive;
   2. the Tokens representing the Claim Amount will be distributed to Eligible Users by accessing or using the user interface available at the Site or interacting with the Smart Contract, subject to the Terms;
   3. the Claim Amounts are offered only to Eligible Users that are not a Restricted Person or Sanctioned Person or acting on behalf or under the authority, instruction or employment of a Restricted Person or Sanctioned Person. For purposes of the Terms: (i) a “**Restricted Person**” is a person or entity resident in, a citizen of, located in, incorporated, formed or organized in or have a registered office in Iran, Cuba, North Korea, Syria, Myanmar (Burma), the regions of Crimea, Donetsk or Luhansk or any other country, region, territory or jurisdiction which has been sanctioned or embargoed by the United States, the United Kingdom or the European Union, the United Nations, North Atlantic Treaty Organisation,&#x20;

      Organisation for Economic Cooperation and Development, Financial Action Task Force, or any other applicable governmental authority; and (ii) a “**Sanctioned Person**” is a person or entity subject to sanctions administered or enforced by any applicable governmental authority or otherwise designated on any list of prohibited or restricted parties by any applicable Governmental Authority, including without limitation the Office of Foreign Assets Control of the United States Department of the Treasury (“**OFAC**”). If you are a Restricted Person or Sanctioned Person or acting on behalf or under the authority, instruction or employment of a Restricted Person or Sanctioned Person, you are not an Eligible User and may not participate in the matters described in these Terms.
   4. you have the right, authority and capacity to enter into these Terms on behalf of yourself and the person or entity that you represent (if applicable);
   5. you are not prohibited from entering or using this Site or transacting with the Smart Contract under any and all applicable (i) laws, constitutions, treaties, statutes, codes, ordinances, principles of common and civil law and equity, orders, decrees, rules, regulations and municipal by-laws, whether domestic, foreign or international; (ii) judicial, arbitral, administrative, ministerial, departmental and regulatory judgments, orders, writs, injunctions, decisions, rulings, decrees and awards of any: (A) multinational or supranational body or organization, nation, government, state, province, country, territory, municipality, quasi-government, administrative, judicial or regulatory authority, agency, board, body, bureau, commission, instrumentality, court or tribunal or any political subdivision thereof, or any central bank (or similar monetary or regulatory authority) thereof, any taxing authority, any ministry or department or agency of any of the foregoing; (B) self-regulatory organization or stock exchange; (C) entity exercising executive, legislative, judicial, regulatory or administrative functions of or pertaining to government; and (D) corporation or other entity owned or controlled, through stock or capital ownership or otherwise, by any of such entities or other bodies pursuant to the foregoing (collectively, “**Governmental Authority**”); and(iii) policies, practices and guidelines of, or contracts with, any Governmental Authority, which, although not actually having the force of law, are considered by such Governmental Authority as requiring compliance as if having the force of law, as the same may be amended from time to time and any successor thereto and in each case binding on or affecting the person or entity, or the assets of the person or entity, referred to in the context in which such word is used (collectively, “**Applicable Laws**”);
   6. you understand the risks associated with using our Site and the Smart Contract;
   7. these Terms shall not be construed as an invitation to the public to subscribe for any securities, and you understand and acknowledge that no actions of, or documentation issued by, the Company shall be construed as such; and
   8. we are not registered with or licensed by any financial regulatory or securities authority in Panama or elsewhere. Accordingly, no Panama or other financial regulatory or securities authority has passed upon the contents of these Terms or the merits of receiving the Migration Amount, nor have these Terms been filed with, or reviewed by, any Panama or other financial regulatory or securities authority.

2. **User Responsibilities**

   1. You are responsible for implementing reasonable measures for securing the wallet, vault, or other storage mechanism (“**Wallet**”) you use to receive and hold the Claim Amount, including any requisite private keys or other credentials necessary to access such Wallet. You acknowledge that we are not responsible for transferring, safeguarding, or maintaining your private keys or any assets associated with your Wallet, including without limitation the Claim Amount. If you lose, mishandle or have stolen your Wallet private keys, you acknowledge that you may not be able to recover associated assets (including without limitation the Claim Amount) and that we are not responsible for such loss. You will implement reasonable and appropriate measures designed to secure access to (i) any device connected with the email address associated with your Wallet, (ii) private keys required to access your Wallet and/or the Claim Amount, and (iii) your username, password, and any other login or identifying credentials.
   2. The Smart Contract is accessible directly through compatible third-party wallet software and services (“**Third Party Services**”). Interacting with the Smart Contract does not require use of the Site or the user interface on such Site; the Site merely provides a convenient and user-friendly method of reading and displaying data from the Smart Contract and generating standard transaction messages compatible with the Smart Contract. The Site does not interact with the Smart Contract and does not conduct any transaction on your behalf. Because the Site does not provide compatible wallet software, such Third Party Services constitute an essential third party or user dependency without which the transactions to receive the Claim Amount cannot be exercised. There is no guarantee of the continued operation, maintenance, availability, or security of any of such Third Party Services. You expressly relieve the Company Parties (as defined below) from any and all liability arising from your use of such Third Party Services and agree the Company Parties shall not be responsible for any loss or damage of any sort arising from or related to such Third Party Services.
   3. You will provide to us, or to our nominee, immediately upon our request, information that we, in our sole discretion, deem to be required to maintain compliance with any Applicable Laws and we, or our nominee, may keep a copy of such information for our records. Such information will be used by us, or our nominee, to confirm compliance with such federal, state, local, domestic or foreign laws, regulations, and policies before any delivery of the Claim Amount to you.

3. **Delivery of Claim Amount**

   1. You may request delivery of your Claim Amount to your Wallet by interacting with the Smart Contract. You agree that you will be responsible for all transaction fees or gas fees payable in connection with interacting with the Smart Contract and/or receipt of the Claim Amount. You understand and agree that delivery of the Claim Amount will be made only to the Wallet eligible for the allocation. We reserve the right, in our sole discretion, to prescribe additional conditions relating to specific Wallet requirements for the delivery of the Claim Amount.&#x20;
   2. Without limiting the grounds upon which we may refuse to deliver the Claim Amount, if the delivery of the Claim Amount becomes impossible or a violation of any Applicable Laws, or if we suspect such, then, in addition to any other remedies available to us we will not be required to deliver any Claim Amount to you or any other person or entity acting on your behalf we reserve the right to take any actions considered necessary or desirable for us to meet our legal and regulatory obligations.
   3. By providing access to the Smart Contract for distribution of the Claim Amount, we are solely providing a technical service to you. We are not distributing or selling any digital assets to you or a party to any arrangement for sale or investment in respect of any digital assets, nor are we acting as an exchange, broker, trustee, custodian, bailee, manager or administrator in respect of any digital assets. No form of partnership, joint venture, agency or any similar relationship between you and us and/or other individuals or entities involved with the deployment or operation of the Smart Contract is created hereunder.
   4. The Smart Contract and all related facts and circumstances relating to the distribution of the Claim Amount have not been reviewed, approved, endorsed or registered with any Governmental Authority. We and the developers or creators of the Smart Contract are not licensed by any regulator or other authority to provide any legal, financial, accounting, investment or other advice or services. You are advised to seek your own advice in this regard before interacting with the Smart Contract.

4. **Taxes**

   You are responsible for determining what, if any, taxes apply to your receipt of the Claim Amount, including, for example, sales, use, value added, and similar taxes. It is also your responsibility to withhold, collect, report, and remit the correct taxes to the appropriate tax authorities. We are not responsible for withholding, collecting, reporting, or remitting any sales, use, value added, or other tax arising from your receipt of the Claim Amount. You agree not to hold us or any of the Company Parties liable for any tax liability associated with or arising from the ownership, use, or liquidation of the Claim Amount, or any other action or transaction related to the Claim Amount.<br>

5. **Representations and Warranties**

   You represent, warrant, and covenant that:

   1. you are an Eligible Person and not a Restricted Person;
   2. you have sufficient understanding of cryptographic tokens, token storage mechanisms (such as digital wallets), and blockchain technology to understand these Terms and to appreciate the risks and implications of interacting with the Site and Smart Contract and receiving the Claim Amount;
   3. you have read and understand these Terms and are agreeing to these Terms voluntarily and based on your own independent judgment and on advice from independent advisors as you have considered to be necessary or appropriate, after due inquiry;
   4. your receipt of the Claim Amount complies with Applicable Laws, including but not limited to (i) legal capacity and any other threshold or eligibility requirements in your jurisdiction for receipt of the Claim Amount and entering into legally binding contracts with us, (ii) any foreign exchange or regulatory restrictions applicable to the Claim Amount, and (iii) any governmental or other consents that may need to be obtained;
   5. you are legally permitted to receive, hold and use the Claim Amount;
   6. you will comply with applicable tax obligations, if any, in your jurisdiction arising from your receipt of the Claim Amount;
   7. you are not receiving the Claim Amount from countries or regions comprehensively sanctioned by any applicable sanctions laws such as OFAC (including countries such as Iran, North Korea, Sudan, and Syria), or on behalf of the governments of these countries or regions, nor will you conduct or facilitate any transactions with persons or entities located in these countries or regions; and
   8. you waive the right to participate in a class action lawsuit or a class wide arbitration against any entity or individual involved with the delivery of the Claim Amount.

6. **Indemnification**

   1. To the fullest extent permitted by Applicable Laws, you will indemnify, defend, and hold harmless us and our past, present and future predecessors in interest, successors in interest, successors, predecessors, acquirors, parent companies, subsidiaries and affiliates, and each of our and their respective past, present, and future employees, officers, directors, managers, contractors, consultants, equity holders, suppliers, vendors, service providers, agents, representatives, predecessors, successors, acquirors, heirs, executors, administrators, fiduciaries, trustees, conservators and assigns (collectively, the "**Company Parties**"), on demand from and against all claims, demands, actions, damages, losses, costs, and expenses (including legal fees, court costs, investigative costs, amounts paid in settlement, and other costs and expenses) that arise from or relate to: (i) your claim request, (ii) your receipt of the Claim Amount, (iii) your violation of these Terms, or (iv) your violation of any rights of any other person or entity.
   2. The rights of the Company Parties under Section 6(a) are in addition to, and not in lieu of, (i) any other indemnities set forth in any other written agreement between you and us, and (ii) any other remedies that may be available to us under Applicable Laws or in equity.
   3. We reserve the right to exercise sole control over the defence, at your cost and expense, of any claim subject to indemnification under this Section 6.

7. **No Warranty**
   1. TO THE FULLEST EXTENT PERMITTED BY APPLICABLE LAWS, THE SITE AND SMART CONTRACT IS PROVIDED ON AN "AS IS" AND "AS AVAILABLE" BASIS WITHOUT WARRANTIES OF ANY KIND, WHETHER EXPRESS OR IMPLIED, AND WE EXPRESSLY DISCLAIM ALL SUCH WARRANTIES INCLUDING WITHOUT LIMITATION IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT. NO ADVICE OR INFORMATION, WHETHER ORAL OR WRITTEN, OBTAINED BY YOU FROM A COMPANY PARTY OR THROUGH THE SITE OR THE SMART CONTRACT WILL CREATE ANY WARRANTY NOT EXPRESSLY STATED HEREIN. WITHOUT LIMITING THE FOREGOING, THE COMPANY PARTIES DO NOT WARRANT THAT THE SITE OR THE SMART CONTRACT WILL MEET YOUR REQUIREMENTS; THAT THE SITE AND THE SMART CONTRACT WILL BE AVAILABLE AT ANY PARTICULAR TIME OR LOCATION, UNINTERRUPTED OR SECURE; THAT ANY DEFECTS OR ERRORS WILL BE CORRECTED; OR THAT THE SITE AND THE SMART CONTRACT ARE FREE OF VIRUSES OR OTHER HARMFUL COMPONENTS.\
      ANY CONTENT DOWNLOADED OR OTHERWISE OBTAINED THROUGH THE USE OF THE SITE OR THE SMART CONTRACT IS DOWNLOADED AT YOUR OWN RISK AND YOU WILL BE SOLELY RESPONSIBLE FOR ANY DAMAGE TO YOUR COMPUTER SYSTEM OR MOBILE DEVICE OR LOSS OF DATA THAT RESULTS FROM SUCH DOWNLOAD OR YOUR USE OF THE SITE OR THE SMART CONTRACT.
   2. YOU UNDERSTAND THAT BLOCKCHAIN TECHNOLOGY, THE SMART CONTRACT, AND OTHER CRYPTOCURRENCY ARE NEW AND UNTESTED TECHNOLOGIES OUTSIDE OF OUR CONTROL AND, THEREFORE, ADVERSE CHANGES IN MARKET FORCES, LAW, OR TECHNOLOGY WILL EXCUSE OUR PERFORMANCE UNDER THESE TERMS.
   3. TRANSACTIONS USING BLOCKCHAIN TECHNOLOGY, SUCH AS THOSE INVOLVING THE SMART CONTRACT, ARE AT RISK TO MULTIPLE POTENTIAL FAILURES, INCLUDING HIGH VOLUME ON THE PROTOCOL, COMPUTER FAILURE, PROTOCOL FAILURE OF ANY KIND, USER FAILURE, TOKEN THEFT, HACKING OF THE SMART CONTRACT, AND TELECOMMUNICATIONS OR INTERNET FAILURE OR DISRUPTION. WE ARE NOT RESPONSIBLE FOR ANY LOSS OF DATA, TOKENS, CLAIM AMOUNT OR OTHER CRYPTOCURRENCY, HARDWARE, OR SOFTWARE RESULTING FROM ANY TYPES OF FAILURES, THEFT OR HACK.<br>

8. **Limitation of Liability**
   1. You agree that to the maximum extent permitted by Applicable Laws, in no event shall any Company Party be liable for any direct, indirect, punitive, incidental, special, consequential or exemplary damages, including without limitation damages for loss of profits, goodwill, use, data or other intangible losses, arising out of or relating to these Terms, the Site, the Smart Contract or the Claim Amount or the use of, or inability to use, the Site or the Smart Contract. Under no circumstances will any Company Party be responsible for any damage, loss or injury resulting from hacking, tampering or other unauthorized access or use of the Site, the Smart Contract and other information contained therein. To the maximum extent permitted by Applicable Laws, the Company Parties assume no liability or responsibility for any (i) errors, mistakes, or inaccuracies of content; (ii) personal injury or property damage, of any nature whatsoever, resulting from your access to, interaction with or use of our Site or the Smart Contract; (iii) any unauthorized access to or use of our secure servers and/or any and all personal information stored therein; (iv) any interruption or cessation of transmission to or from the Site or the Smart Contract; (v) any bugs, viruses, trojan horses, or the like that may be transmitted to or through our Site or the Smart Contract by any third party; (vi) any errors or omissions in any content or for any loss or damage incurred as a result of the use of any content posted, emailed, transmitted, or otherwise made available through the Site or the Smart Contract; and/or (vii) the defamatory, offensive, or illegal conduct of any third party. You agree that if, notwithstanding the other provisions of these Terms, a Company Party is found to be liable for any claims, proceedings, liabilities, obligations, damages, losses or costs, such Company Party’s liability shall in no event exceed US$100.
   2. This limitation of liability section applies whether the alleged liability is based on contract, tort, negligence, strict liability, or any other basis, even if we have been advised of the possibility of such damage. The foregoing limitation of liability shall apply to the fullest extent permitted by Applicable Laws.<br>

9. **Limitations as Allowed by Law**

   Some states, provinces and other jurisdictions do not allow the exclusion and limitations of certain implied warranties, or the exclusion or limitation of incidental or consequential damages, so the above limitations or exclusions may not apply to you. The Terms gives you specific legal rights, and you may also have other rights which vary from jurisdiction to jurisdiction. The disclaimers, exclusions, and limitations of liability under the Terms will not apply to the extent prohibited by Applicable Laws.

10. **Release**

    To the fullest extent permitted by Applicable Laws, you release the Company Parties from any and all past, present, or future claims, actions, causes of action, class actions, costs, demands, obligations, expenses, injuries, judgments, losses, suits, damages, fees, interest, expenses, compensation, class actions, or causes of action for declaratory or injunctive relief, restitution, compensatory, general, special, statutory, or punitive damages of any kind or nature whatsoever, whether known or unknown, foreseen or unforeseen, liquidated or unliquidated, anticipated or unanticipated, suspected or unsuspected, past, present, or future, direct or indirect, contingent or absolute, whether individual, collective, or representative, and whether based on tort, contract, or other theories of recovery, including, without limitation, legal fees and other costs of defense arising out of, or in any way related to (i) any act or omission of the Company Parties in connection with the development, operation or management of the Site, Smart Contract or Claim Amount process, (ii) your access to, interaction with or use of the Site or the Smart Contract, and/or (iii) your receipt of the Claim Amount (each a "**Claim**" and collectively "**Claims**"), notwithstanding that any such Claim may have been contributed to or occasioned by the negligence of any of the Company Parties.<br>

11. **Governing Law and Jurisdiction**

    These Terms are entered into in Panama and shall be governed by, and construed in accordance with, the laws of Panama. You agree that we may initiate a proceeding related to the enforcement or validity of our intellectual property rights in any court having jurisdiction. For any other proceeding that is not subject to arbitration under these Terms, the courts located in Panama will have exclusive jurisdiction. You waive any objection to venue in any such courts.<br>

12. **Dispute Resolution and Arbitration**

    PLEASE READ THE FOLLOWING SECTION CAREFULLY BECAUSE IT REQUIRES YOU TO ARBITRATE CERTAIN DISPUTES AND CLAIMS WITH US AND LIMITS HOW YOU CAN SEEK RELIEF FROM US. ALSO, ARBITRATION PRECLUDES YOU FROM SUING IN COURT OR HAVING A JURY TRIAL.

    1. You and we agree that subject to Section 11 above, any Claim is personal to you and us and that any dispute will be resolved solely through individual action, and will not be brought as a class arbitration, class action, or any other type of representative proceeding.
    2. Except for disputes in which you or we seek injunctive or other equitable relief for the alleged unlawful use of intellectual property, you and we waive all rights to a jury trial and to have any Claim resolved in court. Instead, for any Claim you agree to first contact us and attempt to resolve the Claim informally by sending a written notice of your Claim (“**Notice**”) to us by email at <admin@kodiak.finance>. The Notice must: (i) include your name, residence address, email address, and telephone number; (ii) describe the nature and basis of the Claim; and (iii) set forth the specific relief sought. Our notice to you will be similar in form to that described above. If you and we cannot reach an agreement to resolve the Claim within thirty (30) days after such Notice is received, then either party may submit the dispute to binding arbitration administered by the Centro de Conciliación y Arbitraje de Panamá (“**CeCAP**”) before one arbitrator (the "**Arbitrator**"). The place of arbitration shall be Panama unless you and we agree otherwise and shall be conducted under CeCAP's Arbitration Regulation (the "**CeCAP Rules**"). The language to be used in the arbitral proceedings shall be English. The most recent version of the CeCAP Rules is available on the CeCAP website and are hereby incorporated by reference. You either acknowledge and agree that you have read and understand the CeCAP Rules or waive your opportunity to read the CeCAP Rules and waive any claim that the CeCAP Rules are unfair or should not apply for any reason.
    3. The Arbitrator will have exclusive authority to make all procedural and substantive decisions regarding any dispute and to grant any remedy that would otherwise be available in court, including the power to determine the question of arbitrability. The Arbitrator may conduct only an individual arbitration and may not consolidate more than one individual’s Claims, preside over any type of class or representative proceeding or preside over any proceeding involving more than one individual.
    4. The Arbitrator, we and you will maintain the confidentiality of any arbitration proceedings, judgments and awards, including, but not limited to, all information gathered, prepared, and presented for purposes of the arbitration or related to the dispute(s) therein. The Arbitrator will have the authority to make appropriate rulings to safeguard confidentiality unless the law provides to the contrary. The duty of confidentiality does not apply to the extent that disclosure is necessary to prepare for or conduct the arbitration hearing on the merits, in connection with a court application for a preliminary remedy or in connection with a judicial challenge to an arbitration award or its enforcement, or to the extent that disclosure is otherwise required by law or judicial decision.
    5. You and we agree that for any arbitration you or we initiate, you will pay the filing fee and all other CeCAP fees and costs. You and we agree that the courts of Panama have exclusive jurisdiction over the enforcement of an arbitration award.
    6. You further agree as follows: (i) any Claim brought by you must be filed within one year after your receipt of the Claim Amount; otherwise, the Claim is permanently barred, which means that you will not have the right to assert the Claim; (ii) no recovery by you may be sought or received for damages other than out-of-pocket expenses, except that the prevailing party will be entitled to costs and legal fees; and (iii) any Claim must be brought by you individually and not consolidated as part of a group or class action complaint.
    7. If any portion of this Section 12 is found to be unenforceable or unlawful for any reason: (i) the unenforceable or unlawful provision shall be severed from the Terms; (ii) severance of the unenforceable or unlawful provision shall have no impact whatsoever on the remainder of this Section 12 or the parties’ ability to compel arbitration of any remaining Claims on an individual basis under this Section 12; and (iii) to the extent that any Claims must proceed on a class, collective, consolidated, or representative basis, such claims must be litigated in a civil court of competent jurisdiction and not in arbitration, and the parties agree that litigation of those claims shall be stayed pending the outcome of any individual claims in arbitration. Further, if any part of this Section 12 is found to prohibit an individual claim seeking injunctive relief, then that provision will have no effect to the extent such relief is allowed to be sought out of arbitration, and the remainder of this Section 12 will be enforceable.<br>

13. **Severability**

    If a court of competent jurisdiction holds any provision of these Terms to be invalid or unenforceable, the remaining provisions of these Terms will remain in full force and effect. You and we intend that any invalid or unenforceable provisions will be interpreted to give effect to the intent of the original provisions. If such construction is not possible, the invalid or unenforceable provision will be severed from these Terms, but the rest of these Terms will remain in full force and effect.<br>

14. **Modification to these Terms**

    We reserve the right, in our sole discretion, to modify the Terms from time to time. If we make changes, we will provide you with notice of such changes, such as by providing notice through the Site or updating the “Last Updated” date at the top of the Terms. You waive any right to receive specific notice of each such change. It is your responsibility to periodically review these Terms to stay informed of any changes. You will be subject to and will be deemed to have been made aware of and to have accepted the changes in any revised Terms by your receipt of the Claim Amount, whether such changes occurred before or after your receipt of the Claim Amount.<br>

15. **Force Majeure**\
    The Company Parties will have no responsibility or liability for any failure or delay in performance any obligation under these Terms or any loss or damage that you may incur, due to any circumstance or event beyond our control, including any (a) flood, extraordinary weather conditions, earthquake, or other act of God, (b) fire, (c) war, (d) insurrection, (e) riot, (f) labour dispute, (g) accident, (h) epidemic or pandemic, (i) action of government, (j) new laws or regulations or change in existing laws or regulations or the interpretation or enforcement of any of the foregoing, (k) communications, (l) power failure, (m) equipment or software unavailability, disruption or malfunction, (n) hacking or other attack on the Site or the Smart Contract, (o) the unavailability, disruption or malfunction of any network or blockchains or (p) the unavailability, disruption or malfunction of the Internet.<br>

16. **Collection of Information**

    You acknowledge and agree that we will collect and store your Wallet address, IP address, and information regarding activity on the Site. The purpose of this data collection is to enable us to track your agreement to these Terms and to enforce the Terms if necessary. We do not intend to sell, share, transfer, or commercialize this information or use it in any automated decision-making process. You hereby authorize us to collect and store the your Wallet, IP address, and activity on the Site for the purposes above, which include enforcing the Terms.<br>

17. **Miscellaneous**
    1. You agree that we and you are independent contractors, and neither Party, nor any of their respective affiliates, is an agent of the other for any purpose or has the authority to bind the other.
    2. You acknowledge and agree that the Company Parties other than the Parties are third party beneficiaries of these Terms and that your obligations under these Terms are expressly intended to benefit all of the Company Parties despite not being signatories to these Terms.
    3. In connection with these Terms, you will comply with all applicable import, re-import, export, and re-export control and laws, regulations, guidance and programs, including the Export Administration Regulations, the International Traffic in Arms Regulations, and country or individual-specific economic sanctions programs implemented by OFAC or any equivalent applicable regimes. You are solely responsible for legal compliance related to your acquisition, use, exchange, and transfer of the Claim Amount.
    4. All communications and notices to be made or given pursuant to these Terms must be in the English language.
    5. You will not assign these Terms, or delegate or sublicense any of your rights under these Terms, without our prior written consent. Any assignment or transfer in violation of this Section 16(e) will be void. We may assign these Terms or any of its provisions without your consent. Subject to the foregoing, these Terms will be binding upon, and enure to the benefit of, the parties and their respective successors and permitted assigns.
    6. The failure by us to enforce any provision of these Terms will not constitute a present or future waiver of such provision, and will not limit our right to enforce such provision at a later time. All waivers by us must be in writing to be effective.
    7. These Terms (including the web links and other agreements and instruments referred to in these Terms) constitute the entire agreement among the parties and supersede all prior agreements and understandings, both written and oral, among the parties with respect to the subject matter hereof and thereof.
    8. You confirm to have carefully reviewed these Terms and fully understand all the risks set out herein.
    9. You agree that upon termination or expiry of these Terms or completion of the transactions contemplated herein, you shall continue to be bound by these Terms and such obligations survive such termination or expiry.
    10. Unless advised in writing of a different name and address, all notices, submissions and communications of any kind required or otherwise made under the Terms shall be sent (as required), and you and we each agree to accept service of any process for claims arising out of or related to the Terms via the following methods:
        1. If to you, via a message sent to your Wallet; and
        2. If to the Company Parties, to the following email address: <admin@kodiak.finance>.


