Skip to main content

Prerequisites

Before running the script, ensure you have the following installed: Python:
  • Python 3.10
  • Web3 (pip install web3)
  • Requests (pip install requests)
TypeScript:
  • Node.js 18+
  • TypeScript (npm install -g typescript)
  • Web3 (npm install web3)
  • Axios (npm install axios)
JavaScript:
  • Node.js 18+
  • Web3 (npm install web3)
  • Axios (npm install axios)
Additionally, you need access to an Ethereum-compatible blockchain node, such as an Infura or Tenderly RPC endpoint.

How GlueX Router Works

The GlueX Router simplifies the token zapping process by:
  1. Fetching a price quote for zapping tokens into liquidity positions.
  2. Generating the appropriate calldata for the zap.
  3. Executing the transaction on-chain to zap tokens and receive LP tokens.

Script Overview

1. Setup and Configuration

The following script initializes the necessary configurations:
from web3 import Web3
import requests
import json
import os
import time

# Configuration
API_KEY = "your_api_key"
UNIQUE_PID = "your_unique_pid"
QUOTE_ENDPOINT = "https://router.gluex.xyz/v1/quote"
RPC_URL = "https://mainnet.gateway.co/your_rpc_url"
PRIVATE_KEY = "your_private_key"

# Token Information
TOKEN_IN = "0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE"  # Input token address
LP_TOKEN_OUT = "0x0d4a11d5EEaaC28EC3F61d100daF4d40471f1852"  # LP token address
INPUT_AMOUNT = 1000000000000000000  # Example: 1 token in Wei

# Initialize Web3
web3 = Web3(Web3.HTTPProvider(RPC_URL))
account = web3.eth.account.from_key(PRIVATE_KEY)
COMPUTATION_UNITS = 1000000
COMPUTATION_COST = web3.eth.gas_price

2. Fetching a Zap Quote

Before executing the zap, obtain a quote from the GlueX Router. This ensures that you get the best rate available:
def fetch_quote(body, headers):
    """Fetch a quote from the GlueX Router."""
    response = requests.post(QUOTE_ENDPOINT, json=body, headers=headers)
    return response.json()
This function sends a request to the GlueX Router to retrieve a quote for zapping tokens.

3. Executing the Zap Transaction

Once the quote is retrieved, execute the zap transaction by sending the appropriate calldata:
def execute_transaction(calldata, router_address, account, value=0):
    """Execute transaction on the GlueX Router."""
    txn = {
        "from": account.address,
        "to": Web3.to_checksum_address(router_address),
        "data": calldata,
        "gas": COMPUTATION_UNITS,
        "gasPrice": web3.eth.gas_price,
        "nonce": web3.eth.get_transaction_count(account.address),
        "value": value,
        "chainId": 1
    }
    signed_txn = web3.eth.account.sign_transaction(txn, account.key)
    txn_hash = web3.eth.send_raw_transaction(signed_txn.raw_transaction)
    print(f"Transaction Hash: {web3.to_hex(txn_hash)}")
    return txn_hash
This function constructs and signs the transaction, ensuring it is sent to the Ethereum blockchain for processing.

4. End-to-End Zap Execution

The main() function ties everything together by fetching a quote and executing the transaction:
def main():
    headers = {"x-api-key": API_KEY}
    body = {
        "chainID": "ethereum",  # Ethereum Mainnet
        "userAddress": account.address,
        "outputReceiver": account.address,
        "uniquePID": UNIQUE_PID,
        "inputToken": TOKEN_IN,
        "outputToken": LP_TOKEN_OUT,
        "inputAmount": INPUT_AMOUNT,
        "isPermit2": False
    }
    
    print("============================================================================")
    print("Fetching zap quote...")
    print(body)
    quote_data = fetch_quote(body, headers)
    
    if quote_data.get('statusCode') != 200:
        print("Error fetching quote:", quote_data)
        return
    
    print("Quote received successfully:")
    print(quote_data)
    
    router_address = quote_data["result"]["router"]
    calldata = quote_data["result"]["calldata"]
    
    print("Executing transaction...")
    execute_txn = execute_transaction(calldata, router_address, account, value=0)
    
    receipt = web3.eth.wait_for_transaction_receipt(execute_txn)
    print("Transaction confirmed. Receipt:")
    print(receipt)
    print("")

if __name__ == "__main__":
    main()

