# API

## Metadata Endpoint

You can retrieve all available trading pairs along with their associated on-chain metadata using the following endpoint:

**GET**

```
http://54.199.103.16:8080/ethereum/metadata
http://54.199.103.16:8080/base/metadata
http://54.199.103.16:8080/bsc/metadata
http://54.199.103.16:8080/arbitrum/metadata
http://54.199.103.16:8080/avax/metadata
http://54.199.103.16:8080/polygon/metadata
http://54.199.103.16:8080/megaeth/metadata
http://54.199.103.16:8080/hyperevm/metadata
http://54.199.103.16:8080/monad/metadata
```

### Description

This endpoint returns a list of supported pairs and the relevant contract addresses required for integration, including pool, price provider, and quoter contracts, as well as the underlying token addresses.

### Response Format

**Content-Type:** `application/json`

**Example response:**

```json
[
  {
    "pair": "ethusdc",
    "poolAddress": "0xbF48bCf474d57fF82A3215319229e0DE1476A557",
    "priceProvider_address": "0xbD321D18a7ce5fb91F8b16e026e3258f7b310598",
    "quoterAddress": "0x58F9d1865d4Aeb59a9a7Dc68A3b4e0B42D9Ef5eD",
    "token0": "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2",
    "token1": "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48",
    "cexStep":0.0002,
    "dexStep":0.0
  }
]
```

### Field Definitions

| Field                   | Description                                                            |
| ----------------------- | ---------------------------------------------------------------------- |
| `pair`                  | Canonical pair identifier (lowercase, no separator).                   |
| `poolAddress`           | Address of the Metric liquidity pool for the pair.                     |
| `priceProvider_address` | Address of the active Price Provider used to source reference pricing. |
| `quoterAddress`         | Address of the quoter contract used for off-chain quoting.             |
| `token0`                | Address of the first token in the pair.                                |
| `token1`                | Address of the second token in the pair.                               |

### Notes

Throughout the documentation, **`ethusdc`** is used as the primary example pair.\
Any other supported pair returned by this endpoint can be substituted directly, following the same conventions and integration flow.

## Retrieve Current Bid and Ask

You can retrieve the current bid and ask prices for a given pair using the following endpoint. Prices are returned based on current data from price provider. On most chains this causes insignificant price delays of below 1 second. On ethereum it currently causes a delay of 12 seconds. We are working to address this with our next update.

**GET**

```
http://54.199.103.16:8080/ethereum/0x3221901709F01737a601F9f02a01df6b13b2A6Ff/bid_ask
```

Pool address serves as unique identifier and is used in this api.

### Inputs

Sent as POST(Currently implemented as GET method for simplicity) parameters.

| Parameter   | Description                                                      |
| ----------- | ---------------------------------------------------------------- |
| `secretKey` | Authentication key (will be required later). Currently optional. |

### Response Format

**Content-Type:** `application/json`

**Example response:**

```json
{
"pair":"ethusdc",
"bidAdj":"43809995982499961913604",
"askAdj":"43845058004094599738265",
"quoteAvailable":true,
"totalToken0Available":"7210037341486830593",
"totalToken1Available":"19571324046",
"latestBlock":24370650,
"blockTs":1770053087,
"serverTs":1770053095,
"quoteExpiration":1770053099,
"depth":{}
}
```

### Field Definitions

| Field                  | Description                                                       |
| ---------------------- | ----------------------------------------------------------------- |
| `pair`                 | Trading pair identifier.                                          |
| `bid`                  | Current bid price (Q64 format).                                   |
| `ask`                  | Current ask price (Q64 format).                                   |
| `quoteAvailable`       | Indicates whether a quote can be requested for the current block. |
| `totalToken0Available` | Total available liquidity for token0.                             |
| `totalToken1Available` | Total available liquidity for token1.                             |
| `latestBlock`          | Block number of latest block                                      |
| `blockTs`              | UNIX timestamp of latest block                                    |
| `serverTs`             | Current UNIX timestamp on server                                  |
| `quoteExpiration`      | UNIX timestamp after which the quote is no longer valid.          |
| `depth`                | A dictionary of asks                                              |

#### `quoteAvailable` Semantics

* `true` — A quote request can be made.

### Price Format (Q64)

Prices are returned in **Q64 fixed-point format**, representing the price of **1 ETH in USD**.

To convert to a human-readable value:

```
price = priceX64 / 2^64
```

With the example values above, this results in approximately:

```
2965 USD per ETH
```

### Price Inversion

To determine how much **ETH corresponds to 1 USD**, invert the price using:

```
invertedPriceX64 = 2^128 / priceX64
```

This yields a value in **ETH per USD (Q64 format)**.

To convert to a human-readable number:

```
invertedPrice = invertedPriceX64 / 2^64
```

Using the example above:

```
≈ 0.00033726 ETH per USD
```

### Depth

\
Bid(asks are the same, we just start with ask and walk across ask bin) **depth price calculation:**

Start with *currentPrice = bidAdj, remainingVolume = X*

