> 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/mirror-protocol/lifecycle/valuechain-transfers.md).

# ValueChain to Spot or Perps

Move an asset that is **already on ValueChain EVM** into a Spot or Perps trading account. This is not a custody or bridge deposit. A bridge call with `toClob: true` already credits Spot and must not be followed by another `depositERC20`. To move funds back to EVM and then off-chain, use [Withdrawals](https://docs.sodex.com/for-developers/developers/mirror-protocol/lifecycle/withdrawals.md).

Call [ClobGateway](https://docs.sodex.com/for-developers/developers/valuechain-evm/contracts.md) (`0x0101010101010101010101010101010101010101` on Mainnet and Testnet). For a direct deposit, the sending wallet pays native SOSO gas. For a permit-enabled ERC-20, a sponsor can [pay gas for a Spot deposit](#sponsored-erc-20-deposit-to-spot). For sponsored submission of an allowlisted call, see [Transaction Relayer](https://docs.sodex.com/for-developers/developers/valuechain-evm/relayer.md) (Mainnet only).

## 1. Confirm the asset can trade

Load [Asset Configuration](https://docs.sodex.com/for-developers/api-reference/mirror-api/asset-configuration.md). The asset can enter CLOB only when `sodexMetadata` is not `null`. Use `sodexMetadata.id` when a trading API requires an asset ID. `0` is valid (USDC); do not treat it as missing.

The ERC-20 to approve is `valueChainMetadata.evmAddress`. Native SOSO has no ERC-20 address. WSOSO is a different token (`0x5050…5050`); use it only when that is the configured trading asset.

```bash
curl -sS 'https://mainnet-gw.sodex.dev/api/v1/asset/config?name=USDC' \
  -H 'Accept: application/json'

curl -sS 'https://mainnet-gw.sodex.dev/api/v1/asset/config?name=SOSO' \
  -H 'Accept: application/json'
```

For SOSO, `valueChainMetadata.isNativeToken` is `true` and `evmAddress` is omitted.

## 2. Check whether the trading account exists

```bash
curl -sS "https://mainnet-gw.sodex.dev/api/v1/user/$USER_ADDRESS/status" \
  -H "Accept: application/json"
```

If `data.status` is `UserNotFound`, the first deposit must be **USDC or SOSO**. Activating the account costs **1 USDC or 1 SOSO**. After the account exists, other assets with non-null `sodexMetadata` can be deposited. This Gateway URL is Mainnet; there is no Testnet Mirror API.

## 3. Deposit from ValueChain

ClobGateway overloads:

| Destination | Call                                                                                                                                                    |
| ----------- | ------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Spot        | `depositERC20(address token, uint256 amount)` — credits the caller.                                                                                     |
| Perps       | `depositERC20(address token, uint256 amount, address recipient, uint256 destination)` with `destination = 1`. `recipient` is the trading-account owner. |

### ERC-20

Save as `trading-deposit.mts` and run `npx tsx trading-deposit.mts`. Set `PRIVATE_KEY`, `TOKEN_ADDRESS` to `valueChainMetadata.evmAddress`, `RAW_AMOUNT` in that token's base units, and `DESTINATION` to `spot` or `perps`. This broadcasts Mainnet transactions from the signer to its own trading account. The wallet needs native SOSO for gas.

```typescript
import { createPublicClient, createWalletClient, defineChain, http, parseAbi, type Address, type Hex } from "viem";
import { privateKeyToAccount } from "viem/accounts";

const valuechain = defineChain({
  id: 286623, name: "ValueChain",
  nativeCurrency: { name: "SOSO", symbol: "SOSO", decimals: 18 },
  rpcUrls: { default: { http: ["https://mainnet.valuechain.xyz"] } },
});
const account = privateKeyToAccount(process.env.PRIVATE_KEY as Hex);
const publicClient = createPublicClient({ chain: valuechain, transport: http() });
const walletClient = createWalletClient({ account, chain: valuechain, transport: http() });
const token = process.env.TOKEN_ADDRESS as Address;
const depositContract = "0x0101010101010101010101010101010101010101";
const amount = BigInt(process.env.RAW_AMOUNT!);
const destination = process.env.DESTINATION;
if (destination !== "spot" && destination !== "perps") throw new Error("Set DESTINATION to spot or perps");
const abi = parseAbi([
  "function approve(address spender, uint256 allowance) returns (bool)",
  "function depositERC20(address token, uint256 amount)",
  "function depositERC20(address token, uint256 amount, address recipient, uint256 destination)",
]);
const approval = await walletClient.writeContract({
  address: token, abi, functionName: "approve", args: [depositContract, amount],
});
const approvalReceipt = await publicClient.waitForTransactionReceipt({ hash: approval });
if (approvalReceipt.status !== "success") throw new Error("Approval reverted");

const hash = destination === "spot"
  ? await walletClient.writeContract({
      address: depositContract, abi, functionName: "depositERC20", args: [token, amount],
    })
  : await walletClient.writeContract({
      address: depositContract, abi, functionName: "depositERC20",
      args: [token, amount, account.address, 1n],
    });
console.log({ transactionHash: hash });
const receipt = await publicClient.waitForTransactionReceipt({ hash });
if (receipt.status !== "success") throw new Error("Trading-account deposit reverted");
```

### Sponsored ERC-20 deposit to Spot

On ValueChain Mainnet (chain ID `286623`), the token owner signs two EIP-712 messages off-chain. A sponsor pays SOSO gas to submit one transaction to **SoDexTokenCallForPermit** at `0x890B7D142841065E64E5f94a455876e6352A7801`. This flow requires a ValueChain ERC-20 that supports EIP-2612 permit. It credits the owner’s Spot account.

| Step                        | Contract                | Authorization                                                                                                                                                                                                  |
| --------------------------- | ----------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| 1. Sign the token permit    | ValueChain ERC-20       | The owner authorizes **SoDexTokenCallForPermit** to spend the exact raw amount. Read `nonces(owner)` on the token.                                                                                             |
| 2. Sign the deposit command | SoDexTokenCallForPermit | The owner authorizes `DepositERC20WithPermit` with **ClobGateway** as `to`. Read the full nonce from `nonces(owner, key)` on the permit contract.                                                              |
| 3. Submit                   | SoDexTokenCallForPermit | The sponsor calls `execute(to, cmdType, cmdData, nonce, deadline, signature)` with transaction value zero. The contract uses the token permit, pulls the tokens and calls ClobGateway on behalf of the signer. |

The ethers v6 example takes an owner signer connected to ValueChain Mainnet and a USDC amount in whole-token units (for example, `"35.688167"`). The two signatures use separate domains and nonces. The deadline is Unix seconds. The example uses nonce key `2`, as in the transaction below.

```javascript
import { AbiCoder, Contract, Interface, Signature, TypedDataEncoder, parseUnits } from "ethers";

const permitAddress = "0x890B7D142841065E64E5f94a455876e6352A7801";
const clob = "0x0101010101010101010101010101010101010101";
const usdc = "0xcb7F80Dff2727c791fA491722c428e6657f7e2c6";
const cmdType = "DepositERC20WithPermit";
const permitAbi = [
  "function nonces(address,uint192) view returns (uint256)",
  "function hashCallForPermit(address,string,bytes,uint256,uint256) view returns (bytes32)",
  "function execute(address,string,bytes,uint256,uint256,bytes)"
];

async function signSpotDeposit(ownerSigner, amountText) {
  const provider = ownerSigner.provider;
  const { chainId } = await provider.getNetwork();
  if (chainId !== 286623n) throw new Error("Connect to ValueChain Mainnet");
  const owner = await ownerSigner.getAddress();
  const token = new Contract(usdc, ["function nonces(address) view returns (uint256)"], provider);
  const permit = new Contract(permitAddress, permitAbi, provider);
  const amount = parseUnits(amountText, 6);
  const deadline = BigInt(Math.floor(Date.now() / 1000) + 300);
  const tokenDomain = { name: "SoDexToken: USDC", version: "1", chainId, verifyingContract: usdc };
  const tokenTypes = { Permit: [
    { name: "owner", type: "address" }, { name: "spender", type: "address" },
    { name: "value", type: "uint256" }, { name: "nonce", type: "uint256" },
    { name: "deadline", type: "uint256" }
  ] };
  const tokenSig = Signature.from(await ownerSigner.signTypedData(tokenDomain, tokenTypes, {
    owner, spender: permitAddress, value: amount, nonce: await token.nonces(owner), deadline
  }));

  const cmd = { token: usdc, amount, deadline, v: tokenSig.v, r: tokenSig.r, s: tokenSig.s };
  const fields = [
    { name: "token", type: "address" }, { name: "amount", type: "uint256" },
    { name: "deadline", type: "uint256" }, { name: "v", type: "uint8" },
    { name: "r", type: "bytes32" }, { name: "s", type: "bytes32" }
  ];
  const cmdData = AbiCoder.defaultAbiCoder().encode(
    fields.map(f => f.type), fields.map(f => cmd[f.name])
  );
  const nonce = await permit.nonces(owner, 2n);
  const domain = { name: "SoDexTokenCallForPermit", version: "1.0.0", chainId, verifyingContract: permitAddress };
  const types = { [cmdType]: fields, CallForPermit: [
    { name: "to", type: "address" }, { name: "cmd", type: cmdType },
    { name: "nonce", type: "uint256" }, { name: "deadline", type: "uint256" }
  ] };
  const message = { to: clob, cmd, nonce, deadline };
  const digest = await permit.hashCallForPermit(clob, cmdType, cmdData, nonce, deadline);
  if (TypedDataEncoder.hash(domain, types, message) !== digest) throw new Error("Permit digest mismatch");
  const signature = await ownerSigner.signTypedData(domain, types, message);
  return [clob, cmdType, cmdData, nonce.toString(), deadline.toString(), signature];
}
```

Submit the signed call through the Mainnet Relayer. Use an [integration ID approved for SoDexTokenCallForPermit](https://docs.sodex.com/for-developers/developers/valuechain-evm/relayer.md#register-an-integration-id). The Relayer broadcasts the transaction and pays the SOSO gas.

```javascript
const args = await signSpotDeposit(ownerSigner, "35.688167");
const calldata = new Interface(permitAbi).encodeFunctionData("execute", args);
const response = await fetch("https://mainnet-gw.sodex.dev/api/v1/relayer/tx", {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({
    integration_id: "YOUR_APPROVED_INTEGRATION_ID",
    target: permitAddress,
    calldata
  })
});
const body = await response.json();
if (!response.ok || body.status !== "1") {
  throw new Error(body.message || `Relayer submission failed (HTTP ${response.status})`);
}
const txHash = body.result?.tx_hash;
if (!txHash) throw new Error("Relayer returned no transaction hash");
console.log({ txHash });
```

Save `txHash` and poll [Relayer transaction status](https://docs.sodex.com/for-developers/api-reference/relayer-api/transaction-status.md). Follow any replacement hash. After successful execution, confirm the owner’s Spot balance as described in section 4.

### Native SOSO

Do not `approve`. `token` is `0x0000000000000000000000000000000000000000` and `msg.value` must equal `amount` (18 decimals). The wallet must hold `amount` plus gas in native SOSO. WSOSO cannot be used in this call.

Save as `trading-deposit-soso.mts` and run `npx tsx trading-deposit-soso.mts`. Set `PRIVATE_KEY`, `RAW_AMOUNT` in wei, and `DESTINATION` to `spot` or `perps`.

```typescript
import { createPublicClient, createWalletClient, defineChain, http, parseAbi, zeroAddress, type Hex } from "viem";
import { privateKeyToAccount } from "viem/accounts";

const valuechain = defineChain({
  id: 286623, name: "ValueChain",
  nativeCurrency: { name: "SOSO", symbol: "SOSO", decimals: 18 },
  rpcUrls: { default: { http: ["https://mainnet.valuechain.xyz"] } },
});
const account = privateKeyToAccount(process.env.PRIVATE_KEY as Hex);
const publicClient = createPublicClient({ chain: valuechain, transport: http() });
const walletClient = createWalletClient({ account, chain: valuechain, transport: http() });
const depositContract = "0x0101010101010101010101010101010101010101";
const amount = BigInt(process.env.RAW_AMOUNT!);
const destination = process.env.DESTINATION;
if (destination !== "spot" && destination !== "perps") throw new Error("Set DESTINATION to spot or perps");
const abi = parseAbi([
  "function depositERC20(address token, uint256 amount)",
  "function depositERC20(address token, uint256 amount, address recipient, uint256 destination)",
]);

const hash = destination === "spot"
  ? await walletClient.writeContract({
      address: depositContract, abi, functionName: "depositERC20",
      args: [zeroAddress, amount], value: amount,
    })
  : await walletClient.writeContract({
      address: depositContract, abi, functionName: "depositERC20",
      args: [zeroAddress, amount, account.address, 1n], value: amount,
    });
console.log({ transactionHash: hash });
const receipt = await publicClient.waitForTransactionReceipt({ hash });
if (receipt.status !== "success") throw new Error("Trading-account deposit reverted");
```

A receipt with a block is inclusion on ValueChain; do not apply extra confirmation depth. See [Transaction Finality](https://docs.sodex.com/for-developers/developers/valuechain-evm/transaction-finality.md). Receipt `success` is not a trading-account credit.

## 4. Confirm the trading balance

Query the destination [Spot](https://docs.sodex.com/for-developers/api-reference/trading-api/rest-v1/sodex-rest-spot-api.md) or [Perps](https://docs.sodex.com/for-developers/api-reference/trading-api/rest-v1/sodex-rest-perps-api.md) balance before trading. That requires a funded, activated trading account and the [Trading](https://docs.sodex.com/for-developers/developers/trading.md) API credentials. Do not treat the EVM receipt as the Spot or Perps balance.

See [Mirror Protocol Lifecycle](https://docs.sodex.com/for-developers/developers/mirror-protocol/lifecycle.md) for external deposit and withdrawal flows.
