> For the complete documentation index, see [llms.txt](https://dev.ada-anvil.io/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://dev.ada-anvil.io/tournament-builder/tournament.md).

# Tournament

## Tournament Creation

**Endpoint**: `POST /tournaments`

Creates a new tournament with the specified configuration parameters.

**Request Parameters**:

* `name` (string): Tournament display name
* `adminAddress` (string): Address with administrative control
* `changeAddress` (string, optional): Address to receive change UTXOs (defaults to adminAddress)
* `bracketSize` (number): Number of participants in the tournament
* `entryFee` (string|number|bigint, optional): Fee for participants (in lovelace)
* `payoutStructure` (string\[]|number\[]|bigint\[]): Array defining prize distribution (in lovelace)

  <div data-gb-custom-block data-tag="hint" data-style="warning" class="hint hint-warning"><p>Even for percentage-based payouts, values for <code>payoutStructure</code> must be pre-calculated as absolute lovelace amounts. The contract does not perform percentage calculations; clients must convert desired percentages to exact lovelace values.</p><p>Example: For a 70%/20%/10% split of 100 ADA, you would provide <code>["70_000_000", "20_000_000", "10_000_000"]</code></p></div>
* `fixedPayouts` (\[string, string|number|bigint]\[], optional): Optional specific reward allocations to addresses
* `utxos` (string\[], min 1): Array of UTXO strings to use for the transaction
* `contractTitle` (string, optional): Contract title for custom deployments
* `contractVersion` (string, optional): Contract version for custom deployments

**Response**:

* `complete`: Hex-encoded transaction for signing

{% hint style="info" %}
The returned transaction must be signed and submitted through the `/tournaments/submit-tx` endpoint before it takes effect on the blockchain.
{% endhint %}

**Technical Notes**:

* The tournament ID is derived from the first UTXO in the transaction
* An NFT is minted representing the tournament
* The tournament datum contains both configuration and current state

**Example (Node.js with fetch)**:

```javascript
async function createTournament() {
  const apiUrl = 'https://preprod.api.ada-anvil.app/v2/services/tournaments';
  
  const requestData = {
    name: "Tournament Name",
    adminAddress: "addr_test1...",
    bracketSize: 8,
    entryFee: "5_000_000", // 5 ADA in lovelace
    payoutStructure: ["30_000_000", "15_000_000", "5_000_000"], // First, second, third place prizes
    fixedPayouts: [
      ["addr_test1...", "1_000_000"]
    ],
    utxos: ["8282...", "8282...", "8282..."] // UTXOs to consume in the transaction
  };
  
  const response = await fetch(apiUrl, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify(requestData),
  });
  
  const data = await response.json();
  console.log('Tournament creation transaction:', data.complete);
  
  // The returned transaction must be signed and submitted (see Transaction Overview: ../guides/transaction/README.md)
  return data.complete;
}
```

## Adding Participants to Tournament

**Endpoint**: `POST /tournaments/{tournamentId}/participants`

Enables tournament administrators to collect valid registrations and officially add participants to the tournament.

**Request Parameters**:

* `adminAddress` (string): Tournament administrator address
* `tournamentId` (string): Tournament identifier
* `changeAddress` (string, optional): Address to receive change UTXOs (defaults to adminAddress)
* `registrations` (object\[], min 1): Array of registration objects, each containing:
  * `address` (string): Participant address
  * `outputRef` (string): Registration UTXO reference in format `txHash#index`
* `utxos` (string\[], min 1): Array of UTXO strings to use for the transaction
* `contractTitle` (string, optional): Contract title for custom deployments
* `contractVersion` (string, optional): Contract version for custom deployments

**Response**:

* `complete`: Hex-encoded transaction for signing

{% hint style="info" %}
The returned transaction must be signed and submitted through the `/tournaments/submit-tx` endpoint before it takes effect on the blockchain.
{% endhint %}

**Technical Notes**:

* Only the tournament admin can add registered participants to the tournament
* Multiple participants can be added in a single transaction
* The transaction updates the tournament datum with new participants
* Registration UTXOs are consumed in the process

**Example (Node.js with fetch)**:

```javascript
async function addParticipantsToTournament(tournamentId) {
  const apiUrl = `https://preprod.api.ada-anvil.app/v2/services/tournaments/${tournamentId}/participants`;
  
  const requestData = {
    adminAddress: "addr_test1...",
    changeAddress: "addr_test1...", // Optional, defaults to adminAddress
    registrations: [
      {
        address: "addr_test12...",
        outputRef: "registrationOutputRef1"
      },
      {
        address: "addr_test13...",
        outputRef: "registrationOutputRef2"
      }
    ],
    utxos: ["8282...", "8282...", "8282..."] // UTXOs to consume in the transaction
  };
  
  const response = await fetch(apiUrl, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify(requestData),
  });
  
  const data = await response.json();
  console.log('Add participants transaction:', data.complete);
  
  // The returned transaction must be signed and submitted (see Transaction Overview: ../guides/transaction/README.md)
  return data.complete;
}
```

## Retrieving Tournaments

**Endpoint**: `GET /tournaments`

Returns a list of all available tournaments.

**Request Parameters**:

* `limit` (number, optional): Number of tournaments to retrieve (default: 100, max: 100)
* `pageState` (string, optional): Pagination token for fetching additional results
* `cursor` (string, optional): Alias for pageState, enables TRPC infinite queries
* `contractTitle` (string, optional): Contract title for custom deployments
* `contractVersion` (string, optional): Contract version for custom deployments

**Response**:

* `results`: Array of tournament objects with their configuration and state
* `pageState`: Optional pagination token for fetching the next page of results

**Technical Notes**:

* Results are paginated with a default limit of 100 tournaments
* The response includes both tournament configuration and current state
* Tournament information is retrieved from the on-chain NFT records
* Invalid registrations may be added to a tournament, but any missing fees will be covered by the tournament administrator when confirming the registration

**Example (Node.js with fetch)**:

```javascript
async function getTournaments(limit = 50, pageState = null) {
  let apiUrl = `https://preprod.api.ada-anvil.app/v2/services/tournaments?limit=${limit}`;
  
  if (pageState) {
    apiUrl += `&pageState=${encodeURIComponent(pageState)}`;
  }
  
  const response = await fetch(apiUrl, {
    method: 'GET',
    headers: {
      'Content-Type': 'application/json',
    }
  });
  
  const data = await response.json();
  console.log(`Retrieved ${data.results.length} tournaments`);
  
  // For pagination, use the returned pageState token
  if (data.pageState) {
    console.log('More tournaments available, use pageState for pagination');
  }
  
  return data;
}
```

## Tournament Settlement

**Endpoint**: `PATCH /tournaments/{tournamentId}/settle`

Completes a tournament by distributing prizes according to the specified results.

**Request Parameters**:

* `adminAddress` (string): Administrator address (must match tournament creator)
* `changeAddress` (string, optional): Address to receive change UTXOs (defaults to adminAddress)
* `tournamentId` (string): Tournament identifier
* `results` (string\[]): Array of participant addresses in order of their placement (1st place first, 2nd place second, etc.)

{% hint style="info" %}
This `results` list doesn't have to be exhaustive, but at least all winning participants (configured in the original `payoutStructure`) must be specified.
{% endhint %}

* `utxos` (string\[], min 1): Array of UTXO strings to use for the transaction
* `contractTitle` (string, optional): Contract title for custom deployments
* `contractVersion` (string, optional): Contract version for custom deployments

**Response**:

* `complete`: Hex-encoded transaction for signing

{% hint style="info" %}
The returned transaction must be signed and submitted through the `/tournaments/submit-tx` endpoint before it takes effect on the blockchain.
{% endhint %}

**Technical Notes**:

* Only the tournament admin can settle a tournament
* Tournament must be fully filled (all participant slots must be occupied)
* Prizes are distributed according to the tournament's payout structure
* The tournament NFT is burned during settlement
* Prize UTXOs include tournament ID as a unique tag in the datum to implement the [unique outputs pattern](https://aiken-lang.org/fundamentals/common-design-patterns#unique-outputs), preventing double-satisfaction vulnerabilities

**Example (Node.js with fetch)**:

```javascript
async function settleTournament(tournamentId, results) {
  const apiUrl = `https://preprod.api.ada-anvil.app/v2/services/tournaments/${tournamentId}/settle`;
  
  const requestData = {
    adminAddress: "addr_test1...",
    tournamentId: tournamentId,
    changeAddress: "addr_test1...", // Optional, defaults to adminAddress
    results: [
      "addr_test1winner...", // 1st place (gets highest prize)
      "addr_test1second...", // 2nd place
      "addr_test1third..."   // 3rd place (and so on)
    ],
    utxos: ["8282...", "8282...", "8282..."] // UTXOs to consume in the transaction
  };
  
  const response = await fetch(apiUrl, {
    method: 'PATCH',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify(requestData),
  });
  
  const data = await response.json();
  console.log('Settlement transaction:', data.complete);
  
  // The returned transaction must be signed and submitted (see Transaction Overview: ../guides/transaction/README.md)
  return data.complete;
}
```
