-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.ts
157 lines (135 loc) · 4.34 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
import { RunesSDK } from '../../src/typescript/sdk';
import { WebSocketClientService } from '../../src/services/websocket/websocket.client.service';
// Initialize SDK for CEX usage
class CexIntegrationExample {
private sdk: RunesSDK;
private depositAddresses: Map<string, string> = new Map();
constructor() {
this.sdk = new RunesSDK({
rpcUrl: 'https://mempool.space/api',
wsUrl: 'wss://mempool.space/api/ws'
});
}
// Example 1: Track Rune token deposits
async trackDeposits(tokenName: string, depositAddress: string) {
this.depositAddresses.set(depositAddress, tokenName);
// Connect to WebSocket
await this.sdk.connect();
// Listen for transactions
this.sdk.on('transaction', async (tx) => {
const token = this.depositAddresses.get(tx.to);
if (token === tokenName) {
// Check confirmations
const confirmations = await this.sdk.getConfirmations(tx.id);
// Process deposit after 3 confirmations
if (confirmations >= 3) {
console.log('Deposit confirmed:', {
token: tokenName,
amount: tx.amount,
txId: tx.id,
from: tx.from,
to: tx.to
});
// Here you would typically:
// 1. Update user balance in your database
// 2. Notify user about successful deposit
// 3. Move funds to cold storage if needed
}
}
});
}
// Example 2: Monitor multiple addresses
async monitorBalances(addresses: string[]) {
try {
const balances = await Promise.all(
addresses.map(async (addr) => {
const balance = await this.sdk.getRuneBalance(addr);
return {
address: addr,
balance: balance,
timestamp: new Date().toISOString()
};
})
);
return balances;
} catch (error) {
console.error('Error monitoring balances:', error);
throw error;
}
}
// Example 3: Handle withdrawals
async processWithdrawal(
tokenName: string,
fromAddress: string,
toAddress: string,
amount: number
) {
try {
// 1. Verify balance before withdrawal
const balance = await this.sdk.getRuneBalance(fromAddress);
if (balance < amount) {
throw new Error('Insufficient balance');
}
// 2. Process withdrawal
const tx = await this.sdk.sendRunes(tokenName, toAddress, amount);
// 3. Monitor transaction confirmations
let confirmations = 0;
while (confirmations < 3) {
await new Promise(resolve => setTimeout(resolve, 1000)); // Wait 1 second
confirmations = await this.sdk.getConfirmations(tx.id);
}
return {
success: true,
txId: tx.id,
confirmations: confirmations
};
} catch (error) {
console.error('Withdrawal failed:', error);
throw error;
}
}
// Example 4: Error handling and reconnection
private setupErrorHandling() {
this.sdk.on('error', async (error) => {
console.error('WebSocket error:', error);
// Attempt to reconnect
try {
await this.sdk.connect();
} catch (reconnectError) {
console.error('Reconnection failed:', reconnectError);
}
});
}
// Example 5: Batch balance updates
async batchUpdateBalances(userBalances: Map<string, number>) {
const updates: Promise<void>[] = [];
for (const [address, expectedBalance] of userBalances.entries()) {
updates.push(
(async () => {
const actualBalance = await this.sdk.getRuneBalance(address);
if (actualBalance !== expectedBalance) {
console.log('Balance mismatch:', {
address,
expected: expectedBalance,
actual: actualBalance
});
// Update your database with actual balance
}
})()
);
}
await Promise.all(updates);
}
}
// Usage example
async function main() {
const cex = new CexIntegrationExample();
// Start tracking deposits
await cex.trackDeposits('DOG', 'deposit-address-1');
// Monitor balances every minute
setInterval(async () => {
const balances = await cex.monitorBalances(['address-1', 'address-2']);
console.log('Current balances:', balances);
}, 60000);
}
main().catch(console.error);