Services Industries ADI Ecosystem Cases Company Careers Blog Contacts
Services
Industries
ADI Ecosystem
Company

ADI Wallet Implementation Guide: Complete Developer Manual

Building non-custodial crypto capabilities into an existing application usually creates major friction. Users stumble through 12-word seed phrases, lose private keys, and abandon onboarding screens. ADI Wallet avoids this hurdle by replacing seed phrases with device passkeys (Face ID, Touch ID, and platform authenticators) through account abstraction on EVM-compatible networks and the ADI Layer 2 chain.

This ADI wallet implementation guide walks through connecting ADI Wallet into an application stack.

Build a Wallet Experience Tailored to Your Product

We provide wallet integration and blockchain engineering services tailored to your business requirements

Table of contents:

  1. What is ADI Wallet?
  2. System Requirements and Environment
  3. ADI Wallet Architecture Overview
  4. How to Implement ADI Wallet: Primary Implementation Steps
  5. ADI Wallet Error Handling and Edge Cases
  6. ADI Wallet Security Best Practices
  7. ADI Wallet Troubleshooting and Common Pitfalls
  8. Summary

What is ADI Wallet?

ADI Wallet is a self-custody wallet infrastructure built to eliminate cryptographic key management for end users. It merges smart contract accounts with WebAuthn standards, allowing applications to deploy self-custodial wallets without forcing users to store mnemonics.

The system handles several practical payment and data flows:

  • In-app token checkouts. Settle payments using stablecoins or ADI utility tokens without forcing the user to leave your interface.
  • Programmable identity. Link verified user profiles and permissions to a decentralized identifier.
  • Automated recurring disbursements. Execute scheduled or batch transfers using session validation.
  • Tokenized asset access. Manage digital receipts, real-world asset (RWA) representations, and tokenized credentials on-chain.

If your team needs to support Web3 transactions while keeping your user experience as clean as a standard web application, this tutorial provides the exact steps to get it running.

System Requirements and Environment

Before writing code, verify that your engineering environment satisfies these baseline needs. Tech stack and supported environments:

  • Runtime: Node.js 18.x or 20.x LTS.
  • Language: TypeScript 5.0+ or JavaScript ES2022.
  • Frontend: Any modern browser supporting the WebAuthn API (Chrome 108+, Safari 16+, Firefox 115+, Edge 108+).
  • Frameworks: Express, Fastify, Next.js, or NestJS for backend endpoints; React, Vue, or vanilla JavaScript on the frontend.

The implementation uses the official Node.js server SDK alongside the client-side authentication library:

JSON

{

  “dependencies”: {

    “@adi-wallet/sdk”: “^2.4.0”,

    “@adi-wallet/web-auth”: “^2.4.0”,

    “dotenv”: “^16.4.5”

  },

  “devDependencies”: {

    “@types/node”: “^20.11.0”,

    “typescript”: “^5.3.3”

  }

}

You must register for an organization account in the ADI Developer Portal. Once registered, create an application workspace to generate three values:

  1. ADI_CLIENT_ID: Public identifier for your client application.
  2. ADI_CLIENT_SECRET: Secret key used for server-to-server API communication. Keep this off the frontend.
  3. ADI_WEBHOOK_SECRET: Cryptographic secret used to verify inbound webhook signatures.

So, let’s move on to how to connect ADI Wallet to your project.

ADI Wallet Architecture Overview

A secure ADI Wallet setup relies on a three-tier architecture:

  • Your client application
  • Your backend server
  • ADI API network

Direct communication between the user’s browser and the ADI API is restricted to passkey challenge ceremonies and signed transaction relaying. All sensitive account management tasks, webhook verifications, and permission minting remain isolated on your application server.

The security design combines two distinct mechanisms:

  • Server-to-Server. Calls from your backend to ADI use standard Bearer tokens generated from your client credentials.
  • User Authorization. End users sign transactions using WebAuthn passkeys stored in their device’s Secure Enclave or Trusted Execution Environment. Your backend never touches or stores private keys.

Our ADI Wallet tutorial covers all you need to know.

Installation and Setup

Install the server package inside your backend project directory:

npm install @adi-wallet/sdk dotenv

If you manage a frontend build as well, install the client package:

npm install @adi-wallet/web-auth

Environment Configuration

Store your credentials in a .env file at the root of your project:

# Environment Mode: sandbox | production

ADI_ENVIRONMENT=sandbox

# API Credentials

ADI_CLIENT_ID=app_client_test_88f92a10

ADI_CLIENT_SECRET=sec_test_90e761dfa78c93b4510b65287b46d03a

ADI_WEBHOOK_SECRET=whsec_test_04b8ce99127598cdba92e2124503

# Application Settings

