@diviswap/sdk
v1.8.1
Published
Official Diviswap SDK - Crypto rails made simple
Maintainers
Readme
Diviswap SDK
The official TypeScript/JavaScript SDK for Diviswap - crypto rails made simple. Get up and running in under 9 minutes!
Quick Start
Installation
npm install @diviswap/sdk
# or
yarn add @diviswap/sdk
# or
pnpm add @diviswap/sdkBasic Usage
import { Diviswap } from '@diviswap/sdk';
// Initialize the SDK
const diviswap = Diviswap.init({
mode: 'partner',
keyId: process.env.DIVISWAP_PARTNER_KEY_ID,
secretKey: process.env.DIVISWAP_PARTNER_SECRET_KEY,
authMethod: 'hmac',
environment: 'sandbox' // or 'production'
});
// Register a new user
const { user } = await diviswap.auth.register({
email: '[email protected]',
password: 'secure-password'
});
// Check KYC status
const compliance = await diviswap.kyc.getComplianceStatus();
if (!compliance.canTransact) {
// KYC verification required - redirect to your KYC flow
console.log('KYC required:', compliance.nextStep);
return;
}
// Create a bank account (payee)
const payee = await diviswap.payees.create({
nickname: 'My Bank',
accountNumber: '123456789',
routingNumber: '021000021',
accountType: 'checking'
});
// Create an offramp transaction (sell crypto for fiat)
// First send crypto, then record the transaction
const transaction = await diviswap.transactions.offramp({
amount: 0.5,
currency: 'ETH',
fromAddress: '0x742d35Cc6634C0532925a3b844Bc9e7595f6E123',
payeeId: payee.id,
chain: 'ethereum',
txHash: '0x...' // Your crypto transaction hash
});Features
- Simple Authentication - Register and login with just email/password
- Bank Account Management - Add and verify bank accounts easily
- Crypto On/Off Ramps - Convert between fiat and crypto seamlessly
- Address Management - Automatic wallet tracking and manual address management
- Automatic Token Refresh - Never worry about expired tokens
- TypeScript Support - Full type safety and IntelliSense
- Multi-Environment - Support for production, sandbox, and local development
- Lightweight - Minimal dependencies, uses native fetch
API Reference
Authentication
// Register new user
await diviswap.auth.register({
email: '[email protected]',
password: 'password',
firstName: 'John',
lastName: 'Doe'
});
// Login existing user
await diviswap.auth.login({
email: '[email protected]',
password: 'password'
});
// Check if authenticated
const isLoggedIn = diviswap.auth.isAuthenticated();
// Logout
await diviswap.auth.logout();KYC Verification
// Check compliance status
const status = await diviswap.kyc.getComplianceStatus();
if (!status.canTransact) {
console.log('KYC required:', status.nextStep);
}
// Check if KYC approved
const isApproved = await diviswap.kyc.isKycApproved();
// Wait for approval (polling)
try {
await diviswap.kyc.waitForApproval({
pollInterval: 5000,
maxAttempts: 60
});
} catch (error) {
console.log('KYC not approved');
}
// Get rejection reasons
if (status.kycStatus === 'REJECTED') {
const reasons = await diviswap.kyc.getRejectionReasons();
}Payees (Bank Accounts)
// Create payee
const payee = await diviswap.payees.create({
nickname: 'My Checking',
accountNumber: '123456789',
routingNumber: '021000021',
accountType: 'checking'
});
// List all payees
const payees = await diviswap.payees.list();
// Set default payee
await diviswap.payees.setDefault(payee.id);
// Delete a payee
await diviswap.payees.delete(payee.id);Transactions
IMPORTANT: If no transaction hash is supplied, the offramp will fail.
// Offramp (sell crypto for fiat)
// IMPORTANT: Send crypto first, then call offramp with the tx hash
const offramp = await diviswap.transactions.offramp({
amount: 0.5,
currency: 'ETH',
fromAddress: '0x...',
payeeId: 'payee-id',
chain: 'ethereum',
txHash: '0x...' // Required: hash from your crypto transaction.
});
// List transactions
const transactions = await diviswap.transactions.list({
status: 'completed'
});
// Get fee estimate
const estimate = await diviswap.transactions.estimateFees({
amount: 100,
currency: 'USD',
type: 'offramp'
});
// Get recent transactions
const recent = await diviswap.transactions.getRecent(10);Address Management
Automatic Wallet Tracking (Recommended)
import { Diviswap, connectWallet, trackCurrentWallet, setupWalletTracking } from '@diviswap/sdk';
const diviswap = Diviswap.init(config);
// Connect and automatically track wallet
const connections = await connectWallet(diviswap);
console.log('Tracked addresses:', connections);
// Track current wallet state without requesting permission
const current = await trackCurrentWallet(diviswap);
// Setup automatic tracking for account/chain changes
const tracker = setupWalletTracking(diviswap, {
trackAccountChanges: true,
trackChainChanges: true,
setAsDefault: true
});Manual Address Management
// Create address manually
const address = await diviswap.addresses.create({
chain_id: 1, // Ethereum mainnet
address: '0x742d35Cc6634C0532925a3b844Bc9e7595f6E123',
is_default: true
});
// List all addresses
const addresses = await diviswap.addresses.list();
// Filter by chain
const ethAddresses = await diviswap.addresses.list({ chain_id: 1 });
// Get default addresses only
const defaults = await diviswap.addresses.list({ is_default: true });
// Set address as default for its chain
await diviswap.addresses.setDefault({
chain_id: 1,
address: '0x742d35Cc6634C0532925a3b844Bc9e7595f6E123'
});
// Delete address
await diviswap.addresses.delete({
chain_id: 1,
address: '0x742d35Cc6634C0532925a3b844Bc9e7595f6E123'
});
// Convenience methods
const ethAddresses = await diviswap.addresses.getByChain('ethereum');
const defaultEth = await diviswap.addresses.getDefault('ethereum');
const chainId = diviswap.addresses.getChainId('base'); // Returns 8453React Hooks for Addresses
import { useAddresses, useWalletConnection, useWalletAddresses } from '@diviswap/sdk/react';
function AddressManager() {
const { addresses, loading, createAddress, setDefaultAddress } = useAddresses(diviswap);
const { connections, connect, isConnecting } = useWalletConnection(diviswap);
// Combined hook for wallet + address management
const {
addresses,
connections,
connectAndTrack,
isConnecting
} = useWalletAddresses(diviswap);
return (
<div>
<button onClick={() => connectAndTrack()} disabled={isConnecting}>
{isConnecting ? 'Connecting...' : 'Connect Wallet'}
</button>
{addresses.map(addr => (
<div key={`${addr.chain_id}-${addr.address}`}>
{addr.address} {addr.is_default && '(Default)'}
</div>
))}
</div>
);
}Supported Chains
import { CHAIN_IDS } from '@diviswap/sdk';
// Mainnets
CHAIN_IDS.ethereum // 1
CHAIN_IDS.optimism // 10
CHAIN_IDS.base // 8453
CHAIN_IDS.polygon // 137
CHAIN_IDS.arbitrum // 42161
// Testnets
CHAIN_IDS.sepolia // 11155111
CHAIN_IDS.optimismSepolia // 11155420
CHAIN_IDS.baseSepolia // 84532
CHAIN_IDS.polygonAmoy // 80002
CHAIN_IDS.arbitrumSepolia // 421614Fee Management (Monetization)
// Set your custom fee (default is 0.5%)
await diviswap.fees.setFee({ percentage: 0.75 });
// Get current fee settings
const fees = await diviswap.fees.getFees();
console.log(`Total fee: ${fees.totalFeePercentage}%`);
// Calculate fees for a specific amount
const calc = await diviswap.fees.calculateFees({ amount: 100 });
console.log(`Diviswap fee: $${calc.baseFee} (1.5%)`);
console.log(`Your earnings: $${calc.integratorFee} (0.75%)`);
console.log(`Total fee: $${calc.totalFee}`);Monetization
Earn revenue from every transaction with customizable integrator fees:
- Default 0.5% fee - Start earning immediately
- Fully customizable - Set any fee percentage
- Per-user pricing - Different fees for different user tiers
- Transparent - Users see exact fee breakdowns
See the Integrator Fees Guide for details.
Configuration
Initialization Options
Diviswap.init({
mode: 'partner', // Required: 'partner' for partner authentication
keyId: 'pk_...', // Required: Your Partner Key ID
secretKey: 'sk_...', // Required: Your Partner Secret Key
authMethod: 'hmac', // Optional: 'hmac' (default) or 'jwt'
environment: 'production', // Optional: 'production' | 'sandbox' | 'development'
debug: false, // Optional: Enable debug logging
timeout: 30000 // Optional: Request timeout in ms
});Environments
- Production:
https://api.diviswap.com - Sandbox:
https://api.diviswap.com(uses sandbox partner credentials) - Development:
http://localhost:5000
Security
- Partner authentication with HMAC-SHA256 request signing (recommended) or JWT
- Partner credentials (keyId/secretKey) are required for all requests
- User sessions managed via JWT tokens after login
- Sensitive data is never logged in debug mode
- KYC verification required before transactions
- All user data encrypted and stored securely
Examples
Complete Offramp Flow
import { Diviswap } from '@diviswap/sdk';
async function sellCrypto() {
// Initialize SDK
const diviswap = Diviswap.init({
mode: 'partner',
keyId: process.env.DIVISWAP_PARTNER_KEY_ID,
secretKey: process.env.DIVISWAP_PARTNER_SECRET_KEY,
authMethod: 'hmac',
environment: 'sandbox'
});
try {
// Login user
await diviswap.auth.login({
email: '[email protected]',
password: 'password'
});
// Check KYC status
const compliance = await diviswap.kyc.getComplianceStatus();
if (!compliance.canTransact) {
console.log('KYC verification required:', compliance.nextStep);
return;
}
// Get or create a payee
let payee = await diviswap.payees.getDefault();
if (!payee) {
payee = await diviswap.payees.create({
nickname: 'My Bank',
accountNumber: '123456789',
routingNumber: '021000021',
accountType: 'checking',
setAsDefault: true
});
}
// Get deposit address for the chain
const depositAddress = diviswap.transactions.getDepositAddressForChain('ethereum');
// 1. First, send crypto to the deposit address (using your wallet library)
// const txHash = await sendTransaction({ to: depositAddress, value: amount });
// 2. Then record the offramp transaction with the tx hash
const tx = await diviswap.transactions.offramp({
amount: 0.5,
currency: 'ETH',
fromAddress: '0x742d35Cc6634C0532925a3b844Bc9e7595f6E123',
payeeId: payee.id,
chain: 'ethereum',
txHash: '0x...' // Transaction hash from step 1
});
console.log(`Offramp ${tx.id} created!`);
} catch (error) {
console.error('Error:', error);
}
}
sellCrypto();Complete Wallet Integration Flow
import { Diviswap, connectWallet, useWalletAddresses } from '@diviswap/sdk';
async function integrateWallet() {
const diviswap = Diviswap.init({
mode: 'partner',
keyId: process.env.DIVISWAP_PARTNER_KEY_ID,
secretKey: process.env.DIVISWAP_PARTNER_SECRET_KEY,
authMethod: 'hmac',
environment: 'sandbox'
});
try {
// Connect user's wallet and automatically track addresses
const connections = await connectWallet(diviswap);
console.log('Connected wallets:', connections);
// Get user's tracked addresses
const addresses = await diviswap.addresses.list();
console.log('User addresses:', addresses);
// Use default Ethereum address for offramp
const defaultEth = await diviswap.addresses.getDefault('ethereum');
if (defaultEth) {
// Create offramp transaction using tracked address
const tx = await diviswap.transactions.offramp({
amount: 0.1,
currency: 'ETH',
fromAddress: defaultEth.address,
txHash: '0x...', // Transaction hash from user's wallet
chain: 'ethereum',
payeeId: 'user-bank-account-id'
});
console.log('Offramp created:', tx.id);
}
} catch (error) {
console.error('Error:', error);
}
}
integrateWallet();Error Handling
The SDK throws typed errors for different scenarios:
import { DiviswapError, AuthenticationError, ValidationError } from '@diviswap/sdk';
try {
await diviswap.auth.login(credentials);
} catch (error) {
if (error instanceof AuthenticationError) {
console.error('Invalid credentials');
} else if (error instanceof ValidationError) {
console.error('Invalid input:', error.details);
} else if (error instanceof DiviswapError) {
console.error('API error:', error.message);
}
}Support
- Email: [email protected]
- Documentation: https://docs.diviswap.com
- Issues: https://github.com/liberex-sv/diviswap-sdk/issues
License
MIT