Walk across bins. For each bin compute:\
\&#xNAN;*volumeInThisBin = currentBin.cumulativeVolume − previousBin.cumulativeVolume*

If *remainingVolume <= volumeInThisBin* — order completes inside this bin:

*exitPrice = currentPrice + (currentBin.price − currentPrice) × remainingVolume / volumeInThisBin*

Record fill price: *(currentPrice + exitPrice) / 2* weighted by remainingVolume

Otherwise — order consumes entire bin:

Record fill price: *(currentPrice + currentBin.price) / 2* (It's linear within bin. But since bins can vary in size it's not linear across several bins.)

Update *currentPrice = currentBin.price*, subtract *volumeInThisBin* from *remainingVolume*, move to next bin

Final *fill price = volume-weighted average of each bin's recorded fill price*

### Usage Notes

* Cumulative volume is a scaled value of token1 to token0. Formula is:\
  10^(max(18, token1.decimals()) - token0.decimals())
* Q64 pricing internally normalizes token decimals (e.g. ETH: 18 decimals, USDC: 6 decimals).
* The **quoter operates directly on Q64 values**, so no conversion is required when interacting with it.
* For off-chain price comparisons, human-readable values may be used.
* To convert human-readable prices back for calculations, multiply by `10^decimals` of the corresponding token.

## Simulate the Swap

Was used previously before our bid\_ask api had the capacity to return depth and exact prices.

Alternatively you can simulate a swap by calling the quoter contract:

```
quoteSwap(
  address pool,
  bool zeroForOne,
  int128 amountSpecified,
  uint128 priceLimitX64,
  uint128 bidPriceX64, (optional for api, must use on chain)
  uint128 askPriceX64,(optional for api, must use on chain)
)
```

This function belongs to a separate smart contract (see **Section 2.4: Quoter Address**) and returns simulated swap results based on current market conditions. Prices are filled automatically based on our price providers.

### Direct Contract Call

If calling the contract directly, use the `eth_call` RPC method.

* The transaction is intentionally reverted during the internal call
* Simulation results are returned via emitted logs
* No state changes occur
* Prices should be retrieved from price provider first

### API Wrapper

For convenience, Metric exposes an HTTP API that wraps the quoter call:

**POST**

```
http://54.199.103.16:8080/ethereum/0x3221901709F01737a601F9f02a01df6b13b2A6Ff/quote
```

### Inputs

Sent as JSON body parameters.

| Parameter         | Type    | Description                               |
| ----------------- | ------- | ----------------------------------------- |
| `pool`            | address | Pool address.                             |
| `zeroForOne`      | bool    | Swap direction (`true`: token0 → token1). |
| `amountSpecified` | string  | Exact input or output amount (signed).    |
| `priceLimitX64`   | string  | Price limit in Q64 format.                |
| `bidPriceX64`     | string  | Current bid price (Q64).                  |
| `askPriceX64`     | string  | Current ask price (Q64).                  |

### Response Format

**Content-Type:** `application/json`

**Relevant fields:**

| Field          | Description                                                          |
| -------------- | -------------------------------------------------------------------- |
| `amount0Delta` | Amount of token0 sent (negative) or received (positive) by the pool. |
| `amount1Delta` | Amount of token1 sent (negative) or received (positive) by the pool. |

### Notes

* Delta signs follow pool perspective (not trader perspective).
* All price inputs must be provided in **Q64 format**.
* No additional decimal normalization is required when using the quoter.
* Currently API throws http error when trying to swap more tokens than available. This will be improved in the future. To return the quote for as many tokens as can be exchanged

## Check our gas for reference

```
http://54.199.103.16:8080/ethereum/gas
```

Response:

```json
{
"max_priority_fee_per_gas":"1300000000",
"base_fee":"48502981",
"max_fee_per_gas":"1348502981",
"block_number":"24526324"
}
```

## Request a Signed Oracle Update

### Option 1 — Higher Fixed Heartbeat Fee (Simpler)

As a simpler alternative, the oracle heartbeat can be funded with a **higher default gas price**, removing the need for per-request signing.

* Suitable for quick integrations

Please contact us to agree on the gas price to be used in this mode.

### Option 2 — Signed Call Data (Long-Term)

```
http://54.199.103.16:8080/ethereum/0x3221901709F01737a601F9f02a01df6b13b2A6Ff/get_signed_data
```

Address here is poolAddress of the pool

**This is only necessary on ethereum.** On other chains we either have 99.99% inclusion or allow the price to survive for one or several more blocks to achieve desired uptime out of the box.

As a long-term solution, the API will return:

* Signed call data
* Oracle contract address

This allows integrators to **fully control oracle updates and gas management**.

You can pass the data from this API to our oracle forcing an update. Your trade has to follow it in the same block.

The oracle already exposes the following interface:

```solidity
interface IUpgrader {
    function updateBySignature(
        address feedCreator,
        uint256 deadline,
        uint256 newSlotValue,
        bytes calldata signature
    ) external returns (bool success);
}
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://oracle-based-omm.gitbook.io/metric/RSm94m71kqtGICv4iKRj/developers/api.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
