Free 30-min Web3 Consultation
Book Consultation
Smart Contract Security Audits
View Audit Services
Custom DeFi Protocol Development
Explore DeFi
Full-Stack Web3 dApp Development
View App Services
Free 30-min Web3 Consultation
Book Consultation
Smart Contract Security Audits
View Audit Services
Custom DeFi Protocol Development
Explore DeFi
Full-Stack Web3 dApp Development
View App Services
Free 30-min Web3 Consultation
Book Consultation
Smart Contract Security Audits
View Audit Services
Custom DeFi Protocol Development
Explore DeFi
Full-Stack Web3 dApp Development
View App Services
Free 30-min Web3 Consultation
Book Consultation
Smart Contract Security Audits
View Audit Services
Custom DeFi Protocol Development
Explore DeFi
Full-Stack Web3 dApp Development
View App Services
LABS
Guides

How to Implement a User Onboarding Flow with Embedded Compliance

A developer-focused tutorial on architecting and coding a user onboarding system that integrates identity verification, risk assessment, and sanctions screening directly into the sign-up flow.
Chainscore © 2026
introduction
TUTORIAL

How to Implement a User Onboarding Flow with Embedded Compliance

A step-by-step guide for developers to integrate compliance checks directly into user sign-up and transaction flows, ensuring regulatory adherence without sacrificing user experience.

Traditional compliance in Web3 often acts as a gatekeeper, halting user journeys for manual review. Embedded compliance flips this model by integrating checks—like sanctions screening, identity verification, and transaction risk analysis—directly into the application's logic. This approach allows platforms to enforce rules programmatically at key interaction points: user registration, wallet connection, token swaps, or NFT purchases. By using on-chain and off-chain data, developers can create flows that are both secure and seamless, reducing friction while maintaining a robust compliance posture. The goal is to make regulatory requirements a native feature of the product, not a disruptive afterthought.

Implementing this starts with defining your compliance requirements. Common checks include: screening wallet addresses against sanctions lists (e.g., OFAC), verifying proof-of-humanity via services like Worldcoin or Gitcoin Passport, assessing transaction risk based on source/destination, and enforcing jurisdictional geofencing. For a user onboarding flow, the first critical step is the Initial Wallet Connection. Upon a user connecting a wallet like MetaMask, your dApp's backend should immediately call a compliance API, such as Chainalysis or TRM Labs, to screen the address. This check should happen before any further UI is rendered or personal data is collected.

Here is a simplified code example for a Next.js/React frontend handler that performs an address screening check upon connection:

javascript
import { useAccount, useConnect } from 'wagmi';
import { screeningApi } from '../lib/compliance';

function ConnectButton() {
  const { connect, connectors } = useConnect();
  const { address } = useAccount();

  const handleConnect = async (connector) => {
    // 1. Connect wallet
    const { accounts } = await connect({ connector });
    const userAddress = accounts[0];

    // 2. Embedded Compliance Check
    try {
      const screenResult = await screeningApi.screenAddress(userAddress);
      
      if (screenResult.riskLevel === 'HIGH' || screenResult.isSanctioned) {
        // Block flow and show compliant message
        alert('Cannot proceed due to compliance requirements.');
        // Optionally, disconnect wallet here
        return;
      }
      // 3. Proceed to next onboarding step
      console.log('Address cleared, proceeding...');
    } catch (error) {
      console.error('Screening failed:', error);
    }
  };

  return (
    <button onClick={() => handleConnect(connectors[0])}>
      Connect Wallet
    </button>
  );
}

This pattern ensures the compliance gate is triggered at the earliest possible point.

After the initial wallet screening, the next layer is Progressive Disclosure and KYC. Not all users or actions require full identity verification. Use a risk-based approach: only prompt for KYC (using a provider like Veriff or Persona) when a user attempts a high-value transaction, accesses advanced features, or triggers a risk rule. Store verification status and risk scores in your user session or database to avoid repeating checks. This method balances user privacy with regulatory demands. Remember, data handling must comply with regulations like GDPR; clearly communicate what data is collected, why, and how it's used, obtaining explicit consent where required.

