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

# GlamClient

The `GlamClient` class is the main entry point for the GLAM SDK. It uses lazy initialization to load sub-clients only when needed, optimizing performance and resource usage.

```mermaid theme={null}
graph TB
    GC[GlamClient]
    BC[BaseClient]

    GC -->|extends| BC

    CORE[Sub-clients: Core Operations]
    PROTO[Sub-clients: Protocol Integrations]

    GC -.->|lazy load| CORE
    GC -.->|lazy load| PROTO

    MODELS[Data Models<br/><i>StateModel, MintModel</i>]
    GC --> MODELS

    PROGRAMS[GLAM Programs<br/><i>protocol, mint, etc</i>]
    BC -->|RPC| PROGRAMS

    style GC fill:#010101,stroke:#fefefe,color:#fefefe,stroke-width:3px
    style BC fill:#333,stroke:#fefefe,color:#fefefe
    style CORE fill:#444,stroke:#fefefe,color:#fefefe
    style PROTO fill:#444,stroke:#fefefe,color:#fefefe
    style MODELS fill:#555,stroke:#fefefe,color:#fefefe
    style PROGRAMS fill:#666,stroke:#fefefe,color:#fefefe
```

`GlamClient` extends `BaseClient`, which provides:

* **Connection Management**: Handles Solana RPC connections
* **Transaction Processing**: Sign, send, and confirm transactions
* **Program Integration**: Interfaces with GLAM Protocol programs

## Initialization

Initialize `GlamClient` with the default Anchor provider and wallet:

```typescript theme={null}
import { GlamClient, ClusterNetwork } from '@glamsystems/glam-sdk';

// ANCHOR_PROVIDER_URL and ANCHOR_WALLET env variables must be set
const glamClient = new GlamClient();
```

The client can be customized by providing a `GlamClientConfig` object:

```typescript theme={null}
export type GlamClientConfig = {
  provider?: Provider;
  wallet?: Wallet;
  cluster?: ClusterNetwork;
  statePda?: PublicKey;
  jupiterApiKey?: string;
};
```

For example, if Jupiter functionality is used, the Jupiter API key should be configured as follows:

```typescript theme={null}
const glamClient = new GlamClient({ jupiterApiKey: "YOUR_JUPITER_API_KEY" });
```

Refer to [Custom Wallet](./custom-wallet) for more information on how to use a custom wallet.

### Sub-clients

