Meteora
  • Meteora: The most dynamic and sustainable liquidity layer on Solana
  • PRODUCT OVERVIEW
    • Meteora Liquidity Pools
      • DLMM Overview
        • What is DLMM?
        • DLMM Program
        • Dynamic Fees
        • Strategies & Use Cases
        • DLMM Farming Rewards
      • DLMM Launch Pool Overview
      • Dynamic AMM Overview
        • What is a Dynamic AMM Pool?
        • Dynamic AMM LP Fee and APY Calculation
        • Creating a Dynamic AMM Pool via the UI
        • Claiming Fees from Permanently Locked Liquidity
        • Dynamic AMM Stable Pools
        • Dynamic LST Pools
        • Additional yield from Dynamic Vaults
        • Dynamic AMM Farm Overview
      • DAMM v2 Overview
      • Memecoin Pool Overview
        • Memecoin Pool v2
          • What is Memecoin Pool v2?
        • Memecoin Pool v1
          • What is Memecoin Pool v1?
          • Permanently Locking Liquidity
      • Stake2Earn Pool Overview
        • What is a Stake2Earn Pool?
        • Stake2Earn for Launchpads
      • Multi-Token Stable Pool Overview
    • Alpha Vault Overview
    • Dynamic Vault Overview
      • What is a Dynamic Vault?
      • Dynamic Vault Program
      • Hermes - Meteora's Keeper
        • Algorithm to find optimal yield allocations
        • Rebalance crank
        • Operation fee calculation
      • Design Goals
      • Security
      • Dynamic Vaults Whitepaper
      • Dynamic Vaults Community Explainers
      • Affiliate Program for Dynamic Vault
        • Become an Affiliate Partner (Dynamic Vaults)
    • Dynamic Bonding Curve (DBC) Overview
      • What is the Dynamic Bonding Curve?
      • Customizable Pool Configuration
      • Bonding Curve Formula
      • DBC Migrator Keeper
  • Meteora's Anti-Sniper Suite (A.S.S.)
    • Meteora’s Anti-Sniper Suite
      • Dynamic Fees
      • Fee Scheduler
      • Rate Limiter
      • Alpha Vault
  • INTEGRATION
    • DLMM Integration
      • DLMM SDK
        • DLMM TypeScript SDK
        • CPI Examples
      • DLMM API
      • Fetching information on locked liquidity in a DLMM
    • Dynamic AMM Pool Integration
      • Dynamic AMM SDK
        • Dynamic AMM TypeScript SDK
        • CPI Examples
      • Dynamic AMM API
        • Pool Info
        • Pool State
      • Setting Pool and Fee Config for Dynamic AMM Pools
      • Create Dynamic Pool with Timestamp/Slot Activation
      • Dynamic AMM - Farm Integration
    • DAMM v2 Integration
      • DAMM v2 SDK
        • DAMM v2 TypeScript SDK
        • DAMM v2 Rust SDK
      • DAMM v2 API
      • Setting Pool and Fee Config for DAMM v2
      • Technical FAQ
    • Memecoin Pool Integration
      • Memecoin Pool v2 Integration
        • Setting Pool and Fee Config for Memecoin Pool v2
      • Memecoin Pool v1 Integration
        • TypeScript Code Examples
        • CPI Examples
        • Setting Pool and Fee Config for Memecoin Pool v1
        • Track permanently-locked liquidity in Memecoin Pool v1
        • Track Protocol Fee from swaps in Memecoin Pool v1
    • Stake2Earn Pool Integration
    • Dynamic Vault Integration
      • Using TypeScript-Client
      • Using Rust-Client
      • Using CPI
      • Vault API
        • Vault Info
        • Vault State
      • Vault Developer Resources
    • Alpha Vault Integration
      • Alpha Vault TypeScript SDK
      • Alpha Vault without Whitelist Setup
      • Alpha Vault with Whitelist Setup
    • Dynamic Bonding Curve (DBC) Integration
      • DBC SDK
        • DBC TypeScript SDK
        • DBC Rust SDK
      • DBC Fee Scheduler Formula
      • DBC Scripts
      • Program Repo
      • Launchpad Template
      • Technical FAQ
  • TOKEN LAUNCH POOLS
    • Steps to Create a Pool for a Token Launch
      • Create: DLMM Launch Pool
      • Create: Dynamic AMM Pool
      • Create: Memecoin Pool v1
      • Create: DAMM v2 Pool
      • Create: Stake2Earn Pool
      • Create: Pools with Alpha Vault
        • Create: DLMM Launch Pool with Alpha Vault
        • Create: Dynamic AMM Pool with Alpha Vault
        • Create: Memecoin Pool with Alpha Vault
        • Create: Stake2Earn Pool with Alpha Vault
    • Anti-Sniper Fee Suite for a Token Launch
  • Resources
    • Audits
    • Meteora Program IDs
    • Meteora APIs
    • Devnet Testing
    • Community Data Dashboards & Tools
    • Meteora Brand Assets
    • THE MASSIVE METEORA STIMULUS PACKAGE
      • Overview
      • 1. Dynamic Liquidity Market Maker (DLMM)
      • 2. Formation Of An LP Army DAO
      • 3. The 10% Stimulus Proposal
  • USER FAQ
    • Getting Started LPing
      • Supported Wallets
      • Prepare SOL
      • SOL required for Rent
      • What is Wrapped SOL?
      • What is an AMM?
      • What does it mean to provide liquidity?
      • How to swap to the tokens required for adding liquidity to a pool
      • How to quickly check if a token has any risks
      • Viewing your transaction history
      • My wallet has been compromised. What should I do?
    • Differences between DLMM and Dynamic Pools
    • DLMM FAQ
    • Dynamic AMM FAQ
      • How is the pool price of the token calculated in a Dynamic AMM?
      • What is a Meteora LP token?
      • How do I see fees earned on a Dynamic AMM Pool?
      • How to track your earnings for a Dynamic Pool?
      • What is Virtual Price in a Dynamic Pool?
      • How do LP tokens, fees, and virtual price work for Dynamic Pools?
      • Why must I add liquidity in non-stable Dynamic Pools using a 50:50 value ratio?
      • What is AMP in a Dynamic Pool with stable coins?
      • Why is the USDT-USDC pool not 1:1 in ratio of assets?
      • Can I create an LST, FX, or Multi-token pool using the Dynamic Pool creation tool?
    • Alpha Vault FAQ
    • Why is the token sometimes not picked up and tradable on Jupiter?
    • How do I create a new farm?
    • Video Tutorials to Get Started
      • LP Army Boot Camp
      • DLMM Strategy Sessions / Jam Sessions
  • Security and Risks
    • Risk of Impermanent Loss (IL)
    • Risk of depositing into an imbalanced pool / pool with price out of sync
    • Smart contract risk
    • Risk of a stablecoin depeg
    • Operational risk for dynamic vaults and pools
    • Lending risk for dynamic vaults and pools
  • legal
    • Terms of Service
    • Stake2Earn Terms of Service