ADI_BASE_URL=https://api.sandbox.adi.foundation/v1

Initializing the SDK

Create a dedicated client wrapper instance on your server:

// src/lib/adiClient.ts

import { AdiClient } from ‘@adi-wallet/sdk’;

import dotenv from ‘dotenv’;

dotenv.config();

const environment = (process.env.ADI_ENVIRONMENT || ‘sandbox’) as ‘sandbox’ | ‘production’;

export const adi = new AdiClient({

  clientId: process.env.ADI_CLIENT_ID!,

  clientSecret: process.env.ADI_CLIENT_SECRET!,

  environment: environment,

  timeoutMs: 10000,

});

How to Implement ADI Wallet: Primary Implementation Steps

Setting up the system requires 4 consecutive development phases:

  • Onboarding user wallets
  • Reading account state
  • Dispatching transactions
  • Handling asynchronous webhooks

Our ADI Wallet tutorial covers them all.

1. Connecting a User Wallet

Users can either create a fresh passkey wallet or connect an existing one. The flow begins on your server, which requests an onboarding session challenge from ADI.

Step 1: Request an Onboarding Session (Backend)

// src/controllers/walletController.ts

import { Request, Response } from ‘express’;

import { adi } from ‘../lib/adiClient’;

export async function createWalletSession(req: Request, res: Response) {

  try {

    const { userId, email } = req.body;

    const session = await adi.wallets.createSession({

      externalUserId: userId,

      userEmail: email,

      scopes: [‘wallet:read’, ‘wallet:transact’],

      redirectOrigin: ‘https://yourapp.example.com’,

    });

    // session contains sessionId and challengeToken for WebAuthn

    return res.status(201).json({

      sessionId: session.sessionId,

      challenge: session.challengeToken,

    });

  } catch (error: any) {

    return res.status(500).json({ error: error.message });

  }

}

Step 2: Trigger Passkey Registration (Client)

The client application catches the challenge and invokes the native device authenticator:

// frontend/src/walletAuth.ts

import { AdiWebAuth } from ‘@adi-wallet/web-auth’;

export async function handleWalletConnection(sessionId: string, challenge: string) {

  const auth = new AdiWebAuth({ environment: ‘sandbox’ });

  // Prompts Face ID, Touch ID, or OS Passkey dialog

  const credentials = await auth.registerOrLink({

    sessionId,

    challenge,

  });

  if (!credentials.success) {

    throw new Error(‘User cancelled or rejected the passkey request.’);

  }

  // Send the signed confirmation token back to your server

  const response = await fetch(‘/api/wallet/confirm’, {

    method: ‘POST’,

    headers: { ‘Content-Type’: ‘application/json’ },

    body: JSON.stringify({

      sessionId,

      signature: credentials.signature,

      publicKey: credentials.publicKey,

    }),

  });

  return await response.json();

}

Step 3: Confirm and Store the Wallet Reference (Backend)

Once confirmed, ADI returns a permanent walletId and public account address. Save these in your user database:

export async function confirmWallet(req: Request, res: Response) {

  const { sessionId, signature, publicKey } = req.body;

  const result = await adi.wallets.finalizeConnection({

    sessionId,

    signature,

    publicKey,

  });

  // Persist record to your internal database

  await db.users.update({

    where: { id: result.externalUserId },

    data: {

      adiWalletId: result.walletId,

      adiPublicAddress: result.accountAddress,

      walletLinkedAt: new Date(),

    },

  });

  return res.status(200).json({ status: ‘connected’, walletId: result.walletId });

}

2. Reading Wallet Data

Once linked, queries for account balances and past transaction ledgers use the persistent walletId.

Querying Balances

export async function getWalletBalance(req: Request, res: Response) {

  const { walletId } = req.params;

  // Retrieve balances across all tokens configured on the account

  const balanceResponse = await adi.wallets.getBalance(walletId, {

    currencies: [‘ADI’, ‘USDC’, ‘EURC’],

  });

  return res.json({

    walletId: balanceResponse.walletId,

    network: balanceResponse.network,

    balances: balanceResponse.balances, // Array: [{ symbol: ‘ADI’, amount: ‘250.50’, raw: ‘250500000000000000000’ }]

  });

}

Fetching Paginated Transaction History

Transaction lists should always implement cursor-based pagination. Avoid hardcoded limits:

export async function listTransactions(req: Request, res: Response) {

  const { walletId } = req.params;

  const cursor = (req.query.cursor as string) || undefined;

  const limit = Math.min(Number(req.query.limit) || 20, 100);

  const history = await adi.wallets.getHistory(walletId, {

    limit,

    cursor,

    direction: ‘all’, // ‘incoming’ | ‘outgoing’ | ‘all’

  });

  return res.json({

    data: history.items,

    nextCursor: history.nextCursor,

    hasMore: history.hasMore,

  });

}

