> 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/rfq.md).

# RFQ Subscribe and Redeem

During the RFQ session, buy vault shares with USDC or sell vault shares for USDC at a maker quote. The session comes from [trading status](https://docs.sodex.com/for-developers/api-reference/wealth-api/trading.md#trading-status). When `channel` is `batch`, use [Vault Lifecycle](https://docs.sodex.com/for-developers/developers/wealth/vault-lifecycle.md) instead.

A buy escrows USDC and later delivers vault shares. A sell escrows vault shares and later delivers USDC. The quote is filled by calling `buy` or `sell` on TigrisRFQ before it expires. Settlement is a later claim. A successful `buy` or `sell` does not transfer the quoted proceeds in that transaction.

**Mainnet base URL:** `https://mainnet-gw.sodex.dev/api/v1/wealth`

Field definitions and rejection codes are on [Trading](https://docs.sodex.com/for-developers/api-reference/wealth-api/trading.md#rfq-quote).

## 1. Confirm the session

```bash
curl -sS "https://mainnet-gw.sodex.dev/api/v1/wealth/funds/CXMT/trading-status" \
  -H "Accept: application/json"
```

Submit only when `data.channel` is `rfq` and `data.rfq.quotable` is true. `data.rfq.address` is the TigrisRFQ contract for this call. `minBuyAmount` and `minSellAmount` are the raw-unit minimums. `expectedDeliveryAt` is the expected delivery time for orders submitted in this session.

`data.vault` is the vault. The USDC for a buy must already be on ValueChain. If it is still on another network, move it with [Mirror Protocol](https://docs.sodex.com/for-developers/developers/mirror-protocol.md) first. The owner wallet pays SOSO gas.

## 2. Request a quote

`side` is `buy` or `sell`. `owner` is the wallet that will call `buy` or `sell`. `payAmount` is a positive base-10 integer in raw chain units: USDC for a buy, vault shares for a sell.

```bash
curl -sS "https://mainnet-gw.sodex.dev/api/v1/wealth/funds/CXMT/rfq/quote" \
  -H "Accept: application/json" \
  -H "Content-Type: application/json" \
  -d '{"side":"buy","owner":"0x1111111111111111111111111111111111111111","payAmount":"1000000"}'
```

`code` `-1` is a gateway error. `code` `0` with `data.quotable` false is a desk rejection. Read `data.reason.code` and request another quote. `detail` is the maker's original phrase.

A quotable response includes `vault`, `payAmount`, `receiveAmount`, `nonce`, `deadline`, `signature`, and `orderHash`. Submit those values unchanged. `deadline` is a Unix timestamp in seconds. `expiresInMs` is the remaining lifetime in milliseconds. `expiresInMs` `0` means the quote just expired.

The signature binds this `nonce`. Submit it before requesting another quote for the same owner. The contract consumes that nonce inside `buy` or `sell`. Nonce `0` is the wallet's first quote.

## 3. Submit the order

Approve the token the order escrows, then call TigrisRFQ from the owner wallet. `msg.sender` must be `owner`. A buy approves the vault underlying (`getAsset()`) for `payAmount`. A sell approves the vault share token for `payAmount`. The spender is `data.rfq.address`.

```solidity
function buy(address vault, uint256 payAmount, uint256 receiveAmount, uint256 deadline, bytes quoteSignature) external;
function sell(address vault, uint256 payAmount, uint256 receiveAmount, uint256 deadline, bytes quoteSignature) external;
```

The five-argument calls attach no builder fee. The six-argument form adds `builderFeeData`. Encoding is in [Builder Integration](https://docs.sodex.com/for-developers/developers/wealth/builder.md).

Install `viem` and `tsx`. Set `PRIVATE_KEY`, `FUND_ID`, `SIDE` (`buy` or `sell`), and `PAY_AMOUNT`. Save as `rfq-order.mts` and run `npx tsx rfq-order.mts`.

```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 fundId = process.env.FUND_ID ?? "CXMT";
const side = process.env.SIDE ?? "buy";
const payAmount = process.env.PAY_AMOUNT!;
const base = "https://mainnet-gw.sodex.dev/api/v1/wealth";

const statusBody = await fetch(`${base}/funds/${fundId}/trading-status`, {
  headers: { Accept: "application/json" },
}).then((res) => res.json());
if (statusBody.code !== 0) throw new Error(statusBody.error);
const trading = statusBody.data;
if (trading.channel !== "rfq" || trading.rfq?.quotable !== true) {
  throw new Error(`RFQ session is not open: ${trading.channel}`);
}

const quoteBody = await fetch(`${base}/funds/${fundId}/rfq/quote`, {
  method: "POST",
  headers: { Accept: "application/json", "Content-Type": "application/json" },
  body: JSON.stringify({ side, owner: account.address, payAmount }),
}).then((res) => res.json());
if (quoteBody.code !== 0) throw new Error(quoteBody.error);
const quote = quoteBody.data;
if (!quote.quotable) throw new Error(`Quote rejected: ${quote.reason?.code}`);

const rfq = trading.rfq.address as Address;
const vault = quote.vault as Address;
const erc20Abi = parseAbi([
  "function approve(address spender, uint256 amount) returns (bool)",
  "function allowance(address owner, address spender) view returns (uint256)",
]);
const vaultAbi = parseAbi(["function getAsset() view returns (address)"]);
const rfqAbi = parseAbi([
  "function buy(address vault, uint256 payAmount, uint256 receiveAmount, uint256 deadline, bytes quoteSignature)",
  "function sell(address vault, uint256 payAmount, uint256 receiveAmount, uint256 deadline, bytes quoteSignature)",
  "function getBuyOrderIdByHash(address vault, bytes32 orderHash) view returns (uint256)",
  "function getSellOrderIdByHash(address vault, bytes32 orderHash) view returns (uint256)",
]);

const asset = await publicClient.readContract({
  address: vault, abi: vaultAbi, functionName: "getAsset",
});
const spendToken = side === "buy" ? asset : vault;
const amount = BigInt(quote.payAmount);
const allowance = await publicClient.readContract({
  address: spendToken, abi: erc20Abi, functionName: "allowance", args: [account.address, rfq],
});
if (allowance < amount) {
  const approveHash = await walletClient.writeContract({
    address: spendToken, abi: erc20Abi, functionName: "approve", args: [rfq, amount],
  });
  const approveReceipt = await publicClient.waitForTransactionReceipt({ hash: approveHash });
  if (approveReceipt.status !== "success") throw new Error("Approval reverted");
}

const hash = await walletClient.writeContract({
  address: rfq,
  abi: rfqAbi,
  functionName: side === "buy" ? "buy" : "sell",
  args: [vault, amount, BigInt(quote.receiveAmount), BigInt(quote.deadline), quote.signature as Hex],
});
const receipt = await publicClient.waitForTransactionReceipt({ hash });
if (receipt.status !== "success") throw new Error(`${side} reverted`);

const orderId = await publicClient.readContract({
  address: rfq,
  abi: rfqAbi,
  functionName: side === "buy" ? "getBuyOrderIdByHash" : "getSellOrderIdByHash",
  args: [vault, quote.orderHash as Hex],
});
console.log({ txHash: hash, orderId: orderId.toString() });
```

Save `txHash` and `orderId`. `BuySubmitted` or `SellSubmitted` on the receipt carries the same `orderId`. The indexed topics are `vault`, `owner`, and `orderId`.

After the receipt, the escrow is on TigrisRFQ and the order is `PENDING`. The owner cannot cancel it. `deadline` expires the quote. It does not expire an order that was already accepted.

`buyOnBehalf` and `sellOnBehalf` pull the escrow with an ERC-2612 permit and require `RELAYER_ROLE` on `msg.sender`. The permit spender is TigrisRFQ. A permit that fails is ignored when the allowance is already in place. The owner wallet calls `buy` or `sell` directly.

## 4. Claim the result

The operator records one fill. A full fill pays `receiveAmount`. A partial fill pays `receiveAmount * filledPayAmount / payAmount`. A rejection leaves the fill at zero. The settler then marks a filled order `SETTLED`. A rejected order can be claimed while it is still `REJECTED`.

| Status                                                     | Claim                                                                    |
| ---------------------------------------------------------- | ------------------------------------------------------------------------ |
| `PENDING`, `PARTIALLY_FILLED`, `FILLED`                    | Wait.                                                                    |
| `SETTLED` or `REJECTED`, and `claimed` is false            | `claimBuy(vault, orderId)` or `claimSell(vault, orderId)`.               |
| `delayedStatus` is `SETTLED` and `delayedClaimed` is false | `claimDelayedBuy(vault, orderId)` or `claimDelayedSell(vault, orderId)`. |

The immediate claim pays the filled amount minus any delayed portion, and refunds the unfilled escrow. Tokens are sent to the order owner. A delayed portion stays on the order until `claimDelayedBuy` or `claimDelayedSell`. A sell claim deducts a builder fee when one was stored. A buy claim does not. See [Builder Integration](https://docs.sodex.com/for-developers/developers/wealth/builder.md).

Read the order with `getBuyOrder(vault, orderId)` or `getSellOrder(vault, orderId)`.

```solidity
function claimBuy(address vault, uint256 orderId) external;
function claimSell(address vault, uint256 orderId) external;
function claimDelayedBuy(address vault, uint256 orderId) external;
function claimDelayedSell(address vault, uint256 orderId) external;
```

The same order appears in [User Fund History](https://docs.sodex.com/for-developers/api-reference/wealth-api/user-fund-history.md) with `channel` `rfq`. Match `txHash` to the submit transaction. `claimable` on that entry is the immediate leg. `delayedPending` means the delayed leg is still outstanding. Those flags are independent. An omitted flag means that aspect is unknown.

{% content-ref url="/pages/L63DkYfJHl0ox6fA6QPm" %}
[Trading](https://docs.sodex.com/for-developers/api-reference/wealth-api/trading.md)
{% endcontent-ref %}

{% content-ref url="/pages/a1uIUuv4ujFrQ0lk4JjC" %}
[Escrow Vault Lifecycle](https://docs.sodex.com/for-developers/developers/wealth/vault-lifecycle.md)
{% endcontent-ref %}
