> For the complete documentation index, see [llms.txt](https://docs.sodex.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.sodex.com/for-developers/developers/wealth/bridged-vaults.md).

# Bridged Vaults

Deposit into or redeem from an external vault through SoDEX's bridge contracts on **ValueChain**. Submit directly with wallet-paid gas, or sign a Permit and use [Transaction Relayer](https://docs.sodex.com/for-developers/developers/valuechain-evm/relayer.md). Both paths settle asynchronously.

This guide uses the live `Morpho-Earn` fund: USDC ↔ soUSDC through Base (`BASE_ETH`). Wealth displays the share as `vsoUSDC`; bridge calls use **`soUSDC`**.

## Configuration

Load [Fund Information](https://docs.sodex.com/for-developers/api-reference/wealth-api/funds.md#get-fund-information) for `Morpho-Earn` and confirm `fundType=bridged_vault`, `fundStatus=live`. Read `caller()`, `callForPermit()`, and `getToken(symbol)` from the [Mainnet Portal](https://docs.sodex.com/for-developers/developers/wealth/contracts.md#bridged-vault-contracts). Check that `getToken("soUSDC")` matches the fund's `share.address`.

| Setting                    | Value                                                 |
| -------------------------- | ----------------------------------------------------- |
| Transaction network        | ValueChain Mainnet, chain ID `286623`                 |
| External execution network | Base: `BASE_ETH`                                      |
| Deposit                    | Type `3` (`DEPOSIT_VAULT`), `USDC` → `soUSDC`         |
| Redeem                     | Type `4` (`REDEEM_VAULT`), `soUSDC` → `USDC`          |
| Delivery                   | `toClob=false`: signing user's ValueChain EVM balance |

A bridged fund has no local escrow vault: `contracts` may be empty and `chainConfig` may be `null`. [Trading status](https://docs.sodex.com/for-developers/api-reference/wealth-api/trading.md) does not currently expose bridge readiness and may return `not found` or `closed / bridge_not_ready`. Validate the on-chain route and simulate the call instead of waiting for a `bridge` channel.

The user needs USDC for deposits or shares for redemptions **on ValueChain**. For [Bridge Deposits](https://docs.sodex.com/for-developers/developers/mirror-protocol/lifecycle/deposits.md) from an external wallet, set `toClob=true` when the funds are intended for Spot/Future trading; otherwise, `toClob=false` is recommended to credit the ValueChain EVM balance. Vault deposits spend this EVM balance. These ValueChain vault requests require neither ERC-20 approval nor an ERC-2612 signature; source-chain bridge deposits have their own approval step.

**Amounts:** use `bigint` in each ValueChain token's local units (`decimals()`). `inAmount` is the input; `minOutAmount` is the minimum acceptable output after slippage. Both must remain positive after route normalization. NAV is a valuation snapshot, not an execution quote; supply a minimum based on a current quote and the user's accepted tolerance.

Check route availability, balances, minimums, and `normalizeAmountByChain` before submitting. Order/event amounts use **external chain units**; convert them with the relevant token's `convertFromChainAmount` before comparing with ValueChain balances.

## Gasless integration

The user signs EIP-712 data. Relayer calls `SoDexTokenCallForPermit.execute`, which verifies the signature and asks Caller to create the request for the signer.

Register an [integration ID](https://docs.sodex.com/for-developers/developers/valuechain-evm/relayer.md#register-an-integration-id) and have the **Permit contract** approved as your Relayer target. Relayer pays native SOSO gas on Mainnet; the user supplies the input asset.

| Field                                    | Value                                                              |
| ---------------------------------------- | ------------------------------------------------------------------ |
| EIP-712 domain                           | Name `SoDexTokenCallForPermit`, version `1.0.0`, chain ID `286623` |
| `verifyingContract` and Relayer `target` | Permit proxy address                                               |
| Signed `to` and `execute` argument `to`  | Caller address                                                     |
| Primary type / command                   | `CallForPermit` / `CreateBridgeCallFor`                            |

Use `signTypedData`, not `personal_sign` or `signMessage`. This path supports EOA signatures, not ERC-1271 contract-wallet signatures. Read `nonces(user, key)` immediately before signing and pass its complete return value unchanged; coordinate sequential requests for the same user/key. The example uses key `0`.

### Core signing and submission flow

The following snippets assume a viem ValueChain public `client`, the user's connected `wallet`, and the deployed contracts' ABIs (`permitAbi` and `callerAbi`). Build `cmd` from the operation table above, with `chain="BASE_ETH"`, local-unit amounts, and `toClob=false`. Define EIP-712 `types` using these field names, types, and order:

```
CallForPermit(address to,CreateBridgeCallFor cmd,uint256 nonce,uint256 deadline)
CreateBridgeCallFor(string chain,uint8 callForType,string inCoinSymbol,uint256 inAmount,string outCoinSymbol,uint256 minOutAmount,bool toClob)
```

```typescript
const nonce = await client.readContract({
  address: permit, abi: permitAbi, functionName: "nonces",
  args: [user.address, 0n],
});
const deadline = (await client.getBlock()).timestamp + 600n;
const cmdData = encodeAbiParameters(
  parseAbiParameters("string, uint8, string, uint256, string, uint256, bool"),
  [cmd.chain, cmd.callForType, cmd.inCoinSymbol, cmd.inAmount,
   cmd.outCoinSymbol, cmd.minOutAmount, cmd.toClob],
); // Arguments only; no function selector.

const signature = await wallet.signTypedData({
  account: user.address,
  domain: {
    name: "SoDexTokenCallForPermit", version: "1.0.0",
    chainId: 286623, verifyingContract: permit,
  },
  types, primaryType: "CallForPermit",
  message: { to: caller, cmd, nonce, deadline },
});
const args = [caller, "CreateBridgeCallFor", cmdData, nonce, deadline, signature] as const;
await client.simulateContract({
  address: permit, abi: permitAbi, functionName: "execute", args,
  account: user.address,
});
const calldata = encodeFunctionData({ abi: permitAbi, functionName: "execute", args });

// Persist the request before POST; save payload.result.tx_hash afterward.
const response = await fetch("https://mainnet-gw.sodex.dev/api/v1/relayer/tx", {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({ target: getAddress(permit), calldata, integration_id: integrationId }),
});
const payload = await response.json();
if (!response.ok || payload.status !== "1") throw new Error(payload.message || "Relayer error");
if (!payload.result?.tx_hash) throw new Error("Submission unknown; reconcile before retrying");
```

The signed `cmd` is a nested `CreateBridgeCallFor` struct, not a `bytes` field. You can verify the local EIP-712 digest against `hashCallForPermit(to, cmdType, cmdData, nonce, deadline)` before signing. The deadline limits request creation; it does not cancel an order already created.

## Direct submission

Call the seven-argument method from the user's ValueChain wallet, which pays SOSO gas. These Solidity sketches use enum values `3` and `4`:

```solidity
// Deposit
caller.createBridgeCallFor("BASE_ETH", DEPOSIT_VAULT, "USDC", assets, "soUSDC", minShares, false);
// Redeem
caller.createBridgeCallFor("BASE_ETH", REDEEM_VAULT, "soUSDC", shares, "USDC", minAssets, false);
```

Apply the same route validation and simulation. The direct method uses `msg.sender` as owner; sending it directly through Relayer would use the Relayer wallet's assets. The overload with an explicit `account` is restricted to Permit.

### Query status on chain

Use the ValueChain RPC directly; no Relayer status query is needed. Include `BridgeCallForCreated` and `getCallForById` in `callerAbi`, and import `parseEventLogs` from viem. Pass the wallet's request `txHash`, the submitting `user`, and the submitted `cmd`:

```typescript
const sameAddress = (a: string, b: string) => a.toLowerCase() === b.toLowerCase();
const receipt = await client.waitForTransactionReceipt({ hash: txHash });
if (receipt.status !== "success") throw new Error("Request reverted");
const events = parseEventLogs({
  abi: callerAbi, eventName: "BridgeCallForCreated", strict: true,
  logs: receipt.logs.filter((log) => sameAddress(log.address, caller)),
});
const matches = events.map((event) => event.args.bridgeCallFor).filter((order) =>
  sameAddress(order.user, user.address) && order.chain === cmd.chain &&
  order.callForType === cmd.callForType && order.inCoinSymbol === cmd.inCoinSymbol &&
  order.outCoinSymbol === cmd.outCoinSymbol && order.toClob === cmd.toClob,
);
if (matches.length !== 1) throw new Error("Expected one matching bridge order");
const callForId = matches[0].callForId; // Save with Caller address and request hash.

const order = await client.readContract({
  address: caller, abi: callerAbi, functionName: "getCallForById", args: [callForId],
});
console.log("Bridge status:", order.status, "Output (external units):", order.outAmount);
```

Repeat only `getCallForById` every 5–10 seconds while status is `0` (`PENDING`) or `4` (`APPROVED`). Stop at `1` (`SUCCESS`), `2` (`FAILED`), or `3` (`REJECTED`) and reconcile credit as below. After a timeout or restart, resume with the saved Caller and `callForId`; do not submit another request.

## Settlement and recovery

**Transaction confirmation means the request was created, not that the vault operation settled.**

1. Follow [Relayer transaction status](https://docs.sodex.com/for-developers/api-reference/relayer-api/transaction-status.md), including `replaced_by_hash`. For direct submission, wait for a successful receipt.
2. Parse Caller's `BridgeCallForCreated` event from that receipt and save `callForId`. Match the signer and operation; do not predict the ID before submission.
3. Query `getCallForById(callForId)` on the same Caller until terminal, then reconcile output or returned input.

| Status     | Value | Action                                                |
| ---------- | ----- | ----------------------------------------------------- |
| `PENDING`  | `0`   | Input locked; continue tracking.                      |
| `APPROVED` | `4`   | Input burned; external execution awaits settlement.   |
| `SUCCESS`  | `1`   | Convert `outAmount` to local units and verify credit. |
| `FAILED`   | `2`   | Input minted back; verify its return.                 |
| `REJECTED` | `3`   | Input unlocked; verify its return.                    |

With `toClob=false`, output and returned input go to the signing user's EVM balance. There is no separate receiver. `toClob=true` selects CLOB delivery, including refunds, and requires destination-specific reconciliation. No escrow claim or adapter `sync*` call is needed.

For the indexed timeline, query [User Fund History](https://docs.sodex.com/for-developers/api-reference/wealth-api/user-fund-history.md) with `fundId=Morpho-Earn&channel=bridge`. Match `bridge.sourceChainId`, `bridge.contract`, and `bridge.orderId` to the ValueChain chain ID, Caller, and `callForId`. Keep the request hash separately: the order's `txHash` is the external execution hash on success.

A timeout or missing history row does not establish failure. Resume the saved transaction/order; if submission returned no hash, follow [Submission Recovery](https://docs.sodex.com/for-developers/developers/valuechain-evm/relayer.md#submission-recovery) before retrying. Check input return after a failed/rejected order. Use settlement events and converted amounts to reconcile credit, since current balances may include other transfers.
