forked from ussyalfaks/Grainlify-Stellar-Contracts
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbounty-escrow-client.ts
More file actions
1505 lines (1385 loc) · 45.1 KB
/
Copy pathbounty-escrow-client.ts
File metadata and controls
1505 lines (1385 loc) · 45.1 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
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { Contract, SorobanRpc, Keypair } from '@stellar/stellar-sdk';
import { NetworkError, ValidationError, parseContractError, ContractError } from './errors';
import { invokeContract, InvocationConfig } from './invocation';
export interface BountyEscrowConfig {
/** Deployed BountyEscrow contract address. */
contractId: string;
/** Soroban RPC endpoint used for reads and transaction submission. */
rpcUrl: string;
/** Stellar network passphrase for the target network. */
networkPassphrase: string;
}
/** Input item for batch-locking a bounty escrow. */
export interface LockFundsItem {
/** Application-level bounty identifier. */
bounty_id: bigint;
/** Stellar account that deposits the escrowed funds. */
depositor: string;
/** Amount to lock, expressed in the contract token's smallest unit. */
amount: bigint;
/** Unix timestamp after which the bounty may become refundable. */
deadline: number;
}
/** Input item for batch-releasing a bounty escrow. */
export interface ReleaseFundsItem {
/** Application-level bounty identifier. */
bounty_id: bigint;
/** Stellar account that should receive the released bounty funds. */
contributor: string;
}
/** On-chain lifecycle states for a bounty escrow. */
export type EscrowStatus = 'Locked' | 'Released' | 'Refunded' | 'PartiallyRefunded';
/** Supported refund modes for admin-approved refunds. */
export type RefundMode = 'Full' | 'Partial';
/** Historical refund record attached to an escrow. */
export interface RefundRecord {
/** Refunded amount in the contract token's smallest unit. */
amount: bigint;
/** Stellar account that received the refund. */
recipient: string;
/** Unix timestamp when the refund was executed. */
timestamp: number;
/** Whether the refund closed the escrow or returned a partial amount. */
mode: RefundMode;
}
/** Pending claim authorization for a bounty recipient. */
export interface ClaimRecord {
/** Application-level bounty identifier. */
bounty_id: bigint;
/** Stellar account authorized to claim the bounty. */
recipient: string;
/** Claimable amount in the contract token's smallest unit. */
amount: bigint;
/** Unix timestamp when the claim authorization expires. */
expires_at: number;
/** Whether the authorized claim has already been consumed. */
claimed: boolean;
}
/** Current state for one bounty escrow. */
export interface Escrow {
/** Stellar account that deposited the escrow funds. */
depositor: string;
/** Original locked amount in the contract token's smallest unit. */
amount: bigint;
/** Remaining escrow balance after releases or partial refunds. */
remaining_amount: bigint;
/** Current on-chain escrow lifecycle state. */
status: EscrowStatus;
/** Unix timestamp used by refund eligibility checks. */
deadline: number;
/** Refund events recorded for this escrow. */
refund_history: RefundRecord[];
}
/** Escrow record paired with its bounty identifier. */
export interface EscrowWithId {
/** Application-level bounty identifier. */
bounty_id: bigint;
/** Escrow state for the identifier. */
escrow: Escrow;
}
/** Composite filter supported by the bounty escrow query endpoint. */
export interface EscrowQueryFilter {
/** Enables filtering by lifecycle status when true. */
has_status_filter: boolean;
/** Lifecycle status to match when status filtering is enabled. */
status: EscrowStatus;
/** Enables filtering by depositor account when true. */
has_depositor_filter: boolean;
/** Depositor account to match when depositor filtering is enabled. */
depositor: string;
/** Inclusive minimum escrow amount. */
min_amount: bigint;
/** Inclusive maximum escrow amount. */
max_amount: bigint;
/** Inclusive minimum deadline timestamp. */
min_deadline: number;
/** Inclusive maximum deadline timestamp. */
max_deadline: number;
}
/** Aggregate totals and counts across indexed bounty escrows. */
export interface AggregateStats {
/** Sum of currently locked funds. */
total_locked: bigint;
/** Sum of released funds. */
total_released: bigint;
/** Sum of refunded funds. */
total_refunded: bigint;
/** Number of locked escrows. */
count_locked: number;
/** Number of released escrows. */
count_released: number;
/** Number of refunded escrows. */
count_refunded: number;
}
/** Per-bounty analytics snapshot (from `get_bounty_analytics`). */
export interface BountyAnalytics {
total_amount_locked: bigint;
total_amount_released: bigint;
total_amount_refunded: bigint;
remaining_amount: bigint;
created_at: bigint;
last_updated: bigint;
partial_releases_count: number;
partial_refunds_count: number;
}
/** Contract-wide analytics snapshot (from `get_contract_analytics`). */
export interface ContractAnalytics {
active_bounty_count: number;
released_bounty_count: number;
refunded_bounty_count: number;
total_locked: bigint;
total_released: bigint;
total_refunded: bigint;
average_bounty_amount: bigint;
snapshot_timestamp: bigint;
}
/** Per-depositor lifetime stats (from `get_depositor_stats`), by escrow status. */
export interface DepositorStats {
locked_count: number;
locked_amount: bigint;
released_count: number;
released_amount: bigint;
refunded_count: number;
refunded_amount: bigint;
}
/** Admin approval record required before a refund can be executed. */
export interface RefundApproval {
/** Application-level bounty identifier. */
bounty_id: bigint;
/** Approved refund amount. */
amount: bigint;
/** Stellar account that may receive the refund. */
recipient: string;
/** Approved refund mode. */
mode: RefundMode;
/** Admin account that approved the refund. */
approved_by: string;
/** Unix timestamp when the approval was recorded. */
approved_at: number;
}
/** Refund eligibility result for a bounty escrow. */
export interface RefundEligibility {
/** True when the escrow can be refunded immediately. */
can_refund: boolean;
/** Whether the escrow deadline has elapsed. */
deadline_passed: boolean;
/** Remaining refundable amount. */
remaining_amount: bigint;
/** Optional approval details for admin-approved refunds. */
approval?: RefundApproval;
}
/** Fee policy configured on the bounty escrow contract. */
export interface FeeConfig {
/** Fee charged when locking funds, in basis points. */
lock_fee_rate: bigint;
/** Fee charged when releasing funds, in basis points. */
release_fee_rate: bigint;
/** Stellar account that receives fees. */
fee_recipient: string;
/** Whether fee collection is currently enabled. */
fee_enabled: boolean;
}
/** Pause switches for bounty escrow operations. */
export interface PauseFlags {
/** Whether lock operations are paused. */
lock_paused: boolean;
/** Whether release operations are paused. */
release_paused: boolean;
/** Whether refund operations are paused. */
refund_paused: boolean;
}
/** Configuration for multisig release requirements. */
export interface MultisigConfig {
/** Amount above which a release requires multisig approvals. */
threshold_amount: bigint;
/** List of authorized signers for multisig releases. */
signers: string[];
/** Minimum number of signers that must approve the release. */
required_signatures: number;
}
/** 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;
/** The error count threshold to open the circuit. */
failure_threshold: number;
/** The success count threshold to close the circuit. */
success_threshold: number;
}
/** A single circuit breaker error log entry (from `get_circuit_error_log`). */
export interface ErrorLogEntry {
/** Symbol identifying the operation that failed. */
operation: string;
/** Bounty id the failure occurred on. */
bounty_id: bigint;
/** Numeric contract error code. */
error_code: number;
/** Timestamp the failure was recorded. */
timestamp: bigint;
/** Consecutive failure count at the time this entry was logged. */
failure_count_at_time: number;
}
/** A stable configuration snapshot for audit views. */
export interface AdminConfigSnapshot {
/** Schema version for this snapshot. */
version: number;
/** Contract admin address. */
admin: string;
/** Escrow token contract address. */
token: string;
/** Fee configuration. */
fee_config: FeeConfig;
/** Pause flags. */
pause_flags: PauseFlags;
/** Optional governance contract address. */
governance_contract?: string;
/** Minimum required governance version for admin actions. */
min_governance_version: number;
/** Time window in seconds during which claims are allowed. */
claim_window: bigint;
/** Whether an amount policy (min/max limits) is configured. */
has_amount_policy: boolean;
/** Minimum allowed lock amount. */
min_lock_amount: bigint;
/** Maximum allowed lock amount. */
max_lock_amount: bigint;
}
/**
* Client for interacting with the BountyEscrow Soroban contract
*/
export class BountyEscrowClient {
private contract: Contract;
private server: SorobanRpc.Server;
private config: BountyEscrowConfig;
private invocationConfig: InvocationConfig;
/**
* Create a client bound to one BountyEscrow contract and Soroban RPC endpoint.
*/
constructor(config: BountyEscrowConfig) {
this.config = config;
try {
this.contract = new Contract(config.contractId);
} catch (error) {
this.contract = null as any;
}
try {
this.server = new SorobanRpc.Server(config.rpcUrl, { allowHttp: true });
} catch (error) {
this.server = null as any;
}
this.invocationConfig = {
server: this.server,
contract: this.contract,
networkPassphrase: config.networkPassphrase,
rpcUrl: config.rpcUrl,
};
}
/**
* Initialize the bounty escrow contract
*/
async init(
adminAddress: string,
tokenAddress: string,
sourceKeypair: Keypair
): Promise<void> {
this.validateAddress(adminAddress, 'adminAddress');
this.validateAddress(tokenAddress, 'tokenAddress');
try {
await this.invokeContract('init', [adminAddress, tokenAddress], sourceKeypair);
} catch (error) {
throw this.handleError(error);
}
}
/**
* Lock funds into a bounty escrow
*/
async lockFunds(
depositor: string,
bountyId: bigint,
amount: bigint,
deadline: number,
sourceKeypair: Keypair
): Promise<void> {
this.validateAddress(depositor, 'depositor');
if (amount <= 0n) {
throw new ValidationError('Amount must be greater than zero', 'amount');
}
if (deadline <= Math.floor(Date.now() / 1000)) {
throw new ValidationError('Deadline must be in the future', 'deadline');
}
try {
await this.invokeContract('lock_funds', [depositor, bountyId, amount, deadline], sourceKeypair);
} catch (error) {
throw this.handleError(error);
}
}
/**
* Release full funds for a bounty to a contributor
*/
async releaseFunds(
bountyId: bigint,
contributor: string,
sourceKeypair: Keypair
): Promise<void> {
this.validateAddress(contributor, 'contributor');
try {
await this.invokeContract('release_funds', [bountyId, contributor], sourceKeypair);
} catch (error) {
throw this.handleError(error);
}
}
/**
* Release partial funds for a bounty to a contributor
*/
async partialRelease(
bountyId: bigint,
contributor: string,
amount: bigint,
sourceKeypair: Keypair
): Promise<void> {
this.validateAddress(contributor, 'contributor');
if (amount <= 0n) {
throw new ValidationError('Amount must be greater than zero', 'amount');
}
try {
await this.invokeContract('partial_release', [bountyId, contributor, amount], sourceKeypair);
} catch (error) {
throw this.handleError(error);
}
}
/**
* Approve a refund for a bounty
*/
async approveRefund(
bountyId: bigint,
amount: bigint,
recipient: string,
mode: RefundMode,
sourceKeypair: Keypair
): Promise<void> {
this.validateAddress(recipient, 'recipient');
if (amount <= 0n) {
throw new ValidationError('Amount must be greater than zero', 'amount');
}
this.validateRefundMode(mode);
try {
await this.invokeContract('approve_refund', [bountyId, amount, recipient, mode], sourceKeypair);
} catch (error) {
throw this.handleError(error);
}
}
/**
* Execute a refund for a bounty
*/
async refund(
bountyId: bigint,
sourceKeypair: Keypair
): Promise<void> {
try {
await this.invokeContract('refund', [bountyId], sourceKeypair);
} catch (error) {
throw this.handleError(error);
}
}
/**
* Authorize a claim for a bounty.
*
* Requires setClaimWindow to have been called first with a nonzero
* value. If the contract's claim window is 0 (never configured, or
* explicitly set to 0), the on-chain call fails with
* ClaimWindowNotConfigured — a pending claim created with a 0 window
* would expire at its own creation timestamp and could never be
* claimed by the recipient.
*/
async authorizeClaim(
bountyId: bigint,
recipient: string,
sourceKeypair: Keypair
): Promise<void> {
this.validateAddress(recipient, 'recipient');
try {
await this.invokeContract('authorize_claim', [bountyId, recipient], sourceKeypair);
} catch (error) {
throw this.handleError(error);
}
}
/**
* Set the global claim window in seconds. Admin-only on chain.
*/
async setClaimWindow(
claimWindow: number,
sourceKeypair: Keypair
): Promise<void> {
if (!Number.isInteger(claimWindow) || claimWindow < 0) {
throw new ValidationError('Claim window must be a non-negative integer', 'claimWindow');
}
try {
await this.invokeContract('set_claim_window', [claimWindow], sourceKeypair);
} catch (error) {
throw this.handleError(error);
}
}
/**
* Execute a claim for a bounty
*/
async claim(
bountyId: bigint,
sourceKeypair: Keypair
): Promise<void> {
try {
await this.invokeContract('claim', [bountyId], sourceKeypair);
} catch (error) {
throw this.handleError(error);
}
}
/**
* Cancel a pending claim. Admin-only on chain.
*/
async cancelPendingClaim(
bountyId: bigint,
sourceKeypair: Keypair
): Promise<void> {
try {
await this.invokeContract('cancel_pending_claim', [bountyId], sourceKeypair);
} catch (error) {
throw this.handleError(error);
}
}
/**
* Batch lock funds for multiple bounties
*/
async batchLockFunds(
items: LockFundsItem[],
sourceKeypair: Keypair
): Promise<number> {
if (items.length === 0) {
throw new ValidationError('Items array cannot be empty', 'items');
}
for (let i = 0; i < items.length; i++) {
this.validateAddress(items[i].depositor, `items[${i}].depositor`);
if (items[i].amount <= 0n) {
throw new ValidationError(`Amount at index ${i} must be greater than zero`, 'amount');
}
if (items[i].deadline <= Math.floor(Date.now() / 1000)) {
throw new ValidationError(`Deadline at index ${i} must be in the future`, 'deadline');
}
}
try {
const result = await this.invokeContract('batch_lock_funds', [items], sourceKeypair);
return Number(result);
} catch (error) {
throw this.handleError(error);
}
}
/**
* Batch release funds for multiple bounties
*/
async batchReleaseFunds(
items: ReleaseFundsItem[],
sourceKeypair: Keypair
): Promise<number> {
if (items.length === 0) {
throw new ValidationError('Items array cannot be empty', 'items');
}
for (let i = 0; i < items.length; i++) {
this.validateAddress(items[i].contributor, `items[${i}].contributor`);
}
try {
const result = await this.invokeContract('batch_release_funds', [items], sourceKeypair);
return Number(result);
} catch (error) {
throw this.handleError(error);
}
}
/**
* Get information about a specific escrow
*/
async getEscrowInfo(bountyId: bigint): Promise<Escrow> {
try {
const result = await this.invokeContract('get_escrow_info', [bountyId]);
return result as Escrow;
} catch (error) {
throw this.handleError(error);
}
}
/**
* Get the pending claim for a bounty.
*/
async getPendingClaim(bountyId: bigint): Promise<ClaimRecord> {
try {
const result = await this.invokeContract('get_pending_claim', [bountyId]);
return result as ClaimRecord;
} catch (error) {
throw this.handleError(error);
}
}
/**
* Get the current contract balance
*/
async getBalance(): Promise<bigint> {
try {
const result = await this.invokeContract('get_balance', []);
return BigInt(result);
} catch (error) {
throw this.handleError(error);
}
}
/**
* Query escrows by status.
*/
async queryEscrowsByStatus(
status: EscrowStatus,
offset = 0,
limit = 50
): Promise<EscrowWithId[]> {
this.validatePagination(offset, limit);
try {
const result = await this.invokeContract('query_escrows_by_status', [status, offset, limit]);
return result as EscrowWithId[];
} catch (error) {
throw this.handleError(error);
}
}
/**
* Query escrows by amount range.
*/
async queryEscrowsByAmount(
minAmount: bigint,
maxAmount: bigint,
offset = 0,
limit = 50
): Promise<EscrowWithId[]> {
if (minAmount < 0n || maxAmount < minAmount) {
throw new ValidationError('Amount range is invalid', 'amount');
}
this.validatePagination(offset, limit);
try {
const result = await this.invokeContract('query_escrows_by_amount', [minAmount, maxAmount, offset, limit]);
return result as EscrowWithId[];
} catch (error) {
throw this.handleError(error);
}
}
/**
* Query escrows by deadline range.
*/
async queryEscrowsByDeadline(
minDeadline: number,
maxDeadline: number,
offset = 0,
limit = 50
): Promise<EscrowWithId[]> {
if (!Number.isInteger(minDeadline) || !Number.isInteger(maxDeadline) || minDeadline < 0 || maxDeadline < minDeadline) {
throw new ValidationError('Deadline range is invalid', 'deadline');
}
this.validatePagination(offset, limit);
try {
const result = await this.invokeContract('query_escrows_by_deadline', [minDeadline, maxDeadline, offset, limit]);
return result as EscrowWithId[];
} catch (error) {
throw this.handleError(error);
}
}
/**
* Query escrows by depositor.
*/
async queryEscrowsByDepositor(
depositor: string,
offset = 0,
limit = 50
): Promise<EscrowWithId[]> {
this.validateAddress(depositor, 'depositor');
this.validatePagination(offset, limit);
try {
const result = await this.invokeContract('query_escrows_by_depositor', [depositor, offset, limit]);
return result as EscrowWithId[];
} catch (error) {
throw this.handleError(error);
}
}
/**
* Query escrows with the composite on-chain filter.
*/
async queryEscrows(
filter: EscrowQueryFilter,
offset = 0,
limit = 50
): Promise<EscrowWithId[]> {
if (filter.has_depositor_filter) {
this.validateAddress(filter.depositor, 'filter.depositor');
}
if (filter.min_amount < 0n || filter.max_amount < filter.min_amount) {
throw new ValidationError('Filter amount range is invalid', 'filter.amount');
}
if (filter.min_deadline < 0 || filter.max_deadline < filter.min_deadline) {
throw new ValidationError('Filter deadline range is invalid', 'filter.deadline');
}
this.validatePagination(offset, limit);
try {
const result = await this.invokeContract('query_escrows', [filter, offset, limit]);
return result as EscrowWithId[];
} catch (error) {
throw this.handleError(error);
}
}
/**
* Get aggregate escrow statistics.
*/
async getAggregateStats(): Promise<AggregateStats> {
try {
const result = await this.invokeContract('get_aggregate_stats', []);
return result as AggregateStats;
} catch (error) {
throw this.handleError(error);
}
}
/**
* Get the per-bounty analytics snapshot (accumulators updated on every
* state transition -- O(1) read, suitable for regular polling).
*
* @throws {ContractError} If the bounty does not exist.
*/
async getBountyAnalytics(bountyId: bigint): Promise<BountyAnalytics> {
try {
const result = await this.invokeContract('get_bounty_analytics', [bountyId]);
return result as BountyAnalytics;
} catch (error) {
throw this.handleError(error);
}
}
/**
* Get the contract-wide analytics snapshot.
*/
async getContractAnalytics(): Promise<ContractAnalytics> {
try {
const result = await this.invokeContract('get_contract_analytics', []);
return result as ContractAnalytics;
} catch (error) {
throw this.handleError(error);
}
}
/**
* Count bounties currently in the given status.
*/
async countBountiesByStatus(status: EscrowStatus): Promise<number> {
try {
const result = await this.invokeContract('count_bounties_by_status', [status]);
return Number(result);
} catch (error) {
throw this.handleError(error);
}
}
/**
* Total volume (sum of amounts) of bounties currently in the given status.
*/
async getVolumeByStatus(status: EscrowStatus): Promise<bigint> {
try {
const result = await this.invokeContract('get_volume_by_status', [status]);
return result as bigint;
} catch (error) {
throw this.handleError(error);
}
}
/**
* Get a depositor's lifetime bounty stats, broken down by status.
*/
async getDepositorStats(depositor: string): Promise<DepositorStats> {
this.validateAddress(depositor, 'depositor');
try {
const [lockedCount, lockedAmount, releasedCount, releasedAmount, refundedCount, refundedAmount] =
(await this.invokeContract('get_depositor_stats', [depositor])) as [
number,
bigint,
number,
bigint,
number,
bigint
];
return {
locked_count: lockedCount,
locked_amount: lockedAmount,
released_count: releasedCount,
released_amount: releasedAmount,
refunded_count: refundedCount,
refunded_amount: refundedAmount,
};
} catch (error) {
throw this.handleError(error);
}
}
/**
* Get bounty ids with a remaining amount at or above `minAmount`, newest first.
*
* @param minAmount - Minimum remaining amount (inclusive).
* @param limit - Maximum number of ids to return.
*/
async getHighValueBounties(minAmount: bigint, limit: number): Promise<bigint[]> {
try {
const result = await this.invokeContract('get_high_value_bounties', [minAmount, limit]);
return result as bigint[];
} catch (error) {
throw this.handleError(error);
}
}
/**
* Get the total number of indexed escrows.
*/
async getEscrowCount(): Promise<number> {
try {
const result = await this.invokeContract('get_escrow_count', []);
return Number(result);
} catch (error) {
throw this.handleError(error);
}
}
/**
* Get escrow IDs matching a status filter.
*/
async getEscrowIdsByStatus(
status: EscrowStatus,
offset = 0,
limit = 50
): Promise<bigint[]> {
this.validatePagination(offset, limit);
try {
const result = await this.invokeContract('get_escrow_ids_by_status', [status, offset, limit]);
return result as bigint[];
} catch (error) {
throw this.handleError(error);
}
}
/**
* Get refund history for a bounty.
*/
async getRefundHistory(bountyId: bigint): Promise<RefundRecord[]> {
try {
const result = await this.invokeContract('get_refund_history', [bountyId]);
return result as RefundRecord[];
} catch (error) {
throw this.handleError(error);
}
}
/**
* Get refund eligibility and optional approval details for a bounty.
*/
async getRefundEligibility(bountyId: bigint): Promise<RefundEligibility> {
try {
const result = await this.invokeContract('get_refund_eligibility', [bountyId]);
if (Array.isArray(result)) {
return {
can_refund: Boolean(result[0]),
deadline_passed: Boolean(result[1]),
remaining_amount: BigInt(result[2]),
approval: result[3] ?? undefined,
};
}
return result as RefundEligibility;
} catch (error) {
throw this.handleError(error);
}
}
/**
* Query locked or partially refunded bounties whose deadline is at or before maxDeadline.
*/
async queryExpiringBounties(
maxDeadline: number,
offset = 0,
limit = 50
): Promise<bigint[]> {
if (!Number.isInteger(maxDeadline) || maxDeadline < 0) {
throw new ValidationError('Max deadline must be a non-negative integer', 'maxDeadline');
}
this.validatePagination(offset, limit);
try {
const result = await this.invokeContract('query_expiring_bounties', [maxDeadline, offset, limit]);
return result as bigint[];
} catch (error) {
throw this.handleError(error);
}
}
/**
* Get the current fee configuration
*/
async getFeeConfig(): Promise<FeeConfig> {
try {
const result = await this.invokeContract('get_fee_config', []);
return result as FeeConfig;
} catch (error) {
throw this.handleError(error);
}
}
/**
* Get the current pause flags
*/
async getPauseFlags(): Promise<PauseFlags> {
try {
const result = await this.invokeContract('get_pause_flags', []);
return result as PauseFlags;
} catch (error) {
throw this.handleError(error);
}
}
/**
* Update the contract's fee configuration. Admin-only.
*
* @param lockFeeRate - Optional new lock fee rate in basis points.
* @param releaseFeeRate - Optional new release fee rate in basis points.
* @param feeRecipient - Optional new stellar address of the fee recipient.
* @param feeEnabled - Optional flag to enable or disable fee collection.
* @param sourceKeypair - Signing keypair of the admin.
* @throws {ValidationError} If inputs are invalid.
* @throws {ContractError} If the caller is not authorized (unauthorized error) or the contract is not initialized.
*/
async updateFeeConfig(
lockFeeRate: bigint | null,
releaseFeeRate: bigint | null,
feeRecipient: string | null,
feeEnabled: boolean | null,
sourceKeypair: Keypair
): Promise<void> {
if (lockFeeRate !== null && lockFeeRate !== undefined) {
if (lockFeeRate < 0n) {
throw new ValidationError('Lock fee rate cannot be negative', 'lockFeeRate');
}
}
if (releaseFeeRate !== null && releaseFeeRate !== undefined) {
if (releaseFeeRate < 0n) {
throw new ValidationError('Release fee rate cannot be negative', 'releaseFeeRate');
}
}
if (feeRecipient !== null && feeRecipient !== undefined) {
this.validateAddress(feeRecipient, 'feeRecipient');
}
try {
await this.invokeContract(
'update_fee_config',
[lockFeeRate, releaseFeeRate, feeRecipient, feeEnabled],
sourceKeypair
);
} catch (error) {
throw this.handleError(error);
}
}
/**
* Update operations pause state. Admin-only.
*
* @param lock - Optional pause flag for lock operations.
* @param release - Optional pause flag for release operations.
* @param refund - Optional pause flag for refund operations.
* @param sourceKeypair - Signing keypair of the admin.
* @throws {ContractError} If the caller is not authorized or the contract is not initialized.
*/
async setPaused(
lock: boolean | null,
release: boolean | null,
refund: boolean | null,
sourceKeypair: Keypair
): Promise<void> {
try {
await this.invokeContract(
'set_paused',
[lock, release, refund],
sourceKeypair
);
} catch (error) {
throw this.handleError(error);
}
}
/**
* Set the governance contract address. Admin-only.
*
* @param governanceAddr - The Stellar address of the governance contract.
* @param sourceKeypair - Signing keypair of the admin.
* @throws {ValidationError} If the address is invalid.
* @throws {ContractError} If the caller is not authorized or the contract is not initialized.
*/
async setGovernanceContract(
governanceAddr: string,
sourceKeypair: Keypair
): Promise<void> {