[User] Which tokens are specified as input and output mints in the transaction example involving Alice and Bob?

[Assistant]
In the transaction example involving Alice and Bob, the specified tokens are:

- **Input Mint**: mSOL (Marina SOL)
- **Output Mint**: USDC (USD Coin)

piter API allows for building a swap transaction to receive an exact amount of token A for a maximum in amount of token B.

A Practical Example using the API
Bob is selling a delicious latte for 5 USDC, Alice only holds mSOL but Bob can use the Jupiter API to let Alice swap for exactly 5 USDC then transfer 5 USDC to his payment wallet.

First, we need to show Alice how much mSOL will he have to spend for the latte.

curl -s 'https://quote-api.jup.ag/v4/quote?inputMint=mSoLzYCxHdYgdzU16g5QSh3i5K3z3KZK7ytfqcJm7So&outputMint=EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v&amount=5000000&swapMode=ExactOut&slippageBps=1' | jq '.data | .[0] | .inAmount, .otherAmountThreshold'

Parameters:

The input mint is mSOL and the output mint is USDC.
swapMode is ExactOut, as opposed to the default ExactIn.
we want to receive amount=5000000, 5 USDC.
Response:

inAmount is the quoted estimated amount of mSOL required to receive 5 USDC.
otherAmountThreshold is the maximum in amount, the quote above with the slippage tolerance.
info
Currently, only Orca Whirlpool, Raydium CPAMM, and Raydium CLAMM support ExactOut mode. All tokens may not be available in this mode.

Then Bob creates the transaction with the /swap endpoint, and adds a 5 USDC token transfer from Alice to his payment wallet using the destinationWallet argument, which Alice will verify, sign and send.

info
In the example bellow, we assume the associated token account exists on destinationWallet.

import { Token, TOKEN_PROGRAM_ID, ASSO


[User] What does the method parameter in the Helius request signify?

[Assistant]
In the Helius API request, the `method` parameter specifies the particular action or operation that the API should perform. It is part of the JSON-RPC protocol used by Helius, which allows for remote procedure calls.

For example, in the following code snippet:

```javascript
const response = await fetch(url, {
    method: "POST",
    headers: {
        "Content-Type": "application/json",
    },
    body: JSON.stringify({
        jsonrpc: "2.0",
        id: "helius-test",
        method: "getTokenAccounts",
        params: params,
    }),
});
```

The `method` parameter is set to `"getTokenAccounts"`, indicating that the request is intended to retrieve token accounts. Each method corresponds to a specific functionality provided by the Helius API, and the value of the `method` parameter determines what data or action is being requested from the server.

t fetch(url, {
            method: "POST",
            headers: {
                "Content-Type": "application/json",
            },
            body: JSON.stringify({
                jsonrpc: "2.0",
                id: "helius-test",
                method: "getTokenAccounts",
                params: params,
            }),
        });

        const data = await response.json();

        if (!data.result || data.result.token_accounts.length === 0) {
            console.log("No more results");
            break;
        }

        data.result.token_accounts.forEach((account) => {
            allOwners.add(account.owner);
        });

        cursor = data.result.cursor;
    }

    writeFileSync("output.json", JSON.stringify(Array.from(allOwners), null, 2));
}

getTokenAccounts();
Response

Copy
[
  "111An9SVxuPpgjnuXW9Ub7hcVmZpYNrYZF4edsGwJEW",
  "11Mmng3DoMsq2Roq8LBcqdz6d4kw9oSD8oka9Pwfbj",
  "112uNfcC8iwX9P2TkRdJKyPatg6a4GNcr9NC5mTc2z3",
  "113uswn5HNgEfBUKfK4gVBmd2GpZYbxd1N6h1uUWReg",
  "11CyvpdYTqFmCVWbJJeKFNX8F8RSjNSYW5VVUi8eX4P",
  "11MANeaiHEy9S9pRQNu3nqKa2gpajzX2wrRJqWrf8dQ",
  "11MDcdk32JB8bJzpcCrGijaUbJEUpAgpikVfLrpgru1",
  "11MiBon8Vi6gfvwBz1tCFno52W4QZj4qgktLy5ZNQTz",
  "11MwoPvG25NZQcZaGBkmphb4B5bvPjKBE4zXNaZtZau",
  "11TaqNq9a7PBkYbGLfzpgC5VAr6XRtGBGC5T2AvUVus",
  ...
  "FEwuzsatWmqzxa6AtEWoMsKo2K7vRdHaG8UsuuAzooGn",
  "FEwxV2LT13ifNMs1KdpE87AzBNpK6SGDsACdvqs5utYb"
]
Previous
Get Signatures For Asset
Next
Get Nft Editions
Last updated 1 month ago

On this p


[User] Can you explain the 'rawOrder' object and its components in the context of Magic Eden?

[Assistant]
The `rawOrder` object in the context of Magic Eden is an optional component used when specifying details for a sell order. It allows for more granular control over the orders being interacted with. Here are the components of the `rawOrder` object:

1. **exactOrderSource**:
   - **Type**: string
   - **Description**: This field allows you to specify a particular source from which to consider orders. By setting this value, you can filter the orders to only include those from the designated source.

2. **exclusions**:
   - **Type**: array of objects
   - **Description**: This array is used to list items that should be excluded from the order consideration. Each item in this array can be an object that defines the specific exclusions you want to apply.

Here’s a simple example of how the `rawOrder` object might be structured in a sell request:

```json
{
  "rawOrder": {
    "exactOrderSource": "source_identifier",
    "exclusions": [
      {
        "token": "token_identifier_1",
        "quantity": 1
      },
      {
        "token": "token_identifier_2",
        "quantity": 2
      }
    ]
  }
}
```

In this example:
- The `exactOrderSource` is set to "source_identifier", meaning only orders from this source will be considered.
- The `exclusions` array contains two items, each specifying a token and its quantity that should be excluded from the order processing.

This structure allows users to tailor their sell orders more precisely according to their needs on the Magic Eden platform.

quired
List of items to sell.

object

token
string
required
Token to sell.

quantity
integer
Defaults to 1
Quantity of tokens to sell.

1
orderId
string
Optional order id to sell into.

rawOrder
object
Optional raw order to sell into.

rawOrder object
exactOrderSource
string
Only consider orders from this source.

exclusions
array of objects
Items to exclude

ADD object

ADD object
taker
string
required
Address of wallet filling.

source
string
Filling source used for attribution.

feesOnTop
array of strings
List of fees (formatted as feeRecipient:feeAmount) to be taken when filling.
The currency used for any fees on top matches the accepted bid's currency.
Example: 0xF296178d553C8Ec21A2fBD2c5dDa8CA9ac905A00:1000000000000000

ADD string
onlyPath
boolean
Defaults to false
If true, only the filling path will be returned.

false
normalizeRoyalties
boolean
Defaults to false
Charge any missing royalties.

false
excludeEOA
boolean
Defaults to false
Exclude orders that can only be filled by EOAs, to support filling with smart contracts.

false
allowInactiveOrderIds
boolean
Defaults to false
If true, inactive orders will not be skipped over (only relevant when filling via a specific order id).

false
partial
boolean
Defaults to false
If true, any off-chain or on-chain errors will be skipped.

false
forceRouter
boolean
Defaults to false
If true, filling will be forced to use the common 'approval + transfer' method instead of the approval-less 'on-received hook' method

fals


[User] What is the significance of the `sendAndConfirmTransaction` function in the Solana transaction workflow?

[Assistant]
The `sendAndConfirmTransaction` function in the Solana transaction workflow is significant because it is responsible for sending a transaction to the Solana network and waiting for confirmation that the transaction has been processed successfully. This function ensures that the transaction is not only submitted but also verified, providing feedback on its success or failure.

Here’s a breakdown of its importance:

1. **Transaction Submission**: It sends the constructed transaction to the Solana cluster, which is essential for any operation that modifies the state on the blockchain (e.g., transferring tokens, closing accounts).

2. **Confirmation**: After sending the transaction, it waits for confirmation from the network. This is crucial because it allows developers to know whether their transaction was successful or if it encountered any issues.

3. **Error Handling**: If the transaction fails, `sendAndConfirmTransaction` can provide error messages that help developers diagnose what went wrong, which is vital for debugging and improving the robustness of applications.

### Example Usage

In the provided code snippet, `sendAndConfirmTransaction` is used in the second method of closing a token account:

```javascript
let tx = new Transaction().add(
  createCloseAccountInstruction(
    tokenAccountPubkey, // token account which you want to close
    alice.publicKey, // destination
    alice.publicKey, // owner of token account
  ),
);
console.log(
  `txhash: ${await sendAndConfirmTransaction(connection, tx, [
    feePayer,
    alice /* fee payer + owner */,
  ])}`,
);
```

In this example:
- A transaction is created to close a token account.
- `sendAndConfirmTransaction` is called with the connection, the transaction, and the signers (fee payer and owner).
- The result (transaction hash) is logged, indicating whether the transaction was successful.

Overall, `sendAndConfirmTransaction` is a critical part of the transaction workflow in Solana, ensuring that operations are executed and confirmed on the blockchain.

// connection
  const connection = new Connection(clusterApiUrl("devnet"), "confirmed");

  // 5YNmS1R9nNSCDzb5a7mMJ1dwK9uHeAAF4CmPEwKgVWr8
  const feePayer = Keypair.fromSecretKey(
    bs58.decode(
      "588FU4PktJWfGfxtzpAAXywSNt74AvtroVzGfKkVN1LwRuvHwKGr851uH8czM5qm4iqLbs1kKoMKtMJG4ATR7Ld2",
    ),
  );

  // G2FAbFQPFa5qKXCetoFZQEvF9BVvCKbvUZvodpVidnoY
  const alice = Keypair.fromSecretKey(
    bs58.decode(
      "4NMwxzmYj2uvHuq8xoqhY8RXg63KSVJM1DXkpbmkUY7YQWuoyQgFnnzn6yo3CMnqZasnNPNuAT2TLwQsCaKkUddp",
    ),
  );

  const tokenAccountPubkey = new PublicKey(
    "2XYiFjmU1pCXmC2QfEAghk6S7UADseupkNQdnRBXszD5",
  );

  // 1) use build-in function
  {
    let txhash = await closeAccount(
      connection, // connection
      feePayer, // payer
      tokenAccountPubkey, // token account which you want to close
      alice.publicKey, // destination
      alice, // owner of token account
    );
    console.log(`txhash: ${txhash}`);
  }

  // or

  // 2) compose by yourself
  {
    let tx = new Transaction().add(
      createCloseAccountInstruction(
        tokenAccountPubkey, // token account which you want to close
        alice.publicKey, // destination
        alice.publicKey, // owner of token account
      ),
    );
    console.log(
      `txhash: ${await sendAndConfirmTransaction(connection, tx, [
        feePayer,
        alice /* fee payer + owner */,
      ])}`,
    );
  }
})();

How to Set Authority on Token Accounts or Mints
You can set/update authority. Ther


[User] How does the Solana program ensure that the payer account is the signer?

[Assistant]
In the Solana program, the verification that the payer account is the signer is done by checking the `is_signer` property of the `payer_account`. This is part of the account information passed to the program during the execution of a transaction.

In the provided code snippet, the check is implemented as follows:

```rust
// Checking if payer account is the signer
if !payer_account.is_signer {
    return Err(ProgramError::MissingRequiredSignature);
}
```

