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

Setting Up Real-Time Sanctions Screening for Blockchain Transactions

A technical guide for developers to build a system that screens wallet addresses against global sanctions lists before transaction settlement, covering oracle integration, smart contract logic, and false positive management.
Chainscore © 2026
introduction
DEVELOPER GUIDE

Setting Up Real-Time Sanctions Screening for Blockchain Transactions

A technical guide for developers to implement real-time sanctions screening for on-chain transactions using public APIs and smart contract logic.

Real-time sanctions screening is a critical compliance layer for blockchain applications, allowing protocols to check wallet addresses against global sanctions lists before processing transactions. Unlike traditional finance, blockchain's pseudonymity and immutability make post-transaction compliance nearly impossible, elevating the importance of preemptive screening. This process typically involves querying an external data provider's API, such as Chainalysis, TRM Labs, or Elliptic, to verify if a participating address is flagged. For developers, integrating this check means adding a validation step that can halt a transfer, mint, or swap if a sanctioned entity is detected, thereby mitigating regulatory risk and protecting the protocol's integrity.

The core technical implementation involves creating an off-chain oracle or middleware service that interfaces with sanctions data providers. A common pattern is to use a serverless function (e.g., AWS Lambda, Google Cloud Function) that receives an address via an API call, queries the provider's API with the necessary authentication, and returns a simple boolean or risk score. This service must then be integrated into your application's transaction flow. For smart contract interactions, you can use an oracle network like Chainlink to fetch the off-chain verification result on-chain, or design a system where a privileged admin address can pause transactions based on off-chain alerts. The key is ensuring the screening happens with minimal latency to not degrade the user experience.

Here is a simplified Node.js example using the axios library to query a hypothetical sanctions API endpoint before allowing a function to proceed:

javascript
const axios = require('axios');
const API_KEY = 'your_sanctions_api_key';

async function screenAddress(address) {
  try {
    const response = await axios.get(
      `https://api.sanctionsprovider.com/v1/check/${address}`,
      { headers: { 'Authorization': `Bearer ${API_KEY}` } }
    );
    // Assume API returns { isSanctioned: boolean }
    return !response.data.isSanctioned; // Returns true if address is CLEAR
  } catch (error) {
    console.error('Screening failed:', error);
    return false; // Fail-closed: block transaction on error
  }
}
// Use in your route or contract interaction
const isClear = await screenAddress('0x742d35Cc6634C0532925a3b844Bc9e...');
if (!isClear) throw new Error('Address is sanctioned.');

This fail-closed logic is crucial—if the screening service is unavailable, the transaction should be blocked by default to maintain compliance.

When architecting your system, consider data freshness, cost, and coverage. Sanctions lists are updated frequently (OFAC SDN lists update daily), so cached results should have a short TTL. API calls can be expensive, so implement caching for addresses that interact repeatedly. Ensure your provider covers the relevant jurisdictions and blockchain networks (Ethereum, Solana, etc.) your application supports. For decentralized applications, you might also explore on-chain attestation registries like Ethereum Attestation Service (EAS), where trusted entities can publish attestations about an address's status, allowing smart contracts to perform permissioned checks directly on-chain without a centralized oracle.

Ultimately, implementing real-time screening is a balance between security, cost, and usability. Start by identifying the critical transaction entry points in your dApp—such as deposit functions, token minting, or NFT marketplace listings—and gate them with a screening check. Document your compliance logic clearly for auditors and users. As regulatory scrutiny increases, proactive integration of these tools is becoming a standard requirement for any serious blockchain application handling value.

prerequisites
SETUP GUIDE

Prerequisites and System Architecture

Before implementing a real-time sanctions screening system, you need the right infrastructure, data sources, and development environment. This section outlines the core components and technical requirements.

