TypeScript SDK
The official TypeScript/JavaScript SDK for building on RP1.
Installation
npm install @rp1/sdk
Basic Usage
import { RP1Client, Wallet } from '@rp1/sdk';
// Initialize client
const client = new RP1Client('https://rpc.rp.one');
// Create wallet
const wallet = Wallet.fromMnemonic('your 24 word mnemonic...');
console.log(`Address: ${wallet.address}`);
// Get balance
const balance = await client.getBalance(wallet.address, 'urp1');
console.log(`Balance: ${balance.amount} urp1`);
Client API
Constructor
new RP1Client(rpcEndpoint: string, options?: ClientOptions)
Options:
interface ClientOptions {
apiEndpoint?: string;
grpcEndpoint?: string;
gasPrice?: string;
gasAdjustment?: number;
broadcastTimeout?: number;
pollInterval?: number;
}
Query Methods
// Get account info
const account = await client.getAccount(address);
// Get balance
const balance = await client.getBalance(address, denom);
// Get all balances
const balances = await client.getAllBalances(address);
// Get transaction
const tx = await client.getTx(hash);
// Search transactions
const txs = await client.searchTxs({ sender: address, limit: 10 });
// Get block
const block = await client.getBlock(height);
// Get latest block
const latest = await client.getLatestBlock();
Transaction Methods
// Send tokens
const tx = await client.send({
from: wallet,
to: recipient,
amount: '1000000',
denom: 'urp1',
memo?: 'optional memo',
});
// Broadcast signed transaction
const result = await client.broadcast(signedTx, 'sync');
// Simulate transaction
const simulation = await client.simulate(unsignedTx);
Wallet API
Creation
// From mnemonic (BIP39)
const wallet = Wallet.fromMnemonic(mnemonic, {
hdPath?: "m/44'/118'/0'/0/0",
prefix?: 'rp1',
});
// From private key
const wallet = Wallet.fromPrivateKey(privateKeyBytes);
// Generate new wallet
const wallet = Wallet.generate();
console.log(wallet.mnemonic); // Save this!
Properties
wallet.address // bech32 address
wallet.publicKey // public key bytes
wallet.privateKey // private key bytes (sensitive!)
wallet.mnemonic // mnemonic phrase (sensitive!)
Signing
// Sign arbitrary data
const signature = await wallet.sign(data);
// Sign transaction
const signedTx = await wallet.signTx(unsignedTx, chainId, accountNumber, sequence);
Module Classes
PrivacyModule
import { PrivacyModule } from '@rp1/sdk';
const privacy = new PrivacyModule(client);
// Shield tokens
await privacy.shield(wallet, '1000000', 'urp1');
// Private transfer
await privacy.transfer(wallet, recipient, '500000');
// Unshield tokens
await privacy.unshield(wallet, '500000', 'urp1');
// Get shielded balance
const shieldedBalance = await privacy.getShieldedBalance(wallet);
// Create viewing key
await privacy.createViewingKey(wallet, {
grantee: auditorAddress,
type: 'full',
expiresAt: '2025-12-31',
});
// Revoke viewing key
await privacy.revokeViewingKey(wallet, grantee);
DEXModule
import { DEXModule } from '@rp1/sdk';
const dex = new DEXModule(client);
// Get pools
const pools = await dex.getPools();
// Get quote
const quote = await dex.getQuote({
poolId: '1',
tokenIn: 'urp1',
amountIn: '1000000',
});
// Swap tokens
await dex.swap(wallet, {
poolId: '1',
tokenIn: { denom: 'urp1', amount: '1000000' },
minTokenOut: '980000',
});
// Add liquidity
await dex.addLiquidity(wallet, {
poolId: '1',
tokenAAmount: '1000000',
tokenBAmount: '500000',
minShares: '450000',
});
// Remove liquidity
await dex.removeLiquidity(wallet, {
poolId: '1',
shares: '100000',
minTokenA: '90000',
minTokenB: '45000',
});
LendingModule
import { LendingModule } from '@rp1/sdk';
const lending = new LendingModule(client);
// Supply assets
await lending.supply(wallet, '1000000', 'uusdc');
// Enable as collateral
await lending.enableCollateral(wallet, 'uusdc');
// Borrow
await lending.borrow(wallet, '500000', 'uusdc');
// Repay
await lending.repay(wallet, '500000', 'uusdc');
// Withdraw supply
await lending.withdraw(wallet, '500000', 'uusdc');
// Get position
const position = await lending.getPosition(address, 'uusdc');
// Get health factor
const health = await lending.getHealthFactor(address);
OracleModule
import { OracleModule } from '@rp1/sdk';
const oracle = new OracleModule(client);
// Get current price
const btcPrice = await oracle.getPrice('BTC');
// Get all prices
const prices = await oracle.getAllPrices();
// Get TWAP
const twap = await oracle.getTWAP('ETH', '1h');
// Subscribe to price updates
oracle.subscribePrices(['BTC', 'ETH'], (price) => {
console.log(`${price.symbol}: $${price.price}`);
});
StakingModule
import { StakingModule } from '@rp1/sdk';
const staking = new StakingModule(client);
// Get validators
const validators = await staking.getValidators();
// Delegate
await staking.delegate(wallet, validatorAddress, '1000000');
// Undelegate
await staking.undelegate(wallet, validatorAddress, '500000');
// Redelegate
await staking.redelegate(wallet, srcValidator, dstValidator, '500000');
// Claim rewards
await staking.claimRewards(wallet, validatorAddress);
// Get delegations
const delegations = await staking.getDelegations(address);
Event Subscriptions
// Subscribe to new blocks
client.subscribeBlocks((block) => {
console.log(`New block: ${block.height}`);
});
// Subscribe to transactions
client.subscribeTxs((tx) => {
console.log(`New tx: ${tx.hash}`);
});
// Subscribe to specific events
client.subscribeEvents("message.sender='rp1...'", (event) => {
console.log(`Event: ${JSON.stringify(event)}`);
});
// Unsubscribe
subscription.unsubscribe();
Error Types
import {
RP1Error,
NetworkError,
WalletError,
InsufficientFundsError,
TxFailedError,
InvalidAddressError,
} from '@rp1/sdk';
try {
await client.send({ ... });
} catch (error) {
if (error instanceof TxFailedError) {
console.log(`Code: ${error.code}`);
console.log(`Message: ${error.message}`);
console.log(`Raw log: ${error.rawLog}`);
}
}
Utilities
import {
toMicroAmount,
fromMicroAmount,
isValidAddress,
shortenAddress,
} from '@rp1/sdk';
// Convert amounts
toMicroAmount('1.5', 'urp1'); // '1500000'
fromMicroAmount('1500000', 'urp1'); // '1.5'
// Validate address
isValidAddress('rp1abc...'); // true
// Shorten address
shortenAddress('rp1abcdefghijk...'); // 'rp1abc...jklm'