# Overview
Source: https://docs.gluex.xyz/api-reference/about/overview
Learn about the fundamentals of GlueX APIs and its capabilities
The GlueX API provides developers and partners to securely access the comprehensive set of tools to interact with DeFi and execute complex transactions across multiple EVM networks
Perform efficient and secure interactions like swaps, bridging, lending,
staking, yield farming, zaps and swidges
Fetch real time onchain exchange rates for any token pair
Analyzes and calculates APY and TVL across different DeFi protocols and
liquidity pools
# Authentication, Limits and Errors
Source: https://docs.gluex.xyz/api-reference/exchange-rate-api/authentication-limits-and-errors
# Token Price
Source: https://docs.gluex.xyz/api-reference/exchange-rate-api/post-price
https://raw.githubusercontent.com/gluexprotocol/gluex-openapis/main/exchange-rates-api/openapi.json post /
# Authentication, Limits and Errors
Source: https://docs.gluex.xyz/api-reference/router-api/authentication-limits-and-errors
The GlueX Router API provides secure, scalable access to decentralized exchange routing and trading functionality. This comprehensive guide covers authentication requirements, rate limiting policies, and error handling mechanisms to ensure successful integration with your applications
***
## API Authentication
All GlueX Router API requests require proper authentication using an API key and integrator ID. This dual-authentication approach ensures secure access, enables comprehensive usage tracking, and applies appropriate rate limits based on your access tier
### Getting your API credentials
* Navigate to the [GlueX Portal](https://portal.gluex.xyz/) and complete the registration process by creating your account
* Navigate to the "API Key" section and click "Generate Key" to generate a new API key
* In the same dashboard, locate your unique integrator ID
For a detailed walkthrough of the complete registration process, refer to the
[Get a GlueX API key –
Portal](/documentation/integrating-gluex/getting-an-api-key) guide
### Using the Credentials
**Authentication Headers**
Every API request must include your API key in the request headers:
```http
x-api-key:
```
**Request Body**
Include your integrator ID as the `uniquePID` parameter in the body of each API request:
```json
"uniquePID": ""
```
**Example Request**
```http
POST /v1/price
Host: https://router.gluex.xyz
x-api-key: your-api-key
Content-Type: application/json
```
```json
{
"chainID": "ethereum",
"inputToken": "0x...",
"outputToken": "0x...",
"inputAmount": "100000000",
"userAddress": "0x...",
"outputReceiver": "0x...",
"uniquePID": "your-integrator-id"
}
```
***
## Rate Limits and Access Tiers
GlueX provides tiered API access levels to accommodate diverse integration requirements, from initial prototyping and testing to high frequency, large scale production deployments. These tiers ensure fair resource allocation and optimal service performance for all partners
### Access Tiers Overview
To ensure the stability, reliability and equitable access of the Router API for all users, we implement a system of rate limits organized into distinct access tiers. These limits protect our infrastructure from abuse, manage system load efficiently and guarantee a high quality experience even during peak demand. Each access tier offers a specific API request rate, burst capacity and a corresponding level of support, tailored to different development and production needs
| Tier | Requests Per Second (RPS) | Burst Capacity | Use Case |
| :------------- | :------------------------ | :------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------ |
| **Basic** | 3 | 3 | Ideal for initial development, proof of concept projects, testing and small scale application with infrequent API calls |
| **Growth** | 10 | 30 | Suitable for mid sized production application, services and applications with moderate user traffic |
| **Premium** | 20 | 50 | Designed for large scale production applications, real time trading interfaces and platforms requiring consistent high throughput |
| **Enterprise** | Custom | Custom | Tailored solutions for high volume exchanges, large scale aggregators, institutional trading desks and partners with unique infrastructure requirements |
### Understanding RPS and Burst Capacity
* **Requests Per Second (RPS):** This is the **sustained rate** at which your application can make API calls over a longer period. For example, a tier with 3 RPS can make, on average, 3 requests every second
* **Burst Capacity:** This represents the **maximum number of requests** your application can send in a very short spike *above* its sustained RPS limit before hitting a rate limit error. It acts as a buffer to absorb sudden, short term surges in traffic. Once the burst capacity is depleted, requests will be throttled back to the sustained RPS rate until the bucket refills
### Upgrading your Tier
As your application scales and your API usage grows, GlueX offers seamless tier upgrades to meet your evolving demands. Higher tiers unlock significant advantages, including increased API throughput, enhanced reliability guarantees and dedicated support
Partners interested in upgrading their access tier are encouraged to reach out
directly to the **GlueX team** via our [official Telegram
channel](https://t.me/+_VmO_gIrNjxiZWE0). During this process, we will discuss
your specific needs, projected API usage and provide tailored solutions
⚠️ **Important Note on Endpoint Usage**
To maintain platform stability and ensure optimal performance for all users, GlueX enforces **stricter rate limits on high computation endpoints**, specifically `/v1/quote`. The `/v1/quote` endpoint performs intensive onchain simulations, which are
resource heavy
Conversely, the `/v1/price` endpoint is designed to be lightweight and highly performant for frequent polling. It provides rapid price estimates without deep onchain simulation
**Best Practice:**
* **`/v1/price`** should be the **primary endpoint used in your application**
for displaying real time indicative prices and general market information
* **`/v1/quote`** should be called **only when a user is ready to execute a
swap** and requires precise, executable transaction data.
Adhering to this practice will help you stay within your rate limits and ensure a smooth user experience
### Benefits of Higher Tiers
* **Increased Rate Limits:** Access significantly higher RPS and burst capacities to support larger user bases and more demanding applications
* **Service Level Agreements (SLAs):** Enterprise and Premium tiers often come with formal SLAs, guaranteeing specific uptime, performance metrics and response times for critical issues
* **Priority Support:** Receive expedited assistance from our technical team, ensuring your queries and issues are addressed promptly
* **Custom Integration Guidance:** Benefit from dedicated technical consultations and integration support to optimize your application's performance and integrate the features effectively
* **Custom Pricing and Billing:** For Enterprise partners, flexible pricing models can be arranged to align with your business operations
We are committed to providing a reliable and scalable API experience. If you anticipate exceeding your current tier's limits or have any questions regarding your access tier, please [contact us](https://t.me/+_VmO_gIrNjxiZWE0) for further assistance
### Whitelist Domains
GlueX provides an optional security feature that allows you to restrict API key usage to specific domains. This is particularly valuable for frontend integrations and helps prevent unauthorized usage of your credentials
**Configure**
* Navigate to the **"Keys"** page in the GlueX Portal
* Choose the API key you want to configure
* Add the domains you want to whitelist (eg: `gluex.xyz`)
* Apply the whitelist settings
Requests originating from unlisted domains will be rejected, helping you prevent unauthorized use of your key, so ensure all legitimate domains are included in your whitelist
For assistance or issues related to authentication, contact the GlueX team via the [Telegram support channel](https://t.me/+_VmO_gIrNjxiZWE0)
***
## Error Codes
The Router API performs various validations and simulations to ensure that transactions are safe and executable before returning calldata. If a request fails validation or simulation, the API responds with a standardized error format
### Error Format
All API errors follow a consistent JSON structure for predictable error handling:
```json
{
"statusCode": ,
"error": ""
}
```
### Error Reference
#### Authorization Errors
**Missing API Key**
```json
{
"statusCode": 401,
"error": "Forbidden"
}
```
* **Cause:** API key not provided in request headers
* **Resolution:** Ensure `x-api-key` header is included with valid API key
* **Common Scenarios:** Missing header, empty header value
#### Domain Not Whitelisted
```json
{
"statusCode": 403,
"error": "Request origin not in whitelist"
}
```
* **Cause:** Request originates from a domain not in your whitelist
* **Resolution:** Add the requesting domain to your whitelist in the portal
* **Common Scenarios:** New domain deployment, subdomain access, local development
#### Rate Limiting Errors
```json
{
"statusCode": 429,
"error": "Rate limit exceeded. Please try again later"
}
```
* **Cause:** Request rate exceeds your tier's RPS or burst capacity limits
* **Resolution:** Implement proper rate limiting in your application or upgrade your tier
* **Prevention Strategies:**
* Implement exponential backoff retry logic
* Monitor your request patterns
* Consider tier upgrade for higher limits
* Use `/v1/price` for frequent polling instead of `/v1/quote`
#### Simulation Failure
If the transaction fails during pre-trade simulation (to prevent onchain reverts), the API will return:
```json
{
"statusCode": 400,
"error": "Unable to fetch a solution for the user request"
}
```
* **Cause:** The router was unable to find a valid routing path or execution strategy that would succeed based on the current market conditions, balances or configuration
* **Common Reasons:**
* Insufficient liquidity for the requested trade
* Token pair not supported on specified network
* Amount exceeds available liquidity
* Network congestion or temporary routing issues
* **Resolution Strategies:**
* Reduce trade amount
* Try different token pairs
* Check network status
* Retry after a brief delay
#### Validation Error
If the request contains any invalid parameter that is unrecognized or unsupported, the API will return:
```json
{
"statusCode": 400,
"error": "Invalid provided"
}
```
* **Cause:** Request contains unrecognized, unsupported, or malformed parameters
* **Resolution:** Validate all parameters against API specification
* **Common Issues:**
* Invalid token addresses
* Unsupported chain IDs
* Malformed amounts or addresses
* Missing required parameters
# Liquidity Modules
Source: https://docs.gluex.xyz/api-reference/router-api/get-liquidity
https://raw.githubusercontent.com/gluexprotocol/gluex-openapis/main/router-api/openapi.json get /liquidity
List of all the liquidity modules by chain supported by GlueX
# Price (without calldata)
Source: https://docs.gluex.xyz/api-reference/router-api/post-price
https://raw.githubusercontent.com/gluexprotocol/gluex-openapis/main/router-api/openapi.json post /v1/price
# Quote (with calldata)
Source: https://docs.gluex.xyz/api-reference/router-api/post-quote
https://raw.githubusercontent.com/gluexprotocol/gluex-openapis/main/router-api/openapi.json post /v1/quote
# Authentication, Limits and Errors
Source: https://docs.gluex.xyz/api-reference/yield-api/authentication-limits-and-errors
Documentation for the Yield API's open authentication model, system resource limits, comprehensive error handling with detailed error types and steps, and monitoring capabilities
## API Authentication
The APY Calculator API currently operates as an **open API** without authentication requirements. This design choice prioritizes accessibility and ease of integration for developers while maintaining service reliability through other protective mechanisms
### CORS Policy
The API implements comprehensive Cross-Origin Resource Sharing (CORS) settings to maximize compatibility across different client environments:
```python
allow_origins=["*"] # Accepts requests from any domain
allow_credentials=True # Supports cookies and authentication headers
allow_methods=["GET", "POST"] # Supports primary HTTP methods
allow_headers=["*"] # Accepts any request headers
```
This configuration allows requests from any origin, making it suitable for frontend integrations and testing
**Security Considerations:**
* While permissive, the API relies on input validation and rate limiting for protection
* No sensitive authentication data is exposed due to the open access model
* All requests are logged with unique identifiers for monitoring
### Request Identification
While authentication is not required, each request receives a unique identifier for tracking and debugging purposes:
```http
X-Request-ID: uuid4-generated-string
```
This header is automatically added to all responses and can be used for support inquiries
***
## Rate Limits and Usage Constraints
The API implements intelligent constraints designed to balance performance, reliability, and fair resource allocation across all users
### Input Amount Validation
**Diluted APY Calculations:**
* **Constraint**: Input amounts must be non-negative integers (≥ 0)
* **Rationale**: Negative amounts would produce meaningless yield calculations
* **Validation**: Performed at the endpoint level before processing
* **Error Response**: Returns `422` status with `validation_error` type
**Example Valid Inputs:**
```json
{
"input_amount": 1000, // ✅ Valid
"input_amount": 0, // ✅ Valid (edge case)
"input_amount": 1000000000 // ✅ Valid (large amounts supported)
}
```
**Invalid Examples:**
```json
{
"input_amount": -100, // ❌ Negative value
"input_amount": 1000.5, // ❌ Decimal value
"input_amount": "1000" // ❌ String format
}
```
### Batch Processing Limits
**Maximum Multicall Size**: 30 calls per batch request
**Technical Reasoning:**
* **Timeout Prevention**: Larger batches risk exceeding response time limits
* **Memory Management**: Prevents excessive memory allocation per request
* **Fair Resource Distribution**: Ensures no single request monopolizes system resources
**Optimal Batch Strategies:**
* Group related calculations (same protocol/chain) for better caching efficiency
* Split large datasets into multiple sequential batch requests
* Implement client side batching logic for datasets exceeding 30 items
### Blockchain Support
The API provides comprehensive coverage across major EVM-compatible networks, with standardized naming conventions and aliases for developer convenience
* Ethereum (`ethereum`)
* Base (`base`)
* Arbitrum (`arbitrum`)
* BNB Chain (`bnb`, `binance smart chain`, `bsc`)
* Avalanche (`avalanche`)
* Gnosis (`gnosis`)
* Polygon (`polygon`)
* Optimism (`optimism`)
* Mantle (`mantle`)
* Linea (`linea`)
* Scroll (`scroll`)
* Taiko (`taiko`)
* Blast (`blast`)
* Sonic (`sonic`)
* Berachain (`berachain`)
* Unichain (`unichain`)
* HyperEVM (`hyperevm`)
### Timeout Configurations
The API implements environment-aware timeout settings optimized for different deployment contexts
| Operation Type | Production Timeout | Local Timeout |
| ---------------- | ------------------ | ------------- |
| Liquidity States | 1s | 20s |
| Dependent States | 1s | 20s |
**Timeout Strategy:**
* **Production**: Aggressive timeouts ensure responsive user experience
* **Development**: Extended timeouts accommodate debugging and testing
* **Automatic Failover**: Requests failing due to timeouts trigger retry mechanisms where applicable
### Cache Configuration
The API employs multi-tiered caching for optimal performance and resource utilization
* **Cache Size**: 10,000 entries maximum
* **Cache TTL**: 300 seconds (5 minutes)
* **APY Cache**: 3,600 seconds (1 hour)
### System Resource Limits
The API implements dynamic resource monitoring with automatic request rejection when system constraints are exceeded
* **CPU Usage**: Above 95%
* **Memory Usage**: Above 95%
* **Error Rate**: Above 75% (when total requests > 10)
***
## Error Handling
The API provides comprehensive error handling with structured responses designed for both human debugging and programmatic error recovery
### Error Format
All API errors follow a consistent, machine-readable JSON structure that provides multiple levels of diagnostic information:
```json
{
"success": false,
"error": "Error message description",
"error_type": "error_category",
"step": "operation_step",
"request_id": "uuid4-request-identifier"
}
```
**Field Descriptions:**
* **success**: Always `false` for error responses (enables quick programmatic checks)
* **error**: Human readable message suitable for logging and debugging
* **error\_type**: Standardized category for programmatic error handling
* **step**: Specific operation stage where failure occurred
* **request\_id**: Unique identifier for support and debugging correlation
### Error Types
#### Validation Errors
**HTTP Status Code: 422 Unprocessable Entity**
**Error Type: `validation_error`**
These errors occur during input parameter validation before any processing begins. They indicate client-side issues that require request modification
```json
{
"success": false,
"error": "pool_address must be a valid Ethereum address (0x...)",
"error_type": "validation_error",
"step": "input_validation"
}
```
**Common validation errors**
* Invalid Ethereum addresses (must be 42 characters with 0x prefix)
* Unsupported blockchain networks
* Missing required parameters (`pool_address` or `lp_token_address`)
* Invalid input amounts (negative values)
* Input token same as LP token
#### Calculation Errors
**HTTP Status Code: 404 Not Found**
**Error Type: `calculation_failed`**
These errors occur when the API successfully validates inputs but cannot complete the requested calculation due to missing data or computational issues
```json
{
"success": false,
"error": "Pool data not found for pool_address=0x... in chain ethereum",
"error_type": "calculation_failed",
"step": "pool_data_retrieval"
}
```
Common calculation errors:
* Pool not found in database
* Incomplete pool states
* Missing protocol modules
* Network timeout during state calls
#### Internal Server Errors
**HTTP Status Code: 500 Internal Server Error**
**Error Type: `internal_error`**
System level errors:
```json
{
"success": false,
"error": "Database connectivity failed",
"error_type": "internal_error",
"request_id": "abc123-def456-ghi789"
}
```
#### Service Unavailable
**HTTP Status Code: 503 Service Unavailable**
**Error Type: `startup_error` or `resource_exhaustion`**
Service initialization failures:
```json
{
"success": false,
"error": "Service initialization failed",
"error_type": "startup_error"
}
```
#### Database Errors
Database connectivity issues are handled gracefully:
```json
{
"success": false,
"error": "Database error during pool_address lookup: Connection timeout",
"error_type": "calculation_failed",
"step": "pool_data_retrieval"
}
```
#### Network and Timeout Errors
Blockchain network calls may timeout:
```json
{
"success": false,
"error": "Timeout during state calls",
"error_type": "calculation_failed",
"step": "state_calls_timeout"
}
```
### Error Step Mapping
#### Common Steps
* `input_validation`: Parameter validation failed
* `pool_data_retrieval`: Cannot fetch pool data from database
* `protocol_id_validation`: Missing or invalid protocol identifier
* `module_import_failed`: Cannot load required blockchain modules
* `initialization_failed`: Pool initialization error
#### APY Calculation Steps
* `input_token_validation`: Invalid input token address
* `lp_token_validation`: Input token conflicts with LP token
* `apy_calculation_error`: Mathematical calculation failed
* `states_incomplete`: Required blockchain states not available
#### TVL Calculation Steps
* `tvl_calculation_error`: TVL computation failed
* `pool_creation_failed`: Cannot instantiate pool object
***
## Health Monitoring
The API provides comprehensive health monitoring capabilities designed for both operational oversight and integration into larger monitoring ecosystems
### Health Check Endpoint
**Endpoint**: `GET /health-check`
**Purpose**: Comprehensive system validation suitable for load balancer health checks and monitoring systems
* Router initialization status
* Database connectivity
* Error rate analysis (must be \< 75%)
* System resource usage (CPU and memory \< 95%)
### Metrics Monitoring
**Endpoint**: `GET /metrics`
**Purpose**: Detailed performance and operational metrics for observability and optimization
**Response Format:**
```json
{
"success": true,
"request_metrics": {
"total_requests": 1000,
"cache_hit_rate_percent": 85.5,
"error_rate_percent": 2.1,
"avg_response_time_seconds": 0.245
},
"system_metrics": {
"cpu_usage_percent": 45.2,
"memory_usage_percent": 68.1,
"pending_tasks": 3,
"cache_size": 150,
"uptime_seconds": 86400
}
}
```
***
## Best Practices
### Error Handling in Client Applications
1. **Always check the `success` field** before processing response data
2. **Use `error_type` for programmatic error handling** rather than parsing error messages
3. **Include `request_id` in support requests** for faster debugging
4. **Implement retry logic** for timeout and network errors
5. **Cache successful responses** to reduce API load
### Request Optimization
1. **Use caching**: Identical requests within 5 minutes return cached results
2. **Validate addresses client-side**: Ensure Ethereum addresses are properly formatted
3. **Handle both lookup methods**: Support both `pool_address` and `lp_token_address` parameters
4. **Specify input tokens**: Avoid auto-selection overhead when possible
### Error Recovery
For transient errors (timeouts, network issues):
* Use different endpoints if available (`pool_address` vs `lp_token_address`)
For permanent errors (validation, not found):
* Validate input data
* Check supported chains and protocols via `/active-protocols`
# Active Protocols
Source: https://docs.gluex.xyz/api-reference/yield-api/get-protocols
https://raw.githubusercontent.com/gluexprotocol/gluex-openapis/refs/heads/main/yield-router-api/openapi.json get /active-protocols
Fetches a list of supported blockchain networks and their associated active lending protocols.
# Diluted APY
Source: https://docs.gluex.xyz/api-reference/yield-api/post-diluted-apy
https://raw.githubusercontent.com/gluexprotocol/gluex-openapis/refs/heads/main/yield-router-api/openapi.json post /diluted-apy
Calculate the diluted Annual Percentage Yield (APY) for a lending pool considering the impact of a specific amount.
# Historical APY
Source: https://docs.gluex.xyz/api-reference/yield-api/post-historical-apy
https://raw.githubusercontent.com/gluexprotocol/gluex-openapis/refs/heads/main/yield-router-api/openapi.json post /historical-apy
Calculate the historical Annual Percentage Yield (APY) for a lending pool without considering liquidity impact.
# Total Value Locked
Source: https://docs.gluex.xyz/api-reference/yield-api/post-tvl
https://raw.githubusercontent.com/gluexprotocol/gluex-openapis/refs/heads/main/yield-router-api/openapi.json post /tvl
Calculate the Total Value Locked (TVL) in USD for a lending pool.
# System Overview
Source: https://docs.gluex.xyz/architecture/overview
(COMING SOON)
# API Endpoints
Source: https://docs.gluex.xyz/build-with-gluex/exchange-rate/api-endpoints
This section outlines the primary endpoints provided by the GlueX Exchange Rates API for fetching real-time on-chain token prices and metadata across multiple blockchains.
The GlueX Exchange Rates API offers a streamlined interface to access accurate, rea -time market data directly from decentralized sources. This section details the core endpoints you'll utilize to query token prices, retrieve lists of supported blockchains and fetch comprehensive token metadata
> The `POST /` endpoint is your primary tool for fetching **real time exchange rates** for specific token pairs, supporting batch requests for efficiency
## POST `/`
Returns real time **exchange rates** for one or more token pairs across specified blockchains. This is the primary endpoint for fetching price data
**Description**
* Provides the current exchange rate (`price`) for requested token pairs
* Supports batch requests, allowing you to query up to 25 pairs in a single API call for optimized performance
* Requires `domestic_blockchain`, `domestic_token`, `foreign_blockchain` and `foreign_token` for each pair
**Example Request**
```http
POST /
x-api-key: your-optional-api-key
Content-Type: application/json
```
**Request Body (Example)**
```json
[
{
"domestic_blockchain": "ethereum",
"domestic_token": "0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48",
"foreign_blockchain": "ethereum",
"foreign_token": "0xdac17f958d2ee523a2206206994597c13d831ec7"
},
{
"domestic_blockchain": "polygon",
"domestic_token": "0x2791bca1f2de4661ed88a30c99a7a9229f6476ed",
"foreign_blockchain": "polygon",
"foreign_token": "0x7ceb23fd6bc0add59e62ac25578270cff1b9f619"
}
]
```
**Response**
```json
[
{
"domestic_blockchain": "ethereum",
"domestic_token": "0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48",
"foreign_blockchain": "ethereum",
"foreign_token": "0xdac17f958d2ee523a2206206994597c13d831ec7",
"price": 0.99987654
},
{
"domestic_blockchain": "polygon",
"domestic_token": "0x2791bca1f2de4661ed88a30c99a7a9229f6476ed",
"foreign_blockchain": "polygon",
"foreign_token": "0x7ceb23fd6bc0add59e62ac25578270cff1b9f619",
"price": 0.00032109
}
]
```
**Error Responses**
* 400 Bad Request: Invalid request payload (eg: missing required fields, malformed JSON)
* 500 Server Error: An unexpected error occurred on the server
# Rate Limits and Access Tiers
Source: https://docs.gluex.xyz/build-with-gluex/exchange-rate/api-tiers-limits
GlueX provides tiered API access levels to accommodate diverse integration requirements, from initial prototyping and testing to high frequency, large scale production deployments. These tiers ensure fair resource allocation and optimal service performance for all partners
## Rate Limits and Access Tiers
To ensure the stability, reliability and equitable access of the APIs for all users, we implement a system of rate limits organized into distinct access tiers. These limits protect our infrastructure from abuse, manage system load efficiently and guarantee a high quality experience even during peak demand. Each access tier offers a specific API request rate, burst capacity and a corresponding level of support, tailored to different development and production needs
### Access Tiers Overview
...
### Understanding RPS and Burst Capacity
* **Requests Per Second (RPS):** This is the **sustained rate** at which your application can make API calls over a longer period. For example, a tier with 3 RPS can make, on average, 3 requests every second
* **Burst Capacity:** This represents the **maximum number of requests** your application can send in a very short spike *above* its sustained RPS limit before hitting a rate limit error. It acts as a buffer to absorb sudden, short term surges in traffic. Once the burst capacity is depleted, requests will be throttled back to the sustained RPS rate until the bucket refills
## How to Upgrade Your Tier
As your application scales and your API usage grows, GlueX offers seamless tier upgrades to meet your evolving demands. Higher tiers unlock significant advantages, including increased API throughput, enhanced reliability guarantees and dedicated support
Partners interested in upgrading their access tier are encouraged to reach out directly to the **GlueX team** via our [official Telegram channel](https://t.me/+_VmO_gIrNjxiZWE0). During this process, we will discuss your specific needs, projected API usage and provide tailored solutions
### Benefits of Higher Tiers
* **Increased Rate Limits:** Access significantly higher RPS and burst capacities to support larger user bases and more demanding applications
* **Service Level Agreements (SLAs):** Enterprise and Premium tiers often come with formal SLAs, guaranteeing specific uptime, performance metrics and response times for critical issues
* **Priority Support:** Receive expedited assistance from our technical team, ensuring your queries and issues are addressed promptly
* **Custom Integration Guidance:** Benefit from dedicated technical consultations and integration support to optimize your application's performance and integrate the features effectively
* **Custom Pricing and Billing:** For Enterprise partners, flexible pricing models can be arranged to align with your business operations
***
We are committed to providing a reliable and scalable API experience. If you anticipate exceeding your current tier's limits or have any questions regarding your access tier, please contact us for further assistance
# Overview
Source: https://docs.gluex.xyz/build-with-gluex/exchange-rate/overview
GlueX Exchange Rates API - Real time, onchain exchange rates across multiple blockchains
The GlueX Exchange Rates API provides developers with a robust, scalable, and real time solution to fetch onchain exchange rates for any token pair across multiple supported blockchains. Perfect for integrating live pricing data into DeFi applications, crypto wallets, trading platforms and analytical dashboards
## Base URL
All API endpoint requests are made relative to the following base URL:
```http
http://exchange-rates.gluex.xyz
```
## Key Features
* **Realtime & Accurate Rates**: Realtime data feeds to obtain highly accurate, up to the second exchange rates directly from decentralized liquidity sources, ensuring your application always has the most current information
* **Multichain Support**: Access extensive rate data across a growing ecosystem of EVM compatible blockchains, including major networks like Ethereum, BNB Chain, Polygon, Arbitrum, Optimism, and many others, all through a single, unified API
* **Batch Requests**: Optimize your data fetching and minimize network overhead by retrieving exchange rates for up to 25 distinct token pairs in a single, efficient API call
* **Instant Access**: Start building immediately with public, unauthenticated endpoints for quick testing and low volume usage. For higher throughput, dedicated rate limits and enhanced reliability, easily provision and use an API key
* **Fast & Reliable**: Experience exceptional responsiveness with an average request round trip of under 500ms, ensuring your application remains highly responsive and delivers immediate data to users
* **Specialized Support**: Designed to intelligently handle a wide array of token types, including rebase tokens, yield bearing assets, LP tokens and other complex edge cases, providing reliable rates for even the most nuanced DeFi assets
Experience DeFi at it's finest. Test the Exchange Rate API instantly
directly in your browser
Dive into step by step guides and best practices for integrating the
Exchange Rate API
***
## Tutorials
* [How to Request Exchange Rates](/guides/exchange-rate/how-to-request-exchange-rates)
* [How to Request All Supported Chains](/guides/exchange-rate/how-to-request-all-supported-chains)
# Request and Response Format
Source: https://docs.gluex.xyz/build-with-gluex/exchange-rate/request-response-format
This document outlines the structure of requests and responses for Exchange Rate (common fields and endpoint specific fields)
This document provides a comprehensive guide to the structures used when interacting with the Exchange Rate API. Understanding these formats is crucial for correctly constructing your requests and parsing the API responses
## Request Parameters
The following parameters may be included in the request payload for `/` endpoint
| Name | Type | Required | Description |
| --------------------- | ------ | -------- | -------------------------------------------------- |
| `domestic_blockchain` | string | ✅ | Identifier for the domestic chain (eg: `ethereum`) |
| `domestic_token` | string | ✅ | Address of the domestic token |
| `foreign_blockchain` | string | ✅ | Identifier for the foreign chain |
| `foreign_token` | string | ✅ | Address of the foreign token |
**Example Request Body**
```json
[
{
"domestic_blockchain": "ethereum",
"domestic_token": "0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48",
"foreign_blockchain": "ethereum",
"foreign_token": "0xdac17f958d2ee523a2206206994597c13d831ec7"
},
{
"domestic_blockchain": "polygon",
"domestic_token": "0x2791bca1f2de4661ed88a30c99a7a9226cbefc3f",
"foreign_blockchain": "ethereum",
"foreign_token": "0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2"
}
]
```
## Common Response Fields
The following fields are returned in both `/v1/price` and `/v1/quote` responses.
| Field | Type | Description |
| --------------------- | ------ | -------------------------------------------------------------------------------------------------------------------------------------- |
| `domestic_blockchain` | string | Identifier for the domestic chain (eg: `ethereum`) |
| `domestic_token` | string | Address of the domestic token |
| `foreign_blockchain` | string | Identifier for the foreign chain |
| `foreign_token` | string | Address of the foreign token |
| `price` | number | The exchange rate between the two tokens. This represents how much of the `foreign_token` you get for one unit of the `domestic_token` |
**Example Response**
```json
[
{
"domestic_blockchain": "ethereum",
"domestic_token": "0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48",
"foreign_blockchain": "ethereum",
"foreign_token": "0xdac17f958d2ee523a2206206994597c13d831ec7",
"price": 1.00025
},
{
"domestic_blockchain": "polygon",
"domestic_token": "0x2791bca1f2de4661ed88a30c99a7a9226cbefc3f",
"foreign_blockchain": "ethereum",
"foreign_token": "0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2",
"price": 0.00032
}
]
```
# Overview
Source: https://docs.gluex.xyz/build-with-gluex/overview
GlueX provides easy widget integrations and a fully customizable API and SDK integrations to power DeFi activity across 17 EVM chains. Our suite of APIs has securely routed over 106 million order flows and more than [10 billion dollars](https://dune.com/gluex_protocol/metrics) in volume
## Build With GlueX
[Apply for an Integrator ID](https://portal.gluex.xyz) and then explore how to build below
UI components for effortless DeFi integration
API suite for efficient and secure onchain interaction
# Buy Order
Source: https://docs.gluex.xyz/build-with-gluex/router/advanced-features/buy-order
While traditional swaps (often referred to as `SELL` orders) involve specifying the `inputAmount` and receiving a calculated `outputAmount`, the **Buy Order** functionality allows users to define their desired `outputAmount` of tokens, with the router calculating the required `inputAmount` to achieve that target. This provides greater flexibility for users focused on acquiring a specific amount of an asset
### How It Works
When orderType is set to `BUY`, the GlueX Router fundamentally reverses its calculation logic:
* **Input calculation**: Instead of starting with a fixed input, the router determines the minimum `inputAmount` (and thus `inputToken`) necessary to acquire the `outputAmount` specified by the user, taking into account current market rates, fees and slippage
* **Market buy optimization**: The routing engine optimizes the path to achieve the target outputAmount using the most cost effective `inputAmount` possible
This contrasts directly with the default `SELL` order behavior, where `inputAmount` is predefined, and the `outputAmount` is the calculated variable
### Configuration
To initiate a Buy Order, you must include the `orderType` and `outputAmount` parameters in your `/v1/price` or `/v1/quote` request payload:
```json
{
// ... other parameters
"orderType": "BUY",
"outputAmount": ""
}
```
| `orderType` | Required Field | Description |
| ----------- | -------------- | --------------------------------- |
| `BUY` | `outputAmount` | Amount of output token to receive |
| `SELL` | `inputAmount` | Amount of input token to swap |
If `orderType` is **not specified**, it defaults to `SELL`. In this case,
`inputAmount` parameter becomes mandatory and `outputAmount` will be computed
by the API
### Benefits
* **Flexibility**: Caters directly to users who know exactly how much of a target token they wish to acquire
* **Simplified user flow**: For specific use cases (eg: buying a fixed amount of governance tokens), this simplifies the user experience by reducing mental calculation
* **Optimized input calculation**: The router automatically finds the most efficient way to achieve the desired `outputAmount`
# Liquidity Module Filtering
Source: https://docs.gluex.xyz/build-with-gluex/router/advanced-features/liquidity-module-filtering
The **modulesFilter** is an advanced configuration option that allows developers to precisely control which underlying DEX protocols, lending platforms or other liquidity sources (referred to as [modules](/documentation/references/modules)) should considered when constructing a routing path
### How It Works
By including an array of specific module identifiers in your request, you instruct the routing engine to limit the search space and consider liquidity from these whitelisted sources. Any liquidity available from modules not present in your `modulesFilter` array will be ignored during route construction
Each integrated protocol or liquidity source within GlueX has a unique
identifier (eg: "uniswap\_v3", "aave\_v3", "curve\_stable\_plain", etc). You can
find a comprehensive list of supported modules and their identifiers on the
[liquidity modules](/documentation/references/modules) page or
[here](https://router.gluex.xyz/liquidity)
### Configuration
To filter liquidity modules, include an array of desired module identifiers in your `/v1/price` or `/v1/quote` request payload
```json
{
// ... other parameters
"modulesFilter": ["module_1", "module_2"]
}
```
In this example, the router would only consider paths involving `module_1` and `module_2` liquidity, even if other more optimal routes existed on different protocols
### Use Case
This feature is particularly valuable for projects that require fine grained control over their DeFi integrations:
* **Protocol restriction**: Directly restrict routing to only a predefined set of preferred protocols (eg: for compliance reasons, specific security postures or brand alignment)
* **Avoiding specific sources**
* **Avoid using specific liquidity pools or protocols**
* **Compliance and Regulatory constraints**: Meet internal or external compliance policies that mandate interactions only with approved liquidity sources
* **Custom strategies**: Implement advanced strategies where specific liquidity pools are favored or avoided based on institutional preferences or unique market analyses
### Benefits
* **Provides greater control**: Offers unparalleled control over the routing behavior, allowing you to tailor the integration precisely to your application's needs
* **Supports whitelisted integrations**: Facilitates integration with whitelisted or pre approved liquidity sources, which is critical for institutional or regulated environments
* **Enables custom strategies**: Unlocks the ability to implement unique trade strategies that might prioritize certain protocols over others, even if they aren't always the absolute cheapest
* **Enhanced auditability**: By narrowing down the potential sources, it can simplify the auditing process of your application's DeFi interactions
# Partial Fill Order
Source: https://docs.gluex.xyz/build-with-gluex/router/advanced-features/partial-fill-order
In scenarios characterized by low liquidity, fragmented markets or extremely unfavorable market conditions, attempting to execute a full swap with a large `inputAmount` can result in significant and often unacceptable slippage. The **Partial Fill Orders** feature addresses this by dynamically determining and executing only the optimal portion of a trade
### How It Works
Instead of forcing a full trade that might yield a poor outcome (or cause excessive slippage), the Router intelligently calculates the largest tradable portion that still meets efficient pricing
* **Optimal portion calculation**: If the full inputAmount (for a `SELL` order) would cause the trade to exceed an acceptable slippage tolerance or result in an unprofitably high price impact, the router calculates the largest possible portion of the trade that can still be executed efficiently
* The API response will then provide:
* **Suggested input amount**: the optimized, smaller amount of `inputToken` that can be efficiently traded
* **Expected output amount**: the amount of `outputToken` achievable with the suggested input
### Example
Imagine a user attempts to swap 1,000 USDC for a less liquid token. In a market with shallow or low liquidity for that specific pair, executing the full 1,000 USDC might cause 5% slippage, resulting in a poor exchange rate. With `isPartialFill: true`, the router might determine that only 730 USDC can be traded efficiently (eg: with 0.5% slippage). In this case, the quote response would suggest using 730 USDC as the `effectiveInputAmount` and provide the corresponding `effectiveOutputAmount`, allowing the user to execute the most efficient part of their desired trade
### Configuration
Partial Fill Orders are **disabled by default** to give integrators full control. You can enable it explicitly in your `/v1/price` or `/v1/quote` API request by setting the `isPartialFill` parameter to `true`:
```json
{
// ... other parameters
"isPartialFill": true
}
```
### Benefits
* **Reduces exposure to slippage**: Minimizes potential losses by avoiding transactions that would incur high slippage for the full amount
* **Adapts to realtime market conditions**: Automatically adjusts trade size based on current liquidity and volatility, providing a more robust trading experience
* **Maximizes trade efficiency without user intervention**: Ensures that trades are executed at the best possible price points available, even in challenging market environments, often without direct user intervention beyond the initial configuration
* **Improved user experience**: Prevents failed transactions or surprisingly poor execution for users who might not be aware of underlying liquidity issue
# Surge Protection
Source: https://docs.gluex.xyz/build-with-gluex/router/advanced-features/surge-protection
**Surge Protection** is a built in pre trade safety mechanism designed to safeguard users from significant value loss during periods of shallow liquidity, extreme market volatility or abrupt price movements
### How It Works
Before executing a swap, the Router performs a rapid, hypothetical **reverse trade simulation**. This simulation instantaneously attempts to "sell back" the expected output token for the original input token, all within the context of the same block and without external market interference
* **Simulation logic:** The router uses the current onchain state to estimate how much of the original `inputToken` a user would recover if they immediately tried to reverse the trade
* **Threshold trigger:** If this estimated recovery amount falls below a predefined threshold (currently **90%** of the original `inputAmount`), the trade is deemed high risk and is automatically blocked by the router. This prevents the transaction from being broadcast onchain, saving the user from a potentially significant loss
### Evaluation Criteria
The Surge Protection mechanism evaluates a combination of factors to determine if a trade poses an unacceptable risk:
* **Liquidity depth:** Assesses the available liquidity on the chosen routing path. Extremely shallow liquidity can make trades highly susceptible to price swings
* **Price impact:** Analyzes the estimated price impact of the proposed trade on the affected liquidity pools
* **Volatility within the block:** Detects sudden and significant price changes occurring within the current blockchain block, often indicative of front-running attempts or market manipulation
### Default Threshold
If the estimated reverse loss exceeds **10%** (meaning the recovered amount would be less than 90% of the original input), the trade is halted, and the API returns a `revert: true` flag and the specific error causing the Surge Protection activation
### User Benefits
Implementing Surge Protection directly translates to a safer and more trustworthy experience for the end users:
* **Prevents sudden losses:** Acts as a shield against common DeFi pitfalls like front running (where malicious bots execute trades before and after a user's transaction to profit from price changes) or being the "exit liquidity" in illiquid pools
* **Avoids adverse market conditions:** Protects users from executing trades when liquidity is insufficient or prices are highly volatile, which could lead to substantial value erosion
* **Enhances trust and safety:** By proactively preventing potentially bad trades, Surge Protection significantly enhances user confidence in your application and on us!
### Configuration
Surge Protection is **disabled by default** to give integrators full control. You can enable it explicitly in your `/v1/quote` API request by setting the `surgeProtection` parameter to `true`:
```json
{
// ... other parameters
"surgeProtection": true
}
```
When enabled, any trade exceeding the 10% reverse loss threshold will cause
the `/v1/quote` endpoint to return `revert: true` and will not provide
executable calldata. Your application should gracefully handle this condition
and inform the user
# API Endpoints
Source: https://docs.gluex.xyz/build-with-gluex/router/api-endpoints
This section outlines the primary endpoints (fetch pricing estimates and generate transaction calldata) provided by the Router API
The GlueX Router API provides a powerful and flexible interface for interacting with decentralized finance protocols. This section outlines the core endpoints you'll use to fetch real time pricing estimates and generate the necessary transaction calldata for seamless onchain execution
> **Note:**
> It is highly recommended to call the `price` endpoint before invoking the `quote` endpoint. This pattern is especially critical when building applications. The `price` endpoint can be polled periodically (eg: every few seconds) to provide users with realtime pricing information. Once the user approves the router contract and confirms the intention to swap, the `quote` endpoint should be called to retrieve the final calldata for onchain execution
>
> This architecture reduces unnecessary load on the quote infrastructure and ensures accurate, timely user interactions. Furthermore, GlueX plans to introduce market maker integrations on the `quote` endpoint, which will enhance price discovery and further optimize rate limits for this endpoint
## POST `/v1/price`
Returns a **price estimate** for a token swap. This endpoint is intended for off chain estimation and does not include calldata or simulation metadata
**Description**
* Provides estimated input/output amounts
* Supports partial fill logic
**Example Request**
```http
POST /v1/price
x-api-key: your-api-key
Content-Type: application/json
```
**Request Body (Example)**
```json
{
"chainID": "ethereum",
"inputToken": "0x...",
"outputToken": "0x...",
"inputAmount": "100000000",
"userAddress": "0x...",
"outputReceiver": "0x...",
"uniquePID": "partner-xyz"
}
```
For detailed information on the **request and response formats**, refer the
section [here](/build-with-gluex/router/request-response-format)
***
## POST /v1/quote
Returns a **price quote** along with **transaction calldata** for executing the trade onchain
**Description**
* Includes all `price` endpoint fields
* Adds transaction-specific fields such as `calldata` and `revert`
* Simulation is enabled by default (`computeEstimate: true`)
**Example Request**
```http
POST /v1/quote
x-api-key: your-api-key
Content-Type: application/json
```
**Request Body (Example)**
```json
{
"chainID": "ethereum",
"inputToken": "0x...",
"outputToken": "0x...",
"inputAmount": "100000000",
"userAddress": "0x...",
"outputReceiver": "0x...",
"uniquePID": "partner-xyz",
"computeEstimate": true
}
```
**Additional Response Fields for `quote`**
* `calldata`: ABI encoded transaction data
* `revert`: Boolean indicating if the trade would revert
* `computationUnits`: Estimated gas
* `lowBalance`: Indicates insufficient balance
* `blockNumber`: Block number for simulation context
* `simulation`: Raw trace/debug metadata
For detailed information on the **request and response formats**, refer the
section [here](/build-with-gluex/router/request-response-format)
***
These endpoints form the foundation of GlueX Router’s programmable interface, providing flexible and secure trade execution capabilities across supported [networks](/documentation/references/supported-networks)
# Fee Structure
Source: https://docs.gluex.xyz/build-with-gluex/router/fee-structure
Transparent and fair Router API fees at GlueX
At GlueX, **transparency and fairness** are core to our philosophy. Our Router API is designed not only for optimal trade execution, but also with a fee model that aligns the incentives of users, integrators, and the protocol itself
We apply a **0.03%–0.05% settlement fee** to all trades, which is shared between GlueX and the integrator. In addition, we implement a flexible **positive slippage sharing**, **partner fee configuration**, and an **surplus sharing mechanism** to ensure equitable outcomes for all parties
***
## Settlement Fees
GlueX applies a **0.03%–0.05% settlement fee** on every trade executed through the Router API. This fee is shared **50/50** between GlueX and the integrator
### Highlights
* **Low settlement fees**: Between 0.03% and 0.05% per trade
* **Revenue sharing**: Settlement fees are split equally between GlueX and the integrator
* **No hidden costs**: What you quote is what the user gets — with all fees accounted for transparently in the returned values
***
## Partner Fee Model
To help integrators monetize their services, GlueX supports a configurable **partner fee mechanism** that allows a portion of the output amount to be automatically redirected to a designated wallet
### Configuration
```json
{
// ... other parameters
"partnerFee": "",
"partnerAddress": "<0x_partner_wallet_address>"
}
```
* `partnerFee`: Basis points (bps) applied to the output amount, deducted before final output.
* `partnerAddress`: Wallet address where partner fees are sent.
### How It Works
Partner fees are factored into both `minOutputAmount` and `effectiveOutputAmount`. Once the trade is executed on-chain, the fee amount is automatically transferred to your `partnerAddress`.
***
## Positive Slippage Rewards
When trades execute better than quoted (i.e., **positive slippage**), GlueX ensures that this extra value is **fairly distributed** between the user, the integrator, and the protocol.
### Distribution
* **User**: Gets the primary share of the extra output.
* **Integrator**: Rewarded for routing users and optimizing experience.
* **GlueX**: Retains a portion to support protocol growth and sustainability.
This transparent, win-win-win mechanism fosters long-term trust and collaboration across all stakeholders.
***
## Surplus Sharing
“**Surplus**” refers to the added value when GlueX’s routing achieves **better-than-benchmark** execution (e.g., compared to next best aggregator's market rate). This can result from:
* **Optimized routing paths** across liquidity sources
* **Gas savings** via efficient transaction design
* **Proprietary internal methods**
* **Exclusive liquidity partnerships**
### Surplus Distribution
| Recipient | Share of Surplus |
| ---------- | ---------------- |
| User | ≥ 33% |
| Integrator | ≤ 33% |
| GlueX | ≤ 33% |
### Activation
To receive your share of surplus rewards:
```json
{
// ... other parameters
"activateSurplusFee": true,
"partnerAddress": "<0x_partner_wallet_address>"
}
```
> When `activateSurplusFee` is enabled, specialized contracts handle the fair distribution of captured surplus, ensuring your `partnerAddress` receives its portion automatically.
## Positive Slippage Rewards
When trades execute better than quoted (i.e., **positive slippage exists**), GlueX ensures that this extra value is **fairly distributed** between the user, the integrator, and the protocol - in the same ratio as the surplus.
### Distribution
* **User**: Gets the primary share of the extra output.
* **Integrator**: Rewarded for brinding orderflow and optimizing experience.
* **GlueX**: Retains a portion to support protocol growth and sustainability.
This transparent, win-win-win mechanism fosters long-term trust and collaboration across all stakeholders.
***
At GlueX, our commitment is to building a **transparent, fair, and sustainable** ecosystem for all participants. For help with fee setup, surplus activation, or to explore partnership opportunities, reach out via our [official Telegram](https://t.me/+_VmO_gIrNjxiZWE0).
# Overview
Source: https://docs.gluex.xyz/build-with-gluex/router/overview
The **Router API** is a versatile, high performance tool designed to enable efficient and secure onchain interactions across multiple blockchain networks. It provides developers with a robust solution to seamlessly integrate decentralized finance (DeFi) operations, including token swaps, lending, staking, yield farming and more, into the applications
## Base URL
All API endpoint requests are made relative to the following base URL:
```http
https://router.gluex.xyz
```
Always ensure you are using the correct version (`/v1`) in your API calls for
the latest features and stability
## Key Features
The GlueX Router API offers several advanced features designed to improve transaction efficiency, reduce risk and provide transparency to end users and integrators:
* **Multi Chain Support**: Seamlessly orchestrate complex DeFi operations across all [supported blockchain networks](/documentation/references/supported-networks) intelligently identifing optimal paths
* **Comprehensive DeFi Protocol Integration**: Access unparalleled liquidity and functionality through deep integrations with a vast array of DeFi protocols ensuring maximum liquidity and opportunity, including:
* Decentralized Exchanges (eg: )
* Lending Platforms (eg: Aave, Compound)
* Yield Farming Protocols & Vaults (eg: )
* Staking (eg: )
* Bridging (eg: )
* **Optimized Transaction Execution**: Our advanced routing engine meticulously crafts transaction paths to minimize costly reversions and actively protect against Maximal Extractable Value (MEV) attacks like front running and sandwich attacks ensuring users get the best possible execution
* **Rapid Response Times**: Experience blazing fast performance with an average request round trip time of the quote is approximately 500 milliseconds, enabling highly responsive applications
* **Positive Slippage Rewards**: Any positive slippage (ie, receiving more output than initially quoted) is intelligently and transparently distributed among the end users, integrating partner and us!
* **Dynamic, Zero Routing Fees**: GlueX charges absolutely zero direct routing fees to the end user. Our revenue model is based on a small, transparent share of the positive slippage when it occurs, ensuring there are no hidden costs or charges. This aligns our incentives with providing the most optimal routes
Experience DeFi at it's finest. Test the Router API instantly directly in
your browser
Dive into step by step guides and best practices for integrating the Router
API
## Additional Documentation
To help you get the most out of the GlueX Router API, refer to the following dedicated sections for detailed information and advanced guidance:
* [How to use API endpoints?](api-endpoints)
* [What are the **Request and Response Formats**?](request-response-format)
* [What advanced features do we provide?](advanced-features)
* [Do you want to charge any Fee?](fee-structure)
* [How many times can you call our API?](api-tiers-limits)
* [All set for getting started!](getting-started)
# Request and Response Format
Source: https://docs.gluex.xyz/build-with-gluex/router/request-response-format
This document outlines the structure of requests and responses for Router (common fields and endpoint specific fields)
This document provides a comprehensive guide to the structures used when interacting with the Router API. Understanding these formats is crucial for correctly constructing your requests and parsing the API responses
## Request Parameters
The following parameters may be included in the request payload for `/v1/price` and `/v1/quote` endpoints
| Name | Type | Required | Default Value | Description |
| -------------------- | -------------- | ----------- | ------------- | ---------------------------------------------------- |
| `chainID` | string | Conditional | | Identifier for the target chain (eg: `ethereum`) |
| `networkID` | string/integer | Conditional | | Numerical chain ID (eg: `1` for Ethereum) |
| `inputToken` | string | ✅ | | ERC20 token address to be sold |
| `outputToken` | string | ✅ | | ERC20 token address to be bought |
| `inputAmount` | string/integer | Conditional | | Amount of input token (used for SELL orders) |
| `outputAmount` | string/integer | Conditional | | Desired amount of output token (used for BUY orders) |
| `orderType` | string | Conditional | | Type of order: `BUY` or `SELL` |
| `userAddress` | string | ✅ | | Initiator's wallet address |
| `outputReceiver` | string | ✅ | | Address to receive the output token |
| `uniquePID` | string | ✅ | | Partner ID for analytics and attribution |
| `computeEstimate` | boolean | Optional | true | Enable simulation |
| `computeStable` | boolean | Optional | false | Include USD value metadata in response |
| `surgeProtection` | boolean | Optional | false | Enable or disable Surge Protection |
| `isPartialFill` | boolean | Optional | false | Allow partial fill swaps |
| `isPermit2` | boolean | Optional | false | Use Permit2 for allowance approvals |
| `slippage` | string/integer | Optional | | Maximum slippage allowed (in basis points) |
| `partnerFee` | string/integer | Optional | 0 | Fee in bps applied to output |
| `partnerAddress` | string | Conditional | | EOA to receive partner fee and surplus |
| `modulesFilter` | array | Optional | \[] | Restrict routing to specified liquidity modules |
| `activateSurplusFee` | boolean | Optional | false | Enable surplus sharing contract |
## Common Response Fields
The following fields are returned in both `/v1/price` and `/v1/quote` responses.
| Field | Type | Description |
| ----------------------- | ------- | ---------------------------------------------------- |
| `inputToken` | string | ERC20 address of input token |
| `outputToken` | string | ERC20 address of output token |
| `feeToken` | string | Token used to pay any applicable fees |
| `inputSender` | string | Address initiating the trade |
| `outputReceiver` | string | Address receiving the output |
| `inputAmount` | string | Original input amount |
| `outputAmount` | string | Expected output amount |
| `partnerFee` | string | Amount of fee allocated to partner |
| `routingFee` | string | GlueX's routing fee (typically zero) |
| `effectiveInputAmount` | string | Actual used input in the swap (for partial fills) |
| `effectiveOutputAmount` | string | Actual received output after fees and routing |
| `minOutputAmount` | string | Slippage-protected minimum output |
| `liquidityModules` | array | Liquidity sources/modules used |
| `isNativeTokenInput` | boolean | Indicates if native token (eg: ETH) was used |
| `value` | string | Value (in wei) sent with transaction (if applicable) |
## Endpoint Specific Response Fields
### Fields for `/v1/price`
| Field | Type | Description |
| ------------ | ------- | --------------------------------------------- |
| `surgeValue` | integer | Projected reverse loss estimate in percentage |
### Fields for `/v1/quote`
| Field | Type | Description |
| ------------------ | ------- | ---------------------------------------------- |
| `calldata` | string | ABI encoded transaction data |
| `revert` | boolean | Indicates if trade would revert onchain |
| `computationUnits` | integer | Estimated gas cost |
| `lowBalance` | boolean | True if user balance is insufficient |
| `blockNumber` | integer | Block number used during simulation |
| `simulation` | object | Detailed trace/debug object for advanced usage |
# Configuring the Widget
Source: https://docs.gluex.xyz/build-with-gluex/widget/configuration
The widget supports a range of configuration options, allowing you to:
* Preselect default chain
* Preselect the source and destination token
* Preselect the appearance
* Prefill the amount of the source token
* Prefill the amount of the destination token
* Prefill the slippage configuration
* Allow or deny surplus feature
* Allow or deny specific liquidity sources
* Allow or deny specific chains
* Allow or deny specific tokens
* Specify the receiving address
* Specify the type of order - `BUY` or `SELL`
* Specify the partner fee
These extensive configuration options collectively enable precise control over the widget's behavior and improve the user experience by adjusting it to specific needs and preferences, creating a highly optimized, branded and intuitive experience. This flexibility makes the widget a powerful and adaptable component that can seamlessly integrate into any decentralized application architecture while maintaining consistency with your brand and user experience requirements.
## SDK configuration
The GlueX widget is built on top of our robust SDK, utilizing its core functionality to provide seamless integration and optimal performance. The `sdk` option allows you to configure various aspects of the underlying SDK directly within the widget configuration, ensuring that all SDK-level settings align with your application requirements.
```typescript
const config = {
sdk: {
// .. sdk configuration
},
};
```
The SDK configuration interface provides comprehensive control over core functionality:
```typescript
interface SDKConfig {
userId: string; // the user ID of the user attached with each request for tracking
referrer: string; // the referrer address of the user
rpcUrls: RPCUrls;
chains: Chain[];
debug: boolean;
fees: {
partner?: number;
payoutAddress?: string;
surplusFee?: boolean;
};
}
```
### User
The `userId` field allows you to attach a unique user identifier to each request, enabling comprehensive tracking and analytics capabilities. This identifier helps you monitor user behavior, analyze transaction patterns, and provide personalized experiences. The user ID should be a consistent, unique string that identifies individual users across sessions
```typescript
const config = {
sdk: {
userId: "user-12345",
},
};
```
**Best Practices**
*
- Use consistent identifiers that persist across user sessions
- Ensure user IDs are unique and don't contain sensitive information
- Consider using UUIDs or hashed values for enhanced privacy
- Implement proper user consent mechanisms for tracking where required by regulations
### Referrer
The referrer field specifies the referrer address of the user for tracking and attribution purposes. This is particularly important for affiliate programs, partner integrations and revenue sharing models. The referrer address should be a valid address
```typescript
const config = {
sdk: {
referrer: "0x12345...678",
},
};
```
Referral fee system is coming soon with advanced attribution and reward
mechanisms
**Referrer Implementation Guidelines:**
* Ensure the referrer address is properly formatted and validated
* Use consistent referrer addresses for accurate attribution tracking
* Consider implementing dynamic referrer assignment based on user acquisition channels
* Document referrer relationships for transparent revenue sharing
### RPC endpoints
Configure custom RPC endpoints for different blockchain networks to ensure reliable connectivity, optimal performance and reduced dependency on public infrastructure. Custom RPC configurations help maintain consistent service quality and avoid rate limiting issues that commonly affect public endpoints
```typescript
type RPCUrls = Partial>;
const config = {
sdk: {
rpcUrls: {
ethereum: ["https://mainnet.infura.io/v3/"],
polygon: ["https://polygon-mainnet.infura.io/v3/"],
},
},
};
```
For production deployments, always use your own authenticated RPC provider
(such as Alchemy, Infura, QuickNode, or Ankr). If custom RPC endpoints are not
specified, the widget defaults to public RPC endpoints, which may experience
rate limiting and cause issues like incorrect balance displays, failed
transactions, or degraded performance during high traffic periods
**Best Practices**
\*\*
* **Redundancy**: Configure multiple RPC endpoints per chain for failover protection
* **Monitoring**: Implement RPC endpoint health monitoring and automatic failover
* **Authentication**: Use authenticated endpoints with proper API key management
* **Geographic Distribution**: Consider RPC provider locations relative to your user base for optimal latency
### Explorer URLs
.. TBD ..
### Partner Fees
The partner fee system enables revenue generation through transaction based commissions. The `fees.partner` parameter allows you to configure partner fees for each transaction processed through the widget. The `partner` field expects a value in basis points (bps), where 100 bps equals 1% of the transaction volume. The maximum allowed fee is 10% (1000 bps) to ensure reasonable cost structures for end users
```typescript
const config = {
sdk: {
fees: {
partner: 100, // 1% partner fee
payoutAddress: "0xabc...xyz", // Address to receive accumulated fees
},
},
};
```
To ensure partner fees are correctly collected and distributed, you must
specify the `payoutAddress` in your configuration. This address will receive
the accumulated fees for each transaction. Alternatively, you can configure
this address via the [developer portal](https://portal.gluex.xyz) for
centralized management across multiple integrations
**Partner Fee Implementation Details:**
* **Fee Calculation**: Fees are calculated as a percentage of the total transaction volume
* **Fee Collection**: Fees are automatically deducted during the swap process and distributed to the specified payout address within each transaction
* **Transparency**: Clearly communicate fee structures to end users for transparency and trust
## Form Values
The widget provides comprehensive and flexible options for preconfiguring default values and dynamically updating parameters for chains, tokens, amounts, and addresses. This functionality makes it easy to set up and maintain desired swap parameters, creating seamless user experiences that can adapt to changing requirements and user preferences
### Configuration
The most straightforward approach is to preconfigure values directly in the widget configuration object during initialization. This method ensures consistent default values across all widget instances and provides a stable foundation for your application's swap functionality
```typescript
const config = {
// Network configuration
// set source chain
fromChain: 1,
// set destination chain
toChain: 1,
// Token configuration
// set source token
fromToken: "0xabc...xyz",
// set source token
toToken: "0x123...890",
// Amount configuration
// set source token amount
fromAmount: 1000000,
// Destination configuration
// set the destination wallet address
toAddress: {
name: "My Vault",
address: "0x123...678",
},
};
```
The widget currently supports only swap operations. Therefore, you should
specify either fromChain or toChain, or set both to the same value
**Configuration Value Types and Validation:**
* **Chain IDs**: Use standard chain identifiers (1 for Ethereum, 137 for Polygon, etc.)
* **Token Addresses**: Must be valid ERC20 contract addresses with proper checksum formatting
* **Amounts**: Specify in token's native decimal format (eg: for USDC with 6 decimals, 1000000 = 1 USDC)
* **Addresses**: All addresses must be valid Ethereum format with proper checksum encoding
#### Configuration Updates
The widget supports dynamic configuration updates after initialization, enabling real-time form value changes based on user interactions, market conditions or application state changes. This functionality is particularly valuable for applications using state management libraries like Redux, Zustand or React Context, allowing seamless integration with existing application architectures
**FormUpdateKey Mechanism**
The `formUpdateKey` is a critical component of the state management update system that triggers form re-rendering when configuration changes occur:
```typescript
interface WidgetConfiguration {
// ... other configuration options
/**
* Key that triggers form updates when changed
* Should be updated whenever you want to apply config changes to the form
* Can be any string value - commonly used patterns:
* - Timestamp: Date.now().toString()
* - UUID: crypto.randomUUID()
* - Incremental counter: (counter++).toString()
* - Hash of changed values: hashFunction(changedConfig)
*/
formUpdateKey?: string;
}
```
**Implementation Patterns:**
```typescript
import { useSelector, useDispatch } from "react-redux";
import { updateSwapConfig, incrementUpdateKey } from "./swapSlice";
const WidgetWithRedux = () => {
const dispatch = useDispatch();
const { config, updateKey } = useSelector((state) => state.swap);
const handleUpdateFromChain = (chainId: number) => {
// Update only the specific values you want to change
dispatch(
updateSwapConfig({
fromChain: chainId,
// Optionally clear related values when chain changes
fromToken: undefined,
fromAmount: undefined,
})
);
dispatch(incrementUpdateKey()); // Trigger widget update
};
const handleUpdateTokenPair = (fromToken: string, toToken: string) => {
dispatch(
updateSwapConfig({
fromToken,
toToken,
// Clear amounts when tokens change to prevent confusion
fromAmount: undefined,
})
);
dispatch(incrementUpdateKey());
};
const handlePresetTrade = (preset: "eth-to-usdc" | "usdc-to-dai") => {
const presets = {
"eth-to-usdc": {
fromChain: 1,
toChain: 1,
fromToken: "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2", // WETH
toToken: "0xA0b86a33E6441C8FFa4c02bae5a0Dd0D8e87fb8e", // USDC
fromAmount: 1,
},
"usdc-to-dai": {
fromChain: 1,
toChain: 1,
fromToken: "0xA0b86a33E6441C8FFa4c02bae5a0Dd0D8e87fb8e", // USDC
toToken: "0x6B175474E89094C44Da98b954EedeAC495271d0F", // DAI
fromAmount: 1000,
},
};
dispatch(updateSwapConfig(presets[preset]));
dispatch(incrementUpdateKey());
};
return (
<>
{/* Debug panel - remove in production */}
Configuration History ({state.history.length})
{JSON.stringify(state.history, null, 2)}
);
};
```
### URL search params
To initialize form values in the widget using URL search parameters, you must ensure that `buildUrl` is set to `true` in the widget configuration. This feature enables deep linking, shareable swap configurations, and easy integration with web analytics and tracking systems
```typescript
const config = {
// instruct the widget to use and build url search params
buildUrl: true,
};
```
**Parameter Structure**
The widget accepts the following URL search parameters with comprehensive support for all configurable values:
```
https://?fromAmount=&fromChain=&fromToken=&toAddress=&toChain=&toToken=
```
**Parameter Reference:**
| Parameter | Type | Description | Example |
| ------------ | ------ | --------------------------------------------- | ------------------ |
| `fromAmount` | string | Source token amount in token's decimal format | `1000000` (1 USDC) |
| `fromChain` | string | Source blockchain ID | `1` (Ethereum) |
| `fromToken` | string | Source token contract address | `0xA0b86a33...` |
| `toAddress` | string | Destination wallet address | `0x742d35Cc...` |
| `toChain` | string | Destination blockchain ID | `137` (Polygon) |
| `toToken` | string | Destination token contract address | `0x2791Bca1...` |
**Best Practices**
When constructing URLs programmatically, ensure proper encoding and validation:
```typescript
const buildSwapUrl = (baseUrl: string, params: SwapParams) => {
const urlParams = new URLSearchParams();
// Add parameters with proper validation
if (params.fromAmount && params.fromAmount > 0) {
urlParams.set("fromAmount", params.fromAmount.toString());
}
if (params.fromChain) {
urlParams.set("fromChain", params.fromChain.toString());
}
if (params.fromToken && isValidAddress(params.fromToken)) {
urlParams.set("fromToken", params.fromToken);
}
if (params.toAddress && isValidAddress(params.toAddress)) {
urlParams.set("toAddress", params.toAddress);
}
if (params.toChain) {
urlParams.set("toChain", params.toChain.toString());
}
if (params.toToken && isValidAddress(params.toToken)) {
urlParams.set("toToken", params.toToken);
}
if (params.slippage && params.slippage > 0 && params.slippage <= 50) {
urlParams.set("slippage", params.slippage.toString());
}
if (params.orderType && ["BUY", "SELL"].includes(params.orderType)) {
urlParams.set("orderType", params.orderType);
}
return `${baseUrl}?${urlParams.toString()}`;
};
// Helper function for address validation
const isValidAddress = (address: string): boolean => {
return /^0x[a-fA-F0-9]{40}$/.test(address);
};
// Example usage
const swapUrl = buildSwapUrl("https://your-domain.com/swap", {
fromAmount: 1000000,
fromChain: 1,
fromToken: "0xA0b86a33E6441C8FFa4c02bae5a0Dd0D8e87fb8e",
toAddress: "0x742d35Cc6634C0532925a3b8d5c01B4FBf1234567",
toChain: 137,
toToken: "0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174",
slippage: 0.5,
orderType: "SELL",
});
```
**URL Parameter Behavior**
URL parameters only affect the widget's initialization state. Dynamically changing search parameters in the URL without triggering a page reload will not update the widget's form values. For runtime updates after initialization, use the Form Reference method or Configuration Updates approach described in other sections
Configuration values take precedence over URL search parameters. If you want
URL parameters to control initial form values, ensure that `fromAmount`,
`fromChain`, `fromToken`, `toAddress`, `toChain`, `toToken`, and other
relevant parameters are not defined in the widget configuration object. If
both configuration values and URL parameters are present, the widget will
overwrite URL parameters with configuration values and update the URL
accordingly
**Advanced URL Management:**
* **State Synchronization**: Implement bidirectional sync between URL params and application state
* **Parameter Validation**: Validate all URL parameters before applying them to prevent invalid states
* **Fallback Values**: Provide sensible defaults for missing or invalid URL parameters
* **SEO Optimization**: Use descriptive URL structures for better search engine indexing
* **Analytics Integration**: Track URL parameter usage for user behavior analysis
### Form Ref
The Form Reference method provides the most flexibility and granular control for programmatic manipulation of widget form values after initialization. This approach is ideal for building custom interfaces, creating advanced user experiences, or responding to complex user interactions and external system events
```typescript Example.tsx
export const WidgetPage = () => {
const formRef = useRef(null);
const handleSetEthereum = () => {
// Set source chain to Ethereum with URL update
formRef.current?.setFieldValue("fromChain", 1, {
setUrlSearchParam: true,
});
};
const handleSetPolygon = () => {
// Set destination chain to Polygon without URL update
formRef.current?.setFieldValue("toChain", 137, {
setUrlSearchParam: false,
});
};
;
};
```
## Allow and Deny Lists
The widget provides comprehensive `allow` and `deny` configuration options to give you precise control over which chains, tokens and liquidity sources can be utilized within your application. These filtering mechanisms enable you to create curated experiences that align with your business requirements, regulatory constraints, and user safety considerations
### Chains
Chain filtering allows you to restrict which blockchain networks are available to users, helping you focus on supported networks
```typescript
const config = {
chains: {
// Deny specific chains from being shown in the chains list
deny: [1, 56], // Disable Ethereum and BSC
// Allow only specific chains
allow: [137, 42161, 10], // Allow only Polygon, Arbitrum, and Optimism
},
};
```
### Tokens
Token filtering provides granular control over which tokens are available for trading, enabling you to create curated token lists that match your platform's focus
```typescript
const config = {
tokens: {
// Deny specific tokens (blacklist approach)
deny: [
{
address: "0x...",
chainId: 1,
},
{
address: "0x...",
chainId: 137,
},
],
// Allow only specific tokens (whitelist approach)
allow: [
{
address: "0xA0b86a33E6441C8FFa4c02bae5a0Dd0D8e87fb8e",
symbol: "USDC",
decimals: 6,
chainId: 1,
name: "USD Coin",
logoURI:
"https://assets.coingecko.com/coins/images/6319/thumb/USD_Coin_icon.png",
},
{
address: "0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174",
symbol: "USDC",
decimals: 6,
chainId: 137,
name: "USD Coin (PoS)",
logoURI:
"https://assets.coingecko.com/coins/images/6319/thumb/USD_Coin_icon.png",
},
],
},
};
```
#### Featured Tokens
Create curated lists of featured tokens to guide users toward high quality, liquid trading pairs and improve the overall trading experience
```typescript
const config = {
tokens: {
featured: [
{
address: "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2",
symbol: "WETH",
decimals: 18,
chainId: 1,
name: "Wrapped Ether",
logoURI:
"https://assets.coingecko.com/coins/images/2518/thumb/weth.png",
},
{
address: "0xA0b86a33E6441C8FFa4c02bae5a0Dd0D8e87fb8e",
symbol: "USDC",
decimals: 6,
chainId: 1,
name: "USD Coin",
logoURI:
"https://assets.coingecko.com/coins/images/6319/thumb/USD_Coin_icon.png",
},
{
address: "0x6B175474E89094C44Da98b954EedeAC495271d0F",
symbol: "DAI",
decimals: 18,
chainId: 1,
name: "Dai Stablecoin",
logoURI:
"https://assets.coingecko.com/coins/images/9956/thumb/Badge_Dai.png",
},
],
},
};
```
### Liquidity Sources
Control which liquidity sources and protocols are utilized for trade execution using the `modulesFilter` parameter, enabling you to optimize for specific characteristics like gas efficiency, slippage, or execution speed
```typescript
const config = {
modulesFilter: ["module_1", "module_2"],
};
```
In this example, the router would only consider paths involving module\_1 and module\_2 liquidity, even if other more optimal routes existed on different protocols
To get the most current list of supported modules and their identifiers, you
can visit the [liquidity modules documentation
page](/documentation/get-started/introduction) or check the [live module
registry](https://router.gluex.xyz/liquidity)
**Liquidity Source Management Best Practices:**
* **Diversification**: Use multiple sources to ensure route availability and competitive pricing
* **Regular Updates**: Keep module lists updated as new protocols launch and others become deprecated
* **Reliability Focus**: Prioritize well-established protocols with proven track records
## Destination address
Developers can use the `toAddress` option to configure the destination address. The address property is required, while the name and logoURI properties are optional
```typescript
const config = {
toAddress: {
name: "Vault Deposit",
address: "0xMy...VaultAddress",
logoURI: "https://vault.address/image.svg",
},
};
```
# Customization and Whitelabel
Source: https://docs.gluex.xyz/build-with-gluex/widget/customizations
The GlueX Widget offers comprehensive customization options to match the application's design and functionality requirements. The widget's layout stays consistent, but you can modify colors, fonts, styles, disable or hide parts of the UI and more
Check out [GlueX's Widget Studio](https://studio.gluex.xyz/playground) to
customize and integrate the widget
```typescript
interface WidgetThemeConfiguration = {
// customize individual components
components: WidgetCustomComponents;
// sets the appearance - ("light" | "dark" | "auto")
appearance: Appearance;
// tweak the theme objects such as palette, shape, typography, components, container, colors, fonts and border-radius
theme: WidgetTheme;
// disables parts of the widget
disabled: DisabledUIType[];
// hides parts of the widget
hidden: HiddenUIType[];
// makes parts of the widget as required
required: RequiredUIType[];
}
```
## UI Customization
### Appearance
Controls the widget's overall color scheme, so it can adapt to your app's light or dark mode or follow the user's system preference automatically. Use this to ensure visual consistency and reduce "mode flicker" when users switch themes.
| Property | Default | Allowed Values | Notes |
| ------------ | -------- | ----------------------- | --------------------------------------- |
| `appearance` | `"auto"` | `light`, `dark`, `auto` | `auto` will match the user's OS setting |
```ts
const config = {
appearance: "dark",
};
```
### Elements
Fine tune which parts of the interface your users see or interact with. Disable input fields to guide user flows, hide non essential widgets for a cleaner look or mark critical fields as required to ensure data collection
#### Disabled
Grey out and prevent interaction with specific UI elements
| Property | Type | Default | Notes |
| -------- | --------- | ------- | -------------------------------------------- |
| disabled | string\[] | \[] | List of element keys to disable (greyed out) |
```ts
const config = {
disabled: ["fromAmount", "fromToken"],
};
```
#### Hidden
Completely remove elements from the UI
| Property | Type | Default | Notes |
| -------- | --------- | ------- | ----------------------------------------------- |
| hidden | string\[] | \[] | List of element keys to remove entirely from UI |
```ts
const config = {
hidden: ["poweredBy", "language"],
};
```
#### Required
Ensure users fill out crucial fields before proceeding
| Property | Type | Default | Notes |
| -------- | --------- | ------- | ---------------------------------------- |
| required | string\[] | \[] | List of element keys that must be filled |
```ts
const config = {
required: ["toAddress"],
};
```
## Theme Customizations
### Layout
Override the outer container's dimensions and spacing to fit any layout fixed width/sidebar, full-page modal or embedded card. Control styling factors like height, max-height, padding, box shadow and more for a perfect visual fit
| Property | Type | Default | Notes |
| --------------- | ------ | ------- | ------------------------------ |
| theme.container | object | — | CSS style object for container |
```ts
const config = {
theme: {
container: {
width: "400px",
height: "600px",
maxHeight: "800px",
boxShadow: "0px 8px 32px rgba(0, 0, 0, 0.08)",
padding: "16px",
},
},
};
```
### Shape
Adjust corner radii globally across cards, buttons and panels either a single radius for everything or separate values for primary (cards) and secondary (buttons) elements
| Property | Type | Default | Notes |
| --------------------------------- | ------ | ------- | -------------------------- |
| theme.shape.borderRadius | number | — | Base radius in pixels |
| theme.shape.borderRadiusSecondary | number | — | Secondary (buttons) radius |
```ts
const config = {
theme: {
shape: {
borderRadius: 12,
borderRadiusSecondary: 16,
},
},
};
```
### Typography and Fonts
Define the widget's typographic scale font family, base font size and weight variants for regular, medium and bold text. Use your brand's font stack for full design cohesion
| Property | Type | Default | Notes |
| ---------------------------------- | ------ | ------- | ------------------------------- |
| theme.typography.fontFamily | string | — | CSS font-family string |
| theme.typography.fontSize | number | — | Base font size in pixels |
| theme.typography.fontWeightRegular | number | — | Numeric weight for regular text |
| theme.typography.fontWeightMedium | number | — | Numeric weight for medium text |
| theme.typography.fontWeightBold | number | — | Numeric weight for bold text |
```ts
const config = {
theme: {
typography: {
fontFamily: "Verdana, sans-serif",
fontSize: 14,
fontWeightRegular: 400,
fontWeightMedium: 500,
fontWeightBold: 700,
},
},
};
```
### Color System
Define full light and dark palettes - primary, secondary, background, text and semantic colors (success, error, warning, info) giving you end to end theming control with one config object
```ts
const config = {
theme: {
colorSchemes: {
light: {
palette: {
primary: { main: "#02F994", review: "#02F994" },
secondary: { main: "#F5B5FF" },
background: {
default: "#FFFFFF",
paper: "#F5F5F5",
selected: "#E0E0E0",
},
text: { primary: "#1A1A1A", secondary: "#757575" },
success: { main: "#4CAF50" },
error: { main: "#F44336" },
warning: { main: "#FF9800" },
info: { main: "#2196F3" },
},
},
dark: {
palette: {
/* dark-mode overrides here */
},
},
},
},
};
```
## Component Customization
The GlueX Widget offers robust component customization through custom component overrides. This means you can tailor the look and feel of various elements to perfectly match your application's design
### Step 1: Build Your Custom Component
Create your own React component that matches the expected props for the widget element you want to customize
For example, to customize the token selector button, you might write:
```typescript
// custom/token-selector.tsx
import { type SelectTokenButtonProps } from "@gluex/widget";
export const CustomTokenHeader: React.FC = ({
formType, // "from" | "to" - Indicates if this is the source or destination token
token, // Selected token information
chain, // Selected chain information
isSelected, // is token selected
compact, // Whether to show compact view
onClick, // Handler for when the selector is clicked
}) => {
return
;
};
```
### Token Amount Display
```tsx
import { type TokenAmountPriceProps } from "@gluex/widget";
export const CustomTokenAmountPrice = ({
amount, // Token amount
token, // Token information
tokenPrice, // Current token price
isLoading, // Whether data is loading
}: TokenAmountPriceProps) => {
return
{/* Your custom amount display UI */}
;
};
```
### Transaction Details
```tsx
import { type TransactionDetailsProps } from "@gluex/widget";
export const CustomTransactionDetails = ({
tokens, // From/To token information
fees, // Network, protocol, and total fees
minReceived, // Minimum amount to receive
providers, // List of providers used
}: TransactionDetailsProps) => {
return
{/* Your custom transaction details UI */}
;
};
```
### Completed Transaction
```tsx
import { type CompletedTransactionDetailsProps } from "@gluex/widget";
export const CustomCompletedTransaction = ({
tokens, // From/To token information
amounts, // Transaction amounts
fees, // Transaction fees
transaction, // Transaction details with hash and link
providers, // List of providers used
showRouteSection, // Whether to show route section
showDetailsSection, // Whether to show details section
}: CompletedTransactionDetailsProps) => {
return
{/* Your custom completed transaction UI */}
;
};
```
# Events
Source: https://docs.gluex.xyz/build-with-gluex/widget/events
The GlueX Widget provides a comprehensive event system through the `useWidgetEvents` hook that allows you to subscribe to various widget events.
These hooks helps you retrieve helpful information and to track swap progress, monitor quote execution, observe chain and token selections, track UI interactions and more
We actively work on extending the list of available widget events. If you need
support for a specific event, please contact us via our [support
channels](https://bento.me/gluex-protocol)
## Setup
First, import the necessary types and hooks:
```tsx
import {
WidgetEvent,
useWidgetEvents,
type Route,
type RouteExecutionUpdate,
} from "@gluex/widget";
export const WidgetEvents = () => {
const events = useWidgetEvents();
useEffect(() => {
const onRouteExecutionStarted = (route: Route) => {
// Handle route start
};
const onRouteExecutionUpdated = (update: RouteExecutionUpdate) => {
// Handle route updates
};
const onRouteExecutionCompleted = (route: Route) => {
// Handle route completion
};
const onRouteExecutionFailed = (update: RouteExecutionUpdate) => {
// Handle route failure
};
events.on(WidgetEvent.RouteExecutionStarted, onRouteExecutionStarted);
events.on(WidgetEvent.RouteExecutionUpdated, onRouteExecutionUpdated);
events.on(WidgetEvent.RouteExecutionCompleted, onRouteExecutionCompleted);
events.on(WidgetEvent.RouteExecutionFailed, onRouteExecutionFailed);
// Cleanup subscriptions
return () => {
events.all.clear();
};
}, [events]);
return <>>;
};
```
For optimal performance and to avoid unnecessary re-renders or unexpected
behavior in your main widget component, we recommend using the
`useWidgetEvents` hook outside of the component where the primary
`GlueXWidget` is rendered
## Event Type
The widget emits various events that you can listen to:
```tsx
enum WidgetEvent {
// Route Events
RouteExecutionStarted = "routeExecutionStarted" // When a route starts executing
RouteExecutionUpdated = "routeExecutionUpdated" // Progress updates during execution
RouteExecutionCompleted = "routeExecutionCompleted" // When route completes successfully
RouteExecutionFailed = "routeExecutionFailed" // When route execution fails
RouteHighValueLoss = "routeHighValueLoss" // High value loss detection
RouteSelected = "routeSelected" // When a route is selected
// Chain and Token Events
SourceChainTokenSelected = "sourceChainTokenSelected"
DestinationChainTokenSelected = "destinationChainTokenSelected"
// Wallet Events
WalletConnected = "walletConnected"
SendToWalletToggled = "sendToWalletToggled"
// UI and Form Events
PageEntered = "pageEntered"
FormFieldChanged = "formFieldChanged"
SettingUpdated = "settingUpdated"
TokenSearch = "tokenSearch"
TransactionError = "transactionError"
}
```
## Available Events
### Route Events
#### RouteExecutionStarted
Fires when the user clicks the "Start swapping" or "Start bridging" button, initiating the execution of a selected route. This marks the beginning of the cross-chain transaction process.
**Payload**: `Route`
```typescript
interface Route {
id: string; // Unique identifier for this route instance
fromChainId: number; // Numeric ID of source chain (e.g. 1 = Ethereum, 137 = Polygon)
fromAddress?: string; // Wallet address tokens are taken from (if pre-filled)
fromToken: TokenWithPriceAndAmount & WithAdditionalDetails; // Source token metadata + price/amount info
fromAmount: string; // Amount of source token user requested (in token units)
effectiveFromAmount?: string; // Actual amount used after fee/slippage adjustments
fromAmountUSD: string; // USD value of `fromAmount`
toChainId: number; // Numeric ID of destination chain
toAddress?: string; // Destination wallet address (if sending to different wallet)
toToken: TokenWithPriceAndAmount & WithAdditionalDetails; // Destination token metadata + price/amount info
toAmount: string; // Expected amount of destination token
toAmountReceive: string; // Amount that will actually arrive (after fees)
toAmountMin: string; // Minimum acceptable output (slippage protection floor)
toAmountUSD: string; // USD value of `toAmount`
gasCostUSD?: string; // Estimated gas cost in USD
steps: GlueXStep[]; // Ordered list of low-level execution steps (bridge, swap, etc.)
}
```
**Handler**:
```typescript
const onRouteExecutionStarted = (route: Route) => {
console.log("Route execution started:", route.id);
console.log(
`Converting ${route.fromAmount} ${route.fromToken.symbol} on chain ${route.fromChainId}`
);
console.log(
`Expected to receive ${route.toAmountReceive} ${route.toToken.symbol} on chain ${route.toChainId}`
);
};
```
#### RouteExecutionUpdated
Fires during route execution to provide real-time progress updates. Contains the current process step and updated route information, allowing you to track execution progress and display status to users.
**Payload**: `RouteExecutionUpdate`
```typescript
interface RouteExecutionUpdate {
route: Route; // Updated route object with current state
process: Process; // Current execution process details
}
interface Process {
id: string; // Unique process identifier
status: ProcessStatus; // Current status (pending, running, completed, failed)
type: ProcessType; // Type of process (swap, bridge, approval, etc.)
txHash?: string; // Transaction hash if available
message?: string; // Human-readable status message
error?: string; // Error message if process failed
}
```
**Handler**:
```typescript
const onRouteExecutionUpdated = (update: RouteExecutionUpdate) => {
const { route, process } = update;
console.log(`Route ${route.id} update:`, process.status);
console.log(`Current step: ${process.type}`);
if (process.txHash) {
console.log(`Transaction hash: ${process.txHash}`);
}
};
```
#### RouteExecutionCompleted
Fires when a route execution completes successfully. All steps have been executed and the user has received their destination tokens.
**Payload**: `Route`
**Handler**:
```typescript
const onRouteExecutionCompleted = (route: Route) => {
console.log("Route execution completed successfully:", route.id);
console.log(
`Successfully converted ${route.fromAmount} ${route.fromToken.symbol} to ${route.toAmountReceive} ${route.toToken.symbol}`
);
// Show success notification
showSuccessNotification(
`Swap completed! You received ${route.toAmountReceive} ${route.toToken.symbol}`
);
};
```
#### RouteExecutionFailed
Fires when route execution fails at any step. Provides details about the failure through the process object.
**Payload**: `RouteExecutionUpdate`
**Handler**:
```typescript
const onRouteExecutionFailed = (update: RouteExecutionUpdate) => {
const { route, process } = update;
console.error("Route execution failed:", route.id);
console.error("Failure reason:", process.error);
// Show error notification to user
showErrorNotification(
`Swap failed: ${process.error || "Unknown error occurred"}`
);
};
```
#### RouteHighValueLoss
Fires when the system detects a significant value loss (high slippage, fees, or unfavorable market conditions) and displays a warning to the user.
**Payload**: `RouteHighValueLossUpdate`
```typescript
interface RouteHighValueLossUpdate {
fromAmountUSD: number; // USD value of input amount
toAmountUSD: number; // USD value of expected output
gasCostUSD?: number; // Estimated gas costs in USD
feeCostUSD?: number; // Protocol/bridge fees in USD
valueLoss: number; // Total value loss as percentage (0.05 = 5%)
}
```
**Handler**:
```typescript
const onRouteHighValueLoss = (valueLoss: RouteHighValueLossUpdate) => {
console.warn("High value loss detected:");
console.warn(`Input: $${valueLoss.fromAmountUSD}`);
console.warn(`Output: $${valueLoss.toAmountUSD}`);
console.warn(`Total loss: ${(valueLoss.valueLoss * 100).toFixed(2)}%`);
// Show warning modal
showHighValueLossWarning({
inputValue: valueLoss.fromAmountUSD,
outputValue: valueLoss.toAmountUSD,
lossPercentage: valueLoss.valueLoss,
gasCost: valueLoss.gasCostUSD,
fees: valueLoss.feeCostUSD,
});
};
```
#### RouteSelected
Fires when a user selects a specific route from the available options. This happens before execution begins.
**Payload**: `RouteSelected`
```typescript
interface RouteSelected {
route: Route; // The selected route object
}
```
**Handler**:
```typescript
const onRouteSelected = (selection: RouteSelected) => {
const { route } = selection;
console.log("Route selected:", route.id);
console.log(
`Route details: ${route.fromToken.symbol} → ${route.toToken.symbol}`
);
console.log(`Estimated output: ${route.toAmount} ${route.toToken.symbol}`);
};
```
### Token and Chain Selection Events
#### SourceChainTokenSelected
Fires when the user selects or changes the source chain and token combination.
**Payload**: `ChainTokenSelected`
```typescript
interface ChainTokenSelected {
chainId: Chain["id"]; // Numeric chain ID (e.g., 1 for Ethereum)
tokenAddress: string; // Token contract address (or "0x0" for native tokens)
}
```
**Handler**:
```typescript
const onSourceChainTokenSelected = (selection: ChainTokenSelected) => {
console.log(
`Source selected: Token ${selection.tokenAddress} on chain ${selection.chainId}`
);
};
```
#### DestinationChainTokenSelected
Fires when the user selects or changes the destination chain and token combination.
**Payload**: `ChainTokenSelected`
**Handler**:
```typescript
const onDestinationChainTokenSelected = (selection: ChainTokenSelected) => {
console.log(
`Destination selected: Token ${selection.tokenAddress} on chain ${selection.chainId}`
);
};
```
### Wallet Events
#### WalletConnected
Fires when a user successfully connects their wallet through the widget's internal wallet management UI.
**Payload**: `WalletConnected`
```typescript
interface WalletConnected {
address?: string; // Connected wallet address
chainId?: number; // Currently connected chain ID
chainType?: ChainType; // Type of chain (EVM, Solana, etc.)
}
```
**Handler**:
```typescript
const onWalletConnected = (wallet: WalletConnected) => {
console.log("Wallet connected:", wallet.address);
console.log("Connected to chain:", wallet.chainId);
};
```
#### SendToWalletToggled
Fires when the user toggles the "send to different wallet" option by clicking the wallet icon next to the action button.
**Payload**: `boolean` (true if enabled, false if disabled)
**Handler**:
```typescript
const onSendToWalletToggled = (isEnabled: boolean) => {
console.log("Send to wallet toggled:", isEnabled);
if (isEnabled) {
// Show destination wallet input
showDestinationWalletInput();
console.log("User can now specify a different destination wallet");
} else {
// Hide destination wallet input
hideDestinationWalletInput();
console.log("Tokens will be sent to connected wallet");
}
};
```
### UI and Navigation Events
#### PageEntered
Fires when the user navigates to a different page within the widget.
**Payload**: `NavigationRouteType` (string indicating the page/route name)
**Handler**:
```typescript
const onPageEntered = (page: NavigationRouteType) => {
console.log("User navigated to page:", page);
};
```
#### ReviewTransactionPageEntered
Fires when the user enters the transaction review page by clicking on a specific route.
**Payload**: `Route` (optional - the route being reviewed)
**Handler**:
```typescript
const onReviewTransactionPageEntered = (route?: Route) => {
console.log("User entered transaction review page");
if (route) {
console.log("Reviewing route:", route.id);
console.log(
`Route summary: ${route.fromAmount} ${route.fromToken.symbol} → ${route.toAmount} ${route.toToken.symbol}`
);
// Pre-populate review page with route details
populateReviewPage(route);
}
// Track review page entry
analytics.track("review_page_entered", {
routeId: route?.id,
hasRoute: !!route,
});
// Show transaction warnings or additional info
showTransactionWarnings(route);
};
```
### Form and Settings Events
#### FormFieldChanged
Fires whenever any form field value changes in the widget (amount input, slippage settings, etc.).
**Payload**: `FormFieldChanged`
```typescript
type FormFieldChanged = {
[K in keyof DefaultValues]: {
fieldName: K; // Name of the changed field
newValue: DefaultValues[K]; // New value
oldValue: DefaultValues[K]; // Previous value
};
}[keyof DefaultValues];
```
**Handler**:
```typescript
const onFormFieldChanged = (change: FormFieldChanged) => {
console.log(`Form field "${change.fieldName}" changed:`);
console.log(` Old value: ${change.oldValue}`);
console.log(` New value: ${change.newValue}`);
// Field-specific logic
switch (change.fieldName) {
case "amount":
// Recalculate routes when amount changes
if (change.newValue && parseFloat(change.newValue) > 0) {
debounceRecalculateRoutes();
}
break;
case "slippage":
// Update slippage warnings
validateSlippageSetting(change.newValue);
break;
}
};
```
#### SettingUpdated
Fires when any widget setting is updated (theme, slippage tolerance, gas price, etc.).
**Payload**: `SettingUpdated`
```typescript
interface SettingUpdated {
setting: K; // Name of the updated setting
newValue: SettingsProps[K]; // New setting value
oldValue: SettingsProps[K]; // Previous setting value
newSettings: SettingsProps; // Complete updated settings object
oldSettings: SettingsProps; // Complete previous settings object
}
```
**Handler**:
```typescript
const onSettingUpdated = (update: SettingUpdated) => {
console.log(`Setting "${update.setting}" updated:`);
console.log(` Old value: ${update.oldValue}`);
console.log(` New value: ${update.newValue}`);
};
```
#### TokenSearch
Fires when the user searches for tokens in the token selection interface.
**Payload**: `TokenSearch`
```typescript
interface TokenSearch {
value: string; // Search query entered by user
tokens: TokenWithPriceAndAmount[]; // Array of tokens matching the search
}
```
**Handler**:
```typescript
const onTokenSearch = (search: TokenSearch) => {
console.log(`User searched for: "${search.value}"`);
console.log(`Found ${search.tokens.length} matching tokens`);
// Display search results
displaySearchResults(search.tokens);
};
```
### Error and Support Events
#### TransactionError
Fires when a transaction error occurs during route execution, providing detailed error information for debugging and support.
**Payload**: `TransactionErrorEvent`
```typescript
interface TransactionErrorEvent {
supportId?: string; // Unique support ID for tracking
errorCode: string; // Standardized error code
errorMessage: string; // Human-readable error message
chainId?: number; // Chain where error occurred
tokenSymbol?: string; // Token involved in failed transaction
toolName?: string; // Bridge/DEX tool that failed
stepType?: string; // Type of step that failed (swap, bridge, approval)
txHash?: string; // Transaction hash if available
timestamp: string; // ISO timestamp of error
}
```
**Handler**:
```typescript
const onTransactionError = (error: TransactionErrorEvent) => {
console.error("Transaction error occurred:");
console.error(` Error code: ${error.errorCode}`);
console.error(` Message: ${error.errorMessage}`);
console.error(` Support ID: ${error.supportId}`);
if (error.txHash) {
console.error(` Transaction: ${error.txHash}`);
}
// Show user-friendly error message
showErrorNotification({
title: "Transaction Failed",
message: error.errorMessage,
supportId: error.supportId,
actionButton: "Contact Support",
});
};
```
#### ContactSupport
Fires when the user clicks the "Contact support" button, typically from the transaction details page or error states.
**Payload**: `ContactSupport`
```typescript
interface ContactSupport {
supportId?: string; // Unique identifier for support context
}
```
**Handler**:
```typescript
const onContactSupport = (support: ContactSupport) => {
console.log("User requesting support");
if (support.supportId) {
console.log(`Support ID: ${support.supportId}`);
}
};
```
#### LowAddressActivityConfirmed
Fires when the user confirms they want to proceed despite low activity on the destination address, typically shown as a security warning.
**Payload**: `LowAddressActivityConfirmed`
```typescript
interface LowAddressActivityConfirmed {
address: string; // The address with low activity
chainId: number; // Chain ID where address has low activity
}
```
**Handler**:
```typescript
const onLowAddressActivityConfirmed = (
confirmation: LowAddressActivityConfirmed
) => {
console.log("User confirmed low activity address:");
console.log(` Address: ${confirmation.address}`);
console.log(` Chain ID: ${confirmation.chainId}`);
};
```
# Features
Source: https://docs.gluex.xyz/build-with-gluex/widget/features
### Core Capabilities
* **Extensive Protocol Support**: The GlueX Widget natively supports all tokens, chains and liquidity modules integrated into GlueX, ensuring broad access to the DeFi ecosystem giving access to a vast array of assets and networks without additional setup
* **Comprehensive DeFi Operations**: Beyond simple swaps, the widget facilitates a wide spectrum of DeFi activities, including:
* Routing: Intelligent routing across various protocols to find the most optimal paths for transactions
* Swap: Token exchanges across all supported chains
* Bridge: Asset transfers between diverse networks and ecosystems
* Lend and Borrow: Access to decentralized lending and borrowing protocols
* Stake, Unstake, Restake: Participate in staking programs with full control over your assets
* Mint and Redeem: Interact with various token minting and redemption mechanisms
* Farm Yield: Engage in yield farming strategies to maximize returns
* Provide Liquidity: Contribute to liquidity pools and earn fees
* And many more DeFi operations
* **Flexible Display Variants**: The GlueX Widget offers flexible display options to fit seamlessly into any application layout:
* **Compact Mode**: Ideal for integrating into smaller sections of your application without overwhelming the UI
* **Drawer Mode**: Provides a sleek, slide-out interface that integrates smoothly into existing designs, perfect for a non-intrusive experience
* **Full-Page Mode**: Offers a comprehensive, dedicated view for complex interactions or a primary DeFi experience within your application
* **Granular Control over Assets and Networks**: Developers have precise control over the widget's offerings, with options to explicitly **allow or deny certain chains and tokens** allowing you to tailor the user experience to your specific application's needs
* **Liquidity Module Filtering**: Advanced filtering capabilities enabling you to **select and display only specific liquidity modules** that are most relevant to your application's focus or user base
* **Extensive Theming System**:
* **32+ Preconfigured Themes**: Choose from a rich library of professionally designed themes to instantly match your brand's aesthetic
* **Deep Customization Options**: Go beyond themes with granular control over colors, typography, shapes, spacing and every visual aspect to create a look and feel that perfectly aligns with your brand identity
* **Dark Mode Support**: Integrates with user system preferences for dark mode, ensuring a comfortable viewing experience in all lighting conditions and enhancing user accessibility
* **Configurable Components**: Show, hide, or customize any individual component within the widget. This allows for a **highly modular and adaptable user interface**, giving you complete flexibility over its appearance and functionality
* **Wallet Integration**: Supports **smooth integration with any wallet provider** of your choice, ensuring broad compatibility
* **Industry Standard Adherence**: Built with adherence to top industry standards:
* **EIP-5792**: For batched transactions and improved transaction management
* **ERC-2612**: Enabling gasless approvals for ERC20 tokens
* **EIP-712**: For structured data signing
* **Permit2**: For efficient and secure token approvals
* **Comprehensive Transaction Management**:
* **Real-time Transaction Progress View**: Users can easily monitor the status of their transactions from initiation to completion
* **Detailed Transaction History**: Provides a record of past transactions for easy tracking, auditing and reference
* **Wallet Health Checks**: Includes automated checks to ensure connected wallets are in a healthy state and compatible with the ongoing operations, preventing potential issues
* **Route Settings**: Flexibility to configure their preferred route settings, such as **slippage tolerance, gas preferences and transaction speed**
* **Wide Framework Compatibility**: Extensively tested for compatibility with leading web development frameworks:
* [React](/build-with-gluex/widget/integration/integrate-widget-with-react)
* [Next](/build-with-gluex/widget/integration/integrate-widget-with-nextjs)
* [Vite](/build-with-gluex/widget/integration/integrate-widget-with-vite)
* [Gatsby](/build-with-gluex/widget/integration/integrate-widget-with-gatsby)
* [Vue](/build-with-gluex/widget/integration/integrate-widget-with-vue)
* [Rainbowkit](/build-with-gluex/widget/integration/integrate-widget-with-rainbowkit)
We will roll out support to other frameworks in the future based on their
demand
# Internationalization
Source: https://docs.gluex.xyz/build-with-gluex/widget/i18n
\[COMING SOON ...]
# Installation and Quickstart
Source: https://docs.gluex.xyz/build-with-gluex/widget/installation
Easy installation to go onchain under 5 minutes
## Installation
To begin, install the necessary packages. We recommend using the latest stable versions for optimal performance and security
```bash npm
npm install wagmi @tanstack/react-query @gluex/widget @gluex/sdk
```
```bash yarn
yarn add wagmi @tanstack/react-query @gluex/widget @gluex/sdk
```
```bash pnpm
pnpm add wagmi @tanstack/react-query @gluex/widget @gluex/sdk
```
```bash bun
bun add wagmi @tanstack/react-query @gluex/widget @gluex/sdk
```
## Quickstart
Before you start with integration, you'll need to obtain your API Key and Integrator ID. These are essential for authenticating your application and tracking its usage with GlueX.
You can easily generate these credentials by logging into the [GlueX Portal](https://portal.gluex.xyz).
Once you have your credentials, you can integrate the GlueX Widget with just a few lines of code:
```typescript
import { GlueXWidget, WidgetConfiguration } from "@gluex/widget"
const config: Partial = {
apiKey: enviroment.GLUEX_API_KEY,
integrator: enviroment.INTEGRATOR_ID,
};
export const WidgetPage = () => {
return ;
};
```
# Installing the GlueX widget
Source: https://docs.gluex.xyz/build-with-gluex/widget/integration/installing-the-widget
Learn how to seamlessly integrate the GlueX Widget into your web application to enable powerful DeFi functionalities for your users
The GlueX Widget provides a ready-to-use, customizable UI component that simplifies the integration of advanced DeFi operations (like token swaps, bridge, lend, stake, zap and swidge) directly into your application. This guide walks you through the general installation process, covering prerequisites and package installation
## Prerequisites
Before you begin installing the GlueX widget, please ensure you have the following in place:
* **Integrator ID and API key**: You must have registered for and obtained your unique Integrator ID and API Key from the **[GlueX Developer Portal](https://portal.gluex.xyz)**. These credentials are essential for authenticating your API requests and for tracking your usage and any partner specific configurations (like fees)
* **Node.js and package manager**: Ensure you have a recent version of Node.js installed on your system, along with its package manager (npm/yarn/pnpm/bun)
## Installation
### Install the package
The GlueX widget is distributed as an npm package. It relies on `wagmi` and `@tanstack/react-query` as peer dependencies for managing blockchain interactions and data fetching, respectively.
Use your preferred package manager to install the widget, SDK and their essential peer dependencies:
```bash npm
npm install wagmi @tanstack/react-query @gluex/widget @gluex/sdk
```
```bash yarn
yarn add wagmi @tanstack/react-query @gluex/widget @gluex/sdk
```
```bash pnpm
pnpm add wagmi @tanstack/react-query @gluex/widget @gluex/sdk
```
```bash bun
bun add wagmi @tanstack/react-query @gluex/widget @gluex/sdk
```
### Update dependencies (if necessary)
The widget utilizes `wagmi` and `@tanstack/react-query`. If your project already includes these packages, it is crucial to ensure they are updated to versions compatible with the GlueX widget to avoid conflicts or unexpected behavior
> For comprehensive guidance on upgrading `wagmi` to its latest compatible version, please refer to the official [wagmi migration guide](https://wagmi.sh/react/migration-guide)
## Next Steps
Once the necessary packages are installed, the next crucial step is to integrate the GlueX Widget into your specific application framework. We provide dedicated guides to streamline this process for popular development environments:
* [React Integration Guide](/build-with-gluex/widget/integration/integrate-widget-with-react)
* [NextJS Integration Guide](/build-with-gluex/widget/integration/integrate-widget-with-nextjs)
* [Vite Integration Guide](/build-with-gluex/widget/integration/integrate-widget-with-vite)
* [Gatsby Integration Guide](/build-with-gluex/widget/integration/integrate-widget-with-gatsby)
* [Rainbowkit Integration Guide](/build-with-gluex/widget/integration/integrate-widget-with-rainbowkit)
* Vue Integration Guide (coming soon)
Choose the guide that best matches your project's technical stack to proceed with the integration
## Support
If you have any questions, require assistance during installation or need further guidance on integrating, please join our our [official Telegram channel](https://t.me/+_VmO_gIrNjxiZWE0)
# Integrate GlueX widget as an Iframe
Source: https://docs.gluex.xyz/build-with-gluex/widget/integration/integrate-the-widget-as-iframe
Learn how to integrate the widget into your application as an Iframe, enabling users to perform swaps, bridge assets, lend, stake, zap and swidge directly within the application
While the GlueX Widget is primarily designed as a modular web component for direct integration into popular frontend frameworks (React, Next.js, Gatsby, Vue, etc), it can also be effectively embedded into any web application as an `