Finally, transaction monitoring must be embedded into core smart contract interactions. For DeFi protocols or NFT marketplaces, pre-transaction checks are essential. Use off-chain relayers or meta-transaction systems to validate a transaction's compliance before it is submitted on-chain. Services like Forta Network can monitor for suspicious patterns in real-time. The key is to design your system's architecture so that compliance is a continuous process, not a one-time checkpoint. Log all compliance events for audit trails. By weaving these checks into the fabric of your application, you build a more trustworthy and sustainable platform that can scale within the global regulatory framework.

prerequisites
BUILDING BLOCKS

Prerequisites and Tech Stack

Before implementing a compliant user onboarding flow, you need to establish the foundational technology stack and understand the core concepts of embedded compliance.

The core of any Web3 onboarding flow is a wallet connection. You'll need to integrate a library like WalletConnect v2, MetaMask SDK, or RainbowKit to handle wallet detection, connection prompts, and signature requests. For a seamless experience, consider using a Smart Account (ERC-4337) provider such as Biconomy, Alchemy Account Kit, or ZeroDev. These abstract away gas fees for users and enable social logins and session keys, which are critical for non-custodial yet user-friendly onboarding.

On the compliance side, you must integrate with specialized Know Your Customer (KYC) and Anti-Money Laundering (AML) providers. Services like Synapse, Veriff, Sumsub, and Persona offer APIs to verify user identity, screen against sanctions lists, and perform risk assessments. Your application logic will call these APIs, often after a wallet connects but before granting full platform access. The verification result (e.g., a verified: true flag and a risk score) must be stored securely, typically hashed on-chain or in a private database.

Your backend infrastructure needs to orchestrate these components. A Node.js (Express/Fastify) or Python (FastAPI) server is common. You will need to manage API keys for compliance services, handle webhook events for asynchronous verification results, and maintain a database (PostgreSQL, MongoDB) to link wallet addresses, verification statuses, and user profiles. For on-chain attestations, you may use Ethereum Attestation Service (EAS) or a similar registry to create tamper-proof records of a user's verified status.

Smart contracts also play a role in enforcing compliance. After off-chain verification, you can issue a Soulbound Token (SBT) or a verifiable credential to the user's wallet. Your protocol's main contracts should then check for the presence of this token before allowing certain actions, like high-value transfers or participation in token sales. This creates a gated access system where compliance is programmatically enforced.

Finally, consider the user experience flow. The stack should support a modular design where compliance checks can be triggered at specific points: at initial sign-up, before a first deposit, or when a transaction threshold is exceeded. Tools like Dynamic or Civic Pass offer pre-built SDKs that bundle wallet connection and compliance into a single widget, significantly accelerating development if your use case aligns with their offerings.

architecture-overview
SYSTEM ARCHITECTURE

How to Implement a User Onboarding Flow with Embedded Compliance

A modular, on-chain approach to integrating KYC/AML checks directly into your dApp's sign-up process, ensuring regulatory adherence without sacrificing user experience.

An embedded compliance architecture moves identity verification from a centralized backend to a modular, on-chain layer. Instead of building a custom KYC system, you integrate with specialized compliance-as-a-service providers like Veriff, Persona, or Fractal ID. These providers handle the verification logic and return a cryptographically signed attestation, such as a verifiable credential or a soulbound token (SBT), which is stored on-chain or in a user's wallet. Your smart contract or dApp frontend then checks for this attestation before granting access to gated features. This decouples compliance logic from core application logic, making updates and audits significantly easier.

The user flow typically follows these steps: 1) User initiates sign-up in your dApp. 2) They are redirected to the compliance provider's secure iFrame or SDK. 3) The user completes the required checks (e.g., ID document scan, liveness test). 4) Upon success, the provider mints a non-transferable attestation (like an SBT on Polygon ID or an attestation on Ethereum Attestation Service) to the user's wallet address. 5) Your dApp's smart contract verifies the attestation's signature and validity period before allowing the user to proceed. This creates a trustless, user-centric model where the user owns their credential and can potentially reuse it across other compliant dApps.

