# Withdraw from Wallets

> Move the SOL held by a launch's wallets to one address, from the quote to the settled payout, without sending twice.

This guide drains the SOL from every wallet of a launch into one address you control, as the launch page of the web
app does. The other sources (imported wallets, funders) use the same calls with a different `origin`; see step 2.

A withdrawal collects from each source wallet into an intermediate hop wallet, then pays the destination from the hop.
The destination sees one transfer, whatever the number of source wallets.

You need:

- an upgraded session token in `$PROXIMA_JWT` ([Quickstart](/getting-started/quickstart/));
- the launch id, here `101250846193377`;
- a destination address you control, here `GK25SCapKwYLZzvequPVpAMTnCvaViJvJiajETLPyX54`.

Amounts are integer strings in base units: lamports for SOL. See [Amounts](/getting-started/conventions/#amounts-and-large-integers).

## 1. Check the route

[List withdraw routes](/reference/withdrawals/#list-withdraw-routes) returns the source and destination pairs the API
can pay. A `classic` route keeps the chain and the asset. A `cex` route converts through an exchange and can change
both.

```bash
curl https://api-mig.proxima.tools/withdraw/routes \
  -H "Authorization: Bearer $PROXIMA_JWT"
```

```json
{
  "ok": true,
  "classic": [
    { "src_chain": "sol", "src_asset": "native", "dst_chain": "sol", "dst_asset": "native" }
  ],
  "cex": [
    { "src_chain": "sol", "src_asset": "native", "dst_chain": "bsc", "dst_asset": "native", "providers": ["binance", "kucoin"], "husher_only": false, "indicative_min_src_atomic": "71000000" }
  ]
}
```

**Keep:** the payout kind. SOL to SOL is `classic`.

## 2. Quote the withdrawal

[Retrieve a withdraw quote](/reference/withdrawals/#retrieve-a-withdraw-quote) takes the exact body you will execute
and moves nothing. Write the body to a file: you will send the same bytes in step 4.

```bash
cat > withdraw.json <<'EOF'
{
  "origin": { "kind": "launch", "launch_ext_id": "101250846193377" },
  "source": {
    "chain": "sol",
    "asset": "native",
    "select": { "kind": "launch_all" },
    "mode": "withdraw_all",
    "leave_on": [],
    "amount": "0"
  },
  "payout": {
    "kind": "classic",
    "chain": "sol",
    "asset": "native",
    "address": "GK25SCapKwYLZzvequPVpAMTnCvaViJvJiajETLPyX54"
  }
}
EOF

curl -X POST https://api-mig.proxima.tools/withdraw/quote \
  -H "Authorization: Bearer $PROXIMA_JWT" \
  -H "Content-Type: application/json" \
  -d @withdraw.json
```

`"amount": "0"` drains everything. Another value caps the total taken across the wallets.

```json
{
  "ok": true,
  "total_src_atomic": "2500000000",
  "wallets": [
    { "address": "8M4PPg4goA6dH3HTQs7kFtJwgvb3dRgNaMioaGdgGsxA", "drainable": "1412000000", "included": true },
    { "address": "6i6zd3qY5tT7d1LwhqNkQ7pNXzeaqMQP6WjpJ14273VP", "drainable": "655000000", "included": true },
    { "address": "9AaVX5b1d1q9ugSvjjG2vxbY8tMV6T8tWrDYpGAjYHU7", "drainable": "0", "included": false, "reason": "below_gas_and_leave", "needs": "1240000" },
    { "address": "AKSyicFZaZfLsoL45Jp6LcraGTDeNKQcqrhGFQHUYJf6", "drainable": "433000000", "included": true }
  ],
  "plan": { "hop_count": 1 },
  "estimated_duration_seconds": 20,
  "estimated_receive_atomic": "2499980000"
}
```

Check three things before going on:

- `destination_refused`, when present, says why the destination cannot be paid. Execute would refuse it too.
- Each wallet with `included: false` is skipped, and `reason` says why. `withdraw_in_flight` means another withdrawal
  is already draining that wallet. `needs` is how much SOL the wallet lacks to pay its own fee.
- `estimated_receive_atomic` is in the payout asset. It is absent when the API cannot price the route, which does
  not mean zero.

To withdraw from other wallets, change `origin` and `select` the way the app does:

| Source | `origin` | `source.select` |
| --- | --- | --- |
| A launch's wallets | `{ "kind": "launch", "launch_ext_id": "…" }` | `{ "kind": "launch_all" }`, or `explicit` |
| Imported wallets | `{ "kind": "aged" }` | `{ "kind": "explicit", "wallets": ["…"] }` |
| Funders | `{ "kind": "global" }` | `{ "kind": "explicit", "wallets": ["…"] }` |

**Keep:** the addresses with `included: true`.

## 3. Pin the wallets

When the quote reports wallets that cannot pay their fees (`needs`), the app replaces `select` with an explicit list
of the included wallets before executing.
Execute then acts on the wallets you reviewed, and not on whatever the selection resolves to a few seconds later.

```json
"select": {
  "kind": "explicit",
  "wallets": [
    "8M4PPg4goA6dH3HTQs7kFtJwgvb3dRgNaMioaGdgGsxA",
    "6i6zd3qY5tT7d1LwhqNkQ7pNXzeaqMQP6WjpJ14273VP",
    "AKSyicFZaZfLsoL45Jp6LcraGTDeNKQcqrhGFQHUYJf6"
  ]
}
```

Save the change in `withdraw.json`. From here on, do not edit the file.

**Keep:** `withdraw.json`, byte for byte.

## 4. Execute

[Execute a withdrawal](/reference/withdrawals/#execute-a-withdrawal) validates the body and creates the withdrawal.
It answers `202` while the transfers run in the background.

> **Danger:** This call moves funds, and a classic withdrawal cannot be cancelled once it is accepted. If the call times out or
> answers `5xx`, the withdrawal may already be running. Do not send it again before you read
> [Avoid sending twice](#avoid-sending-twice).

```bash
curl -X POST https://api-mig.proxima.tools/withdraw/execute \
  -H "Authorization: Bearer $PROXIMA_JWT" \
  -H "Content-Type: application/json" \
  -d @withdraw.json
```

```json
{ "ok": true, "id": "44fe5946-76d4-460b-8e6b-db90af5ee652", "group_id": "44fe5946-76d4-460b-8e6b-db90af5ee652" }
```

**Keep:** `id` and `group_id`.

### When a second factor is required

If the account protects `wallet.withdraw`, the first call answers `401` with `code: "2fa_required"` and moves
nothing. The check is skipped when every destination is one of your registered [funders](/reference/funders/) on
the payout chain.

```json
{
  "ok": false,
  "code": "2fa_required",
  "message": "2fa challenge required",
  "twoFaAlgoId": "a98dee99-b8f2-4bd9-9b87-88b5b6c64f1a",
  "method": "totp",
  "label": "wallet.withdraw"
}
```

Send the same file again with the answer in headers. The challenge is bound to a hash of the body, expires after
five minutes and works once. See [Two-factor step-up](/getting-started/two-factor-step-up/) for wallet signatures and
backup codes.

```bash
curl -X POST https://api-mig.proxima.tools/withdraw/execute \
  -H "Authorization: Bearer $PROXIMA_JWT" \
  -H "Content-Type: application/json" \
  -H "X-2FA-Algo-Id: a98dee99-b8f2-4bd9-9b87-88b5b6c64f1a" \
  -H "X-2FA-Response: 482913" \
  -d @withdraw.json
```

## 5. Find every row

One execute can create several withdrawal rows that share a `group_id`. This happens with one row per destination
when `source.transfers` names several recipients, or one row per wallet with a `cex` payout and `per_wallet_orders`.

- If `id` equals `group_id`, there is one row, and its id is `id`.
- Otherwise, call [List withdrawals](/reference/withdrawals/#list-withdrawals) and keep the rows whose `group_id`
  matches.

```bash
curl "https://api-mig.proxima.tools/withdraw?launch_ext_id=101250846193377&limit=200" \
  -H "Authorization: Bearer $PROXIMA_JWT"
```

**Keep:** the id of each row.

## 6. Follow each row until it is terminal

Poll [Retrieve a withdrawal](/reference/withdrawals/#retrieve-a-withdrawal) every second until `status` is
`completed`, `failed` or `cancelled`. A classic withdrawal goes `collecting`, `hop_funded`, then `completed`. A cex
withdrawal adds `paying` and `settling`.

**cURL**

```bash
curl https://api-mig.proxima.tools/withdraw/44fe5946-76d4-460b-8e6b-db90af5ee652 \
  -H "Authorization: Bearer $PROXIMA_JWT"
```
**JavaScript**

```js
const API = "https://api-mig.proxima.tools";
const headers = { Authorization: `Bearer ${process.env.PROXIMA_JWT}` };
const TERMINAL = new Set(["completed", "failed", "cancelled"]);

async function waitForWithdrawal(id, timeoutMs = 180_000) {
  const deadline = Date.now() + timeoutMs;
  while (Date.now() < deadline) {
    const res = await fetch(`${API}/withdraw/${id}`, { headers });
    if (res.ok) {
      const row = await res.json();
      if (TERMINAL.has(row.status)) return row;
    }
    await new Promise((resolve) => setTimeout(resolve, 1000));
  }
  return undefined; // still running: keep checking later, do not execute again
}
```
While it runs:

```json
{
  "id": "44fe5946-76d4-460b-8e6b-db90af5ee652",
  "group_id": "44fe5946-76d4-460b-8e6b-db90af5ee652",
  "status": "collecting",
  "origin": { "kind": "launch", "launch_ext_id": "101250846193377" },
  "src": { "chain": "sol", "asset": "native" },
  "dst": { "chain": "sol", "asset": "native", "address": "GK25SCapKwYLZzvequPVpAMTnCvaViJvJiajETLPyX54" },
  "payout_kind": "classic",
  "collected": [
    { "address": "8M4PPg4goA6dH3HTQs7kFtJwgvb3dRgNaMioaGdgGsxA", "amount": "1412000000", "tx": "3jHysd8FQDH96nh4rwTa5mvNc4iJqpnbfwX5JprNfMu11knLZsjEBEak89SaiSBPByMUmmSdjfeDW9em6o23qrUP" }
  ],
  "awaiting": [
    { "address": "6i6zd3qY5tT7d1LwhqNkQ7pNXzeaqMQP6WjpJ14273VP", "tx": "4Es8NYqYh6RMxBu4QoqdWBH9qBAYi728uPUJPdHGeE2DLm1EDb7vpYsUAzgDgkrFk6gcmAeSLLtYR3ZPVEH13iGX" }
  ],
  "hop": { "address": "4xzNFidgfTahziM2qyvmswto5ABZ4PXyYzFPhuErarVx" },
  "payout": {},
  "created_at": 1793671200,
  "started_at": 1793671201
}
```

Once it is done:

```json
{
  "id": "44fe5946-76d4-460b-8e6b-db90af5ee652",
  "status": "completed",
  "collected": [ "… three entries …" ],
  "hop": { "address": "4xzNFidgfTahziM2qyvmswto5ABZ4PXyYzFPhuErarVx", "landed": "2500000000" },
  "payout": { "tx": "655UrHeo364qmaCcVmKmvLjF4CbwuQSPWVg1ZrkCiG9UKy1ZUh6oTwoLTqCWgSBUEk4num8fFEzzpQYMHatRKfKv" },
  "finished_at": 1793671219
}
```

| Field | Meaning |
| --- | --- |
| `collected` | Legs confirmed into the hop, with the amount and transaction of each. |
| `awaiting` | Legs sent but not yet confirmed. They are on the wire: wait for them. |
| `hop.landed` | What reached the hop. |
| `payout.tx` | The transaction that paid the destination. |
| `error` | Why a `failed` row stopped. |
| `repatriation` | On a failed row, the transfer that sent the hop's balance back (`tx`, `to`, `amount`). |

**Keep:** `payout.tx` as the proof of payment.

## Avoid sending twice

Execute has no idempotency key. These rules come from how the API and the web app behave.

- **One request at a time.** Block a second submit while the first call is pending. The app does this on its
  confirm button.
- **Wallets already in flight are locked.** While a withdrawal is running, its wallets are excluded from any new
  withdrawal on the same chain. A quote shows them with `reason: "withdraw_in_flight"`. An execute that only names
  such wallets answers `422` with `already withdrawing from <addresses>` or `no source wallet eligible for withdrawal`.
- **The lock ends with the row.** Once the first withdrawal is terminal, the same body runs again on what is left.
  With `"amount": "0"`, that is usually dust or new deposits. With a fixed `amount`, it moves that amount a
  second time.
- **After a timeout or a `5xx`, look before you resend.** List recent rows and look for one with the same
  destination created in the last few minutes. If you find it, follow it (step 6). If not, quote again: a wallet
  marked `withdraw_in_flight` means the first call went through.

```bash
curl "https://api-mig.proxima.tools/withdraw?launch_ext_id=101250846193377&limit=20" \
  -H "Authorization: Bearer $PROXIMA_JWT"
```

> **Warning:** A row that stays in a non-terminal status is still running on the server. The app stops waiting after three
> minutes, and so does the example above, but the withdrawal goes on. [Cancel a withdrawal](/reference/withdrawals/#cancel-a-withdrawal)
> only works on `draft` rows. A classic row starts in `collecting`, so cancelling it answers `409`.

## Next steps

- [Withdrawals reference](/reference/withdrawals/): cex payouts, partial amounts, dust and `leave_on`, manual
  `transfers`.
- [Two-factor step-up](/getting-started/two-factor-step-up/): answering challenges with a wallet signature or a
  backup code.
- [Follow a launch in real time](/guides/follow-a-launch/): balances update over the WebSocket once the transfers
  confirm.
- [Errors](/getting-started/errors/#retry-strategy): which failures are safe to retry.
