# Getting Started

{% hint style="info" %}
Integrate YieldFi vaults seamlessly via our SDK. If you have any questions or run into issues during setup, feel free to raise them in our [Discord channel](https://discord.gg/hkhXWr9gN9) or reach out directly on Telegram at **SGYield**.
{% endhint %}

## Quick Start

Get started with the YieldFi SDK in just a few minutes. This guide will walk you through the essential steps to integrate the SDK into your application.

### Step 1: Initialize the SDK

First, create an instance of the YieldFi SDK:

```typescript
import { YieldFiSDK } from "yieldfi-sdk";

// Initialize SDK (async)
const sdk = await YieldFiSDK.create({
  gatewayUrl: "https://gw.yield.fi",
  partnerId: "your-partner-id", // Optional: for tracking
});
```

### Step 2: Authenticate a User

The SDK uses Ethereum wallet signatures for authentication. Here's the complete flow:

```typescript
// 1. Generate a nonce for the user's address
const nonce = await sdk.auth.generateNonce({
  address: "0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb",
});

// 2. Sign the message with the user's wallet
// Using ethers.js v6
import { ethers } from "ethers";

const provider = new ethers.BrowserProvider(window.ethereum);
const signer = await provider.getSigner();
const signature = await signer.signMessage(nonce.message);

// Or using MetaMask directly
const signature = await window.ethereum.request({
  method: "personal_sign",
  params: [nonce.message, userAddress],
});

// 3. Login with the signature
const authResponse = await sdk.auth.login({
  address: "0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb",
  signature,
  message: nonce.message,
});

// 4. Store tokens (you must manage storage yourself)
localStorage.setItem("accessToken", authResponse.accessToken);
localStorage.setItem("refreshToken", authResponse.refreshToken);
localStorage.setItem("user", JSON.stringify(authResponse.user));
```

### Step 3: Query Vaults

Now you can query vault information:

```typescript
// Get all vaults
const vaults = await sdk.vault.getVaults({
  chainId: 1, // Ethereum
  page: 1,
  pageSize: 20,
});

console.log(`Found ${vaults.pagination.total} vaults`);

// Get a specific vault by key
const vault = await sdk.vault.getVaultByKey("yusd", 1);

console.log(`Vault: ${vault.vault.name}`);
console.log(`TVL: ${vault.vault.metrics.tvl}`);
console.log(`APY: ${vault.vault.metrics.apy7d}%`);
```

### Step 4: Query Transactions (Authenticated)

To query transactions, you need an authenticated user:

```typescript
const accessToken = localStorage.getItem("accessToken");

// Get user's transactions
const transactions = await sdk.vault.getTransactions(
  {
    chainId: 1,
    type: "deposit",
    status: "PROCESSED",
    page: 1,
    pageSize: 20,
  },
  accessToken
);

console.log(`Found ${transactions.pagination.total} transactions`);
transactions.data.forEach((tx) => {
  console.log(`Transaction ${tx.id}: ${tx.type} - ${tx.status}`);
});
```

### Step 5: Handle Errors

Always wrap SDK calls in try-catch blocks:

```typescript
import {
  AuthenticationError,
  NetworkError,
  ValidationError,
} from "yieldfi-sdk";

try {
  const vault = await sdk.vault.getVaultByKey("yusd", 1);
} catch (error) {
  if (error instanceof AuthenticationError) {
    console.error("Authentication failed:", error.message);
    // Redirect to login
  } else if (error instanceof NetworkError) {
    console.error("Network error:", error.message);
    // Show retry option
  } else if (error instanceof ValidationError) {
    console.error("Invalid input:", error.message);
    // Show validation error to user
  } else {
    console.error("Unexpected error:", error);
  }
}
```

### Complete Example

Here's a complete example combining all the steps:

```typescript
import { YieldFiSDK } from "yieldfi-sdk";
import { ethers } from "ethers";

async function initializeApp() {
  // 1. Initialize SDK
  const sdk = await YieldFiSDK.create({
    gatewayUrl: "https://gw.yield.fi",
  });

  // 2. Check if user is already authenticated
  const storedToken = localStorage.getItem("accessToken");
  if (storedToken) {
    try {
      // Verify token is still valid by making an authenticated request
      const transactions = await sdk.vault.getTransactions(
        { chainId: 1, page: 1, pageSize: 1 },
        storedToken
      );
      console.log("User is authenticated");
    } catch (error) {
      // Token expired or invalid, clear storage
      localStorage.removeItem("accessToken");
      localStorage.removeItem("refreshToken");
      console.log("Session expired, please login again");
    }
  }

  // 3. Authenticate user (if not already authenticated)
  if (!storedToken) {
    const provider = new ethers.BrowserProvider(window.ethereum);
    const signer = await provider.getSigner();
    const address = await signer.getAddress();

    const nonce = await sdk.auth.generateNonce({ address });
    const signature = await signer.signMessage(nonce.message);

    const authResponse = await sdk.auth.login({
      address,
      signature,
      message: nonce.message,
    });

    localStorage.setItem("accessToken", authResponse.accessToken);
    localStorage.setItem("refreshToken", authResponse.refreshToken);
    localStorage.setItem("user", JSON.stringify(authResponse.user));
  }

  // 4. Query vaults
  const vaults = await sdk.vault.getVaults({ chainId: 1 });
  console.log(`Available vaults: ${vaults.pagination.total}`);

  return sdk;
}

// Initialize the app
initializeApp().then((sdk) => {
  console.log("SDK initialized successfully!");
});
```

### Next Steps

* Configuration Guide - Learn about advanced configuration options
* Authentication Guide - Deep dive into authentication flows
* API Reference - Explore all available APIs


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.yield.fi/earn-with-yieldfi/integration-sdk/getting-started.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
