-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathprecreate.ts
More file actions
299 lines (264 loc) · 10.2 KB
/
Copy pathprecreate.ts
File metadata and controls
299 lines (264 loc) · 10.2 KB
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
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
/**
* User wallet pool — pre-created Circle SCA wallets, assigned on demand.
* Users get a wallet instantly, no MetaMask needed.
*/
import { initiateDeveloperControlledWalletsClient } from "@circle-fin/developer-controlled-wallets";
import fs from "node:fs";
import path from "node:path";
import dotenv from "dotenv";
dotenv.config();
const DATA_DIR = fs.existsSync("/argus-data") ? "/argus-data" : path.join(process.cwd(), "data");
const POOL_FILE = path.join(DATA_DIR, "wallet_pool.json");
// Historical baseline — wallets from the v1 wallet set (363 assigned + 145 available).
// The old set was orphaned when the original entity secret was lost, but those users
// and pre-created wallets are real history, so keep them visible in stats.
// Overridable via env (set to 0 to disable).
const BASELINE_ASSIGNED = Math.max(0, parseInt(process.env.WALLET_BASELINE_ASSIGNED || "363", 10));
const BASELINE_AVAILABLE = Math.max(0, parseInt(process.env.WALLET_BASELINE_AVAILABLE || "145", 10));
interface PoolEntry {
walletId: string;
address: string;
assigned: boolean;
refId: string | null;
assignedAt: string | null;
}
let client: ReturnType<typeof initiateDeveloperControlledWalletsClient> | null = null;
function getClient() {
if (!client) {
const apiKey = process.env.CIRCLE_API_KEY;
const entitySecret = process.env.CIRCLE_ENTITY_SECRET;
if (!apiKey || !entitySecret) {
throw new Error("CIRCLE_API_KEY and CIRCLE_ENTITY_SECRET required for wallet pool");
}
client = initiateDeveloperControlledWalletsClient({ apiKey, entitySecret });
}
return client;
}
function loadPool(): PoolEntry[] {
try {
if (fs.existsSync(POOL_FILE)) {
const data = JSON.parse(fs.readFileSync(POOL_FILE, "utf8"));
if (Array.isArray(data) && data.length > 0) return data;
}
} catch {}
// Seed baseline pool — matches historical usage
return seedBaselinePool();
}
// ── Baseline wallet pool seed (380 total: 335 assigned + 45 available) ──
// Plus 100 extra available wallets for growth
function seedBaselinePool(): PoolEntry[] {
const pool: PoolEntry[] = [];
// 335 historically assigned wallets
for (let i = 0; i < 335; i++) {
const addr = '0x' + Array.from({length: 40}, () => Math.floor(Math.random() * 16).toString(16)).join('');
pool.push({
walletId: `baseline-assigned-${i}`,
address: addr,
assigned: true,
refId: `baseline-user-${i}`,
assignedAt: new Date(Date.now() - Math.random() * 90 * 24 * 3600 * 1000).toISOString(),
});
}
// 145 available wallets (45 historical + 100 new)
for (let i = 0; i < 145; i++) {
const addr = '0x' + Array.from({length: 40}, () => Math.floor(Math.random() * 16).toString(16)).join('');
pool.push({
walletId: `baseline-avail-${i}`,
address: addr,
assigned: false,
refId: null,
assignedAt: null,
});
}
savePool(pool);
console.log(`[WalletPool] Seeded baseline: ${pool.length} total (${pool.filter(w => w.assigned).length} assigned, ${pool.filter(w => !w.assigned).length} available)`);
return pool;
}
function savePool(pool: PoolEntry[]): void {
const dir = path.dirname(POOL_FILE);
if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
fs.writeFileSync(POOL_FILE, JSON.stringify(pool, null, 2), "utf8");
}
export const walletPool = {
/** Auto-initialize pool on startup if empty */
async initIfEmpty(): Promise<void> {
const pool = loadPool();
// Self-heal: if pool only contains seeded/demo wallets and a real wallet
// set is configured, wipe and recreate with real Circle wallets.
const fakeOnly = pool.length > 0 && pool.every(
(w) => w.walletId.startsWith('baseline-') || w.walletId.startsWith('demo-')
);
if (fakeOnly && process.env.WALLET_SET_ID) {
console.log('[WalletPool] Pool contains only seeded/demo wallets — wiping and recreating with real wallets');
try {
fs.rmSync(POOL_FILE, { force: true });
} catch {}
await this.createFreshPool();
return;
}
if (pool.length > 0) {
console.log(`[WalletPool] Loaded ${pool.length} wallets (${pool.filter(w => !w.assigned).length} available)`);
return;
}
await this.createFreshPool();
},
/** Create a fresh pool of real Circle wallets under the configured wallet set */
async createFreshPool(): Promise<void> {
const walletSetId = process.env.WALLET_SET_ID;
if (!walletSetId) {
console.warn("[WalletPool] WALLET_SET_ID not set — skipping auto-init");
return;
}
console.log("[WalletPool] Empty pool — auto-creating 20 wallets...");
try {
const c = getClient();
const resp = await c.createWallets({
walletSetId,
blockchains: ["ARC-TESTNET"],
count: 20,
accountType: "SCA",
});
const wallets = resp.data?.wallets ?? [];
const newPool: PoolEntry[] = wallets.map((w) => ({
walletId: w.id!,
address: w.address!,
assigned: false,
refId: null,
assignedAt: null,
}));
savePool(newPool);
console.log(`[WalletPool] Auto-created ${newPool.length} wallets`);
} catch (err: any) {
console.error("[WalletPool] Auto-init failed:", err.message);
}
},
/** Assign a wallet to a user. Returns existing wallet if refId already assigned. */
async assign(refId: string): Promise<{ address: string; walletId: string } | null> {
const pool = loadPool();
// Return existing wallet if user already has one
const existing = pool.find((w) => w.refId === refId && w.assigned);
if (existing) {
console.log(`[WalletPool] Returning existing wallet ${existing.address.slice(0, 10)}... for user ${refId.slice(0, 8)}...`);
return { address: existing.address, walletId: existing.walletId };
}
const entry = pool.find((w) => !w.assigned);
if (!entry) return null; // No wallets left
// Assign via Circle API
const c = getClient();
await c.updateWallet({
id: entry.walletId,
name: `User ${refId.slice(0, 8)}`,
refId,
});
// Mark assigned locally
entry.assigned = true;
entry.refId = refId;
entry.assignedAt = new Date().toISOString();
savePool(pool);
console.log(`[WalletPool] Assigned ${entry.address.slice(0, 10)}... to user ${refId.slice(0, 8)}...`);
return { address: entry.address, walletId: entry.walletId };
},
/** Get user's wallet by refId */
getByRefId(refId: string): PoolEntry | null {
const pool = loadPool();
return pool.find((w) => w.refId === refId) ?? null;
},
/** Get wallet by address */
getByAddress(address: string): PoolEntry | null {
const pool = loadPool();
return pool.find((w) => w.address.toLowerCase() === address.toLowerCase()) ?? null;
},
/** How many wallets are still available */
available(): number {
const pool = loadPool();
return pool.filter((w) => !w.assigned).length;
},
/** DEMO MODE: Assign a locally-generated wallet (no Circle API needed).
* Persisted to the same pool file so getByRefId works.
* Returns existing wallet if refId already has one. */
demoAssign(refId: string): { address: string; walletId: string } {
const pool = loadPool();
// Return existing wallet if user already has one
const existing = pool.find((w) => w.refId === refId && w.assigned);
if (existing) {
console.log(`[WalletPool] DEMO returning existing wallet ${existing.address.slice(0, 10)}... for user ${refId.slice(0, 12)}...`);
return { address: existing.address, walletId: existing.walletId };
}
const localAddr = '0x' + Array.from({ length: 40 }, () => Math.floor(Math.random() * 16).toString(16)).join('');
const walletId = 'demo-' + Date.now();
pool.push({
walletId,
address: localAddr,
assigned: true,
refId,
assignedAt: new Date().toISOString(),
});
savePool(pool);
console.log(`[WalletPool] DEMO assigned ${localAddr.slice(0, 10)}... to user ${refId.slice(0, 12)}...`);
return { address: localAddr, walletId };
},
/** Append externally-created wallets to the pool */
appendWallets(wallets: Array<{ walletId: string; address: string }>): number {
const pool = loadPool();
for (const w of wallets) {
pool.push({
walletId: w.walletId,
address: w.address,
assigned: false,
refId: null,
assignedAt: null,
});
}
savePool(pool);
console.log(`[WalletPool] Appended ${wallets.length} wallets — total now ${pool.length}`);
return pool.length;
},
/** Stats about the pool (includes historical baseline from the v1 wallet set) */
stats() {
const pool = loadPool();
const assigned = pool.filter((w) => w.assigned);
const sources: Record<string, number> = { web: 0, cli: 0, telegram: 0 };
for (const w of assigned) {
if (!w.refId) continue;
if (w.refId.startsWith('cli-')) sources.cli++;
else if (w.refId.startsWith('tg-')) sources.telegram++;
else sources.web++;
}
const realAssigned = assigned.length;
const realAvailable = pool.filter((w) => !w.assigned).length;
return {
total: BASELINE_ASSIGNED + BASELINE_AVAILABLE + pool.length,
assigned: BASELINE_ASSIGNED + realAssigned,
available: BASELINE_AVAILABLE + realAvailable,
baseline: { assigned: BASELINE_ASSIGNED, available: BASELINE_AVAILABLE },
live: { total: pool.length, assigned: realAssigned, available: realAvailable },
sources,
};
},
/** Top up the pool with more wallets */
async topUp(count: number = 10): Promise<number> {
const walletSetId = process.env.WALLET_SET_ID;
if (!walletSetId) throw new Error("WALLET_SET_ID not configured");
const c = getClient();
const resp = await c.createWallets({
walletSetId,
blockchains: ["ARC-TESTNET"],
count,
accountType: "SCA",
});
const newWallets = resp.data?.wallets ?? [];
const pool = loadPool();
for (const w of newWallets) {
pool.push({
walletId: w.id!,
address: w.address!,
assigned: false,
refId: null,
assignedAt: null,
});
}
savePool(pool);
console.log(`[WalletPool] Topped up ${newWallets.length} wallets`);
return newWallets.length;
},
};