Try Live
Add Docs
Rankings
Pricing
Docs
Install
Theme
Install
Docs
Pricing
More...
More...
Try Live
Rankings
Enterprise
Create API Key
Add Docs
Dfns Typescript SDK
https://github.com/dfns/dfns-sdk-ts
Admin
The Dfns Typescript SDK provides client libraries and tools for interacting with the Dfns API,
...
Tokens:
22,925
Snippets:
97
Trust Score:
7.1
Update:
6 months ago
Context
Skills
Chat
Benchmark
76.5
Suggestions
Latest
Show doc for...
Code
Info
Show Results
Context Summary (auto-generated)
Raw
Copy
Link
# Dfns TypeScript SDK The Dfns TypeScript SDK provides a comprehensive toolkit for integrating cryptographic wallet management and blockchain operations into your applications. Built on top of the Dfns API, this SDK enables developers to create, manage, and sign transactions with wallets across 50+ blockchain networks without directly handling private keys. The SDK implements enterprise-grade security through cryptographic request signing using WebAuthn, asymmetric keys, or passkeys, ensuring that all sensitive operations are properly authenticated and authorized. The SDK is organized into multiple packages covering different use cases: core API clients for direct integration, credential signers for various environments (browser, Node.js, React Native), and blockchain-specific libraries that integrate with popular frameworks like ethers.js, viem, Solana web3.js, and many others. This modular architecture allows developers to include only the components they need, whether building a web application with WebAuthn authentication, a server-side service with key-based signing, or a mobile app using device biometrics. ## Core API Client - DfnsApiClient Main client for interacting with Dfns API to manage wallets, keys, policies, and blockchain operations. ```typescript import { DfnsApiClient } from '@dfns/sdk' import { AsymmetricKeySigner } from '@dfns/sdk-keysigner' const signer = new AsymmetricKeySigner({ credId: 'X2ktMzhxaTEtZTF1bTgtOXY1cG9yY2tkZDe1dG1jYg', privateKey: process.env.DFNS_PRIVATE_KEY, // PEM format private key }) const dfnsClient = new DfnsApiClient({ baseUrl: 'https://api.dfns.io', orgId: 'or-2ng9jv-80cfc-983pop0iauf2sv8r', authToken: process.env.DFNS_AUTH_TOKEN, // Service account or PAT signer, }) // Create a new wallet const wallet = await dfnsClient.wallets.createWallet({ body: { network: 'EthereumSepolia', name: 'My Wallet' } }) console.log('Wallet created:', wallet.id, wallet.address) // List all wallets const { items } = await dfnsClient.wallets.listWallets({}) console.log(`Total wallets: ${items.length}`) // Generate a signature const signature = await dfnsClient.wallets.generateSignature({ walletId: wallet.id, body: { kind: 'Hash', hash: '0x1234567890abcdef' } }) console.log('Signature:', signature.signature) ``` ## Server-Side Signer - AsymmetricKeySigner Cryptographic signer for server-side environments using asymmetric key pairs to sign user action challenges. ```typescript import { AsymmetricKeySigner } from '@dfns/sdk-keysigner' import { DfnsApiClient } from '@dfns/sdk' const signer = new AsymmetricKeySigner({ credId: process.env.DFNS_CRED_ID, privateKey: process.env.DFNS_PRIVATE_KEY, // RSA/ECDSA private key in PEM format algorithm: 'sha256', // Optional, defaults based on key type }) const dfnsClient = new DfnsApiClient({ orgId: process.env.DFNS_ORG_ID, authToken: process.env.DFNS_AUTH_TOKEN, baseUrl: 'https://api.dfns.io', signer, }) try { const wallet = await dfnsClient.wallets.createWallet({ body: { network: 'Bitcoin', name: 'BTC Wallet' } }) console.log('Bitcoin wallet:', wallet.address) } catch (error) { console.error('Failed to create wallet:', error) } ``` ## Browser WebAuthn Signer - WebAuthnSigner Browser-based signer using WebAuthn/passkeys for secure credential management without exposing private keys. ```typescript import { WebAuthnSigner } from '@dfns/sdk-browser' import { DfnsApiClient } from '@dfns/sdk' const webauthn = new WebAuthnSigner({ relyingParty: { id: 'acme.com', // Your domain (use root domain for subdomain compatibility) name: 'Acme Corporation' }, timeout: 60000, // Optional, default 60 seconds }) const dfnsClient = new DfnsApiClient({ baseUrl: 'https://api.dfns.io', orgId: 'or-2ng9jv-80cfc-983pop0iauf2sv8r', authToken: userAuthToken, signer: webauthn, }) // User will be prompted for biometric/security key const transaction = await dfnsClient.wallets.broadcastTransaction({ walletId: 'wa-123', body: { kind: 'Eip1559', to: '0x1234567890123456789012345678901234567890', value: '1000000000000000000', // 1 ETH in wei gasLimit: '21000', maxFeePerGas: '2000000000', maxPriorityFeePerGas: '1000000000', } }) console.log('Transaction hash:', transaction.txHash) ``` ## User Authentication - DfnsAuthenticator Handles user login and registration flows with credential creation and challenge-response authentication. ```typescript import { DfnsAuthenticator } from '@dfns/sdk' import { WebAuthnSigner } from '@dfns/sdk-browser' const dfnsAuth = new DfnsAuthenticator({ baseUrl: 'https://api.dfns.io', orgId: 'or-2ng9jv-80cfc-983pop0iauf2sv8r', signer: new WebAuthnSigner({ relyingParty: { id: 'acme.com', name: 'Acme Corporation' } }), }) // User login - prompts for WebAuthn credential try { const loginResult = await dfnsAuth.login({ orgId: 'or-2ng9jv-80cfc-983pop0iauf2sv8r', username: 'user@example.com', }) console.log('Login successful, token:', loginResult.token) // Store token for subsequent API calls localStorage.setItem('dfnsToken', loginResult.token) } catch (error) { console.error('Login failed:', error.message) } // User registration - creates new WebAuthn credential const registerResult = await dfnsAuth.register({ orgId: 'or-2ng9jv-80cfc-983pop0iauf2sv8r', username: 'newuser@example.com', registrationCode: 'code-from-invite-email', }) console.log('User registered:', registerResult.user.id) ``` ## Delegated API Client - DfnsDelegatedApiClient Server-side client for delegated signing where challenge signing happens separately from request execution. ```typescript import { DfnsDelegatedApiClient } from '@dfns/sdk' const dfnsDelegated = new DfnsDelegatedApiClient({ baseUrl: 'https://api.dfns.io', orgId: 'or-2ng9jv-80cfc-983pop0iauf2sv8r', authToken: userAuthToken, // End user's auth token }) // Server endpoint: Initialize wallet creation app.post('/api/wallets/create/init', async (req, res) => { const payload = { network: 'EthereumSepolia' } const challenge = await dfnsDelegated.wallets.createWalletInit({ body: payload }) // Send challenge to client for signing res.json({ challengeIdentifier: challenge.challengeIdentifier, challenge: challenge.challenge }) }) // Server endpoint: Complete wallet creation app.post('/api/wallets/create/complete', async (req, res) => { const { payload, signedChallenge } = req.body const wallet = await dfnsDelegated.wallets.createWalletComplete( { body: payload }, signedChallenge // Signed by user's WebAuthn credential in browser ) res.json({ walletId: wallet.id, address: wallet.address }) }) ``` ## React Native Passkeys Signer - PasskeysSigner Mobile credential signer using platform-specific passkey APIs for iOS and Android. ```typescript import { PasskeysSigner } from '@dfns/sdk-react-native' import { DfnsApiClient } from '@dfns/sdk' const passkeys = new PasskeysSigner({ relyingParty: { id: 'acme.com', name: 'Acme Mobile App' }, timeout: 60000, }) const dfnsClient = new DfnsApiClient({ baseUrl: 'https://api.dfns.io', orgId: process.env.DFNS_ORG_ID, authToken: userToken, signer: passkeys, }) // Platform-specific passkey prompt (Face ID, Touch ID, or biometric) const wallet = await dfnsClient.wallets.createWallet({ body: { network: 'Solana', name: 'SOL Mobile Wallet' } }) console.log('Mobile wallet created:', wallet.address) // Sign transaction with biometric authentication const signature = await dfnsClient.wallets.generateSignature({ walletId: wallet.id, body: { kind: 'Transaction', transaction: '0x...' // Serialized transaction } }) ``` ## Viem Integration - DfnsWallet Integration with viem library for Ethereum operations with Dfns-managed wallets. ```typescript import { DfnsWallet } from '@dfns/lib-viem' import { DfnsApiClient } from '@dfns/sdk' import { AsymmetricKeySigner } from '@dfns/sdk-keysigner' import { createWalletClient, http, parseEther } from 'viem' import { mainnet } from 'viem/chains' import { toAccount } from 'viem/accounts' const signer = new AsymmetricKeySigner({ credId: process.env.DFNS_CRED_ID, privateKey: process.env.DFNS_PRIVATE_KEY, }) const dfnsClient = new DfnsApiClient({ orgId: process.env.DFNS_ORG_ID, authToken: process.env.DFNS_AUTH_TOKEN, baseUrl: 'https://api.dfns.io', signer, }) const dfnsWallet = await DfnsWallet.init({ walletId: 'wa-123', dfnsClient, }) const walletClient = createWalletClient({ account: toAccount(dfnsWallet), chain: mainnet, transport: http('https://eth-mainnet.g.alchemy.com/v2/YOUR_KEY'), }) // Send transaction using viem APIs const hash = await walletClient.sendTransaction({ to: '0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb', value: parseEther('0.1'), }) console.log('Transaction sent:', hash) // Sign typed data const signature = await dfnsWallet.signTypedData({ domain: { name: 'Acme', version: '1', chainId: 1 }, types: { Person: [{ name: 'name', type: 'string' }] }, primaryType: 'Person', message: { name: 'Alice' }, }) ``` ## Ethers.js v6 Integration - DfnsWallet Integration with ethers.js v6 for Ethereum and EVM-compatible blockchain operations. ```typescript import { DfnsWallet } from '@dfns/lib-ethersjs6' import { DfnsApiClient } from '@dfns/sdk' import { AsymmetricKeySigner } from '@dfns/sdk-keysigner' import { JsonRpcProvider, parseEther } from 'ethers' const signer = new AsymmetricKeySigner({ privateKey: process.env.DFNS_PRIVATE_KEY, credId: process.env.DFNS_CRED_ID, }) const dfnsClient = new DfnsApiClient({ orgId: process.env.DFNS_ORG_ID, authToken: process.env.DFNS_AUTH_TOKEN, baseUrl: 'https://api.dfns.io', signer, }) const rpcProvider = new JsonRpcProvider('https://sepolia.infura.io/v3/YOUR_KEY') const wallet = await DfnsWallet.init({ walletId: process.env.DFNS_WALLET_ID, dfnsClient, }) const connectedWallet = wallet.connect(rpcProvider) // Get balance const balance = await connectedWallet.getBalance() console.log('Balance:', balance.toString()) // Send transaction const tx = await connectedWallet.sendTransaction({ to: '0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb', value: parseEther('0.05'), }) await tx.wait() console.log('Transaction confirmed:', tx.hash) // Interact with smart contract const contract = new Contract(contractAddress, abi, connectedWallet) const result = await contract.transfer(recipient, parseEther('10')) ``` ## Wallet Operations - Create and Broadcast Comprehensive wallet creation across multiple networks and transaction broadcasting. ```typescript import { DfnsApiClient } from '@dfns/sdk' import { AsymmetricKeySigner } from '@dfns/sdk-keysigner' const dfnsClient = new DfnsApiClient({ orgId: process.env.DFNS_ORG_ID, authToken: process.env.DFNS_AUTH_TOKEN, baseUrl: 'https://api.dfns.io', signer: new AsymmetricKeySigner({ credId: process.env.DFNS_CRED_ID, privateKey: process.env.DFNS_PRIVATE_KEY, }), }) // Create wallets on different networks const ethWallet = await dfnsClient.wallets.createWallet({ body: { network: 'Ethereum', name: 'ETH Mainnet' } }) const btcWallet = await dfnsClient.wallets.createWallet({ body: { network: 'Bitcoin', name: 'BTC Wallet' } }) const solWallet = await dfnsClient.wallets.createWallet({ body: { network: 'Solana', name: 'SOL Wallet' } }) // Broadcast EVM transaction const evmTx = await dfnsClient.wallets.broadcastTransaction({ walletId: ethWallet.id, body: { kind: 'Eip1559', to: '0x1234567890123456789012345678901234567890', value: '1000000000000000000', gasLimit: '21000', maxFeePerGas: '30000000000', maxPriorityFeePerGas: '2000000000', externalId: 'unique-tx-id-123', } }) console.log('EVM tx status:', evmTx.status, 'hash:', evmTx.txHash) // Broadcast Bitcoin PSBT const btcTx = await dfnsClient.wallets.broadcastTransaction({ walletId: btcWallet.id, body: { kind: 'Psbt', psbt: '70736274ff01007d...', externalId: 'btc-tx-456', } }) ``` ## Policy and Permissions Management Configure approval policies and permission controls for wallet operations. ```typescript import { DfnsApiClient } from '@dfns/sdk' const dfnsClient = new DfnsApiClient({ /* ... config ... */ }) // Create approval policy requiring 2 out of 3 approvers const policy = await dfnsClient.policies.createPolicy({ body: { name: 'High Value Transaction Policy', activityKind: 'Wallets:BroadcastTransaction', rule: { kind: 'TransactionAmountLimit', configuration: { limit: '10000000000000000000', // 10 ETH currency: 'ETH', } }, approvalSettings: { required: 2, approvers: [ { userId: 'us-123' }, { userId: 'us-456' }, { userId: 'us-789' }, ] }, } }) // Grant permissions to user await dfnsClient.permissions.createPermission({ body: { userId: 'us-123', permissionName: 'Wallets:Create', } }) // List user permissions const permissions = await dfnsClient.permissions.listUserPermissions({ userId: 'us-123' }) console.log('User permissions:', permissions.items) ``` ## Advanced Transaction Signing Sign messages, typed data, and complex transaction types across different blockchain protocols. ```typescript import { DfnsApiClient } from '@dfns/sdk' const dfnsClient = new DfnsApiClient({ /* ... config ... */ }) // Sign arbitrary hash const hashSig = await dfnsClient.wallets.generateSignature({ walletId: 'wa-123', body: { kind: 'Hash', hash: '0xabcdef1234567890' } }) // Sign EVM message const msgSig = await dfnsClient.wallets.generateSignature({ walletId: 'wa-123', body: { kind: 'Message', message: '0x48656c6c6f' } // "Hello" in hex }) // Sign EVM transaction const txSig = await dfnsClient.wallets.generateSignature({ walletId: 'wa-123', body: { kind: 'Transaction', transaction: '0x02f8...' // Serialized EIP-1559 transaction } }) // Get wallet details const wallet = await dfnsClient.wallets.getWallet({ walletId: 'wa-123' }) console.log('Network:', wallet.network) console.log('Address:', wallet.address) console.log('Public key:', wallet.signingKey.publicKey) console.log('Status:', wallet.status) // List wallet assets const assets = await dfnsClient.wallets.getWalletAssets({ walletId: 'wa-123' }) assets.items.forEach(asset => { console.log(`${asset.symbol}: ${asset.balance}`) }) ``` ## Summary The Dfns TypeScript SDK provides enterprise-grade wallet infrastructure for building blockchain applications across 50+ networks without managing private keys directly. The primary use cases include: (1) building custodial wallet services where users authenticate via WebAuthn/passkeys for maximum security, (2) server-side automation using service accounts with key-based signing for trading bots, payment processors, or treasury management, (3) mobile wallet applications leveraging device biometrics through React Native passkeys, and (4) integrating with existing dApps by replacing standard signers with Dfns-managed wallets in popular libraries like ethers.js and viem. Integration patterns follow a consistent structure: initialize a credential signer appropriate for your environment (WebAuthnSigner for browsers, AsymmetricKeySigner for servers, PasskeysSigner for mobile), create a DfnsApiClient with organization credentials and authentication token, then use the client's namespaced methods (wallets, keys, policies, etc.) to perform operations. For delegated architectures where servers coordinate operations but users retain signing control, use DfnsDelegatedApiClient which splits operations into init/complete pairs. All sensitive operations require cryptographic proof via challenge-response protocols, ensuring end-to-end security from user authentication through transaction broadcast.