> For the complete documentation index, see [llms.txt](https://docs.trilobyte.finance/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.trilobyte.finance/technical-documentation/typescript-sdk.md).

# TypeScript SDK

Trilobyte provides auto-generated TypeScript client bindings for all **seven** contracts. These enable frontend applications, backend services, and keeper bots to interact with the protocol.

## Packages

| Package                                  | Path                                       | Description                                                                                                                  |
| ---------------------------------------- | ------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------- |
| `@trilobyte/globals-client`              | `contracts/globals/bindings/`              | Settings, roles, collateral, fees, both asset whitelists, exposure tracking, compliance-gate pointer, Factory/vault registry |
| `@trilobyte/vault-client`                | `contracts/vault/bindings/`                | Full two-tranche vault lifecycle, waterfall payments, yield/recovery claims, covenants, debt tokens, SEP-41                  |
| `@trilobyte/factory-client`              | `contracts/factory/bindings/`              | Vault creation, registry queries (incl. pagination)                                                                          |
| `@trilobyte/timelock-client`             | `contracts/timelock/bindings/`             | Schedule, execute, cancel operations, AccessControl                                                                          |
| `@trilobyte/collateral-escrow-client`    | `contracts/collateral-escrow/bindings/`    | Borrower-collateral lock / release / seize, pledge queries                                                                   |
| `@trilobyte/compliance-allowlist-client` | `contracts/compliance-allowlist/bindings/` | `is_allowed` gate queries, `set_allowed` admin writes                                                                        |
| `@trilobyte/web-auth-client`             | `contracts/web-auth/bindings/`             | SEP-45 `web_auth_verify`                                                                                                     |

## Generation

Bindings are generated using the Stellar CLI:

```bash
# Generate all bindings (build WASM + generate + compile)
./scripts/generate-bindings.sh
```

This runs `stellar contract bindings typescript` for each contract, generating fully typed TypeScript clients from the contract ABIs.

## Usage

### Installation

Add bindings as local path dependencies in your project's `package.json`:

```json
{
  "dependencies": {
    "@trilobyte/globals-client": "file:../trilobyte-new/contracts/globals/bindings",
    "@trilobyte/vault-client": "file:../trilobyte-new/contracts/vault/bindings",
    "@trilobyte/factory-client": "file:../trilobyte-new/contracts/factory/bindings",
    "@trilobyte/timelock-client": "file:../trilobyte-new/contracts/timelock/bindings",
    "@trilobyte/collateral-escrow-client": "file:../trilobyte-new/contracts/collateral-escrow/bindings",
    "@trilobyte/compliance-allowlist-client": "file:../trilobyte-new/contracts/compliance-allowlist/bindings"
  }
}
```

### Example: Query Vault Config

```typescript
import { Client as VaultClient } from '@trilobyte/vault-client';

const vault = new VaultClient({
  contractId: 'CABC...',
  networkPassphrase: 'Test SDF Network ; September 2015',
  rpcUrl: 'https://soroban-testnet.stellar.org',
});

const config = await vault.get_config();
console.log('Phase:', config.result.phase);
console.log('Leverage ratio:', config.result.leverage_ratio);

// `outstanding` is NOT a field on VaultConfig — query it separately, per tranche:
const outstandingSenior = await vault.get_outstanding_senior();
const outstandingJunior = await vault.get_outstanding_junior();
console.log('Outstanding:', outstandingSenior.result, outstandingJunior.result);
```

### Example: Deposit into a Tranche

```typescript
const tx = await vault.deposit({
  investor: 'GABC...',
  amount: 20_000_0000000n, // 20,000 with 7 decimals
  tranche: 1, // Tranche::Junior = 1, Tranche::Senior = 0
});

await tx.signAndSend();
```

### Example: Create a Vault

`create_vault` takes the full `VaultParams` struct, which now carries `leverage_ratio` and `reporting_interval` in place of the removed `split_ratio`, plus the `related_party` disclosure flag:

```typescript
import { Client as FactoryClient } from '@trilobyte/factory-client';

const factory = new FactoryClient({
  contractId: 'CDEF...',
  networkPassphrase: 'Test SDF Network ; September 2015',
  rpcUrl: 'https://soroban-testnet.stellar.org',
});

const tx = await factory.create_vault({
  params: {
    manager: 'GABC...',
    borrower: 'GDEF...',
    lent_token: 'CGHI...',
    principal: 100_000_0000000n,
    interest_rate: 1500, // 15%
    loan_term: 12,
    leverage_ratio: 400, // 4.00x -> junior = 20% of principal
    reporting_interval: 0n, // no reporting covenant
    permissioned: false,
    grace_period: 2592000n,
    funding_deadline: 0n,
    approval_deadline: 0n,
    related_party: false,
    // Borrower collateral (optional). For a manager-collateral-only loan:
    collateral_escrow: undefined,   // Option<Address> → None
    collateral_token: undefined,    // Option<Address> → None
    collateral_recovery: undefined, // Option<Address> → None
    collateral_min: 0n,
  },
  salt: Buffer.from('unique-salt-value-32-bytes......'), // 32 bytes
});

await tx.signAndSend();
```

For a **borrower-collateral-backed** loan, set `collateral_escrow` to the escrow contract address, `collateral_token` to the pledged asset (which must be on Globals' collateral-asset whitelist), `collateral_recovery` to the recovery party, and `collateral_min` to the on-chain floor — then have the borrower `lock` the pledge in the escrow and call the vault's `record_collateral_pledge(pledge_id)` before disbursement.

### Example: Fund the junior tranche, then lock it

```typescript
// Junior investor(s) deposit until junior_target is reached
await (await vault.deposit({ investor: 'GJUN...', amount: 20_000_0000000n, tranche: 1 })).signAndSend();

// Manager locks junior once junior_raised + collateral_amount >= junior_target
await (await vault.lock_junior({ caller: 'GMGR...' })).signAndSend();

// Now senior deposits are accepted
await (await vault.deposit({ investor: 'GSEN...', amount: 80_000_0000000n, tranche: 0 })).signAndSend();
```

### Example: Claim yield from a tranche

```typescript
const claimable = await vault.get_claimable({ investor: 'GSEN...', tranche: 0 });
console.log('Claimable senior yield:', claimable.result);

await (await vault.claim_yield({ investor: 'GSEN...', tranche: 0 })).signAndSend();
```

## Keeper / Cron Integration

The TypeScript bindings are consumed by the `trilobyte-vault` NestJS backend. The keeper cron module uses them to:

1. **`apply_late_fee()`** — when a payment is overdue (manager-only)
2. **`check_default()`** — when past the grace period (permissionless)
3. **`check_funding_expiry()`** / **`check_approval_expiry()`** — for deadline enforcement (permissionless)
4. **`check_reporting()`** — when a reporting covenant is overdue (permissionless)
5. **`bump_investor_ttls(start, count)`** — paginated TTL keep-alive for investor position records
6. Instance/persistent TTL extension for Globals, Factory, and Timelock, plus the shared vault Wasm code entry by hash — see the TTL policy in [Deployment](/technical-documentation/deployment.md)

All except `apply_late_fee` are permissionless entry points callable by any address.

*As of September 2026.*
