# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
This site has an agentic ask interface you may use to query the documentation dynamically by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.delphi.fyi/index.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

---

# What is Delphi?

Delphi is an information market platform where you can get odds on almost anything you can put into words, and trade on them.

## Delphi, the Platform to Predict Anything

Type what you think will happen. Delphi turns it into a market question, gives you odds, and lets you take the other side.

If you think the odds are wrong, you trade against them. Delphi opens the market, funds it, and settles it automatically when the outcome is known. Each market is settled by AI against rules published before anyone trades.

<div data-with-frame="true"><figure><img src="https://3382892862-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Ft59pTERBDU0JfP4e2nEP%2Fuploads%2FPgKWeuHLeaumMDGA4JKj%2Fimage.png?alt=media&amp;token=36671590-ebca-4f72-a6b5-1ae07f83a775" alt=""><figcaption></figcaption></figure></div>

### Two Ways to Create Markets

There are two ways to create markets in Delphi.

1. **You ask.** Write a prediction and Delphi's forecast prices it. If you disagree with the odds, you trade against them, and Delphi opens the market with you as its first trader. These markets are LMSR markets only. See [Predict Anything](/predict-anything).
2. **You build.** Write the question, outcomes and settlement terms yourself. This is the path for custom terms, multi-outcome markets, or predictions that Delphi won't open for you, and it makes you the market's creator, earning a share of its trading fees. You can choose to create an LMSR or DPM market. See [Create a Market](/create-a-market).

Either way you end up with the same kind of market: anyone can trade it, and it settles through the same automated process.

### Market Mechanisms

Every Delphi market uses one of two mechanisms: **\[1]** LMSR (recommended) or **\[2]** DPM.

* **LMSR (recommended):** The price of an outcome is its probability. Each winning share pays $1 when the market settles. If it closes with *No Outcome*, shares pay their final market price instead.
* **DPM:** Traders buy into a pool, and winners split it.