Here's a breakdown of how this works:

1. **Account Information**: When the program is invoked, it receives an array of `AccountInfo` objects, which represent the accounts involved in the transaction.

2. **Iterating Through Accounts**: The program uses an iterator (`accounts_iter`) to access the accounts. The first account retrieved is expected to be the payer account.

3. **Signer's Check**: The program checks the `is_signer` boolean property of the `payer_account`. If this property is `false`, it indicates that the payer account did not provide a signature for the transaction.

4. **Error Handling**: If the payer account is not a signer, the program returns an error (`ProgramError::MissingRequiredSignature`), which prevents further execution of the program.

This mechanism ensures that only accounts that have signed the transaction can be treated as valid payers, thereby enforcing security and integrity in the execution of the program.

time, check if the account's already been initialized or not.
Check if any cross program ids passed (whenever needed) are as expected.
A basic instruction which initializes a hero state account, but with the above mentioned checks is defined below

verify-accounts.rs
use borsh::{BorshDeserialize, BorshSerialize};
use solana_program::{
    account_info::{next_account_info, AccountInfo},
    clock::Clock,
    entrypoint,
    entrypoint::ProgramResult,
    msg,
    program_error::ProgramError,
    pubkey::Pubkey,
    rent::Rent,
    system_program::ID as SYSTEM_PROGRAM_ID,
    sysvar::Sysvar,
};

entrypoint!(process_instruction);

#[derive(BorshSerialize, BorshDeserialize, Debug)]
pub struct HelloState {
    is_initialized: bool,
}

// Accounts required
/// 1. [signer] Payer
/// 2. [writable] Hello state account
/// 3. [] System Program
pub fn process_instruction(
    program_id: &Pubkey,
    accounts: &[AccountInfo],
    _instruction_data: &[u8],
) -> ProgramResult {
    let accounts_iter = &mut accounts.iter();
    // Payer account
    let payer_account = next_account_info(accounts_iter)?;
    // Hello state account
    let hello_state_account = next_account_info(accounts_iter)?;
    // System Program
    let system_program = next_account_info(accounts_iter)?;

    let rent = Rent::get()?;

    // Checking if payer account is the signer
    if !payer_account.is_signer {
        return Err(ProgramError::MissingRequiredSignature);
    }

    // Checking if hello state acco


[User] What strategies can traders utilize with Jito's bundles to enhance their transaction outcomes?

[Assistant]
Traders can utilize several strategies with Jito's bundles to enhance their transaction outcomes, particularly through the following mechanisms:

1. **Atomic Arbitrage**: Traders can create bundles that include multiple transactions that need to be executed in a specific order to capitalize on price discrepancies across different markets. Since bundles are executed sequentially and atomically (all-or-nothing), this ensures that the entire arbitrage opportunity is captured without the risk of partial execution.

   ```json
   {
     "bundle": [
       { "transaction": "buy_token_A", "amount": 100 },
       { "transaction": "sell_token_A_for_token_B", "amount": 100 },
       { "transaction": "buy_token_B", "amount": 100 }
     ]
   }
   ```

2. **MEV Strategies**: Traders can leverage the concept of Maximum Extractable Value (MEV) by submitting bundles that compete against other bundles based on the tips they offer to validators. By strategically setting higher tips, traders can increase the likelihood of their bundles being included in the block.

3. **Complex Transaction Combinations**: By bundling up to five transactions, traders can create complex strategies that involve multiple steps, such as executing trades, providing liquidity, or interacting with various decentralized applications (dApps) in a single atomic operation.

4. **Simulating Bundles**: Before submitting, traders can simulate their bundles using the Jito Block-Engine to identify the most profitable combinations of transactions. This allows them to optimize their strategies based on potential outcomes and maximize their returns.

5. **Competitive Bidding**: Since bundles compete against each other based on the tips associated with them, traders can analyze the market and adjust their bids to ensure their bundles stand out, thereby increasing the chances of execution.

By utilizing these strategies, traders can effectively enhance their transaction outcomes while navigating the competitive landscape of the Solana ecosystem through Jito's bundle functionality.

rior transaction execution through fast landing, MEV protection, and revert protection, available for both single transactions and multiple transactions(bundles) via gRPC and JSON-RPC services, ensuring optimal performance in the highly competitive Solana ecosystem.”

../_images/matrixtxnsv4.png
System Overview
../_images/systemdiagramv2.png
🌐 How does the system work?
Validators run a modified Agave validator client called Jito-Solana that enables higher value capture for them and their stakers

The validator then connects to the Jito Block-Engine and Jito-Relayer

The Block-Engine submits profitable bundles to the validator

The Relayer acts as a proxy to filter and verify transactions for validators

Searchers, dApps, Telegram bots and others connect to the Block-Engine and submit transactions & bundles.

Submissions can be over gRPC or JSON-RPC

Bundles have tips bids associated with them; these bids are then redistributed to the validators and their stakers

💼 What are bundles?
Bundles are groups of transactions (max 5) bundled together

The transactions are executed sequentially and atomically meaning all-or-nothing

Bundles enable complex MEV strategies like atomic arbitrage

Bundles compete against other bundles on tips to the validator

📬 How do Bundles work?
Traders submit bundle to block engines

Block engines simulate bundles to determine the most profitable combinations

Winning bundles are sent to validators to include in blocks

Validators execute bundles a


[User] What responsibilities do users have when using Pump Portal regarding taxes?

[Assistant] Users of Pump Portal are solely responsible for reporting and paying any taxes applicable to their use of the Interface. This means that it is the user's duty to understand and comply with any tax obligations that may arise from their transactions or interactions facilitated by Pump Portal.

ge and agree that the Interface facilitates your interaction with decentralized networks and technology and, as such, we have no control over any blockchain or virtual currencies and cannot and do not ensure that any of your interactions will be confirmed on the relevant blockchain and do not have the ability to effectuate any cancellation or modification requests regarding any of your interactions.

Without limiting the foregoing, you specifically understand and hereby represent your acknowledgment of the following:

The pricing information data provided through the Interface does not represent an offer, a solicitation of an offer, or any advice regarding, or recommendation to enter into, a transaction with the Interface. The Interface does not act as an agent for any of the users. The Interface does not own or control any of the underlying software through which blockchain networks are formed, and therefore is not responsible for them and their operation. You are solely responsible for reporting and paying any taxes applicable to your use of the Interface. Although it is intended to provide accurate and timely information on the Interface, the Interface or relevant tools may not always be entirely accurate, complete, or current and may also include technical inaccuracies or typographical errors. Accordingly, you should verify all information before relying on it, and all decisions based on information contained on the Interface or relevant tools are your sole responsibility


[User] What type of data can I expect in the response body when I access the volume chart endpoint on CoinGecko?

[Assistant]
When you access the volume chart endpoint on CoinGecko, specifically the endpoint `https://pro-api.coingecko.com/api/v3/exchanges/{id}/volume_chart/range`, you can expect the response body to be an array of arrays of numbers. Each sub-array contains two elements:

1. A UNIX timestamp representing the date.
2. A string representing the volume in BTC for that date.

For example, the response might look like this:

```json
[
  [
    1711792200000,
    "306800.051794186777005"
  ],
  [
    1711795800000,
    "302561.8185582217570913"
  ],
  [
    1711799400000,
    "298240.5127048246776691"
  ]
]
```

This structure provides historical volume data for the specified exchange within the date range you query.

023777005"
5
  ],
6
  [
7
    1711795800000,
8
    "302561.8185582217570913"
9
  ],
10
  [
11
    1711799400000,
12
    "298240.5127048246776691"
13
  ]
14
]

💼 Exchange Volume Chart within Time Range by ID
get
https://pro-api.coingecko.com/api/v3/exchanges/{id}/volume_chart/range
This endpoint allows you to query the historical volume chart data in BTC by specifying date range in UNIX based on exchange’s id

📘
Notes

You can query the historical volume chart data of derivatives exchanges with this endpoint as well
The data interval for this endpoint is fixed at daily
The date range between from and to must be within 31 days
Cache/Update Frequency: 5 minutes
Exclusive for all Paid Plan Subscribers (Analyst, Lite, Pro and Enterprise)
Path Params
id
string
required
exchange id or derivative exchange id
*refers to /exchanges/list or /derivatives/exchanges/list.

Query Params
from
number
required
starting date in UNIX timestamp

to
number
required
ending date in UNIX timestamp

Response

200
Get exchange volume chart data

Response body
array of arrays of numbers
array of numbers
Updated 10 months ago

Exchange Volume Chart by ID
Derivatives
Did this page help you?
Language

Shell

Node

Ruby

PHP

Python
Credentials
x-cg-pro-api-key

Log in to use your API keys
1
curl --request GET \
2
     --url https://pro-api.coingecko.com/api/v3/exchanges/id/volume_chart/range \
3
     --header 'accept: application/json'

