302 lines
9.1 KiB
Plaintext
302 lines
9.1 KiB
Plaintext
# Users
|
|
|
|
## How it works
|
|
|
|
A **user account** is the onchain account that holds your positions, orders, and collateral on Drift. Each wallet can create multiple user accounts (called **subaccounts**), identified by a numeric ID (0, 1, 2, etc.). All subaccounts under the same wallet share cross-margin, meaning collateral and risk are calculated across all of them together.
|
|
|
|
User accounts store your perp positions (long/short), spot balances (deposits/borrows), open orders, and leverage settings. When you interact with Drift (place orders, deposit, trade), you're modifying data in your user account. The account is a Solana PDA (Program Derived Address) owned by the Drift program.
|
|
|
|
Subaccounts are useful for separating strategies, isolating risk between different trading styles, or delegating specific accounts to bots while keeping others manual. You can switch between subaccounts using the SDK, and each one maintains its own positions and orders while sharing the wallet's overall collateral pool.
|
|
|
|
## SDK Usage
|
|
|
|
Most write actions in Drift are done through `DriftClient`. For account-level reads (positions, orders, health), you'll typically use a `User`.
|
|
|
|
### Initialize a User Account
|
|
|
|
Create a new Drift user subaccount (PDA) for your wallet and return the transaction signature + user account address.
|
|
|
|
<SDKDoc>
|
|
<TypeScript name="initializeUserAccount" type="method" owner="DriftClient">
|
|
```js
|
|
// Assumes you already constructed and subscribed `driftClient`.
|
|
const [txSig, userAccountPublicKey] = await driftClient.initializeUserAccount(0, "my-account");
|
|
console.log(txSig, userAccountPublicKey.toBase58());
|
|
```
|
|
</TypeScript>
|
|
</SDKDoc>
|
|
|
|
#### Get the Next Subaccount ID
|
|
|
|
Return the next available subaccount ID for this client instance.
|
|
|
|
<SDKDoc>
|
|
<TypeScript name="getNextSubAccountId" type="method" owner="DriftClient">
|
|
```js
|
|
const nextId = driftClient.getNextSubAccountId();
|
|
console.log(nextId);
|
|
```
|
|
</TypeScript>
|
|
</SDKDoc>
|
|
|
|
### Get a User and Subscribe
|
|
|
|
Import the `User` class and subscribe to account updates for a specific user instance.
|
|
|
|
<SDKDoc>
|
|
<TypeScript name="User" type="class">
|
|
```js
|
|
import { User } from "@drift-labs/sdk";
|
|
|
|
const user = driftClient.getUser();
|
|
await user.subscribe();
|
|
```
|
|
</TypeScript>
|
|
</SDKDoc>
|
|
|
|
#### Get active subaccount user
|
|
|
|
Get the `User` object for the currently active subaccount.
|
|
|
|
<SDKDoc>
|
|
<TypeScript name="getUser" type="method" owner="DriftClient">
|
|
```js
|
|
const user = driftClient.getUser();
|
|
```
|
|
</TypeScript>
|
|
</SDKDoc>
|
|
|
|
#### Get a specific subaccount user
|
|
|
|
Get the `User` object for a specific subaccount ID.
|
|
|
|
<SDKDoc>
|
|
<TypeScript name="getUser" type="method" owner="DriftClient">
|
|
```js
|
|
const user = driftClient.getUser(1);
|
|
```
|
|
</TypeScript>
|
|
</SDKDoc>
|
|
|
|
#### Read account via `User`
|
|
|
|
Read raw onchain `UserAccount` data from a `User` instance.
|
|
|
|
<SDKDoc>
|
|
<TypeScript name="getUserAccount" type="method" owner="User">
|
|
```js
|
|
const account = driftClient.getUser().getUserAccount();
|
|
console.log(account);
|
|
```
|
|
</TypeScript>
|
|
</SDKDoc>
|
|
|
|
#### Read account via `DriftClient`
|
|
|
|
Read raw onchain `UserAccount` data directly from `DriftClient` for the active subaccount.
|
|
|
|
<SDKDoc>
|
|
<TypeScript name="getUserAccount" type="method" owner="DriftClient">
|
|
```js
|
|
const account = driftClient.getUserAccount();
|
|
console.log(account);
|
|
```
|
|
</TypeScript>
|
|
</SDKDoc>
|
|
|
|
#### Refresh user accounts
|
|
|
|
Force-refresh subscribed user-related accounts from RPC.
|
|
|
|
<SDKDoc>
|
|
<TypeScript name="fetchAccounts" type="method" owner="User">
|
|
```js
|
|
const user = driftClient.getUser(0);
|
|
await user.fetchAccounts();
|
|
```
|
|
</TypeScript>
|
|
</SDKDoc>
|
|
|
|
### Derived Addresses (User Account)
|
|
|
|
User accounts are **Program Derived Addresses (PDAs)** - deterministic addresses generated from seeds (the program ID, wallet authority, and subaccount ID). PDAs are a Solana concept that lets you calculate an account's address without making an RPC call.
|
|
|
|
This is useful when you need to reference a user account address before fetching it, such as when constructing transactions or querying multiple accounts in parallel.
|
|
|
|
For a deeper understanding of PDAs and program structure, see [Program Structure](/developers/concepts/program-structure).
|
|
|
|
Derive the user account PDA for a given subaccount without an RPC fetch.
|
|
|
|
<SDKDoc>
|
|
<TypeScript name="getUserAccountPublicKey" type="method" owner="DriftClient">
|
|
```js
|
|
const userAccountPublicKey = await driftClient.getUserAccountPublicKey(0);
|
|
console.log(userAccountPublicKey.toBase58());
|
|
```
|
|
</TypeScript>
|
|
</SDKDoc>
|
|
|
|
### Query User State (Orders / Positions)
|
|
|
|
#### Get token amount (deposit vs borrow)
|
|
|
|
Return your token balance for a spot market as a signed value (`+` deposit, `-` borrow).
|
|
|
|
<SDKDoc>
|
|
<TypeScript name="getTokenAmount" type="method" owner="User">
|
|
```js
|
|
import { BN } from "@drift-labs/sdk";
|
|
|
|
const user = driftClient.getUser();
|
|
const tokenAmount = user.getTokenAmount(0);
|
|
|
|
const isDeposit = tokenAmount.gte(new BN(0));
|
|
const isBorrow = tokenAmount.lt(new BN(0));
|
|
console.log({ tokenAmount: tokenAmount.toString(), isDeposit, isBorrow });
|
|
```
|
|
</TypeScript>
|
|
</SDKDoc>
|
|
|
|
#### Get a perp position
|
|
|
|
Get your perp position record for a market index (or `undefined` if no position exists).
|
|
|
|
<SDKDoc>
|
|
<TypeScript name="getPerpPosition" type="method" owner="User">
|
|
```js
|
|
const position = driftClient.getUser().getPerpPosition(0);
|
|
console.log(position?.baseAssetAmount.toString());
|
|
```
|
|
</TypeScript>
|
|
</SDKDoc>
|
|
|
|
#### Get an order by order id
|
|
|
|
Look up a specific order using its internal Drift `orderId`.
|
|
|
|
<SDKDoc>
|
|
<TypeScript name="getOrder" type="method" owner="User">
|
|
```js
|
|
const order = driftClient.getUser().getOrder(1);
|
|
console.log(order);
|
|
```
|
|
</TypeScript>
|
|
</SDKDoc>
|
|
|
|
#### Get an order by user order id
|
|
|
|
Look up a specific order using your custom `userOrderId`.
|
|
|
|
<SDKDoc>
|
|
<TypeScript name="getOrderByUserOrderId" type="method" owner="User">
|
|
```js
|
|
const order = driftClient.getUser().getOrderByUserOrderId(1);
|
|
console.log(order);
|
|
```
|
|
</TypeScript>
|
|
</SDKDoc>
|
|
|
|
#### Get all open orders
|
|
|
|
Return all currently open (unfilled/uncancelled) orders for this user.
|
|
|
|
<SDKDoc>
|
|
<TypeScript name="getOpenOrders" type="method" owner="User">
|
|
```js
|
|
const orders = driftClient.getUser().getOpenOrders();
|
|
console.log(orders.length);
|
|
```
|
|
</TypeScript>
|
|
</SDKDoc>
|
|
|
|
### Active Subaccount
|
|
|
|
The **active subaccount** is the default subaccount that DriftClient methods operate on when you don't explicitly specify a subaccount ID. By default, the active subaccount is 0.
|
|
|
|
Many SDK methods use the active subaccount implicitly:
|
|
- `driftClient.getUser()` - returns the User for the active subaccount
|
|
- `driftClient.getUserAccount()` - returns the account data for the active subaccount
|
|
- `driftClient.placePerpOrder(orderParams)` - places an order on the active subaccount
|
|
- `driftClient.getSpotPosition(marketIndex)` - gets position from the active subaccount
|
|
- `driftClient.getPerpPosition(marketIndex)` - gets position from the active subaccount
|
|
|
|
You can change which subaccount is active using `switchActiveUser()`, or you can explicitly pass a subaccount ID to methods that support it (like `getUser(subAccountId)`).
|
|
|
|
### Switch Active Subaccount
|
|
|
|
Change the active subaccount context used by default in `DriftClient` methods.
|
|
|
|
<SDKDoc>
|
|
<TypeScript name="switchActiveUser" type="method" owner="DriftClient">
|
|
```js
|
|
// Switch to subaccount 1.
|
|
await driftClient.switchActiveUser(1);
|
|
```
|
|
</TypeScript>
|
|
</SDKDoc>
|
|
|
|
### Update Delegate
|
|
|
|
A **delegate** is another wallet that can trade on behalf of your user account without being able to withdraw funds. This is useful for allowing trading bots to manage positions while keeping withdrawal authority secure.
|
|
|
|
Learn more: [Delegated Accounts](/protocol/getting-started/delegated-accounts)
|
|
|
|
Set or update the delegate authority allowed to trade on a subaccount.
|
|
|
|
<SDKDoc>
|
|
<TypeScript name="updateUserDelegate" type="method" owner="DriftClient">
|
|
```js
|
|
import { PublicKey } from "@solana/web3.js";
|
|
|
|
await driftClient.updateUserDelegate(new PublicKey("<DELEGATE_PUBKEY>"), 0);
|
|
```
|
|
</TypeScript>
|
|
</SDKDoc>
|
|
|
|
### Update Margin Settings
|
|
|
|
**Margin trading** settings control how your account can use leverage and borrow against collateral. You can enable/disable margin trading or set custom margin ratios to control risk.
|
|
|
|
Learn more: [Margin](/protocol/trading/margin)
|
|
|
|
Enable or disable margin trading permissions for one or more subaccounts.
|
|
|
|
<SDKDoc>
|
|
<TypeScript name="updateUserMarginTradingEnabled" type="method" owner="DriftClient">
|
|
```js
|
|
await driftClient.updateUserMarginTradingEnabled([
|
|
{ marginTradingEnabled: true, subAccountId: 0 },
|
|
]);
|
|
```
|
|
</TypeScript>
|
|
</SDKDoc>
|
|
|
|
Set a custom margin ratio cap for one or more subaccounts.
|
|
|
|
<SDKDoc>
|
|
<TypeScript name="updateUserCustomMarginRatio" type="method" owner="DriftClient">
|
|
```js
|
|
// marginRatio is a number scaled by 10000 (MARGIN_PRECISION)
|
|
// e.g. 10000 = 1x max leverage, 5000 = 2x, 2000 = 5x
|
|
await driftClient.updateUserCustomMarginRatio([
|
|
{ marginRatio: 5000, subAccountId: 0 }, // 2x max leverage
|
|
]);
|
|
```
|
|
</TypeScript>
|
|
</SDKDoc>
|
|
|
|
### Delete a User Account
|
|
|
|
If a subaccount has no assets/liabilities, it can be deleted to reclaim rent.
|
|
|
|
Delete an empty subaccount and close its user account.
|
|
|
|
<SDKDoc>
|
|
<TypeScript name="deleteUser" type="method" owner="DriftClient">
|
|
```js
|
|
await driftClient.deleteUser(1);
|
|
```
|
|
</TypeScript>
|
|
</SDKDoc>
|
|
|