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

# depositToYieldVault

# depositToYieldVault

Deposits assets into an [Earn](https://docs.dynamic.xyz/docs/earn/overview.md) vault, then signs and sends the transaction for you. You pass a `vaultId` and a plain amount like `'10.5'`, and Dynamic looks up the vault's address and decimal places for you, so you never have to handle those yourself.

For EVM vaults, a wallet needs to give the vault contract permission to move its tokens before its first deposit. This is called an **approval** (or **allowance**). The contract that receives the deposit, and therefore the one the approval authorizes, depends on the vault's provider, and `depositToYieldVault` resolves it for you. If the wallet hasn't approved enough yet, `depositToYieldVault` signs and sends that approval automatically, before the deposit. `onStepChange` tells you which of the two is happening so you can reflect it in your UI.

Solana vaults have no approval step. A Solana deposit is instead an ordered sequence of up to three transactions, such as the deposit followed by a transaction that stakes the new shares in the vault's farm. `depositToYieldVault` signs, sends, and confirms each transaction before it starts the next, and `onTransactionStepChange` reports progress through the sequence.

## Usage

```javascript theme={"system"}
import { depositToYieldVault } from '@dynamic-labs-sdk/client';

const { transactionHash } = await depositToYieldVault({
  vaultId: 'fb-eth-galaxy-usdc-fw-01',
  walletAccount,
  amount: '10.5', // 10.5 USDC — human-readable units, not raw
  onStepChange: (step) => {
    console.log('Step:', step); // 'approval' or 'transaction'
  },
});

console.log('Transaction hash:', transactionHash);
```

## Parameters

| Parameter | Type | Description |
| - | - | - |
| `vaultId` | `string` | Opaque vault identifier, from [`listYieldVaults`](https://docs.dynamic.xyz/docs/javascript/reference/client/list-yield-vaults). |
| `walletAccount` | `WalletAccount` | The wallet account depositing the assets. Must be an EVM wallet account for an EVM vault, or a Solana wallet account for a Solana vault. |
| `amount` | `string` | How much of the vault's underlying asset to deposit, in the asset's human-readable units (`'10.5'` USDC, not `'10500000'`). Rejected when it carries more precision than the asset supports. |
| `receiverAddress` | `string` (optional) | The address credited with the resulting vault position. Defaults to `walletAccount`'s own address. Must equal the wallet's own address for a Solana vault. |
| `onStepChange` | `(step: 'approval' \| 'transaction') => void` (optional) | Callback invoked when the execution step changes. `'approval'` only fires for an EVM vault when the wallet's current allowance is short of `amount`. For a Solana vault, `'transaction'` fires once per transaction in the sequence. |
| `onTransactionStepChange` | `(progress: YieldTransactionProgress) => void` (optional) | Callback invoked as each transaction of a multi-transaction deposit begins, which only happens for Solana vaults. `progress` has `ordinal` (zero-based position), `total` (number of transactions), and an optional `label` such as `'deposit'` or `'stake-in-farm'`. |
| `sponsored` | `boolean` (optional) | Whether the transaction is gas-sponsored. When omitted, an EVM deposit is sponsored if EVM gas sponsorship is enabled and the wallet is a Dynamic embedded wallet, and a Solana deposit is not sponsored. `false` never sponsors. `true` requires sponsorship and rejects when it is unavailable. |
| `client` | `DynamicClient` (optional) | The Dynamic client instance. Only required when using multiple Dynamic clients. |

## Returns

`Promise<{ transactionHash: string }>` - The hash of the deposit transaction. For a Solana vault, this is the signature of the last transaction in the sequence.

## Step Lifecycle

| Step | Description |
| - | - |
| `approval` | Signing the approval transaction (see above). Only fires for an EVM vault when the wallet hasn't already approved enough. |
| `transaction` | Signing the deposit transaction. For a Solana vault, this fires once for each transaction in the sequence. |

> [!WARNING]
>
> For an EVM vault, a resolved `depositToYieldVault` call means the deposit transaction was **sent**, not that it finished. See [Waiting for confirmation](#waiting-for-confirmation) before showing a success state to the user.

## Waiting for confirmation

For an EVM vault, `transactionHash` is returned as soon as the deposit is broadcast to the network, and it can still fail or revert after that. Wait for a receipt before telling the user their deposit succeeded:

```typescript theme={"system"}
import { depositToYieldVault, getActiveNetworkData } from '@dynamic-labs-sdk/client';
import { createPublicClientFromNetworkData } from '@dynamic-labs-sdk/evm/viem';

const { transactionHash } = await depositToYieldVault({
  vaultId: 'fb-eth-galaxy-usdc-fw-01',
  walletAccount,
  amount: '10.5',
});

const { networkData } = await getActiveNetworkData({ walletAccount });
const publicClient = createPublicClientFromNetworkData({ networkData });

const receipt = await publicClient.waitForTransactionReceipt({
  hash: transactionHash as `0x${string}`,
});

if (receipt.status !== 'success') {
  throw new Error('Deposit transaction reverted');
}
```

### Solana vaults

For a Solana vault, `depositToYieldVault` polls each transaction until it reaches the `confirmed` commitment level before it starts the next one, and it resolves only after the last transaction has confirmed. A resolved call therefore means every transaction in the sequence landed, although a `confirmed` transaction is not yet `finalized`. You do not need to wait for a receipt the way you do for an EVM vault.

All of the transactions in the sequence are built against one blockhash, which stays valid only briefly. If the user takes too long to approve, a later transaction expires before it can be signed. When a transaction fails, expires, or is rejected by the user, `depositToYieldVault` stops and rejects with a `SolanaYieldStepError`. Every transaction before the failed one has already confirmed, so the deposit may be partially applied. Read the position with [`getYieldPosition`](https://docs.dynamic.xyz/docs/javascript/reference/client/get-yield-position) before you retry.

`SolanaYieldStepError` is exported from `@dynamic-labs-sdk/solana` and has these properties:

| Property | Type | Description |
| - | - | - |
| `code` | `string` | One of `yield_step_expired`, `yield_step_failed`, or `yield_step_send_failed`. |
| `ordinal` | `number` | Zero-based position of the failed transaction. The transactions before it have already confirmed. |
| `signature` | `string \| undefined` | Signature of the failed transaction, when it was broadcast. |

```typescript theme={"system"}
import { depositToYieldVault } from '@dynamic-labs-sdk/client';
import { SolanaYieldStepError } from '@dynamic-labs-sdk/solana';

try {
  await depositToYieldVault({ vaultId, walletAccount, amount: '10.5' });
} catch (error) {
  if (error instanceof SolanaYieldStepError && error.ordinal > 0) {
    // Earlier transactions confirmed, so check the position before retrying.
  }
}
```

## Examples

### With progress UI

```javascript theme={"system"}
import { useState } from 'react';
import { depositToYieldVault } from '@dynamic-labs-sdk/client';

const DepositButton = ({ vaultId, walletAccount, amount, onComplete }) => {
  const [step, setStep] = useState(null);

  const handleDeposit = async () => {
    const { transactionHash } = await depositToYieldVault({
      vaultId,
      walletAccount,
      amount,
      onStepChange: setStep,
    });

    onComplete(transactionHash);
  };

  return (
    <button onClick={handleDeposit} disabled={!!step}>
      {step === 'approval' && 'Approving...'}
      {step === 'transaction' && 'Depositing...'}
      {!step && 'Deposit'}
    </button>
  );
};
```

> [!NOTE]
>
> This example uses React; the JavaScript SDK is framework-agnostic and can be used with any frontend or in Node.

### Solana vault with transaction progress

```javascript theme={"system"}
import { depositToYieldVault } from '@dynamic-labs-sdk/client';

const { transactionHash } = await depositToYieldVault({
  vaultId, // a vault on Solana
  walletAccount, // a Solana wallet account
  amount: '10.5',
  onTransactionStepChange: ({ label, ordinal, total }) => {
    // For example "Transaction 1 of 2: deposit".
    console.log(`Transaction ${ordinal + 1} of ${total}: ${label ?? 'transaction'}`);
  },
});
```

## Supported Chains

`depositToYieldVault` supports EVM wallet accounts for EVM vaults and Solana wallet accounts for Solana vaults. Pass a wallet account from the same chain family as the vault's `chainName`: the API rejects an address from the other family with an HTTP 400 error. Wallet accounts on other chains are not supported, and a wallet provider that does not implement the underlying `executeYieldTransaction` method throws a `WalletProviderMethodUnavailableError`.

## React

```tsx theme={"system"}
import { useDepositToYieldVault } from '@dynamic-labs-sdk/react-hooks';
import { useState } from 'react';

function DepositButton({ vaultId, walletAccount, amount, onComplete }) {
  const { mutate: deposit, isPending } = useDepositToYieldVault();
  const [step, setStep] = useState(null);

  return (
    <button
      onClick={() =>
        deposit(
          { vaultId, walletAccount, amount, onStepChange: setStep },
          { onSuccess: ({ transactionHash }) => onComplete(transactionHash) },
        )
      }
      disabled={isPending}
    >
      {step === 'approval' && 'Approving...'}
      {step === 'transaction' && 'Depositing...'}
      {!step && 'Deposit'}
    </button>
  );
}
```

`useDepositToYieldVault` accepts the same parameters, including `onTransactionStepChange`. It invalidates [`useGetYieldPosition`](https://docs.dynamic.xyz/docs/javascript/reference/client/get-yield-position) on success, so the position refetches automatically. That refetch can still briefly show the old balance, since the deposit transaction may not be mined yet (see [Waiting for confirmation](#waiting-for-confirmation)).

## Related

* [`withdrawFromYieldVault`](https://docs.dynamic.xyz/docs/javascript/reference/client/withdraw-from-yield-vault) - Withdraw from a vault
* [`getYieldPosition`](https://docs.dynamic.xyz/docs/javascript/reference/client/get-yield-position) - Read the resulting position
* [`listYieldVaults`](https://docs.dynamic.xyz/docs/javascript/reference/client/list-yield-vaults) - Find a vault to deposit into


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.