Try It!
RESPONSE
1
[
2
  [
3
    1711792200000,
4
    "306800.0517941


[User] How does ChainStack define the different levels of commitment for block processing?

[Assistant]
ChainStack defines three levels of commitment for block processing, which indicate the reliability of the block's status within the network:

1. **Processed**: This level indicates that the node has processed the block, but it may be on a fork. This means that while the block has been acknowledged by the node, it is not guaranteed to be part of the main chain.

2. **Confirmed**: At this level, the block is confirmed by the cluster as not being on a fork. This means that the block has been validated and is part of the main chain, providing a higher level of assurance than the processed state.

3. **Finalized**: This is the highest level of commitment. A block is considered finalized by the cluster, meaning it is irrevocably part of the blockchain and cannot be altered. This provides the strongest guarantee of the block's permanence in the network.

These levels help users understand the reliability of the block data they are working with, which is crucial for applications that depend on accurate blockchain state information.

Get you own node endpoint today

Start for free and get your app to production levels immediately. No credit card required.

You can sign up with your GitHub, X, Google, or Microsoft account.

Parameters
commitment — (optional) the level of commitment desired:
processed — the node has processed the block and the block may be on a fork.
confirmed — the block is confirmed by the cluster as not being on a fork.
finalized — the block is finalized by the cluster.
Response
value — the current supply information:
total — the total supply of lamports.
circulating — the circulating supply of lamports.
nonCirculating — the non-circulating supply of lamports.
nonCirculatingAccounts — the accounts that hold the non-circulating supply.
Use case
A practical use case for getSupply is to understand the current state of the network's economy. This can be useful for wallets or other applications that need to display or make use of this information.

Try the getSupply RPC method yourself
Body Params
id
integer
Defaults to 1
1
jsonrpc
string
Defaults to 2.0
2.0
method
string
Defaults to getSupply
getSupply
params
array
Defaults to
Response

200
Supply details

Updated 7 days ago

getStakeMinimumDelegation | Solana
getTokenAccountBalance | Solana
Did this page help you?
Language

Shell

Node

Ruby

PHP

Python
1
curl --request POST \
2
     --url https://nd-326-444-187.p2pify.com/9de47db917d4f69168e3fed02217d15b/ \
3
     --header 'accept: application/json' \
4
     --header 'content-type: appli


[User] How do dynamic pools in Meteora ensure that they remain active and do not become inactive?

[Assistant]
Dynamic pools in Meteora ensure that they remain active and do not become inactive by operating across the full price range. This means that the liquidity within these pools is always available for trading, regardless of price fluctuations. Unlike other types of pools that may become inactive if the price moves outside a specified range, dynamic pools are designed to continuously facilitate trades, thus maintaining their activity.

Additionally, dynamic pools utilize a constant product AMM (automated market maker) model, which simplifies the process for liquidity providers (LPs) and eliminates the need for active management and rebalancing. This design choice contributes to the ongoing functionality of the pools, ensuring they remain engaged in trading activities.

pared to dynamic pools.

DLMM pools also don't provide LP tokens upon adding liquidity, so projects cannot lock their liquidity permanently (unlike dynamic pools).

Any user can create a new DLMM pool here.

Dynamic Pools
Dynamic pools are pools with a constant product AMM (automated market maker) model that are relatively more straightforward to use for LPs. Unlike DLMM, dynamic pools have a fixed fee %, do not allow LPs to concentrate liquidity, and operate across the full price range so they won't become inactive. Therefore, dynamic pools do not require active management and rebalancing from LPs.

Assets in dynamic pools are also deposited directly into the vaults in the yield layer, so SOL/USDC/USDT assets will be dynamically allocated to external lending protocols to generate yield and rewards for LPs. LPs can receive yield from a few places — the AMM trading fees, the SOL/USDC/USDT lending interest, and any liquidity mining rewards collected from the platforms.

Creating a new dynamic pool is permissionless, meaning any user or developer can create a new pool without approval from the Meteora team.

In addition, with dynamic pools, memecoin creators have the option to "burn" their liquidity by permanently locking the Meteora LP tokens (which represent the liquidity in a dynamic pool). Memecoin creators can compound and claim fees on permanently locked liquidity forever, even though they no longer have access to that liquidity. Memecoin creators can consider launching t


[User] What is the significance of the airdrop_amount variable in the Solana airdrop process?

[Assistant]
The `airdrop_amount` variable in the Solana airdrop process specifies the amount of SOL (Solana's native cryptocurrency) that is requested to be transferred to a specified account. In the provided code example, the `airdrop_amount` is set to `1_000_000_000`, which corresponds to 1 SOL, as the smallest unit of SOL is called a lamport, where 1 SOL equals 1 billion lamports.

Here’s a breakdown of its significance:

1. **Funding an Account**: The airdrop is used to fund a new account (in this case, the `payer` account) with SOL, which is necessary for performing transactions on the Solana network. Without sufficient SOL, the account cannot pay for transaction fees or interact with smart contracts.

2. **Testing and Development**: Airdrops are particularly useful in development and testing environments where developers need to quickly fund accounts without needing to purchase SOL from an exchange.

3. **Transaction Fees**: The amount specified in `airdrop_amount` directly impacts the ability of the account to pay for transaction fees. Each transaction on the Solana network requires a small amount of SOL to be paid as a fee.

Here’s the relevant part of the code for context:

```rust
// Request airdrop
let airdrop_amount = 1_000_000_000; // 1 SOL
let signature = client
    .request_airdrop(&payer.pubkey(), airdrop_amount)
    .expect("Failed to request airdrop");
```

In summary, the `airdrop_amount` variable is crucial for ensuring that the account has enough SOL to participate in the Solana network's activities.

Client::new_with_commitment(rpc_url, CommitmentConfig::confirmed());

    // Generate a new keypair for the payer
    let payer = Keypair::new();

    // Request airdrop
    let airdrop_amount = 1_000_000_000; // 1 SOL
    let signature = client
        .request_airdrop(&payer.pubkey(), airdrop_amount)
        .expect("Failed to request airdrop");

    // Wait for airdrop confirmation
    loop {
        let confirmed = client.confirm_transaction(&signature).unwrap();
        if confirmed {
            break;
        }
    }

    // Create the instruction
    let instruction = Instruction::new_with_borsh(
        program_id,
        &(),    // Empty instruction data
        vec![], // No accounts needed
    );

    // Add the instruction to new transaction
    let mut transaction = Transaction::new_with_payer(&[instruction], Some(&payer.pubkey()));
    transaction.sign(&[&payer], client.get_latest_blockhash().unwrap());

    // Send and confirm the transaction
    match client.send_and_confirm_transaction(&transaction) {
        Ok(signature) => println!("Transaction Signature: {}", signature),
        Err(err) => eprintln!("Error sending transaction: {}", err),
    }
}

Before running the script, replace the program ID in the code snippet above with the one for your program.

You can get your program ID by running the following command.

Terminal
solana address -k ./target/deploy/hello_world-keypair.json

#[tokio::main]
async fn main() {
-     let program_id = Pubkey::f


[User] In Solana, what does the error code -32005 mean and how does it relate to node performance?

[Assistant]
In Solana, the error code -32005 indicates that a node is unhealthy. This can occur for various reasons related to the node's performance and synchronization with the network. The error message associated with this code may specify additional information, such as how many slots the node is behind.

For example, if a node is behind by a certain number of slots, the error response might look like this:

```json
{
  "jsonrpc": "2.0",
  "error": {
    "code": -32005,
    "message": "Node is behind by 42 slots",
    "data": {
      "numSlotsBehind": 42
    }
  },
  "id": 1
}
```

This indicates that the node has not kept up with the latest transactions and updates in the blockchain, which can affect its ability to process requests and maintain a reliable connection to the network. A node that is behind may struggle to provide accurate or timely data, leading to potential issues for applications relying on that node for blockchain interactions.

2005,
    "message": "Node is unhealthy",
    "data": {}
  },
  "id": 1
}

Unhealthy Result (if additional information is available)

{
  "jsonrpc": "2.0",
  "error": {
    "code": -32005,
    "message": "Node is behind by 42 slots",
    "data": {
      "numSlotsBehind": 42
    }
  },
  "id": 1
}

getHighestSnapshotSlot RPC Method
Edit Page
Returns the highest slot information that the node has snapshots for.

This will find the highest full snapshot slot, and the highest incremental snapshot slot based on the full snapshot slot, if there is one.

Version Restriction
This method is only available in solana-core v1.9 or newer. Please use getSnapshotSlot for solana-core v1.8 and below.

Parameters #
None

Result #
When the node has a snapshot, this returns a JSON object with the following fields:

full: <u64> - Highest full snapshot slot
incremental: <u64|null> - Highest incremental snapshot slot based on full
Code sample #
curl https://api.devnet.solana.com -s -X POST -H "Content-Type: application/json" -d '
  {"jsonrpc":"2.0","id":1,"method":"getHighestSnapshotSlot"}
'

Response #
Result when the node has a snapshot:

{
  "jsonrpc": "2.0",
  "result": {
    "full": 100,
    "incremental": 110
  },
  "id": 1
}

Result when the node has no snapshot:

{
  "jsonrpc": "2.0",
  "error": { "code": -32008, "message": "No snapshot" },
  "id": 1
}

getIdentity RPC Method
Edit Page
Returns the identity pubkey for the current node

Parameters #
None

Result #
The result field will be a J


[User] What function retrieves the minimum amount required for rent exemption for a Nonce Account in Solana?

[Assistant]
The function that retrieves the minimum amount required for rent exemption for a Nonce Account in Solana is `getMinimumBalanceForRentExemption`. You can use this function by passing in the length of the Nonce Account, which is defined as `web3.NONCE_ACCOUNT_LENGTH`.

Here’s an example of how to use this function in code:

```javascript
const web3 = require("@solana/web3.js");

// Create connection
let connection = new web3.Connection(web3.clusterApiUrl("devnet"), "confirmed");

// Get Minimum amount for rent exemption
let minimumAmount = await connection.getMinimumBalanceForRentExemption(
  web3.NONCE_ACCOUNT_LENGTH,
);

console.log("Minimum amount for rent exemption:", minimumAmount);
```

This code snippet establishes a connection to the Solana Devnet and retrieves the minimum balance required for a Nonce Account to be rent-exempt, then logs that amount to the console.

 certain custodial services, Nonce Accounts are used. Transactions which use a recentBlockhash captured on-chain by a Nonce Account do not expire as long at the Nonce Account is not advanced.

You can create a nonce account by first creating a normal account, then using SystemProgram to make the account a Nonce Account.

Example Usage #
const web3 = require("@solana/web3.js");

// Create connection
let connection = new web3.Connection(web3.clusterApiUrl("devnet"), "confirmed");

// Generate accounts
let account = web3.Keypair.generate();
let nonceAccount = web3.Keypair.generate();

// Fund account
let airdropSignature = await connection.requestAirdrop(
  account.publicKey,
  web3.LAMPORTS_PER_SOL,
);

await connection.confirmTransaction({ signature: airdropSignature });

// Get Minimum amount for rent exemption
let minimumAmount = await connection.getMinimumBalanceForRentExemption(
  web3.NONCE_ACCOUNT_LENGTH,
);

// Form CreateNonceAccount transaction
let transaction = new web3.Transaction().add(
  web3.SystemProgram.createNonceAccount({
    fromPubkey: account.publicKey,
    noncePubkey: nonceAccount.publicKey,
    authorizedPubkey: account.publicKey,
    lamports: minimumAmount,
  }),
);
// Create Nonce Account
await web3.sendAndConfirmTransaction(connection, transaction, [
  account,
  nonceAccount,
]);

let nonceAccountData = await connection.getNonce(
  nonceAccount.publicKey,
  "confirmed",
);

console.log(nonceAccountData);
// NonceAccount {
//   authorizedPub


[User] What is the significance of the hourly borrow rate in Jupiter's trading model?

[Assistant]
In Jupiter's trading model, the hourly borrow rate is significant because it represents the cost associated with borrowing assets from the pool to create larger trading positions. When traders use leverage, they borrow assets to increase their position size, which incurs an hourly fee that must be paid to the pool.

This borrow fee is an essential factor in calculating the actual leverage of a position, as it reduces the effective profit a trader can realize. Since positions always incur borrow fees and are never compensated with funding, the actual leverage for a position is slightly lower than the nominal leverage due to these fees.

For example, if a trader creates a 2x long position by borrowing 1x SOL from the pool, they will need to account for the hourly borrow rate in their profit and loss calculations. This means that while they might initially aim for a certain leverage, the ongoing costs of borrowing will affect their overall trading strategy and profitability.

In summary, the hourly borrow rate is crucial as it impacts the cost of maintaining leveraged positions and influences the trader's net profit or loss.

tand how the fee calculations work
realizedPnl = unrealizedPnl - (closeBaseFee + priceImpactFee + borrowFee)

info
This code snippet shows an example of calculating a position's PNL programmatically.

info
Read the Jupiter Perpetuals fee breakdown here for more info on open / close fees, price impact fees, and borrow fees.

Managing Leverage
Leverage
To allow for leverage, traders borrow assets from the pool to create a larger position. To create a 2x long position SOL-USD, the other 1x SOL will be borrowed from the pool.

This borrow leads to an hourly borrow rate to be paid to the pool. Positions always pay borrow fees and are never paid funding.

This means actual leverage for a position will be slightly lower as the calculation takes into account all fees associated with maintaining the position.

Auto Closing Positions that Exceed Maximum Leverage
The maximum allowed leverage is 500x.

Positions will be liquidated if the trader's collateral, after subtracting fees, adding unrealized profits and subtracting unrealized losses, is less than 0.2% of the position size.

info
When reducing the size of a position, the collateral amount is reduced as well to maintain the leverage for the position. For example, if a position has a 10x leverage, and reduces its size by 50%, the same amount of collateral will be withdrew from the position to maintain the 10x leverage.

Liquidation
The liquidation price for open positions represent the price at which the position will be automatica


[User] What does the market cap rank signify for a coin listed on CoinGecko?

[Assistant]
The market cap rank for a coin listed on CoinGecko signifies the coin's position relative to other cryptocurrencies based on its market capitalization. The market capitalization is calculated by multiplying the current price of the coin by its total circulating supply. A lower market cap rank indicates a higher market capitalization, meaning the coin is more valuable compared to others in the market.

In the context of the documentation, the market cap rank is represented as a number under the `market_cap_rank` field. This rank helps users quickly identify the relative size and importance of a cryptocurrency within the broader market.

For example, if a coin has a `market_cap_rank` of 1, it is the largest cryptocurrency by market cap (e.g., Bitcoin). Conversely, a coin with a `market_cap_rank` of 100 would be smaller, indicating it has a lower market capitalization compared to the top 99 coins.

lds
description
object
coin description

Has additional fields
links
object
links

homepage
array of strings
coin website url

whitepaper
array of strings
coin whitepaper url

blockchain_site
array of strings
coin block explorer url

official_forum_url
array of strings
coin official forum url

chat_url
array of strings
coin chat url

announcement_url
array of strings
coin announcement url

snapshot_url
string
coin snapshot url

twitter_screen_name
string
coin twitter handle

facebook_username
string
coin facebook username

bitcointalk_thread_identifier
string
coin bitcointalk thread identifier

telegram_channel_identifier
string
coin telegram channel identifier

subreddit_url
string
coin subreddit url

repos_url
object
coin repository url

repos_url object
image
object
coin image url

thumb
string
small
string
large
string
country_origin
string
coin country of origin

genesis_date
date-time
coin genesis date

sentiment_votes_up_percentage
number
coin sentiment votes up percentage

sentiment_votes_down_percentage
number
coin sentiment votes down percentage

market_cap_rank
number
coin rank by market cap

market_data
object
coin market data

current_price
object
coin current price in currency

current_price object
total_value_locked
number
total value locked

mcap_to_tvl_ratio
number
market cap to total value locked ratio

fdv_to_tvl_ratio
number
fully diluted valuation to total value locked ratio

roi
number
coin return on investment

ath
object
coin all time high (ath) in c


[User] What are the available commitment levels for the QuickNode getRecentBlockhash method?

[Assistant]
The available commitment levels for the QuickNode `getRecentBlockhash` method are as follows:

1. **finalized**: The node will query the most recent block confirmed by the supermajority of the cluster as having reached maximum lockout, meaning the cluster has recognized this block as finalized.

2. **confirmed**: The node will query the most recent block that has been voted on by the supermajority of the cluster.

3. **processed**: The node will query the most recent block that has been processed by the node.

Please note that the `getRecentBlockhash` method is deprecated and will be removed from Mainnet soon. For a similar method, you can use Solana's `getLatestBlockhash` RPC method.

tion/json" \
  --data '{"jsonrpc":"2.0", "id":1, "method":"getProgramAccounts", "params": ["PROGRAM_TO_SEARCH"]}'
Don't have an account yet?
Create your QuickNode endpoint in seconds and start building
Get started for free
Previous
getParsedTransaction
Next
getRecentBlockhash
Chat with our community
Check out our product changelog
Check on the status of our services
Read our blog for the latest announcements
Want the latest news in Web3?
We send out the #Web3Vibes newsletter with the coolest stuff in Blockchain every month. Sign up below!

hi@example.com
getRecentBlockhash RPC Method
Returns a recent block hash from the ledger, and a fee schedule that can be used to compute the cost of submitting a transaction using it. The API credit value for this method is 30.
Updated on
Aug 21, 2024
Please note that this method is deprecated, no longer available on Devnet and Testnet, and will be removed from Mainnet soon. For a similar method you can use Solana's getLatestBlockhash RPC method.
Parameters
object
array
The configuration object with the following fields:
commitment
string
The level of commitment required for the query. The options include:
finalized
string
The node will query the most recent block confirmed by the supermajority of the cluster as having reached maximum lockout, meaning the cluster has recognized this block as finalized
confirmed
string
The node will query the most recent block that has been voted on by the supermajority of the cluster
processed
string
The no


[User] How can I retrieve the current Solana version running on a node using an RPC call?

[Assistant]
To retrieve the current Solana version running on a node using an RPC call, you can use the `getVersion` method. This method does not require any parameters and will return a JSON object containing the software version of `solana-core` and a unique identifier for the current software's feature set.

Here’s how you can make the RPC call using `curl`:

```bash
curl https://api.devnet.solana.com -s -X POST -H "Content-Type: application/json" -d '
  {"jsonrpc":"2.0","id":1, "method":"getVersion"}
'
```

The expected response will look like this:

```json
{
  "jsonrpc": "2.0",
  "result": { "feature-set": 2891131721, "solana-core": "1.16.7" },
  "id": 1
}
```

In this response:
- `solana-core` indicates the version of the Solana software running on the node (e.g., "1.16.7").
- `feature-set` is a unique identifier of the current software's feature set (e.g., 2891131721).

You can replace the URL with the appropriate network endpoint (e.g., `https://api.mainnet-beta.solana.com` for the mainnet) as needed.

mIdIndex": 4
          }
        ],
        "recentBlockhash": "mfcyqEXB3DnHXki6KjjmZck6YjmZLvpAByy2fj4nh6B"
      },
      "signatures": [
        "2nBhEBYYvfaAe16UMNqRHre4YNSskvuYgx3M6E4JP1oDYvZEJHvoPzyUidNgNX5r9sTyN1J9UxtbCXy2rqYcuyuv"
      ]
    }
  },
  "blockTime": null,
  "id": 1
}