A real-time sanctions screening system for blockchain transactions requires a modular architecture. At its core, you need a data ingestion layer to pull transaction data from nodes or indexers, a screening engine to process this data against watchlists, and an alerting/action layer to flag or block suspicious activity. This is often deployed as a microservices-based system using containers (Docker) and orchestration tools like Kubernetes for scalability and resilience. The system must handle high-throughput, low-latency processing to screen transactions before they are confirmed on-chain.

Your primary data source will be a blockchain node (e.g., a Geth or Erigon client for Ethereum) or a high-performance indexer like The Graph or Covalent. You'll need to subscribe to pending transaction pools and new block events. For the screening logic, you require access to updated sanctions lists, such as the OFAC SDN List and other compliance databases. These lists must be parsed and stored in a query-optimized database like PostgreSQL or Redis for fast pattern matching against transaction from, to, and inputData fields.

Development prerequisites include proficiency in a backend language like Go, Node.js, or Python, and familiarity with Web3 libraries such as web3.js, ethers.js, or web3.py. You will also need to understand smart contract ABIs to decode transaction inputs for more granular screening. Setting up a local testnet (e.g., Hardhat, Anvil) is essential for development and testing without spending real funds. Environment variables should manage sensitive data like node RPC URLs and API keys for commercial sanctions data providers.

A critical architectural decision is where to integrate the screening. For pre-execution screening, you can use a transaction simulation service like Tenderly or OpenZeppelin Defender to analyze transactions in a mempool or sentinel. For post-execution compliance, you screen confirmed blocks and maintain an internal ledger of flagged addresses. The system should log all screening events with a unique ID for audit trails and reporting, which is a key regulatory requirement.

key-concepts-text
COMPLIANCE PRIMER

Key Concepts: Sanctions Lists and On-Chain Verification

Understanding the technical foundations of sanctions screening is critical for building compliant DeFi protocols and Web3 applications. This guide explains how sanctions lists work and the methods for verifying them on-chain.

Sanctions lists are government-issued databases that identify individuals, entities, and wallet addresses prohibited from engaging in financial transactions. Key global lists include the Office of Foreign Assets Control (OFAC) Specially Designated Nationals (SDN) List, the European Union Consolidated List, and the UK Sanctions List. For blockchain, the most relevant is OFAC's list, which includes thousands of cryptocurrency addresses associated with sanctioned entities like ransomware groups and terrorist organizations. Real-time screening involves checking transaction participants against these lists before allowing a transfer to finalize.

On-chain verification presents unique challenges compared to traditional finance. Protocols must decide between off-chain screening (using an API to check an address before submitting a transaction) and on-chain enforcement (embedding logic within a smart contract). Off-chain screening, used by services like Chainalysis and TRM Labs, is faster but relies on external trust. On-chain methods, such as integrating a registry contract that holds a Merkle root of the sanctions list, provide cryptographic guarantees but introduce gas costs and latency. The choice depends on the application's security model and performance requirements.

A common on-chain pattern uses a Merkle proof for verification. A trusted entity maintains an off-chain database of sanctioned addresses and periodically publishes a Merkle root to a smart contract. To verify an address, a user submits a Merkle proof demonstrating the address is not in the sanctioned tree. The contract verifies the proof against the stored root. This method keeps the list private and efficient, as only the root is stored on-chain. However, it requires users to fetch proofs from an oracle or indexer, adding complexity to the transaction flow.

For developers, implementing basic screening starts with accessing list data. OFAC's SDN list is available as an XML or CSV download. Parsing this for Ethereum addresses involves filtering for the "Digital Currency Address" identifier. Here's a simplified Node.js example using axios and ethers to check an address:

javascript
const OFAC_URL = 'https://www.treasury.gov/ofac/downloads/sdn.xml';
async function isSanctioned(address) {
  const response = await axios.get(OFAC_URL);
  // Parse XML, extract digital currency addresses
  const sanctionedAddresses = parseOFACXml(response.data);
  return sanctionedAddresses.includes(address.toLowerCase());
}

Remember, this is for demonstration; production systems require robust parsing, caching, and updating mechanisms.