Key architectural components include the Attestation Registry, a smart contract (often on a cost-effective L2 like Polygon or Base) that logs issued credentials; the Verification Gateway, your dApp's backend service that orchestrates the call to the compliance provider; and the Gating Contract, the access-control logic in your core application. For example, an Aave-compatible lending pool's deposit() function would first call a hasValidKYCAttestation(user) modifier. Using standards like EIP-712 for signed typed data ensures the attestations are verifiable on-chain without relying on a centralized oracle.

When implementing, prioritize privacy-preserving techniques. Zero-knowledge proofs (ZKPs) allow users to prove they hold a valid credential without revealing the underlying data. Protocols like Semaphore or zkPass can generate a ZK proof that a user's credential is valid and not revoked. Your gating contract would then verify this proof. Additionally, consider credential revocation. Your architecture must query a revocation registry or check the attestation's expiry timestamp. Many providers offer on-chain revocation lists or utilize the W3C Verifiable Credentials status standard for this purpose.

For developers, start by integrating a provider's SDK. A basic frontend integration with Persona might look like:

javascript
import { Inquiries } from "@withpersona/persona-react";

function OnboardingButton() {
  const { open } = usePersona();
  const handleVerify = async () => {
    const inquiryId = await open({
      templateId: "itmpl_abc123",
      onComplete: ({ inquiryId, status }) => {
        // Call your backend to mint attestation
        fetch(`/api/mint-attestation`, {
          method: "POST",
          body: JSON.stringify({ inquiryId, status })
        });
      },
    });
  };
  return <button onClick={handleVerify}>Verify Identity</button>;
}

Your backend would then validate the inquiry with Persona's API and trigger an attestation minting transaction.

The main challenges are cost management (attestation minting fees), cross-chain interoperability (making credentials usable across multiple networks), and user experience (minimizing friction). Best practices include using gas-optimized L2s for attestation storage, adopting cross-chain messaging protocols like LayerZero or Axelar for credential portability, and implementing progressive compliance where only high-value transactions require full KYC. This architecture future-proofs your application, as compliance rules can be upgraded by changing the attestation verification logic without modifying your core smart contracts.

compliance-providers
IMPLEMENTATION GUIDE

Key Compliance Service Providers

Integrating compliance into your user onboarding is non-negotiable for regulated applications. These services provide the critical KYC/AML infrastructure, from identity verification to transaction monitoring.

06

Implementing the Onboarding Flow

A technical overview of stitching these services together into a cohesive user journey.

  • Typical Flow: 1. User submits email/phone. 2. Trigger KYC provider (Veriff/Sumsub) for ID check. 3. Screen provided wallet address via Chainalysis. 4. Continuously monitor transactions with ComplyAdvantage.
  • Architecture: Use webhooks from compliance providers to update user status in your backend database.
  • Best Practice: Implement a modular design to easily switch providers or add regional specialists like Trulioo.
step-1-kyc-integration
FOUNDATION

Step 1: Integrate Identity Verification (KYC)

A secure and compliant user onboarding flow begins with robust identity verification. This step establishes user trust and ensures regulatory adherence.

Identity verification, or Know Your Customer (KYC), is a mandatory legal requirement for financial services, including most on-ramps, custodial wallets, and regulated DeFi platforms. It involves collecting and verifying a user's personal information—such as name, date of birth, and address—against official documents like a passport or driver's license. For Web3 applications, integrating a specialized KYC provider is far more efficient and secure than building a custom solution. These providers handle the complex logic of document validation, liveness checks, and sanction screening, returning a simple verification status to your application via an API.

To implement this, you first select a KYC provider. Popular choices include Sumsub, Veriff, and Jumio, each offering different balances of coverage, cost, and developer experience. After creating an account, you'll obtain API keys for authentication. The integration typically involves two main components: a frontend SDK to collect user data and a backend webhook to receive verification results. The frontend SDK launches a secure modal where users upload their ID and take a selfie; this data is sent directly to the provider, not through your servers, enhancing security and data privacy.