getTransactionCount RPC Method
Edit Page
Returns the current Transaction count from the ledger

Parameters #
object optional

Configuration object containing the following fields:

commitment string optional

minContextSlot number optional

The minimum slot that the request can be evaluated at

Result #
<u64> - the current Transaction count from the ledger

Code sample #
curl https://api.devnet.solana.com -s -X POST -H "Content-Type: application/json" -d '
  {"jsonrpc":"2.0","id":1, "method":"getTransactionCount"}
'

Response #
{ "jsonrpc": "2.0", "result": 268, "id": 1 }

getVersion RPC Method
Edit Page
Returns the current Solana version running on the node

Parameters #
None

Result #
The result field will be a JSON object with the following fields:

solana-core - software version of solana-core as a string
feature-set - unique identifier of the current software's feature set as a u32
Code sample #
curl https://api.devnet.solana.com -s -X POST -H "Content-Type: application/json" -d '
  {"jsonrpc":"2.0","id":1, "method":"getVersion"}
'

Response #
{
  "jsonrpc": "2.0",
  "result": { "feature-set": 2891131721, "solana-core": "1.16.7" },
  "id": 1
}

getVoteAccounts RPC Method
Edit Page
Ret


[User] What WebSocket client library can I use with ChainStack to connect to Solana's WebSocket API?

[Assistant]
The documentation does not specify a particular WebSocket client library that you must use with ChainStack to connect to Solana's WebSocket API. However, it mentions that you can use any WebSocket client library for your programming language of choice.

For example, if you're using JavaScript, you can use the built-in WebSocket API or libraries like `ws` or `socket.io`. In Python, you might use `websocket-client`. Here’s a simple example using JavaScript with the built-in WebSocket API:

```javascript
const WebSocket = require('ws');

const ws = new WebSocket('YOUR_CHAINSTACK_WEBSOCKET_ENDPOINT');

ws.on('open', function open() {
    console.log('Connected to WebSocket');
    // You can now send a subscription request, for example:
    ws.send(JSON.stringify({
        jsonrpc: "2.0",
        id: 1,
        method: "blockSubscribe",
        params: []
    }));
});

ws.on('message', function incoming(data) {
    console.log('Received:', data);
});
```

Make sure to replace `'YOUR_CHAINSTACK_WEBSOCKET_ENDPOINT'` with your actual Solana WebSocket endpoint URL. This example demonstrates how to establish a connection and send a subscription request.

 a specific block subscription. This method can be used to cancel an existing subscription to block updates.

See also blockSubscribe | Solana.

👍
Get your own Solana node endpoint today

Start for free and get your app to production levels immediately. No credit card required.

You can sign up with your GitHub, X, Google, or Microsoft account.

Parameters
integer - The ID of the subscription that you want to cancel.
Response
boolean - A boolean value indicating if the subscription was removed successfully. true if removed successfully, false if not.
blockUnsubscribe code examples
📘
Note that subscriptions require a WebSocket connection. You can use a WebSocket client library for your programming language of choice to interact with Solana's WebSocket API.

wscat

$ wscat -c YOUR_CHAINSTACK_WEBSOCKET_ENDPOINT
# Wait for the connection to be established

Connected (press CTRL+C to quit)

> {"jsonrpc":"2.0","id":1,"method":"blockUnsubscribe","params":[0]}
These examples demonstrate how to use the blockUnsubscribe method to remove a subscription matching the ID passed as a parameter. Replace 'YOUR_SOLANA_WEBSOCKET_ENDPOINT' with your actual Solana WebSocket endpoint URL, and use the correct subscription ID in the params array.

accountSubscribe | Solana
The accountSubscribe method in Solana allows developers to receive real-time notifications about changes to a specific account on the Solana blockchain. This subscription-based method provides updates whenever the monitored accoun


[User] How should users verify the information they obtain from the Jupiter Interface?

[Assistant] Users should verify the information they obtain from the Jupiter Interface by cross-referencing it with other reliable sources. Since the documentation notes that the information may not always be entirely accurate, complete, or current, it is essential for users to confirm the details before relying on them. This can involve checking official documentation, consulting expert opinions, or using trusted platforms that provide updated information. Ultimately, the responsibility for decisions based on the information from the Interface lies solely with the users.

mation on the Interface, the Interface or relevant tools may not always be entirely accurate, complete, or current and may also include technical inaccuracies or typographical errors. Accordingly, you should verify all information before relying on it, and all decisions based on information contained on the Interface or relevant tools are your sole responsibility.
In order to allow other users to have a full and positive experience of using the Interface you agree that you will not use the Interface in a manner that:

Breaches the Terms;
Infringes on or violates any copyright, trademark, service mark, patent, right of publicity, right of privacy, or other proprietary or intellectual property rights under the law;
Seeks to interfere with or compromise the integrity, security, or proper functioning of any computer, server, network, personal device, or other information technology system, including, but not limited to, the deployment of viruses and denial of service attacks;
Attempts, in any manner, to obtain the private key, password, account, or other security information from any other user, including such information about the digital wallet;
Decompiles, reverse engineer, or otherwise attempt to obtain the source code or underlying ideas or information of or relating to the Interface;
Seeks to defraud us or any other person or entity, including, but not limited to, providing any false, inaccurate, or misleading information in order to unlawfully obtain the property of anothe


[User] What does the 'trident init' command do in the context of Solana?

[Assistant]
The `trident init` command in the context of Solana is used to initialize a new Anchor-based project. When you run this command, it performs the following actions:

1. **Builds the Anchor-based project**: It sets up the necessary structure and files for an Anchor project, which is a framework for building Solana programs.

