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 wrapping process by:
  1. Fetching a price quote for wrapping native tokens.
  2. Generating the appropriate calldata for the wrap.
  3. Executing the transaction on-chain to wrap the native token into its wrapped form (e.g., ETH to WETH).

Script Overview

1. Setup and Configuration

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
NATIVE_TOKEN_ADDRESS = "0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE"  # Represents native ETH
TOKEN_IN = NATIVE_TOKEN_ADDRESS
TOKEN_OUT = "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2"  # WETH Contract Address
INPUT_AMOUNT = 1000000000000000000  # Example: 1 ETH 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 Wrap Quote

def fetch_quote(body, headers):
    """Fetch a quote from the GlueX Router."""
    response = requests.post(QUOTE_ENDPOINT, json=body, headers=headers)
    return response.json()

3. Executing the Wrap Transaction

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

4. End-to-End Wrap Execution

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": TOKEN_OUT,
        "inputAmount": INPUT_AMOUNT,
        "isPermit2": False
    }
    
    print("============================================================================")
    print("Fetching wrap 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=INPUT_AMOUNT)
    
    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
NATIVE_TOKEN_ADDRESS = "0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE"
TOKEN_IN = NATIVE_TOKEN_ADDRESS
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": TOKEN_OUT,
        "inputAmount": INPUT_AMOUNT,
        "isPermit2": False
    }
    print("============================================================================")
    print("Fetching wrap 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=INPUT_AMOUNT)
    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 NATIVE_TOKEN_ADDRESS = "0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE";
const TOKEN_IN = NATIVE_TOKEN_ADDRESS;
const 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: TOKEN_OUT,
        inputAmount: INPUT_AMOUNT,
        isPermit2: false
    };
    const requestBody = {
        ...body,
        inputAmount: body.inputAmount.toString()
    };
    console.log("============================================================================");
    console.log("Fetching wrap 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, INPUT_AMOUNT);
    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 NATIVE_TOKEN_ADDRESS = "0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE";
const TOKEN_IN = NATIVE_TOKEN_ADDRESS;
const 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: TOKEN_OUT,
        inputAmount: INPUT_AMOUNT,
        isPermit2: false
    };
    const requestBody = {
        ...body,
        inputAmount: body.inputAmount.toString()
    };
    console.log("============================================================================");
    console.log("Fetching wrap 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, INPUT_AMOUNT);
    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 wrap, run the script as follows:
python wrap_token.py