hypesdk
Version:
A powerful SDK for interacting with the Hype blockchain, featuring advanced routing and token swap capabilities
481 lines (369 loc) • 13 kB
Markdown
# HypeSDK
A powerful SDK for interacting with the Hype blockchain, featuring advanced routing, token swap capabilities, and token management tools.
## Installation
```bash
npm install hypesdk
```
## Features
- 🔒 **Secure Wallet Management**: Create and manage wallets securely
- 💸 **Native Token Operations**: Transfer HYPE tokens easily
- 🔄 **Token Swaps**: Execute optimal route swaps with multiple hops
- 💱 **Token Wrapping**: Wrap and unwrap native HYPE tokens
- ⚡ **Gas Optimization**: Automatic gas estimation and priority fee adjustment
- 📊 **Token Analytics**: Check token holders and balances
- 🔍 **Transaction Info**: Detailed transaction information and status
- 🎯 **Token Airdrops**: Efficient batch token distribution
## Quick Reference
### Initialization
```typescript
// Initialize with default RPC URL
const sdk = new HyperSDK();
// The SDK automatically connects to the Hype blockchain using:
// - RPC URL: https://rpc.hyperscan.com
// - Chain ID: 12120
// - Native Token: HYPE
// - Block Explorer: https://purrsec.com
```
### Constructor Options
```typescript
interface HyperSDKOptions {
provider?: ethers.JsonRpcProvider; // Optional custom provider
rpcUrl?: string; // Optional custom RPC URL
}
// Example with custom options:
const sdk = new HyperSDK({
rpcUrl: "https://your-custom-rpc.com",
});
```
### Wallet Operations
```typescript
createWallet(): Promise<{ address: string; privateKey: string }>
transfer(privateKey: string, toAddress: string, amount: string, priorityFeeMultiplier?: number): Promise<string>
```
### Token Operations
```typescript
wrap(privateKey: string, amount: string, priorityFeeMultiplier?: number): Promise<string>
unwrap(privateKey: string, amount: string, priorityFeeMultiplier?: number): Promise<string>
deployToken(privateKey: string, name: string, symbol: string, initialSupply: string, priorityFeeMultiplier?: number): Promise<DeployedToken>
```
### Swap Operations
```typescript
swap(privateKey: string, tokenIn: string, tokenOut: string, amountIn: string, slippageBps?: number, priorityFeeMultiplier?: number): Promise<string>
buyWithRoute(privateKey: string, tokenIn: string, tokenOut: string, amountIn: string, slippageBps?: number, priorityFeeMultiplier?: number): Promise<string>
sellWithRoute(privateKey: string, tokenToSell: string, amountIn: string, slippageBps?: number, priorityFeeMultiplier?: number): Promise<string>
```
### Limit Orders
```typescript
createLimitOrderBuy(
privateKey: string,
tokenAddress: string,
amountIn: string,
targetPrice: string,
options?: {
slippageBps?: number;
checkIntervalMs?: number;
timeoutMs?: number;
priorityFeeMultiplier?: number;
}
): Promise<{ orderId: string; cancel: () => void }>
createLimitOrderSell(
privateKey: string,
tokenAddress: string,
amountIn: string,
targetPrice: string,
options?: {
slippageBps?: number;
checkIntervalMs?: number;
timeoutMs?: number;
priorityFeeMultiplier?: number;
}
): Promise<{ orderId: string; cancel: () => void }>
```
### Token Information
```typescript
getTokenBalance(tokenAddress: string, walletAddress: string): Promise<{
balance: string;
formattedBalance: string;
symbol: string;
decimals: number;
name: string;
}>
getTokenHolders(tokenAddress: string, limit?: number): Promise<{
holders: Array<{ address: string; value: string; formattedValue: string }>;
totalHolders: number;
}>
getWalletBalances(walletAddress: string, limit?: number): Promise<{
data: { tokens: Array<TokenBalance>; count: number };
success: boolean;
}>
```
### Transaction Operations
```typescript
getTransactionInfo(txHash: string): Promise<{
data: {
hash: string;
result: string;
priority_fee: string;
max_fee_per_gas: string;
max_priority_fee_per_gas: string;
transaction_burnt_fee: string;
confirmations: number;
confirmation_duration: [number, number];
revert_reason: string | null;
from: AddressInfo;
to: AddressInfo;
}
success: boolean;
}>
```
### Token Distribution
```typescript
// Distribute ERC20 tokens
airdropToken(
privateKey: string,
tokenAddress: string,
recipients: string[],
amounts: string[],
priorityFeeMultiplier?: number
): Promise<string[]>
// Distribute native HYPE
distributeHype(
privateKey: string,
recipients: string[],
amounts: string[],
priorityFeeMultiplier?: number
): Promise<string[]>
```
## Reference
### Token Information & Analytics
#### `getTokenHolders(tokenAddress: string, limit?: number)`
Gets the list of token holders with their balances.
- `tokenAddress`: Token contract address
- `limit`: Maximum number of holders to return (default: 100)
Returns:
```typescript
{
holders: Array<{
address: string;
value: string;
formattedValue: string;
}>;
totalHolders: number;
}
```
#### `getTokenBalance(tokenAddress: string, walletAddress: string)`
Gets the balance of a specific token for a wallet.
Returns:
```typescript
{
balance: string;
formattedBalance: string;
symbol: string;
decimals: number;
name: string;
}
```
### Transaction Operations
#### `getTransactionInfo(txHash: string)`
Gets detailed information about a transaction.
Returns:
```typescript
{
data: {
hash: string;
result: string;
priority_fee: string;
max_fee_per_gas: string;
max_priority_fee_per_gas: string;
transaction_burnt_fee: string;
confirmations: number;
confirmation_duration: [number, number];
revert_reason: string | null;
from: AddressInfo;
to: AddressInfo;
}
success: boolean;
}
```
### Token Distribution
#### `airdropToken(privateKey: string, tokenAddress: string, recipients: string[], amounts: string[], priorityFeeMultiplier?: number)`
Airdrops tokens to multiple recipients in batches of 100.
- `privateKey`: Sender's private key
- `tokenAddress`: Token to airdrop
- `recipients`: Array of recipient addresses
- `amounts`: Array of amounts to send (human readable)
- `priorityFeeMultiplier`: Optional gas priority multiplier (default: 1)
Returns: Array of transaction hashes (one per batch)
Example:
```typescript
// Airdrop to 150 recipients (will be processed in 2 batches)
const txHashes = await sdk.airdropToken(
privateKey,
tokenAddress,
Array(150).fill("0x123..."), // Replace with actual addresses
Array(150).fill("100") // 100 tokens each
);
```
#### `distributeHype(privateKey: string, recipients: string[], amounts: string[], priorityFeeMultiplier?: number)`
Distributes native HYPE tokens to multiple recipients in batches of 100. Features automatic gas price scaling based on batch size.
- `privateKey`: Sender's private key
- `recipients`: Array of recipient addresses
- `amounts`: Array of amounts to send (in HYPE, human readable format)
- `priorityFeeMultiplier`: Optional gas priority multiplier (default: 1, scales with batch size)
Returns: Array of transaction hashes (one per batch)
Example:
```typescript
// Distribute HYPE to 150 recipients (will be processed in 2 batches)
const txHashes = await sdk.distributeHype(
privateKey,
Array(150).fill("0xRecipientAddress"), // Replace with actual addresses
Array(150).fill("0.1"), // 0.1 HYPE each
1.5 // Priority fee multiplier
);
// The function automatically:
// - Processes recipients in batches of 100
// - Scales gas prices based on batch size
// - Waits for each batch to confirm before proceeding
// - Returns array of transaction hashes
```
Key Features:
- Automatic batch processing (100 recipients per transaction)
- Dynamic gas price scaling based on batch size
- Built-in transaction confirmation waiting
- Detailed progress logging
- No token approvals needed (uses native HYPE)
Gas Optimization:
```typescript
// Gas multiplier scales with batch size:
const batchSizeMultiplier = Math.max(1, recipientsInBatch / 20);
const effectiveMultiplier = priorityFeeMultiplier * batchSizeMultiplier;
// Example scaling:
// - 20 recipients: 1x multiplier
// - 50 recipients: 2.5x multiplier
// - 100 recipients: 5x multiplier
```
### Wallet Operations
#### `createWallet()`
Creates a new wallet with address and private key.
Returns:
```typescript
{
address: string;
privateKey: string;
}
```
#### `transfer(privateKey: string, toAddress: string, amount: string, priorityFeeMultiplier?: number)`
Transfers native HYPE tokens.
- `privateKey`: Sender's private key
- `toAddress`: Recipient's address
- `amount`: Amount in HYPE (human readable format)
- `priorityFeeMultiplier`: Optional gas priority multiplier (default: 1)
Returns: Transaction hash
### Token Operations
#### `wrap(privateKey: string, amount: string)`
Wraps native HYPE tokens into wrapped tokens.
Returns: Transaction hash
#### `unwrap(privateKey: string, amount: string)`
Unwraps tokens back to native HYPE.
Returns: Transaction hash
#### `buyWithRoute(privateKey: string, tokenIn: string, tokenOut: string, amountIn: string, slippageBps?: number, priorityFeeMultiplier?: number)`
Executes a token swap using the optimal route.
- `privateKey`: Sender's private key
- `tokenIn`: Input token address
- `tokenOut`: Output token address
- `amountIn`: Amount to swap (human readable)
- `slippageBps`: Slippage tolerance in basis points (default: 100 = 1%)
- `priorityFeeMultiplier`: Gas priority multiplier (default: 1)
Returns: Transaction hash
#### `sellWithRoute(privateKey: string, tokenToSell: string, amountIn: string, slippageBps?: number)`
Executes a token sell operation.
- `privateKey`: Sender's private key
- `tokenToSell`: Address of token to sell
- `amountIn`: Amount to sell
- `slippageBps`: Slippage tolerance in basis points (default: 100 = 1%)
Returns: Transaction hash
### Limit Order Operations
#### `createLimitOrderBuy(privateKey: string, tokenAddress: string, amountIn: string, targetPrice: string, options?)`
Creates a buy limit order that executes when the token price falls to or below the target price.
- `privateKey`: Sender's private key
- `tokenAddress`: Address of the token to buy
- `amountIn`: Amount of HYPE to spend (human readable format)
- `targetPrice`: Target price of token in terms of HYPE
- `options`:
- `slippageBps`: Slippage tolerance in basis points (default: 100 = 1%)
- `checkIntervalMs`: How often to check price in milliseconds (default: 10000 = 10 seconds)
- `timeoutMs`: Order expiration in milliseconds (default: 0 = no expiration)
- `priorityFeeMultiplier`: Gas priority multiplier (default: 1)
Returns: Object with order ID and cancel function
Example:
```typescript
// Buy token when price drops to 80 tokens per HYPE (or better)
const buyOrder = await sdk.createLimitOrderBuy(
privateKey,
"0x1234...abcd", // Token to buy
"0.01", // Spend 0.01 HYPE
"80.0", // Target price: 1 HYPE = 80 tokens
{
slippageBps: 100, // 1% slippage
checkIntervalMs: 30000, // Check every 30 seconds
timeoutMs: 3600000, // Expire after 1 hour
}
);
// Cancel the order if needed
buyOrder.cancel();
```
#### `createLimitOrderSell(privateKey: string, tokenAddress: string, amountIn: string, targetPrice: string, options?)`
Creates a sell limit order that executes when the token price rises to or above the target price.
- `privateKey`: Sender's private key
- `tokenAddress`: Address of the token to sell
- `amountIn`: Amount of tokens to sell (human readable format)
- `targetPrice`: Target price of token in terms of HYPE
- `options`:
- `slippageBps`: Slippage tolerance in basis points (default: 100 = 1%)
- `checkIntervalMs`: How often to check price in milliseconds (default: 10000 = 10 seconds)
- `timeoutMs`: Order expiration in milliseconds (default: 0 = no expiration)
- `priorityFeeMultiplier`: Gas priority multiplier (default: 1)
Returns: Object with order ID and cancel function
Example:
```typescript
// Sell tokens when price rises to 0.015 HYPE per token (or better)
const sellOrder = await sdk.createLimitOrderSell(
privateKey,
"0x1234...abcd", // Token to sell
"100", // Sell 100 tokens
"0.015", // Target price: 1 token = 0.015 HYPE
{
slippageBps: 50, // 0.5% slippage
checkIntervalMs: 60000, // Check every minute
timeoutMs: 7200000, // Expire after 2 hours
}
);
// Cancel the order if needed
sellOrder.cancel();
```
## Error Handling
The SDK throws descriptive errors for common issues:
- Insufficient funds
- Invalid addresses
- Failed transactions
- Network errors
Example error handling:
```typescript
try {
const txHash = await sdk.buyWithRoute(privateKey, tokenIn, tokenOut, amount);
} catch (error) {
if (error.message.includes("insufficient funds")) {
console.error("Not enough balance to complete the transaction");
} else {
console.error("Transaction failed:", error);
}
}
```
## Best Practices
1. Always handle errors appropriately
2. Use reasonable slippage values (0.1% - 2%)
3. Store private keys securely
4. Monitor transaction status after execution
5. Use appropriate gas settings for your needs
## License
[Add your license here]