2. **Reads the generated IDL**: The command reads the Interface Definition Language (IDL) file that describes the program's interface, including the functions and accounts it uses.

3. **Creates the fuzzing template**: Based on the IDL, it generates a template for fuzz testing, which is a technique used to find vulnerabilities and bugs by inputting random data into the program.

This command is essential for setting up the environment needed for developing and testing Solana programs using the Trident fuzzing framework.

orkspace and run:

trident init

This command does the following:

Builds the Anchor-based project.
Reads the generated IDL.
Based on the IDL creates the fuzzing template.
Define Fuzz Accounts #
Define AccountsStorage type for each Account you would like to use:

#[doc = r" Use AccountsStorage<T> where T can be one of:"]
#[doc = r" Keypair, PdaStore, TokenStore, MintStore, ProgramStore"]
#[derive(Default)]
pub struct FuzzAccounts {
    author: AccountsStorage<Keypair>,
    hello_world_account: AccountsStorage<PdaStore>,
    // No need to fuzz system_program
    // system_program: AccountsStorage<todo!()>,
}

Implement Fuzz Instructions #
Each Instruction in the fuzz test has to have defined the following functions:

get_program_id() specifies which program the instruction belongs to. This function is automatically defined and should not need any updates. Its important to use especially if you have multiple programs in your workspace, allowing Trident to generate instruction sequences corresponding to different programs.
get_data() specifies what instruction inputs are sent to the program instructions.
get_accounts() specifies what accounts are sent to the program instructions.
Execute Fuzz Tests #
# Replace <TARGET_NAME> with the name of the
# fuzz test (for example: "fuzz_0")
trident fuzz run-hfuzz <TARGET_NAME>

Debug Fuzz Tests #
# fuzzer will run the <TARGET_NAME> with the specified <CRASH_FILE_PATH>
trident fuzz debug-hfuzz <TARGET_NAME> <CRASH_FILE_PATH>

For additional


[User] How is the spot price (s0) defined in the Magic Eden liquidity pool?

[Assistant]
In the Magic Eden liquidity pool, the spot price (s0) is defined as the price established within the pool itself. This means that the spot price is determined based on the parameters and conditions set within the liquidity pool, reflecting the current market conditions for the assets in that pool.

For further calculations or interactions with the liquidity pool, it's important to note that all values, including the spot price, should be normalized to decimal values (for example, 10% should be represented as 0.1).

RL

https://api-mainnet.magiceden.dev/v2
/marketplace/popular_collections
1
curl --request GET \
2
     --url https://api-mainnet.magiceden.dev/v2/marketplace/popular_collections \
3
     --header 'accept: application/json'

Try It!
RESPONSE
Click Try It! to start a request and see the response here! Or choose an example:
application/json

200

mmm
Tl;dr An automated market maker implies that instead of a human determining sell/buy prices, they are determined by various parameters we are going to walk you through below. 🙂

Now.. let’s talk about price calculation!

Some definitions
Liquidity Pool: simply put, a liquidity pool is a shared pot of digital assets (i.e. tokens)

Spot price - s0: As defined in the pool

Delta - Δ: As defined in the pool. Will be normalized to decimal value if the pool type is exponential

All the below values should be normalized to decimal values for calculations (10% = 0.1, 100bps = 0.01, etc.)

Royalty percentage - r: As defined in the pool (for when the pool is buyer) or the input params (for when the pool is seller)

Seller fee basis points - f: As defined in metadata

Maker fee - m: Maker fee, as defined by our maker/taker fee structure

Taker fee - t: Taker fee, as defined by our maker/taker fee structure

Effective LP fee - l: conditional function where it is zero if the pool is one sided and taken from the pool data if the pool is two sided