Key considerations for a production system include data freshness, privacy, and decentralization. Lists update frequently, so systems need a reliable update mechanism (e.g., Chainlink Oracles or a multisig-controlled contract upgrade). Privacy is a concern: simply querying an external API can leak user data. Techniques like zero-knowledge proofs (ZKPs) allow a user to prove an address is not sanctioned without revealing the address itself, though this is computationally intensive. Ultimately, the goal is to achieve compliance without compromising the censorship-resistant ethos of blockchain, a balance that defines modern on-chain compliance engineering.

CRITICAL INFRASTRUCTURE

Oracle Provider Comparison for Sanctions Data

A comparison of leading oracle solutions for integrating real-time sanctions and AML data into on-chain applications.

Feature / MetricChainlinkPyth NetworkAPI3

Primary Data Type

Off-chain API aggregation

Financial market & institutional data

First-party oracles (dAPIs)

Sanctions List Coverage

OFAC SDN, EU, UN, others

Limited native support

Custom API integration

Update Frequency

On-demand or scheduled (minute-level)

Sub-second for price feeds

Configurable by dAPI owner

Data Freshness SLA

< 60 seconds

< 500 milliseconds

Depends on underlying API

Decentralization Model

Decentralized oracle network (DON)

Publisher-based with on-chain aggregation

First-party node operators

On-chain Verification

zk-proofs (DECO) for select feeds

Attestations from publishers

OEV auctions for data integrity

Integration Complexity

Medium (requires consumer contract)

Low (direct price feed consumption)

High (requires dAPI setup/management)

Typical Cost per Call

$0.10 - $1.00+ (LINK)

Free for public feeds, premium costs vary

Gas fees + API provider costs

step1-integrate-oracle
SETTING UP REAL-TIME SANCTIONS SCREENING

Step 1: Integrate an Oracle for Sanctions Data

This guide explains how to integrate a decentralized oracle to fetch real-time sanctions data for on-chain screening, a foundational step for regulatory compliance in DeFi and blockchain applications.

A decentralized oracle is essential for bringing off-chain sanctions lists, like the OFAC SDN list, onto the blockchain. Services like Chainlink Functions or Pyth provide a secure, reliable bridge for smart contracts to request and receive this external data. The core mechanism involves an on-chain smart contract making a request, which is fulfilled by a decentralized network of node operators that fetch, verify, and deliver the data on-chain. This ensures the data's integrity and availability without relying on a single point of failure.

To implement this, you first deploy a consumer contract that inherits from the oracle's client library, such as FunctionsClient.sol for Chainlink. Your contract must define a request function that specifies the data source (e.g., an API endpoint for a sanctions provider) and a callback function to handle the response. The request is typically sent by calling sendRequest() with encrypted secrets for API keys, the JavaScript source code for the fetch operation, and the list of arguments. The oracle network executes this code off-chain and returns the result to your callback.

For sanctions screening, the source code within your request would call a compliant data provider's API. For example, you might integrate with Chainalysis or Elliptic to check if a given address parameter appears on a sanctions list. The JavaScript source executed by the nodes would look something like:

javascript
const apiResponse = await Functions.makeHttpRequest({
  url: `https://api.sanctionsprovider.com/v1/check/${args[0]}`,
  headers: {'Authorization': `Bearer ${secrets.apiKey}`}
});
return Functions.encodeString(apiResponse.data.isSanctioned);

The returned boolean is then decoded in your callback.

Upon receiving the response in the callback function, your contract must implement the core logic. This typically involves storing the result in a mapping (e.g., mapping(address => bool) public isSanctioned;) and potentially triggering an action. For compliance, this action could be pausing a transaction, freezing funds, or emitting an event for off-chain monitoring. It's critical to handle potential oracle downtime or false positives by implementing fallback mechanisms or multi-source data aggregation to ensure robustness.