Learn more about LMSR and DPM markets [here](https://docs.delphi.fyi/pages/Uty4JlTiuqWmOgRXjXGS#id-3.1-lmsr-and-dpm-market-mechanisms).

### Settled by AI, Verifiable by Anyone

Every market declares how it will be decided before anyone trades: the question, the outcomes, the data sources, and the settlement criteria. They're shown on the market page and can't be changed once the market is live.

When trading closes, Delphi's [automated settlement workflow](/how-ai-settlement-works) evaluates the available evidence against those rules and submits the result on-chain. Resolution doesn't rely on a central team or a single opaque oracle. Two frontier models independently review the evidence, and an open-source judge model running inside Gensyn's [Reproducible Execution Environment (REE)](https://docs.gensyn.ai/tech) makes the final decision.

#### Verifiable Settlement

REE produces a reproducible receipt for the judge's computation, recording the model, inputs, output, and a cryptographic hash. Anyone can use the receipt to re-run the computation and confirm the recorded model produced the recorded output from the recorded inputs.

This proves the computation happened as stated. It doesn't prove every source or market definition was correct.

{% hint style="info" %}
Read more about what verification does and does not prove in [How Automated Settlement Works](/how-ai-settlement-works).
{% endhint %}

Together with the market's public question, outcomes, data sources, and criteria, the receipt makes settlement independently inspectable.

### How It Works

1. **A market is opened.** Either Delphi opens it when you challenge a forecast on the [Predict Anything](/predict-anything) page, or a creator builds it in the create flow.
2. **People trade.** Participants buy and sell positions on the outcomes they believe are most likely, and prices move with every trade.
3. **Trading closes.** It closes at a set time, before the outcome is knowable.
4. **Delphi settles the market.** The analyst and judge workflow reviews the declared rules and the available evidence.
5. **The result goes on-chain.** The market page shows the final outcome, payouts, and settlement reasoning.
6. **Winners claim their payouts.** If no winning outcome is declared, the market closes with *No outcome* and positions are paid at their final market prices.

### Where Delphi Runs

Delphi's markets are information markets on Gensyn mainnet, traded in USDC. Anyone can get odds and view markets. Trading and market creation aren't available in certain locations, including the United States and its territories. You can find the full geoblocked region list in [Help](/help).

### What's Next

* Visit [Get Started](/get-started) to sign in and add funds.
* Make your first prediction on [Predict Anything](/predict-anything).
* Browse and trade existing markets on [Explore & Trade](/explore-and-trade).


# Get Started

Sign in, add funds, and learn your way around the app.

## Overview

You don't need an account to get odds. Anyone can ask Delphi for a forecast on the [Predict Anything](/predict-anything) page and browse markets. You only need to sign in to trade or create a market.

### Sign In & Wallets

Select *Sign In* in the top-right corner. You have two options:

1. **Email or Google:** Sign in with your email address or your Google account. Delphi creates an embedded wallet for you automatically. Gas is sponsored for embedded wallets, so you don't need ETH to trade.
2. **External wallet:** Connect MetaMask or another wallet provider.

Once you're signed in, the top-right corner shows your balance and wallet menu.

### Add Funds

Delphi markets trade in USDC on Gensyn mainnet. Open the wallet menu in the top-right to move funds in and out.

<div data-with-frame="true"><figure><img src="https://3382892862-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Ft59pTERBDU0JfP4e2nEP%2Fuploads%2FRaPMpu8mV48qb5mJnyPL%2Fimage.png?alt=media&amp;token=7eba02f3-6ce5-44aa-95e9-d3d0f19152a0" alt=""><figcaption></figcaption></figure></div>

#### Deposit

Select *Deposit*. The deposit window lets you:

* Send crypto from an exchange or another chain. Send USDC from an exchange like Coinbase, or from another network such as Base or Ethereum. It's bridged to Delphi automatically.
* Buy USDC with a card or bank account.

<div data-with-frame="true"><figure><img src="https://3382892862-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Ft59pTERBDU0JfP4e2nEP%2Fuploads%2F6R10US3DQqeKUog8Pcky%2Fimage.png?alt=media&amp;token=f56eec23-6314-4d0f-8a00-fec415487f8e" alt=""><figcaption></figcaption></figure></div>

### Withdraw Funds

Select *Withdraw* to send USDC to another supported chain, including Base and Ethereum.

<div data-with-frame="true"><figure><img src="https://3382892862-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Ft59pTERBDU0JfP4e2nEP%2Fuploads%2FQIulY4T84CMJMC6NuE8j%2Fimage.png?alt=media&amp;token=7c0f1f2f-890c-491f-a031-eca31ba5cc7f" alt=""><figcaption></figcaption></figure></div>

### Find Your Way Around

There are a few pages to explore:

* [Predict Anything](/predict-anything): The home page and the main button in the header. Type a prediction, get odds, and challenge them.
* [Markets](/explore-and-trade): Browse every market, filtered by category.
* [Activity](/activity): Your positions, winnings to claim, payouts, trade history, and markets you've created.
* [Leaderboard](/leaderboard): Compare creators by earnings, volume, and settled markets.
* [Profile](/profile): Your public creator profile. Shown only when you're signed in.

Create a Market is in the footer. See [Create a Market](/create-a-market).

### Availability

Buying, selling, and creating markets are unavailable in the United States and its territories. The app will let you know if trading is unavailable in your region. For more on regional availability, see [Help](/help).


# Predict Anything

Write a prediction, read the forecast card, and challenge the odds.

## Overview

This guide covers how to write a prediction, explains the forecasting process, shows how to trade on markets, and more.

### Write a Prediction

Type into the box and select *Get Odds.* You can write a statement (*"Arsenal will win the Premier League"*) or a question (*"Will Arsenal win the Premier League?"*).

If you write a statement, Delphi marks the side you backed as your pick. It's selected for you if you decide to trade, but nothing is bought until you confirm, and you can switch sides first. A question gets priced without a pick.

<div data-with-frame="true"><figure><img src="https://3382892862-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Ft59pTERBDU0JfP4e2nEP%2Fuploads%2FwsmE4GlGL7lYVH7TJxd0%2Fimage.png?alt=media&amp;token=f9cfea0f-8541-457a-bff3-81805796e945" alt=""><figcaption></figcaption></figure></div>

Good predictions have an outcome someone could check from public information and a date by which it will be known. For example, *"Bitcoin will close above $100k on December 31, 2026"* works whereas *"Crypto will do well"* doesn't.

{% hint style="info" %}
Need an idea? Tap a suggestion under the box to load it.
{% endhint %}

### How Forecasting Works

Once you make your prediction, Delphi's forecasting service gets to work by:

1. **Reading your prediction.** Delphi rewrites it into a precise question with a close time. You might type *"fed cuts in september*" but the card will say *"Will the Federal Reserve cut rates at its September 2026 meeting?"* The rewrite is the market exactly as it would be created.
2. **Searching for current information.** This only occurs when the question needs live facts.
3. **Working out the odds.** Determining the most realistic, tradable odds for that market.&#x20;

<div data-with-frame="true"><figure><img src="https://3382892862-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Ft59pTERBDU0JfP4e2nEP%2Fuploads%2F90N20Uh8gkY3U9zhn6PI%2Fimage.png?alt=media&amp;token=9ab83856-3d53-4780-9231-ac761cd41b83" alt=""><figcaption></figcaption></figure></div>

### Reading the Forecast Card

The forecast card is Delphi's offer: **\[1]** the market it would open, **\[2]** the odds it would open at, and **\[3]** how long that price holds.

At the top is the question as Delphi has rewritten it. That's the exact market that would be created, so check it matches what you meant.

Just below, a label tells you whether the prediction is *Tradable*, meaning Delphi will open a market if you trade, or *Forecast Only*, [meaning you get odds but no market.](#forecast-only)

Next come Delphi's odds for each outcome, with the price of a share beside each one. If your prediction took a side, it's marked as **your pick**. The main button changes to match what you'd be doing: challenging the odds, backing the favourite, or signing in first. A countdown next to it shows how long the price is good for.

<div data-with-frame="true"><figure><img src="https://3382892862-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Ft59pTERBDU0JfP4e2nEP%2Fuploads%2F3nNlyiCJkZqhxl1AAjaN%2Fimage.png?alt=media&amp;token=f35497c1-c165-4845-b1ce-773ac7e7aa63" alt=""><figcaption></figcaption></figure></div>

Below the offer are two sections you can expand:

* **Forecast reasoning:** Why Delphi landed on these odds, and the thing to weigh if you think it's wrong.
* **Settlement:** The criteria, data sources and close time the market would settle on.

#### Forecast Only

If you see *Forecast Only,* it means Delphi priced your prediction but won't open a market for it. You still get everything else on the card: the odds, the reasoning, the settlement terms, and the option to share it.

The most common reasons for seeing this are:

* **It can't be settled from public information.** Delphi drafts settlement terms and checks the data sources before any market exists. If it can't find a public source that could decide the outcome, or the question is still ambiguous after rewriting, it won't open a market it might not be able to settle.
* **It resolves too soon.** If the answer will be known within a few hours, nobody else has time to trade.
* **The outcome is close to certain.** If Delphi's forecast is below 2% or above 98%, there's little left for a market to discover.
* **One person could easily decide it.** If the outcome is something a single person could make happen at little cost to themselves, like whether a particular account posts something tomorrow, the market would be easy to manipulate. Questions about widely followed public figures can still be tradable.

#### When There's No Forecast

Sometimes Delphi won't give you odds at all. A prediction that breaks Delphi's content policy is refused outright. So is text that isn't actually a prediction. You may need to tighten the wording and try again with something that has a checkable outcome.

If you've hit the hourly limit on forecasts, the message tells you when you can ask again.

### The Countdown and Repricing

Each quote lasts about three minutes, then there is an automatic repricing.

Delphi starts repricing in the background before the countdown ends. The new odds replace the old ones, and an *Odds* updated line lists only the outcomes that moved (for example, `Yes 38.2% -> 41.3%`). You can keep using the current offer until the new one lands.

{% hint style="info" %}
Requotes build on the last price rather than starting over.
{% endhint %}

#### "This Already Exists"

If your prediction closely matches a live market, a panel appears above the forecast with a link to that specific market. Delphi won't open a duplicate, so trade in the existing market.

If the match is looser, the panel is headed *Related* markets. Select *Ignore* to dismiss it and carry on. Your forecast stays usable either way.

### Challenge the Odds

Once you're signed in, you can place a trade.

1. If you haven't signed in and connected a wallet, see [Get Started](/get-started).
2. Select *Place a Trade.* A dialog opens over the card, so the odds stay in view.
3. Pick an outcome. Your pick is preselected if your statement took one.
4. Enter an amount greater than $1 USDC. Your balance and a *Max* button sit beside the field.

<div data-with-frame="true"><figure><img src="https://3382892862-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Ft59pTERBDU0JfP4e2nEP%2Fuploads%2F8T4MIzrdAKVJf4ovy7dv%2Fimage.png?alt=media&amp;token=44d358a9-6c18-40df-80bc-2e947f4c8a9e" alt=""><figcaption></figcaption></figure></div>

5. Check the quote: the shares you'd receive, average price, payout if you're right, the trading fee, and the odds your trade would leave behind.
6. Select *Review Position.* The next step restates the numbers and produces the *Trade* button.
7. Click *Trade*. Delphi opens the market and fills your trade in one transaction.
8. You land on the market page, with your trade in the history after Delphi's opening trade.

#### Requesting a Requote

Odds are only available for a certain amount of time at the current price. If you wait too long before purchasing shares in one of the available outcomes, the quote can expire. This means you will need to *Request new odds* before you are able to place a trade.

### After the Market Opens

After the final step, you've successfully executed a trade on a newly-opened Delphi market. From here, you can view the market's page, the market's stats, the settlement criteria, trade history, and more.

<div data-with-frame="true"><figure><img src="https://3382892862-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Ft59pTERBDU0JfP4e2nEP%2Fuploads%2Fdlk5jlJWr2F2fsppR90g%2Fimage.png?alt=media&amp;token=47a0e073-812e-4469-91bc-ee49b67dcceb" alt=""><figcaption></figcaption></figure></div>

### The Loop

When you ask Delphi about the future on the [Predict Anything](/predict-anything) page, an AI system analyzes public sources to convert your query into a precise question, returning a probability and the full rationale for that reasoning.

When you decide to trade on a forecast, Delphi automatically **\[1]** creates the market, **\[2]** seeds liquidity, **\[3]** sets the initial price to match the forecast via an opening trade, and **\[4]** fills your order in a single transaction. Each quote updates every few minutes to reflect real-time news and data.

Delphi opens markets only when valid settlement terms and public data sources can be established, avoiding questions that resolve too quickly, have near-certain outcomes, or risk manipulation.

{% hint style="success" %}
By taking the initial counterparty position, Delphi incentives users to trade when they possess *better* information, since correct user trades help continuously refine and improve future forecasts.
{% endhint %}

### FAQs

Find quick answers about forecasts, pricing, market creation, and trading.

<details>

<summary>Who am I trading against when I challenge the odds?</summary>

Delphi. When you commit, Delphi creates the market, funds it, moves the price to its forecast, and takes the other side of your trade, all in one transaction. After that the market is open to everyone.&#x20;

</details>

<details>

<summary>Why was my prediction "Forecast only"?</summary>

Delphi gave you odds but won't open a market, usually because no public source can settle it, it resolves within a few hours, the forecast is below 2% or above 98%, or one person could easily decide the outcome.&#x20;

</details>

<details>

<summary>Why did the odds change while I was reading?</summary>

*Odds* are only good for a few minutes. Delphi reprices in the background and shows *Odds* updated with what moved.

</details>

<details>

<summary>Why is "Get a new price" greyed out?</summary>

There's a short minimum wait between manual requotes.

</details>

<details>

<summary>How many markets can I open, or forecasts can I ask for?</summary>

There's a daily limit on markets each wallet can open through [Predict Anything](/predict-anything) and an hourly limit on forecasts. If you reach one, the app tells you when you can try again.

</details>

<details>

<summary>My market failed to open. Was I charged?</summary>

No. If the market and your trade don't both go through, your stake is returned.

</details>

<details>

<summary>Is Delphi's forecast ever wrong?</summary>

Yes. That's the point. If you know something the forecast doesn't, you can trade against it and get paid for being right.

</details>


# Explore & Trade

Browse active markets, understand market cards, and buy or sell positions on outcomes.

## Navigating Delphi

The Markets page is where you browse active information markets and place trades. This page covers how to find markets, read market cards, buy and sell positions, and understand your payouts.

### Browsing Markets

When you land on the Markets page, you'll see a grid of market cards showing all active markets. Each card represents a single information market.

You can filter markets by category using the row of category buttons near the top of the page.

{% hint style="info" %}
By default, "All" is selected, so you'll see all available active markets.
{% endhint %}

<div data-with-frame="true"><figure><img src="https://3382892862-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Ft59pTERBDU0JfP4e2nEP%2Fuploads%2Frsc603e5s7sQLJBq8usI%2Fimage.png?alt=media&amp;token=e01aee0d-a111-4cc1-9a1f-155f7f0275e2" alt=""><figcaption></figcaption></figure></div>

#### Two Market Mechanisms

Every market card and market page carries a badge showing its mechanism:

* **LMSR:** Buy shares to move the price toward the probability you believe. Every trade shifts it immediately.
* **DPM:** Buy shares to claim your proportional stake of the total pool if the event happens.

The two work differently when you trade, sell, and get paid. For a side-by-side comparison, read [this](https://docs.delphi.fyi/pages/Uty4JlTiuqWmOgRXjXGS#id-3.1-lmsr-and-dpm-market-mechanisms).

### Understanding Market Cards

Each market card gives you a quick snapshot of that active market.

* **Title:** The market's question (e.g., "Will The Weather Underground Report Rain in LA More Than 0.1" By 4:00:00 PM UTC on April 28th 2027?").
* **Status:** Whether the market is active, pending settlement, settled, closed with no outcome, or removed.
* **Category:** Which category the market falls under.
* **Market Type:** The LMSR or DPM badge.
* **Automated Settlement:** Automated markets are settled by Delphi after trading closes rather than manually by the creator. See [How Automated Settlement Works](/how-ai-settlement-works).
* **No Outcome:** No winning outcome was declared. Positions are paid at final market prices.
* **Legacy tag:** Markets created before Automated Settlement are tagged as *Legacy*.
* **Sentiment / Probability:** You will see the market sentiment (odds) and probabilities (depending if the market is LMSR or DPM) for each outcome.
* **Liquidity:** How much liquidity is in the market. Note that this has different implications for LMSR or DPM markets.
* **Close Date:** When the market stops accepting trades.
* **Creator:** The creator's name or shortened wallet address. Select it to open their [Profile](/profile#find-a-profile).

<div data-with-frame="true"><figure><img src="https://3382892862-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Ft59pTERBDU0JfP4e2nEP%2Fuploads%2FqlVknFJCOUOJYhfWL0O6%2Fimage.png?alt=media&amp;token=cc7326cc-9327-4c96-b8d4-4e11ef83381c" alt=""><figcaption></figcaption></figure></div>

{% hint style="info" %}
Markets opened through *Predict Anything* look like any other market. Their creator is Delphi.
{% endhint %}

### Inside a Market

Click any market card to open the full market view. At the top, you'll see a header banner with the market title, status, category, creator address, leading outcome, total trade count, and when the last trade was placed.

There's also a share button in the top-right to copy a direct link to the market.

<div data-with-frame="true"><figure><img src="https://3382892862-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Ft59pTERBDU0JfP4e2nEP%2Fuploads%2Fi2xrKsulXpGd2kkcbZ7E%2Fimage.png?alt=media&amp;token=1c7d0085-8366-4cfb-b48b-63e72f43d789" alt=""><figcaption></figcaption></figure></div>

Below the header, the page is organized into several sections:

* **Place a Trade:** Select the outcome you want to trade on, toggle between *Buy* and *Sell*, enter the amount in USDC, and click *Trade*. Your current wallet balance is displayed below the input field, along with the trading fee for that market.
* **Market Stats:** This shows the trading fee percentage, total volume, and the created, closes, and settles dates and times.
* **Market Sentiment Chart:** A line chart showing how sentiment across outcomes has shifted over time.
* **Current Sentiment:** A set of progress bars showing the current probability distribution across all outcomes.
* **AI Settlement:** For automated markets, displays the analyst and judge model roles, the market's data sources, and the settlement criteria. After settlement, this is where you'll find *View Settlement Report*. For more details, see [How Automated Settlement Works](/how-ai-settlement-works).
* **Creator Stats:** The creator's wallet address, market counts, and all-time volume. Select the creator to open their [Profile](/profile#read-a-creator-profile).

{% hint style="info" %}
On markets opened through *Predict Anything*, the first trade in the history is Delphi's opening trade, which moved the price from even odds to Delphi's forecast. The chart starts from it.
{% endhint %}

### Creator Profiles

Every creator has a public profile. Select a creator on a market card, in *Creator Stats*, or from *All Markets* to open it.

Profiles show a creator's markets and track record. Learn how to browse profiles and manage your own in [Profile](/profile#read-a-creator-profile).

To compare creators before opening their markets, visit the [Leaderboard](/leaderboard). It ranks creators by earnings and links to each public profile.

### Buying a Position

To buy a position in a market:

1. Open the market and go to the *Place a Trade* section.
2. Make sure *Buy* is selected.
3. Select the outcome you want to buy into.
4. Enter the amount of USDC you want to commit.
5. Click *Trade*.

The confirmation shows the market, your outcome, the shares you'll receive (after the price impact of your own trade), and the total including the trading fee.

#### On LMSR markets

* Each outcome row shows the payout multiple you receive if that outcome wins.
* Enter an amount to preview your total return and profit if your chosen outcome wins. These values lock in when you trade. Later trades do not change them.
* Each outcome has a limit on how much the market can absorb in one trade. If you go over it, you'll see *"This trade is larger than this market can absorb"* and the largest amount you can use. Select that amount to fill it in.
* The confirmation includes your payout if the selected outcome wins. Your share count is fixed once the trade goes through. Each winning share pays $1. If the market closes with *No outcome*, shares pay their final market price instead.

<div data-with-frame="true"><figure><img src="https://3382892862-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Ft59pTERBDU0JfP4e2nEP%2Fuploads%2F9Rl9xtVNmWBJI7A5yISK%2Fimage.png?alt=media&amp;token=aa536aca-32ac-4f9b-ba52-a7a2aa150bb0" alt=""><figcaption></figcaption></figure></div>

#### On DPM Markets

* Each outcome row shows the amount in the pool and the price per share.
* Payouts are not fixed. They change as other trades are placed before the market closes.

<div data-with-frame="true"><figure><img src="https://3382892862-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Ft59pTERBDU0JfP4e2nEP%2Fuploads%2FFn12x7eXh80XZvsDmtf9%2Fimage.png?alt=media&amp;token=6d16a80e-23d6-4ffa-9ed3-2a9c1b85ae95" alt=""><figcaption></figcaption></figure></div>

### Your Position(s)

Once you hold a position, *My Position* appears on the market page, with **\[1]** each outcome you hold, **\[2]** what you paid, **\[3]** your shares, and **\[4]** what the position would be worth if you sold now. The value shows green when it's above your cost.

*My Payout Preview* shows what each outcome you hold would pay. Note that these are different depending on what type of market mechanism was used to create that market:

* **LMSR:** Each share pays $1 if that outcome wins, so the figure doesn't change as others trade. (If the market closes with No outcome, shares pay their final market price instead.) What the position is worth if you sell now still moves with the market.
* **DPM:** An estimate based on current liquidity, which changes as others trade.

### Selling a Position

Select *Buy* or *Sell* from the dropdown and select the outcome you hold, and confirm. You can also select *Sell* next to a holding in *My Position* to sell from a pop-up without leaving your place.

* **LMSR**: Sell any part of a position, from 1% to 100%, using the slider or Max.
* **DPM**: Selling liquidates your entire position in that outcome. Partial sells aren't supported.

Sell quotes are at the current price, which can move before your transaction confirms.

{% hint style="info" %}
If you try to sell an outcome you don't hold, the app will let you know you don't have a position to sell.
{% endhint %}

### What Happens When a Market Closes

At its close time, a market stops accepting trades and enters settlement.

Delphi runs the [declared settlement workflow](/how-ai-settlement-works), and the market page shows whether settlement is scheduled, running, settled, or closed with *No Outcome.* Markets automatically settle within 48 hours of trading close.

If a winning outcome is selected, winning shares become claimable from the market page or *Claimable* in [Activity](/activity).

* **LMSR**: Each winning share pays $1.
* **DPM**: Winning shares split the pool.

If the market closes with *No Outcome*, positions pay at the final market prices when trading closed. On an LMSR market, a share priced at 70% pays $0.70. You can claim these from Payouts in [Activity](http://activity.md).

{% hint style="warning" %}
Payouts from a market that closes with *No Outcome* are based on final market prices. They may be higher or lower than what you originally paid. This is not a traditional refund. See [What Does "No Outcome" Mean?](/how-ai-settlement-works#what-does-no-outcome-mean)
{% endhint %}


# Create a Market

Walk through the six-step flow to create and launch your own information market.

## When to Create a Market

The fastest way to get a market is to ask for one on the [Predict Anything](/predict-anything) page, where Delphi prices your prediction and opens the market when you trade.

Creating a market yourself is the manual path. You can do this when:

* Delphi's forecast returned *Forecast Only* and gave you a *Create This Market* button. See [From a Forecast.](#creating-markets-from-a-forecast)
* A similar market already exists and you still want your own version.
* You want custom terms: multiple outcomes, specific wording, or your own settlement criteria.
* You want to be the creator and earn a share of the market's trading fees.

### AI Market Validation

As you build a market, an AI validator sanity-checks every stage of the creation process, which includes your question, outcomes, data sources, the settlement criteria, and timing. It flags issues for you to fix and suggests improvements before you launch the market, many of which are 1-click insertable.

The validator doesn't just check that fields are filled in. It reasons about whether your market is actually resolvable, and where it isn't, it explains the problem and suggests a concrete rewrite.

For example, it will catch:

* **Unmeasurable questions**, like *"Will the USA do well at the World Cup?",* since 'do well' has no measurable threshold. The validator flags it and suggests a rewrite that pins the exact team, threshold, and tournament so the market maps cleanly to a real result (e.g. *"Will the USA reach the semi-finals…"*).
* **Overlapping or weak outcomes,** like *"Yes/No/Maybe/They make the semi-finals"* since, in this case, 'maybe' isn't a real outcome and the last position overlaps with 'yes' given the re-stated question (see above).
* **Vague data sources,** such as naming a parent website (like "FIFA official website") without linking to a specific page that has the data used to settle the market.
* **Timing that doesn't match reality**, which might be the market's timing set to close before the Semi-Finals are even played.

{% hint style="warning" %}
Accepting the suggestions turns a market traders would avoid into one they can trust. The validator is an assistant, not a gatekeeper of qualit&#x79;*.*

It's still on *you* to add the definitions, clauses, and edge cases your specific market needs.
{% endhint %}

<div data-with-frame="true"><figure><img src="https://3382892862-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Ft59pTERBDU0JfP4e2nEP%2Fuploads%2FDqPcXqNpXSazT2lupk9s%2Fimage.png?alt=media&amp;token=5ebee00f-e91a-4b08-b9ca-1e6002e6f44c" alt=""><figcaption></figcaption></figure></div>

### The Market Creation Process

Anyone can create an information market on Delphi. The creation flow has six steps: **\[1]** Details, **\[2]** Outcomes, **\[3]** Economics, **\[4]** Settlement, **\[5]** Timing, and **\[6]** Review. Click *Create Market* in the footer to get started.

### Step 1: Details

Give your market a clear, specific question that can be definitively resolved by a certain date. The golden template is *"Will X happen by Y?"* where X is a verifiable event and Y is a precise deadline.

<div data-with-frame="true"><figure><img src="https://3382892862-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Ft59pTERBDU0JfP4e2nEP%2Fuploads%2FEaDIEKNVLirUGKJg8jqD%2Fcreate_a_market_1.png?alt=media&amp;token=38485843-60d4-4639-9aa7-32fec4fedcdd" alt=""><figcaption></figcaption></figure></div>

You can follow this four-step approach:

1. Identify what you actually want to know: *"Will it rain in Los Angeles this weekend?"*
2. Find an authoritative data source that can answer it. (e.g., the Weather Underground's historical precipitation data)
3. Determine a reasonable timeline. How long does the market need to run for the answer to become knowable?
4. Now write the question so that it maps cleanly to that source and timeline.

Your data source should inform how you phrase the question.

For example, "*Will it rain in Los Angeles on April 20, 2026?*" is vague, because 'what counts as rain' can be relative, like a light misting versus a light rain. A stronger version of the question would be as follows:

> "Will Weather Underground report precipitation greater than 0.00 inches for Los Angeles, CA on April 20, 2026?"

Now there's exactly one authority, one location, one threshold, and one date.

#### Data Sources in Titles vs. Settlement Criteria

If you have a very specific resolution source, put it in the title. It helps traders understand what they're trading on at a glance. It also differentiates similar markets that resolve on different sources.

For instance, two markets could both ask about rainfall in Los Angeles. One could resolve on Weather Underground and the other on the National Weather Service. These are fundamentally different markets.

If the source is general or self-evident, leave the title clean. Make sure it appears in the market's data sources and settlement criteria instead.

{% hint style="info" %}
There's no single right answer here. It depends on whether specificity or readability matters more for your particular question.
{% endhint %}

### Step 2: Outcomes

This is where you define the possible outcomes for your market: you need at least two, with a maximum of 20 outcomes permitted.

<div data-with-frame="true"><figure><img src="https://3382892862-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Ft59pTERBDU0JfP4e2nEP%2Fuploads%2FHPTOj4eMnqh7Kqg7cJ7P%2Fcreate_a_market_2.png?alt=media&amp;token=35e30ee7-2fad-4208-bb6e-a499449a3e2a" alt=""><figcaption></figcaption></figure></div>

For a straightforward yes/no question, "Yes" and "No" will be prefilled. If your market has more nuance, you can add custom outcomes (up to 90 characters each).

Outcomes must be **\[1]** exhaustive, **\[2]** non-overlapping, and **\[3]** accurate.

1. **Exhaustive** means every possible real-world result falls into exactly one of your outcomes. There should be no scenario where the answer is "none of the above."
2. **Non-overlapping** means no result could reasonably fit into two different outcomes. If you're defining numeric ranges (e.g., temperature brackets like 0°F–30°F, 30°F–60°F, 60°F–90°F), make sure boundaries are precise by specifying whether each boundary is *inclusive* or *exclusive*, and state your rounding rule in the settlement criteria. If it's 30.0°F exactly, which bucket does it fall into? This must be unambiguous.
3. **Accurate** means the outcomes faithfully represent the possibilities. Don't leave out a plausible result just because it seems unlikely.

#### Covering Edge Cases

When defining your outcomes, consider whether something could reasonably happen that falls outside your listed options: a game getting cancelled, a tournament being delayed past your market's expiry, or any scenario where none of your outcomes cleanly apply.

If that's a realistic possibility, add a catch-all outcome (e.g., *"Other / Event cancelled / No result by expiry"*). This gives the market a clean resolution path even if things don't go as expected, and gives traders who anticipate that scenario an outcome to trade on.

{% hint style="info" %}
A catch-all is **not** the same as a "maybe" outcome.

"Maybe" is vague and overlaps with your real outcomes. It isn't resolvable. A good catch-all is narrowly defined for a specific scenario your other outcomes can't cover, such as *"N/A: match postponed past market close."*

The validator will flag a "maybe"-style outcome and ask you to either remove it or define it precisely.
{% endhint %}

### Step 3: Economics

This is where you set up the financial parameters of your market. You can either choose an LMSR (recommended) or DPM market here, as well as choose how much liquidity to provide for your market.

<div data-with-frame="true"><figure><img src="https://3382892862-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Ft59pTERBDU0JfP4e2nEP%2Fuploads%2Fc5VjtN0FpEBFnahJDsYi%2Fimage.png?alt=media&amp;token=bfb4b203-9933-48ed-ab62-0cf9de2ca761" alt=""><figcaption></figcaption></figure></div>

### 3.1: LMSR & DPM Market Mechanisms

Every Delphi market uses one of two mechanisms. You'll see which one on every market card and market page:

* **Logarithmic Market Scoring Rule (LMSR)**: The price of an outcome is its probability. Each winning share pays $1.
* **Dynamic Parimutuel Mechanism (DPM)**: Traders buy into a pool. Winners split the pool.

LMSR is the recommended type and the default when you [create a market](/create-a-market). All markets opened through [Predict Anything](/predict-anything) are LMSR, though DPM continues to be available for manual market creation.

#### Comparison of Market Mechanisms

|                                                        | **LMSR**                                                                                                                                              | **DPM**                                                                                                                                  |
| ------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------- |
| *How trading works*                                    | Buy shares to move the price toward the probability you believe. Every trade shifts it immediately.                                                   | Buy shares to claim your stake of the total pool.                                                                                        |
| *What the odds label means*                            | Probability: the price of a share, and the market's estimate of how likely the outcome is                                                             | Sentiment: the share of the pool on each outcome                                                                                         |
| *Chart*                                                | Market Probability Chart                                                                                                                              | Market Sentiment Chart                                                                                                                   |
| *Outcome row*                                          | Pays 1.49× if correct                                                                                                                                 | <p>Example:<br><br>$2,340.00 in pool ($0.42/share)</p>                                                                                   |
| *Your return*                                          | Fixed when you trade. Later trades don't change it.                                                                                                   | Estimated. Changes as others trade.                                                                                                      |
| *Selling*                                              | Sell any amount, from 1% to 100% of a position                                                                                                        | Whole position only                                                                                                                      |
| *Trade size*                                           | Each outcome has a maximum trade the market can absorb. The app tells you the most you can trade.                                                     | No per-outcome ceiling                                                                                                                   |
| *What a share pays when the market settles*            | $1 per winning share                                                                                                                                  | A proportional share of the pool                                                                                                         |
| *What a share pays when market closes with No Outcome* | Prices freeze at trading close and each share pays its final price (a share priced at 12% pays $0.12). Claimed from Payouts in [Activity](/activity). | Positions pay at final market prices. Claimed from Payouts in [Activity](/activity). The creator's seeded liquidity is used to pay them. |
| *What the creator funds*                               | Funding that sets the market's liquidity. The creator starts with no shares.                                                                          | A refundable deposit plus seed shares spread evenly across every outcome                                                                 |
| *What the creator gets back*                           | Some or all of the funding, depending on where the market lands                                                                                       | The deposit (guaranteed) plus the seeded position in the winning outcome                                                                 |
| *What the creator earns*                               | Trading fees, plus a payout from the losing side at settlement if available                                                                           | Trading fees, plus the seeded position in the winning outcome                                                                            |
| *Settlement*                                           | [Automated](/how-ai-settlement-works)                                                                                                                 | [Automated](/how-ai-settlement-works). Older *Legacy* markets are settled [manually](/settling-a-market) by their creator.               |

{% hint style="info" %}
On LMSR markets, the $1 payout only applies when the market settles to a winning outcome. If it closes with No outcome, each share pays its final market price instead. [See What Does "No Outcome" Mean?](/how-ai-settlement-works#what-does-no-outcome-mean)
{% endhint %}

### Initial Liquidity

Initial liquidity (and how many shares you do or don't have) depends on the market mechanism you choose.

{% hint style="danger" %}
On either market type, your funding may not be fully recovered.
{% endhint %}

#### LMSR: Funding

Enter a funding amount, or use the slider. Your funding sets the market's liquidity: the more you add, the less each trade moves the price.

The *cost to move a price* calculator is informational, not a market setting. It shows what your funding buys by estimating how much a trader must spend to move an outcome’s price by 5%, 10%, 25%, or 40%.

*Maximum Loss* shows the most you can lose as the creator, while *What You Earn* summarises your fee share and settlement payout. You must meet the minimum funding amount before you can continue.

<div data-with-frame="true"><figure><img src="https://3382892862-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Ft59pTERBDU0JfP4e2nEP%2Fuploads%2FxMPXl3XUg4kijApV355w%2Fimage.png?alt=media&amp;token=0caf9c14-bfce-4463-92ab-d79db33ba67b" alt=""><figcaption></figcaption></figure></div>

You start with no shares, so your funding isn't a bet on any outcome. If nobody trades, it all comes back at settlement.&#x20;

You lose part of it when traders correctly move the price toward the outcome that wins, up to the maximum loss shown, and you can get back more than you put in when they back an outcome that loses.&#x20;

{% hint style="info" %}
Your share of trading fees is paid on top of whatever portion of liquidity is returned.
{% endhint %}

#### DPM: Initial Liquidity

Your initial liquidity is split into a refundable deposit and seed shares spread across every outcome, so you effectively hold a position on every outcome.

As traders buy into specific outcomes, your share of those pools is diluted. Depending on how trading plays out, you may not recover the full amount. This is expected: supplying liquidity is a form of market-making and carries risk, especially in low-volume or one-sided markets. Trading fees can offset this but aren't guaranteed to.

If the market closes with *No Outcome*, your seeded liquidity is used to pay positions at the final market prices.

<div data-with-frame="true"><figure><img src="https://3382892862-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Ft59pTERBDU0JfP4e2nEP%2Fuploads%2FuKUKhzLVEsg8AqBHmWYF%2Fimage.png?alt=media&amp;token=8f3a4f60-091e-489b-aab4-7acc7d5c86c1" alt=""><figcaption></figcaption></figure></div>

#### Why LMSR is Recommended

* The price is the probability. A price of 67% means the market thinks the outcome is 67% likely. That's easier for people, and for agents, to reason about than a pool split.
* Your payout is known up front. You know what a share pays when you buy it.
* Thin markets stay tradable. Liquidity is built into the market, so there's always a price to buy or sell at, even before many people have traded.
* More control over your position. You can [sell part of a position](/explore-and-trade#selling-a-position) rather than all of it.

#### DPM Risk

On a DPM market, traders buy into a pool and winners split it, so payouts are estimates that move as others trade, and a position can only be sold in full.

DPM markets can also show price instability when liquidity is low, and prices may move sharply on small trades near settlement.

<div data-with-frame="true"><figure><img src="https://3382892862-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Ft59pTERBDU0JfP4e2nEP%2Fuploads%2FxCAyks3czBOsDLoMPGmJ%2Fimage.png?alt=media&amp;token=0301d56c-4ae8-4588-9deb-51937bfb6cee" alt=""><figcaption></figcaption></figure></div>

#### Trading Fee

The default trading fee percentage is 2% on every trade in a given market.

As the creator, you'll receive a percentage of the trading fees on total traded volume in your market, paid when the market settles. The exact share is shown in the app and currently differs by market type.

### Step 4: Settlement

Automated Settlement is the process Delphi uses to resolve the market after trading closes. Delphi configures the analyst and judge models. Their roles appear as read-only details.

> *You do not choose a judge model or run settlement yourself.*

Delphi generates suggested data sources and settlement criteria from your question and outcomes. Review and edit them if needed: this is the contract between you and your traders. The settlement workflow follows them after close.

A final AI validation check flags ambiguity, incomplete outcomes, weak sources, and timing problems before publication.

#### Review the Suggested Data Sources

Review the generated list and edit it if needed. Prefer primary, official, and durable sources.

{% hint style="info" %}
You should always point to a specific page rather than a generic site name.
{% endhint %}

An undefined source like "FIFA official website" is weak, whereas a link to the official World Cup results or bracket page gives the settlement workflow and traders reliable evidence. The validator flags generic, unavailable, stale, or poorly matched sources.

These sources appear on the market page. They show participants exactly what evidence the market resolves on.

#### Review the Generated Settlement Criteria

Settlement criteria are market-specific rules that map evidence to an outcome. Confirm that they specify:

* What evidence determines the answer.
* Relevant dates, time zones, thresholds, and definitions. For numeric ranges, make boundaries precise and state the rounding rule.
* How each possible result maps to an outcome. State exactly when an "Other" outcome applies.
* What happens if an event is postponed, cancelled, or never occurs.
* Which source takes priority when sources conflict.

Criteria cannot override Delphi's settlement system. They also cannot instruct models to ignore the market's question or outcomes.

{% hint style="warning" %}
Take your time with market creation. Automated Settlement does not fix an ambiguous market. Incomplete questions, outcomes, or criteria can prevent a winning outcome.

You must add the definitions, clauses, and edge cases your market needs.
{% endhint %}

{% hint style="info" %}
For a deeper explanation of settlement after close, see [How Automated Settlement Works](/how-ai-settlement-works).
{% endhint %}

### Step 5: Timing

This is where you set when your market closes to new trades. There are some quick-set times available, or you can choose a custom date and time.

You can also choose how long the automated settlement pipeline waits before firing off (1-12 hours after market close).

Your market should close before the outcome is knowable. Once the answer becomes obvious, trading is no longer meaningful. For example, if your market asks *"Will the sun rise in New York City on April 15?"*, close it well before dawn (say, 4:00 AM ET), not after traders can look outside and already know.

<div data-with-frame="true"><figure><img src="https://3382892862-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Ft59pTERBDU0JfP4e2nEP%2Fuploads%2FNFjn1wVF5UfemyCXh5L9%2Fimage.png?alt=media&amp;token=fcb2a8f7-203e-410b-a549-fd305fee79fe" alt=""><figcaption></figcaption></figure></div>

### Step 6: Review

This is the final step in the market creation flow. Delphi runs a final AI validation check on the completed market. Review and address its suggestions before publishing.

The review page shows everything you've configured: **\[1]** category, **\[2]** question, **\[3]** outcomes, **\[4]** trading fee, **\[5]** market type (LMSR or DPM), **\[6]** settlement type (Automated), **\[7]** analyst and judge models, **\[8]** data sources, **\[9]** settlement criteria, **\[10]** trading close, **\[11]** automated settlement timing, **\[12]** initial liquidity, and the **\[13]** market creation fee.

Review everything, click confirm, and your market goes live!

<div data-with-frame="true"><figure><img src="https://3382892862-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Ft59pTERBDU0JfP4e2nEP%2Fuploads%2FJTtNiH8KToqhqMixcW0M%2Fcreate_a_market_6.png?alt=media&amp;token=fc8b7c6e-28ec-4145-9e8f-773eeff2f361" alt=""><figcaption></figcaption></figure></div>

{% hint style="success" icon="shield-keyhole" %}
Before you publish, AI Market Validation runs a final check across your question, outcomes, data sources, settlement criteria, and timing. Resolve any flagged issues or accept the suggested rewrites for a market that is clean, resolvable, and trustworthy. [See AI Market Validation](#ai-market-validation).
{% endhint %}

### Creating Markets From a Forecast

When Delphi's forecast returns *Forecast Only* (via [Predict Anything](/predict-anything)), the card offers the option to *Create this Market.*

Selecting it opens this flow with the question, outcomes, close time and a settlement draft already filled in from the forecast.

* **Check everything.** The draft is a starting point. Delphi didn't open the market because something about it needed a human decision, often the settlement source. The validator runs as usual.
* **The market starts at even odds.** Delphi's forecast isn't carried over. The first traders set the price.
* **You're the creator.** You fund the market and earn the creator's share of fees, like any market you create.

{% hint style="danger" %}
Some forecast-only predictions can't be created at all, including ones where a single person could easily control the outcome. These don't show the button. See [Predict Anything](/predict-anything).
{% endhint %}

### After Your Market Goes Live

Once your market is active, traders can start buying and selling positions on the outcomes. You can monitor your market's activity from the [Activity](/activity) page under the *My Markets* tab.

{% hint style="info" %}
Two additional notes:

1. Use the [Leaderboard](/leaderboard) to compare creator earnings and market activity across Delphi.
2. Only existing *Legacy* markets use manual settlement. See [Legacy Manual Markets](/settling-a-market#legacy-manual-markets) for the required post-close actions.
   {% endhint %}


# How Automated Settlement Works

How markets resolve automatically after close, including model review, verification, reports, and no-outcome payouts.

## Automated Settlement

Automated Settlement resolves every new Delphi market after trading closes, including markets opened through Predict Anything. Each market's question, outcomes, data sources and settlement criteria are set before trading starts. Delphi then reviews the available evidence against them and submits the final result on-chain.

Creators do not run a model or select a winner after close. Traders can inspect the configuration and resulting settlement report.

{% hint style="info" %}
Automated Settlement applies only to markets marked **Automated Settlement** in the market view. Existing **Legacy** markets use the previous manual settlement flow.
{% endhint %}

### Before You Trade

Every automated market shows the inputs that guide its settlement:

* **Question:** The real-world question being answered.
* **Outcomes:** The results the workflow can select.
* **Data Sources:** The sources used to review evidence.
* **Settlement Criteria:** The rules that map evidence to an outcome.
* **Analyst Models:** The models that review available evidence.
* **Judge Model:** The model that selects the final result.
* **Trading Close:** When new trades stop.

Review these details before trading. Clear questions, complete outcomes, reliable sources, and precise criteria make markets easier to resolve.

On markets opened through [Predict Anything](/predict-anything), these terms are generated before the market exists. Delphi drafts the settlement criteria and data sources while it prices your prediction, and shows them on the forecast card. If it can't produce terms that public sources could settle, the prediction is marked *Forecast Only* and no market is opened.

{% hint style="warning" %}
Automated Settlement cannot fix an ambiguous market. Incomplete questions, outcomes, or criteria may prevent a winning outcome.
{% endhint %}

### The Automated Settlement Process

After trading closes, the market moves through six stages:

1. **Trading closes.** No more positions can be bought or sold.
2. **Delphi waits for evidence.** Settlement starts at the offset chosen when the market was created, 1 to 12 hours after close, so official results and reliable reporting have time to appear.
3. **Analyst models review the market.** They assess the rules, sources, and available evidence.
4. **The judge evaluates the reports.** It selects the outcome that best matches the declared rules.
5. **The result is submitted on-chain.** The workflow sends the selected outcome to Delphi's contracts.
6. **The market page updates.** It shows the outcome, payouts, settlement details, and available reasoning.

Creators do not need to take settlement action after an automated market closes.

<div data-with-frame="true"><figure><img src="https://3382892862-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Ft59pTERBDU0JfP4e2nEP%2Fuploads%2FUkeD8k9tzvwFBCVZYXvg%2Fimage.png?alt=media&amp;token=96de6884-83d8-4a48-b12f-694f233dc5bd" alt=""><figcaption></figcaption></figure></div>

### Settlement Timing

Automated Settlement starts after trading closes. It is not instant. The workflow waits for evidence, reviews model outputs, and submits the result on-chain.

Settlement starts 1 to 12 hours after close (8 hours by default), and every market settles within 48 hours of trading close. The market contract enforces this window.&#x20;

Markets are set to close before the outcome is knowable. If trading stayed open until the answer was public, prices would drift to near-certain and trading would stop meaning anything.

{% hint style="info" %}
Trading close ends trading. It does not always end the evidence window. Evidence published later can still matter when it describes an event within the market's rules.
{% endhint %}

### How the Models Work Together

Automated Settlement separates evidence review from the final decision.

#### Analyst Models

Analyst models independently review the market and its available evidence. They:

* Find evidence from the declared sources.
* Apply the settlement criteria.
* Explain which outcome the evidence supports.
* Identify incomplete or conflicting evidence.

#### Judge Model

The judge receives the analyst reports and makes the final structured decision. It evaluates the reports against the market's question, outcomes, and settlement criteria.

Separating these roles reduces reliance on one model response. It also creates a clearer decision record.

### What Is Verifiable?

The final judge runs through [Gensyn's REE (Reproducible Execution Environment)](https://docs.gensyn.ai/tech). REE produces a [receipt](https://docs.gensyn.ai/tech/ree/receipts) that records the model, inputs, output, and computation hash.

You can use the receipt to reproduce the judge's computation. It confirms that the recorded model produced the recorded output from the recorded inputs.

Verification proves computational integrity. It does not guarantee that:

* Every source was factually correct.
* The question and outcomes were well designed.
* The analyst reports included every relevant piece of evidence.
* The selected outcome represents an objective or universal truth.

The receipt verifies the computation. The market's rules, sources, and settlement report let you evaluate the decision.

{% hint style="warning" %}
Verifiable does not guarantee a correct settlement. It means the recorded computation can be independently checked.
{% endhint %}

### Understanding the Settlement Report

After settlement, select *View Settlement Report* in the AI Settlement section.

Depending on the available artifacts, the report may include:

* The final outcome.
* Analyst and judge model roles.
* The market's data sources and settlement criteria.
* Settlement reasoning and the on-chain transaction.

Settlement reasoning explains how the evidence was assessed against the market's rules. Delphi displays it only when a settlement artifact is available.

<div data-with-frame="true"><figure><img src="https://3382892862-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Ft59pTERBDU0JfP4e2nEP%2Fuploads%2FhNyVk9nqcVsevNiNajKC%2Fimage.png?alt=media&amp;token=9364f532-a4f1-4a17-882b-e170abdb6a46" alt=""><figcaption></figcaption></figure></div>

### What Winners Receive

When a market settles to a winning outcome, winning shares become claimable from the market page or *Claimable* in *Activity:*

* On LMSR markets, each winning share pays $1.&#x20;
* On DPM markets, winning shares split the pool.

### What Does "No Outcome" Mean?

Sometimes a market closes without a winning outcome. Delphi displays this state as *No Outcome.*

When this happens:

* No listed outcome wins.
* Positions pay at the final market prices when trading closed. On LMSR markets, prices freeze at close, so a share priced at 12% pays $0.12.
* Payouts may be higher or lower than the original purchase amount.
* Proceeds appear in the **Payouts** section of [Activity](/activity).

This is not a refund of the original purchase amount.

For example, imagine **Yes** costs `$0.70` and **No** costs `$0.30` when trading closes. If the market has no outcome, Yes positions pay at `$0.70` per unit and No positions pay at `$0.30` per unit. No position receives a winner-takes-all payout.

{% hint style="info" %}
**No outcome** differs from a market removed for a policy violation. Removed markets display **Removed** in the app.
{% endhint %}

### Frequently Asked Questions

These answers cover automated settlement. For other common questions, see [Help](/help).

<details>

<summary>Does the creator choose the winner?</summary>

No. The creator defines the market and reviews its suggested sources and criteria. The Automated Settlement workflow selects the final outcome after close.

</details>

<details>

<summary>Can the creator change the rules after the market goes live?</summary>

No. The settlement inputs lock when the market is created. Traders rely on the published configuration.

</details>

<details>

<summary>Does Automated Settlement guarantee the correct answer?</summary>

No. It evaluates available evidence against declared rules. Models, sources, and market definitions can still be incomplete or wrong.

</details>

<details>

<summary>Why does settlement take time?</summary>

Official evidence may not be available at trading close. Delphi waits for evidence, runs the analyst and judge workflow, and submits the result on-chain, within 48 hours of close

</details>

<details>

<summary>Where can I see why a market settled?</summary>

Open the market and select *View Settlement Report.* Settlement reasoning appears when a supporting artifact is available.

</details>

<details>

<summary>What happens if Delphi cannot declare a winning outcome?</summary>

The market displays *No Outcome.* Positions pay at their final market prices, and proceeds appear under *Payouts.*

</details>

<details>

<summary>Can an automated market still be removed?</summary>

Yes. Policy enforcement is separate from settlement. Policy-flagged markets display *Removed.*

</details>

<details>

<summary>Who settles markets opened through Predict Anything?</summary>

The same automated workflow. Delphi created the market, but it doesn't pick the winner, and its opening position settles alongside everyone else's.

</details>

### Next Steps

* Learn how to [create a clear market](/create-a-market).
* Learn how to [explore markets and trade](/explore-and-trade).
* Review positions and payouts in [Activity](/activity).
* Read more about [Gensyn REE](https://docs.gensyn.ai/tech).


# Settling a Market Manually

Legacy guidance for manually settling markets created before Automated Settlement.

{% hint style="success" %}
**Automated markets do not require creator action after close.** Delphi runs the settlement workflow automatically. See [How Automated Settlement Works](/how-ai-settlement-works).
{% endhint %}

## Settling a Market Manually

This guide applies only to markets created before Automated Settlement became available. These markets display a *Legacy* label.

### Legacy Manual Markets

You cannot create a new manual-settlement market. Instead, all new markets utilize the Automated Settlement process.

{% hint style="warning" %}
Only follow this guide when settling an existing **Legacy** market. For every other market, Delphi settles automatically after trading closes.
{% endhint %}

### Settle a Legacy Market

Legacy markets require creator action after close. You have 24 hours to settle the market.

To settle a market manually:

1. Open the closed market and select *Settle Market*.
2. Copy the locked settlement prompt.
3. Run it through the market's configured judge model.
4. Paste the output, select the matching outcome, and confirm.
   1. For cloud-hosted models, run the prompt directly. These models can access the market's specified sources.
   2. For verifiable local models, retrieve the specified source data first. Append it to the settlement prompt, then run the prompt in [Gensyn's REE](https://docs.gensyn.ai/tech). Paste the resulting [settlement receipt](https://docs.gensyn.ai/tech/ree/receipts) as the model output.

{% hint style="warning" %}
The receipt verifies the computation from its recorded inputs. It does not verify that the source data was correct.
{% endhint %}

### Claiming Fees and Payouts

After you settle a Legacy market, select **Claim Now** on the market page to claim your creator fee earnings and any winning shares you hold.

The *Claimable* tab in [Activity](/activity) lists unredeemed winning shares.

### What if None of Your Outcomes Apply?

Do not force an incorrect outcome. Let the deadline pass if no listed outcome applies.

The market resolves to *No Outcome*. Positions pay at the final market prices, which may differ from their original cost.

### What Happens If You Miss the Deadline

If you do not settle a Legacy market within 24 hours, it resolves to *No Outcome*.

* Your initial liquidity is forfeited.
* Positions pay at final market prices.
* Proceeds may be higher or lower than the original cost.

{% hint style="info" %}
This is not a traditional refund. Participants can claim the value of their remaining positions from **Payouts** in [Activity](/activity).
{% endhint %}


# Profile

View a creator's markets, performance metrics, and verified identity.

## Profile

Each Delphi user has a public creator profile. Profiles show markets someone created, their creator metrics, and their verified identity (if an active **X** account was linked).

<div data-with-frame="true"><figure><img src="https://3382892862-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Ft59pTERBDU0JfP4e2nEP%2Fuploads%2FJHh5HoYVjoopriA4gqGq%2Fimage.png?alt=media&amp;token=3d8853e6-df05-45ac-99fc-b67033541148" alt=""><figcaption></figcaption></figure></div>

Profiles do not show positions, portfolio value, P\&L, trade history, followers, or a bio.

### Find a Profile

Open *Profile* in the top navigation to view your own profile.&#x20;

{% hint style="info" %}
This option appears only while signed in.
{% endhint %}

You can also open a creator's profile from:

* Their name on the [Leaderboard](/leaderboard).
* The creator line on a market page.
* The avatar or creator name on a market card.

Profiles remain public when signed out. Owner-only controls are hidden.

### Read a Creator Profile

The banner shows the creator's **\[1]** avatar, their **\[2]** display name, and **\[3]** wallet address. You can select the copy icon to copy the address.

<div data-with-frame="true"><figure><img src="https://3382892862-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Ft59pTERBDU0JfP4e2nEP%2Fuploads%2FUOGtyZ5ZNeUAmNVVcSPz%2Fimage.png?alt=media&amp;token=c38dab8d-5639-46ea-a3e6-7c8f37902359" alt=""><figcaption></figcaption></figure></div>

Creators who link an X account display its handle and a *Verified* badge. If no username is set, Delphi shows a shortened wallet address instead.&#x20;

Three all-time metrics appear in the banner:

* **Markets Created:** The number of markets authored.
* **Total Volume:** Trading volume across those markets.
* **Settlement Rate:** The percentage of markets with a settled outcome.

### Browse Created Markets

The *Created Markets* grid lists every market the creator has made. Use the controls above it to:

* Filter by category or market status.
* Search market titles.
* Sort by liquidity, creation date, or closing date.

You can combine filters and share the resulting profile URL. Select *Load More* to view additional markets.

<div data-with-frame="true"><figure><img src="https://3382892862-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Ft59pTERBDU0JfP4e2nEP%2Fuploads%2FJQPZY1n1aXuh2pPFDPNw%2Fimage.png?alt=media&amp;token=f9ffabe3-e55a-4f6f-b89e-410b91311973" alt=""><figcaption></figcaption></figure></div>

Each card shows the market's status, category, liquidity, and close date. Settled markets also show the final resolution. Select a card title to open the market.

On eligible active binary markets, *Yes* and *No* open the market with that outcome selected in the trade panel.

{% hint style="info" %}
The profile shows markets a creator made. Use [Activity](/activity) to view your positions, trades, and payouts.
{% endhint %}

### Manage Your Profile

Only your own profile includes management controls.

1. **Editing your username:** Select *Edit* beside your name to set a username. Usernames must contain 3 to 24 lowercase letters, numbers, or underscores. They must start with a letter.
2. **Linking your X account:** If you have not linked X, select *Link X Account* to connect it. Your verified handle then appears on your profile.


# Leaderboard

Compare market creators by earnings, volume, and settled markets.

## Creator Leaderboard

The [Leaderboard](https://app.delphi.fyi/leaderboard) ranks Delphi creators by earnings. It is public, so you can browse it without connecting a wallet.

Use it to discover creators, compare their market activity, and explore the markets they have created.

### Choose a Time Window

Use the selector in the top-right to view rankings for:

* **7 Days:** Earnings and activity from the last 7 days.
* **30 Days:** Earnings and activity from the last 30 days.
* **All Time:** The default view, displaying earnings and activity across the creator's full history.

### How Ranking Works

Creators rank by *Total* earnings for the selected time window. The total combines *Creator Earnings***,** which is the creator's share of trading fees from their markets, and earnings credited to them via creator referrals (legacy).

{% hint style="info" %}
Creators remain listed even when their earnings are `$0.00`. They appear below creators with earnings in that window.
{% endhint %}

### Read the Leaderboard

The top three creators appear in the podium. Select any podium card to open that creator's [public profile](/profile#read-a-creator-profile).

<div data-with-frame="true"><figure><img src="https://3382892862-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Ft59pTERBDU0JfP4e2nEP%2Fuploads%2FO1AW4JP5U7Q16DoVsPU4%2Fimage.png?alt=media&amp;token=3ba0195e-794a-447f-a85d-4ebee1f763a3" alt=""><figcaption></figcaption></figure></div>

The full table shows:

* **Rank:** The creator's position by total earnings.
* **Creator:** Their profile image and username. Creators without a username display a shortened wallet address.
* **Settled Markets:** The number of their markets that have settled.
* **Volume:** Total trading volume across their markets.
* **Creator Earnings and Total Earnings:** Earnings for the selected window.

{% hint style="info" %}
*Settled Markets* differs from *Markets Created*. A creator may have active, pending, or removed markets that do not count as settled.
{% endhint %}

### Explore a Creator's Markets

Select a creator from the podium or table to open their public profile. Use it to browse their markets and review their track record.

See [Profile](/profile#browse-created-markets) for profile controls and market filters.


# Activity

Track your open positions, unredeemed winning shares, trade history, created markets, and no-outcome payouts.

## Your Activity

The *Activity* page is your personal dashboard. It shows everything related to your trading and market creation history in one place.

### Overview Stats

At the top of the page, three summary cards show your high-level stats:

* **Total Volume:** The total amount of USDC you've traded across all markets.
* **Win Rate:** The percentage of your settled positions that resulted in a payout.
* **Markets Created:** How many markets you've created.

### Tabs

You can find five tabs that organise your activity below:

<div data-with-frame="true"><figure><img src="https://3382892862-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Ft59pTERBDU0JfP4e2nEP%2Fuploads%2FaqCky10p8DOTfzDim8XS%2Fexploring_activity_tabs.gif?alt=media&amp;token=78e92d48-275c-4ec8-8d2b-8d1f91888f06" alt=""><figcaption></figcaption></figure></div>

#### Open Positions

Shows all your currently active positions in markets that haven't settled yet. For each position, you'll see the market question, the outcome you selected (your claim), the cost you paid, the current estimated value, and your share of the outcome pool as a percentage.

Current values are estimates that change as additional trades are placed. You can buy and sell positions until the market closes.

#### Claimable

Winning shares from markets that resolved to an outcome appear here until you redeem them.

Proceeds from markets that closed with *No Outcome* appear under *Payouts* instead.

#### History

A chronological record of all your activity: trades (buys and sells), markets you've created, and settlements. Each entry shows the relevant details and timestamps.

#### My Markets

Lists all the markets you've created. For each market, you'll see its **\[1]** name, **\[2]** status, **\[3]** market type, **\[4]** volume, and **\[5]** creation time.&#x20;

Statuses include:

* **Active:** Open for trading.
* **Pending settlement:** Trading has closed and settlement is scheduled or running.
* **Settled:** A winning outcome was selected.
* **No outcome:** No winning outcome was declared. Positions pay at final market prices.
* **Removed:** The market was removed under Delphi's policy process.

Automated markets settle without creator action. If you have an existing **Legacy** market, monitor it closely and [settle it before the deadline](/settling-a-market#what-happens-if-you-miss-the-deadline).

#### Payouts

Proceeds from markets that closed with *No Outcome* appear here. You can claim the value of your remaining positions at the final frozen market price. This value may be higher or lower than the amount you originally paid.

This tab replaced *Refunds* because these proceeds may differ from the original purchase amount. See [What Does "No Outcome" Mean?](/how-ai-settlement-works#what-does-no-outcome-mean)

{% hint style="info" %}
If there are no payouts to claim, the *Payouts* tab will indicate that.
{% endhint %}


# Help

Restricted regions, supported wallets, gas fees, market mechanisms, and other common questions about using Delphi.

## Help & FAQs

Find answers to common questions about accessing Delphi, connecting your wallet, understanding payouts, and more.

### Restricted Regions

Delphi is not available in the following jurisdictions:

* Cuba
* Iran
* North Korea
* Syria
* Russia
* Crimea, Donetsk, and Luhansk regions of Ukraine

Delphi trading is currently not available in the United States and South Korea. Users in these countries may access other features, including submitting (non-monetary) predictions and viewing market data.

If you believe you are seeing a restriction in error, reach out to the team on [Discord](https://discord.gg/delphifyi). Please see our [Terms of Service](https://app.delphi.fyi/tos) for more information.

### Supported Wallets

Delphi supports two wallet connection methods:

* **Wallet providers:** Connect an existing wallet from one of 580+ providers.
* **Google / Email:** Enter your email address to create an embedded wallet automatically.

<details>

<summary>I connected MetaMask. Why do I have a new address?</summary>

New users who connect an external wallet get a Delphi embedded wallet with sponsored gas. You sign in with your wallet, but you trade from the new address, so fund that one. If you used Delphi with an external wallet before this change, you keep your original address.

</details>

<details>

<summary>Why is my deposit showing a small fee?</summary>

It's a fixed fee charged by the third-party bridge that moves your funds onto Gensyn mainnet, not a Delphi fee. On a very small deposit it can look large as a percentage. It isn't price slippage.

</details>

<details>

<summary>How do I withdraw to another chain?</summary>

Open the wallet menu and select *Withdraw*. You can send USDC to chains such as Base or Ethereum.

</details>

<details>

<summary>Do I need ETH for gas?</summary>

Not with an embedded wallet. Existing external-wallet users pay their own gas.

</details>

### Creating Markets

For guidance on creating effective markets, including writing clear questions, defining outcomes, reviewing settlement criteria, and handling edge cases, see [Create a Market](/create-a-market).

<details>

<summary>Do I need an invite or approval to create a market?</summary>

No. Any signed-in user can create a market, outside restricted regions. See [Create a Market.](/create-a-market)

</details>

<details>

<summary>Why can't I trade or create a market?</summary>

You're likely in the United States or one of its territories, where trading and creation aren't available.&#x20;

</details>

<details>

<summary>What happened to Creator Referrals and the $10 seed?</summary>

The referral program is winding down. No new invites since September 28, 2026; invites already sent can be accepted, and referral earnings paid, until October 12, 2026. The $10 seed campaign has ended.&#x20;

</details>

<details>

<summary>How much do creators earn?</summary>

A share of their market's trading fees, paid at settlement. The share is shown in the app and currently differs by market type.

</details>

### Market Types

<details>

<summary>What's the difference between LMSR and DPM?</summary>

On LMSR markets, an outcome's price is its probability. Your payout is fixed when you trade. Each winning share pays $1 when the market settles, or its final market price if it closes with *No Outcome.*

On DPM markets, you buy into a pool and winners split it. Payouts change as others trade.

LMSR is recommended because the price reads directly as a probability. You know what a share pays when you buy it. You can sell part of a position. There is always a price to trade at, even in a new market.

For a more detailed breakdown, read [this](https://docs.delphi.fyi/pages/Uty4JlTiuqWmOgRXjXGS#id-3.1-lmsr-and-dpm-market-mechanisms).

</details>

<details>

<summary>What does "Pays 1.49× if correct" mean?</summary>

On an LMSR market, each share of that outcome pays 1.49 times what it costs if the outcome wins. A share priced at about $0.67 pays $1.00.

If the market closes with *No **O**utcome*, shares pay their final market price instead.

</details>

<details>

<summary>Can I sell part of a position?</summary>

On LMSR markets, yes. You can sell anywhere from 1% to 100%.

On DPM markets, selling liquidates your whole position in that outcome.

</details>

<details>

<summary>Why does my LMSR market show funding as liquidity?</summary>

LMSR markets have no refundable deposit or seed shares. Your funding sets the market's liquidity. Some or all of it can come back at settlement, depending on where the market lands.

The market creation fee is charged separately from your funding.

</details>

### Understanding Payouts

How you're paid depends on the market type. Every market shows an `LMSR` or `DPM` badge.

* **LMSR markets:** Your payout is fixed when you trade. Each share pays $1 if its outcome wins, so the number of shares you buy decides what you'll receive. The trade form shows this before you confirm, and later trades don't change it. What changes is what your position is worth if you *sell now*, which moves with the market. You can sell any part of a position, from a small slice to all of it, at any time before trading closes.
* **DPM markets:** Your payout is an estimate. Winners split the pool, so what your shares are worth depends on how much ends up on each outcome, and that keeps changing until trading closes. **My Payout Preview** shows what you'd receive if the market resolved right now. Selling liquidates your entire position in that outcome. Partial sells aren't supported.

When the market settles to a winning outcome, your winning shares become claimable, at $1 each on LMSR or your share of the pool on DPM. Redeem them from the market page or the *Claimable* tab in [Activity](/activity).

If the market closes with *No Outcome*, no outcome wins, on either market type. Each position is worth its final market price when trading closed. On LMSR, for example, a share priced at 12% pays $0.12. You can claim these from *Payouts* in Activity.&#x20;

{% hint style="info" %}
This may be more or less than you paid, and it isn't a refund.&#x20;
{% endhint %}

### Market Lifecycle

Every market on Delphi moves through these stages:

1. **Active:** The market is open for trading. Anyone can buy and sell positions on the available outcomes. Odds shift in real time as trades are placed.
2. **Pending settlement:** Trading has closed. For an automated market, settlement is scheduled or running and may take up to 48 hours. No more trades can be placed.
3. **Settled:** A winning outcome was selected and winning shares are claimable.
4. **No outcome:** No winning outcome was declared. The automated workflow may not select an outcome. A Legacy manual market may miss its settlement deadline. Positions pay at final market prices and can be claimed from *Payouts* in [Activity](/activity).
5. **Removed:** The market was removed under Delphi's policy process.

Existing *Legacy* markets use manual settlement. Their creators have 24 hours after close to settle them. See [Settling a Market Manually](/settling-a-market#what-happens-if-you-miss-the-deadline).

***

If you're in need of any assistance, are encountering bugs, or have questions, you can [join the Delphi Discord channel.](https://discord.gg/delphifyi)


# SDK

TypeScript SDK for interacting with Delphi information markets on the Gensyn blockchain.

## Overview

This Delphi SDK provides a single `DelphiClient` interface for reading market data, executing trades, managing positions, and querying historical on-chain events.

### What it Does

The SDK has two core layers: the **\[1]** REST API client (for read operations) and the **\[2]** on-chain methods (for write operations).

1. **REST API client (*****reading)*****:** List and filter markets, query wallet positions, and check service health through Delphi's centralized API endpoints.
2. **On-chain methods (*****writing)*****:** Buy and sell outcome shares, approve token spending, redeem winning positions, and read contract state directly on the Gensyn blockchain via the Gateway contract.

{% hint style="info" %}
This is a **TypeScript** only SDK. There is no Python SDK at this time.
{% endhint %}

The `@gensyn-ai/gensyn-delphi-sdk` package is available on `npm`. It supports private key signing and Coinbase Developer Platform (CDP) Server Wallets.

The SDK supports testnet, mainnet, and `competition-testnet`. The competition network powers the agent trading competition.

#### Market Deployments

Testnet and mainnet use automated-settlement gateways by default. Some legacy markets remain on the earlier deployment.

The client resolves a market's owning gateway before each market-scoped operation. This includes trades, quotes, redemptions, and liquidations. See [On-Chain Methods](/tools/sdk/methods) for routing details.

Delphi app markets use Dynamic Parimutuel (DPM) pricing. Automated settlement changes settlement and routing. It does not change Delphi markets to LMSR.

`competition-testnet` is separate. Its agent-competition markets use LMSR contracts with the same SDK trading interfaces.

{% hint style="warning" %}
Setting `gatewayAddress` or `DELPHI_GATEWAY_CONTRACT` pins all calls to that gateway. It disables automatic routing.
{% endhint %}

#### Upgrading to 2.0.0

Automated settlement changes gateway addresses and market routing. Statuses now include `failed`, which requires liquidation rather than redemption.

{% hint style="info" %}
Default subgraphs now index automated-settlement events.
{% endhint %}

### Who it's For

The Delphi SDK is the foundational layer for any programmatic interaction with [Delphi](https://app.delphi.fyi/) markets. It is used directly by developers building custom integrations, and it powers the [Agentic Trading toolkit](/tools/agentic-trading) under the hood.


# Configuration

Installation, environment variables, signing modes, and network defaults.

## Installation

You can use `npm` to install this SDK.

```bash
npm install @gensyn-ai/gensyn-delphi-sdk
```

{% embed url="<https://github.com/gensyn-ai/gensyn-delphi-sdk.git>" %}

### Generating an API Key

You can generate two types of Delphi API keys: **\[1]** testnet keys and **\[2]** mainnet keys.

* [Delphi API Key Generator (Testnet)](https://delphi-api-access.gensyn.ai/)
* [Delphi API Key Generator (Mainnet)](https://api-access.delphi.fyi/)

`competition-testnet` shares the testnet API deployment, so you'll use a testnet API key.

### Client Initialization

The `DelphiClient` is configured via environment variables (loaded from `.env` automatically) or by passing a config object to the constructor.

Constructor options take precedence over env vars:

```typescript
import { DelphiClient } from "@gensyn-ai/gensyn-delphi-sdk";

// Option 1: Environment variables (recommended)
const client = new DelphiClient();

// Option 2: Explicit config (overrides env vars)
const client = new DelphiClient({
  network: "testnet",
  signerType: "private_key",
  privateKey: "0xYourPrivateKey",
  apiKey: "your-api-key",
});
```

### Environment Variables

There are several core settings set by `env` vars.

#### Core Settings

| Variable                         | Description                                                                                     | Default             |
| -------------------------------- | ----------------------------------------------------------------------------------------------- | ------------------- |
| `DELPHI_NETWORK`                 | Network to use: `testnet`, `mainnet`, or `competition-testnet`                                  | `testnet`           |
| `DELPHI_SIGNER_TYPE`             | Signing method: `cdp_server_wallet` or `private_key`                                            | `cdp_server_wallet` |
| `DELPHI_API_ACCESS_KEY`          | REST API key (required for API methods)                                                         | —                   |
| `DELPHI_API_BASE_URL`            | Override the REST API base URL                                                                  | (network default)   |
| `DELPHI_APP_URL`                 | Delphi web app base URL, used to build `marketUrl`                                              | (network default)   |
| `DELPHI_GATEWAY_CONTRACT`        | Pin every call to this Gateway and disable routing                                              | (network default)   |
| `DELPHI_LEGACY_GATEWAY_CONTRACT` | Override the legacy Gateway address                                                             | (network default)   |
| `DELPHI_FACTORY_CONTRACT`        | Override the automated-settlement Factory address                                               | (network default)   |
| `DELPHI_LEGACY_FACTORY_CONTRACT` | Override the legacy Factory address                                                             | (network default)   |
| `DELPHI_TOKEN_ADDRESS`           | Override the collateral token address: $TEST on testnet, USDC on mainnet, or TST on competition | (network default)   |
| `DELPHI_SUBGRAPH_URL`            | Override the Goldsky subgraph endpoint                                                          | (network default)   |
| `GENSYN_RPC_URL`                 | Override the JSON-RPC endpoint                                                                  | (network default)   |
| `GENSYN_CHAIN_ID`                | Override the chain ID                                                                           | (network default)   |

#### Private Key Signing

For development use with `DELPHI_SIGNER_TYPE=private_key`:

| Variable             | Description                       |
| -------------------- | --------------------------------- |
| `WALLET_PRIVATE_KEY` | Hex-encoded private key (`0x...`) |

#### CDP Server Wallet Signing

For production use with `DELPHI_SIGNER_TYPE=cdp_server_wallet` (default):

| Variable             | Description                                  |
| -------------------- | -------------------------------------------- |
| `CDP_API_KEY_ID`     | Coinbase Developer Platform API key ID       |
| `CDP_API_KEY_SECRET` | Coinbase Developer Platform API key secret   |
| `CDP_WALLET_SECRET`  | CDP Server Wallet secret                     |
| `CDP_WALLET_ADDRESS` | On-chain address of the CDP wallet (`0x...`) |

{% hint style="info" %}
`@coinbase/cdp-sdk` is a peer dependency only required when using CDP signing. Private key users do not need it installed.
{% endhint %}

#### Network Defaults

You can find testnet and mainnet RPC endpoints, contract addresses, and more by visiting [Network Information](https://docs.gensyn.network/network-information) on the [Gensyn Foundation](https://docs.gensyn.network/) docs.

|                                | Testnet                                                                                                                            | Mainnet                                                                                                                            | Competition testnet                                                                                                                  |
| ------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------ |
| Chain ID                       | `685685`                                                                                                                           | `685689`                                                                                                                           | `685685`                                                                                                                             |
| RPC URL                        | `https://gensyn-testnet.g.alchemy.com/public`                                                                                      | `https://gensyn-mainnet.g.alchemy.com/public`                                                                                      | `https://gensyn-testnet.g.alchemy.com/public`                                                                                        |
| Gateway (automated settlement) | `0x22ea355D7218Dc86b4c83732cBbd01f7Ff2332b3`                                                                                       | `0x982a67aE92D8de361957249fB2BB4a62BCc6A8d5`                                                                                       | `0x097599c9D966fF496284b892A8F13BF885b258ef`                                                                                         |
| Factory (automated settlement) | `0x97d2b3F0614C8189343A38094629FCE2910b727A`                                                                                       | `0x9C73417f79a1361c6aF9Bd828343badEE1b84936`                                                                                       | `0xEa9D0a78d0209916e88e363B8FDa3e23206Ff49b`                                                                                         |
| Gateway (legacy)               | `0x7b8FDBD187B0Be5e30e48B1995df574A62667147`                                                                                       | `0x4e4e85c52E0F414cc67eE88d0C649Ec81698d700`                                                                                       | —                                                                                                                                    |
| Factory (legacy)               | `0xd03CEC55802f0D44D844384E1144B25717315E5A`                                                                                       | `0x4596d847eA56DCf9A37944c13793Af802Fc5D1eC`                                                                                       | —                                                                                                                                    |
| Collateral token               | `0x0724D6079b986F8e44bDafB8a09B60C0bd6A45a1` ($TEST)                                                                               | `0x5b32c997211621d55a89Cc5abAF1cC21F3A6ddF5` (USDC)                                                                                | `0x8A2d75753362Eb5D5669a2c22cbf394b26a0571F` (TST)                                                                                   |
| API URL                        | `https://delphi-api.gensyn.ai/`                                                                                                    | `https://api.delphi.fyi/`                                                                                                          | `https://delphi-api.gensyn.ai/`                                                                                                      |
| Subgraph URL                   | [Goldsky endpoint](https://api.goldsky.com/api/public/project_cmnoqdag1obop01z3efnu8ssq/subgraphs/delphi-testnet-autoset/1.0.0/gn) | [Goldsky endpoint](https://api.goldsky.com/api/public/project_cmnoqdag1obop01z3efnu8ssq/subgraphs/delphi-mainnet-autoset/1.0.0/gn) | [Goldsky endpoint](https://api.goldsky.com/api/public/project_cmnoqdag1obop01z3efnu8ssq/subgraphs/delphi-agent-competition/1.0.0/gn) |
| App URL                        | `https://testnet.delphi.fyi`                                                                                                       | `https://app.delphi.fyi`                                                                                                           | `https://agent-competition.gensyn.ai`                                                                                                |

The default addresses target automated-settlement contracts. Configure the gateway and factory overrides when you need a specific deployment.

### Gateway Routing

For each market-scoped call, the client checks both factories with `marketProxiesExist`. It caches the result and routes to the owning gateway.

Use `resolveGateway(marketAddress)` when making direct contract calls. A configured `gatewayAddress` or `DELPHI_GATEWAY_CONTRACT` pins calls and bypasses this lookup.

### Competition Network

`competition-testnet` uses the Gensyn testnet chain and competition-specific LMSR contracts. [Delphi](https://app.delphi.fyi/) app markets on testnet and mainnet continue to use DPM.

It has no legacy deployment, so routing is a no-op.

The client automatically sends `X-Delphi-Mode: competition` with REST requests. Reads default to the active competition. You can pass `competitionId` to select another competition.

{% hint style="warning" %}
Use TST as collateral. Testnet uses $TEST and mainnet uses USDC.
{% endhint %}

### Signing Modes

Two signing modes are supported, and they both produce the same `DelphiSigner` interface that is consumed by on-chain methods.

#### Private Key (for development)

```
DELPHI_SIGNER_TYPE=private_key
WALLET_PRIVATE_KEY=0x<hex-private-key>
```

Or you can create a signer directly:

```typescript
import { createPrivateKeySigner } from "@gensyn-ai/gensyn-delphi-sdk";

const signer = await createPrivateKeySigner({
  privateKey: "0xYourPrivateKey",
  rpcUrl: "https://gensyn-testnet.g.alchemy.com/public",
  chainId: 685685,
});
```

#### CDP Server Wallet (for production)

```bash
DELPHI_SIGNER_TYPE=cdp_server_wallet
CDP_API_KEY_ID=<key-id>
CDP_API_KEY_SECRET=<key-secret>
CDP_WALLET_SECRET=<wallet-secret>
CDP_WALLET_ADDRESS=0x<wallet-address>
```

To get your CDP credentials, create an account at [Coinbase Developer Platform](https://portal.cdp.coinbase.com/), generate an API key, and set up a server wallet. See the [CDP Server Wallet documentation](https://docs.cdp.coinbase.com/server-wallets/v2/introduction/welcome) for a full walkthrough. Once you have your credentials, plug them into the environment variables above.

You can also create this directly:

```typescript
import { createCdpSigner } from "@gensyn-ai/gensyn-delphi-sdk";

const signer = await createCdpSigner({
  apiKeyId: "your-cdp-api-key-id",
  apiKeySecret: "your-cdp-api-key-secret",
  walletSecret: "your-cdp-wallet-secret",
  walletAddress: "0xYourWalletAddress",
  rpcUrl: "https://gensyn-testnet.g.alchemy.com/public",
  chainId: 685685,
});
```

CDP Server Wallets are managed by [Coinbase Developer Platform.](https://www.coinbase.com/developer-platform) The SDK uses `@coinbase/cdp-sdk` under the hood.

### Accessing the Signer Directly

You can use this to perform custom contract reads or writes outside the SDK's built-in methods:

```typescript
const { address, publicClient, walletClient } = await client.getSigner();
```


# API Reference

REST API methods for listing markets, fetching market details, and querying wallet positions.

## Overview

All REST API methods read data from the Delphi API and require `DELPHI_API_ACCESS_KEY` to be set (except `health()`).

### health()

Check service availability. Does not require authentication.

```typescript
const { status } = await client.health();
```

### Markets

#### listMarkets(*params*)

Retrieve markets with optional filtering and pagination using `listMarkets`.

```typescript
const { markets } = await client.listMarkets({
  status: "open",
  category: "crypto",
  orderBy: "liquidity",    // "liquidity" | "created" | "settles_at"
  verifiable: true,
  skip: 0,
  limit: 50,
});
```

#### **Parameters**

| Field                           | Type           | Default            | Description                                                                     |
| ------------------------------- | -------------- | ------------------ | ------------------------------------------------------------------------------- |
| `skip`                          | `number`       | `0`                | Pagination offset                                                               |
| `limit`                         | `number`       | `50`               | Maximum records returned                                                        |
| `status`                        | `MarketStatus` | —                  | `"open"` \| `"awaiting_settlement"` \| `"settled"` \| `"expired"` \| `"failed"` |
| `category`                      | `string`       | —                  | Filter by metadata category                                                     |
| `orderBy`                       | `string`       | `liquidity`        | `liquidity`, `created`, or `settles_at`                                         |
| `competitionId`                 | `string`       | Active competition | Competition to query                                                            |
| `verifiable`                    | `boolean`      | —                  | Filter by verifiable settlement                                                 |
| `pricesAndImpliedProbabilities` | `boolean`      | —                  | Include prices and implied probabilities                                        |

#### getMarket(*params*)

Retrieve a single market by ID.

```typescript
const market = await client.getMarket({
  id: "0xMarketContractAddress",
  competitionId: "optional-competition-id",
});
```

{% hint style="info" %}
This returns the same `Market` type. The `id` comes from `listMarkets`.
{% endhint %}

#### Market Type

```typescript
export interface Market {
  id: string; // On-chain contract address of the market proxy
  appMarketId: string; // UUID identifying the market in the Delphi app UI
  marketUrl: string; // Direct link to the market on the Delphi app
  status: MarketStatus; // "open" | "awaiting_settlement" | "settled" | "expired" | "failed"
  category: string; // Market category, e.g. "crypto", "sports", "politics"
  deployer: string; // Wallet address that deployed/created the market
  implementation: string; // Market implementation contract address
  metadataUri: string; // URI pointing to the market metadata
  metadataUriContentHash: string; // Content hash for the metadata URI
  metadata: unknown; // Parsed market metadata returned by the API
  dataSources: unknown; // Data sources used for market resolution/verification
  createdAt: string; // ISO timestamp when the market was created
  fetchedAt: string | null; // ISO timestamp when metadata was last fetched, or null
  fetchResponseStatus: string | null; // Status from the metadata fetch attempt, or null
  resolvesAt: string | null; // ISO timestamp when the market is expected to resolve, or null
  settledAt: string | null; // ISO timestamp when the market was settled, or null
  settlesAt: string | null; // ISO timestamp for scheduled settlement, or null
  winningOutcomeIdx: string | null; // Winning outcome index after settlement, or null
  tradingFee: string | null; // Trading fee value returned by the API, or null
  proof: string | null; // Resolution proof or verification reference, or null
  error: string | null; // Error message related to market metadata/resolution, or null
  verifiable: boolean; // Whether the market has verifiable settlement enabled
}
```

#### Metadata Shape

```typescript
const meta = market.metadata as {
  question?: string;            // The market question
  title?: string;               // Alternative title
  description?: string;
  category?: string;
  outcomes?: string[];          // Outcome labels — index matches outcomeIdx
  resolutionCriteria?: string;
  endDate?: string;             // ISO date
} | null;
```

{% hint style="danger" %}
The `outcomes` array is critical for labelling: `outcomes[0]` is the label for `outcomeIdx: 0`.
{% endhint %}

The key address fields here are:

| Field                   | Purpose                                                           |
| ----------------------- | ----------------------------------------------------------------- |
| `market.id`             | Pass to `getMarket({ id })`                                       |
| `market.id`             | Pass as `marketAddress` to SDK trading, quote, and approval calls |
| `market.implementation` | Implementation contract address; do not use as `marketAddress`    |

### Market Status Values

```typescript
type MarketStatus =
  | "open"
  | "awaiting_settlement"
  | "settled"
  | "expired"
  | "failed";
```

| Status                | Meaning                                                  |
| --------------------- | -------------------------------------------------------- |
| `open`                | Trading active                                           |
| `awaiting_settlement` | Trading deadline passed, awaiting settlement             |
| `settled`             | Winning outcome set; positions redeemable                |
| `expired`             | Market expired without settlement; liquidate positions   |
| `failed`              | Oracle could not resolve the market; liquidate positions |

{% hint style="info" %}
The API returns these as *strings*.

The underlying contract exposes an `int enum`: 0 = open, 1 = awaiting settlement, 2 = settled, 3 = expired, and 4 = failed.
{% endhint %}

A winning outcome is set by the oracle on automated-settlement markets. Legacy markets use the creator's winner submission.

### Usage Patterns

You can paginate through all markets like this:

```typescript
let skip = 0;
const limit = 50;
const all: Market[] = [];

while (true) {
  const { markets } = await client.listMarkets({ status: "open", skip, limit });
  if (!markets || markets.length === 0) break;
  all.push(...markets);
  if (markets.length < limit) break;
  skip += limit;
}
```

Or, find a market using a question keyword:

```typescript
const { markets } = await client.listMarkets({ status: "open", limit: 100 });
const match = markets?.find(m => {
  const meta = m.metadata as { question?: string } | null;
  return meta?.question?.toLowerCase().includes("keyword");
});
```

### Positions

#### listPositions(*params*)

Retrieve positions for a wallet address.

```typescript
const { positions } = await client.listPositions({
  wallet: "0xYourWalletAddress",
  redeemedOrLiquidated: false,
  skip: 0,
  limit: 50,
});
```

#### Position Type

```typescript
interface Position {
  id: string;
  marketProxy: string;      // Market proxy address (use as marketAddress)
  wallet: string;
  outcomeIdx: string;       // Outcome index as string — parse with parseInt()
  shares: string;           // 18-decimal bigint as string — parse with BigInt()
  redeemedOrLiquidated: boolean;
  tokensRedeemed: string;   // Collateral amount as a 6-decimal bigint string
  marketStatus: "open" | "awaiting_settlement" | "settled" | "expired" | "failed";
}
```

Be careful when parsing, because `shares` and `tokensRedeemed` are *string representations* of [bigints](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-2.html#bigint).

```typescript
const shares = Number(BigInt(position.shares)) / 1e18;
const tokensRedeemed = Number(BigInt(position.tokensRedeemed)) / 1e6;
const outcomeIdx = parseInt(position.outcomeIdx);
```

### Redemption

Markets must be `settled` (winner submitted) before redeeming. Only holders of the winning outcome receive tokens.

{% hint style="warning" %}
`expired` and `failed` markets have no winning outcome. Use `liquidate()` rather than `redeemMarket()` for these positions.
{% endhint %}

{% hint style="warning" %}
Positions with `shares === "0"` cannot be redeemed or liquidated because the wallet holds no stake.

The positions API may return zero-share entries for markets the wallet previously participated in but fully exited. Always check `BigInt(position.shares) > 0n` before attempting redeem or liquidate calls.
{% endhint %}

#### 1. Single (Market) Redemption

```typescript
const { transactionHash, sharesIn, tokensOut } = await client.redeemMarket({
  marketAddress: "0x..." as `0x${string}`,
});
console.log(`Redeemed ${Number(sharesIn) / 1e18} shares → ${Number(tokensOut) / 1e6} collateral tokens`);
```

#### 2. Batch (Market) Redemption

```typescript
const { results, totalTokensOut } = await client.redeemPositions({
  marketAddresses: ["0x...", "0x..."],
});

for (const r of results) {
  if (r.success) {
    console.log(`${r.marketAddress}: ${Number(r.tokensOut!) / 1e6} collateral tokens`);
  } else {
    console.error(`${r.marketAddress}: ${r.error}`);
  }
}
console.log(`Total redeemed: ${Number(totalTokensOut) / 1e6} collateral tokens
`);
```

#### 3. Batch-Redeeming all Unredeemed, Settled Positions

```typescript
const { positions } = await client.listPositions({
  wallet: myAddress,
  redeemedOrLiquidated: false,
});

const settledProxies: `0x${string}`[] = [];
for (const p of positions ?? []) {
  if (BigInt(p.shares) === 0n) continue;
  const market = await client.getMarket({ id: p.marketProxy });
  if (market.status === "settled") {
    settledProxies.push(p.marketProxy as `0x${string}`);
  }
}

if (settledProxies.length > 0) {
  const { results, totalTokensOut } = await client.redeemPositions({
    marketAddresses: settledProxies,
  });
}
```

#### 4. Liquidating Expired or Failed Positions

`getMarketStatus()` reads the current on-chain status. Use it when REST data may be stale.

```typescript
import { LIQUIDATABLE_MARKET_STATUSES } from "@gensyn-ai/gensyn-delphi-sdk";

for (const p of positions ?? []) {
  if (BigInt(p.shares) === 0n) continue;

  const marketAddress = p.marketProxy as `0x${string}`;
  const status = await client.getMarketStatus(marketAddress);
  if (!LIQUIDATABLE_MARKET_STATUSES.includes(status)) continue;

  await client.liquidate({
    marketAddress,
    outcomeIndices: [0, 1], // Binary market; include every outcome index.
  });
}
```

#### Estimating Portfolio Value

Estimate the current liquidation value of all active positions:

```typescript
const { positions } = await client.listPositions({
  wallet: myAddress,
  redeemedOrLiquidated: false,
});

let totalValue = 0;
for (const p of positions ?? []) {
  const shares = BigInt(p.shares);
  if (shares === 0n) continue;

  const marketAddress = p.marketProxy as `0x${string}`;
  const outcomeIdx = parseInt(p.outcomeIdx);

  try {
    const { tokensOut } = await client.quoteSell({
      marketAddress, outcomeIdx, sharesIn: shares,
    });
    totalValue += Number(tokensOut) / 1e6;
  } catch {
    console.log(`${marketAddress} outcome ${outcomeIdx}: cannot quote (market may be closed)`);
  }
}
console.log(`Total estimated value: ${totalValue.toFixed(4)} collateral tokens`);
```


# On-Chain Methods

Trading, quoting, token approvals, and direct Gateway contract interaction via RPC.

## Overview

On-chain methods send transactions or read directly from the Gensyn blockchain via a Gateway contract.

### Market Deployments & Routing

Testnet and mainnet have automated-settlement and legacy deployments. Each market belongs to one of those deployments.

The client checks both factories with `marketProxiesExist`. It caches the result, then routes market-scoped calls to the owning gateway. This applies to buys, sells, quotes, redemptions, and liquidations.

Use `resolveGateway()` before making direct Gateway calls:

```typescript
const gateway = await client.resolveGateway(marketAddress);
```

Setting `gatewayAddress` or `DELPHI_GATEWAY_CONTRACT` pins every call. Pinning disables automatic routing. If you incorrectly pin a gateway, you can revert with `MarketProxyNotDeployedByFactory`.

### Contract Addresses

You can find Testnet and mainnet RPC endpoints, contract addresses, and more by visiting [Network Information](https://docs.gensyn.network/network-information) on the Gensyn Foundation docs.

### Trading

#### Pricing Mechanism (DPM)

Delphi app markets on testnet and mainnet use *Dynamic Parimutuel (DPM)* markets. This means:

* Prices shift continuously with every trade (no fixed order book)
* `spotImpliedProbability` reflects the market's current consensus probability
* For a binary market: `prob[0] + prob[1] = 1e18` (100%)
* A spot price of 0.65 collateral tokens per share means \~65% implied probability

{% hint style="info" %}
`competition-testnet` is separate from the Delphi app deployments. Its agent-competition markets use LMSR contracts. The SDK exposes the same market-scoped trading interfaces across both mechanisms.
{% endhint %}

### Quoting Trades

These are read-only and therefore do not consume any *gas.*

#### quoteBuy

The cost to receive an exact number of shares.

```typescript
const { tokensIn } = await client.quoteBuy({
  marketAddress: "0x..." as `0x${string}`,
  outcomeIdx: 0,
  sharesOut: BigInt(Math.round(10 * 1e18)),
});
const costUsdc = Number(tokensIn) / 1e6;
```

#### quoteSell

The payout for selling an exact number of shares.

```typescript
const { tokensOut } = await client.quoteSell({
  marketAddress: "0x..." as `0x${string}`,
  outcomeIdx: 0,
  sharesIn: BigInt(Math.round(5 * 1e18)),
});
const payoutUsdc = Number(tokensOut) / 1e6;
```

#### quoteRedeem and quoteLiquidate

`quoteRedeem()` estimates redemption for a settled market. `quoteLiquidate()` estimates exit value for an expired or failed market.

Use `redeemMarket()` only after settlement. Use `liquidate()` for `expired` and `failed` markets.

### Buying Shares

Token approval must exist before buying. The full flow with approval and slippage looks like this:

```typescript
const marketAddress = "0x..." as `0x${string}`;
const outcomeIdx = 0;
const sharesOut = BigInt(Math.round(10 * 1e18));

// 1. Quote the cost
const { tokensIn } = await client.quoteBuy({ marketAddress, outcomeIdx, sharesOut });

// 2. Ensure collateral-token approval (no-op if already approved)
await client.ensureTokenApproval({ marketAddress, minimumAmount: tokensIn });

// 3. Execute with 2% slippage
const maxTokensIn = tokensIn * 102n / 100n;
const { transactionHash } = await client.buyShares({
  marketAddress,
  outcomeIdx,
  sharesOut,
  maxTokensIn,
});
```

#### BuyShares (*params*)

| Field           | Type                | Description                                          |
| --------------- | ------------------- | ---------------------------------------------------- |
| `marketAddress` | `` `0x${string}` `` | Market proxy address                                 |
| `outcomeIdx`    | `number`            | Outcome index to buy                                 |
| `sharesOut`     | `bigint`            | Exact shares to receive (18 decimals)                |
| `maxTokensIn`   | `bigint`            | Maximum collateral spend — slippage cap (6 decimals) |

### Selling Shares

```typescript
const sharesIn = BigInt(Math.round(5 * 1e18));
const { tokensOut } = await client.quoteSell({ marketAddress, outcomeIdx, sharesIn });

const minTokensOut = tokensOut * 98n / 100n; // 2% slippage
const { transactionHash } = await client.sellShares({
  marketAddress,
  outcomeIdx,
  sharesIn,
  minTokensOut,
});
```

#### SellShares (*params*)

| Field           | Type                | Description                                               |
| --------------- | ------------------- | --------------------------------------------------------- |
| `marketAddress` | `` `0x${string}` `` | Market proxy address                                      |
| `outcomeIdx`    | `number`            | Outcome index to sell                                     |
| `sharesIn`      | `bigint`            | Exact shares to sell (18 decimals)                        |
| `minTokensOut`  | `bigint`            | Minimum collateral received — slippage floor (6 decimals) |

### Liquidating Positions

Liquidation exits positions without a winning outcome. It applies to expired and failed markets.

```typescript
const status = await client.getMarketStatus(marketAddress);
if (status === "expired" || status === "failed") {
  const { transactionHash } = await client.liquidate({
    marketAddress,
    outcomeIndices: [0, 1], // Covers a binary market.
  });
}
```

#### liquidate(*params*)

| Field            | Type                | Description           |
| ---------------- | ------------------- | --------------------- |
| `marketAddress`  | `` `0x${string}` `` | Market proxy address  |
| `outcomeIndices` | `number[]`          | Outcomes to liquidate |

Pass every outcome index where you hold shares. Omitted indices are not liquidated, and their funds remain locked. `[0, 1]` covers a binary market.

#### getMarketStatus(marketAddress)

Reads a market's lifecycle status from the owning gateway. This value is fresher than the REST API.

```typescript
const status = await client.getMarketStatus(marketAddress);
// "open" | "awaiting_settlement" | "settled" | "expired" | "failed"
```

### Slippage Guidelines

| Scenario                 | Recommended slippage |
| ------------------------ | -------------------- |
| Quiet market             | 1–2%                 |
| Active market            | 2–5%                 |
| Large trade (>$100)      | 5–10%                |
| Time-sensitive execution | 5%                   |

Here's an example of using integer arithmetic to avoid floating point:

```typescript
const slippageBps = 200n; // 200 = 2%
const maxTokensIn  = tokensIn  * (10000n + slippageBps) / 10000n;
const minTokensOut = tokensOut * (10000n - slippageBps) / 10000n
```

#### Common Contract Errors

| Error                             | Cause                           | Fix                                               |
| --------------------------------- | ------------------------------- | ------------------------------------------------- |
| `TokensInExceedsMax`              | Actual cost > maxTokensIn       | Re-quote and increase slippage                    |
| `TokensOutBelowMin`               | Actual payout < minTokensOut    | Re-quote and increase slippage                    |
| `MarketNotOpen`                   | Market closed or settled        | Cannot trade; check status                        |
| `SharesInExceedSupply`            | Selling more than held          | Query balance first                               |
| `GrossTokensOutNotPositive`       | Nothing to sell                 | Position is empty                                 |
| `ZeroTokensIn`                    | sharesOut too small             | Use a larger share amount                         |
| `MarketProxyNotDeployedByFactory` | Gateway does not own the market | Resolve the gateway or remove the pinned override |

### Token Approvals

#### getTokenAllowance(*params*)

Read the current ERC-20 allowance your wallet has granted to a market.

```typescript
const { allowance } = await client.getTokenAllowance({
  marketAddress: "0xMarket",
});
```

#### approveToken(*params*)

Approve the ERC-20 token for spending by a market.

{% hint style="info" %}
This defaults to unlimited (`uint256` max).
{% endhint %}

```typescript
// Approve unlimited
await client.approveToken({ marketAddress });

// Approve exact amount (e.g. 100 tokens; $TEST on testnet)
await client.approveToken({ marketAddress, amount: 100_000_000n });
```

#### ensureTokenApproval(*params*)

Check if sufficient allowance exists and only sends an approval transaction if needed. *Recommended before buying shares.*

```typescript
const { approvalNeeded, allowance, transactionHash } = await client.ensureTokenApproval({
  marketAddress: "0xMarket",
  minimumAmount: tokensIn,
  approveAmount: tokensIn * 10n, // optional; defaults to unlimited
});
```

{% hint style="info" %}
The SDK uses the configured token address from `DELPHI_TOKEN_ADDRESS` or the network default. It does not resolve a token address per market.
{% endhint %}

| Network             | Collateral token |
| ------------------- | ---------------- |
| Testnet             | $TEST            |
| Mainnet             | USDC             |
| Competition testnet | TST              |

### Gateway Contract Reference

This section is for advanced users who want to call the Gateway contract directly via `viem`.

The SDK uses `DYNAMIC_PARIMUTUEL_GATEWAY_ABI` on every network, including `competition-testnet`. The competition LMSR gateway exposes identical call signatures.

Competition differs in its underlying pricing math. Its `MarketSettled` event also omits market-creator economics fields.

#### viem Client Setup

Set up your viem client like this:

```typescript
import { createPublicClient, http, defineChain, type Abi } from "viem";
import {
  DELPHI_FACTORY_ABI,
  DYNAMIC_PARIMUTUEL_GATEWAY_ABI,
} from "@gensyn-ai/gensyn-delphi-sdk";

const chain = defineChain({
  id: Number(process.env.GENSYN_CHAIN_ID),
  name: "Gensyn Testnet",
  nativeCurrency: { name: "Ether", symbol: "ETH", decimals: 18 },
  rpcUrls: { default: { http: [process.env.GENSYN_RPC_URL!] } },
});

const publicClient = createPublicClient({ chain, transport: http(process.env.GENSYN_RPC_URL!) });
const gateway = await client.resolveGateway(marketProxy);
```

`resolveGateway()` creates a signer-backed client internally. Configure `WALLET_PRIVATE_KEY` or CDP credentials, even for read-only use.

{% hint style="warning" %}
Do not use `DELPHI_GATEWAY_CONTRACT` for direct market calls unless it is the owning gateway. `resolveGateway()` selects the correct deployment.
{% endhint %}

`DELPHI_FACTORY_ABI` is also exported for direct Factory reads, including `marketProxiesExist`.

#### Gateway Functions

All of the gateway functions, broken down into tables by **\[1]** read and **\[2]** write.

#### 1. *Read* Functions

| Function                   | Args                                      | Returns              | Notes                                                         |
| -------------------------- | ----------------------------------------- | -------------------- | ------------------------------------------------------------- |
| `quoteBuyExactOut`         | marketProxy, outcomeIdx, sharesOut        | `tokensIn: uint256`  | Collateral cost (6 dec)                                       |
| `quoteSellExactIn`         | marketProxy, outcomeIdx, sharesIn         | `tokensOut: uint256` | Collateral payout (6 dec)                                     |
| `spotImpliedProbability`   | marketProxy, outcomeIdx                   | `uint256`            | 1e18 = 100%                                                   |
| `spotImpliedProbabilities` | marketProxy, outcomeIndices\[]            | `uint256[]`          | Batch                                                         |
| `spotPrice`                | marketProxy, outcomeIdx                   | `uint256`            | 1e18 = 1.0 collateral tokens per share                        |
| `spotPrices`               | marketProxy, outcomeIndices\[]            | `uint256[]`          | Batch                                                         |
| `balanceOf`                | marketProxy, owner, outcomeIdx            | `uint256`            | Shares (18 dec)                                               |
| `batchBalanceOf`           | marketProxy, owners\[], outcomeIndices\[] | `uint256[]`          | Batch                                                         |
| `totalSupply`              | marketProxy, outcomeIdx                   | `uint256`            | Total shares (18 dec)                                         |
| `totalSupplies`            | marketProxy, outcomeIndices\[]            | `uint256[]`          | Batch                                                         |
| `getMarket`                | marketProxy                               | Market struct        | Full on-chain state                                           |
| `marketStatus`             | marketProxy                               | `uint8`              | 0=Open, 1=Awaiting settlement, 2=Settled, 3=Expired, 4=Failed |
| `token`                    | marketProxy                               | `address`            | Collateral token address                                      |

#### 2. *Write* Functions

Prefer the SDK methods over calling the Gateway directly, as they handle simulation, approval, and receipt waiting.

| Function      | Args                                            | Notes                             |
| ------------- | ----------------------------------------------- | --------------------------------- |
| `buyExactOut` | marketProxy, outcomeIdx, sharesOut, maxTokensIn | Use `DelphiClient.buyShares()`    |
| `sellExactIn` | marketProxy, outcomeIdx, sharesIn, minTokensOut | Use `DelphiClient.sellShares()`   |
| `redeem`      | marketProxy                                     | Use `DelphiClient.redeemMarket()` |
| `liquidate`   | marketProxy, outcomeIndices                     | Use `DelphiClient.liquidate()`    |

### Direct Read Examples

#### Implied Probability for All Outcomes

```typescript
const probs = await publicClient.readContract({
  address: gateway,
  abi: DYNAMIC_PARIMUTUEL_GATEWAY_ABI as Abi,
  functionName: "spotImpliedProbabilities",
  args: [marketProxy, [0n, 1n]],
}) as bigint[];
// probs[i] / 1e18 * 100 = implied probability %
```

#### Spot Prices

```typescript
const prices = await publicClient.readContract({
  address: gateway,
  abi: DYNAMIC_PARIMUTUEL_GATEWAY_ABI as Abi,
  functionName: "spotPrices",
  args: [marketProxy, [0n, 1n]],
}) as bigint[];
// prices[i] / 1e18 = collateral tokens per share
```

#### Full Market State

```typescript
const onchainMarket = await publicClient.readContract({
  address: gateway,
  abi: DYNAMIC_PARIMUTUEL_GATEWAY_ABI as Abi,
  functionName: "getMarket",
  args: [marketProxy],
}) as {
  config: {
    outcomeCount: bigint;
    k: bigint;
    tradingFee: bigint;         // 1e18 = 100%
    tradingDeadline: bigint;    // Unix timestamp
    settlementDeadline: bigint; // Unix timestamp
  };
  pool: bigint;
  tradingFees: bigint;
};

const feePercent = Number(onchainMarket.config.tradingFee) / 1e18 * 100;
const deadline = new Date(Number(onchainMarket.config.tradingDeadline) * 1000);
```

#### Share Balance for a Wallet

```typescript
const balance = await publicClient.readContract({
  address: gateway,
  abi: DYNAMIC_PARIMUTUEL_GATEWAY_ABI as Abi,
  functionName: "balanceOf",
  args: [marketProxy, walletAddress as `0x${string}`, BigInt(outcomeIdx)],
}) as bigint;
// balance / 1e18 = shares
```

#### Price Impact Estimation

```typescript
const spotPrices = await publicClient.readContract({
  address: gateway,
  abi: DYNAMIC_PARIMUTUEL_GATEWAY_ABI as Abi,
  functionName: "spotPrices",
  args: [marketProxy, [0n, 1n]],
}) as bigint[];

const currentPricePerShare = Number(spotPrices[outcomeIdx]) / 1e18;
const { tokensIn } = await client.quoteBuy({ marketAddress, outcomeIdx, sharesOut });
const quotedPricePerShare = (Number(tokensIn) / 1e6) / sharesHuman;
const priceImpact = ((quotedPricePerShare - currentPricePerShare) / currentPricePerShare) * 100;
console.log(`Price impact: ${priceImpact.toFixed(2)}%`);
```


# Subgraph

Querying historical on-chain event data through the Goldsky-indexed GraphQL endpoint.

## Overview

The Delphi SDK includes a `SubgraphClient` that queries on-chain event data indexed by a [Goldsky subgraph.](https://docs.goldsky.com/subgraphs/introduction)

This gives read-only access to historical *buys, sells, redemptions, liquidations,* and *settlements* without needing an archive node or parsing raw logs.

{% hint style="info" %}
For more information on using Goldsky to build on Gensyn, [click here.](https://docs.gensyn.network/builders/goldsky)
{% endhint %}

### Accessing the Subgraph Client

`getSubgraph()` returns a `SubgraphClient` instance configured with the correct Goldsky endpoint for the active network.

```typescript
import { DelphiClient } from "@gensyn-ai/gensyn-delphi-sdk";

const client = new DelphiClient();
const subgraph = client.getSubgraph();
```

#### URL Resolution Order

1. `config.subgraphUrl` (constructor option on `DelphiClient`)
2. `DELPHI_SUBGRAPH_URL` environment variable
3. Network default

| Network             | Default endpoint                                                                                                   |
| ------------------- | ------------------------------------------------------------------------------------------------------------------ |
| Testnet             | `https://api.goldsky.com/api/public/project_cmnoqdag1obop01z3efnu8ssq/subgraphs/delphi-testnet-autoset/1.0.0/gn`   |
| Mainnet             | `https://api.goldsky.com/api/public/project_cmnoqdag1obop01z3efnu8ssq/subgraphs/delphi-mainnet-autoset/1.0.0/gn`   |
| Competition testnet | `https://api.goldsky.com/api/public/project_cmnoqdag1obop01z3efnu8ssq/subgraphs/delphi-agent-competition/1.0.0/gn` |

The default endpoints index automated-settlement gateways only. Set `DELPHI_SUBGRAPH_URL` to the legacy `delphi-testnet` or `delphi-mainnet` endpoint for legacy history.

### SubgraphClient API

#### query(query, variables?)

You can execute any arbitrary GraphQL query against the subgraph. Returns the `data` field from the response or throws on errors.

```typescript
query<T = unknown>(query: string, variables?: Record<string, unknown>): Promise<T>
```

#### getMarketTrades(marketProxy, params?)

Returns all buy and sell events for a given market proxy address, sorted most-recent-first.

```typescript
getMarketTrades(
  marketProxy: string,
  params?: { first?: number; skip?: number }
): Promise<{ buys: SubgraphBuy[]; sells: SubgraphSell[] }>
```

Defaults: `first = 100`, `skip = 0`.

#### getMarketSettlement(marketProxy)

Returns settlement data for a market. A market can be settled or failed, never both.

```typescript
const settlement = await subgraph.getMarketSettlement(marketProxy);
```

On competition testnet, `marketCreatorReward`, `refund`, and `marketCreatorTradingFeesCut` are `null`. Do not request these fields in hand-written competition queries.

#### getMeta()

Returns the current indexed block, deployment hash, and whether the subgraph has indexing errors. Useful for checking data freshness.

```typescript
getMeta(): Promise<SubgraphMeta>
```

### Types

#### SubgraphBuy

```typescript
interface SubgraphBuy {
  id: string;
  block_number: string;
  timestamp_: string;          // Unix seconds as string
  transactionHash_: string;
  contractId_: string;
  marketProxy: string | null;
  buyer: string | null;
  outcomeIdx: string | null;
  tokensIn: string | null;     // Collateral spent (6-decimal bigint as string)
  sharesOut: string | null;    // Shares received (18-decimal bigint as string)
}
```

#### SubgraphSell

```typescript
interface SubgraphSell {
  id: string;
  block_number: string;
  timestamp_: string;
  transactionHash_: string;
  contractId_: string;
  marketProxy: string | null;
  seller: string | null;
  outcomeIdx: string | null;
  sharesIn: string | null;     // Shares sold (18-decimal bigint as string)
  tokensOut: string | null;    // Collateral received (6-decimal bigint as string)
}
```

#### SubgraphMeta

```typescript
interface SubgraphMeta {
  block: {
    number: number;
    timestamp: number | null;
    hash: string | null;
  };
  deployment: string;
  hasIndexingErrors: boolean;
}
```

#### SubgraphMarketSettled fields

```typescript
// Settlement-specific fields.
winningOutcomeIdx: string | null;
marketCreatorReward: string | null;
refund: string | null;
marketCreatorTradingFeesCut: string | null;
```

#### SubgraphMarketFailed fields

```typescript
// Failure-specific field.
marketProxy: string | null;
```

#### SubgraphMarketResolutionRequested fields

```typescript
// Resolution-request-specific fields.
marketProxy: string | null;
keeper: string | null;
```

### GraphQL Schema Entities

The automated-settlement subgraph indexes market activity and settlement events.

Each entity is available as both a singular query (by `id`) and a plural collection query with filtering, ordering, and pagination.

| Entity                    | Singular query                  | Collection query                  | Description                |
| ------------------------- | ------------------------------- | --------------------------------- | -------------------------- |
| GatewayBuy                | `gatewayBuy(id)`                | `gatewayBuys(...)`                | Share purchase events      |
| GatewaySell               | `gatewaySell(id)`               | `gatewaySells(...)`               | Share sale events          |
| GatewayRedemption         | `gatewayRedemption(id)`         | `gatewayRedemptions(...)`         | Settled market redemptions |
| GatewayLiquidation        | `gatewayLiquidation(id)`        | `gatewayLiquidations(...)`        | Position liquidations      |
| GatewayMarketSettled      | `gatewayMarketSettled(id)`      | `gatewayMarketSettleds(...)`      | Market settlement events   |
| GatewayMarketFailed       | `gatewayMarketFailed(id)`       | `gatewayMarketFaileds(...)`       | Failed market events       |
| MarketResolutionRequested | `marketResolutionRequested(id)` | `marketResolutionRequesteds(...)` | Oracle resolution requests |
| Initialized               | `initialized(id)`               | `initializeds(...)`               |                            |

### Entity Fields

#### Common Fields (All Entities)

| Field              | Type      | Description               |
| ------------------ | --------- | ------------------------- |
| `id`               | `ID!`     | Unique event identifier   |
| `block_number`     | `BigInt!` | Block number of the event |
| `timestamp_`       | `BigInt!` | Unix timestamp (seconds)  |
| `transactionHash_` | `String!` | Transaction hash          |
| `contractId_`      | `String!` | Gateway contract address  |

#### Additional Fields (Specific Entities)

* **GatewayBuy** additional fields: `marketProxy`, `buyer`, `outcomeIdx`, `tokensIn` (collateral, 6-dec), `sharesOut` (shares, 18-dec)
* **GatewaySell** additional fields: `marketProxy`, `seller`, `outcomeIdx`, `sharesIn` (shares, 18-dec), `tokensOut` (collateral, 6-dec)
* **GatewayRedemption** additional fields: `marketProxy`, `redeemer`, `sharesIn` (18-dec), `tokensOut` (collateral, 6-dec)
* **GatewayLiquidation** additional fields: `marketProxy`, `liquidator`, `outcomeIndices`, `sharesIn`, `totalTokensOut` (collateral, 6-dec)
* **GatewayMarketSettled** additional fields: `marketProxy`, `winningOutcomeIdx`, `marketCreatorReward`, `refund`, `marketCreatorTradingFeesCut`. The economics fields are `null` on competition testnet.
* **GatewayMarketFailed** additional fields: `marketProxy`
* **MarketResolutionRequested** additional fields: `marketProxy`, `keeper`

#### Collection Query Parameters

All plural queries accept these:

| Parameter        | Type               | Description                                      |
| ---------------- | ------------------ | ------------------------------------------------ |
| `first`          | `Int`              | Max results (default 100, max 1000)              |
| `skip`           | `Int`              | Pagination offset                                |
| `orderBy`        | `<Entity>_orderBy` | Field to sort by (e.g. `timestamp_`, `tokensIn`) |
| `orderDirection` | `OrderDirection`   | `asc` or `desc`                                  |
| `where`          | `<Entity>_filter`  | Filter conditions                                |
| `block`          | `Block_height`     | Query at a specific block height                 |

#### Filtering (*where* clause)

| Suffix    | Operator         | Example                           |
| --------- | ---------------- | --------------------------------- |
| (none)    | equals           | `{ marketProxy: "0x..." }`        |
| `_not`    | not equals       | `{ buyer_not: "0x..." }`          |
| `_gt`     | greater than     | `{ timestamp__gt: "1700000000" }` |
| `_lt`     | less than        | `{ tokensIn_lt: "1000000" }`      |
| `_gte`    | greater or equal | `{ block_number_gte: "100" }`     |
| `_lte`    | less or equal    | `{ block_number_lte: "500" }`     |
| `_in`     | in list          | `{ outcomeIdx_in: ["0", "1"] }`   |
| `_not_in` | not in list      | `{ marketProxy_not_in: [...] }`   |

{% hint style="info" %}
String fields also support: `_contains`, `_contains_nocase`, `_not_contains`, `_starts_with`, `_starts_with_nocase`, `_ends_with`, `_ends_with_nocase` (and their `_not_` variants).
{% endhint %}

### Usage Examples

Here are some common subgraph query examples.

#### 1. Listing recent trades for a given market

```typescript
const subgraph = client.getSubgraph();
const { buys, sells } = await subgraph.getMarketTrades("0x1234...abcd", { first: 20 });

for (const buy of buys) {
  const cost = Number(BigInt(buy.tokensIn ?? "0")) / 1e6;
  const shares = Number(BigInt(buy.sharesOut ?? "0")) / 1e18;
  const time = new Date(Number(buy.timestamp_) * 1000).toLocaleString();
  console.log(`BUY  ${time} | ${buy.buyer} | outcome ${buy.outcomeIdx} | ${cost.toFixed(4)} collateral tokens → ${shares.toFixed(4)} shares`);
}
```

#### 2. Querying global recent buys

```typescript
const data = await subgraph.query<{ gatewayBuys: SubgraphBuy[] }>(`{
  gatewayBuys(first: 10, orderBy: timestamp_, orderDirection: desc) {
    id buyer marketProxy outcomeIdx tokensIn sharesOut timestamp_
  }
}`);
```

#### 3. Filtering buys by wallet address

```typescript
const data = await subgraph.query<{ gatewayBuys: SubgraphBuy[] }>(`{
  gatewayBuys(
    first: 50,
    orderBy: timestamp_, orderDirection: desc,
    where: { buyer: "${walletAddress.toLowerCase()}" }
  ) {
    id marketProxy outcomeIdx tokensIn sharesOut timestamp_ transactionHash_
  }
}`);
```

#### 4. Filtering buys by time range

```typescript
const oneDayAgo = Math.floor(Date.now() / 1000) - 86400;
const data = await subgraph.query<{ gatewayBuys: SubgraphBuy[] }>(`{
  gatewayBuys(
    first: 100,
    orderBy: timestamp_, orderDirection: desc,
    where: { timestamp__gte: "${oneDayAgo}" }
  ) {
    id buyer marketProxy outcomeIdx tokensIn sharesOut timestamp_
  }
}`);
```

#### 5. Querying redemptions for a given market

```typescript
const data = await subgraph.query<{ gatewayRedemptions: GatewayRedemption[] }>(`{
  gatewayRedemptions(
    first: 50,
    orderBy: timestamp_, orderDirection: desc,
    where: { marketProxy: "${marketProxy}" }
  ) {
    id timestamp_ marketProxy redeemer sharesIn tokensOut transactionHash_
  }
}`);
```

#### 6. Querying market settlements

```typescript
const data = await subgraph.query<{ gatewayMarketSettleds: SubgraphMarketSettled[] }>(`{
  gatewayMarketSettleds(
    first: 10,
    orderBy: timestamp_, orderDirection: desc,
    where: { marketProxy: "${marketProxy}" }
  ) {
    id timestamp_ marketProxy winningOutcomeIdx transactionHash_
  }
}`);
```

#### 7. Checking subgraph indexing status

```typescript
const meta = await subgraph.getMeta();
console.log(`Indexed up to block ${meta.block.number}`);
console.log(`Has errors: ${meta.hasIndexingErrors}`);
```

#### 8. Pagination

```typescript
let skip = 0;
const pageSize = 100;
const allBuys: SubgraphBuy[] = [];

while (true) {
  const { buys } = await subgraph.getMarketTrades(marketProxy, { first: pageSize, skip });
  allBuys.push(...buys);
  if (buys.length < pageSize) break;
  skip += pageSize;
}
```

#### 9. Parsing subgraph values

```typescript
// Timestamps → Date
const date = new Date(Number(event.timestamp_) * 1000);

// Collateral amounts (6 decimals)
const collateral = Number(BigInt(event.tokensIn ?? "0")) / 1e6;

// Share amounts (18 decimals)
const shares = Number(BigInt(event.sharesOut ?? "0")) / 1e18;

// Outcome index
const outcomeIdx = Number(event.outcomeIdx ?? "0");

// Effective price per share (from a buy event)
const pricePerShare = collateral / shares;
```


# Agentic Trading Toolkit

A toolkit that enables AI agents to browse, trade, and manage positions on Delphi through natural language.

## What is Agentic Trading?

Agentic Trading is a toolkit that enables AI agents to interact with the Delphi prediction market platform on Gensyn.

It provides skill files, example scripts, and configuration patterns that let agents browse markets, execute trades, manage positions, query historical data, and redeem winnings, all through natural language interaction.

Under the hood, Agentic Trading uses the [Delphi SDK](/tools/sdk) for all market data access and on-chain operations. The SDK handles the technical complexity (RPC calls, contract interaction, token approvals, signing), while the Agentic Trading layer provides the behavioral framework that tells agents *when* and *how* to use those capabilities based on user intent.

You can install the Delphi skill with this command:

```bash
npx skills add https://github.com/gensyn-ai/gensyn-delphi-skills --skill delphi
```

### How it Works

The toolkit consists of two main pieces:

* **Skill Files:** Markdown files that describe agent behavior patterns: which SDK methods to call based on what the user asks for, how to format responses, and how to handle edge cases. These follow the standard skill MD approach for Claude and similar agent integrations.
* **Example Scripts:** These are ready-to-run TypeScript scripts in the `scripts/` folder that demonstrate every common operation. Agents can reference these as working examples or run them directly.

### Delphi's Pricing Mechanism

Delphi uses a *dynamic parimutuel (DPM)* pricing mechanism. Prices emerge from the distribution of all participants' wagers, rather than being set by a market maker. As new bets flow in, implied probabilities continuously update, and outcomes attracting more capital see their odds shorten, while less-backed outcomes become cheaper.

### Agent Trading Competition

The toolkit supports the agent trading competition on `competition-testnet`. It uses separate LMSR contracts and the TST collateral token.

You can configure the network in [Get Started](/tools/agentic-trading/get-started).

### What Agents Can Do

Agents can perform a wide range of actions using `SKILLS.md` :

* List, search, and browse prediction markets
* Fetch market details with live on-chain prices and implied probabilities
* Quote buy/sell trades (read-only, no gas cost)
* Execute buy and sell transactions with automatic token approval and slippage protection
* View portfolio positions and trade history
* Query historical on-chain event data via Goldsky subgraph (buys, sells, redemptions, liquidations, settlements)
* Redeem winnings from settled markets
* Manage ERC-20 token allowances

{% hint style="warning" %}
Agents cannot create listable markets. Markets **must** be created through the Delphi UI.

*Any markets created outside the UI will not appear in the interface.*
{% endhint %}


# Get Started

Clone the repo, install the skill, configure your environment, and start interacting with your agent.

## Prerequisites

There are several dependencies required to enable Agentic Trading on Delphi:

* Node.js installed (`npm -v` to verify)
* A wallet with ETH for gas and collateral tokens: $TEST on testnet, USDC on mainnet, or TST on competition testnet
* A [Delphi API access](#api-access-key-required) key

### Github Repos

You can find the Agentic Trading Toolkit (ATT) Skills file and the Delphi SDK here.

{% embed url="<https://github.com/gensyn-ai/gensyn-delphi-skills>" %}

{% embed url="<https://github.com/gensyn-ai/gensyn-delphi-sdk.git>" %}

### 1. Install the Delphi Skill

Run this single command to install the Delphi skill:

```bash
npx skills add https://github.com/gensyn-ai/gensyn-delphi-skills --skill delphi
```

You'll then be prompted to choose a scope and install the skill to the agent(s) of your choice.

1. **Choose a Scope:**
   1. **Global:** The agent can use Delphi from any folder
   2. **Project:** The agent can only use Delphi when working with that specific subfolder
2. **Select Agent(s):** Use the `space` key to choose which agents to install the skill for (Claude Code, Cursor, Cline, etc.)

### 2. Configure Environment Variables

Create a `.env` file in the project root with your credentials. You need two things: **\[1]** an API key and **\[2]** wallet signing credentials.

#### API Access Key (Required)

See the [SDK Configuration](/tools/sdk/configuration) documentation for details on requesting a testnet or mainnet API access key.

`competition-testnet` uses the testnet API deployment. Use a testnet API key.

#### Wallet Signing (Required)

You have two options for wallet signing: either a **\[1]** private key (which is easiest for development or a **\[2]** Coinbase CDP server wallet (recommended for production use cases).

#### via Private Key

```bash
DELPHI_SIGNER_TYPE=private_key
WALLET_PRIVATE_KEY=0x<your-hex-private-key>
```

#### via Coinbase CDP Server Wallet

```bash
CDP_API_KEY_ID=<your-key-id>
CDP_API_KEY_SECRET=<your-key-secret>
CDP_WALLET_SECRET=<your-wallet-secret>
CDP_WALLET_ADDRESS=0x<your-wallet-address>
```

CDP Server Wallet is the default signer type. There is no need to set `DELPHI_SIGNER_TYPE`. You can get your CDP credentials from the [Server Wallet v2 Quickstart](https://docs.cdp.coinbase.com/server-wallets/v2/introduction/quickstart).

{% hint style="info" %}
With CDP Server Wallets, private keys are secured in Coinbase's Trusted Execution Environment (TEE) and never leave the TEE. See the [Server Wallet v2 docs](https://docs.cdp.coinbase.com/server-wallets/v2/introduction/quickstart) for details.
{% endhint %}

#### Network Selection (Optional)

The SDK defaults to testnet. Set `DELPHI_NETWORK` to select mainnet or the competition.

Testnet defaults are listed in [SDK Configuration](/tools/sdk/configuration). Do not hardcode gateway addresses.

Competition testnet uses the testnet chain and RPC. It uses separate LMSR contracts and TST collateral with six decimals.

| Variable                | Values                                                                               | Default     |
| ----------------------- | ------------------------------------------------------------------------------------ | ----------- |
| `DELPHI_NETWORK`        | `"testnet"` \| `"mainnet"` \| `"competition-testnet"`                                | `"testnet"` |
| `DELPHI_COMPETITION_ID` | Optional competition ID; defaults to the active competition and is ignored elsewhere | —           |

#### Overrides (Optional)

These override network defaults if you need to point at a custom endpoint:

| Variable                  | Description                      |
| ------------------------- | -------------------------------- |
| `GENSYN_RPC_URL`          | Custom RPC endpoint              |
| `GENSYN_CHAIN_ID`         | Custom chain ID                  |
| `DELPHI_GATEWAY_CONTRACT` | Custom gateway contract address  |
| `DELPHI_API_BASE_URL`     | Custom API base URL              |
| `DELPHI_SUBGRAPH_URL`     | Custom Goldsky subgraph endpoint |

#### Example .env File

```
# Required
DELPHI_API_ACCESS_KEY=your-api-key-here

# Signing — Option A: Private key
DELPHI_SIGNER_TYPE=private_key
WALLET_PRIVATE_KEY=0xYourPrivateKeyHere

# Network (optional — defaults to testnet)
# DELPHI_NETWORK=testnet

# Competition (optional)
# DELPHI_NETWORK=competition-testnet
# DELPHI_COMPETITION_ID=  # Defaults to the active competition.
```

#### Wallet Funding

To execute Delphi transactions, your signer wallet must have:

* **ETH** on the Gensyn chain (for gas fees)
* **$TEST** on testnet, **USDC** on mainnet, or **TST** on competition testnet

Competition TST cannot be faucet-minted. Organizers distribute it after wallet registration. Gas still uses testnet ETH.

{% hint style="info" %}
Competition users need `@gensyn-ai/gensyn-delphi-sdk` version `2.1.0` or later. A fresh install uses a supported version.
{% endhint %}

### 3. Start Using your Agent

Open your agent of choice and start interacting with Delphi. The agent will use the skill files to understand your intent and call the appropriate [SDK](/tools/sdk) methods.

{% hint style="success" %}
The whole point of Agentic Trading is that you interact through natural language. So can you say *"buy 10 shares of outcome 0"* and the agent handles it. Get creative!
{% endhint %}

You can try something like:

* *"Show me the open prediction markets"*
* *"What's the current price on \[market name]?"*
* *"Buy 10 shares of outcome 0 on \[market address]"*
* *"What are my current positions?"*

{% hint style="info" %}
See the [Usage Guide](/tools/agentic-trading/usage-guide) for more in-depth information.
{% endhint %}


# Creating & Funding Wallets

How to fund your wallet with ETH and collateral tokens for trading on Delphi.

## Wallet Funding

To trade on Delphi using the Agentic Trading Toolkit, you need two assets on the Gensyn chain:

* **ETH:** This is used for gas fees.
* **Collateral tokens:** **\[1]** $TEST on testnet, **\[2]** USDC on mainnet, and **\[3]** TST on competition testnet.

If you're starting from scratch, this page walks you through creating a wallet and funding it for your network.

If you already have some of these pieces in place, you can skip ahead using the shortcuts below:

* **No wallet yet, or no crypto holdings:** Start at [Getting Started with a Crypto Wallet.](#getting-started-with-a-crypto-wallet)
* **Wallet with ETH and native USDC on Ethereum Mainnet:** Skip to [Manual Bridging](#manual-bridging), or let the Delphi agent handle bridging automatically.
* **Wallet already has ETH and bridged USDC on Gensyn Mainnet:** You're ready to trade. See the [agent documentation](/tools/agentic-trading/usage-guide) to get started.
* **Working on testnet:** Skip to [Testnet Funding.](#testnet)

The funding process differs between testnet and mainnet. Testnet uses a faucet-based flow for fast iteration whereas mainnet bridges real ETH and native USDC from Ethereum.

{% hint style="info" %}
For `competition-testnet`, ETH gas guidance remains the same as testnet. TST collateral cannot be faucet-minted or bridged. Organizers distribute TST when they register your wallet.
{% endhint %}

For canonical network parameters (RPC URLs, chain IDs, block explorers) and OP Stack contract addresses, refer to the [OP Stack Contracts](https://docs.gensyn.network/providers/network-information#op-stack-contracts) section in the [Gensyn Network](https://docs.gensyn.network/) docs.

### Getting Started with a Crypto Wallet

To use Delphi you need a self-custody crypto wallet that holds ETH and USDC on Ethereum Mainnet. This section orients you if you're new to crypto: detailed setup steps are maintained by the wallet providers and exchanges themselves.

#### Create a Wallet

Any EVM-compatible self-custody wallet works. Two common options:

* [MetaMask](https://metamask.io/download): A browser extension and mobile app, widely supported by dApps.
* [Coinbase Wallet](https://www.coinbase.com/wallet/downloads): A browser extension and mobile app that directly integrates with Coinbase exchange accounts.

Follow the provider's setup guide to create the wallet and securely back up your recovery phrase.

#### Fund with ETH and USDC

The simplest path for most users is to buy ETH and USDC on a centralized exchange like [Coinbase](https://www.coinbase.com), then withdraw to your self-custody wallet on Ethereum Mainnet. Coinbase's [withdrawal guide](https://help.coinbase.com/en/coinbase/getting-started/crypto-education/how-to-send-crypto) walks through the process.

{% hint style="warning" %}
USDC must be native Circle-issued USDC on Ethereum Mainnet (`0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48`).

USDC.e, axlUSDC, and other bridged variants will not work. Coinbase withdraws native USDC by default, so this is only a concern if you're sourcing USDC from another platform.
{% endhint %}

Once your wallet holds ETH and native USDC on Ethereum Mainnet, you have two options:

1. **Let the Delphi agent handle bridging automatically:** This is the default path.
2. **Bridge manually:** Continue to [Manual Bridging](#manual-bridging) below.

### Manual Bridging

If you prefer to bridge funds yourself rather than let the agent handle it, or if you're building custom tooling against the Delphi SDK, use the flows below.

ETH bridges via the OP Stack canonical bridge. USDC bridges via Stargate V2 (LayerZero), which offers faster finality than the canonical bridge for ERC-20 transfers.

Both scripts below require `DELPHI_NETWORK=mainnet` in your `.env`.

### Testnet

On testnet, you'll bridge Sepolia ETH to Gensyn Testnet for gas, then mint $TEST from a faucet contract on Gensyn Testnet.

* **Prerequisites:** You need Sepolia ETH in your wallet before you can do anything else. $TEST is minted directly on Gensyn Testnet. No prior balance is needed.

#### Step 1: Get Sepolia ETH

Use a Sepolia faucet to get ETH on Ethereum Sepolia. We recommend the [Google Cloud Web3 Faucet](https://cloud.google.com/application/web3/faucet/ethereum/sepolia).

#### Step 2: Bridge ETH to Gensyn Testnet

Use the bundled script to bridge ETH from Sepolia to Gensyn Testnet via the OP Stack canonical bridge:

```bash
npx tsx scripts/bridge-eth-to-gensyn-testnet.ts <amount-eth>
# or
npm run bridge-eth-to-gensyn-testnet 0.0001
```

ETH arrives on Gensyn Testnet within a few minutes of Sepolia confirmation. The deposit appears under the **Internal txns** tab on the [Gensyn Testnet explorer](https://gensyn-testnet.explorer.alchemy.com/), not under regular Transactions.

{% hint style="info" %}
OP Stack deposits are a special transaction type (`0x7e`) triggered by the L1 bridge rather than a user-signed L2 transaction.
{% endhint %}

#### Alternative: Call the L1 Bridge Directly

You can bypass the script and call `depositETH` directly on the Sepolia L1StandardBridge. For the contract address, see [OP Stack Contracts.](https://docs.gensyn.network/providers/network-information#op-stack-contracts)

Using Foundry's `cast`:

```bash
# Deposit 0.1 ETH to your own address on Gensyn Testnet
cast send <L1StandardBridge-Sepolia> \
  "depositETH(uint32,bytes)" 200000 "0x" \
  --value 0.1ether \
  --rpc-url https://ethereum-sepolia-rpc.publicnode.com \
  --private-key $PRIVATE_KEY

# Deposit to a different address
cast send <L1StandardBridge-Sepolia> \
  "depositETHTo(address,uint32,bytes)" $RECIPIENT 200000 "0x" \
  --value 0.1ether \
  --rpc-url https://ethereum-sepolia-rpc.publicnode.com \
  --private-key $PRIVATE_KEY
```

You can also do this using `viem`:

```typescript
import { createWalletClient, http, parseEther, encodeFunctionData } from "viem";
import { sepolia } from "viem/chains";
import { privateKeyToAccount } from "viem/accounts";

const account = privateKeyToAccount(process.env.WALLET_PRIVATE_KEY as `0x${string}`);
const walletClient = createWalletClient({
  account,
  chain: sepolia,
  transport: http("https://ethereum-sepolia-rpc.publicnode.com"),
});

const hash = await walletClient.sendTransaction({
  to: "<L1StandardBridge-Sepolia>",
  value: parseEther("0.1"),
  data: encodeFunctionData({
    abi: [{
      name: "depositETH",
      type: "function",
      inputs: [
        { name: "_minGasLimit", type: "uint32" },
        { name: "_extraData", type: "bytes" },
      ],
      stateMutability: "payable",
    }],
    functionName: "depositETH",
    args: [200000, "0x"],
  }),
});
```

#### Step 3: Claim $TEST from the Faucet

On testnet, the collateral is $TEST, minted directly from a faucet contract on Gensyn Testnet. Each call dispenses 1,000 $TEST. Its on-chain symbol is `MT`.

You can find the Delphi testnet contracts here:

| Contract               | Address                                      |
| ---------------------- | -------------------------------------------- |
| $TEST Faucet           | `0xB5876320DdA1AEE3eFC03aD02dC2e2CB4b61B7D9` |
| $TEST collateral token | `0x0724D6079b986F8e44bDafB8a09B60C0bd6A45a1` |

Use the bundled script to claim:

```bash
npx tsx scripts/testnet-faucet.ts
# or
npm run testnet-faucet
```

This calls `requestToken()` on the faucet, logs your balance before and after, and waits for the transaction to confirm.

To call the faucet directly with `cast`:

```bash
cast send 0xB5876320DdA1AEE3eFC03aD02dC2e2CB4b61B7D9 \
  "requestToken()" \
  --rpc-url https://gensyn-testnet.g.alchemy.com/public \
  --private-key $PRIVATE_KEY
```

### Mainnet

On mainnet, you'll bridge real ETH and native USDC from Ethereum to Gensyn Mainnet. ETH uses the canonical OP Stack bridge; USDC uses Stargate V2 (LayerZero) for faster finality.

* **Prerequisites:** You need both ETH and native USDC on Ethereum Mainnet before bridging.
  * **ETH** is needed to pay L1 gas for the bridge transactions, and once bridged, to pay gas when trading on Gensyn.
  * **USDC** must be native Circle-issued USDC on Ethereum Mainnet (`0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48`). USDC.e, axlUSDC, and other bridged variants will not work.

Both scripts below require `DELPHI_NETWORK=mainnet` in your `.env`.

#### Bridging ETH (Ethereum Mainnet to Gensyn Mainnet)

ETH bridges via the OP Stack canonical bridge:

```bash
npx tsx scripts/bridge-eth-to-gensyn-mainnet.ts <amount-eth>
# or
npm run bridge-eth-to-gensyn-mainnet 0.0001
```

ETH arrives within a few minutes and appears under the **Internal txns** tab on the [Gensyn Mainnet explorer](https://gensyn-mainnet.explorer.alchemy.com/): this is the same pattern as when bridging to testnet (see above).

For the L1StandardBridge and related contract addresses, see [OP Stack Contracts.](https://docs.gensyn.network/providers/network-information#op-stack-contracts)

#### Bridging USDC (Ethereum Mainnet to Gensyn Mainnet via Stargate V2)

USDC bridges via Stargate V2 (LayerZero) rather than the canonical bridge. The script handles approval, quotes the LayerZero fee, and sends in one flow:

```bash
npx tsx scripts/bridge-usdc-to-gensyn-mainnet.ts <amount-usdc> [slippage-pct]
# or
npm run bridge-usdc-to-gensyn-mainnet 10
npm run bridge-usdc-to-gensyn-mainnet 10 1
```

Default slippage is 0.5%. You'll need ETH on Ethereum Mainnet to cover the LayerZero messaging fee (\~0.001–0.005 ETH) in addition to normal Ethereum gas. Track delivery at [LayerZero Scan](https://layerzeroscan.com/).

For the Stargate pool addresses, OFT addresses, and Gensyn's LayerZero Endpoint ID, see the [LayerZero / Stargate](https://docs.gensyn.network/providers/bridges#layerzero-stargate) section under [Bridges.](https://docs.gensyn.network/providers/bridges)


# Usage Guide

What you can ask the agent to do, example prompts, and available scripts.

## Using Natural Language

Agentic Trading is designed to be used through natural language: you tell your agent what you want to do, and it handles the SDK calls, contract interactions, and error handling for you. This page covers what you can do and how to do it.

{% hint style="info" %}
For the underlying code-level details (type definitions, parameter schemas, contract methods, GraphQL queries), see the [Delphi SDK documentation.](/tools/sdk)
{% endhint %}

### Asking your Agent to Do Things

Once you've completed the [Getting Started](/tools/agentic-trading/get-started) setup, open your agent and start with natural language. Here are the core capabilities:

#### Browse & Research Markets

* *"Show me the open prediction markets"*
* *"List crypto markets"*
* *"What's the current price and probability on \[market name]?"*
* *"Get me the details for market \[id]"*

The agent can list markets, filter by status or category, and fetch live on-chain prices and implied probabilities for any market.

#### Trade

* *"Buy 10 shares of outcome 0 on \[market address]"*
* *"How much would it cost to buy 5 shares of outcome 1?"*
* *"Sell all my shares in \[market address]"*
* *"Quote a sell for 20 shares of outcome 0"*

The agent handles the full trade flow automatically: quoting the cost, approving the `maxTokensIn` slippage cap, applying slippage protection, and executing the transaction. You can also ask for a quote first without committing.

#### Manage Positions

* *"What are my current positions?"*
* *"Show me my active positions that haven't been redeemed"*
* *"Redeem my winnings from \[market address]"*
* *"Redeem all my settled positions"*
* *"Liquidate my expired markets"*
* *"Liquidate my failed markets"*

The agent can list your holdings, filter out zero-share positions, and handle both single and batch redemptions. Expired and failed markets have no winning outcome. Exit them with liquidation, not redemption.

#### Query Trade History

* *"Show me recent trades for \[market address]"*
* *"What buys happened in the last 24 hours?"*
* *"Has \[market address] been settled? Who won?"*

The agent queries the Goldsky subgraph for historical on-chain events including buys, sells, redemptions, liquidations, and settlements.

#### Manage Token Approvals

* *"Check my token allowance for \[market address]"*
* *"Approve unlimited collateral spending for \[market address]"*

In most cases you won't need to manage approvals manually, since the agent handles this automatically before trades. But you can check or set approvals explicitly if needed.

{% hint style="warning" %}
Agents cannot create markets. Markets *must* be created through the Delphi UI.

**Markets created outside the UI will not appear in the interface.**
{% endhint %}

### Monitoring your Agent (TUI)

The toolkit includes a read-only terminal dashboard (TUI) for supervising your agent's Delphi activity in real time. It never signs or trades, so it's safe to leave running alongside an active agent. It only observes.

Launch it with a wallet address and network (both required):

```bash
npx tsx scripts/agent-tui/index.tsx <wallet-address> <testnet|mainnet|competition-testnet>
# or, via the npm script:
npm run agent-tui -- <wallet-address> <testnet|mainnet|competition-testnet>
```

It reads `DELPHI_API_ACCESS_KEY` from your `.env`. The network argument selects RPC and API endpoints, with no `DELPHI_NETWORK` fallback. `DELPHI_COMPETITION_ID` is read from `.env` for competition views.

Positions outside the selected market scope can appear as unpriced.

<div data-with-frame="true"><figure><img src="https://3382892862-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Ft59pTERBDU0JfP4e2nEP%2Fuploads%2FC7OW4u58TQkQST27h3tQ%2Fimage.png?alt=media&amp;token=8add8855-f51b-4c62-bc93-5f06647ff1b3" alt=""><figcaption></figcaption></figure></div>

The dashboard has four screens:

* **Overview:** A live snapshot including the Edge View and Agent Logs
* **Portfolio:** Your current positions
* **My Activity:** The wallet's trade history
* **Markets:** Browse markets, with drill-down into any single market

| Key       | Action                                                                        |
| --------- | ----------------------------------------------------------------------------- |
| `1`–`4`   | Switch screens                                                                |
| `↑` / `↓` | Move selection                                                                |
| `⏎`       | Open details                                                                  |
| `esc`     | Go back                                                                       |
| `r`       | Refresh                                                                       |
| `q`       | Quit                                                                          |
| `--once`  | Render one frame and exit. Useful for non-interactive shells and screenshots. |

### Example Scripts

The `scripts/` folder in the skills repo contains working TypeScript examples for every common operation.

These serve two purposes: **\[1]** agents can reference or run them directly, and **\[2]** you can use them to test your setup or run operations outside of an agent conversation.

| Script                                     | Purpose                                                 | Usage                                                                                                                   |
| ------------------------------------------ | ------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------- |
| `scripts/list-markets.ts`                  | List and filter markets; honors `DELPHI_COMPETITION_ID` | `npx tsx scripts/list-markets.ts [status] [category] [limit]`                                                           |
| `scripts/get-market.ts`                    | Get market details; honors `DELPHI_COMPETITION_ID`      | `npx tsx scripts/get-market.ts <market-id>`                                                                             |
| `scripts/quote-buy.ts`                     | Get buy quote (read-only)                               | `npx tsx scripts/quote-buy.ts <market-address> <outcome-idx> <shares>`                                                  |
| `scripts/quote-sell.ts`                    | Get sell quote (read-only)                              | `npx tsx scripts/quote-sell.ts <market-address> <outcome-idx> <shares>`                                                 |
| `scripts/quote-redeem.ts`                  | Preview a redemption quote (read-only)                  | `npx tsx scripts/quote-redeem.ts <market-address>`                                                                      |
| `scripts/quote-liquidate.ts`               | Preview a liquidation quote (read-only)                 | `npx tsx scripts/quote-liquidate.ts <market-address>`                                                                   |
| `scripts/buy-shares.ts`                    | Buy shares; accepts fractional slippage percentages     | `npx tsx scripts/buy-shares.ts <market-address> <outcome-idx> <shares> [slippage-pct]`                                  |
| `scripts/sell-shares.ts`                   | Sell shares; accepts fractional slippage percentages    | `npx tsx scripts/sell-shares.ts <market-address> <outcome-idx> <shares> [slippage-pct]`                                 |
| `scripts/list-positions.ts`                | List wallet positions                                   | `npx tsx scripts/list-positions.ts [wallet-address]`                                                                    |
| `scripts/redeem.ts`                        | Redeem winnings from settled markets                    | `npx tsx scripts/redeem.ts <market-address> [market-address ...]`                                                       |
| `scripts/liquidate.ts`                     | Recover funds from expired or failed markets            | `npx tsx scripts/liquidate.ts <market-address> [market-address ...]`                                                    |
| `scripts/get-wallet-balances.ts`           | Check ETH and collateral-token balances                 | `npx tsx scripts/get-wallet-balances.ts`                                                                                |
| `scripts/token-approval.ts`                | Check or set market token approval                      | `npx tsx scripts/token-approval.ts <market-address> [amount\|unlimited]`                                                |
| `scripts/list-recent-trades.ts`            | List recent trades via subgraph                         | `npx tsx scripts/list-recent-trades.ts <market-proxy-address> [limit]`                                                  |
| `scripts/log-event.ts`                     | Support the TUI's Agent Logs view                       | `npx tsx scripts/log-event.ts <type> "<message>"`                                                                       |
| `scripts/compute-edge.ts`                  | Support the TUI's Edge View                             | `npx tsx scripts/compute-edge.ts <market-address> <outcome-idx> <your-prob> [market-address outcome-idx your-prob ...]` |
| `scripts/agent-tui/index.tsx`              | Launch the terminal dashboard                           | `npm run agent-tui -- <wallet-address> <testnet\|mainnet\|competition-testnet>`                                         |
| `scripts/testnet-faucet.ts`                | Claim $TEST; unavailable on competition                 | `npx tsx scripts/testnet-faucet.ts`                                                                                     |
| `scripts/bridge-eth-to-gensyn-testnet.ts`  | Bridge Sepolia ETH to Gensyn Testnet                    | `npx tsx scripts/bridge-eth-to-gensyn-testnet.ts <amount-eth>`                                                          |
| `scripts/bridge-eth-to-gensyn-mainnet.ts`  | Bridge Ethereum ETH to Gensyn Mainnet                   | `npx tsx scripts/bridge-eth-to-gensyn-mainnet.ts <amount-eth>`                                                          |
| `scripts/bridge-usdc-to-gensyn-mainnet.ts` | Bridge Ethereum USDC to Gensyn Mainnet                  | `npx tsx scripts/bridge-usdc-to-gensyn-mainnet.ts <amount-usdc> [slippage-pct]`                                         |

All scripts use the shared client setup from `scripts/client.ts` which handles environment variable configuration automatically. You can also run them via npm scripts: `npm run list-markets`, `npm run buy-shares`, etc.

For faucet and bridge helpers, see [Creating & Funding Wallets](/tools/agentic-trading/creating-and-funding-wallets) for the full funding flow and network-specific guidance.

{% hint style="info" %}
Before trying to run any scripts, make sure you've completed the [Getting Started setup](/tools/agentic-trading/get-started) and you have all required dependencies installed *and* the `.env` file configured.
{% endhint %}

### Going Deeper

If you want to write custom integrations or understand the code-level details behind what the agent is doing, the [Delphi SDK](/tools/sdk) documentation covers everything:

* [Configuration](/tools/sdk/configuration): Environment variables, signing modes, network defaults
* [API Reference](/tools/sdk/api): Market and position types, filtering, pagination, redemption patterns
* [On-Chain Methods](/tools/sdk/methods): Trading mechanics, slippage, Gateway contract reference, token approvals
* [Subgraph](/tools/sdk/subgraph): GraphQL schema, entity types, filtering operators, raw query examples


# Troubleshooting

Covers common errors, environment variable issues, wallet problems, and slippage failures.

## Overview

There are several errors which can occur when using the Agentic Trading toolkit.

### Contract Errors

These errors occur during on-chain trade execution.

| Error                             | Cause                                               | Fix                                                   |
| --------------------------------- | --------------------------------------------------- | ----------------------------------------------------- |
| `TokensInExceedsMax`              | Price moved above your `maxTokensIn` since quoting  | Re-quote and increase slippage tolerance              |
| `TokensOutBelowMin`               | Price moved below your `minTokensOut` since quoting | Re-quote and increase slippage tolerance              |
| `MarketNotOpen`                   | Market is closed or settled                         | Check `market.status` before trading                  |
| `SharesInExceedSupply`            | Selling more shares than your wallet holds          | Check position balance before selling                 |
| `GrossTokensOutNotPositive`       | Attempting to sell with no position                 | Position is empty — nothing to sell                   |
| `ZeroTokensIn`                    | `sharesOut` amount too small to register            | Use a larger share amount                             |
| `MarketProxyNotDeployedByFactory` | Pinned gateway does not own the market              | Remove the pinned gateway or resolve market ownership |

### Environment Variable Errors

| Error                      | Cause                                                      | Fix                                                                                                                          |
| -------------------------- | ---------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------- |
| `Requires apiKey`          | `DELPHI_API_ACCESS_KEY` not set                            | Add it to your `.env` file — generate at [Delphi API Access](https://delphi-api-access.gensyn.ai/)                           |
| `Requires rpcUrl`          | `GENSYN_RPC_URL` not set and network default not resolving | Set `DELPHI_NETWORK=testnet` or provide `GENSYN_RPC_URL` explicitly                                                          |
| `Requires privateKey`      | Using private key signing without `WALLET_PRIVATE_KEY`     | Set `WALLET_PRIVATE_KEY` in `.env` or switch to CDP signer                                                                   |
| `CDP signing requires ...` | Missing one or more CDP environment variables              | Ensure all four `CDP_*` variables are set: `CDP_API_KEY_ID`, `CDP_API_KEY_SECRET`, `CDP_WALLET_SECRET`, `CDP_WALLET_ADDRESS` |

### Wallet & Network Issues

Errors related to token bridging, balance lag, MetaMask, market or market action issues, and more.

#### MetaMask Not Showing the Correct Balance

If MetaMask shows unexpected balances or token symbols after connecting to the Gensyn network:

1. Open MetaMask and go to **Settings** then **Networks**
2. Find the Gensyn network entry and click **Edit**
3. Verify the RPC URL matches: `https://gensyn-testnet.g.alchemy.com/public`
4. Verify the Chain ID matches: `685685`
5. Save and refresh the page

#### Bridge Transactions Not Appearing

After bridging tokens from Sepolia to Gensyn testnet, balances may take up to 5 minutes to reflect.

If tokens still don't appear:

1. Check the transaction on the explorer to confirm it was sent
2. Verify you're viewing the correct network in MetaMask (Gensyn Testnet, not Sepolia)
3. Try switching away from the Gensyn network and switching back
4. Refresh MetaMask or the Delphi UI

#### Transactions Failing with Insufficient Funds

Your signer wallet needs both ETH for gas and collateral tokens for trading on the Gensyn chain.

If transactions fail:

1. Check your ETH balance: even read-only quote operations are free, but all write operations (buy, sell, approve, redeem) require gas
2. Check your collateral balance: Make sure you have enough to cover the trade amount plus slippage
3. On Delphi testnet, use the $TEST faucet or bridge ETH for gas
4. Competition TST has no faucet. Organizers distribute it after registration

### Positions Showing Zero Shares

The positions API may return entries with `shares === "0"` for markets you previously participated in but fully exited. These are expected. They indicate historical participation, not current holdings.

{% hint style="info" %}
Always check `BigInt(position.shares) > 0n` before attempting to redeem or liquidate.
{% endhint %}

### Market Not Found or Not Trading

* **Market shows as `awaiting_settlement`**: Trading deadline has passed. You cannot buy or sell, but the market hasn't been settled yet.
* **Market shows as `settled`**: Trading is closed. If you hold the winning outcome, you can redeem your position.
* **Market shows as `expired`**: Market expired without settlement. Positions are not redeemable — recover funds with `liquidate()`.
* **Market shows as `failed`**: Oracle settlement could not resolve the market. Positions are not redeemable — recover funds with `liquidate()`.
* **Market not appearing in search**: There is currently no search functionality in the Delphi UI. Use `client.listMarkets()` with filtering to find markets programmatically, or browse by category and status.

### Competition issues

| Symptom                                     | Cause                                               | Fix                                                          |
| ------------------------------------------- | --------------------------------------------------- | ------------------------------------------------------------ |
| Every API call returns `401`                | Mainnet key used on competition                     | Use a testnet API key                                        |
| `listMarkets()` returns no markets          | No active competition is selected                   | Pass `DELPHI_COMPETITION_ID`                                 |
| `getMarket()` returns `404`                 | Market is outside the selected competition          | Use the correct competition ID                               |
| Trades do not appear on the leaderboard     | Wallet is unregistered or below activity thresholds | Register the signer wallet and meet competition requirements |
| A modest quote reverts                      | LMSR liquidity is shallow                           | Reduce trade size                                            |
| Client construction fails                   | SDK version is below `2.1.0`                        | Install `@gensyn-ai/gensyn-delphi-sdk` `2.1.0` or later      |
| `redeemMarket()` reverts on a closed market | Market is expired or failed                         | Use `liquidate()`                                            |

### Slippage Failures (on Active Markets)

If your trades keep failing with `TokensInExceedsMax` or `TokensOutBelowMin`, the market is likely seeing high trading volume and prices are moving between your quote and execution.

Increase your slippage tolerance:

| Scenario                 | Recommended slippage |
| ------------------------ | -------------------- |
| Quiet market             | 1–2%                 |
| Active market            | 2–5%                 |
| Large trade (>$100)      | 5–10%                |
| Time-sensitive execution | 5%                   |

You can also try using *basis points* for precise integer arithmetic:

```typescript
const slippageBps = 200n; // 200 = 2%
const maxTokensIn  = tokensIn  * (10000n + slippageBps) / 10000n;
const minTokensOut = tokensOut * (10000n - slippageBps) / 10000n;
```


