# Integration Flow

This guide outlines the step-by-step process for integrating with the Tournament Builder developed for Forge Digital Ventures. For technical details of the architecture, see the [Overview](/tournament-builder/overview.md) document.

{% hint style="info" %}
This workflow assumes you have already set up your development environment and have the necessary credentials to access the Anvil API.
{% endhint %}

## 1. Tournament Creation

{% tabs %}
{% tab title="Step-by-Step Process" %}

1. **Prepare Tournament Configuration**
   * Define bracket size, entry fees, and payout structure
   * Identify administrator address
   * Gather UTXOs for transaction fees
2. **Create Tournament Transaction**
   * Call the [`/tournaments` endpoint](/tournament-builder/tournament.md#create-tournament) with configuration
   * Receive transaction hex in response
3. **Sign and Submit Transaction**
   * Sign the transaction with appropriate keys
   * Submit the signed transaction (see [Transaction Overview](/guides/transaction.md) for details)

{% hint style="success" %}
When successful, the tournament is created and an NFT is minted to represent it on-chain. The tournament is now ready to accept registrations.
{% endhint %}
{% endtab %}

{% tab title="Example API Flow" %}

```javascript
// 1. Configure tournament parameters
const tournamentConfig = {
  name: "Tournament Name",
  adminAddress: "addr1...",
  bracketSize: 16,
  entryFee: "10000000", // 10 ADA in lovelace
  payoutStructure: ["7000000", "2000000", "1000000"],
  utxos: ["1234...#0", "5678...#1"]
};

// 2. Create tournament transaction
const response = await fetch("/tournaments", {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify(tournamentConfig)
});
const { transaction } = await response.json();

// 3. Sign and submit transaction
// See Transaction Overview documentation for details: ../guides/transaction/README.md
const signedTx = await signTransaction(transaction);
const submitResponse = await fetch("/tournaments/submit-tx", {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({ transaction: signedTx })
});
const { txHash } = await submitResponse.json();

console.log("Tournament created with transaction:", txHash);
```

{% endtab %}
{% endtabs %}

## 2. Registration Management

The Tournament Builder uses a two-phase registration process:

1. Participants self-register (creating registration UTXOs)
2. Tournament administrator collects these registrations and officially adds participants

### Phase 1: Participants Register

1. **Participant Initiates Registration**
   * Call [`POST /tournaments/{id}/register`](/tournament-builder/registration.md#register) with participant address
   * Include UTXOs covering entry fee
   * Submit resulting transaction
   * This creates a registration UTXO at the registration script address
2. **Verification**
   * Query [`GET /tournaments/{id}/registrations`](/tournament-builder/registration.md#list-registrations) to confirm registration
   * Validate status and fee payment
   * Participants must monitor their registration status
3. **Optional: Registration Cancellation**
   * If needed, participants can cancel their registration before being added to the tournament
   * Call [POST /tournaments/{id}/unregister\`](/tournament-builder/registration.md#cancel-registration)
   * The registration UTXO with the full entry fee amount is returned to the participant
   * This provides a complete refund mechanism for participants who change their mind

### Phase 2: Tournament Administrator Adds Participants

1. **Collect Registration Outputs**
   * Tournament administrator gathers valid registration output references
   * Uses [`GET /tournaments/{id}/registrations`](/tournament-builder/registration.md#list-registrations) to find valid registrations
2. **Add Participants to Tournament**
   * Administrator calls [`POST /tournaments/{id}/participants`](/tournament-builder/tournament.md#add-participants) with registration list
   * Only the tournament admin can perform this action
   * Administrator signs and submits transaction
   * This transaction consumes the registration UTXOs and updates the tournament datum
   * Participants are now officially part of the tournament

### Phase 3: Tournament Settlement

1. **Finalize Participant List**
   * Administrator reviews and confirms all participants
2. **Conduct Tournament**
   * Actual competition happens off-chain
   * Results are determined through competition
3. **Submit Results**
   * Tournament administrator submits final standings using the [`PATCH /tournaments/{id}/settle` endpoint](/tournament-builder/tournament.md#tournament-settlement)
   * Smart contract distributes rewards according to payout structure defined at tournament creation
   * Each prize recipient receives their prize as a transaction output with the tournament ID as datum
   * For details on prize distribution and fees, see the [Fee Structure](/tournament-builder/fee-structure.md) document


---

# Agent Instructions: Querying This Documentation

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

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

```
GET https://dev.ada-anvil.io/tournament-builder/integration-flow.md?ask=<question>
```

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

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