Key considerations for production include cost management, as each oracle request consumes LINK tokens and gas, and data freshness, requiring regular update cycles. You should also assess the legal and technical reliability of your chosen sanctions data provider. By completing this integration, you establish a real-time, automated screening layer that can be invoked before any token transfer or user onboarding, forming the backbone of a compliant DeFi application.

step2-design-screening-contract
CORE ARCHITECTURE

Step 2: Design the Screening Smart Contract

This step involves building the on-chain logic that will automatically screen transaction participants against sanctions lists before execution.

The core of a real-time sanctions screening system is a smart contract that acts as a policy enforcer. This contract must be deployed on the blockchain where you want to screen transactions, such as Ethereum, Polygon, or Arbitrum. Its primary function is to intercept relevant function calls—like transfer() or swap()—and query an oracle or verifiable data source to check if the involved addresses (sender or recipient) are on a sanctions list. The contract should store a configurable list of authorized data providers, often managed by a multi-signature wallet or DAO for decentralized governance.

A critical design pattern is the check-effects-interactions model adapted for compliance. First, the contract checks the sanction status via a trusted oracle like Chainlink or a custom zk-proof verifier. Then, based on the result, it applies the effects by either allowing the transaction to proceed or reverting it. For flexibility, you might implement a pausable mechanism that can temporarily halt all screening during upgrades or emergencies. The contract's state should also log screening events for audit trails, emitting logs with details like the screened address, the data source used, the timestamp, and the pass/fail result.

Here is a simplified Solidity function skeleton illustrating the core logic:

solidity
function screenedTransfer(address to, uint256 amount) external {
    require(!sanctionsOracle.isSanctioned(msg.sender), "Sender sanctioned");
    require(!sanctionsOracle.isSanctioned(to), "Recipient sanctioned");
    // If checks pass, execute the transfer
    _transfer(msg.sender, to, amount);
    emit ScreeningPerformed(msg.sender, to, true, block.timestamp);
}

The sanctionsOracle would be an interface to an external adapter that fetches and returns the compliance status. Using a modular oracle design separates concerns, allowing you to update the data source without redeploying the core screening logic.

Security considerations are paramount. The contract must guard against Oracle manipulation and front-running. Using a decentralized oracle network with multiple nodes reduces single points of failure. For maximum security and privacy, consider integrating zero-knowledge proofs (ZKPs). In this model, an off-chain prover checks the sanctions list and generates a ZK proof that an address is not sanctioned without revealing the address or the list contents. The smart contract only needs to verify the proof on-chain, which is computationally cheap and keeps sensitive data private.

Finally, the contract should include upgrade pathways. Compliance requirements and sanctions lists change frequently. Design your contract using a proxy pattern (like the Transparent Proxy or UUPS) or a modular diamond pattern (EIP-2535) so the screening logic and oracle addresses can be updated without migrating user funds or breaking existing integrations. Thoroughly test all edge cases, including oracle downtime scenarios, using frameworks like Foundry or Hardhat to ensure the system fails securely and predictably under all conditions.

step3-handle-false-positives
HANDLING EXCEPTIONS

Step 3: Implement Logic for False Positives and Appeals

A robust sanctions screening system must account for false positives and provide a clear path for manual review. This step focuses on building the logic to manage and resolve flagged transactions that are not actual violations.

When a transaction is flagged by your screening service (e.g., Chainalysis, TRM Labs, Elliptic), it is a potential match, not a confirmed violation. A false positive occurs when a transaction is incorrectly flagged, often due to partial name matches, VASP addresses, or sanctioned entities interacting with non-sanctioned sub-addresses. Your system's logic must immediately place these flagged transactions into a quarantine state, preventing further automated processing while allowing for human review. This is a critical compliance and risk management control.

The core of your implementation is an appeals and review workflow. Create a secure internal dashboard or integrate with your existing compliance tools where analysts can review the alert. The logic should fetch and display the risk indicators from the screening provider's API, such as the matched name, associated addresses, and risk score. For on-chain context, your system should also pull the transaction details from a node or indexer like Alchemy or QuickNode, showing the full path of funds.