5. Complete Code Implementation

from web3 import Web3
import requests
import json
import os
import time

# Configuration
API_KEY = "your_api_key"
UNIQUE_PID = "your_unique_pid"
QUOTE_ENDPOINT = "https://router.gluex.xyz/v1/quote"
RPC_URL = "https://mainnet.gateway.co/your_rpc_url"
PRIVATE_KEY = "your_private_key"

# Token Information
TOKEN_IN = "0xA0b86a33E6441b8c4C8C1C1B9B9B9B9B9B9B9B9B"
LP_TOKEN_OUT = "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2"
INPUT_AMOUNT = 1000000000000000000

web3 = Web3(Web3.HTTPProvider(RPC_URL))
account = web3.eth.account.from_key(PRIVATE_KEY)
COMPUTATION_UNITS = 1000000
COMPUTATION_COST = web3.eth.gas_price

def fetch_quote(body, headers):
    response = requests.post(QUOTE_ENDPOINT, json=body, headers=headers)
    return response.json()

def execute_transaction(calldata, router_address, account, value=0):
    txn = {
        "from": account.address,
        "to": Web3.to_checksum_address(router_address),
        "data": calldata,
        "gas": COMPUTATION_UNITS,
        "gasPrice": web3.eth.gas_price,
        "nonce": web3.eth.get_transaction_count(account.address),
        "value": value,
        "chainId": 1
    }
    signed_txn = web3.eth.account.sign_transaction(txn, account.key)
    txn_hash = web3.eth.send_raw_transaction(signed_txn.raw_transaction)
    print(f"Transaction Hash: {web3.to_hex(txn_hash)}")
    return txn_hash

def main():
    headers = {"x-api-key": API_KEY}
    body = {
        "chainID": "ethereum",
        "userAddress": account.address,
        "outputReceiver": account.address,
        "uniquePID": UNIQUE_PID,
        "inputToken": TOKEN_IN,
        "outputToken": LP_TOKEN_OUT,
        "inputAmount": INPUT_AMOUNT,
        "isPermit2": False
    }
    print("============================================================================")
    print("Fetching zap quote...")
    print(body)
    quote_data = fetch_quote(body, headers)
    if quote_data.get('statusCode') != 200:
        print("Error fetching quote:", quote_data)
        return
    print("Quote received successfully:")
    print(quote_data)
    router_address = quote_data["result"]["router"]
    calldata = quote_data["result"]["calldata"]
    print("Executing transaction...")
    execute_txn = execute_transaction(calldata, router_address, account, value=0)
    receipt = web3.eth.wait_for_transaction_receipt(execute_txn)
    print("Transaction confirmed. Receipt:")
    print(receipt)
    print("")

if __name__ == "__main__":
    main()
import { Web3 } from 'web3';
import axios from 'axios';

const API_KEY = "your_api_key";
const UNIQUE_PID = "your_unique_pid";
const QUOTE_ENDPOINT = "https://router.gluex.xyz/v1/quote";
const RPC_URL = "https://mainnet.gateway.co/your_rpc_url";
const PRIVATE_KEY = "your_private_key";

const TOKEN_IN = "0xA0b86a33E6441b8c4C8C1C1B9B9B9B9B9B9B9B9B";
const LP_TOKEN_OUT = "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2";
const INPUT_AMOUNT = BigInt("1000000000000000000");

const web3 = new Web3(RPC_URL);
const account = web3.eth.accounts.privateKeyToAccount(PRIVATE_KEY);
const COMPUTATION_UNITS = 1000000;

const fetchQuote = async (body: any, headers: { [key: string]: string }) => {
    const response = await axios.post(QUOTE_ENDPOINT, body, { headers });
    return response.data;
};

const executeTransaction = async (
    calldata: string,
    routerAddress: string,
    account: any,
    value: bigint = BigInt(0)
) => {
    const txn = {
        from: account.address,
        to: web3.utils.toChecksumAddress(routerAddress),
        data: calldata,
        gas: COMPUTATION_UNITS,
        gasPrice: await web3.eth.getGasPrice(),
        nonce: await web3.eth.getTransactionCount(account.address),
        value: value,
        chainId: 1
    };
    const signedTxn = await account.signTransaction(txn);
    const receipt = await web3.eth.sendSignedTransaction(signedTxn.rawTransaction);
    const txHash = web3.utils.toHex(receipt.transactionHash);
    console.log(`Transaction Hash: ${txHash}`);
    return txHash;
};

