@solsdk/keystone_sdk
Version:
SDK for Keystone Protocol
218 lines (166 loc) • 5.83 kB
Markdown
<div align="center">
<h1 style="margin-top:20px;">@solsdk/keystone_sdk</h1>
<p>
<a href="https://www.npmjs.com/package/@solsdk/keystone_sdk"><img alt="NPM package" src="https://img.shields.io/npm/v/@solsdk/keystone_sdk" /></a>
</p>
</div>
## Installation
```bash
npm i @solsdk/keystone_sdk
# or
yarn add @solsdk/keystone_sdk
# or
pnpm add @solsdk/keystone_sdk
```
## Overview
@solsdk/keystone_sdk is a modern, robust, and strictly-typed SDK for building high-performance applications on Solana. Designed with best practices in mind, it provides a clean, intuitive, and reliable API for developers who value code quality, maintainability, and security.
- 100% TypeScript, strict types, no `any` or unsafe casts
- Follows KISS, DRY, YAGNI, BDUF, SOLID, and APO principles
- RESTful, modular, and extensible architecture
- Thoroughly tested and production-ready
- Actively maintained and open to contributions
## Getting Started
Start integrating @solsdk/keystone_sdk into your project in minutes.
### 1. Setting up your wallet
```bash
# Generate a new Solana keypair
solana-keygen new
# Get your wallet's public key
solana address
# Add your private key to your .env file for secure access
cd {projectLocation}
echo WALLET_PRIVATE_KEY=`cat ~/.config/solana/id.json` >> .env
```
### 2. Basic Usage Example
```typescript
import { Connection, Keypair, PublicKey } from '@solana/web3.js';
import {
DriftClient,
initialize,
BN,
QUOTE_PRECISION,
BASE_PRECISION,
PRICE_PRECISION,
PositionDirection,
MarketType,
OrderTriggerCondition,
getMarketOrderParams,
getLimitOrderParams,
getTriggerMarketOrderParams,
getTriggerLimitOrderParams
} from '@solsdk/keystone_sdk';
const main = async () => {
const env = 'devnet';
// Initialize SDK
const sdkConfig = initialize({ env });
// Set up connection and wallet
const connection = new Connection(sdkConfig.RPC_URL, 'confirmed');
const wallet = Keypair.fromSecretKey(/* your secret key here */);
// Create client instance
const client = new DriftClient({
connection,
wallet,
programID: new PublicKey(sdkConfig.PROGRAM_ID),
});
await client.subscribe();
// Example: Place a market order
const marketIndex = 0; // Replace with your market index
const txSig = await client.placeOrders([
getMarketOrderParams({
baseAssetAmount: new BN(1).mul(BASE_PRECISION),
direction: PositionDirection.LONG,
marketIndex,
})
]);
console.log(`Order placed. Transaction signature: ${txSig}`);
};
main();
```
## Concepts
### Order Placement
The SDK provides several methods for placing orders on the Drift Protocol:
```typescript
// Place multiple orders in a single transaction
await client.placeOrders([
getMarketOrderParams({ /* order parameters */ }),
getLimitOrderParams({ /* order parameters */ }),
]);
// Cancel existing orders and place new ones in a single transaction
await client.cancelAndPlaceOrders(
{ marketType: MarketType.PERP, marketIndex: 0 }, // cancel parameters
[getMarketOrderParams({ /* order parameters */ })] // new orders
);
// Prepare a transaction for placing orders without sending it
const { placeOrdersTx } = await client.preparePlaceOrdersTx([
getMarketOrderParams({ /* order parameters */ })
]);
// Later send the transaction
const txSig = await client.sendTransaction(placeOrdersTx);
```
### Order Parameter Helpers
The SDK provides helper functions to create properly formatted order parameters:
```typescript
// Market order
const marketOrderParams = getMarketOrderParams({
marketIndex: 0,
direction: PositionDirection.LONG,
baseAssetAmount: new BN(1).mul(BASE_PRECISION),
});
// Limit order
const limitOrderParams = getLimitOrderParams({
marketIndex: 0,
direction: PositionDirection.LONG,
baseAssetAmount: new BN(1).mul(BASE_PRECISION),
price: new BN(50000).mul(PRICE_PRECISION), // $50,000
});
// Trigger market order
const triggerMarketOrderParams = getTriggerMarketOrderParams({
marketIndex: 0,
direction: PositionDirection.SHORT,
baseAssetAmount: new BN(1).mul(BASE_PRECISION),
triggerPrice: new BN(60000).mul(PRICE_PRECISION), // $60,000
triggerCondition: OrderTriggerCondition.ABOVE,
});
```
### Managing Orders
The SDK provides methods for canceling orders and retrieving order information:
```typescript
// Cancel all orders for a specific market
await client.cancelOrders(MarketType.PERP, 0);
// Cancel orders with a specific direction
await client.cancelOrders(MarketType.PERP, 0, PositionDirection.LONG);
// Cancel a specific order by ID
await client.cancelOrder({
marketIndex: 0,
marketType: MarketType.PERP,
orderId: new BN('12345')
});
// Get user's active orders
const user = await client.getUser();
const activeOrders = user.getActiveOrders();
// Fill a specific order (typically used by keepers/fillers)
await client.fillPerpOrder(
userAccountPublicKey,
userAccount,
{ marketIndex: 0, orderId: new BN('12345') }
);
```
### Precision & Big Numbers
@solsdk/keystone_sdk uses BN.js for all numeric values to ensure precision and safety when working with Solana tokens. All numbers are represented as integers, with explicit precision constants available for import.
| Precision Name | Value |
|---------------------- |--------|
| QUOTE_PRECISION | 10^6 |
| BASE_PRECISION | 10^9 |
| PRICE_PRECISION | 10^6 |
| ... | ... |
**Note:** When dividing BN numbers, use provided helper functions to avoid precision loss.
```typescript
import { convertToNumber } from '@solsdk/keystone_sdk';
const value = convertToNumber(new BN(10500), new BN(1000)); // = 10.5
```
## License
MIT License
---
**Ready to build?**
Install @solsdk/keystone_sdk today and join a growing community of developers building the future on Solana.
---