On the backend, you must set up a secure endpoint to listen for the provider's webhook callbacks. When a user's verification is complete, the provider sends a POST request to your webhook URL with a payload containing the user's unique applicantId and a reviewStatus (e.g., "completed", "pending"). Your server should verify the webhook signature (using a secret from the provider) to ensure the request is authentic, then update the user's verification state in your database. A common pattern is to store the applicantId and status, then mint a Soulbound Token (SBT) or update an on-chain registry to reflect the verified status, enabling gasless checks by other smart contracts.

step-2-screening-integration
COMPLIANCE LAYER

Step 2: Implement Sanctions and AML Screening

Integrate real-time sanctions and anti-money laundering checks into your user onboarding process to meet global regulatory requirements.

After collecting a user's identity information, the next critical step is to screen them against global sanctions lists and perform anti-money laundering (AML) risk assessments. This process is non-negotiable for operating a compliant service in most jurisdictions. You must check the provided name, date of birth, and address against databases like the Office of Foreign Assets Control (OFAC) Specially Designated Nationals (SDN) list, the European Union consolidated sanctions list, and other relevant Politically Exposed Persons (PEP) and adverse media databases. A match doesn't automatically mean rejection, but it triggers a mandatory enhanced due diligence (EDD) review.

To implement this, you will integrate with a specialized compliance API provider. Leading services include Chainalysis, Elliptic, TRM Labs, and ComplyAdvantage. These providers maintain up-to-date lists and offer simple REST APIs. Your backend service should call their screening endpoint with the user's sanitized PII. The response will typically include a risk score and flags for any potential matches, which your system must log securely for audit trails. Here is a conceptual Node.js example using a generic client:

javascript
async function screenUser(userData) {
  const response = await complianceClient.screen({
    name: userData.fullName,
    birthdate: userData.dob,
    country: userData.countryCode
  });
  // Store `response.riskScore` and `response.matches` in your DB
  return response;
}

Your application logic must define clear rules based on the screening results. A common flow is: Low Risk - proceed with standard onboarding. Medium Risk - flag for manual review by your compliance team before allowing full access. High Risk or Confirmed Sanctions Match - block onboarding entirely and file a Suspicious Activity Report (SAR) if required. It's crucial to design this as a synchronous blocking step in your onboarding funnel; the user should not gain access to financial features until screening is complete and passed according to your policy.

Remember that sanctions lists are updated frequently—sometimes daily. Relying on a static, downloaded list is insufficient for production. Your chosen provider's API ensures you have the latest data. Furthermore, screening is not a one-time event. You should implement ongoing monitoring to re-screen existing users periodically (e.g., quarterly) and immediately when sanctions lists are updated, as a user who was once clear could later become flagged. This requires a background job that queries your user database and calls the screening API.

Finally, document every action. Maintain immutable logs of all screening requests, responses, risk scores, and the resulting decisions (e.g., USER_APPROVED, FLAGGED_FOR_REVIEW). This audit trail is essential for demonstrating your compliance program to regulators. Store these logs separately from your main application database with restricted access. By embedding these checks directly into your onboarding flow, you automate compliance, reduce manual workload, and significantly lower your regulatory risk.

step-3-risk-orchestration
IMPLEMENTATION

Step 3: Build the Onboarding Orchestrator

This guide details how to construct a smart contract orchestrator that manages user onboarding, compliance checks, and token distribution in a single transaction.

The onboarding orchestrator is a smart contract that sequences the critical steps of user entry: identity verification, compliance screening, and initial asset provisioning. Its primary function is to ensure these steps are atomic—either all succeed or the entire transaction reverts, preventing users from getting stuck in a partially onboarded state. This contract acts as the single entry point, calling external services like Sygnum's BankingCircle for KYC/AML and managing the minting or transfer of a protocol's native token or NFT.

