### Query Swap Route Endpoint (Anti-MEV Supported) - JavaScript Example Source: https://docs.gmgn.ai/index/cooperation-api-integrate-gmgn-solana-trading-api This snippet demonstrates how to construct a GET request URL to query the GMGN AI DeFi router for a swap route. It includes parameters for input and output tokens, amounts, wallet addresses, slippage, and anti-MEV support. The API key is required for authentication. ```javascript const inputToken = "So11111111111111111111111111111111111111112"; const outputToken = "7EYnhQoR9YM3N7UoaKRoA44Uy8JeaZV3qyouov87awMs"; const amount = "100000000"; // 0.1 SOL in lamports const fromAddress = "2kpJ5QRh16aRQ4oLZ5LnucHFDAZtEFz6omqWWMzDSNrx"; const slippage = 10; // 10% const isAntiMEV = true; const fee = 0.002; // Minimum fee for anti-MEV const apiUrl = `https://gmgn.ai/defi/router/v1/sol/tx/get_swap_route?token_in_address=${inputToken}&token_out_address=${outputToken}&in_amount=${amount}&from_address=${fromAddress}&slippage=${slippage}&is_anti_mev=${isAntiMEV}&fee=${fee}`; console.log(apiUrl); ``` -------------------------------- ### GET /api/v1/recommend_slippage/{chain_code}/{token_address} Source: https://docs.gmgn.ai/index/cooperation-api-integrate-gmgn-eth-base-bsc-trading-api/get-the-recommended-slippage-value-of-eth-base-bsc-token Get the recommended slippage value for a given token on a specific blockchain. ```APIDOC ## GET /api/v1/recommend_slippage/{chain_code}/{token_address} ### Description Retrieves the recommended slippage value for a specified token contract address on a given blockchain. This is useful for optimizing token swaps and avoiding issues related to accumulated slippage, especially when dealing with altcoins. ### Method GET ### Endpoint `/api/v1/recommend_slippage/{chain_code}/{token_address}` ### Parameters #### Path Parameters - **chain_code** (string) - Required - The code representing the blockchain (e.g., 'sol' for Solana, 'eth' for Ethereum, 'bsc' for Binance Smart Chain). - **token_address** (string) - Required - The contract address of the token for which to get the recommended slippage. #### Query Parameters - **token_in_address** (string) - Optional - The contract address of the input token. If provided, it helps in calculating slippage considering the swap between two altcoins. ### Request Example ``` GET https://gmgn.ai/api/v1/recommend_slippage/sol/9U1NKvb9bUTrqcdymkQ2kDkLxSVyCLUrAfVswcSZPUMP?token_in_address=0x0c48250eb1f29491f1efbeec0261eb556f0973c7 ``` ### Response #### Success Response (200) - **code** (integer) - Indicates success (0) or failure (-1). - **msg** (string) - An error message if the request failed, otherwise empty. - **data** (object) - Contains the slippage recommendation details: - **recommend_slippage** (string) - The recommended slippage value (e.g., "1" for 1%). - **display_slippage** (string) - The slippage value to be displayed to the user (e.g., "1"). - **has_tax** (boolean) - Indicates if the token has a tax. #### Response Example ```json { "msg": "", "code": 0, "data": { "recommend_slippage": "1", "display_slippage": "1", "has_tax": false } } ``` ``` -------------------------------- ### GET /swap/v1/sol/tx/get_swap_route Source: https://docs.gmgn.ai/index/cooperation-api-integrate-gmgn-solana-trading-api Queries for the optimal swap route for a given token swap on the Solana network. Supports Anti-MEV functionality via JITO. ```APIDOC ## GET /swap/v1/sol/tx/get_swap_route ### Description Queries for the optimal swap route for a given token swap on the Solana network. Supports Anti-MEV functionality via JITO. ### Method GET ### Endpoint `/swap/v1/sol/tx/get_swap_route` ### Parameters #### Query Parameters - **token_in_address** (string) - Required - The address of the token to spend, e.g., So11111111111111111111111111111111111111112 - **token_out_address** (string) - Required - The address of the target token, e.g., 7EYnhQoR9YM3N7UoaKRoA44Uy8JeaZV3qyouov87awMs - **in_amount** (string) - Required - Amount in lamports, 100000000=0.1SOL - **from_address** (string) - Required - The wallet address initiating the transaction, e.g., 2kpJ5QRh16aRQ4oLZ5LnucHFDAZtEFz6omqWWMzDSNrx - **slippage** (float) - Required - Slippage percentage, e.g., 10 for 10% - **swap_mode** (string) - Optional - ExactIn or ExactOut, default is ExactIn - **fee** (float) - Optional - Network priority fees and PRC node tip fees. For example, 0.006, unit SOL. If 'is_anti_mev' is 'true', 'fee' needs to be at least 0.002. - **is_anti_mev** (bool) - Optional - Set 'true' when swap with JITO Anti-MEV - **partner** (string) - Optional - Partner source name ### Request Example ``` GET https://gmgn.ai/defi/router/v1/sol/tx/get_swap_route?token_in_address=So11111111111111111111111111111111111111112&token_out_address=7EYnhQoR9YM3N7UoaKRoA44Uy8JeaZV3qyouov87awMs&in_amount=100000000&from_address=2kpJ5QRh16aRQ4oLZ5LnucHFDAZtEFz6omqWWMzDSNrx&slippage=10&is_anti_mev=true&fee=0.002 ``` ### Response #### Success Response (200) (Response structure not provided in the input text) #### Response Example (Response example not provided in the input text) ``` -------------------------------- ### Fetch Gas Price (Python) Source: https://docs.gmgn.ai/index/cooperation-api-integrate-gmgn-eth-base-bsc-trading-api/get-the-recommended-gas-price-for-eth-base-bsc-chain This Python snippet demonstrates how to fetch the recommended gas price for a specified network using the provided API endpoint. It utilizes the `requests` library to make a GET request and prints the relevant gas price data from the JSON response. ```python import requests def get_gas_price(network): url = f"https://api.example.com/defi/quotation/v1/chains/{network}/gas_price" try: response = requests.get(url) response.raise_for_status() # Raise an exception for bad status codes data = response.json() if data.get("code") == 0: return data.get("data") else: print(f"Error fetching gas price: {data.get('msg')}") return None except requests.exceptions.RequestException as e: print(f"An error occurred: {e}") return None # Example usage: eth_gas = get_gas_price("eth") if eth_gas: print("ETH Gas Price Data:", eth_gas) base_gas = get_gas_price("base") if base_gas: print("Base Gas Price Data:", base_gas) bsc_gas = get_gas_price("bsc") if bsc_gas: print("BSC Gas Price Data:", bsc_gas) ``` -------------------------------- ### Get Project Website Data Source: https://docs.gmgn.ai/index/cooperation-api-integrate-gmgn-eth-base-bsc-trading-api/swap-transaction-simulation-eth-base-bsc Retrieves project website data, including from_address and call wallet addresses for the gmgn_ai project. ```APIDOC ## GET /websites/gmgn_ai ### Description Retrieves project website data, including from_address and call wallet addresses for the gmgn_ai project. ### Method GET ### Endpoint /websites/gmgn_ai ### Parameters #### Query Parameters - **from_address** (string) - Optional - The sender's wallet address. - **call_wallet_address** (string) - Optional - The recipient's wallet address. ### Request Example ```json { "example": "" } ``` ### Response #### Success Response (200) - **from_address** (string) - The sender's wallet address. - **call_wallet_address** (string) - The recipient's wallet address. #### Response Example ```json { "from_address": "0x21A2c6c70Bbbe32A9C865a305C1c490E3F40Ad36", "call_wallet_address": "0x21A2c6c70Bbbe32A9C865a305C1c490E3F40Ad36" } ``` ``` -------------------------------- ### Fetch Gas Price (JavaScript) Source: https://docs.gmgn.ai/index/cooperation-api-integrate-gmgn-eth-base-bsc-trading-api/get-the-recommended-gas-price-for-eth-base-bsc-chain This JavaScript code snippet shows how to retrieve the recommended gas price for a given network using the API. It employs the `fetch` API to make an asynchronous GET request and processes the JSON response to extract and display gas price information. ```javascript async function getGasPrice(network) { const url = `https://api.example.com/defi/quotation/v1/chains/${network}/gas_price`; try { const response = await fetch(url); if (!response.ok) { throw new Error(`HTTP error! status: ${response.status}`); } const data = await response.json(); if (data.code === 0) { return data.data; } else { console.error(`Error fetching gas price: ${data.msg}`); return null; } } catch (error) { console.error('An error occurred:', error); return null; } } // Example usage: getGasPrice('eth').then(gasData => { if (gasData) { console.log('ETH Gas Price Data:', gasData); } }); getGasPrice('base').then(gasData => { if (gasData) { console.log('Base Gas Price Data:', gasData); } }); getGasPrice('bsc').then(gasData => { if (gasData) { console.log('BSC Gas Price Data:', gasData); } }); ``` -------------------------------- ### GET /websites/gmgn_ai Source: https://docs.gmgn.ai/index/cooperation-api-integrate-gmgn-eth-base-bsc-trading-api/get-the-available-routing-for-eth-base-bsc-transactions Retrieves basic information about a cross-chain transaction. This includes details such as source chain ID, contract address, currency amounts (in both quantity and USD value), token addresses, and a list of steps involved in the transaction. ```APIDOC ## GET /websites/gmgn_ai ### Description Retrieves the basic information of the cross-chain transaction, mainly including the following information: - Source chain ID: `chain_id` - Contract address: `to` - Source currency quantity: `amount_in` - Source currency USD value: `amount_in_usd` - Output currency quantity: `amount_out` - Get the value of USD currency: `amount_out_usd` - Purchase token address: `buy_token_address` - Selling token address: `sell_token_address` - After the step list: `steps` (Steps has three fields: `id`/`type`/`tool`) ### Method GET ### Endpoint /websites/gmgn_ai ### Parameters #### Query Parameters - **amountIn** (string) - Required - The amount of the input currency. - **amountOut** (string) - Required - The amount of the output currency. - **buyTokenAddress** (string) - Required - The address of the token being bought. - **sellTokenAddress** (string) - Required - The address of the token being sold. - **chainId** (string) - Required - The ID of the source chain. - **to** (string) - Required - The contract address for the transaction. ### Request Example ```json { "amountIn": "987855194221161593", "amountOut": "100000000000000000", "buyTokenAddress": "0x2C3Bc638031AAbB701EA5f30c522379dEE5c2B22", "sellTokenAddress": "0x481c4572e017e636177920D79db157c0Cf3A4697", "chainId": "1", "to": "0x2abbEAf73456b6c0b1a1E7e32Dbd63Bf4fafAC40" } ``` ### Response #### Success Response (200) - **routes** (array) - An array of route objects, each containing transaction details. - **chain_id** (integer) - The ID of the chain. - **to** (string) - The contract address. - **amount_in** (string) - The quantity of the input currency. - **amount_out** (string) - The quantity of the output currency. - **input_token_address** (string) - The address of the input token. - **output_token_address** (string) - The address of the output token. - **type** (string) - The type of route (e.g., "v3"). - **path** (array) - An array of token addresses representing the path. - **pool_address** (array) - An array of pool addresses. - **fee** (array) - An array of fees. - **steps** (array) - An array of steps involved in the route. - **id** (integer) - The step ID. - **type** (string) - The type of step (e.g., "swap"). - **tool** (string) - The tool used for the step (e.g., "uniswapv3"). - **token_in_usd_price** (number) - The USD price of the input token. - **amount_in_usd** (string) - The USD value of the input amount. - **token_out_usd_price** (number) - The USD price of the output token. - **amount_out_usd** (string) - The USD value of the output amount. - **value** (number) - The overall value of the route. #### Response Example ```json { "routes": [ { "chain_id": 1, "to": "0x2abbEAf73456b6c0b1a1E7e32Dbd63Bf4fafAC40", "amount_in": "987855194221161593", "amount_out": "100000000000000000", "input_token_address": "0x481c4572e017e636177920D79db157c0Cf3A4697", "output_token_address": "0x2C3Bc638031AAbB701EA5f30c522379dEE5c2B22", "type": "v3", "path": [ "0x481c4572e017e636177920D79db157c0Cf3A4697", "0xB4FBF271143F4FBf7B91A5ded31805e42b2208d6", "0x2C3Bc638031AAbB701EA5f30c522379dEE5c2B22" ], "pool_address": [ "0x717BFacEBD23A5505b061Cf15a9C0fB2Ac1CABE4", "0x20A741900D8b8Fcd10b4Af1822EE07622aF165C3" ], "fee": [ 3000, 3000 ], "steps": [ { "id": 1, "type": "swap", "tool": "uniswapv3" } ], "token_in_usd_price": 0, "amount_in_usd": "0", "token_out_usd_price": 0, "amount_out_usd": "0", "value": 0 } ] } ``` ``` -------------------------------- ### Solana Token Swap and Transaction Status Check Example (JavaScript) Source: https://docs.gmgn.ai/index/cooperation-api-integrate-gmgn-solana-trading-api This JavaScript code demonstrates how to perform a token swap on Solana using the GMGN AI API. It includes fetching a swap route, signing the transaction, submitting it, and then polling the transaction status endpoint until the transaction is confirmed or expired. Dependencies include @project-serum/anchor, @solana/web3.js, bs58, node-fetch, and a local sleep utility. ```javascript import { Wallet } from '@project-serum/anchor' import { Connection, Keypair, VersionedTransaction, LAMPORTS_PER_SOL } from '@solana/web3.js' import bs58 from 'bs58'; import fetch from 'node-fetch' import sleep from './util/sleep.js' const inputToken = 'So11111111111111111111111111111111111111112' const outputToken = '7EYnhQoR9YM3N7UoaKRoA44Uy8JeaZV3qyouov87awMs' const amount = '50000000' const fromAddress = '2kpJ5QRh16aRQ4oLZ5LnucHFDAZtEFz6omqWWMzDSNrx' const slippage = 0.5 // GMGN API domain const API_HOST = 'https://gmgn.ai' async function main() { // Wallet initialization, skip this step if using Phantom const wallet = new Wallet(Keypair.fromSecretKey(bs58.decode(process.env.PRIVATE_KEY || ''))) console.log(`wallet address: ${wallet.publicKey.toString()}`) // Get quote and unsigned transaction const quoteUrl = `${API_HOST}/defi/router/v1/sol/tx/get_swap_route?token_in_address=${inputToken}&token_out_address=${outputToken}&in_amount=${amount}&from_address=${fromAddress}&slippage=${slippage}` let route = await fetch(quoteUrl) route = await route.json() console.log(route) // Sign transaction const swapTransactionBuf = Buffer.from(route.data.raw_tx.swapTransaction, 'base64') const transaction = VersionedTransaction.deserialize(swapTransactionBuf) transaction.sign([wallet.payer]) const signedTx = Buffer.from(transaction.serialize()).toString('base64') console.log(signedTx) // Submit transaction let res = await fetch(`${API_HOST}/txproxy/v1/send_transaction`, { method: 'POST', headers: {'content-type': 'application/json'}, body: JSON.stringify( { "chain": "sol", "signedTx": signedTx } ) }) res = await res.json() console.log(res) // Check transaction status // If the transaction is successful, success returns true // If is does not go through,expired=true will be returned after 60 seconds while (true) { const hash = res.data.hash const lastValidBlockHeight = route.data.raw_tx.lastValidBlockHeight const statusUrl = `${API_HOST}/defi/router/v1/sol/tx/get_transaction_status?hash=${hash}&last_valid_height=${lastValidBlockHeight}` let status = await fetch(statusUrl) status = await status.json() console.log(status) if (status && (status.data.success === true || status.data.expired === true)) break await sleep(1000) } } main() ``` -------------------------------- ### Submit Signed Transaction to GMGN AI Proxy (JavaScript) Source: https://docs.gmgn.ai/index/cooperation-api-integrate-gmgn-solana-trading-api This snippet demonstrates how to decode a raw transaction, sign it with a local wallet, and then encode it for submission to the GMGN AI transaction proxy. It requires the 'Buffer' and 'VersionedTransaction' objects, and a wallet with a payer. ```javascript const swapTransactionBuf = Buffer.from(route.data.raw_tx.swapTransaction, 'base64') const transaction = VersionedTransaction.deserialize(swapTransactionBuf) transaction.sign([wallet.payer]) const signedTx = Buffer.from(transaction.serialize()).toString("base64") ```