Your code must handle the resolution paths. For a confirmed false positive, the system should whitelist the specific address or transaction hash for a configurable period, ensuring it isn't flagged again for the same reason. This whitelist should be stored securely and checked before the external screening API call to reduce costs and latency. For a true positive (confirmed sanction violation), the logic should trigger a high-priority alert, log the event for reporting, and may initiate a predefined action like freezing funds in a custodial setting.

Consider implementing automated challenge protocols for certain low-risk scenarios. For example, if a flagged address belongs to a known, licensed VASP in a reputable jurisdiction, your logic could automatically verify its status against a registry and resolve the alert without manual intervention. This balance between automation and human oversight is key for scaling compliance operations. Always document every review decision for audit trails.

Finally, structure your logic to be provider-agnostic where possible. Abstract the screening and alert management behind internal interfaces. This allows you to switch screening providers or use multiple providers in parallel without rewriting your core compliance workflow, future-proofing your implementation against changes in the regulatory or vendor landscape.

step4-frontend-integration
IMPLEMENTATION

Step 4: Integrate Screening into a Transaction Flow

This guide details how to integrate real-time sanctions screening into your dApp's transaction flow using Chainscore's API.

Integrating sanctions screening requires intercepting a transaction before it is signed and broadcast to the network. The typical flow involves: generating the unsigned transaction object, extracting the recipient address, calling the screening API, and conditionally proceeding based on the risk score. This check should be performed client-side in the user's wallet context or within a secure backend service to prevent transaction manipulation. For EVM chains, you would screen the to address; for token transfers, you must also screen the token contract if it's a new interaction.

The core integration is a call to the https://api.chainscore.dev/v1/screen/address endpoint. You need to pass the address and the chain ID (e.g., 1 for Ethereum Mainnet). The response includes a risk_score (0-100) and a risk_level (e.g., LOW, HIGH). A common practice is to block transactions with a risk_score above 85 or a risk_level of HIGH. Here's a JavaScript example using fetch:

javascript
async function screenAddress(address, chainId) {
  const response = await fetch('https://api.chainscore.dev/v1/screen/address', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ address, chainId })
  });
  const result = await response.json();
  return result.risk_level === 'HIGH' ? false : true;
}

For a robust user experience, implement clear feedback. If an address is flagged, present a non-dismissible modal or alert explaining that the transaction cannot proceed due to sanctions compliance. Do not simply fail silently. Log the blocked attempt (without personal user data) for your compliance records. For DeFi protocols, this check is crucial before interactions with router contracts or vault deposits. Remember to also screen the msg.sender for inbound transactions if your protocol accepts direct transfers, which can be done via an OpenZeppelin-style _beforeTokenTransfer hook.

Consider gas implications and latency. The API call typically adds 200-500ms. To optimize, you can cache low-risk addresses locally for a short period (5-10 minutes). However, never cache high-risk results. For batch operations, use the https://api.chainscore.dev/v1/screen/addresses/bulk endpoint. Always ensure your integration fails closed: if the screening service is unavailable, you should default to blocking the transaction or pausing the feature, depending on your compliance requirements. This "safe mode" is a regulatory expectation.

Finally, test your integration thoroughly. Use known sanctioned addresses from public lists, like the OFAC Specially Designated Nationals (SDN) list, to verify blocking works. Test with clean addresses to ensure no false positives. Monitor your API usage and error rates in production. This step transforms your dApp from a passive tool into an active participant in global compliance, protecting your users and your project from legal and reputational risk.

IMPLEMENTATION PHASES

Risk Matrix: Sanctions Screening Implementation Risks

Key risks and mitigation strategies for different approaches to integrating real-time sanctions screening into a blockchain transaction flow.

Risk FactorIn-House API IntegrationManaged Screening ServiceHybrid (On-Chain + Off-Chain)