Powered by GitBook
On this page
  • Resources
  • Devnet Testing
  • Quick Start Guide
  1. INTEGRATION
  2. Dynamic Vault Integration

Using TypeScript-Client

Mercurial Vault SDK is a TypeScript library that allows you to interact with Mercurial's dynamic vaults.

PreviousDynamic Vault IntegrationNextUsing Rust-Client

Last updated 4 months ago

The typescript client provides an easy way to integrate and interact with our Mercurial Dynamic Vaults. With the integration, your users can deposit and withdraw tokens from the vaults and receive the yield generated by the lending pools. You can also display key information regarding the vaults like total LP supply, total liquidity and APY etc. You can follow the simple guide below to get started.

Alternatively, you can also refer to and git clone the demo repos (react or node) to get started. The example demo includes all functionality and information we display on our own site.

Resources

NPM: https://www.npmjs.com/package/@mercurial-finance/vault-sdk

SDK: https://github.com/mercurial-finance/vault-sdk

Demo: https://vault-sdk-demo.vercel.app/

Demo repo: https://github.com/mercurial-finance/vault-sdk-demo

  • Easiest way to get started with our Typescript SDK, the example demo includes all functionality and information we display on our own site.

Node Demo repo: https://github.com/mercurial-finance/vault-sdk-node-demo

  • This is a simple demo written in node to help you have a quick understanding of how to integrate with the mercurial vault and call the various key functions.

  • You can git clone the repo and follow the steps in the readme to run the demo.