Effective price - e: What the person interacting with the pool expects to receive (if pool is buyer


[User] How is the getVersion method called using Curl in QuickNode?

[Assistant]
The `getVersion` method in QuickNode can be called using Curl with the following command:

```bash
curl https://docs-demo.solana-mainnet.quiknode.pro/ \
  -X POST \
  -H "Content-Type: application/json" \
  --data '{"jsonrpc":"2.0","id":1, "method":"getVersion"}'
```

In this command:
- The URL points to the QuickNode endpoint.
- The `-X POST` option specifies that this is a POST request.
- The `-H "Content-Type: application/json"` header indicates that the request body is in JSON format.
- The `--data` option contains the JSON payload, which specifies the JSON-RPC version, an identifier, and the method to be called (`getVersion`).

This request will return the current Solana version running on the node.

rted for free
Previous
getTransaction
Next
getVersion
Chat with our community
Check out our product changelog
Check on the status of our services
Read our blog for the latest announcements
Want the latest news in Web3?
We send out the #Web3Vibes newsletter with the coolest stuff in Blockchain every month. Sign up below!

hi@example.com
getVersion RPC Method
Returns the current solana version running on the node. The API credit value for this method is 30.
Updated on
Sep 20, 2024
Parameters
This method does not accept any parameters
Returns
result
A JSON object with the following fields:
solana-core
The software version of solana-core
feature-set
The unique identifier of the current software's feature set
Request

Curl
curl https://docs-demo.solana-mainnet.quiknode.pro/ \
  -X POST \
  -H "Content-Type: application/json" \
  --data '{"jsonrpc":"2.0","id":1, "method":"getVersion"}'
Don't have an account yet?
Create your QuickNode endpoint in seconds and start building
Get started for free
Previous
getTransactionCount
Next
getVoteAccounts
Chat with our community
Check out our product changelog
Check on the status of our services
Read our blog for the latest announcements
Want the latest news in Web3?
We send out the #Web3Vibes newsletter with the coolest stuff in Blockchain every month. Sign up below!

hi@example.com
getVoteAccounts RPC Method
Returns the account info and associated stake for all the voting accounts in the current bank. The API credit value for this method is 30


[User] Can you explain how Helius verifies a payment mint using VERIFY_PAYMENT_MINT?

[Assistant]
The `VERIFY_PAYMENT_MINT` method in Helius is used to verify a payment mint. This method ensures that the minting process for a payment has been executed correctly and that the minted payment is valid.

While the specific details of the implementation are not provided in the snippet, typically, such a verification method would involve checking the following:

1. **Mint Address**: Confirming that the mint address corresponds to a valid payment mint.
2. **Signature Verification**: Ensuring that the transaction has been signed correctly by the appropriate authorities.
3. **State Validation**: Checking the current state of the payment mint to ensure it is in a valid state for verification.

Here is a hypothetical example of how you might call this method in code:

```javascript
const paymentMintAddress = "your_payment_mint_address_here";

async function verifyPaymentMint() {
    try {
        const result = await Helius.VERIFY_PAYMENT_MINT(paymentMintAddress);
        console.log("Payment Mint Verification Result:", result);
    } catch (error) {
        console.error("Error verifying payment mint:", error);
    }
}

verifyPaymentMint();
```

In this example, replace `"your_payment_mint_address_here"` with the actual address of the payment mint you wish to verify. The function `verifyPaymentMint` calls the `VERIFY_PAYMENT_MINT` method and logs the result or any errors encountered during the verification process.

For more detailed implementation specifics, you would need to refer to the complete Helius documentation.

METHOD
EQUIP_TRAIT
EQUIP_TRAIT_AUTHORITY
REMOVE_TRAIT
REMOVE_TRAIT_AUTHORITY
UPDATE_TRAIT_VARIANT
UPDATE_TRAIT_VARIANT_AUTHORITY
UPDATE_CLASS_VARIANT_AUTHORITY
UPDATE_TRAIT_VARIANT_METADATA
UPDATE_CLASS_VARIANT_METADATA
BEGIN_VARIANT_UPDATE
BEGIN_TRAIT_UPDATE
CANCEL_UPDATE
UPDATE_VARIANT
TRANSFER_PAYMENT
BURN_PAYMENT
BURN_PAYMENT_TREE
TRANSFER_PAYMENT_TREE
ADD_PAYMENT_MINT_PAYMENT_METHOD
ADD_TRAIT_CONFLICTS
VERIFY_PAYMENT_MINT
VERIFY_PAYMENT_MINT_TEST
BOUND_HADO_MARKET_TO_FRAKT_MARKET
DEPOSIT_TO_BOND_OFFER_STANDARD
WITHDRAW_FROM_BOND_OFFER_STANDARD
INITIALIZE_HADO_MARKET
FINISH_HADO_MARKET
UPDATE_HADO_MARKET_FEE
REMOVE_BOND_OFFER_V2
REPAY_FBOND_TO_TRADE_TRANSACTIONS
EXIT_VALIDATE_AND_SELL_TO_BOND_OFFERS_V2
REFINANCE_TO_BOND_OFFERS_V2
CREATE_BOND_AND_SELL_TO_OFFERS
LIQUIDATE_BOND_ON_AUCTION_PNFT
CLAIM_NFT_BY_LENDER_PNFT
CREATE_BOND_AND_SELL_TO_OFFERS_FOR_TEST
INITIALIZE_FLASH_LOAN_POOL
DEPOSIT_SOL_TO_FLASH_LOAN_POOL
WITHDRAW_SOL_FROM_FLASH_LOAN_POOL
TAKE_FLASH_LOAN
REPAY_FLASH_LOAN
CREATE_BOND_OFFER_STANDARD
UPDATE_BOND_OFFER_STANDARD
STAKE_BANX
UNSTAKE_BANX
UNSUB_OR_HARVEST_WEEKS
UNSUB_OR_HARVEST_WEEKS_ENHANCED
UPDATE_STAKING_SETTINGS
MAP_BANX_TO_POINTS
PATCH_BROKEN_USER_STAKES
DEPOSIT_TO_REWARDS_VAULT
WITHDRAW_REWARDS_FROM_VAULT
REFINANCE_FBOND_BY_LENDER
SELL_STAKED_BANX_TO_OFFERS
REPAY_STAKED_BANX
CREATE_PERPETUAL_BOND_OFFER
REMOVE_PERPETUAL_OFFER
REPAY_PERPETUAL_LOAN
REFINANCE_PERPETUAL_LOAN
CREATE_BOND_AND_SELL_TO_OFFERS_CNFT
REPAY_FBOND_TO_TRADE_TRANSACTIONS_CNFT
REFINAN


[User] What information can be found by clicking on a pool in the AcceleRaytor section of Raydium?

[Assistant] When you click on a pool in the AcceleRaytor section of Raydium, you can view additional details about the pool. This includes important information such as the requirements to join the pool, which is essential to ensure that you will be able to participate in the token offering.

pe=Day

RAY Staking
If you're holding RAY tokens, staking is an easy way to earn additional RAY.

How to stake:

To stake, first navigate to the 'Staking' tab in the Raydium app.

2. Enter the amount of tokens you wish to stake, then click 'Stake' and then approve the transaction.

3. You should now see the balance of your staked tokens, as well as your pending rewards. If you want to unstake, simply click the '-' button.

That's it! You're now staking on Raydium!

Acceleraytor
How to Participate

AcceleRaytor is an initiative by Raydium to spearhead the growth of the Solana Ecosystem. It serves as a launchpad for the latest projects to raise capital and drive initial liquidity in a decentralized and interoperable manner, while enabling both project and Raydium communities to participate in carefully curated and vetted token offerings.

If you're interested in launching a project on AcceleRaytor, please fill out this form and we'll get back to you if the project is a good fit!

How to participate:

AcceleRaytor launches consist of 'pools' where users can contribute funds in order to receive an allocation of project tokens.

Visit the 'AcceleRaytor' page on Raydium. Here you can view pools and their status.

2. You can click on a pool to view additional details. Make sure to make note of the requirements to join the pool to ensure you'll be able to participate.

3. When the pool opens, to participate first make sure that you meet the requirements, check official announc


[User] How can I obtain the CoinGecko API ID for a specific coin using the /coins/list endpoint?

[Assistant]
To obtain the CoinGecko API ID for a specific coin using the `/coins/list` endpoint, you can follow these steps:

1. **Make a Request to the `/coins/list` Endpoint**: This endpoint returns a list of all coins available on CoinGecko along with their respective API IDs.

2. **Filter the Response**: Once you receive the response, you can search through the list to find the specific coin you are interested in and retrieve its API ID.

### Example Code

Here’s an example of how you could implement this in Python using the `requests` library:

```python
import requests

def get_coin_id(coin_name):
    # Make a request to the /coins/list endpoint
    response = requests.get('https://api.coingecko.com/api/v3/coins/list')

    # Check if the request was successful
    if response.status_code == 200:
        coins = response.json()

        # Search for the coin in the response
        for coin in coins:
            if coin['name'].lower() == coin_name.lower():
                return coin['id']  # Return the API ID of the coin
    else:
        print("Error fetching data:", response.status_code)

    return None

# Example usage
coin_name = "Bitcoin"
coin_id = get_coin_id(coin_name)
if coin_id:
    print(f"The API ID for {coin_name} is: {coin_id}")
else:
    print(f"{coin_name} not found.")
```

### Explanation

- The code sends a GET request to the `/coins/list` endpoint.
- It checks if the response is successful (status code 200).
- It iterates through the list of coins to find the one that matches the provided name.
- If found, it returns the API ID of that coin.

This method allows you to programmatically obtain the CoinGecko API ID for any coin listed on the platform.

btain the coin id (api id) via several ways:
refers to respective coin page and find ‘api id’
refers to /coins/list endpoint
refers to google sheets here
You may also flag to include more data such as tickers, market data, community data, developer data and sparkline
You may refer to last_updated in the endpoint response to check whether the price is stale
📘
Notes

Tickers are limited to 100 items, to get more tickers, please go to /coins/{id}/tickers
Cache/Update Frequency:
Every 60 seconds for all the API plans
Community data for Twitter and Telegram will be updated on weekly basis (Reddit community data is no longer supported)
Path Params
id
string
required
coin id
*refers to /coins/list.

Query Params
localization
boolean
include all the localized languages in the response, default: true

tickers
boolean
include tickers data, default: true

market_data
boolean
include market data, default: true

community_data
boolean
include community data, default: true

developer_data
boolean
include developer data, default: true

sparkline
boolean
include sparkline 7 days data, default: false

Response

200
Get current data for a coin

Response body
object
id
string
coin id

symbol
string
coin symbol

name
string
coin name

web_slug
string
coin web slug

asset_platform_id
string
coin asset platform id

platforms
object
coin asset platform and contract address

Has additional fields
detail_platforms
object
detailed coin asset platform and contract address

Has additional fields
b


[User] How can I identify the source and destination tokens in a QuickNode swap?

[Assistant]
In a QuickNode swap, you can identify the source and destination tokens using the `inputMint` and `outputMint` fields in the response from the API.

- **inputMint**: This field contains the mint address of the source token, which is the token you are swapping from.
- **outputMint**: This field contains the mint address of the destination token, which is the token you are swapping to.

Here is an example of how the response might look:

```json
{
  "jsonrpc": "2.0",
  "id": 1,
  "result": {
    "inputMint": "source_token_mint_address",
    "inAmount": "100",
    "outputMint": "destination_token_mint_address",
    "outAmount": "95",
    "otherAmountThreshold": "1",
    "swapMode": "exactIn",
    "slippageBps": 50,
    "platformFee": {
      "amount": "0.5",
      "feeBps": 5
    },
    "priceImpactPct": "0.5"
  }
}
```

In this example:
- The source token's mint address is `"source_token_mint_address"`.
- The destination token's mint address is `"destination_token_mint_address"`.

You can use these mint addresses to identify the specific tokens involved in the swap.

Bps is what we suggest you to use. Reference maxAutoSlippageBps and autoSlippageCollisionUsdValue when using this parameter.
maxAutoSlippageBps
integer
Used in conjunction with autoSlippage when set to true, the maximum slippageBps returned by the API will respect this value. It is recommended that set this value when using autoSlippage.
autoSlippageCollisionUsdValue
integer
Used in conjunction with autoSlippage when set to true, the API will use a default 1000 USD value as way to calculate the slippage impact for the autoSlippage. You can set a custom USD value using this parameter.
useQNMarketCache
boolean
When set to true, the response includes your added pools/markets
Returns
jsonrpc
string
The version of the JSON-RPC protocol being used
id
integer
A unique identifier for the request
result
object
The result of the quote
inputMint
string
The source token's mint address
inAmount
string
The amount of the source token being swapped
outputMint
string
The destination token's mint address
outAmount
string
The amount of the destination token received after the swap
otherAmountThreshold
string
A threshold amount for the destination token
swapMode
string
Indicates the swap mode
slippageBps
integer
Slippage tolerance in basis points
platformFee
object
The platform Fee object which contains the following fields:
amount
string
The amount of the platform fee
feeBps
integer
The fee percentage in basis points
priceImpactPct
string
The percentage of price impact due to the swap
routePlan


[User] How does Magic Eden's approach to wallet detection differ from that in the Solana ecosystem?

[Assistant]
Magic Eden's approach to wallet detection for Bitcoin differs from that in the Solana ecosystem primarily due to the lack of an established standard in the Bitcoin development community. Here are the key differences based on the documentation:

1. **Namespace Usage**: Magic Eden recommends using a unique namespace (`window.magicEden.bitcoin`) to avoid conflicts with other wallets that may occupy the same namespace. This is a specific approach tailored to the Bitcoin ecosystem.

2. **Direct Provider Detection**: To detect if the Magic Eden wallet is installed, developers can check for the `isMagicEden` flag within the `window.magicEden.bitcoin` object. The provided code snippet demonstrates this method:
   ```javascript
   const getBtcProvider = () => {
       if ("magicEden" in window) {
           const anyWindow: any = window;
           if (anyWindow.magicEden.bitcoin && anyWindow.magicEden.bitcoin.isMagicEden)
               return anyWindow.magicEden.bitcoin;
       }
       window.location.href = "https://wallet.magiceden.io/";
   };
   ```
   This code not only checks for the provider but also suggests redirecting users to download the wallet if it is not installed.

3. **Lack of a Unified Standard**: Unlike Solana, where there is a more established and agreed-upon wallet standard, the Bitcoin development community is still evolving, and there isn't a unified standard for wallet detection. This means that while Solana developers can rely on a consistent method for wallet interactions, Bitcoin developers must implement custom solutions like the one provided by Magic Eden.

4. **Alternative Detection Method**: Magic Eden also mentions the possibility of using the Bitcoin Wallet Standard to identify compatible wallets, but this requires more effort and is not as straightforward as the methods available in the Solana ecosystem.

In summary, Magic Eden's wallet detection for Bitcoin is more customized and less standardized compared to the more uniform approach seen in the Solana ecosystem.

y other wallets who occupy the same namespace. Therefore, we make use of the Bitcoin extension of the Wallet Standard to successfully identify the correct provider in this case.

We recommend interacting via our unique window.magicEden.bitcoin namespace whenever possible to avoid the above conflicts.

Directly Locating the Provider
To properly detect if the ME wallet is installed, you can look for an additional isMagicEden flag. All together it will look something like this:

Copy
const getBtcProvider = () => {
	if ("magicEden" in window) {
		const anyWindow: any = window;
		if (anyWindow.magicEden.bitcoin && anyWindow.magicEden.bitcoin.isMagicEden)
			return anyWindow.magicEden.bitcoin;
	}
	window.location.href = "https://wallet.magiceden.io/";
};
Note:

This includes a redirect to our website to download the wallet if a user does not have it installed. This is not mandatory for detecting the provider, but a suggested action to take in that case

Utilizing the Wallet Standard
Alternatively, you can utilize the Bitcoin Wallet Standard to identify a list of all wallets that comply with the standard, and select Magic Eden from there. This requires a bit more leg work up front, but allows app developers to easily discover all compatible BTC wallets.

Reference our Wallet Standard BTC Demo for a full code breakdown of this implementation style.

Caution:

The BTC development community is still rather young, and there isn't an "agreed upon" standard like you might find in Solana.


[User] How does the onFinish callback function operate in the context of transaction signing on Magic Eden?

[Assistant]
In the context of transaction signing on Magic Eden, the `onFinish` callback function is invoked after the transaction signing process is completed. This function receives a response that contains information about the signed transaction.

Here’s how it operates:

1. **Response Handling**: The `onFinish` function takes a parameter called `response`, which contains the signed transaction data. Specifically, it includes a property called `psbtBase64`, which is a base64-encoded representation of the partially signed Bitcoin transaction (PSBT).

2. **Finalizing Inputs**: Inside the `onFinish` function, the PSBT is converted from its base64 format back into a PSBT object using `Psbt.fromBase64(response.psbtBase64)`. This allows you to work with the PSBT programmatically.

3. **Finalizing the Transaction**: The `finalizeAllInputs()` method is called on the PSBT object. This method finalizes all inputs of the PSBT, preparing it for broadcasting to the Bitcoin network.

4. **Extracting the Signed Transaction**: After finalizing, the signed transaction is extracted using `psbResponse.extractTransaction()`. This gives you a transaction object that represents the fully signed transaction.

5. **Getting the Hex Representation**: Finally, the signed transaction is converted to its hexadecimal format using `signedTx.toHex()`, which is the format required for broadcasting the transaction to the Bitcoin network.

Here is a simplified code example illustrating the `onFinish` callback:

```javascript
onFinish: (response) => {
  const psbResponse = Psbt.fromBase64(response.psbtBase64);
  psbResponse.finalizeAllInputs();
  const signedTx = psbResponse.extractTransaction();
  const txHex = signedTx.toHex();
  // You can now broadcast txHex to the network
},
```

In summary, the `onFinish` callback is crucial for handling the signed transaction, finalizing it, and preparing it for broadcasting, ensuring that the transaction can be successfully sent to the Bitcoin network.

electedUTXO,
    recipientAddress: RECIPIENT_ADDRESS,
    changeAddress: nativeSegwitAddress,
    amountToSend: 1000,
    scriptPubKey,
  });

  try {
    await signTransaction({
      payload: {
        network: {
          type: BitcoinNetworkType.Mainnet,
        },
        psbtBase64: psbt,
        broadcast: true,
        message: "tip the author! Don't worry this will not be broadcasted.",
        inputsToSign: [
          {
            address: nativeSegwitAddress!,
            signingIndexes: [0],
      },
      ],
    },
    onFinish: (response) => {
      const psbResponse = Psbt.fromBase64(response.psbtBase64);
      psbResponse.finalizeAllInputs();
      const signedTx = psbResponse.extractTransaction();
      const txHex = signedTx.toHex();
    },
      onCancel: () => {
        alert('Request canceled');
      },
  });
} catch (err) {
  console.error(err);
}
}
There's a lot going on here, so here's a breakdown of each part.