A typical orchestrator flow involves three key interactions. First, it calls a whitelist or registry contract (often managed off-chain) to verify the user's passed KYC status. Second, it executes any required fund transfers, such as pulling stablecoins from the user for an initial deposit. Finally, it mints and distributes the access token to the user's wallet. Using OpenZeppelin's ReentrancyGuard and implementing proper error handling with custom errors (e.g., KYCNotVerified, InsufficientPayment) is crucial for security and gas efficiency.

Here is a simplified Solidity skeleton for the orchestrator's core function:

solidity
function onboardUser(address user, uint256 depositAmount) external payable nonReentrant {
    // 1. Compliance Check
    if (!kycRegistry.isVerified(user)) revert KYCNotVerified();
    // 2. Process Payment
    stablecoin.safeTransferFrom(user, address(this), depositAmount);
    // 3. Mint Access Token
    membershipToken.safeMint(user, 1);
    // 4. Emit Event
    emit UserOnboarded(user, depositAmount, block.timestamp);
}

The contract should store immutable addresses for its dependencies (KYC registry, token contracts) and emit clear events for off-chain monitoring.

For production systems, consider gas optimization and upgradeability. The orchestrator should be deployed as a Proxy (using UUPS or Transparent patterns) to allow for logic updates as compliance requirements evolve. To save gas for users, you can sponsor transactions via a meta-transaction relayer or implement a multicall function for batch onboarding. Always conduct thorough unit and fork tests using Foundry or Hardhat, simulating mainnet interactions with the external compliance service.

Finally, integrate the orchestrator with your frontend application. Use ethers.js or viem to construct the transaction, ensuring the user signs only once for the entire bundled operation. The UI should clearly communicate the three-step process—verify, pay, receive—and handle transaction states (pending, success, error) gracefully. This seamless integration turns a complex multi-step procedure into a single, user-friendly click, significantly improving the onboarding conversion rate.

step-4-frontend-flow
IMPLEMENTATION GUIDE

Step 4: Design the Frontend User Flow

This guide details how to build a user onboarding flow that integrates compliance checks directly into the frontend experience, using tools like Privy, Dynamic, and Chainscore.

A seamless yet compliant onboarding flow is critical for user retention and regulatory safety. The goal is to abstract away complexity: users should experience a single, fluid sign-up process while your application performs necessary checks in the background. This involves integrating several key components: a wallet connection and social login provider (like Privy or Dynamic), a compliance verification service (like Chainscore), and your application's own backend for session management. The frontend orchestrates these services, presenting a unified interface to the user.

Start by designing the user journey. A typical flow begins with a connection modal. Using a toolkit like @privy-io/react-auth, you can offer multiple entry points: Embedded Wallets for new users, external wallets (MetaMask, Coinbase Wallet) for experienced ones, and social logins (Google, Discord) for convenience. Upon connection, immediately trigger a compliance check by sending the user's wallet address or email to a service like Chainscore via its API. This check assesses risk factors like sanctions exposure or association with stolen funds, returning a score or flag.

Based on the compliance result, your UI must react appropriately. For low-risk users, proceed directly to the main application interface. For medium-risk users, you might implement step-up verification, such as requesting additional KYC information through a modal. For high-risk users, the flow should gracefully block access, potentially displaying a clear message and offering a support contact. This logic should be handled client-side initially for speed, with critical decisions validated by your backend to prevent manipulation.

Here is a simplified React code example demonstrating the core flow after installing necessary SDKs:

javascript
import { usePrivy } from '@privy-io/react-auth';
import { chainscore } from '@chainscore/sdk';

function OnboardingButton() {
  const { login, user } = usePrivy();
  const scClient = chainscore('your-api-key');

  const handleLogin = async () => {
    await login(); // Privy opens modal
    if (user?.wallet?.address) {
      const { riskScore } = await scClient.screenAddress(user.wallet.address);
      if (riskScore < 30) {
        // Low risk: proceed
        router.push('/dashboard');
      } else {
        // Higher risk: show step-up modal
        setShowComplianceModal(true);
      }
    }
  };
  return <button onClick={handleLogin}>Connect Wallet</button>;
}