Docs: https://docs.mercurial.finance/mercurial-dynamic-yield-infra/

Discord: https://discord.com/channels/841152225564950528/864859354335412224

Devnet Testing

  • Devnet:

Note: If you are an affiliate partner, you are required to pass in your partner address in step 5 (in guide) when you initialize the vault instance. This is to allow our system to track the referral fees generated due to the liquidity provided by your users. To become an affiliate partner, you can contact us via our discord.

Quick Start Guide

1. Install Mercurial Vaults Dependencies

npm i @mercurial-finance/vault-sdk @project-serum/anchor @solana/web3.js @solana/spl-token @solana/spl-token-registry

2. Import the needed libraries

import { StaticTokenListResolutionStrategy, TokenInfo } from "@solana/spl-token-registry";
import { AnchorProvider } from '@project-serum/anchor';
import VaultImpl from '@mercurial-finance/vault-sdk';
import { BN } from 'bn.js';

3. Set up the connection, wallet and provider necessary to interact with the network

Set up the devnet connection

const devnetConnection = new Connection('https://api.devnet.solana.com/', { commitment: 'confirmed' });

Set up your mock wallet. We will be using the devnet wallet address for this demo

const mockWallet = new Wallet(new Keypair());

Finally, set up the Provider using the devnetConnection and mock wallet object

const provider = new AnchorProvider(devnetConnection, mockWallet, {
    commitment: 'confirmed',
});

4. Airdrop SOL into the devnet wallet

As this demo will be done using a devnet wallet, we can use the Solana airdrop function to deposit some initial SOL into the wallet.

Define the SOL airdrop function as shown below. We have already included this function in the util.ts file for easy access and use.

const airDropSol = async (connection: Connection, publicKey: PublicKey, amount = 1 * LAMPORTS_PER_SOL) => {
    try {
        const airdropSignature = await connection.requestAirdrop(
            publicKey,
            amount,
        );
        const latestBlockHash = await connection.getLatestBlockhash();
        await connection.confirmTransaction({
            blockhash: latestBlockHash.blockhash,
            lastValidBlockHeight: latestBlockHash.lastValidBlockHeight,
            signature: airdropSignature,
        });
    } catch (error) {
        console.error(error);
        throw error;
    }
};

To trigger the airdrop to your devnet wallet, simply call the function with devnetConnection and your mockWallet public key as input parameters.

// Airdrop to devnet wallet
await airDropSol(devnetConnection, mockWallet.publicKey);

5. Initialize the Vault

Retrieve the token info required to initialize the vault instance. We use the SOL token as an example here.

// Retrieve the token info for the vault (example: SOL)
const tokenMap = new StaticTokenListResolutionStrategy().resolve();
const SOL_TOKEN_INFO = tokenMap.find(token => token.symbol === 'SOL') as TokenInfo;

Set up the vault instance using the connection and the token info

// Getting a Vault Implementation instance (SOL)
const vault: VaultImpl = await VaultImpl.create(
    devnetConnection,
    SOL_TOKEN_INFO,
    {
        cluster: 'devnet'
    }
);

If you are an affiliate partner, you have to pass in an additional parameter - affiliateId when setting up the vault instance. The affiliateId is the partner wallet address that was used to set up the affiliate relationship with the Mercurial Dynamic Yield layer.

// Getting a Vault Implementation instance (SOL)
const vaultImpl: VaultImpl = await VaultImpl.create(
    devnetConnection,
    SOL_TOKEN_INFO,
    {
        cluster: 'devnet',
        // Replace with your own Partner ID!
        affiliateId: new PublicKey('7236FoaWTXJyzbfFPZcrzg3tBpPhGiTgXsGWvjwrYfiF')
    }
);

6. Get key data from the vault instance

Retrieve on-chain data from the vault and off-chain APY data from API. Key info includes total amount currently unlocked for user withdrawals, virtual price and the various strategies connected to the vault. The code for this can be found in getVaultDetails.ts

