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

# TypeScript SDK

> Full reference for the official Grat TypeScript and JavaScript client.

The TypeScript SDK is the primary way to interact with the Grat relay. It provides a type-safe interface for sponsoring transactions, simulating Soroban contract calls, and monitoring relay health.

<Note>
  Grat SDK is compatible with Stellar Protocol 26 (Yardstick). Fee estimation and Soroban simulation reflect the latest protocol changes.
</Note>

### Installation

<CodeGroup>
  ```bash npm theme={null}
  npm install @grat-official-sdk/sdk
  ```

  ```bash yarn theme={null}
  yarn add @grat-official-sdk/sdk
  ```

  ```bash pnpm theme={null}
  pnpm add @grat-official-sdk/sdk
  ```
</CodeGroup>

### Client Setup

Initialize the Grat client based on your target environment.

<CodeGroup>
  ```typescript Testnet theme={null}
  import { Grat } from '@grat-official-sdk/sdk';

  // Uses the default local relay at http://localhost:3000
  const grat = Grat.testnet();

  // Or specify a custom relay URL
  const gratCustom = Grat.testnet('https://relay-testnet.yourdomain.com');
  ```

  ```typescript Mainnet theme={null}
  import { Grat } from '@grat-official-sdk/sdk';

  // API Key and Relay URL are required for mainnet
  const grat = Grat.mainnet('your-api-key', 'https://relay.yourdomain.com');
  ```
</CodeGroup>

### Constructor Configuration

If you need more control, you can use the standard constructor.

| Parameter    | Type                     | Default     | Description                                    |
| :----------- | :----------------------- | :---------- | :--------------------------------------------- |
| `relayUrl`   | `string`                 | `""`        | The full URL of your Grat relay server.        |
| `network`    | `"testnet" \| "mainnet"` | `"testnet"` | The Stellar network passphrase to use.         |
| `apiKey`     | `string`                 | `""`        | Your project's API key (required for mainnet). |
| `maxRetries` | `number`                 | `3`         | Maximum number of retries for failed requests. |
| `timeout`    | `number`                 | `30000`     | Request timeout in milliseconds.               |

### Methods

#### `sponsor(transaction)`

Wraps a signed transaction in a fee-bump envelope and submits it to the network.

* **Parameters**: `transaction: Transaction | FeeBumpTransaction`
* **Returns**: `Promise<SponsorResult>`

```typescript theme={null}
const result = await grat.sponsor(tx);
console.log(result.hash);
```

#### `sponsorContract(transaction)`

An alias for `sponsor`, specifically labeled for Soroban smart contract transactions.

* **Parameters**: `transaction: Transaction`
* **Returns**: `Promise<SponsorResult>`

```typescript theme={null}
const result = await grat.sponsorContract(sorobanTx);
```

#### `simulate(transaction)`

Simulates a Soroban transaction to get resource fee estimates and diagnostic events.

* **Parameters**: `transaction: Transaction`
* **Returns**: `Promise<SimulationResult>`

```typescript theme={null}
const simulation = await grat.simulate(tx);
console.log(simulation.resourceFee);
```

#### `estimate(transaction)`

Returns estimated network fees (Classic and Soroban) for a given transaction.

* **Parameters**: `transaction: Transaction | FeeBumpTransaction`
* **Returns**: `Promise<EstimateResult>`

```typescript theme={null}
const fees = await grat.estimate(tx);
```

#### `status()`

Returns the health status and metadata of the connected relay server.

* **Returns**: `Promise<HealthStatus>`

```typescript theme={null}
const health = await grat.status();
console.log(health.status); // "ok"
```

### Phase 2 Methods

<Info>
  The following methods are part of the Phase 2 Credit System and are currently under development.
</Info>

* **`credits.balance()`**: Get the current credit balance for your API key.
* **`credits.history()`**: Retrieve a list of recent credit deposits and spend events.
* **`credits.depositInfo()`**: Get instructions for depositing XLM to top up your credits.
* **`transactions.list()`**: List all transactions sponsored by your API key.
* **`transactions.get(hash)`**: Get detailed sponsorship metadata for a specific hash.

### Response Types

#### `SponsorResult`

```typescript theme={null}
interface SponsorResult {
  hash: string;        // Transaction hash
  feePaid: string;     // Total fee paid in stroops
  ledger: number;      // Ledger number where tx was included
  resultXdr: string;   // Stellar result XDR
}
```

### Error Handling

The SDK throws descriptive errors that can be caught and handled.

```typescript theme={null}
try {
  await grat.sponsor(tx);
} catch (error) {
  if (error instanceof GratError) {
    // Relay returned an error (e.g., 400, 429, 500)
    console.error(error.code, error.message);
  } else if (error instanceof NetworkError) {
    // Communication failure with the relay
    console.error("Network issue:", error.message);
  }
}
```

### Automatic Retries

The SDK automatically retries requests that fail due to rate limiting (429) or temporary server issues (503). It uses exponential backoff to avoid overwhelming the relay. You can customize this behavior using the `maxRetries` option in the client configuration.

### End-to-End Example: USDC Payment

```typescript theme={null}
import { Grat } from '@grat-official-sdk/sdk';
import { Keypair, Asset, TransactionBuilder, Networks, Operation } from '@stellar/stellar-sdk';

async function sendUSDC() {
  const grat = Grat.testnet();
  const senderKp = Keypair.fromSecret("SD...");
  const usdc = new Asset("USDC", "GB...");

  // 1. Build payment
  const tx = new TransactionBuilder(
    { publicKey: senderKp.publicKey(), sequence: "123" },
    { fee: "100", networkPassphrase: Networks.TESTNET }
  )
  .addOperation(Operation.payment({
    destination: "GC...",
    asset: usdc,
    amount: "50.00"
  }))
  .setTimeout(30)
  .build();

  // 2. Sign and Sponsor
  tx.sign(senderKp);
  const result = await grat.sponsor(tx);
  
  console.log("USDC Sent! Hash:", result.hash);
}
```

[View on GitHub](https://github.com/gratnetwork/grat)