Understanding UTXOs:
In the world of Bitcoin, the concept of a "balance" operates differently compared to traditional bank accounts or even some other blockchain networks. Rather than representing your funds as a single total amount, your Bitcoin balance is actually the sum of all values from Unspent Transaction Outputs (UTXOs). UTXOs are essentially fragments of Bitcoin left over from previous transactions that you have received but not yet spent.

When someone sends you Bitcoin, the amount is recorded in the blockchain as a UTXO, earmarked


[User] How can users fetch their DCA accounts using the Jupiter DCA program?

[Assistant]
Users can fetch their DCA accounts using the Jupiter DCA program by utilizing the `getCurrentByUser` method provided by the DCA API. This method retrieves all DCA accounts associated with a specific user.

Here’s an example of how to implement this in code:

```javascript
async function main() {
  // Assuming 'user' is already defined and represents the current user
  const dcaAccounts = await dca.getCurrentByUser(user.publicKey);
  console.log({ dcaAccounts });
}

main();
```

In this example, the `main` function calls `getCurrentByUser` with the user's public key, which returns the DCA accounts associated with that user. The results are then logged to the console. This allows users to easily access their DCA accounts in the Jupiter DCA program.

wing from program ATA
async function withdraw(dcaPubKey) {
  // it's possible to withdraw in-tokens only or out-tokens only or both in and out tokens together. See WithdrawParams for more details
  const params: WithdrawParams = {
    user: user.publicKey,
    dca: dcaPubKey,
    inputMint: USDC,
    withdrawInAmount: BigInt(1_000_000),
  };

  const { tx } = await dca.withdraw(params);

  const txid = await sendAndConfirmTransaction(connection, tx, [user]);

  console.log('Withdraw: ', { txid });
}

async function closeDCA(dcaPubKey) {
  const params: CloseDCAParams = {
    user: user.publicKey,
    dca: dcaPubKey,
  };

  const { tx } = await dca.closeDCA(params);

  const txid = await sendAndConfirmTransaction(connection, tx, [user]);

  console.log('Close DCA: ', { txid });
}

async function main() {
  const dcaPubKey = await createDCA();
  console.log('DCA Pub Key: ', { dcaPubKey });

  const dcaAccount = await dca.fetchDCA(dcaPubKey);
  console.log('DCA Account Data: ', { dcaAccount });

  const dcaAccounts = await dca.getCurrentByUser(user.publicKey);
  console.log({ dcaAccounts });

  await dca.getBalancesByAccount(dcaPubKey);

  await withdraw(dcaPubKey);

  await closeDCA(dcaPubKey);
}

main();

DCA CPI Integration
This section contains examples of composing Jupiter's DCA program in your program via Cross Program Invocation (CPI).

Our aim is to simplify the process for our partners to integrate Jupiter's DCA for customized incentive programs.

Use Cases
The use cas


[User] What is the format of the public key required in the getTokenAccountBalance method in Alchemy?

[Assistant]
The public key required in the `getTokenAccountBalance` method in Alchemy must be in a base-58 encoded string format. This is the format used for the Pubkey of the queried token account.

Here’s an example of how you would structure a request using this public key:

```json
{
    "method": "getTokenAccountBalance",
    "jsonrpc": "2.0",
    "params": [
        "3Lz6rCrXdLybFiuJGJnEjv6Z2XtCh5n4proPGP2aBkA1"  // Example of a base-58 encoded public key
    ],
    "id": "017a141e-9a15-4ce3-b039-865e7dc7da00"
}
```

Make sure to replace the example public key with the actual base-58 encoded public key of the token account you wish to query.

List": false
    }
  ]
}
'

Response

200
Response body
object
id
integer
jsonrpc
string
result
object
context
object

context object
value
object

value object

getTokenAccountBalance
post
https://{network}.g.alchemy.com/v2/{apiKey}
Returns the token balance of an SPL Token account..

Parameters
<base-58 encoded string> - Pubkey of queried token account
<object> - (optional) Config object:
commitment: <object> - (optional) Configures the commitment level of the blocks queried
Accepts one of the following strings: ["finalized", "confirmed", "processed"]
For more info, refer to this doc.
Results
amount: <u64 string> - the raw balance without decimals
decimals: <u8> - number of base 10 digits to the right of the decimal place
uiAmountString: <string> - the balance as a string, using mint-prescribed decimals
Example
Request
cURL

curl --location --request POST 'https://solana-mainnet.g.alchemy.com/v2/demo/' \
--header 'Content-Type: application/json' \
--data-raw '{
    "method": "getTokenAccountBalance",
    "jsonrpc": "2.0",
    "params": [
        "3Lz6rCrXdLybFiuJGJnEjv6Z2XtCh5n4proPGP2aBkA1"
    ],
    "id": "017a141e-9a15-4ce3-b039-865e7dc7da00"
}'
Response
JavaScript

{
    "jsonrpc": "2.0",
    "result": {
        "context": {
            "slot": 137567036
        },
        "value": {
            "amount": "301922375078",
            "decimals": 6,
            "uiAmount": 301922.375078,
            "uiAmountString": "301922.375078"
        }
    },
    "id": "017a141e-


[User] What is the significance of setting maxRetries to 0 in Solana transaction submissions?

[Assistant]
Setting `maxRetries` to 0 in Solana transaction submissions is significant because it allows developers to take control of the transaction resubmission process during times of network congestion. When `maxRetries` is set to 0, the application will not automatically retry the transaction after it fails. Instead, developers can implement a custom algorithm for resubmitting the transaction.

This approach can be beneficial in scenarios where the network is congested, as it allows for more tailored handling of transaction retries. For instance, some applications might choose to continuously resubmit transactions at a constant interval until a timeout occurs, rather than relying on the default retry mechanism which may not be optimal under high load conditions.

By managing the retry logic manually, developers can optimize for their specific use case, potentially improving the chances of successful transaction processing in a congested environment.

ly storing the lastValidBlockHeight that comes from getLatestBlockhash. Once stashed, an application can then poll the cluster's blockheight and manually retry the transaction at an appropriate interval. In times of network congestion, it's advantageous to set maxRetries to 0 and manually rebroadcast via a custom algorithm. While some applications may employ an exponential backoff algorithm, others such as Mango opt to continuously resubmit transactions at a constant interval until some timeout has occurred.

import {
  Keypair,
  Connection,
  LAMPORTS_PER_SOL,
  SystemProgram,
  Transaction,
} from "@solana/web3.js";
import * as nacl from "tweetnacl";

const sleep = async (ms: number) => {
  return new Promise(r => setTimeout(r, ms));
};

(async () => {
  const payer = Keypair.generate();
  const toAccount = Keypair.generate().publicKey;

  const connection = new Connection("http://127.0.0.1:8899", "confirmed");

  const airdropSignature = await connection.requestAirdrop(
    payer.publicKey,
    LAMPORTS_PER_SOL,
  );

  await connection.confirmTransaction({ signature: airdropSignature });

  const blockhashResponse = await connection.getLatestBlockhash();
  const lastValidBlockHeight = blockhashResponse.lastValidBlockHeight - 150;

  const transaction = new Transaction({
    feePayer: payer.publicKey,
    blockhash: blockhashResponse.blockhash,
    lastValidBlockHeight: lastValidBlockHeight,
  }).add(
    SystemProgram.transfer({
      fromPubkey: payer.publicKey,


[User] What does the response format of the CoinGecko API for the OHLC endpoint look like?

[Assistant]
The response format for the CoinGecko API's OHLC (Open, High, Low, Close) endpoint is structured as an array of arrays, where each inner array represents the OHLC data for a specific time period. Each inner array contains the following elements:

1. **Timestamp** (in milliseconds since UNIX epoch)
2. **Open price**
3. **High price**
4. **Low price**
5. **Close price**

Here’s an example of the response format:

```json
[
  [
    1709395200000,  // Timestamp
    61942,          // Open price
    62211,          // High price
    61721,          // Low price
    61845           // Close price
  ],
  [
    1709409600000,  // Timestamp
    61828,          // Open price
    62139,          // High price
    61726,          // Low price
    62139           // Close price
  ],
  [
    1709424000000,  // Timestamp
    62171,          // Open price
    62210,          // High price
    61821,          // Low price
    62068           // Close price
  ]
]
```

In this format, each array corresponds to a different time period, allowing users to analyze the historical price movements of a specific coin.

    --url 'https://pro-api.coingecko.com/api/v3/coins/id/ohlc?days=1' \
3
     --header 'accept: application/json'

Try It!
RESPONSE
1
[
2
  [
3
    1709395200000,
4
    61942,
5
    62211,
6
    61721,
7
    61845
8
  ],
9
  [
10
    1709409600000,
11
    61828,
12
    62139,
13
    61726,
14
    62139
15
  ],
16
  [
17
    1709424000000,
18
    62171,
19
    62210,
20
    61821,
21
    62068
22
  ]
23
]

Coin Historical Chart Data by ID
get
https://pro-api.coingecko.com/api/v3/coins/{id}/market_chart
This endpoint allows you to get the historical chart data of a coin including time in UNIX, price, market cap and 24hrs volume based on particular coin id.

👍
Tips

You may obtain the coin id (api id) via several ways:
refers to respective coin page and find ‘api id’
refers to /coins/list endpoint
refers to google sheets here
You may use tools like epoch converter to convert human readable date to UNIX timestamp
📘
Notes

You may leave the interval params as empty for automatic granularity:
1 day from current time = 5-minutely data
2 - 90 days from current time = hourly data
above 90 days from current time = daily data (00:00 UTC)
For non-Enterprise plan subscribers who would like to get hourly data, please leave the interval params empty for auto granularity
The 5-minutely and hourly interval params are also exclusively available to Enterprise plan subscribers, bypassing auto-granularity:
interval=5m: 5-minutely historical data (responses include information from the past 10 d


[User] What type of request does CoinGecko use to access the on-chain search pools API?

[Assistant]
To access the on-chain search pools API, CoinGecko uses a GET request. Here is an example of how to make this request using `curl`:

```bash
curl --request GET \
     --url https://pro-api.coingecko.com/api/v3/onchain/search/pools \
     --header 'accept: application/json'
```

This request retrieves data related to on-chain search pools from the CoinGecko API.


[User] How can I determine the price of a liquidity addition in USD using Bitquery?

[Assistant]
To determine the price of a liquidity addition in USD using Bitquery, you can utilize the GraphQL subscription for real-time liquidity addition events. Specifically, you would focus on the `Quote` field within the `DEXPools` subscription, which provides the price information in USD.

Here’s an example of how to structure your GraphQL subscription to get the necessary details:

```graphql
subscription {
  Solana {
    DEXPools(
      where: {
        Pool: {
          Dex: { ProtocolFamily: { is: "YourDesiredProtocol" } }
          Base: { ChangeAmount: { gt: "0" } }  # ChangeAmount > 0 indicates liquidity addition
        }
      }
    ) {
      Pool {
        Market {
          MarketAddress
          BaseCurrency {
            MintAddress
            Symbol
            Name
          }
          QuoteCurrency {
            MintAddress
            Symbol
            Name
          }
        }
        Dex {
          ProtocolFamily
          ProtocolName
        }
        Quote {
          PostAmount          # Amount of liquidity added
          PriceInUSD         # Price of the liquidity addition in USD
          PostAmountInUSD    # Total value of the added liquidity in USD
        }
        Base {
          ChangeAmount       # Change in liquidity amount
          PostAmount         # Amount after addition
        }
      }
    }
  }
}
```

In this subscription:
- Replace `"YourDesiredProtocol"` with the specific protocol you are interested in.
- The `Quote` field contains `PriceInUSD`, which gives you the price of the liquidity addition in USD.
- `PostAmountInUSD` provides the total value of the liquidity added in USD.

This subscription will allow you to receive real-time updates on liquidity additions, including their prices in USD.

Symbol
            Name
          }
        }
        Dex {
          ProtocolFamily
          ProtocolName
        }
        Quote {
          PostAmount
          PriceInUSD
          PostAmountInUSD
        }
        Base {
          ChangeAmount
          PostAmount
        }
      }
    }
  }
}

Liquidity removal for Meteora Pairs
This subscription returns the real-time liquidity addition event details for the Meteora Pairs.

subscription {
  Solana {
    DEXPools(
      where: {
        Pool: {
          Dex: { ProtocolFamily: { is: "Meteora" } }
          Base: { ChangeAmount: { lt: "0" } }
        }
      }
    ) {
      Pool {
        Market {
          MarketAddress
          BaseCurrency {
            MintAddress
            Symbol
            Name
          }
          QuoteCurrency {
            MintAddress
            Symbol
            Name
          }
        }
        Dex {
          ProtocolFamily
          ProtocolName
        }
        Quote {
          PostAmount
          PriceInUSD
          PostAmountInUSD
        }
        Base {
          ChangeAmount
          PostAmount
        }
      }
    }
  }
}

Solana Raydium API
In this section, we will see how to get Raydium information using Bitquery APIs.

This Solana API is part of our Early Access Program (EAP), which is intended for evaluation purposes.

This program allows you to test the data and its integration into your applications before full-scale implementation. Read more here

New Liquidity


[User] What does the 'effectiveSlot' field signify in the reward response from Solana?

[Assistant]
The 'effectiveSlot' field in the reward response from Solana signifies the slot in which the rewards are effective. This means that it indicates the specific slot at which the reward amount was credited to the account.

For example, in the response provided:

```json
{
  "amount": 2500,
  "effectiveSlot": 224,
  "epoch": 2,
  "postBalance": 499999442500
}
```

The 'effectiveSlot' value of 224 indicates that the reward of 2500 lamports became effective at slot 224.

g optional

epoch u64 optional

An epoch for which the reward occurs. If omitted, the previous epoch will be used

minContextSlot number optional

The minimum slot that the request can be evaluated at

Result #
The result field will be a JSON array with the following fields:

epoch: <u64> - epoch for which reward occurred
effectiveSlot: <u64> - the slot in which the rewards are effective
amount: <u64> - reward amount in lamports
postBalance: <u64> - post balance of the account in lamports
commission: <u8|undefined> - vote account commission when the reward was credited
Code sample #
curl https://api.devnet.solana.com -s -X POST -H "Content-Type: application/json" -d '
  {
    "jsonrpc": "2.0",
    "id": 1,
    "method": "getInflationReward",
    "params": [
      [
        "6dmNQ5jwLeLk5REvio1JcMshcbvkYMwy26sJ8pbkvStu",
        "BGsqMegLpV6n6Ve146sSX2dTjUMj3M92HnU8BbNRMhF2"
      ],
      {"epoch": 2}
    ]
  }
'

Response #
{
  "jsonrpc": "2.0",
  "result": [
    {
      "amount": 2500,
      "effectiveSlot": 224,
      "epoch": 2,
      "postBalance": 499999442500
    },
    null
  ],
  "id": 1
}

getLargestAccounts RPC Method
Edit Page
Returns the 20 largest accounts, by lamport balance (results may be cached up to two hours)

Parameters #
object optional

Configuration object containing the following fields:

commitment string optional

filter string optional

filter results by account type

Values: circulatingnonCirculating

Result #
The result will be an RpcResponse JSO


[User] How is the AUM for stablecoins calculated in Jupiter's JLP pool?

[Assistant]
In Jupiter's JLP pool, the Assets Under Management (AUM) for stablecoins, specifically USDC and USDT, is calculated using the following formula:

```
aum = owned * current_price
```

Here, `owned` refers to the amount of the stablecoin held, and `current_price` is the market price of that stablecoin at the time of calculation. This formula allows for the determination of the total value of the stablecoin assets in the pool.

 for JLP.
A module will appear at the bottom showing the estimated quantity of JLP and the fees for buying into the pool (More info on these fees in Maintaining Target Weight)
A notification asking for confirmation of the transaction will appear. Confirm the transaction.
You will receive a message on the success of the transaction.

LP Economics
The JLP Token
The JLP token is the token given to users who provide liquidity to the JLP pool. JLP can be acquired either through Jupiter Swap or through the Earn page, which mints or burns JLP tokens directly from the pool.

More information on how to get JLP here.

Custodies
The JLP pool manages several custodies (tokens) for liquidity providers:

SOL: 7xS2gz2bTp3fwCC7knJvUWTEU9Tycczu6VhJYKgi1wdz
ETH: AQCGyheWPLeo6Qp9WpYS9m3Qj479t7R636N9ey1rEjEn
BTC: 5Pv3gM9JrFFH883SWAhvJC9RPYmo8UNxuFtv5bMMALkm
USDC: G18jKKXQwBbrHeiK3C9MRXhkHsLHf7XgCSisykV46EZa
USDT: 4vkNeXiYEUizLdrpdPS1eC2mccyM4NUPRtERrk6ZETkk
More info on the Custody account is explained in Onchain Account Types.

Assets Under Management
The AUM for each Custody account in the pool is calculated as follows:

Stablecoins (USDC, USDT)
aum = owned * current_price

Non-stablecoins (SOL, ETH, wBTC)
Calculate the global short position profit/loss (Unrealized PnL in USD):
unrealized_pnl = (global_short_sizes * (|global_short_average_prices - current_price|)) / global_short_average_prices)

