### Fetch Token Pricing Data with Axios (JavaScript)
Source: https://docs.odos.xyz/build/enterprise-api
Example using the Axios library to make a GET request to the token pricing endpoint. Ensure your API key and chain ID are correctly set. The response includes pricing information for a specified token.
```javascript
const axios = require('axios');
const apiKey = 'ebf0c0c0-bacd-4490-8983-3e8b7368bc73'; // Replace with your actual API key provided by Odos
const chainId = '1'; //
const tokenAddress = '0xD533a949740bb3306d119CC777fa900bA034cd52';
axios.get(`https://enterprise-api.odos.xyz/pricing/token/${chainId}/${tokenAddress}`, {
headers: { 'x-api-key': apiKey }})
```
--------------------------------
### Fetch Token Pricing Data with cURL
Source: https://docs.odos.xyz/build/enterprise-api
Example using cURL to make a GET request to the token pricing endpoint. This demonstrates how to include the API key in the request headers for authentication.
```bash
curl -X GET "https://enterprise-api.odos.xyz/pricing/token/1/0xD533a949740bb3306d119CC777fa900bA034cd52" \
-H "x-api-key: ebf0c0c0-bacd-4490-8983-3e8b7368bc73"
```
--------------------------------
### Install python-dotenv for Python
Source: https://docs.odos.xyz/api/authentication
Install the python-dotenv package to manage environment variables securely in your Python project.
```bash
pip install python-dotenv
```
--------------------------------
### Install dotenv for Node.js
Source: https://docs.odos.xyz/api/authentication
Install the dotenv package to manage environment variables securely in your JavaScript project.
```bash
npm install dotenv
```
--------------------------------
### Example Transaction Response Structure
Source: https://docs.odos.xyz/api/sor/execute
This is an example of the JSON structure returned after a transaction simulation or execution, showing details like block number, gas estimates, and transaction parameters.
```json
{
"blockNumber": 23619524,
"gasEstimate": 214504,
"gasEstimateValue": 1.12,
"transaction": {
"to": "0x221a4c9e54baebd678ff1823e4fca2ac3685ca64",
"from": "0x5AD89031aAfFe2F82dF3b98Fa4181E08B5dCFF9C",
"data": "0x12ab34cd...",
"chainId": 8453,
"gas": 235000,
"gasPrice": "1000000000",
"value": "0",
"nonce": 112
},
"simulation": {
"isSuccess": true,
"amountsOut": ["1833893"],
"simGasUsed": 203421,
"gasEstimate": 214504,
"simulationError": null
}
}
```
--------------------------------
### Path Visualization Configuration Example
Source: https://docs.odos.xyz/build/pathviz
Use this JSON object to configure the appearance of the path visualization, including colors for links, nodes, and text, as well as the dimensions of the diagram. All attributes are optional.
```json
{
"linkColors": ["#FF0000", "#FFFF00", "#FFA500"],
"nodeColor": "#708090",
"nodeTextColor": "#E2E5E8",
"legendTextColor": "#C5CCD2",
"width": 1000,
"height": 800
}
```
--------------------------------
### Example Odos v3 Request Body
Source: https://docs.odos.xyz/api/permit2/execute
This is an example of the JSON request body used for Odos v3 swaps, including chain ID, user address, path ID, permit2 signature, and simulation flag.
```json
{
"chainId": 8453,
"userAddr": "0x123...",
"pathId": "abcd1234...",
"permit2Signature": "0xabc...",
"simulate": false
}
```
--------------------------------
### Execute Transaction in JavaScript
Source: https://docs.odos.xyz/api/sor/execute
Use this snippet to sign and send a transaction using Web3.js. Ensure you have the 'web3' library installed and your private key configured in environment variables.
```javascript
import Web3 from 'web3';
import 'dotenv/config';
const web3 = new Web3('https://base.llamarpc.com');
const tx = assembled.transaction;
const signedTx = await web3.eth.accounts.signTransaction(tx, process.env.PRIVATE_KEY);
const receipt = await web3.eth.sendSignedTransaction(signedTx.rawTransaction);
console.log('Transaction hash:', receipt.transactionHash);
```
--------------------------------
### Create Interactive Button with JSX
Source: https://docs.odos.xyz/blog/mdx-blog-post
Use JSX within your blog posts to create interactive React components like buttons. This example shows a simple button that triggers an alert on click.
```jsx
```
--------------------------------
### Create .env file
Source: https://docs.odos.xyz/api/authentication
Create a .env file in your project's root directory to store environment-specific variables.
```bash
touch .env
```
--------------------------------
### Execute Transaction with Python (Web3.py)
Source: https://docs.odos.xyz/api/permit2/execute
This Python snippet demonstrates how to sign and send a transaction using Web3.py. It requires the Web3 library and access to your private key via environment variables.
```python
from web3 import Web3
import os
w3 = Web3(Web3.HTTPProvider("https://base.llamarpc.com"))
tx = swap_data["transaction"]
signed_tx = w3.eth.account.sign_transaction(tx, os.getenv("PRIVATE_KEY"))
tx_hash = w3.eth.send_raw_transaction(signed_tx.rawTransaction)
print("Transaction hash:", w3.to_hex(tx_hash))
```
--------------------------------
### Display Odos Path Visualization in HTML
Source: https://docs.odos.xyz/build/pathviz
This HTML and JavaScript example demonstrates fetching quote data with path visualization enabled and setting the base64 encoded image as the source for an img tag. Ensure your server is configured to handle CORS requests if running locally.
```html
Odos Path Viz Example
```
--------------------------------
### Assemble Transaction with JavaScript
Source: https://docs.odos.xyz/api/zaps/assemble
This JavaScript snippet demonstrates how to assemble a transaction using the /sor/assemble endpoint. It utilizes fetch for the POST request and requires your ODOS_API_KEY to be set in your environment variables. Remember to replace placeholder values.
```javascript
import 'dotenv/config';
const assembleUrl = 'https://enterprise-api.odos.xyz/sor/assemble';
const assembleRequestBody = {
userAddr: '0x...', // the checksummed address used to generate the quote
pathId: quote.pathId, // Replace with the pathId from quote response (Step 1)
simulate: true, // set to true if not performing your own gas estimation
};
const response = await fetch(assembleUrl, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'x-api-key': process.env.ODOS_API_KEY
},
body: JSON.stringify(assembleRequestBody),
});
if (response.ok) {
const assembledTransaction = await response.json();
console.log(assembledTransaction);
} else {
console.error('Error assembling transaction:', response.statusText);
}
```
--------------------------------
### Example Quote API Response
Source: https://docs.odos.xyz/api/sor/quote
This is an example of a successful response from the ODOS Quote API v3, containing details like pathId, gas estimates, and price impact. The 'pathId' is crucial for assembling the final transaction.
```json
{
"pathId": "f2c16f4a3e94a12b9f1cce13e332cc4c",
"outAmounts": ["2389819"],
"gasEstimate": 231122,
"priceImpact": 0.023,
"percentDiff": -0.15,
"traceId": "13b8c84d-4d21-4d2b-8579-71b1f8c0c0c7"
}
```
--------------------------------
### Assemble Transaction Request - Python
Source: https://docs.odos.xyz/api/sor/assemble
This Python script demonstrates how to assemble a transaction using the /sor/assemble endpoint. It sends a POST request with user address, pathId, and simulation flag. The API key should be loaded from environment variables.
```python
import os
import requests
from dotenv import load_dotenv
load_dotenv()
assemble_url = 'https://enterprise-api.odos.xyz/sor/assemble'
assemble_request_body = {
"userAddr": "0x...",
"pathId": quote["pathId"],
"simulate": True
}
headers = {
"Content-Type": "application/json",
"x-api-key": os.getenv("ODOS_API_KEY")
}
response = requests.post(assemble_url, json=assemble_request_body, headers=headers)
assembled = response.json()
print(assembled["transaction"])
```
--------------------------------
### Getting USD price of a token
Source: https://docs.odos.xyz/api/pricing/price
Retrieve the USD price for a specific token by providing its chain ID and contract address.
```APIDOC
## GET /pricing/token/{chainId}/{tokenAddress}
### Description
Retrieves the USD price of a specific token on a given blockchain.
### Method
GET
### Endpoint
/pricing/token/{chainId}/{tokenAddress}
### Parameters
#### Path Parameters
- **chainId** (integer) - Required - The ID of the blockchain network.
- **tokenAddress** (string) - Required - The checksummed contract address of the token.
#### Request Headers
- **x-api-key** (string) - Required - Your Odos API key.
### Response
#### Success Response (200)
- **price** (number) - The current USD price of the token.
- **decimals** (integer) - The number of decimals for the token.
- **symbol** (string) - The symbol of the token.
#### Response Example
```json
{
"price": 1950.50,
"decimals": 18,
"symbol": "ETH"
}
```
```
--------------------------------
### Getting price of multiple tokens
Source: https://docs.odos.xyz/api/pricing/price
Retrieve pricing data for multiple tokens in a single call by providing a comma-separated list of token addresses.
```APIDOC
## GET /pricing/tokens
### Description
Retrieves pricing data for multiple tokens in a single call.
### Method
GET
### Endpoint
/pricing/tokens
### Parameters
#### Query Parameters
- **chainId** (integer) - Required - The ID of the blockchain network.
- **tokens_addresses** (string) - Required - A comma-separated list of checksummed token contract addresses.
#### Request Headers
- **x-api-key** (string) - Required - Your Odos API key.
### Response
#### Success Response (200)
- A JSON object where keys are token addresses and values are objects containing pricing data for each token.
- **price** (number) - The current USD price of the token.
- **decimals** (integer) - The number of decimals for the token.
- **symbol** (string) - The symbol of the token.
#### Response Example
```json
{
"0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48": {
"price": 1.0005,
"decimals": 6,
"symbol": "USDC"
},
"0xdAC17F958D2ee523a2206206994597C13D831ec7": {
"price": 0.9998,
"decimals": 6,
"symbol": "USDT"
}
}
```
```
--------------------------------
### Execute Transaction with Web3.js
Source: https://docs.odos.xyz/api/permit2/execute
Use this snippet to sign and send a transaction using Web3.js. Ensure you have imported Web3 and configured your environment variables for the private key.
```javascript
import Web3 from 'web3';
import 'dotenv/config';
const web3 = new Web3('https://base.llamarpc.com');
const tx = swapData.transaction;
const signed = await web3.eth.accounts.signTransaction(tx, process.env.PRIVATE_KEY);
const receipt = await web3.eth.sendSignedTransaction(signed.rawTransaction);
console.log('Transaction Hash:', receipt.transactionHash);
```
--------------------------------
### Generate Token Swap Quote (Python)
Source: https://docs.odos.xyz/api/sor/quote
This Python example demonstrates how to request an optimized token swap route from the ODOS Quote API v3. It requires the 'requests' and 'python-dotenv' libraries. Set your ODOS_API_KEY in a .env file.
```python
import requests
import os
from dotenv import load_dotenv
load_dotenv()
quote_url = 'https://enterprise-api.odos.xyz/sor/quote/v3'
quote_request_body = {
"chainId": 8453,
"inputTokens": [
{"tokenAddress": "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913", "amount": "10000000"}
],
"outputTokens": [
{"tokenAddress": "0xca73ed1815e5915489570014e024b7EbE65dE679", "proportion": 1}
],
"userAddr": "0x...",
"slippageLimitPercent": 0.3,
"compact": True
}
headers = {
"Content-Type": "application/json",
"x-api-key": os.getenv("ODOS_API_KEY")
}
response = requests.post(quote_url, json=quote_request_body, headers=headers)
quote = response.json()
print(quote)
```
--------------------------------
### Get USD Price of a Single Token
Source: https://docs.odos.xyz/api/pricing/price
Retrieve the USD price for a specific token on a given chain. Ensure your ODOS_API_KEY is set in your environment variables.
```python
import os, requests
from dotenv import load_dotenv
load_dotenv()
token_price_base_url = "https://enterprise-api.odos.xyz/pricing/token"
chain_id = 1 # the chain id the token/asset is from
token_address = "0x..." # the checksummed address of the token/asset to get a price for
headers = { "x-api-key": os.getenv("ODOS_API_KEY") }
response = requests.get(f"{token_price_base_url}/{chain_id}/{token_address}", headers=headers)
if response.status_code == 200:
token_price = response.json()
print(token_price)
else:
print(f"Error getting token price: {response.json()}")
```
--------------------------------
### GET /pricing/currencies
Source: https://docs.odos.xyz/api/pricing/price
Retrieves a list of available currency names and their corresponding API codes. The 'id' field from each currency entry can be used as a parameter for other pricing endpoints.
```APIDOC
## GET /pricing/currencies
### Description
Retrieves a list of available currency names and their corresponding API codes. The 'id' field from each currency entry can be used as a parameter for other pricing endpoints.
### Method
GET
### Endpoint
/pricing/currencies
### Parameters
#### Query Parameters
None
### Request Example
None
### Response
#### Success Response (200)
- **currencies** (array) - A list of currency objects, each containing an 'id' and 'name'.
#### Response Example
```json
[
{
"id": "USD",
"name": "United States Dollar"
},
{
"id": "EUR",
"name": "Euro"
}
]
```
```
--------------------------------
### Getting price of a token in different currencies
Source: https://docs.odos.xyz/api/pricing/price
The Odos Pricing API supports fetching prices for supported crypto assets in various currencies beyond just USD.
```APIDOC
## GET /pricing/token/{chainId}/{tokenAddress}
### Description
Retrieves the price of a specific token in various supported fiat currencies, in addition to USD.
### Method
GET
### Endpoint
/pricing/token/{chainId}/{tokenAddress}
### Parameters
#### Path Parameters
- **chainId** (integer) - Required - The ID of the blockchain network.
- **tokenAddress** (string) - Required - The checksummed contract address of the token.
#### Query Parameters
- **vsCurrencies** (string) - Optional - A comma-separated list of currency symbols (e.g., "eur,gbp,jpy") to get prices in. Defaults to USD if not specified.
#### Request Headers
- **x-api-key** (string) - Required - Your Odos API key.
### Response
#### Success Response (200)
- A JSON object containing the price of the token in the requested currencies.
#### Response Example
```json
{
"usd": 1950.50,
"eur": 1800.25,
"gbp": 1550.75
}
```
```