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

# Migrate from v3 to v4

> Migrate from avnu SDK v3 to v4 - Breaking changes, new features, and step-by-step guide.

avnu SDK v4 introduces significant improvements including a new paymaster architecture leveraging starknet.js, streamlined function naming, enhanced type safety with Zod validation, and new services for market data and staking.

If you encounter any missing changes, please [let us know](https://t.me/avnu_developers) and we will update this guide.

<Warning>
  This guide covers **breaking changes** that require code modifications. Review each section carefully before upgrading.
</Warning>

## Quick Summary

* **Function Renaming**: `fetch*` functions renamed to `get*` (e.g., `fetchQuotes` → `getQuotes`)
* **Paymaster Architecture**: Now uses starknet.js `PaymasterInterface` instead of SDK-internal handling
* **`executeSwap` Signature**: Changed from positional arguments to a single params object
* **DCA Service**: Refactored with new `*ToCalls` + `execute*` pattern
* **Type Changes**: `Quote`, `Route`, `Page`, and other types have structural changes
* **Slippage**: Now expressed as decimal (0.01 = 1%) consistently

## Prerequisites

Before migrating, ensure you have:

```bash theme={null}
# Update starknet.js to v8.9+ (required for PaymasterInterface)
npm install starknet@^8.9.1

# Update the SDK
npm install @avnu/avnu-sdk@^4.0.0
```

<Note>
  Node.js >= 22 is required for SDK v4.0.0.
</Note>

## Breaking Changes

### Swap Service

#### Function Renaming

| v3 Function                      | v4 Function                    | Notes                      |
| :------------------------------- | :----------------------------- | :------------------------- |
| `fetchQuotes()`                  | `getQuotes()`                  | Same functionality         |
| `fetchSources()`                 | `getSources()`                 | Same functionality         |
| `fetchBuildExecuteTransaction()` | `quoteToCalls()`               | Returns `AvnuCalls`        |
| `calculateMinAmount()`           | `calculateMinReceivedAmount()` | Slippage semantics changed |

#### New Function

* `calculateMaxSpendAmount(amount, slippage)` - Calculate max spend amount for exactTokenTo swaps

#### Removed Functions

* `fetchPrices()` - Use `getQuotes()` or the new Impulse service `getPrices()`
* `fetchBuildSwapTypedData()` - Paymaster flow refactored
* `fetchExecuteSwapTransaction()` - Paymaster flow refactored

#### `executeSwap` Signature Change

<CodeGroup>
  ```typescript v3 theme={null}
  import { executeSwap } from '@avnu/avnu-sdk';

  const response = await executeSwap(
    account,           // AccountInterface
    quote,             // Quote
    {                  // ExecuteSwapOptions
      executeApprove: true,
      slippage: 0.005,
    },
    { baseUrl: '...' } // AvnuOptions
  );
  ```

  ```typescript v4 theme={null}
  import { executeSwap } from '@avnu/avnu-sdk';

  const response = await executeSwap(
    {                    // InvokeSwapParams
      provider: account, // AccountInterface
      quote,             // Quote
      slippage: 0.005,   // Required (decimal: 0.005 = 0.5%)
      executeApprove: true,
    },
    { baseUrl: '...' }   // AvnuOptions
  );
  ```
</CodeGroup>

#### `quoteToCalls` Change

<CodeGroup>
  ```typescript v3 theme={null}
  import { fetchBuildExecuteTransaction } from '@avnu/avnu-sdk';

  const { calls } = await fetchBuildExecuteTransaction(
    quoteId,
    takerAddress,
    slippage,
    true // includeApprove
  );
  ```

  ```typescript v4 theme={null}
  import { quoteToCalls } from '@avnu/avnu-sdk';

  const { calls, chainId } = await quoteToCalls({
    quoteId,
    slippage: 0.005,
    takerAddress,     // optional
    executeApprove: true,
  });
  ```
</CodeGroup>

### DCA Service

The DCA service has been refactored with a new pattern separating call building from execution.

#### Function Renaming

| v3 Function            | v4 Function          |
| :--------------------- | :------------------- |
| `fetchGetOrders()`     | `getDcaOrders()`     |
| `fetchCreateOrder()`   | `createDcaToCalls()` |
| `fetchCancelOrder()`   | `cancelDcaToCalls()` |
| `executeCreateOrder()` | `executeCreateDca()` |
| `executeCancelOrder()` | `executeCancelDca()` |

#### Removed Functions

These low-level functions have been removed in favor of the new pattern:

* `fetchEstimateFeeCreateOrder()`
* `fetchEstimateFeeCancelOrder()`
* `fetchBuildCreateOrderTypedData()`
* `fetchBuildCancelOrderTypedData()`
* `fetchExecuteCreateOrder()`
* `fetchExecuteCancelOrder()`

#### Type Renaming

| v3 Type           | v4 Type              |
| :---------------- | :------------------- |
| `CreateOrderDto`  | `CreateDcaOrder`     |
| `OrderReceipt`    | `DcaOrder`           |
| `OrderStatus`     | `DcaOrderStatus`     |
| `Trade`           | `DcaTrade`           |
| `TradeStatus`     | `DcaTradeStatus`     |
| `GetOrdersParams` | `GetDcaOrdersParams` |

#### DCA Migration Example

<CodeGroup>
  ```typescript v3 theme={null}
  import { executeCreateOrder, fetchGetOrders } from '@avnu/avnu-sdk';

  // Get orders
  const orders = await fetchGetOrders({ traderAddress });

  // Create order
  const response = await executeCreateOrder(
    account,
    order,
    { gasless: true, gasTokenAddress: '0x...' }
  );
  ```

  ```typescript v4 theme={null}
  import { executeCreateDca, getDcaOrders } from '@avnu/avnu-sdk';

  // Get orders
  const orders = await getDcaOrders({ traderAddress });

  // Create order
  const response = await executeCreateDca({
    provider: account,
    order,
    // Paymaster now uses starknet.js PaymasterInterface
  });
  ```
</CodeGroup>

### Paymaster (Critical Change)

<Warning>
  The paymaster architecture has fundamentally changed. V3's built-in gasless handling has been replaced with starknet.js `PaymasterInterface` integration.
</Warning>

#### v3 Approach (Removed)

In v3, gasless transactions were handled internally by the SDK:

```typescript theme={null}
// v3 - NO LONGER WORKS
const response = await executeSwap(account, quote, {
  gasless: true,
  gasTokenAddress: '0x049d36570d4e46f48e99674bd3fcc84644ddd6b96f7c741b1562b82f9e004dc7',
  maxGasTokenAmount: BigInt('1000000000000000000'),
});
```

#### v4 Approach (New)

In v4, you must use a `PaymasterInterface` from starknet.js:

```typescript theme={null}
import { executeSwap } from '@avnu/avnu-sdk';
// PaymasterInterface comes from starknet.js
import { PaymasterInterface } from 'starknet';

// Create your paymaster provider (implementation depends on your setup)
const paymasterProvider: PaymasterInterface = /* your paymaster implementation */;

const response = await executeSwap({
  provider: account,
  quote,
  slippage: 0.005,
  paymaster: {
    active: true,
    provider: paymasterProvider,
    params: executionParams, // ExecutionParameters from starknet.js
  },
});
```

#### New Paymaster Functions

The SDK now exposes dedicated paymaster functions for advanced use cases:

* `buildPaymasterTransaction()` - Build a transaction for the paymaster
* `signPaymasterTransaction()` - Sign the typed data
* `executePaymasterTransaction()` - Execute the signed transaction
* `executeAllPaymasterFlow()` - Helper that chains all three steps

<Note>
  For detailed paymaster configuration, refer to the [starknet.js documentation](https://www.starknetjs.com/docs/guides/outsideExecution) and the [avnu Paymaster docs](/docs/paymaster/index).
</Note>

### Token Service

The token service has minimal breaking changes. New functions have been added:

* `fetchTokenByAddress(tokenAddress)` - Get a specific token by address
* `fetchVerifiedTokenBySymbol(symbol)` - Get a verified token by symbol

### Type Changes

#### `Quote` Type

```typescript theme={null}
// v3
interface Quote {
  buyAmountWithoutFees: bigint;
  buyAmountWithoutFeesInUsd: number;
  gasFees: bigint;
  gasFeesInUsd: number;
  avnuFees: bigint;
  avnuFeesInUsd: number;
  avnuFeesBps: bigint;
  integratorFees: bigint;
  integratorFeesInUsd: number;
  integratorFeesBps: bigint;
  liquiditySource: string;
  gasless: Gasless;
  // ...
}

// v4
interface Quote {
  fee: Fee;           // Consolidated fee structure
  priceImpact: number;        // New
  estimatedSlippage?: number; // New
  gasFees: bigint;
  gasFeesInUsd?: number;      // Now optional
  // ...
}

interface Fee {
  feeToken: string;
  avnuFees: bigint;
  avnuFeesInUsd: number;
  avnuFeesBps: bigint;
  integratorFees: bigint;
  integratorFeesInUsd: number;
  integratorFeesBps: bigint;
}
```

#### `Route` Type

```typescript theme={null}
// v3
interface Route {
  routeInfo?: Map<string, string>;
  // ...
}

// v4
interface Route {
  routeInfo?: Record<string, string>; // Changed from Map to Record
  alternativeSwapCount: number;       // New field
  // ...
}
```

#### `Source` Type

```typescript theme={null}
// v3
interface Source {
  name: string;
  address: string;  // Removed in v4
  icon?: string;    // Removed in v4
  type: SourceType;
}

// v4
interface Source {
  name: string;
  type: SourceType;
}
```

#### `SourceType` Enum

```typescript theme={null}
// v3
enum SourceType {
  DEX = 'DEX',
  MARKET_MAKER = 'MARKET_MAKER',
  SOLVER = 'SOLVER',        // Removed in v4
  ORDERBOOK = 'ORDERBOOK',
}

// v4
enum SourceType {
  DEX = 'DEX',
  MARKET_MAKER = 'MARKET_MAKER',
  TOKEN_WRAPPER = 'TOKEN_WRAPPER', // New
  ORDERBOOK = 'ORDERBOOK',
}
```

#### `Page<T>` Type

```typescript theme={null}
// v3
interface Page<T> {
  content: T[];
  totalPages: number;
  totalElements: number;
  size: number;
  number: number;  // Field name in v3
}

// v4
interface Page<T> {
  content: T[];
  totalPages: number;
  totalElements: number;
  size: number;
  page: number;    // Renamed from 'number' to 'page'
}
```

### Slippage Semantics

<Warning>
  Slippage is now consistently expressed as a **decimal** value.
</Warning>

| Value   | Meaning       |
| :------ | :------------ |
| `0.001` | 0.1% slippage |
| `0.005` | 0.5% slippage |
| `0.01`  | 1% slippage   |
| `0.05`  | 5% slippage   |

```typescript theme={null}
// Correct usage in v4
const minReceived = calculateMinReceivedAmount(amount, 0.005); // 0.5% slippage
const maxSpend = calculateMaxSpendAmount(amount, 0.01);        // 1% slippage
```

### Gas Fees Denomination

<Warning>
  Gas fees are now denominated in **STRK** instead of **ETH**.
</Warning>

In v3, the `gasFees` field in quotes was denominated in ETH (WEI). Starting from v4, gas fees are denominated in STRK (FRI).

```typescript theme={null}
// v3 - Gas fees in ETH (WEI)
const gasFeesInEth = quote.gasFees; // BigInt in WEI

// v4 - Gas fees in STRK (FRI)
const gasFeesInStrk = quote.gasFees; // BigInt in FRI
```

## New Features (Non-Breaking)

### Impulse Service (Market Data)

New service for market data, prices, volume, and TVL:

```typescript theme={null}
import {
  getMarketData,
  getTokenMarketData,
  getPriceFeed,
  getPrices,
  getVolumeByExchange,
  getTVLByExchange,
  FeedDateRange,
  PriceFeedType,
  FeedResolution,
} from '@avnu/avnu-sdk';

// Get popular tokens with market data
const marketData = await getMarketData();

// Get price feed for a token
const priceFeed = await getPriceFeed(
  tokenAddress,
  {
    type: PriceFeedType.CANDLE,
    dateRange: FeedDateRange.ONE_DAY,
    resolution: FeedResolution.HOURLY,
  }
);
```

### Staking Service

New service for avnu stake delegation:

```typescript theme={null}
import {
  getAvnuStakingInfo,
  getUserStakingInfo,
  stakeToCalls,
  executeStake,
} from '@avnu/avnu-sdk';

// Get staking info
const stakingInfo = await getAvnuStakingInfo();

// Stake tokens
const response = await executeStake({
  provider: account,
  poolAddress: '0x...',
  amount: BigInt('1000000000000000000'),
});
```

### Zod Validation

All API responses are now validated and transformed using Zod schemas:

* Automatic hex string to BigInt conversion
* Automatic ISO string to Date conversion
* Runtime type safety

## Migration Checklist

<Steps>
  <Step title="Update Dependencies">
    ```bash theme={null}
    npm install @avnu/avnu-sdk@^4.0.0 starknet@^6.0.0
    ```
  </Step>

  <Step title="Update Function Imports">
    Replace `fetch*` imports with `get*`:

    ```typescript theme={null}
    // Before
    import { fetchQuotes, fetchSources } from '@avnu/avnu-sdk';

    // After
    import { getQuotes, getSources } from '@avnu/avnu-sdk';
    ```
  </Step>

  <Step title="Update executeSwap Calls">
    Change from positional arguments to params object:

    ```typescript theme={null}
    // Before
    executeSwap(account, quote, options, avnuOptions)

    // After
    executeSwap({ provider: account, quote, slippage, ...options }, avnuOptions)
    ```
  </Step>

  <Step title="Update Paymaster Integration">
    If using gasless transactions, implement `PaymasterInterface` from starknet.js.
  </Step>

  <Step title="Update DCA Calls">
    Replace old DCA functions with new pattern:

    * `fetchGetOrders` → `getDcaOrders`
    * `executeCreateOrder` → `executeCreateDca`
    * `executeCancelOrder` → `executeCancelDca`
  </Step>

  <Step title="Update Type References">
    * `Page.number` → `Page.page`
    * `Route.routeInfo` is now `Record<string, string>` instead of `Map`
    * Access fees via `quote.fee` instead of individual fee fields
  </Step>

  <Step title="Verify Slippage Values">
    Ensure all slippage values are decimals (0.01 = 1%).
  </Step>

  <Step title="Test Your Integration">
    Run your test suite and verify all functionality works as expected.
  </Step>
</Steps>

## Troubleshooting

<AccordionGroup>
  <Accordion title="TypeError: fetchQuotes is not a function">
    The function has been renamed to `getQuotes`. Update your import:

    ```typescript theme={null}
    import { getQuotes } from '@avnu/avnu-sdk';
    ```
  </Accordion>

  <Accordion title="TypeError: Cannot read property 'number' of undefined">
    The `Page` type's `number` field has been renamed to `page`:

    ```typescript theme={null}
    // Before
    const currentPage = result.number;

    // After
    const currentPage = result.page;
    ```
  </Accordion>

  <Accordion title="Gasless transactions not working">
    Gasless handling has moved to starknet.js `PaymasterInterface`. You need to:

    1. Create a `PaymasterInterface` implementation
    2. Pass it via the `paymaster` parameter

    See the [Paymaster section](#paymaster-critical-change) for details.
  </Accordion>

  <Accordion title="Type error on Quote.avnuFees">
    Fee fields are now consolidated under `quote.fee`:

    ```typescript theme={null}
    // Before
    const fees = quote.avnuFees;

    // After
    const fees = quote.fee.avnuFees;
    ```
  </Accordion>

  <Accordion title="Route.routeInfo type mismatch">
    `routeInfo` changed from `Map<string, string>` to `Record<string, string>`:

    ```typescript theme={null}
    // Before (Map)
    const value = route.routeInfo?.get('key');

    // After (Record)
    const value = route.routeInfo?.['key'];
    ```
  </Accordion>
</AccordionGroup>

## Resources

* [avnu SDK GitHub Repository](https://github.com/avnu-labs/avnu-sdk)
* [Dapp Example](https://github.com/avnu-labs/avnu-sdk/tree/develop/dapp-example)
* [starknet.js Documentation](https://www.starknetjs.com/)
* [avnu Paymaster Documentation](/docs/paymaster/index)
* [avnu Developer Telegram](https://t.me/avnu_developers)