const main = async () => {
    const headers = { "x-api-key": API_KEY };
    const body = {
        chainID: "ethereum",
        userAddress: account.address,
        outputReceiver: account.address,
        uniquePID: UNIQUE_PID,
        inputToken: TOKEN_IN,
        outputToken: LP_TOKEN_OUT,
        inputAmount: INPUT_AMOUNT,
        isPermit2: false
    };
    const requestBody = {
        ...body,
        inputAmount: body.inputAmount.toString()
    };
    console.log("============================================================================");
    console.log("Fetching zap quote...");
    console.log(requestBody);
    const quoteData = await fetchQuote(requestBody, headers);
    if (quoteData.statusCode !== 200) {
        console.log("Error fetching quote:", quoteData);
        return;
    }
    console.log("Quote received successfully:");
    console.log(quoteData);
    const routerAddress = quoteData.result.router;
    const calldata = quoteData.result.calldata;
    console.log("Executing transaction...");
    const executeTxn = await executeTransaction(calldata, routerAddress, account, BigInt(0));
    const receipt = await web3.eth.getTransactionReceipt(executeTxn);
    console.log("Transaction confirmed. Receipt:");
    console.log(receipt);
    console.log("");
};
main().catch(console.error);
import { Web3 } from 'web3';
import axios from 'axios';

const API_KEY = "your_api_key";
const UNIQUE_PID = "your_unique_pid";
const QUOTE_ENDPOINT = "https://router.gluex.xyz/v1/quote";
const RPC_URL = "https://mainnet.gateway.co/your_rpc_url";
const PRIVATE_KEY = "your_private_key";

const TOKEN_IN = "0xA0b86a33E6441b8c4C8C1C1B9B9B9B9B9B9B9B9B";
const LP_TOKEN_OUT = "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2";
const INPUT_AMOUNT = BigInt("1000000000000000000");

const web3 = new Web3(RPC_URL);
const account = web3.eth.accounts.privateKeyToAccount(PRIVATE_KEY);
const COMPUTATION_UNITS = 1000000;

const fetchQuote = async (body, headers) => {
    const response = await axios.post(QUOTE_ENDPOINT, body, { headers });
    return response.data;
};

const executeTransaction = async (
    calldata,
    routerAddress,
    account,
    value = BigInt(0)
) => {
    const txn = {
        from: account.address,
        to: web3.utils.toChecksumAddress(routerAddress),
        data: calldata,
        gas: COMPUTATION_UNITS,
        gasPrice: await web3.eth.getGasPrice(),
        nonce: await web3.eth.getTransactionCount(account.address),
        value: value,
        chainId: 1
    };
    const signedTxn = await account.signTransaction(txn);
    const receipt = await web3.eth.sendSignedTransaction(signedTxn.rawTransaction);
    const txHash = web3.utils.toHex(receipt.transactionHash);
    console.log(`Transaction Hash: ${txHash}`);
    return txHash;
};

const main = async () => {
    const headers = { "x-api-key": API_KEY };
    const body = {
        chainID: "ethereum",
        userAddress: account.address,
        outputReceiver: account.address,
        uniquePID: UNIQUE_PID,
        inputToken: TOKEN_IN,
        outputToken: LP_TOKEN_OUT,
        inputAmount: INPUT_AMOUNT,
        isPermit2: false
    };
    const requestBody = {
        ...body,
        inputAmount: body.inputAmount.toString()
    };
    console.log("============================================================================");
    console.log("Fetching zap quote...");
    console.log(requestBody);
    const quoteData = await fetchQuote(requestBody, headers);
    if (quoteData.statusCode !== 200) {
        console.log("Error fetching quote:", quoteData);
        return;
    }
    console.log("Quote received successfully:");
    console.log(quoteData);
    const routerAddress = quoteData.result.router;
    const calldata = quoteData.result.calldata;
    console.log("Executing transaction...");
    const executeTxn = await executeTransaction(calldata, routerAddress, account, BigInt(0));
    const receipt = await web3.eth.getTransactionReceipt(executeTxn);
    console.log("Transaction confirmed. Receipt:");
    console.log(receipt);
    console.log("");
};
main().catch(console.error);

6. Running the Script

To execute the zap, run the script as follows:
python zap_token.py