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

# Close a Position

> Close a basket position — one call on a managed wallet, or client-signed transactions (BYOW).

Closing sells the wallet's **full holding** of a basket's tokens back to USDC. It is
balance-driven — whatever of the basket the wallet holds gets closed, exactly what
[`positions.getHoldings`](https://docs.cesto.co/sdk/positions#position-by-product-sdk-positions) reports. There
is no `amount` and no partial close. Both models share this semantics; they differ only in
who signs.

> [tab] Managed (recommended)
>
> For Cesto-managed wallets (provisioned via [`users.create`](https://docs.cesto.co/sdk/managed-wallets)),
> Cesto signs server-side — one call, then poll:
>
> ```ts theme={null}
> import { Cesto } from '@cesto/sdk';
>
> const cesto = new Cesto({ apiKey: process.env.CESTO_API_KEY }); // write-scoped key, server-side only
>
> const result = await cesto.close.startAndWait({
>   user: user.solanaAddress, // or the externalUserId / EVM wallet you provisioned with
>   product: 'stable-genius',
> });
> result.status;       // 'COMPLETED' | 'PARTIALLY_COMPLETED' | 'FAILED'
> result.transactions; // per-leg { nodeId, ok, signature?, error? }
> ```
>
> A `PARTIALLY_COMPLETED` close means some legs sold and some didn't; a fresh
> `close.start` targets exactly what's left. To get the USDC back to the user's EVM
> wallet afterwards, see [Managed Wallets → Withdrawing](https://docs.cesto.co/sdk/managed-wallets.md#withdrawing).

> [tab] BYOW (client-signed)
>
> Closing follows the same client-signed **prepare → sign → submit → poll** flow as
> [opening](https://docs.cesto.co/sdk/open-position.md), with two differences:
>
> * **No `amount`** — close always sells the wallet's full holding (see above).
>
> * The prepare call is `close.prepare` / the one-call helper is `close.execute`.
>
> > [!WARNING]
> >
> > Like opening, closing requires a **write-scoped** API key. Cesto **sponsors the gas
> > and ATA rent**, so the wallet needs **no SOL**.
>
> ## One-call flow (you hold the keypair)
>
> ```ts theme={null}
> import { signWithKeypair } from '@cesto/sdk';
>
> const result = await cesto.close.execute({
>   wallet,
>   product: 'stable-genius',
>   signTransactions: signWithKeypair(keypair), // same helper as open — signs each leg locally
> });
> result.status;       // 'COMPLETED' | 'PARTIALLY_COMPLETED' | 'FAILED'
> result.transactions; // per-leg { nodeId, ok, signature?, error? }
> ```
>
> See [Open a Position](https://docs.cesto.co/sdk/open-position.md) for the
> full `signWithKeypair` setup (and how to supply your own `signTransactions` callback
> instead). The keypair stays server-side, loaded from the environment — never hardcoded,
> never shipped to a client.
>
> ## Split flow (browser wallet signs)
>
> **1. Backend: prepare**
>
> ```ts theme={null}
> const prepared = await cesto.close.prepare({
>   wallet: userWalletAddress,
>   product: 'stable-genius',
> });
> // { executionId, transactions: [{ nodeId, transaction }], expiresAt }
> ```
>
> Send `prepared.transactions` to the browser immediately — the set expires **\~60
> seconds** after prepare.
>
> **2. Browser: the user signs**
>
> Sign the transactions **as-is** — any modified byte is rejected at submit. Same
> signing code as the [open flow](https://docs.cesto.co/sdk/open-position.md).
>
> **3. Backend: submit and wait**
>
> ```ts theme={null}
> await cesto.positions.submit({
>   executionId: prepared.executionId,
>   transactions: signed,
> });
>
> const result = await cesto.positions.waitForExecution(prepared.executionId);
> ```
>
> ## Method reference
>
> ### `close.prepare(params)`
>
> **wallet** `string` *required*
>
> Solana address of the wallet closing the position.
>
> **product** `string` *required*
>
> Basket to close — product id or slug.
>
> Returns `{ executionId, transactions, expiresAt }`.
>
> `positions.submit`, `getExecution`, and `waitForExecution` are shared with the open
> flow — see the [method reference](https://docs.cesto.co/sdk/open-position.md) there.

> [!WARNING]
>
> **Examples on this page move real mainnet funds.** Closing sells real holdings on Solana
> mainnet — test with small amounts first.

## Existing Cesto users

When the wallet belongs to a **Cesto account holder**, the user approves once by signing a
message and Cesto closes the position with their Cesto wallet — no per-transaction signing.
Same `close.start` as the managed flow, plus a `consent` field:

```ts theme={null}
const { exists, delegatedSigning } = await cesto.users.lookup({ wallet });
// delegatedSigning: true → Cesto can sign for this user

const challenge = await cesto.close.createChallenge({
  wallet: userWalletAddress,
  product: 'stable-genius',
});

const signature = await wallet.signMessage(challenge.message); // base58

const { executionId } = await cesto.close.start({
  user: userWalletAddress,
  product: challenge.productId,
  consent: { challengeToken: challenge.challengeToken, signature },
});

// hasPosition flips false once the close completes
const holdings = await cesto.positions.getHoldings({
  wallet: userWalletAddress,
  product: challenge.productId,
});
```

Identical to the [open version](https://docs.cesto.co/sdk/open-position.md#existing-cesto-users) minus the `amount`:
the approval binds this wallet and this basket, and `start` resolves as soon as the job is
**queued**. It is **never retried automatically** — the approval is single-use.

> [!WARNING]
>
> As on the open path, `positions.getExecution` / `waitForExecution` cannot see executions
> started with `consent` — they are scoped to the issuing API key, and these are recorded
> against the user. Track the outcome with
> [`getHoldings`](https://docs.cesto.co/sdk/positions#position-by-product-sdk-positions) instead.

External wallets that have never used Cesto return `delegatedSigning: false` and take the
BYOW flow above. See [Users](https://docs.cesto.co/sdk/users.md).

## Results, errors, and security

Terminal statuses (`COMPLETED`, `PARTIALLY_COMPLETED`, `FAILED`), partial-completion
semantics, the common-error table, and the security model are identical to opening — see
[Open a Position](https://docs.cesto.co/sdk/open-position.md#execution-results). Two close-specific notes:

* A wallet with **no holdings** of the basket has nothing to sell — check
  `positions.getHoldings(...).hasPosition` before preparing a close.
* A `PARTIALLY_COMPLETED` close means some legs sold and some didn't; the remaining
  holdings are still in the wallet and a fresh close (`close.start` or `close.prepare`)
  will target exactly what's left.

## Rebalancing

To move a position to the basket's latest version instead of closing it, see
[Rebalance a Position](https://docs.cesto.co/sdk/rebalance-position.md).


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