Sub-clients are lazily loaded on first access. For a comprehensive list, see [client.ts](https://github.com/glamsystems/glam-sdk-ts/blob/main/src/client.ts).

| Sub-client      | Category             | Description                                         |
| --------------- | -------------------- | --------------------------------------------------- |
| `jupiterSwap`   | Protocol Integration | Jupiter swap integration                            |
| `kaminoLending` | Protocol Integration | Kamino lending integration                          |
| `kaminoFarm`    | Protocol Integration | Kamino farming integration                          |
| `kaminoVaults`  | Protocol Integration | Kamino vaults integration                           |
| `cctp`          | Protocol Integration | Cross-Chain Transfer Protocol                       |
| `vault`         | Core Operations      | Vault management                                    |
| `access`        | Core Operations      | ACL management                                      |
| `timelock`      | Core Operations      | Time lock management                                |
| `invest`        | Core Operations      | Investment flows (for tokenized vaults)             |
| `fees`          | Core Operations      | Fee management (for tokenized vaults)               |
| `price`         | Core Operations      | Pricing tokens and positions (for tokenized vaults) |
| `state`         | Utilities            | Vault state queries                                 |

## Transaction Builder

Each sub-client provides a `TxBuilder` instance for constructing instructions and transactions.

### Building Instructions

To build an instruction that enables Jupiter Swap on a vault:

```typescript theme={null}
const permissionsMap = getProgramAndBitflagByProtocolName(glamClient.staging);
const [integrationProgram, protocolBitflag] = permissionsMap["JupiterSwap"];

const ix = await glamClient.access.txBuilder.enableDisableProtocolsIx(
  new PublicKey(integrationProgram),
  parseInt(protocolBitflag, 2),
  true,
  signer
);
```

### Building Transactions

To build a complete transaction:

```typescript theme={null}
const tx = await glamClient.access.txBuilder.enableDisableProtocolsTx(
  new PublicKey(integrationProgram),
  parseInt(protocolBitflag, 2),
  true,
  txOptions
);
```

## Sending Transactions

Convert a legacy transaction to a versioned transaction and send it:

```typescript theme={null}
const vTx = await glamClient.intoVersionedTransaction(tx, txOptions); 
const txSig = await glamClient.sendAndConfirm(vTx); 
```

## Transaction Options

Most client methods accept an optional `TxOptions` parameter:

```typescript theme={null}
const txOptions: TxOptions = {
  simulate: true,
  maxFeeLamports: 100_000, // 0.0001 SOL
  useMaxFee: true
}

await glamClient.invest.subscribe(amount, false, txOptions);
```

The `TxOptions` type provides additional configuration for transactions:

```typescript theme={null}
export type TxOptions = {
  signer?: PublicKey;
  computeUnitLimit?: number;
  getPriorityFeeMicroLamports?: (tx: VersionedTransaction) => Promise<number>;
  maxFeeLamports?: number;
  useMaxFee?: boolean;
  preInstructions?: TransactionInstruction[];
  lookupTables?: PublicKey[] | AddressLookupTableAccount[];
  simulate?: boolean;
};
```

**Available options:**

* `signer`: Override the default signer
* `computeUnitLimit`: Set the compute unit limit
* `getPriorityFeeMicroLamports`: Callback function to calculate dynamic priority fees
* `maxFeeLamports`: Set the maximum priority fee
* `useMaxFee`: Use the maximum priority fee
* `preInstructions`: Add instructions before the main instruction
* `lookupTables`: Include address lookup tables
* `simulate`: Simulate the transaction before sending

## State Model

The SDK abstracts on-chain vault state using the `StateModel` class, which defines the vault's configuration at creation time.

```typescript lines state-model.ts theme={null}
export class StateIdlModel implements StateModelType {
  accountType: StateAccountType; // vault or tokenizedVault
  name: number[];                // vault name encoded as char array
  uri: string | null;            // vault URI
  enabled: boolean | null;       // enabled flag
  assets: PublicKey[] | null;    // allowed assets
  created: CreatedModel | null;  // creation seeds, pubkey, and timestamp
  owner: PublicKey | null;       // vault owner
  portfolioManagerName: number[] | null;    // portfolio manager name encoded as char array
  borrowable: PublicKey[] | null;           // borrowable assets
  timelockDuration: number | null;          // timelock duration in seconds
  integrationAcls: IntegrationAcl[] | null; // integration ACLs
  delegateAcls: DelegateAcl[] | null;       // delegate ACLs
  ...
}
```

### Fetching Vault State

Fetch the state of the active vault:

```typescript theme={null}
const stateModel = await glamClient.fetchStateModel();
```

Or fetch the state of a specific vault by passing its state account public key:

```typescript theme={null}
const stateModel = await glamClient.fetchStateModel(vaultStatePubkey);
```

## Mint Model

The SDK represents on-chain mint data using the `MintModel` class, which defines the tokenized vault's configuration at creation time.

```typescript lines mint-model.ts theme={null}
export class MintIdlModel implements MintModelType {
  symbol: string;  // token metadata symbol
  name: number[];  // token metadata name
  uri: string;     // token metadata URI
  yearInSeconds: number | null;         // number of seconds in a year
  permanentDelegate: PublicKey | null;  // permanent delegate
  defaultAccountStateFrozen: boolean | null; // default account state is frozen if true, otherwise active
  feeStructure: FeeStructure | null;    // fee configurations
  notifyAndSettle: NotifyAndSettle | null;// notification and settlement periods 
  lockupPeriod: number | null;            // lockup period in seconds
  maxCap: BN | null;                      // maximum vault capacity
  minSubscription: BN | null;             // minimum subscription amount
  minRedemption: BN | null;               // minimum redemption amount
  allowlist: PublicKey[] | null;          // allowlist of users    
  blocklist: PublicKey[] | null;          // blocklist of users
  ...
}
```

### Accessing Mint Model

Access the `MintModel` of a tokenized vault via its `stateModel`:

```typescript theme={null}
const mintModel = stateModel.mintModel;
```

## Use Staging Programs

<Warning>
  GLAM mainnet staging programs are available for testing and development purposes. They contain unaudited code and features that are not yet ready for production.
</Warning>

To use staging programs, make sure env variable `NEXT_PUBLIC_GLAM_STAGING` or `GLAM_STAGING`, is set to `true`.
