import { AuthenticationClient } from 'auth0';
class ComplianceService {
constructor() {
this.accessToken = null;
this.tokenExpiry = null;
}
// Get or refresh Token
async getAccessToken() {
if (this.accessToken && this.tokenExpiry > Date.now()) {
return this.accessToken;
}
const auth0Client = new AuthenticationClient({
domain: 'dex.asia.auth.chainstream.io',
clientId: process.env.CHAINSTREAM_CLIENT_ID,
clientSecret: process.env.CHAINSTREAM_CLIENT_SECRET
});
const { data } = await auth0Client.oauth.clientCredentialsGrant({
audience: 'https://api.dex.chainstream.io',
scope: 'kyt.read kyt.write'
});
this.accessToken = data.access_token;
// Token usually valid 24 hours, refresh 1 hour early
this.tokenExpiry = Date.now() + (23 * 60 * 60 * 1000);
return this.accessToken;
}
// Deposit compliance check
async checkDeposit(deposit) {
const token = await this.getAccessToken();
// 1. Register transaction
const registerResponse = await fetch('https://api-dex.chainstream.io/v1/kyt/transfer', {
method: 'POST',
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({
network: deposit.network,
asset: deposit.asset,
transferReference: deposit.txHash,
direction: 'received'
})
});
const registered = await registerResponse.json();
// 2. Wait and get risk assessment
const risk = await this.waitForAnalysis(token, registered.externalId);
// 3. Generate decision
const decision = this.makeDecision(risk);
// 4. Record audit
await this.auditLog(deposit, risk, decision);
return decision;
}
async waitForAnalysis(token, transferId, maxAttempts = 10) {
for (let i = 0; i < maxAttempts; i++) {
const response = await fetch(
`https://api-dex.chainstream.io/v1/kyt/transfers/${transferId}/summary`,
{ headers: { 'Authorization': `Bearer ${token}` } }
);
const result = await response.json();
if (result.rating) {
return result;
}
await new Promise(r => setTimeout(r, 3000));
}
throw new Error('Analysis timeout');
}
makeDecision(risk) {
const decisions = {
'SEVERE': {
action: 'FREEZE',
requireSAR: true,
notify: ['[email protected]', '[email protected]']
},
'HIGH': {
action: 'HOLD',
requireReview: true,
holdHours: 24
},
'MEDIUM': {
action: 'PASS',
flagMonitoring: true
},
'LOW': {
action: 'PASS'
}
};
return decisions[risk.rating] || decisions['LOW'];
}
async auditLog(deposit, risk, decision) {
console.log({
timestamp: new Date().toISOString(),
type: 'COMPLIANCE_CHECK',
deposit,
risk,
decision
});
}
}
// Usage example
const compliance = new ComplianceService();
app.post('/deposit/process', async (req, res) => {
const deposit = req.body;
const decision = await compliance.checkDeposit(deposit);
res.json(decision);
});