3. Initiating Transactions

Transferring assets follows three states:

  • Building the raw transaction payload
  • Obtaining client authorization via passkey
  • Broadcasting the signed bundle to the network

// Step 1: Server builds unsigned transaction intent

export async function createTransferIntent(req: Request, res: Response) {

  const { senderWalletId, recipientAddress, amount, tokenSymbol } = req.body;

  const intent = await adi.transactions.createIntent({

    senderWalletId,

    recipientAddress,

    token: tokenSymbol,

    amount, // Human readable string, e.g., “15.00”

    feeMode: ‘SPONSORED’, // ‘SPONSORED’ uses your paymaster pool; ‘USER_PAYS’ deducts from sender

  });

  return res.json({

    transactionId: intent.id,

    signingPayload: intent.signingPayload,

  });

}

On the frontend, pass signingPayload into the client authenticator. Once the user approves the biometric prompt, dispatch the output back to your server:

// Step 2: Server submits signed payload

export async function submitTransfer(req: Request, res: Response) {

  const { transactionId, clientSignature } = req.body;

  const execution = await adi.transactions.submit({

    transactionId,

    clientSignature,

  });

  // Returns immediate tracking state

  return res.json({

    txHash: execution.txHash,

    status: execution.status, // ‘PENDING’ | ‘SUBMITTED’

  });

}

Handling State Progression

Blockchain operations do not finalize instantly. You should monitor three transaction milestones:

StatusMeaningRecommended System Action
PENDINGCreated in memory, awaiting network inclusionDisplay a spinner; do not unlock products
SUBMITTEDPropagated across nodes, awaiting block confirmationKeep status as processing; lock user balance
CONFIRMEDSettled and proven via zero-knowledge validity proofDeliver order or credit user account balance
FAILEDTransaction ran out of gas or was rejected by node rulesRestore balance; prompt user to retry

4. Webhooks and Event Processing

Do not poll transaction endpoints repeatedly. Use webhook subscriptions instead.

Registering the Endpoint

Configure your webhook destination via the ADI portal or SDK:

await adi.webhooks.register({

  url: ‘https://api.yourapp.example.com/webhooks/adi’,

  events: [

    ‘wallet.created’,

    ‘transaction.confirmed’,

    ‘transaction.failed’,

    ‘balance.updated’,

  ],

});

Verifying and Ingesting Webhooks

Webhook payloads must be validated against their HMAC-SHA256 signature. A missing or invalid signature means the request should be dropped immediately.

// src/routes/webhookRoute.ts

import { Request, Response } from ‘express’;

import crypto from ‘crypto’;

export function handleWebhook(req: Request, res: Response) {

  const signature = req.headers[‘x-adi-signature’] as string;

  const timestamp = req.headers[‘x-adi-timestamp’] as string;

  const secret = process.env.ADI_WEBHOOK_SECRET!;

  if (!signature || !timestamp) {

    return res.status(401).send(‘Missing signature headers’);

  }

  // Prevent replay attacks older than 5 minutes

  const currentTime = Math.floor(Date.now() / 1000);

  if (Math.abs(currentTime – Number(timestamp)) > 300) {

    return res.status(400).send(‘Webhook timestamp expired’);

  }

  // Calculate HMAC using raw body buffer

  const rawBody = (req as any).rawBody; // Assumes raw body middleware is used

  const computedSignature = crypto

    .createHmac(‘sha256’, secret)

    .update(`${timestamp}.${rawBody}`)

    .digest(‘hex’);

  if (!crypto.timingSafeEqual(Buffer.from(signature), Buffer.from(computedSignature))) {

    return res.status(403).send(‘Invalid webhook signature’);

  }

  const payload = JSON.parse(rawBody);

  switch (payload.event) {

    case ‘transaction.confirmed’:

      // Update purchase record to paid

      break;

    case ‘transaction.failed’:

      // Alert user of failed transfer

      break;

    default:

      // Acknowledge unhandled events

      break;

  }

  return res.status(200).json({ received: true });

}

Take Your ADI Wallet Integration From Setup to Production

ADI Wallet Error Handling and Edge Cases

Production stability depends on how your code treats edge cases and downstream exceptions.

Common Error Codes

Error CodeHTTP StatusRoot CauseResolution
INSUFFICIENT_FUNDS400Wallet lacks token balance or gas feePrompt user to top up balance
CHALLENGE_EXPIRED408WebAuthn prompt was ignored by userGenerate a fresh challenge token
RATE_LIMIT_EXCEEDED429Exceeded 100 requests per minuteApply exponential backoff
INVALID_NONCE409Multiple concurrent outgoing transactionsQueue transactions sequentially per wallet
UNAUTHORIZED_SCOPE403API key lacks permission for the endpointUpdate application scopes in portal