Finally, ensure the user's compliance status is managed persistently. Upon successful verification, your backend should issue a session token or JWT, storing the user's wallet address and risk score. This token authorizes subsequent API calls. Implement periodic re-screening for active sessions, especially before high-value transactions, by calling the compliance API again. Log all screening events for audit purposes. By embedding these checks into the initial flow, you create a secure foundation without sacrificing user experience, turning regulatory necessity into a seamless part of your product.

GLOBAL REGULATORY LANDSCAPE

Comparison of Compliance Check Requirements by Jurisdiction

Key KYC/AML verification steps and data collection mandates for user onboarding in major financial jurisdictions.

Compliance CheckUnited States (FinCEN)European Union (AMLD6)United Kingdom (FCA)Singapore (MAS)

Mandatory Identity Verification (KYC)

Source of Funds Declaration

Politically Exposed Person (PEP) Screening

Sanctions List Screening

Adverse Media Screening

Transaction Monitoring Threshold

$3,000

€1,000

ÂŁ1,000

S$1,000

Travel Rule Applicability

$3,000

€1,000

€1,000

S$1,500

Mandatory Cooling-off Period

ONBOARDING & COMPLIANCE

Frequently Asked Questions (FAQ)

Common developer questions and troubleshooting for implementing secure, compliant user onboarding flows in Web3 applications.

An embedded compliance flow integrates verification checks directly into your application's UI, typically via a modal or component, without redirecting users to a third-party site. This contrasts with a redirect flow, where users are sent to an external KYC provider's page.

Key differences:

  • User Experience: Embedded flows maintain your app's branding and context, reducing drop-off rates. Redirects can break the user journey.
  • Technical Control: Embedded flows allow you to manage the verification lifecycle (start, retry, success/failure callbacks) programmatically within your code.
  • Data Handling: With embedded flows, sensitive PII is often processed directly by the compliance provider's secure iframe or SDK, keeping it off your servers.

Tools like Coinbase Verifications SDK or Synapse's KYB API offer embedded solutions, while many traditional providers use redirects.

conclusion
IMPLEMENTATION SUMMARY

Conclusion and Next Steps

You have now built a foundational user onboarding flow that integrates compliance checks directly into the user journey. This guide covered the essential steps from initial wallet connection to automated risk screening.

The implemented flow provides a significant security and compliance upgrade over traditional methods. By using programmatic checks from providers like Chainalysis or TRM Labs via their APIs, you can screen addresses for sanctions exposure, high-risk activity, and stolen funds before allowing interaction. This proactive approach reduces regulatory risk and protects your platform's integrity. The key is to treat the compliance result as a gate in your application logic, not just a passive alert.

For production deployment, consider these next steps. First, audit and harden your smart contracts, especially the logic governing access based on the off-chain compliance signal. Use a multi-sig or timelock for critical updates. Second, implement privacy-preserving techniques like zero-knowledge proofs if you need to verify compliance without revealing the user's full address to your backend. Projects like Aztec or Tornado Cash Nova explore these concepts. Finally, establish a clear appeals process for false positives, as blockchain analysis is not infallible.

To extend this system, explore integrating transaction monitoring. Services can alert you if a previously cleared user later interacts with a sanctioned address. You could also implement tiered access based on risk scores, allowing low-risk users full access while restricting high-risk wallets to limited functionality. Always stay updated on regulatory guidance from bodies like FATF and consult with legal experts to ensure your flow meets specific jurisdictional requirements like the EU's MiCA regulation.

The code patterns shown here are a starting point. As the regulatory landscape evolves, so must your compliance integration. Treat it as a core, living component of your dApp's architecture. For further learning, review the documentation for Chainalysis API, TRM Labs API, and consider the compliance modules available in web3 development frameworks like OpenZeppelin Defender.

How to Implement User Onboarding with Embedded Compliance | ChainScore Guides