> ## 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.

# Instructions

> Submit and manage bilateral settlement instructions.

## submit

Submit your side of a bilateral settlement. If a counterparty has already submitted with the same `trade_reference`, the system auto-matches and creates a settlement.

```typescript theme={null}
const instruction = await client.instructions.submit({
  templateSlug: "cross_platform_dvp",
  role: "seller",
  party: {
    externalReference: "KSFI-II-4401",
    name: "Securitize Fund I",
    walletAddress: "0x1234567890abcdef1234567890abcdef12345678",
  },
  legs: [
    {
      legType: "asset_delivery",
      instrumentId: "0x6B175474E89094C44Da98b954EedeAC495271d0F",
      quantity: "12000000",
      direction: "deliver",    // seller delivers the asset
      chainId: 11155111,
    },
    {
      legType: "payment",
      instrumentId: "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48",
      quantity: "12120000000000",
      direction: "receive",    // seller receives payment
      chainId: 11155111,
    },
  ],
  timeoutAt: new Date(Date.now() + 86400000).toISOString(),
  idempotencyKey: client.generateIdempotencyKey(),
});

console.log(instruction.tradeReference); // "KS-abc12345"
console.log(instruction.status);         // "pending_match" or "matched"
console.log(instruction.settlementId);   // UUID if matched, null if pending
```

### Parameters

| Field            | Type                    | Required         | Description                                                                                |
| ---------------- | ----------------------- | ---------------- | ------------------------------------------------------------------------------------------ |
| `templateSlug`   | `string`                | Yes              | Settlement template to use                                                                 |
| `role`           | `string`                | Yes              | Your role (`"seller"` or `"buyer"`)                                                        |
| `party`          | `InstructionPartyInput` | Yes              | Your party details                                                                         |
| `legs`           | `InstructionLegInput[]` | Yes              | What you're delivering                                                                     |
| `timeoutAt`      | `string`                | Yes              | ISO 8601 settlement timeout                                                                |
| `idempotencyKey` | `string`                | Yes              | Unique key for safe retries                                                                |
| `tradeReference` | `string`                | No               | Existing reference to match against                                                        |
| `tradeType`      | `string`                | No               | `"repo_open"` for repo lifecycle (`"spot_dvp"` default)                                    |
| `repoTerms`      | `RepoTermsInput`        | With `repo_open` | Repo economics: `tenorDays`, `rateBps`, `haircutBps`, `marginBandLower`, `marginBandUpper` |

### InstructionPartyInput

| Field               | Type     | Required | Description                                               |
| ------------------- | -------- | -------- | --------------------------------------------------------- |
| `externalReference` | `string` | Yes      | Your internal account or entity ID                        |
| `walletAddress`     | `string` | Yes      | On-chain wallet address (needed for compliance screening) |
| `name`              | `string` | No       | Display name for the party                                |

### InstructionLegInput

Each DvP instruction should include two legs: `asset_delivery` and `payment`. The direction is derived from your role - sellers deliver assets and receive payment, buyers deliver payment and receive assets.

| Field           | Type                     | Required | Description                                                       |
| --------------- | ------------------------ | -------- | ----------------------------------------------------------------- |
| `legType`       | `string`                 | Yes      | `"asset_delivery"` or `"payment"`                                 |
| `instrumentId`  | `string`                 | Yes      | Token contract address (e.g., `0x...`)                            |
| `quantity`      | `string`                 | Yes      | Amount (string for precision)                                     |
| `direction`     | `"deliver" \| "receive"` | Yes      | Derived from role: seller delivers assets, buyer delivers payment |
| `chainId`       | `number`                 | No       | Blockchain network for this leg                                   |
| `tokenStandard` | `string`                 | No       | e.g., `"ERC-20"`, `"ERC-3643"`                                    |

### Return type: InstructionRead

| Field            | Type                | Description                                                |
| ---------------- | ------------------- | ---------------------------------------------------------- |
| `id`             | `string`            | Instruction UUID                                           |
| `tradeReference` | `string`            | Trade reference (generated if not provided)                |
| `status`         | `InstructionStatus` | `"pending_match"`, `"matched"`, `"cancelled"`, `"expired"` |
| `settlementId`   | `string \| null`    | Settlement UUID if matched, null if pending                |
| `templateSlug`   | `string`            | Template used                                              |
| `role`           | `string`            | The role you submitted as                                  |
| `party`          | `object`            | Your party details                                         |
| `legs`           | `object[]`          | Your leg details                                           |
| `timeoutAt`      | `string`            | Settlement timeout                                         |
| `expiresAt`      | `string`            | When this instruction expires if unmatched                 |
| `createdAt`      | `string`            | Creation timestamp                                         |

***

## get

Fetch a single instruction by ID.

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

***

## list

List instructions with optional status filter.

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

for (const instr of items) {
  console.log(`${instr.tradeReference}: ${instr.status}`);
}
```

### Parameters

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

***

## cancel

Cancel a pending instruction. Only works for instructions with `pending_match` status.

```typescript theme={null}
const cancelled = await client.instructions.cancel("instruction-uuid");
console.log(cancelled.status); // "cancelled"
```

***

## Bilateral matching flow

```mermaid theme={null}
sequenceDiagram
    participant S as Seller Platform
    participant KS as KeyStone API
    participant B as Buyer Platform

    S->>KS: instructions.submit(role: "seller")
    KS-->>S: { status: "pending_match", tradeReference: "KS-abc" }
    Note over S,B: Seller shares trade reference with buyer
    B->>KS: instructions.submit(role: "buyer", tradeReference: "KS-abc")
    KS-->>B: { status: "matched", settlementId: "550e8400-e29b-41d4-a716-446655440000" }
```

The first instruction gets `pending_match` and a trade reference. The second instruction with the same trade reference triggers matching and creates a settlement.