Data Source Latency

High (24-48h update cycles)

Low (< 1h update cycles)

Medium (4-12h for on-chain components)

False Positive Rate

5-15% (typical initial tuning)

1-3% (pre-optimized models)

2-8% (depends on rule weighting)

Integration Complexity

High (requires devops, SRE)

Low (SDK/API-based)

Medium (smart contract + API logic)

Upfront Development Cost

$50k - $200k+

$5k - $20k

$25k - $75k

Ongoing Operational Cost

Variable ($5k-$15k/month)

Predictable ($0.10-$1.00 per screening)

Mixed (gas fees + service fees)

Regulatory Audit Trail

Real-Time Blocking (< 2 sec)

Custodial Risk

None (self-hosted)

Medium (third-party dependency)

Low (failover to on-chain)

OFAC SDN List Coverage

100% (manual updates)

100% + 30+ global lists

100% + programmable additions

DEVELOPER TROUBLESHOOTING

Frequently Asked Questions (FAQ)

Common questions and solutions for integrating real-time sanctions screening into blockchain applications. Covers API usage, data handling, and compliance logic.

The Office of Foreign Assets Control (OFAC) is a U.S. regulator that maintains lists of sanctioned individuals, entities, and cryptocurrency addresses (the SDN List). Screening is legally required for U.S. persons and entities to avoid facilitating transactions with blocked parties. For dApps, this means checking both the sender and recipient addresses against the SDN List before a transaction is finalized. Failure to screen can result in severe penalties, including fines and loss of banking relationships. Integrating screening at the smart contract or RPC layer helps projects maintain compliance and mitigate legal risk in DeFi, NFTs, and cross-chain bridges.

conclusion
IMPLEMENTATION SUMMARY

Conclusion and Next Steps

You have now configured a foundational system for real-time sanctions screening on blockchain transactions. This guide covered the core components: connecting to a node, sourcing sanctions data, and implementing a basic screening logic.

The architecture you've built provides a critical security layer, but it is a starting point. In production, you must address several advanced considerations. False positive management is paramount; overly broad screening can block legitimate users. Implement a risk-scoring system instead of binary blocking, and create an appeals process. Data freshness is another challenge; sanctions lists update frequently. Automate periodic pulls from your data provider's API and consider using webhook notifications for critical updates to maintain screening accuracy.

To enhance your system, explore integrating with specialized blockchain analytics providers like Chainalysis, Elliptic, or TRM Labs. These services offer more sophisticated risk scores by analyzing transaction patterns, clustering addresses, and tracking fund flows beyond simple list matching. Their APIs can provide context such as an address's association with mixers, stolen funds, or high-risk DeFi protocols, allowing for more nuanced compliance decisions.

For developers looking to extend this system, consider these next technical steps:

  • Implement asynchronous screening for high-throughput applications to avoid blocking the main transaction flow.
  • Add multi-chain support by integrating with nodes or indexers for other EVM chains (Polygon, Arbitrum) and non-EVM chains (Solana, Cosmos).
  • Develop an admin dashboard to visualize screening results, manage flagged transactions, and adjust risk parameters.
  • Automate reporting for regulatory compliance by logging all screened transactions and decisions to a secure database.

The regulatory landscape for blockchain transactions is evolving rapidly. Stay informed about guidelines from bodies like the Financial Action Task Force (FATF) and updates to the Office of Foreign Assets Control (OFAC) Specially Designated Nationals (SDN) list. Compliance is not a one-time setup but an ongoing process. Regularly audit your screening logic, test with known high-risk addresses, and ensure your practices align with the legal requirements of the jurisdictions you operate in.

Finally, remember that technology is only one part of the solution. A robust compliance program also requires clear internal policies, trained personnel, and executive oversight. Use the automated screening system you've built as a tool to empower your compliance team, not replace their judgment. By combining real-time data, intelligent code, and human expertise, you can build a secure and compliant platform for the future of finance.