Idempotency Keys

Network hiccups can cause retry storms. Every transfer submission must provide an idempotency header so identical payloads are never executed twice:

const response = await adi.transactions.submit({

  transactionId,

  clientSignature,

}, {

  idempotencyKey: `tx_${userId}_${orderId}`, // Deduplicates duplicate requests for 24h

});

ADI Wallet Security Best Practices

Securing self-custody systems requires isolating permissions and enforcing strict client-server boundaries. Best practices for securing ADI wallet:

  1. Keep Secrets Server-Side. Never embed ADI_CLIENT_SECRET or ADI_WEBHOOK_SECRET inside client scripts, frontend repositories, or mobile app bundles.
  2. Short-Lived Challenges. Expire WebAuthn passkey registration and signing challenges after 120 seconds. Long challenge windows leave users vulnerable to man-in-the-middle session hijacking.
  3. Isolate Raw Body for Webhooks. Ensure your HTTP server captures the pristine raw body buffer before any JSON parsing middleware modifies spacing or key ordering.
  4. Transit and Rest Standards. Enforce TLS 1.3 for all outbound API traffic. Store user wallet IDs encrypted using AES-256-GCM in your primary relational database.
  5. Enforce Egress Rate Limiting. Prevent automated balance drain exploits by setting outgoing transfer limits per user (for example: max 5 withdrawals per hour).

These 5 best practices are a must for any ADI Wallet API tutorial.

ADI Wallet Troubleshooting and Common Pitfalls

Here we want to highlight 3 common pitfalls.

Signature Verification Fails on Webhooks

If your server repeatedly returns HTTP 403 on valid webhooks, check your body-parser middleware. Standard express.json() mutates the payload string into an object, discarding raw byte positions. Store the original buffer on the request object using the verify callback:

app.use(express.json({

  verify: (req: any, res, buf) => {

    req.rawBody = buf.toString();

  }

}));

Decimals and Precision Errors

Tokens like USDC use 6 decimal places, while native ADI uses 18. Avoid using standard JavaScript floating-point arithmetic (0.1 + 0.2) when formatting currency amounts. Parse amounts as strings or use arbitrary-precision libraries like bignumber.js to avoid truncating funds.

WebAuthn Fails on Desktop

WebAuthn requires an active user gesture (like a button click) in an authenticated HTTPS context. Calling passkey prompts inside asynchronous callbacks without direct user interaction causes modern browsers to block the request.

Summary

You now have a clean system connecting your application to ADI Wallet:

  • Your backend handles server-level secrets
  • Your frontend delegates key security directly to the user’s hardware passkey
  • Your webhook endpoints listen for verified state updates

Build on ADI Chain with an Experienced Technology Partner

    Formats: pdf, doc, docx, rtf, ppt, pptx.
    Herman CTO
    Herman Stohniiev
    CTO and Co-founder
    Herman Stohniiev has extensive experience in software architecture, blockchain infrastructure, and Web3 development. He specializes in designing scalable technology solutions, building blockchain-based products, and bridging traditional financial systems with decentralized technologies. With a strong background in technical leadership and product development, Herman focuses on advancing blockchain adoption and developing infrastructure for institutional and enterprise use cases.
    FAQ

    Frequently Asked Questions

    • What happens if a user loses the phone or laptop containing their passkey?
      Modern operating systems sync WebAuthn passkeys across devices by default through services like Apple iCloud Keychain or Google Password Manager. A user setting up a replacement phone regains access instantly. If they lose access to their entire cloud account, things get messy fast. That is why we think enrolling a recovery guardian or secondary device during initial onboarding is worth the extra step. It saves headache-inducing account recovery tickets later.
    • Can our backend cover gas fees so users never need crypto tokens?
      Yes. Pass feeMode: 'SPONSORED' inside the transfer creation payload on your server. The network pulls fees directly from your funded paymaster balance instead of deducting gas from the customer. Keeps checkout slick. Honestly, just track that balance with a Slack bot or automated email alert so your deposit never empties out during an unexpected traffic spike.
    • How do we stop people from accidentally firing duplicate payments?
      Attach an idempotency key whenever you submit a transfer request. Build this string by combining the internal order ID with the customer account ID. The network locks and caches that value for twenty-four hours. If a customer mashes the confirm button during lag, the API spots the duplicate key and returns the original transaction record instead of running two separate charges.
    Subscription

    Subscribe to Newsletter

    Subscribe to IdeaSoft newsletter — be the first to get blog updates and IdeaSoft news!

    Not subscribed, because of server error. Try again later...
    Successfully subscribed!