@wirexapp/wpay-baas-sdk
v0.1.0
Published
SDK for integration with the WirexPay platform. Supports Account Abstraction, token transfers, yield management, and smart deposit addresses.
Downloads
439
Readme
WirexPay SDK
SDK for integration with the WirexPay platform. Supports Account Abstraction (ZeroDev Kernel V3.1), token transfers, yield, and smart deposit addresses.
Installation
npm install @wirexpay/sdkPeer dependency: viem ^2.0.0
SDK Initialization
import { createSDK, type SDKEnvironment } from '@wirexpay/sdk';
const sdk = await createSDK({
env: 'dev', // 'dev' | 'prod'
companyId: '0x...', // Company ID in hex format
getMainWalletClient: () => mainWalletClient, // Embedded wallet with EtheriumProvider
enableLogging: true, // optional, default false
logger: customLogger, // optional, custom logger
});Configuration Parameters
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| env | 'dev' \| 'prod' | Yes | Environment |
| companyId | string | Yes | Company ID in hex format |
| getMainWalletClient | () => MainWalletClient | Yes | Function that returns embedded wallet with EtheriumProvider |
| enableLogging | boolean | No | Enable logging (default false) |
| logger | Logger | No | Custom logger (requires enableLogging: true) |
User Registration Flow
1: Get Smart Wallet Address
const address = await sdk.crypto.wallet.getSmartWalletAddress();
console.log('Smart Wallet:', address);2: Check Policy & Executor Status
const isPolicyInstalled = await sdk.crypto.accountAbstraction.isPolicyInstalled();
const isExecutorInstalled = await sdk.crypto.accountAbstraction.isExecutorInstalled();
console.log('Policy installed:', isPolicyInstalled);
console.log('Executor installed:', isExecutorInstalled);3: Install Policy & Executor (if not installed)
if (!isPolicyInstalled || !isExecutorInstalled) {
const result = await sdk.crypto.accountAbstraction.signInPolicyAndExecutor();
console.log('Transaction hash:', result?.receipt?.transactionHash);
}4: If you use Privy as auth — Link Smart Wallet to Privy (SIWE)
import { useLinkWithSiwe } from '@privy-io/react-auth';
const { generateSiweMessage, linkWithSiwe } = useLinkWithSiwe();
const smartWalletClient = await sdk.crypto.wallet.getSmartWalletClient();
const message = await generateSiweMessage({
address: smartWalletClient.account.address,
chainId: 'eip155:' + smartWalletClient.chain?.id,
});
const signature = await smartWalletClient.signMessage({
account: smartWalletClient.account,
message: message,
});
await linkWithSiwe({
message: message,
chainId: 'eip155:' + smartWalletClient.chain?.id,
signature,
walletClientType: 'smart_wallet',
connectorType: 'kernel',
});5: Register in Accounts Smart Contract
const receipt = await sdk.crypto.accountContract.registerInAccounts();
const isRegistered = await sdk.crypto.accountContract.isWalletInAccounts();
console.log('Registered in contract:', isRegistered);6: Register in API
Option A: Using Privy auth
import { getAccessToken, useIdentityToken } from '@privy-io/react-auth';
const accessToken = await getAccessToken();
const { identityToken } = useIdentityToken();
const userResponse = await sdk.auth.registerUser({
privy: {
accessToken: accessToken,
identityToken: identityToken,
},
country: 'FR',
});Option B: Using JWT token
const userResponse = await sdk.auth.registerUser({
authorizationToken: 'your-jwt-token',
country: 'FR',
});7: Login to API
Option A: Using Privy auth
const authResponse = await sdk.auth.login({
privy: {
accessToken: accessToken,
identityToken: identityToken,
},
});
console.log('Access token:', authResponse.access_token);Option B: Using JWT token
const authResponse = await sdk.auth.login({
authorizationToken: 'your-jwt-token',
});SDK Modules
sdk.auth — Authentication Service
| Method | Description |
|--------|-------------|
| login(params) | Login retail user (Privy or JWT) |
| loginCompany(params) | Login company/corporation |
| registerUser(params) | Register retail user |
| registerCompany(params) | Register company/corporation |
| getAccessToken() | Get current access token (returns null if expired) |
| isAuthenticated() | Check if user is authenticated |
| getUserWallet() | Get current user wallet address |
| setUserWallet(wallet) | Set user wallet address |
| setAuthState(response, userWallet?) | Manually set auth state from an auth response |
| ensureAuthenticated() | Throws AuthenticationError if not authenticated |
| clearAuth() | Clear all authentication state |
| getAuthHeaders() | Get Authorization and X-User-Wallet headers |
Authentication Parameters:
All auth methods accept either Privy tokens or a JWT authorization token:
// Option 1: Privy authentication
{
privy: {
accessToken: string; // Privy access token
identityToken: string; // Privy identity token
}
}
// Option 2: JWT authentication
{
authorizationToken: string; // Your JWT token
}Company Registration Parameters:
interface RegisterCompanyParams {
privy?: PrivyAuth;
authorizationToken?: string;
companyAddress: string;
companyName: string;
registrationCountry: string;
registrationNumber: string;
}sdk.crypto.wallet — Wallet Service
| Method | Description |
|--------|-------------|
| getSmartWalletAddress() | Get Smart Wallet address |
| getSmartWalletClient() | Get Kernel client with Policy |
| getSmartWalletClientWithoutPolicy() | Get Kernel client without Policy |
| getSmartAccountSigner() | Get signer for Smart Account |
| getMainWalletClient() | Get main wallet client |
| sendUserOperationsAndWaitReceipt(callData, smartWalletClient?) | Send user operations and wait for receipt |
| sendUserOperationsWithNonceAndWaitReceipt(callData, nonce) | Send user operations with specific nonce |
| invalidateLocalCache() | Clear cached wallet clients |
sdk.crypto.accountAbstraction — Account Abstraction Service
| Method | Description |
|--------|-------------|
| isPolicyInstalled() | Check if Execution Delay Policy is installed |
| isExecutorInstalled() | Check if Funds Management Executor is installed |
| signInPolicyAndExecutor() | Install Policy and Executor together |
| signInPolicy() | Install Policy only |
| signInExecutor() | Install Executor only |
sdk.crypto.accountContract — Account Contract Service
| Method | Description |
|--------|-------------|
| isWalletInAccounts() | Check if wallet is registered in Accounts contract |
| registerInAccounts() | Register wallet in Accounts contract (retail) |
| isWalletInCorporateAccounts() | Check if wallet is registered in Corporate Accounts contract |
| registerInCorporateAccounts() | Register wallet in Corporate Accounts contract (B2B) |
sdk.crypto.transfer — Transfer Service
| Method | Description |
|--------|-------------|
| makeFullErc20Transfer(params) | Full ERC20 transfer (two steps in one) |
| makeErc20TransferFirstPart(params) | First part: create withdrawal request |
| makeErc20TransferFinal(callData) | Second part: complete the transfer |
| makeErc20TransferSynthetic(params) | Transfer synthetic tokens |
| batchTransfer(params) | Execute multiple transfers in a batch |
Transfer Parameters:
interface Erc20TransferParams {
tokenAddress: `0x${string}`;
recipientAddress: `0x${string}`;
amount: number;
}
interface BatchTransferParams {
items: BatchTransferItem[];
}
interface BatchTransferItem {
to: `0x${string}`;
amount: string;
token: string;
guid: string;
}sdk.crypto.yield — Yield Service
| Method | Description |
|--------|-------------|
| fetchYieldData() | Get yield data (APY, pending, weekly, lifetime) |
| getYieldDataForGraphic() | Get data for graph visualization |
| getWeeklyYield() | Get weekly yield |
| withdraw() | Withdraw accumulated yield |
| switchYieldToken(token) | Switch yield token |
YieldData Structure:
interface YieldData {
tokenSymbol: string;
apy: string;
currentYield: string;
weeklyYield: string;
lifetimeYield: string;
}sdk.crypto.smartDepositAddress — Smart Deposit Addresses
| Method | Description |
|--------|-------------|
| initializeSmartDepositAddresses(forceRefresh?) | Create/get all deposit addresses |
| getAddresses() | Get cached addresses |
| clearAddresses() | Clear address cache |
Supported Networks:
- EVM: Base, Arbitrum, BNB Chain, Ethereum, Kaia, Polygon, Optimism
- TRON
- Solana
sdk.api.wallets — Wallets API
| Method | Description |
|--------|-------------|
| getBalances() | Get wallet balances |
sdk.api.withdrawal — Withdrawal API
| Method | Description |
|--------|-------------|
| getWithdrawalRequests() | Get list of withdrawal requests |
sdk.api.baas — BaaS Module
Banking-as-a-Service module with the following sub-services:
sdk.api.baas.user — User Service
| Method | Description |
|--------|-------------|
| getUser() | Get current user |
| getUserV2() | Get current user (v2) |
| createUser(request) | Create a new user |
| createRetailUser(request) | Create a retail user |
| validateRetailUser() | Validate retail user |
| authorizeUser(params) | Authorize user |
| updatePhoneNumber(request) | Update phone number |
| confirmPhoneNumber(request) | Confirm phone number via OTP |
| uploadDocument(formData) | Upload verification document |
| updateFreshdeskId(request) | Update Freshdesk ID |
| getSharingToken(request) | Get sharing token |
| setSharingToken(request) | Set sharing token |
| getVerificationToken() | Get verification token |
| getVerificationLink() | Get verification link |
sdk.api.baas.activity — Activity Service
| Method | Description |
|--------|-------------|
| getFeed(request?) | Get activity feed |
| getById(request) | Get activity by ID |
| getFullStatement(request) | Get full statement |
| getRequestedErcWithdrawals() | Get requested ERC withdrawals |
sdk.api.baas.bank — Bank Service
| Method | Description |
|--------|-------------|
| getAccounts(request?) | Get bank accounts |
| activateAccount(request) | Activate bank account |
| estimateTransfer(request) | Estimate bank transfer |
| executeTransfer(request) | Execute bank transfer |
| estimateCorridorTransferV2(corridor, request) | Estimate corridor transfer (v2) |
| executeCorridorTransferV2(corridor, request) | Execute corridor transfer (v2) |
sdk.api.baas.cards — Cards Service
| Method | Description |
|--------|-------------|
| getCards(request?) | Get user cards |
| getCard(cardId) | Get card details |
| getCardTransactions(request?) | Get card transactions |
| issuePlasticCard(request) | Issue a plastic card |
| issueVirtualCard(request) | Issue a virtual card |
| activateCard(cardId, request) | Activate card |
| blockCard(cardId) | Block card |
| unblockCard(cardId) | Unblock card |
| closeCard(cardId) | Close card |
| getCardDetails(cardId, request) | Get card PAN and expiry |
| getCardCvv(cardId, request) | Get card CVV |
| getCardPin(cardId, request) | Get card PIN |
| changeCardLimit(cardId, request) | Change card limit |
| changeCardName(cardId, request) | Change card name |
| estimateCardTransfer(request) | Estimate card transfer |
| executeCardTransfer(request) | Execute card transfer |
| estimateCardWithdrawal(cardId, request) | Estimate card withdrawal |
| executeCardWithdrawal(cardId, request) | Execute card withdrawal |
| getActive3dsRequests() | Get active 3DS requests |
| approve3dsRequest(transactionId) | Approve 3DS request |
| decline3dsRequest(transactionId) | Decline 3DS request |
| getDeliveryCountries() | Get card delivery countries |
| getDeliveryMethods(country) | Get card delivery methods |
| getOrderFees(type, country) | Get card order fees |
| createOrderFeesInvoice(type, country, request) | Create order fees invoice |
sdk.api.baas.config — Config Service
| Method | Description |
|--------|-------------|
| getConfig() | Get client app config |
sdk.api.baas.confirmation — Confirmation Service
| Method | Description |
|--------|-------------|
| verifySignature(request) | Verify signature for action confirmation |
| requestSms(request) | Request SMS confirmation code |
| verifySms(request) | Verify SMS confirmation code |
sdk.api.baas.recipients — Recipients Service
| Method | Description |
|--------|-------------|
| getRecipients(request?) | Get all recipients |
| getRecipientsByCatalog(request) | Get recipients by catalog |
| getRecipientsByCurrency(request) | Get recipients by currency |
| getRecipientsByName(request) | Get recipients by name |
| getRecipientsByType(request) | Get recipients by type |
| getRecipientById(recipientId) | Get recipient by ID |
| createRecipient(request) | Create recipient |
| createRecipientV2(request) | Create recipient (v2) |
| updateRecipient(recipientId, request) | Update recipient |
| deleteRecipient(recipientId) | Delete recipient |
| createRecipientPaymentDetails(recipientId, request) | Create payment details |
| updateRecipientPaymentDetails(recipientId, paymentDetailsId, request) | Update payment details |
| deleteRecipientPaymentDetails(recipientId, paymentDetailsId) | Delete payment details |
| incrementRecipientUsage(recipientId) | Increment recipient usage counter |
sdk.api.baas.rates — Rates Service
| Method | Description |
|--------|-------------|
| getRates(request) | Get exchange rates |
sdk.api.baas.token — Token Service
| Method | Description |
|--------|-------------|
| getToken(request) | Get OAuth2 token |
sdk.api.baas.wallet — Wallet Service
| Method | Description |
|--------|-------------|
| getWallet(request?) | Get wallet by ID or default |
| getWallets() | Get all wallets |
| createGlobalWallet(request) | Create global wallet |
Examples
Full Token Transfer
const result = await sdk.crypto.transfer.makeFullErc20Transfer({
tokenAddress: '0x920D17f7A226Ce306f2B51F74a0f0dA89C3b8dF3',
recipientAddress: '0x...',
amount: 100,
});
console.log('First part tx:', result.firstPartTxHash);
console.log('Final tx:', result.finalTxHash);
console.log('Success:', result.success);Two-Step Transfer
// Step 1: Initiate transfer
const txHash = await sdk.crypto.transfer.makeErc20TransferFirstPart({
tokenAddress: '0x920D17f7A226Ce306f2B51F74a0f0dA89C3b8dF3',
recipientAddress: '0x...',
amount: 100,
});
// Step 2: Get withdrawal requests
const withdrawals = await sdk.api.withdrawal.getWithdrawalRequests();
// Step 3: Complete transfer (after valid_after time)
await sdk.crypto.transfer.makeErc20TransferFinal(withdrawal.call_data);Batch Transfer
const txHashes = await sdk.crypto.transfer.batchTransfer({
items: [
{ to: '0x...', amount: '100', token: 'USDC', guid: 'tx-1' },
{ to: '0x...', amount: '50', token: 'USDC', guid: 'tx-2' },
],
});Yield Operations
const yieldData = await sdk.crypto.yield.fetchYieldData();
console.log('APY:', yieldData.apy);
console.log('Pending yield:', yieldData.currentYield);
await sdk.crypto.yield.withdraw();Smart Deposit Addresses
const addresses = await sdk.crypto.smartDepositAddress.initializeSmartDepositAddresses();
addresses.forEach(addr => {
console.log(`Chain: ${addr.depositChain}`);
console.log(`Address: ${addr.depositAddress}`);
console.log(`Tokens: ${addr.supportedTokens.join(', ')}`);
});Types
import type {
SDKConfig,
SDKEnvironment,
Logger,
TokenInfo,
ContractAddresses,
Hex,
TransactionHash,
MainWalletClient,
TransferRequest,
TransferResult,
BatchTransferItem,
BatchTransferResult,
YieldData,
YieldGraphicDataPoint,
AccountStatus,
PolicyStatus,
PrivyAuth,
LoginUserParams,
LoginCompanyParams,
RegisterUserParams,
RegisterCompanyParams,
AuthResponse,
RegisterUserResponse,
} from '@wirexpay/sdk';Error Handling
The SDK provides typed error classes:
| Error | Description |
|-------|-------------|
| SDKError | Base error class |
| ConfigurationError | Invalid configuration |
| NetworkError | Network/HTTP errors |
| ContractError | Smart contract interaction errors |
| WalletError | Wallet-related errors |
| TransactionError | Transaction execution errors |
| AuthenticationError | Authentication failures |
| ValidationError | Input validation errors |
import { SDKError, AuthenticationError } from '@wirexpay/sdk';
try {
await sdk.auth.login({ authorizationToken: 'token' });
} catch (error) {
if (error instanceof AuthenticationError) {
// handle auth error
}
}License
MIT
