elliptic.ts
Overview
The `elliptic.ts` file provides a specialized integration module for interacting with the Elliptic Anti-Money Laundering (AML) API. Its primary purpose is to validate blockchain addresses by assessing their associated risk scores through Elliptic’s AML platform. This validation helps ensure that addresses involved in transactions are not flagged for illicit activities such as fraud or money laundering.
Key features of this file include:
Secure initialization of the Elliptic AML client using API credentials loaded from environment variables.
An address validation method (
validateAddress) that queries Elliptic’s synchronous wallet exposure endpoint.An in-memory caching mechanism to store validation results for 6 hours, minimizing redundant API calls.
Graceful error handling, particularly for addresses not yet processed or unknown to Elliptic.
Risk score thresholding to classify addresses as valid or invalid.
This module is typically utilized by higher-level components such as API controllers within the Proxy API Service to provide a clean and efficient address validation interface.
Detailed Explanation
Constants and Types
ELLIPTIC_API_KEYandELLIPTIC_API_SECRET
Loaded from environment variables, these credentials authenticate API requests to Elliptic. The file enforces their presence at runtime by throwing errors if missing.RISK_SCORE_THRESHOLD
A numeric threshold (default = 1) for risk scores returned by Elliptic. Addresses with a risk score equal to or exceeding this value are considered invalid.CACHE_TTL_MS
Cache time-to-live in milliseconds (6 hours). After this time, cached validation results are automatically invalidated.AddressCache(Type alias)
A partial record mapping blockchain addresses (strings) to boolean validation results (truefor valid,falsefor invalid).Interfaces
WalletResponseandWalletError
Define the expected shapes of successful wallet responses and error responses from the Elliptic API.
Class: Elliptic
The `Elliptic` class encapsulates the interaction with the Elliptic AML service and manages an internal cache of validation results.
Properties
Property | Type | Description |
|---|---|---|
`aml` | `AML` | Instance of Elliptic SDK AML client initialized with API credentials. |
`addressCache` | `AddressCache` | In-memory cache for address validation results. |
Constructor
constructor()
Initializes the
AMLclient with the API key and secret.Initializes an empty
addressCache.
Methods
validateAddress
async validateAddress(address: string): Promise<{ valid: boolean }>
Validates a blockchain address by checking its risk exposure using Elliptic AML API.
Parameters:
address(string): The blockchain address to validate.
Returns:
A Promise resolving to an object
{ valid: boolean }indicating whether the address is considered valid.
Behavior:
Cache Check:
Returns cached result immediately if present.API Request:
Sends a synchronous POST request to/v2/wallet/synchronouswith:{ "subject": { "asset": "holistic", "blockchain": "holistic", "type": "address", "hash": address }, "type": "wallet_exposure" }Risk Score Evaluation:
If the returnedrisk_scoreexists and is greater than or equal toRISK_SCORE_THRESHOLD, caches and returnsvalid: false.Default Validity:
Otherwise, caches and returnsvalid: true.Error Handling:
If the API returns a 404 with error nameNotInBlockchain, the address is assumed valid and cached as such.Cache Expiry:
Sets a timer to delete the cached entry after 6 hours.
Throws:
Propagates any unexpected errors from the API call.
Usage Example
const elliptic = new Elliptic();
async function checkAddress(address: string) {
try {
const result = await elliptic.validateAddress(address);
if (result.valid) {
console.log(`Address ${address} is valid.`);
} else {
console.log(`Address ${address} is invalid due to high risk.`);
}
} catch (error) {
console.error('Validation error:', error);
}
}
Important Implementation Details
Caching Mechanism:
The class caches validation results keyed by address to reduce calls to the Elliptic API. Cached entries are deleted after 6 hours usingsetInterval. This improves performance and reduces API usage costs.Risk Score Thresholding:
The validation logic is based on comparing the risk score returned by Elliptic against a threshold (RISK_SCORE_THRESHOLD), which is currently set to 1.Error Handling for Unknown Addresses:
If Elliptic does not have information on the address (HTTP 404 withNotInBlockchain), the system assumes the address is valid. This design delegates responsibility for further validation to the client, avoiding false negatives.Synchronous API Call:
The validation uses Elliptic’s synchronous wallet exposure endpoint, which returns immediate results suitable for real-time validation scenarios.Environment Variables Enforcement:
The file immediately throws errors if the required API credentials are missing, preventing misconfigured deployments.
Interaction with Other System Components
Proxy API Controller (
controller.ts):
TheEllipticclass is used by API controllers to implement the/api/v1/validate/{address}endpoint, which clients call to validate blockchain addresses.Caching Strategy Complement:
Works alongside other caching mechanisms in the Proxy API Service to optimize external API usage.Elliptic SDK Dependency:
Relies on theelliptic-sdkpackage for communicating with the Elliptic AML API, abstracting lower-level HTTP client details.Environment Configuration:
Depends on environment variables for API keys, which are typically set in the deployment environment or.envfiles managed by the overall application.
Class Diagram
classDiagram
class Elliptic {
-aml: AML
-addressCache: AddressCache
+constructor()
+validateAddress(address: string): Promise<{ valid: boolean }>
}
Summary
`elliptic.ts` is a focused module for blockchain address validation by leveraging Elliptic’s AML API. It provides a robust, cached, and fault-tolerant mechanism to assess address risk, facilitating compliance and security for blockchain-based applications within the broader Proxy API Service architecture.
By abstracting the Elliptic AML integration into a dedicated class, the system promotes clean separation of concerns, allowing higher-level components to easily incorporate address validation without exposing sensitive API details or managing caching logic.
Additional Notes
Extensibility:
The class design allows easy extension, such as adding more granular risk assessment or supporting additional Elliptic API endpoints.Potential Improvement:
The cache cleanup currently usessetIntervalinside thefinallyblock; depending on usage patterns, this might create multiple timers. A more robust cache eviction strategy or a dedicated caching library could improve resource management.Security:
API keys must be securely stored and managed. The immediate checks on environment variables help prevent runtime misconfiguration.
This documentation should enable developers and system integrators to understand, maintain, and utilize the `elliptic.ts` module effectively within the larger Proxy API Service ecosystem.