tip
If current_price > global_short_average_prices, traders are losing on short positions.

Net Ass


[User] How do stableSwapBps and stableSwapTaxBps affect the swap fees for stablecoins in Jupiter?

[Assistant]
In Jupiter, the swap fees for stablecoins are calculated using the following formula:

```
swap fee = stableSwapBps ± stableSwapTaxBps
```

Here's how each component affects the swap fees:

1. **stableSwapBps**: This is a fixed base fee that is applied to the swap of stablecoins. It represents the standard fee charged for the transaction.

2. **stableSwapTaxBps**: This is an additional tax fee that can either increase or decrease the total swap fee based on certain conditions. The specific value of stableSwapTaxBps will depend on factors defined in the system, such as the current and target weightage of the tokens involved in the swap.

Thus, the total swap fee for stablecoins will be the sum of the stableSwapBps and the stableSwapTaxBps, which can either add to or subtract from the base fee, depending on the circumstances. This structure allows for flexibility in the fee calculation based on market conditions or liquidity factors.

ap is hit.
tokenWeightageBufferBps: The token weightage buffer (in BPS) to calculate the token's maximum or minimum current weightage based on the target weightage. Currently, tokenWeightageBufferBps is set to 2000 which means the current weightage cannot be lower of higher than + / - 20% of the token's target weightage. For example, if SOL's target weightage for the JLP pool is 50%, the current weightage cannot be less than 40% or exceed 60%. The pool will not allow deposits or withdrawals if the action causes the token to exceed its target weightage.
maxPositionUsd: Sets the maximum position size for the Jupiter Perpetuals exchange. The current maxPositionUsd value is 2500000000000 which means a position's max size is $2,500,000.
fees: Sets the fee amounts or percentages for the Jupiter Perpetuals exchange.

increasePositionBps: A fixed fee of 6 BPS (0.06%) is charged for opening or increasing a position.
decreasePositionBps: A fixed fee of 6 BPS (0.06%) is charged for closing or decreasing a position.
addRemoveLiquidityBps: Fee charged when adding or removing liquidity to/from the pool.
swapBps: Swap fee for exchanging non-stablecoin tokens routed through the liquidity pool.
For stablecoins: swap fee = stableSwapBps ± stableSwapTaxBps
For non-stablecoins: swap fee = swapBps ± taxBps
taxBps: Tax fee for non-stablecoins, determined based on the difference between the current and target weightage. A larger difference results in a higher tax fee, encouraging liquidity provider


[User] What is the difference between linear and exponential pools in terms of calculating the number of NFTs buyable on Magic Eden?

[Assistant]
The difference between linear and exponential pools in calculating the number of NFTs buyable on Magic Eden lies in the formulas used for each type of pool.

### Linear Pools
For linear pools, the number of NFTs buyable (\( n \)) is calculated using the following formula:

\[
n = (2s + \Delta) - \sqrt{(2s + \Delta)^2 - 8\Delta d^2\Delta}
\]

Where:
- \( s \) is the current spot price.
- \( \Delta \) is the curve delta.
- \( d \) is the amount deposited.

If the deposited amount \( d \) is greater than or equal to the amount needed to fulfill \( s \Delta \) buys, then:

\[
n = d
\]

### Exponential Pools
For exponential pools, the calculation is different. We define:

\[
\gamma = \frac{1}{1 + \Delta}
\]

Then, the number of NFTs buyable (\( n \)) is calculated using the logarithmic function:

\[
n = \log_{\gamma}\left(d(\gamma - 1)s + 1\right)
\]

### Summary
- **Linear Pools** use a quadratic formula to determine the number of NFTs buyable based on the spot price and deposited amount, with a condition if the deposit exceeds the required amount.
- **Exponential Pools** utilize logarithmic calculations based on a derived value \( \gamma \) to determine the number of NFTs buyable.

These differences in calculation methods reflect the underlying mechanics of how each pool type operates within the Magic Eden platform.

Chart

For readability reasons, the red and blue lines do not extend past the 0, even though the pool can still buy NFTs after selling some. However, if the pool was to buy a token, we can simulate this by extending the lines to show what the effective buy/selling prices will be. After buying one token, the pool is willing to sell at approximately 1.5 SOL and buy at 1.15 SOL instead of the previous 1.94 SOL and 1.44 SOL.

Chart

Below is an example of a linear curve, with the same values as the exponential curve except for delta being 0.1 SOL

Chart

Buyable/Sellable Tokens
To find the number of NFTs to sell, it is just the number of NFTs that are deposited into the pool. The process to find the number of NFTs buyable is a little trickier, but the easiest way to do it is probably iteratively, as seen in the code snippet below.

To do it in a non-iterative fashion, we can use the arithmetic and geometric sequence functions to find that if n is the number of NFTs buyable given a spot price and curve delta, and d is the amount deposited, then

For linear pools:
n
=
(
2
s
+
Δ
)
-
(
2
s
+
Δ
)
2
-
8
Δ
d
2
Δ

This is assuming that the deposited amount d is less than the amount needed to fulfill
s
Δ
 buys. Otherwise, n = d

For exponential pools: we can define
γ
=
1
1

+

Δ
, then
n
=
l
o
g
γ
(
d
(
γ
-
1
)
s
+
1
)

Maker Fees
Most of the above discussion does not involve maker fees. Adding maker fees to the current iteration of MMM will change the behavior in two ways

Since