> ## Documentation Index
> Fetch the complete documentation index at: https://docs.keystoneos.xyz/llms.txt
> Use this file to discover all available pages before exploring further.

# Settlements

> Create, monitor, and manage settlements.

<Info>
  Settlements can also be viewed and monitored in the [KeyStone Dashboard](https://app.keystoneos.xyz). Use the SDK for programmatic creation and automation.
</Info>

## create

Direct settlement creation when both parties are known by a single platform.

```typescript theme={null}
const settlement = await client.settlements.create({
  idempotencyKey: client.generateIdempotencyKey(),
  templateSlug: "dvp-bilateral",
  externalReference: "TRADE-2026-0042",
  parties: [
    { role: "seller", externalReference: "ACC-001", name: "Securitize Fund I", walletAddress: "0xSeller..." },
    { role: "buyer", externalReference: "ACC-002", name: "Ondo Capital", walletAddress: "0xBuyer..." },
  ],
  legs: [
    { legType: "asset_delivery", instrumentId: "OUSG", quantity: "500000", direction: "deliver", partyRole: "seller" },
    { legType: "payment", instrumentId: "USDC", quantity: "502500", direction: "deliver", partyRole: "buyer" },
  ],
  timeoutAt: new Date(Date.now() + 86400000).toISOString(),
});
```

<Note>
  **Direct creation vs. bilateral instructions:** Use `settlements.create()` when your platform knows both parties upfront (single-platform use case). For cross-platform settlements - or when counterparties submit independently - use [`instructions.submit()`](/sdks/typescript/instructions). The bilateral instruction flow is the recommended approach for most integrations.
</Note>

### Parameters

| Field               | Type                     | Required | Description                                  |
| ------------------- | ------------------------ | -------- | -------------------------------------------- |
| `idempotencyKey`    | `string`                 | Yes      | Unique key for safe retries                  |
| `templateSlug`      | `string`                 | Yes\*    | Template slug (provide slug or ID, not both) |
| `templateId`        | `string`                 | Yes\*    | Template UUID                                |
| `externalReference` | `string`                 | No       | Your internal trade reference                |
| `parties`           | `SettlementPartyInput[]` | Yes      | All parties in the settlement                |
| `legs`              | `SettlementLegInput[]`   | Yes      | All legs (asset deliveries and payments)     |
| `timeoutAt`         | `string`                 | Yes      | ISO 8601 settlement timeout                  |

### SettlementPartyInput

| Field               | Type     | Required | Description                                |
| ------------------- | -------- | -------- | ------------------------------------------ |
| `role`              | `string` | Yes      | Party role (e.g., `"seller"`, `"buyer"`)   |
| `externalReference` | `string` | Yes      | Your internal account ID                   |
| `walletAddress`     | `string` | Yes      | On-chain wallet (for compliance screening) |
| `name`              | `string` | No       | Display name                               |
| `chainId`           | `number` | No       | Blockchain network                         |

### SettlementLegInput

| Field               | Type                     | Required | Description                           |
| ------------------- | ------------------------ | -------- | ------------------------------------- |
| `legType`           | `string`                 | Yes      | `"asset_delivery"` or `"payment"`     |
| `instrumentId`      | `string`                 | Yes      | Token address, ISIN, or currency code |
| `quantity`          | `string`                 | Yes      | Amount (string for precision)         |
| `direction`         | `"deliver" \| "receive"` | Yes      | Transfer direction                    |
| `partyRole`         | `string`                 | Yes      | Which party owns this leg             |
| `chainId`           | `number`                 | No       | Blockchain network                    |
| `tokenStandard`     | `string`                 | No       | e.g., `"ERC-20"`, `"ERC-3643"`        |
| `externalReference` | `string`                 | No       | External leg reference                |

***

## get

Fetch a settlement by ID with parties and legs.

```typescript theme={null}
const settlement = await client.settlements.get("settlement-uuid");

console.log(settlement.state);              // "AWAITING_DEPOSITS"
console.log(settlement.parties.length);     // 2
console.log(settlement.legs.length);        // 2
console.log(settlement.externalReference);  // "TRADE-2026-0042"
```

### SettlementRead

| Field                | Type                | Description                                                                                |
| -------------------- | ------------------- | ------------------------------------------------------------------------------------------ |
| `id`                 | `string`            | Settlement UUID                                                                            |
| `state`              | `SettlementState`   | Current lifecycle state                                                                    |
| `templateId`         | `string`            | Template UUID                                                                              |
| `templateVersion`    | `number`            | Template version at creation time                                                          |
| `externalReference`  | `string \| null`    | Your trade reference                                                                       |
| `parties`            | `SettlementParty[]` | All parties with roles and status                                                          |
| `legs`               | `SettlementLeg[]`   | All legs with amounts and status                                                           |
| `timeoutAt`          | `string`            | When the settlement times out                                                              |
| `createdAt`          | `string`            | Creation timestamp                                                                         |
| `updatedAt`          | `string`            | Last update timestamp                                                                      |
| `linkedSettlementId` | `string \| null`    | Ties a repo's opening and closing legs together                                            |
| `tradeType`          | `string \| null`    | `"spot_dvp"`, `"repo_open"`, or `"repo_close"`                                             |
| `repoTerms`          | `RepoTerms \| null` | Repo economics (`tenorDays`, `rateBps`, `haircutBps`, margin band, `closeLegSettlementId`) |

### SettlementState

`INSTRUCTED`, `COMPLIANCE_CHECKING`, `COMPLIANCE_CLEARED`, `AWAITING_DEPOSITS`, `SETTLED`, `FINALIZED`, `REJECTED`, `ROLLED_BACK`, `TIMED_OUT`, `MANUAL_REVIEW`

***

## list

Paginated list with optional state filter.

```typescript theme={null}
const { items, total } = await client.settlements.list({
  state: "FINALIZED",
  limit: 20,
  offset: 0,
});

for (const s of items) {
  console.log(`${s.id}: ${s.state} - ${s.externalReference}`);
}
```

| Field    | Type              | Default | Description        |
| -------- | ----------------- | ------- | ------------------ |
| `state`  | `SettlementState` | -       | Filter by state    |
| `limit`  | `number`          | `50`    | Max items per page |
| `offset` | `number`          | `0`     | Items to skip      |

***

## listEvents

State transition history for a settlement.

```typescript theme={null}
const { items: events } = await client.settlements.listEvents("settlement-uuid");

for (const event of events) {
  console.log(`${event.fromState ?? "(initial)"} -> ${event.toState}`);
  console.log(`  At: ${event.createdAt}`);
  console.log(`  By: ${event.triggeredBy}`);
  console.log(`  Hash: ${event.contentHash}`);
}
```

### SettlementEventRead

| Field         | Type             | Description                                                   |
| ------------- | ---------------- | ------------------------------------------------------------- |
| `id`          | `string`         | Event UUID                                                    |
| `sequence`    | `number`         | Event sequence number                                         |
| `fromState`   | `string \| null` | Previous state (null for initial event)                       |
| `toState`     | `string`         | State after this transition                                   |
| `triggeredBy` | `string`         | What triggered it (e.g., `"system:engine"`, `"m2m:platform"`) |
| `contentHash` | `string`         | SHA-256 evidence hash                                         |
| `createdAt`   | `string`         | Timestamp                                                     |

***

## submitComplianceDecision

Approve or reject a settlement flagged during compliance screening.

```typescript theme={null}
// Approve
const settlement = await client.settlements.submitComplianceDecision(
  "settlement-uuid",
  { decision: "approve" },
);

// Reject
const settlement = await client.settlements.submitComplianceDecision(
  "settlement-uuid",
  { decision: "reject" },
);
```

Only applicable when the settlement is in `COMPLIANCE_CHECKING` state with a flagged party.

***

## getRelated

Get the opening and closing legs of a repo settlement pair.

```typescript theme={null}
const { opening, closing } = await client.settlements.getRelated("settlement-uuid");

if (opening) console.log(`Opening: ${opening.id} (${opening.state})`);
if (closing) console.log(`Closing: ${closing.id} (${closing.state})`);
```

Returns `{ opening: SettlementRead | null, closing: SettlementRead | null }`.
