forked from ussyalfaks/Grainlify-Stellar-Contracts
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprogram-escrow-client.ts
More file actions
640 lines (573 loc) · 19 KB
/
Copy pathprogram-escrow-client.ts
File metadata and controls
640 lines (573 loc) · 19 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
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
import { Contract, SorobanRpc, Keypair } from '@stellar/stellar-sdk';
import { NetworkError, ValidationError, parseContractError, ContractError } from './errors';
import { invokeContract, InvocationConfig } from './invocation';
export interface ProgramEscrowConfig {
/** Deployed ProgramEscrow contract address. */
contractId: string;
/** Soroban RPC endpoint used for reads and transaction submission. */
rpcUrl: string;
/** Stellar network passphrase for the target network. */
networkPassphrase: string;
}
/** Program escrow state returned by contract read methods. */
export interface ProgramData {
/** Application-level program identifier. */
program_id: string;
/** Total funds deposited into the program escrow. */
total_funds: bigint;
/** Remaining spendable balance in the program escrow. */
remaining_balance: bigint;
/** Stellar account authorized to execute payouts. */
authorized_payout_key: string;
/** Historical payout records for the program. */
payout_history: PayoutRecord[];
/** Token contract address used by the program escrow. */
token_address: string;
}
/** Single payout event recorded by the program escrow. */
export interface PayoutRecord {
/** Stellar account that received the payout. */
recipient: string;
/** Payout amount in the contract token's smallest unit. */
amount: bigint;
/** Unix timestamp when the payout was recorded. */
timestamp: number;
}
/** Scheduled release entry for program escrow funds. */
export interface ProgramReleaseSchedule {
/** Unique schedule identifier. */
schedule_id: bigint;
/** Stellar account that should receive the scheduled release. */
recipient: string;
/** Scheduled amount in the contract token's smallest unit. */
amount: bigint;
/** Unix timestamp when the release becomes executable. */
release_timestamp: number;
/** Whether the scheduled release has already been executed. */
released: boolean;
}
/** Configuration for the circuit breaker. */
export interface CircuitBreakerConfig {
/** Count of consecutive errors required to open the circuit. */
failure_threshold: number;
/** Count of consecutive successes required to close the circuit in half-open state. */
success_threshold: number;
/** Maximum number of records in the error log. */
max_error_log: number;
}
/** Possible states for the circuit breaker. */
export type CircuitState = 'Closed' | 'Open' | 'HalfOpen';
/** Current status snapshot of the circuit breaker. */
export interface CircuitBreakerStatus {
/** The state of the circuit breaker. */
state: CircuitState;
/** Number of consecutive failures in closed state. */
failure_count: number;
/** Number of consecutive successes in half-open state. */
success_count: number;
/** Timestamp of the last recorded failure. */
last_failure_timestamp: bigint;
/** Timestamp of when the circuit was opened. */
opened_at: bigint;
}
/** Contract-wide health snapshot returned by health_check(). */
export interface HealthStatus {
is_healthy: boolean;
last_operation: bigint;
total_operations: bigint;
contract_version: string;
}
/** Aggregated monitoring analytics returned by get_monitoring_analytics(). */
export interface ProgramAnalytics {
total_locked: bigint;
total_released: bigint;
total_payouts: number;
active_programs: number;
operation_count: number;
}
/** Lifecycle status of a dispute. */
export type DisputeStatus = 'None' | 'Open' | 'Resolved' | 'Cancelled';
/** Record stored on-chain for an active or historical dispute. */
export interface DisputeRecord {
opened_by: string;
opened_at: number;
reason: string;
status: DisputeStatus;
resolved_by?: string;
resolved_at?: number;
}
/**
* Client for interacting with the ProgramEscrow Soroban contract
*/
export class ProgramEscrowClient {
private contract: Contract;
private server: SorobanRpc.Server;
private config: ProgramEscrowConfig;
private invocationConfig: InvocationConfig;
/**
* Create a client bound to one ProgramEscrow contract and Soroban RPC endpoint.
*/
constructor(config: ProgramEscrowConfig) {
this.config = config;
try {
this.contract = new Contract(config.contractId);
} catch (error) {
// Allow invalid contract IDs for testing purposes
this.contract = null as any;
}
try {
this.server = new SorobanRpc.Server(config.rpcUrl, { allowHttp: true });
} catch (error) {
// Allow server initialization to fail for testing
this.server = null as any;
}
this.invocationConfig = {
server: this.server,
contract: this.contract,
networkPassphrase: config.networkPassphrase,
rpcUrl: config.rpcUrl,
};
}
/**
* Initialize a new program escrow
*/
async initProgram(
programId: string,
authorizedPayoutKey: string,
tokenAddress: string,
sourceKeypair: Keypair
): Promise<ProgramData> {
if (!programId || programId.trim().length === 0) {
throw new ValidationError('Program ID cannot be empty', 'programId');
}
this.validateAddress(authorizedPayoutKey, 'authorizedPayoutKey');
this.validateAddress(tokenAddress, 'tokenAddress');
try {
const result = await this.invokeContract(
'init_program',
[programId, authorizedPayoutKey, tokenAddress],
sourceKeypair
);
return this.parseProgramData(result);
} catch (error) {
throw this.handleError(error);
}
}
/**
* Lock funds into the program escrow
*/
async lockProgramFunds(
from: string,
amount: bigint,
sourceKeypair: Keypair
): Promise<ProgramData> {
if (amount <= 0n) {
throw new ValidationError('Amount must be greater than zero', 'amount');
}
try {
const result = await this.invokeContract(
'lock_program_funds',
[from, amount],
sourceKeypair
);
return this.parseProgramData(result);
} catch (error) {
throw this.handleError(error);
}
}
/**
* Execute batch payouts to multiple recipients
*/
async batchPayout(
recipients: string[],
amounts: bigint[],
sourceKeypair: Keypair
): Promise<ProgramData> {
if (recipients.length === 0) {
throw new ValidationError('Recipients array cannot be empty', 'recipients');
}
if (recipients.length !== amounts.length) {
throw new ValidationError(
'Recipients and amounts arrays must have the same length',
'recipients'
);
}
for (let i = 0; i < amounts.length; i++) {
if (amounts[i] <= 0n) {
throw new ValidationError(
`Amount at index ${i} must be greater than zero`,
'amounts'
);
}
}
for (let i = 0; i < recipients.length; i++) {
this.validateAddress(recipients[i], `recipients[${i}]`);
}
try {
const result = await this.invokeContract(
'batch_payout',
[recipients, amounts],
sourceKeypair
);
return this.parseProgramData(result);
} catch (error) {
throw this.handleError(error);
}
}
/**
* Execute a single payout
*/
async singlePayout(
recipient: string,
amount: bigint,
sourceKeypair: Keypair
): Promise<ProgramData> {
this.validateAddress(recipient, 'recipient');
if (amount <= 0n) {
throw new ValidationError('Amount must be greater than zero', 'amount');
}
try {
const result = await this.invokeContract(
'single_payout',
[recipient, amount],
sourceKeypair
);
return this.parseProgramData(result);
} catch (error) {
throw this.handleError(error);
}
}
/**
* Get program information
*/
async getProgramInfo(): Promise<ProgramData> {
try {
const result = await this.invokeContract('get_program_info', []);
return this.parseProgramData(result);
} catch (error) {
throw this.handleError(error);
}
}
/**
* Get remaining balance
*/
async getRemainingBalance(): Promise<bigint> {
try {
const result = await this.invokeContract('get_remaining_balance', []);
return BigInt(result);
} catch (error) {
throw this.handleError(error);
}
}
/**
* Create a release schedule
*/
async createProgramReleaseSchedule(
recipient: string,
amount: bigint,
releaseTimestamp: number,
sourceKeypair: Keypair
): Promise<ProgramReleaseSchedule> {
this.validateAddress(recipient, 'recipient');
if (amount <= 0n) {
throw new ValidationError('Amount must be greater than zero', 'amount');
}
try {
const result = await this.invokeContract(
'create_program_release_schedule',
[recipient, amount, releaseTimestamp],
sourceKeypair
);
return this.parseReleaseSchedule(result);
} catch (error) {
throw this.handleError(error);
}
}
/**
* Trigger program releases
*/
async triggerProgramReleases(sourceKeypair: Keypair): Promise<number> {
try {
const result = await this.invokeContract(
'trigger_program_releases',
[],
sourceKeypair
);
return Number(result);
} catch (error) {
throw this.handleError(error);
}
}
// ==========================================================================
// Dispute resolution
// ==========================================================================
/** Open a program-wide dispute, blocking all payouts and releases. Admin-only. */
async openDispute(reason: string, sourceKeypair: Keypair): Promise<void> {
try {
await this.invokeContract('open_dispute', [reason], sourceKeypair);
} catch (error) {
throw this.handleError(error);
}
}
/** Resolve the currently open program-wide dispute, re-enabling payouts. Admin-only. */
async resolveDispute(sourceKeypair: Keypair): Promise<void> {
try {
await this.invokeContract('resolve_dispute', [], sourceKeypair);
} catch (error) {
throw this.handleError(error);
}
}
/** Cancel the currently open program-wide dispute, re-enabling payouts. Admin-only. */
async cancelDispute(sourceKeypair: Keypair): Promise<void> {
try {
await this.invokeContract('cancel_dispute', [], sourceKeypair);
} catch (error) {
throw this.handleError(error);
}
}
/** Get the current or most recent program-wide dispute record, if any. */
async getDispute(): Promise<DisputeRecord | undefined> {
try {
const result = await this.invokeContract('get_dispute', []);
return (result ?? undefined) as DisputeRecord | undefined;
} catch (error) {
throw this.handleError(error);
}
}
/** Whether a program-wide dispute is currently open. */
async isDisputed(): Promise<boolean> {
try {
const result = await this.invokeContract('is_disputed', []);
return Boolean(result);
} catch (error) {
throw this.handleError(error);
}
}
/** Whether a global or recipient-scoped dispute currently blocks this recipient. */
async isRecipientDisputed(recipient: string): Promise<boolean> {
this.validateAddress(recipient, 'recipient');
try {
return await this.invokeContract('is_recipient_disputed', [recipient]);
} catch (error) {
throw this.handleError(error);
}
}
/** Whether a global or schedule-scoped dispute currently blocks this release schedule. */
async isScheduleDisputed(scheduleId: bigint): Promise<boolean> {
try {
return await this.invokeContract('is_schedule_disputed', [scheduleId]);
} catch (error) {
throw this.handleError(error);
}
}
// ==========================================================================
// Whitelist management
// ==========================================================================
/** Add or remove an address from the anti-abuse whitelist. Admin-only. */
async setWhitelist(
address: string,
whitelisted: boolean,
sourceKeypair: Keypair
): Promise<void> {
this.validateAddress(address, 'address');
try {
await this.invokeContract('set_whitelist', [address, whitelisted], sourceKeypair);
} catch (error) {
throw this.handleError(error);
}
}
/** Whether an address is currently whitelisted. */
async isWhitelisted(address: string): Promise<boolean> {
this.validateAddress(address, 'address');
try {
return await this.invokeContract('is_whitelisted', [address]);
} catch (error) {
throw this.handleError(error);
}
}
/** Enable or disable whitelist enforcement contract-wide. Admin-only. */
async setWhitelistEnforced(enabled: boolean, sourceKeypair: Keypair): Promise<void> {
try {
await this.invokeContract('set_whitelist_enforced', [enabled], sourceKeypair);
} catch (error) {
throw this.handleError(error);
}
}
// ==========================================================================
// Circuit breaker admin controls
// ==========================================================================
/** Register or rotate the circuit breaker admin address. */
async setCircuitAdmin(
newAdmin: string,
caller: string | null,
sourceKeypair: Keypair
): Promise<void> {
this.validateAddress(newAdmin, 'newAdmin');
try {
await this.invokeContract('set_circuitadmin', [newAdmin, caller], sourceKeypair);
} catch (error) {
throw this.handleError(error);
}
}
/** Reset the circuit breaker (Open -> HalfOpen -> Closed). Circuit-admin only. */
async resetCircuitBreaker(caller: string, sourceKeypair: Keypair): Promise<void> {
this.validateAddress(caller, 'caller');
try {
await this.invokeContract('reset_circuit_breaker', [caller], sourceKeypair);
} catch (error) {
throw this.handleError(error);
}
}
/** Update circuit breaker thresholds. Circuit-admin only. */
async configureCircuitBreaker(
failureThreshold: number,
successThreshold: number,
maxErrorLog: number,
caller: string,
sourceKeypair: Keypair
): Promise<void> {
this.validateAddress(caller, 'caller');
try {
await this.invokeContract(
'configure_circuit_breaker',
[caller, failureThreshold, successThreshold, maxErrorLog],
sourceKeypair
);
} catch (error) {
throw this.handleError(error);
}
}
/** Immediately open the circuit, blocking all payout/release operations. Circuit-admin only. */
async emergencyOpenCircuit(caller: string, sourceKeypair: Keypair): Promise<void> {
this.validateAddress(caller, 'caller');
try {
await this.invokeContract('emergency_open_circuit', [caller], sourceKeypair);
} catch (error) {
throw this.handleError(error);
}
}
/** Get the current circuit breaker status snapshot. */
async getCircuitStatus(): Promise<CircuitBreakerStatus> {
try {
const result = await this.invokeContract('get_circuit_status', []);
return result as CircuitBreakerStatus;
} catch (error) {
throw this.handleError(error);
}
}
// ==========================================================================
// Governance integration
// ==========================================================================
/** Set the governance contract address used for version-gated admin operations. Admin-only. */
async setGovernanceContract(governanceAddress: string, sourceKeypair: Keypair): Promise<void> {
this.validateAddress(governanceAddress, 'governanceAddress');
try {
await this.invokeContract('set_governance_contract', [governanceAddress], sourceKeypair);
} catch (error) {
throw this.handleError(error);
}
}
/** Get the configured governance contract address, if any. */
async getGovernanceContract(): Promise<string | null> {
try {
const result = await this.invokeContract('get_governance_contract', []);
return result as string | null;
} catch (error) {
throw this.handleError(error);
}
}
/** Set the minimum governance contract version required for gated admin operations. Admin-only. */
async setMinGovernanceVersion(minVersion: number, sourceKeypair: Keypair): Promise<void> {
try {
await this.invokeContract('set_min_governance_version', [minVersion], sourceKeypair);
} catch (error) {
throw this.handleError(error);
}
}
/** Get the configured minimum governance version (0 if unset). */
async getMinGovernanceVersion(): Promise<number> {
try {
const result = await this.invokeContract('get_min_governance_version', []);
return Number(result);
} catch (error) {
throw this.handleError(error);
}
}
// ==========================================================================
// Monitoring / analytics
// ==========================================================================
/** Get the current contract health snapshot. */
async healthCheck(): Promise<HealthStatus> {
try {
const result = await this.invokeContract('health_check', []);
return result as HealthStatus;
} catch (error) {
throw this.handleError(error);
}
}
/** Get aggregated monitoring analytics across all programs. */
async getMonitoringAnalytics(): Promise<ProgramAnalytics> {
try {
const result = await this.invokeContract('get_monitoring_analytics', []);
return result as ProgramAnalytics;
} catch (error) {
throw this.handleError(error);
}
}
private validateAddress(address: string, fieldName: string): void {
if (!address || address.trim().length === 0) {
throw new ValidationError(`${fieldName} cannot be empty`, fieldName);
}
// Basic Stellar address validation (starts with G and is 56 chars)
if (!address.match(/^G[A-Z0-9]{55}$/)) {
throw new ValidationError(`${fieldName} is not a valid Stellar address`, fieldName);
}
}
private async invokeContract(
method: string,
args: any[],
sourceKeypair?: Keypair
): Promise<any> {
return invokeContract(
method,
args,
this.invocationConfig,
{
sourceKeypair,
readOnly: !sourceKeypair,
}
);
}
private handleError(error: any): Error {
if (error instanceof ValidationError ||
error instanceof NetworkError ||
error instanceof ContractError) {
return error;
}
// Check if it's a network error first (before parsing as contract error)
if (error.code === 'ECONNREFUSED' || error.code === 'ETIMEDOUT' || error.code === 'ENOTFOUND') {
return new NetworkError(
`Failed to connect to RPC server: ${this.config.rpcUrl}`,
undefined,
error
);
}
if (error.response?.status) {
return new NetworkError(
`RPC request failed with status ${error.response.status}`,
error.response.status,
error
);
}
// Try to parse as contract error
return parseContractError(error);
}
private parseProgramData(result: any): ProgramData {
// Simplified parser - in real implementation would parse XDR
return result as ProgramData;
}
private parseReleaseSchedule(result: any): ProgramReleaseSchedule {
// Simplified parser - in real implementation would parse XDR
return result as ProgramReleaseSchedule;
}
}