// Get on-chain data from the vault and off-chain data from the api
export const getVaultDetails = async (vaultImpl: VaultImpl) => {
    //Get the total unlocked amount in vault that is withdrawable by users
    const vaultUnlockedAmount = (await vaultImpl.getWithdrawableAmount()).toNumber();
    //Calculate virtual price using the vault's unlocked amount and lp supply
    const virtualPrice = (vaultUnlockedAmount / vaultImpl.lpSupply.toNumber()) || 0;

    // Get the off-chain data from API
    const URL = KEEPER_URL['devnet'];
    const vaultStateAPI: VaultStateAPI = await (await fetch(`${URL}/vault_state/${SOL_TOKEN_INFO.address}`)).json();
    const totalAllocation = vaultStateAPI.strategies.reduce((acc, item) => acc + item.liquidity, vaultStateAPI.token_amount)

    return {
        lpSupply: (await vaultImpl.getVaultSupply()).toString(),
        withdrawableAmount: vaultUnlockedAmount,
        virtualPrice,
        usd_rate: vaultStateAPI.usd_rate,
        closest_apy: vaultStateAPI.closest_apy, // 1 hour average APY
        average_apy: vaultStateAPI.average_apy, // 24 hour average APY
        long_apy: vaultStateAPI.long_apy, // 7 day average APY
        earned_amount: vaultStateAPI.earned_amount, // total fees earned by vault
        virtual_price: vaultStateAPI.virtual_price,
        total_amount: vaultStateAPI.total_amount,
        total_amount_with_profit: vaultStateAPI.total_amount_with_profit,
        token_amount: vaultStateAPI.token_amount,
        fee_amount: vaultStateAPI.fee_amount,
        lp_supply: vaultStateAPI.lp_supply,
        strategyAllocation: vaultStateAPI.strategies
            .map(item => ({
                name: item.strategy_name,
                liquidity: item.liquidity,
                allocation: ((item.liquidity / totalAllocation) * 100).toFixed(0),
                maxAllocation: item.max_allocation,
            }))
            .concat({
                name: 'Vault Reserves',
                liquidity: vaultStateAPI.token_amount,
                allocation: ((vaultStateAPI.token_amount / totalAllocation) * 100).toFixed(0),
                maxAllocation: 0,
            })
            .sort((a, b) => b.liquidity - a.liquidity),
    }
}

You can trigger the function and get the vault details via the following:

const vaultDetails = await getVaultDetails(vault);
console.log(vaultDetails);

7. To deposit tokens into the vault

The steps below will allow you to deposit tokens into the vault by specifying the source wallet and the amount you want to deposit.

// Deposits into the vault 
const depositAmount = 0.1;
const depositTx = await vault.deposit(mockWallet.publicKey, new BN(depositAmount * 10 ** SOL_TOKEN_INFO.decimals)); // 0.1 SOL
const depositResult = await provider.sendAndConfirm(depositTx);

8. To withdraw tokens from the vault

The steps below will allow you to withdraw tokens from the vault by specifying the destination wallet and the amount you want to withdraw from the vault.

// Withdraw from the vault
const withdrawAmount = 0.05;
const withdrawTx = await vault.withdraw(mockWallet.publicKey, new BN(withdrawAmount * 10 ** SOL_TOKEN_INFO.decimals)); // 0.05 SOL
const withdrawResult = await provider.sendAndConfirm(withdrawTx); // Transaction hash    

9. Retrieve affiliate partner info (only if you are set up as an affiliate partner)

If you are an affiliate partner, you can retrieve information about the partner account.

const partnerInfo = await vaultImpl.getAffiliateInfo();
console.log('Result:', {
        'publicKey': mockWallet.publicKey.toString(),
        'balance': (await vaultImpl.getUserBalance(mockWallet.publicKey)).toString(),
        'Partner Token': partnerInfo.partnerToken.toString(),
        'Vault': partnerInfo.vault.toString(),
        'Total Fee': partnerInfo.totalFee.toString(),
        'Fee Ratio': partnerInfo.feeRatio.toString(),
        'Cumulative Fee': partnerInfo.cummulativeFee.toString(),
})

https://devnet.meteora.ag/