@jpool/bond-sdk 0.1.0-next.1 → 0.1.0-next.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,1202 @@
1
+ 'use strict';
2
+
3
+ var anchor = require('@coral-xyz/anchor');
4
+ var web3_js = require('@solana/web3.js');
5
+ var bs58 = require('bs58');
6
+ var fs = require('fs');
7
+
8
+ function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
9
+
10
+ var bs58__default = /*#__PURE__*/_interopDefault(bs58);
11
+
12
+ // src/client.ts
13
+
14
+ // src/helpers.ts
15
+ var SLOTS_PER_EPOCH_MAINNET = 432e3;
16
+ var SLOTS_PER_EPOCH_DEVNET = 4e5;
17
+ function slotToEpoch(slot, cluster) {
18
+ const slotsPerEpoch = cluster === "mainnet-beta" ? SLOTS_PER_EPOCH_MAINNET : SLOTS_PER_EPOCH_DEVNET;
19
+ return Math.floor(slot / slotsPerEpoch);
20
+ }
21
+
22
+ // src/idl/jbond.json
23
+ var jbond_default = {
24
+ address: "4a3YovKEfm4jWhczCzJciHXL1xVkXWfGQjRCaMft7M4G",
25
+ metadata: {
26
+ name: "jbond",
27
+ version: "0.1.0",
28
+ spec: "0.1.0",
29
+ description: "Validator compensation program for boosting APR"
30
+ },
31
+ instructions: [
32
+ {
33
+ name: "bond_init",
34
+ docs: [
35
+ "Register validator and fund initial collateral"
36
+ ],
37
+ discriminator: [
38
+ 220,
39
+ 108,
40
+ 156,
41
+ 81,
42
+ 16,
43
+ 185,
44
+ 144,
45
+ 157
46
+ ],
47
+ accounts: [
48
+ {
49
+ name: "global_state",
50
+ writable: true,
51
+ pda: {
52
+ seeds: [
53
+ {
54
+ kind: "const",
55
+ value: [
56
+ 103,
57
+ 108,
58
+ 111,
59
+ 98,
60
+ 97,
61
+ 108,
62
+ 95,
63
+ 115,
64
+ 116,
65
+ 97,
66
+ 116,
67
+ 101
68
+ ]
69
+ }
70
+ ]
71
+ }
72
+ },
73
+ {
74
+ name: "validator_bond_account",
75
+ writable: true,
76
+ pda: {
77
+ seeds: [
78
+ {
79
+ kind: "const",
80
+ value: [
81
+ 118,
82
+ 97,
83
+ 108,
84
+ 105,
85
+ 100,
86
+ 97,
87
+ 116,
88
+ 111,
89
+ 114,
90
+ 95,
91
+ 98,
92
+ 111,
93
+ 110,
94
+ 100
95
+ ]
96
+ },
97
+ {
98
+ kind: "account",
99
+ path: "vote_account"
100
+ }
101
+ ]
102
+ }
103
+ },
104
+ {
105
+ name: "identity"
106
+ },
107
+ {
108
+ name: "vote_account"
109
+ },
110
+ {
111
+ name: "creator",
112
+ docs: [
113
+ "The account creating the bond (pays for account creation and initial collateral)"
114
+ ],
115
+ writable: true,
116
+ signer: true
117
+ },
118
+ {
119
+ name: "system_program",
120
+ address: "11111111111111111111111111111111"
121
+ }
122
+ ],
123
+ args: [
124
+ {
125
+ name: "initial_collateral",
126
+ type: "u64"
127
+ },
128
+ {
129
+ name: "withdrawal_authority",
130
+ type: {
131
+ option: "pubkey"
132
+ }
133
+ }
134
+ ]
135
+ },
136
+ {
137
+ name: "bond_top_up",
138
+ docs: [
139
+ "Top up collateral for existing validator"
140
+ ],
141
+ discriminator: [
142
+ 132,
143
+ 225,
144
+ 254,
145
+ 187,
146
+ 152,
147
+ 162,
148
+ 176,
149
+ 66
150
+ ],
151
+ accounts: [
152
+ {
153
+ name: "validator_bond_account",
154
+ writable: true,
155
+ pda: {
156
+ seeds: [
157
+ {
158
+ kind: "const",
159
+ value: [
160
+ 118,
161
+ 97,
162
+ 108,
163
+ 105,
164
+ 100,
165
+ 97,
166
+ 116,
167
+ 111,
168
+ 114,
169
+ 95,
170
+ 98,
171
+ 111,
172
+ 110,
173
+ 100
174
+ ]
175
+ },
176
+ {
177
+ kind: "account",
178
+ path: "validator_bond_account.vote_account",
179
+ account: "ValidatorBondAccount"
180
+ }
181
+ ]
182
+ }
183
+ },
184
+ {
185
+ name: "depositor",
186
+ writable: true,
187
+ signer: true
188
+ },
189
+ {
190
+ name: "system_program",
191
+ address: "11111111111111111111111111111111"
192
+ }
193
+ ],
194
+ args: [
195
+ {
196
+ name: "amount",
197
+ type: "u64"
198
+ }
199
+ ]
200
+ },
201
+ {
202
+ name: "bond_withdraw",
203
+ discriminator: [
204
+ 99,
205
+ 64,
206
+ 127,
207
+ 178,
208
+ 53,
209
+ 117,
210
+ 70,
211
+ 204
212
+ ],
213
+ accounts: [
214
+ {
215
+ name: "validator_bond_account",
216
+ writable: true,
217
+ pda: {
218
+ seeds: [
219
+ {
220
+ kind: "const",
221
+ value: [
222
+ 118,
223
+ 97,
224
+ 108,
225
+ 105,
226
+ 100,
227
+ 97,
228
+ 116,
229
+ 111,
230
+ 114,
231
+ 95,
232
+ 98,
233
+ 111,
234
+ 110,
235
+ 100
236
+ ]
237
+ },
238
+ {
239
+ kind: "account",
240
+ path: "validator_bond_account.vote_account",
241
+ account: "ValidatorBondAccount"
242
+ }
243
+ ]
244
+ }
245
+ },
246
+ {
247
+ name: "withdrawal_authority",
248
+ writable: true,
249
+ signer: true
250
+ },
251
+ {
252
+ name: "destination",
253
+ writable: true
254
+ },
255
+ {
256
+ name: "system_program",
257
+ address: "11111111111111111111111111111111"
258
+ }
259
+ ],
260
+ args: [
261
+ {
262
+ name: "amount",
263
+ type: "u64"
264
+ }
265
+ ]
266
+ },
267
+ {
268
+ name: "initialize",
269
+ docs: [
270
+ "Initialize the global state and reserve vault"
271
+ ],
272
+ discriminator: [
273
+ 175,
274
+ 175,
275
+ 109,
276
+ 31,
277
+ 13,
278
+ 152,
279
+ 155,
280
+ 237
281
+ ],
282
+ accounts: [
283
+ {
284
+ name: "global_state",
285
+ writable: true,
286
+ pda: {
287
+ seeds: [
288
+ {
289
+ kind: "const",
290
+ value: [
291
+ 103,
292
+ 108,
293
+ 111,
294
+ 98,
295
+ 97,
296
+ 108,
297
+ 95,
298
+ 115,
299
+ 116,
300
+ 97,
301
+ 116,
302
+ 101
303
+ ]
304
+ }
305
+ ]
306
+ }
307
+ },
308
+ {
309
+ name: "authority",
310
+ writable: true,
311
+ signer: true
312
+ },
313
+ {
314
+ name: "reserve"
315
+ },
316
+ {
317
+ name: "system_program",
318
+ address: "11111111111111111111111111111111"
319
+ }
320
+ ],
321
+ args: []
322
+ },
323
+ {
324
+ name: "withdraw_compensation",
325
+ docs: [
326
+ "Withdraw compensation from validator to reserve (oracle only)"
327
+ ],
328
+ discriminator: [
329
+ 10,
330
+ 228,
331
+ 22,
332
+ 213,
333
+ 205,
334
+ 117,
335
+ 181,
336
+ 75
337
+ ],
338
+ accounts: [
339
+ {
340
+ name: "global_state",
341
+ writable: true,
342
+ pda: {
343
+ seeds: [
344
+ {
345
+ kind: "const",
346
+ value: [
347
+ 103,
348
+ 108,
349
+ 111,
350
+ 98,
351
+ 97,
352
+ 108,
353
+ 95,
354
+ 115,
355
+ 116,
356
+ 97,
357
+ 116,
358
+ 101
359
+ ]
360
+ }
361
+ ]
362
+ }
363
+ },
364
+ {
365
+ name: "validator_bond_account",
366
+ writable: true,
367
+ pda: {
368
+ seeds: [
369
+ {
370
+ kind: "const",
371
+ value: [
372
+ 118,
373
+ 97,
374
+ 108,
375
+ 105,
376
+ 100,
377
+ 97,
378
+ 116,
379
+ 111,
380
+ 114,
381
+ 95,
382
+ 98,
383
+ 111,
384
+ 110,
385
+ 100
386
+ ]
387
+ },
388
+ {
389
+ kind: "account",
390
+ path: "validator_bond_account.vote_account",
391
+ account: "ValidatorBondAccount"
392
+ }
393
+ ]
394
+ }
395
+ },
396
+ {
397
+ name: "reserve",
398
+ writable: true
399
+ },
400
+ {
401
+ name: "authority",
402
+ docs: [
403
+ "Authority that can trigger claims"
404
+ ],
405
+ signer: true
406
+ },
407
+ {
408
+ name: "system_program",
409
+ address: "11111111111111111111111111111111"
410
+ }
411
+ ],
412
+ args: [
413
+ {
414
+ name: "amount",
415
+ type: "u64"
416
+ }
417
+ ]
418
+ }
419
+ ],
420
+ accounts: [
421
+ {
422
+ name: "GlobalState",
423
+ discriminator: [
424
+ 163,
425
+ 46,
426
+ 74,
427
+ 168,
428
+ 216,
429
+ 123,
430
+ 133,
431
+ 98
432
+ ]
433
+ },
434
+ {
435
+ name: "ValidatorBondAccount",
436
+ discriminator: [
437
+ 25,
438
+ 67,
439
+ 241,
440
+ 227,
441
+ 226,
442
+ 104,
443
+ 108,
444
+ 73
445
+ ]
446
+ }
447
+ ],
448
+ events: [
449
+ {
450
+ name: "CollateralToppedUp",
451
+ discriminator: [
452
+ 189,
453
+ 137,
454
+ 204,
455
+ 58,
456
+ 135,
457
+ 182,
458
+ 19,
459
+ 176
460
+ ]
461
+ },
462
+ {
463
+ name: "CollateralWithdrawn",
464
+ discriminator: [
465
+ 51,
466
+ 224,
467
+ 133,
468
+ 106,
469
+ 74,
470
+ 173,
471
+ 72,
472
+ 82
473
+ ]
474
+ },
475
+ {
476
+ name: "CompensationClaimed",
477
+ discriminator: [
478
+ 36,
479
+ 159,
480
+ 41,
481
+ 178,
482
+ 104,
483
+ 135,
484
+ 220,
485
+ 32
486
+ ]
487
+ },
488
+ {
489
+ name: "ValidatorRegistered",
490
+ discriminator: [
491
+ 20,
492
+ 20,
493
+ 190,
494
+ 191,
495
+ 53,
496
+ 174,
497
+ 95,
498
+ 72
499
+ ]
500
+ }
501
+ ],
502
+ errors: [
503
+ {
504
+ code: 6e3,
505
+ name: "InvalidVoteAccount",
506
+ msg: "Invalid vote account"
507
+ },
508
+ {
509
+ code: 6001,
510
+ name: "IdentityMismatch",
511
+ msg: "Identity does not match vote account"
512
+ },
513
+ {
514
+ code: 6002,
515
+ name: "InsufficientCollateral",
516
+ msg: "Insufficient collateral amount"
517
+ },
518
+ {
519
+ code: 6003,
520
+ name: "TargetAprTooLow",
521
+ msg: "Target APR is below minimum threshold"
522
+ },
523
+ {
524
+ code: 6004,
525
+ name: "MathOverflow",
526
+ msg: "Math overflow"
527
+ },
528
+ {
529
+ code: 6005,
530
+ name: "InvalidAmount",
531
+ msg: "Invalid amount"
532
+ },
533
+ {
534
+ code: 6006,
535
+ name: "ValidatorNotActive",
536
+ msg: "Validator boost account is not active"
537
+ },
538
+ {
539
+ code: 6007,
540
+ name: "ValidatorAlreadyRegistered",
541
+ msg: "Validator already registered"
542
+ },
543
+ {
544
+ code: 6008,
545
+ name: "Unauthorized",
546
+ msg: "Unauthorized"
547
+ }
548
+ ],
549
+ types: [
550
+ {
551
+ name: "CollateralToppedUp",
552
+ type: {
553
+ kind: "struct",
554
+ fields: [
555
+ {
556
+ name: "validator",
557
+ type: "pubkey"
558
+ },
559
+ {
560
+ name: "amount",
561
+ type: "u64"
562
+ },
563
+ {
564
+ name: "new_total",
565
+ type: "u64"
566
+ },
567
+ {
568
+ name: "timestamp",
569
+ type: "i64"
570
+ }
571
+ ]
572
+ }
573
+ },
574
+ {
575
+ name: "CollateralWithdrawn",
576
+ type: {
577
+ kind: "struct",
578
+ fields: [
579
+ {
580
+ name: "validator",
581
+ type: "pubkey"
582
+ },
583
+ {
584
+ name: "amount",
585
+ type: "u64"
586
+ },
587
+ {
588
+ name: "remaining_collateral",
589
+ type: "u64"
590
+ },
591
+ {
592
+ name: "timestamp",
593
+ type: "i64"
594
+ }
595
+ ]
596
+ }
597
+ },
598
+ {
599
+ name: "CompensationClaimed",
600
+ type: {
601
+ kind: "struct",
602
+ fields: [
603
+ {
604
+ name: "validator",
605
+ type: "pubkey"
606
+ },
607
+ {
608
+ name: "amount",
609
+ type: "u64"
610
+ },
611
+ {
612
+ name: "remaining_collateral",
613
+ type: "u64"
614
+ },
615
+ {
616
+ name: "total_withdrawn",
617
+ type: "u64"
618
+ },
619
+ {
620
+ name: "epoch",
621
+ type: "u64"
622
+ },
623
+ {
624
+ name: "timestamp",
625
+ type: "i64"
626
+ }
627
+ ]
628
+ }
629
+ },
630
+ {
631
+ name: "GlobalState",
632
+ type: {
633
+ kind: "struct",
634
+ fields: [
635
+ {
636
+ name: "authority",
637
+ type: "pubkey"
638
+ },
639
+ {
640
+ name: "reserve",
641
+ type: "pubkey"
642
+ },
643
+ {
644
+ name: "total_validators",
645
+ type: "u32"
646
+ },
647
+ {
648
+ name: "total_withdrawn",
649
+ type: "u64"
650
+ },
651
+ {
652
+ name: "bump",
653
+ type: "u8"
654
+ }
655
+ ]
656
+ }
657
+ },
658
+ {
659
+ name: "ValidatorBondAccount",
660
+ type: {
661
+ kind: "struct",
662
+ fields: [
663
+ {
664
+ name: "identity",
665
+ type: "pubkey"
666
+ },
667
+ {
668
+ name: "vote_account",
669
+ type: "pubkey"
670
+ },
671
+ {
672
+ name: "creator",
673
+ type: "pubkey"
674
+ },
675
+ {
676
+ name: "withdrawal_authority",
677
+ type: {
678
+ option: "pubkey"
679
+ }
680
+ },
681
+ {
682
+ name: "total_withdrawn",
683
+ type: "u64"
684
+ },
685
+ {
686
+ name: "last_withdrawal_epoch",
687
+ type: "u64"
688
+ },
689
+ {
690
+ name: "is_active",
691
+ type: "bool"
692
+ },
693
+ {
694
+ name: "created_at",
695
+ type: "i64"
696
+ },
697
+ {
698
+ name: "bump",
699
+ type: "u8"
700
+ }
701
+ ]
702
+ }
703
+ },
704
+ {
705
+ name: "ValidatorRegistered",
706
+ type: {
707
+ kind: "struct",
708
+ fields: [
709
+ {
710
+ name: "validator",
711
+ type: "pubkey"
712
+ },
713
+ {
714
+ name: "vote_account",
715
+ type: "pubkey"
716
+ },
717
+ {
718
+ name: "collateral_amount",
719
+ type: "u64"
720
+ },
721
+ {
722
+ name: "timestamp",
723
+ type: "i64"
724
+ }
725
+ ]
726
+ }
727
+ }
728
+ ]
729
+ };
730
+
731
+ // src/types/index.ts
732
+ var BondTransactionType = /* @__PURE__ */ ((BondTransactionType2) => {
733
+ BondTransactionType2["Deposit"] = "deposit";
734
+ BondTransactionType2["Withdrawal"] = "withdrawal";
735
+ BondTransactionType2["Compensation"] = "compensation";
736
+ return BondTransactionType2;
737
+ })(BondTransactionType || {});
738
+
739
+ // src/utils/wallet.ts
740
+ function isVersionedTransaction(tx) {
741
+ return "version" in tx;
742
+ }
743
+ var NodeWallet = class {
744
+ constructor(payer) {
745
+ this.payer = payer;
746
+ }
747
+ async signTransaction(tx) {
748
+ if (isVersionedTransaction(tx)) {
749
+ tx.sign([this.payer]);
750
+ } else {
751
+ tx.partialSign(this.payer);
752
+ }
753
+ return tx;
754
+ }
755
+ async signAllTransactions(txs) {
756
+ return txs.map((t) => {
757
+ if (isVersionedTransaction(t)) {
758
+ t.sign([this.payer]);
759
+ } else {
760
+ t.partialSign(this.payer);
761
+ }
762
+ return t;
763
+ });
764
+ }
765
+ get publicKey() {
766
+ return this.payer.publicKey;
767
+ }
768
+ };
769
+
770
+ // src/client.ts
771
+ var JBondClient = class _JBondClient {
772
+ connection;
773
+ program;
774
+ provider;
775
+ config;
776
+ constructor(config, wallet) {
777
+ this.config = config;
778
+ this.connection = new web3_js.Connection(config.rpcUrl, "confirmed");
779
+ this.provider = new anchor.AnchorProvider(
780
+ this.connection,
781
+ // @ts-expect-error support anonymous
782
+ wallet ?? { publicKey: web3_js.PublicKey.default },
783
+ anchor.AnchorProvider.defaultOptions()
784
+ );
785
+ this.program = new anchor.Program(jbond_default, this.provider);
786
+ }
787
+ /**
788
+ * Creates an instance of `JBondClient` using a provided connection and wallet.
789
+ */
790
+ static fromWallet(config, wallet) {
791
+ return new this(config, wallet);
792
+ }
793
+ /**
794
+ * Creates an instance of `JBondClient` using the provided connection and keypair.
795
+ */
796
+ static fromKeypair(config, keypair) {
797
+ return _JBondClient.fromWallet(config, new NodeWallet(keypair));
798
+ }
799
+ // Get PDA for global state
800
+ getGlobalStatePDA() {
801
+ return web3_js.PublicKey.findProgramAddressSync(
802
+ [Buffer.from("global_state")],
803
+ this.program.programId
804
+ );
805
+ }
806
+ // Get PDA for validator bond account
807
+ getValidatorBondPDA(voteAccount) {
808
+ return web3_js.PublicKey.findProgramAddressSync(
809
+ [
810
+ Buffer.from("validator_bond"),
811
+ voteAccount.toBuffer()
812
+ ],
813
+ this.program.programId
814
+ );
815
+ }
816
+ // Build initialize instruction
817
+ async buildInitializeInstruction(props) {
818
+ const [globalState] = this.getGlobalStatePDA();
819
+ return this.program.methods.initialize().accountsStrict({
820
+ globalState,
821
+ authority: props.authority,
822
+ reserve: this.config.reserveAddress,
823
+ systemProgram: web3_js.SystemProgram.programId
824
+ }).instruction();
825
+ }
826
+ // Build register validator instruction
827
+ async buildRegisterValidatorInstruction(props) {
828
+ const { creator, identity, voteAccount, initialCollateral, withdrawalAuthority } = props;
829
+ const [validatorBondAccountAddress] = this.getValidatorBondPDA(voteAccount);
830
+ const accountInfo = await this.connection.getAccountInfo(validatorBondAccountAddress);
831
+ if (accountInfo) {
832
+ throw new Error("Validator bond account already exists");
833
+ }
834
+ const [globalState] = this.getGlobalStatePDA();
835
+ const collateralLamports = new anchor.BN(initialCollateral * web3_js.LAMPORTS_PER_SOL);
836
+ return this.program.methods.bondInit(collateralLamports, withdrawalAuthority ?? null).accountsStrict({
837
+ creator,
838
+ globalState,
839
+ validatorBondAccount: validatorBondAccountAddress,
840
+ identity,
841
+ voteAccount,
842
+ systemProgram: web3_js.SystemProgram.programId
843
+ }).instruction();
844
+ }
845
+ // Build top up collateral instruction
846
+ buildTopUpCollateralInstruction(props) {
847
+ const { user, voteAccount, amount } = props;
848
+ const [validatorBondAccountAddress] = this.getValidatorBondPDA(voteAccount);
849
+ const amountLamports = new anchor.BN(amount * web3_js.LAMPORTS_PER_SOL);
850
+ return this.program.methods.bondTopUp(amountLamports).accountsStrict({
851
+ validatorBondAccount: validatorBondAccountAddress,
852
+ depositor: user,
853
+ systemProgram: web3_js.SystemProgram.programId
854
+ }).instruction();
855
+ }
856
+ async buildWithdrawCollateralInstruction(props) {
857
+ const { withdrawalAuthority: user, voteAccount, destination, amount } = props;
858
+ const [validatorBondAccountAddress] = this.getValidatorBondPDA(voteAccount);
859
+ const amountLamports = new anchor.BN(amount * web3_js.LAMPORTS_PER_SOL);
860
+ return this.program.methods.bondWithdraw(amountLamports).accountsStrict({
861
+ validatorBondAccount: validatorBondAccountAddress,
862
+ withdrawalAuthority: user,
863
+ destination,
864
+ systemProgram: web3_js.SystemProgram.programId
865
+ }).instruction();
866
+ }
867
+ // Build withdraw compensation instruction
868
+ buildWithdrawCompensationInstruction(props) {
869
+ const { authority, voteAccount, amount } = props;
870
+ const [globalState] = this.getGlobalStatePDA();
871
+ const [validatorBondAccountAddress] = this.getValidatorBondPDA(voteAccount);
872
+ const amountLamports = new anchor.BN(amount * web3_js.LAMPORTS_PER_SOL);
873
+ return this.program.methods.withdrawCompensation(amountLamports).accountsStrict({
874
+ globalState,
875
+ validatorBondAccount: validatorBondAccountAddress,
876
+ reserve: this.config.reserveAddress,
877
+ authority,
878
+ systemProgram: web3_js.SystemProgram.programId
879
+ }).instruction();
880
+ }
881
+ // Build multiple withdraw compensation instructions
882
+ buildWithdrawCompensationsInstructions(authority, withdrawals) {
883
+ return Promise.all(
884
+ withdrawals.map(
885
+ ({ voteAccount, amount }) => this.buildWithdrawCompensationInstruction({ authority, voteAccount, amount })
886
+ )
887
+ );
888
+ }
889
+ // Get validator bond account state
890
+ async getValidatorBondAccount(voteAccount) {
891
+ const [validatorBondAccountAddress] = this.getValidatorBondPDA(voteAccount);
892
+ try {
893
+ const account = await this.program.account.validatorBondAccount.fetch(validatorBondAccountAddress);
894
+ return {
895
+ identity: account.identity.toString(),
896
+ voteAccount: account.voteAccount.toString(),
897
+ withdrawalAuthority: account.withdrawalAuthority ? account.withdrawalAuthority.toString() : null,
898
+ totalWithdrawn: account.totalWithdrawn.toNumber() / web3_js.LAMPORTS_PER_SOL,
899
+ lastWithdrawalEpoch: account.lastWithdrawalEpoch.toNumber(),
900
+ isActive: account.isActive,
901
+ createdAt: account.createdAt.toNumber() * 1e3,
902
+ // TODO
903
+ bump: account.bump
904
+ };
905
+ } catch {
906
+ return null;
907
+ }
908
+ }
909
+ /**
910
+ * Get the collateral balance of a validator bond account
911
+ * @param voteAccount - The vote account public key
912
+ * @returns The available collateral balance in SOL (excluding rent-exempt amount)
913
+ */
914
+ async getValidatorCollateralBalance(voteAccount) {
915
+ const [validatorBondAccountAddress] = this.getValidatorBondPDA(voteAccount);
916
+ const accountInfo = await this.connection.getAccountInfo(validatorBondAccountAddress);
917
+ if (!accountInfo) {
918
+ return 0;
919
+ }
920
+ const rentExempt = await this.connection.getMinimumBalanceForRentExemption(
921
+ accountInfo.data.length
922
+ );
923
+ const availableBalance = Math.max(0, accountInfo.lamports - rentExempt);
924
+ return availableBalance / web3_js.LAMPORTS_PER_SOL;
925
+ }
926
+ // Get global state state
927
+ async getGlobalState() {
928
+ const [globalState] = this.getGlobalStatePDA();
929
+ try {
930
+ const account = await this.program.account.globalState.fetch(globalState);
931
+ return {
932
+ authority: account.authority.toString(),
933
+ totalValidators: account.totalValidators,
934
+ totalWithdrawn: account.totalWithdrawn.toNumber() / web3_js.LAMPORTS_PER_SOL
935
+ };
936
+ } catch {
937
+ return null;
938
+ }
939
+ }
940
+ // Get current epoch
941
+ async getCurrentEpoch() {
942
+ const epochInfo = await this.connection.getEpochInfo();
943
+ return epochInfo.epoch;
944
+ }
945
+ // Helper methods for backward compatibility (can be removed if not needed)
946
+ async initialize(authority) {
947
+ const authorityPubkey = authority || this.provider.wallet.publicKey;
948
+ const ix = await this.buildInitializeInstruction({ authority: authorityPubkey });
949
+ const tx = await this.provider.sendAndConfirm(
950
+ new web3_js.Transaction().add(ix),
951
+ []
952
+ );
953
+ return tx;
954
+ }
955
+ // Note: this method will be removed or changed in the future (CLI only)
956
+ async registerValidator(voteAccount, initialCollateral, withdrawalAuthority, identity) {
957
+ const identityPubkey = identity ?? this.provider.wallet.publicKey;
958
+ const ix = await this.buildRegisterValidatorInstruction(
959
+ { creator: identityPubkey, identity: identityPubkey, voteAccount, initialCollateral, withdrawalAuthority }
960
+ );
961
+ const tx = await this.provider.sendAndConfirm(
962
+ new web3_js.Transaction().add(ix),
963
+ []
964
+ );
965
+ return tx;
966
+ }
967
+ async topUpCollateral(voteAccount, amount, validator) {
968
+ const userPubkey = validator ?? this.provider.wallet.publicKey;
969
+ const ix = await this.buildTopUpCollateralInstruction(
970
+ { user: userPubkey, voteAccount, amount }
971
+ );
972
+ const tx = await this.provider.sendAndConfirm(
973
+ new web3_js.Transaction().add(ix),
974
+ []
975
+ );
976
+ return tx;
977
+ }
978
+ async withdrawCollateral(voteAccount, destination, amount, withdrawalAuthority) {
979
+ const authorityPubkey = withdrawalAuthority ?? this.provider.wallet.publicKey;
980
+ const ix = await this.buildWithdrawCollateralInstruction(
981
+ { withdrawalAuthority: authorityPubkey, voteAccount, destination, amount }
982
+ );
983
+ const tx = await this.provider.sendAndConfirm(
984
+ new web3_js.Transaction().add(ix),
985
+ []
986
+ );
987
+ return tx;
988
+ }
989
+ async claimCompensation(voteAccount, amount, authority) {
990
+ const authorityPubkey = authority ?? this.provider.wallet.publicKey;
991
+ const ix = await this.buildWithdrawCompensationInstruction(
992
+ { authority: authorityPubkey, voteAccount, amount }
993
+ );
994
+ const tx = await this.provider.sendAndConfirm(
995
+ new web3_js.Transaction().add(ix),
996
+ []
997
+ );
998
+ return tx;
999
+ }
1000
+ /**
1001
+ * Get transaction history grouped by epochs
1002
+ * @param voteAccount - The vote account to get history for
1003
+ * @param epochsCount - Number of recent epochs to return (default: 10)
1004
+ * @returns Array of epoch history items sorted by epoch (descending)
1005
+ */
1006
+ async getHistoryGroupedByEpochs(voteAccount, epochsCount = 10) {
1007
+ const currentEpoch = await this.getCurrentEpoch();
1008
+ const fullHistory = await this.getFullHistory(voteAccount);
1009
+ const epochMap = /* @__PURE__ */ new Map();
1010
+ for (const item of fullHistory) {
1011
+ if (item.epoch < currentEpoch - epochsCount + 1) {
1012
+ continue;
1013
+ }
1014
+ if (!epochMap.has(item.epoch)) {
1015
+ epochMap.set(item.epoch, {
1016
+ epoch: item.epoch,
1017
+ deposits: 0,
1018
+ withdrawals: 0,
1019
+ balanceChange: 0,
1020
+ signatures: []
1021
+ });
1022
+ }
1023
+ const epochData = epochMap.get(item.epoch);
1024
+ if (item.type === "deposit") {
1025
+ epochData.deposits += item.amount;
1026
+ } else if (item.type === "withdrawal") {
1027
+ epochData.withdrawals += item.amount;
1028
+ }
1029
+ if (!epochData.signatures.includes(item.signature)) {
1030
+ epochData.signatures.push(item.signature);
1031
+ }
1032
+ }
1033
+ for (const epochData of epochMap.values()) {
1034
+ epochData.balanceChange = epochData.deposits - epochData.withdrawals;
1035
+ }
1036
+ const result = [...epochMap.values()].toSorted((a, b) => b.epoch - a.epoch);
1037
+ return result;
1038
+ }
1039
+ async getHistory(voteAccount, options) {
1040
+ const [ValidatorBondAccount] = this.getValidatorBondPDA(voteAccount);
1041
+ const signatures = await this.connection.getSignaturesForAddress(
1042
+ ValidatorBondAccount,
1043
+ {
1044
+ limit: options?.limit || 1e3,
1045
+ before: options?.before,
1046
+ until: options?.until
1047
+ }
1048
+ );
1049
+ const signatureStrings = signatures.map((sig) => sig.signature);
1050
+ const BATCH_SIZE = 100;
1051
+ const allTransactions = [];
1052
+ for (let i = 0; i < signatureStrings.length; i += BATCH_SIZE) {
1053
+ const batch = signatureStrings.slice(i, i + BATCH_SIZE);
1054
+ const transactions = await this.connection.getParsedTransactions(
1055
+ batch,
1056
+ {
1057
+ maxSupportedTransactionVersion: 0
1058
+ }
1059
+ );
1060
+ allTransactions.push(...transactions);
1061
+ }
1062
+ const cluster = options?.cluster || "mainnet-beta";
1063
+ const history = [];
1064
+ for (const [idx, tx] of allTransactions.entries()) {
1065
+ const sigInfo = signatures[idx];
1066
+ if (!tx || !tx.meta) {
1067
+ continue;
1068
+ }
1069
+ try {
1070
+ const slot = tx.slot || 0;
1071
+ const instructions = tx.transaction.message.instructions;
1072
+ for (const instruction of instructions) {
1073
+ if ("programId" in instruction && instruction.programId.equals(this.program.programId)) {
1074
+ const ixData = instruction;
1075
+ if ("parsed" in ixData && ixData.parsed) {
1076
+ continue;
1077
+ }
1078
+ const data = ixData.data;
1079
+ if (!data) {
1080
+ continue;
1081
+ }
1082
+ let type = null;
1083
+ let amount = 0;
1084
+ try {
1085
+ const dataBuffer = bs58__default.default.decode(data);
1086
+ if (dataBuffer.length >= 16) {
1087
+ const discriminator = dataBuffer.slice(0, 8);
1088
+ const bondInitDiscriminator = this.getInstructionDiscriminator("bondInit");
1089
+ const bondTopUpDiscriminator = this.getInstructionDiscriminator("bondTopUp");
1090
+ const withdrawCompensationDiscriminator = this.getInstructionDiscriminator("withdrawCompensation");
1091
+ const bondWithdrawDiscriminator = this.getInstructionDiscriminator("bondWithdraw");
1092
+ const amountBytes = dataBuffer.slice(8, 16);
1093
+ const amountBN = new anchor.BN(amountBytes, "le");
1094
+ amount = amountBN.toNumber() / web3_js.LAMPORTS_PER_SOL;
1095
+ if (Buffer.from(discriminator).equals(Buffer.from(bondInitDiscriminator))) {
1096
+ type = "deposit" /* Deposit */;
1097
+ } else if (Buffer.from(discriminator).equals(Buffer.from(bondTopUpDiscriminator))) {
1098
+ type = "deposit" /* Deposit */;
1099
+ } else if (Buffer.from(discriminator).equals(Buffer.from(withdrawCompensationDiscriminator))) {
1100
+ type = "compensation" /* Compensation */;
1101
+ } else if (Buffer.from(discriminator).equals(Buffer.from(bondWithdrawDiscriminator))) {
1102
+ type = "withdrawal" /* Withdrawal */;
1103
+ }
1104
+ }
1105
+ } catch {
1106
+ console.warn("Failed to decode instruction data");
1107
+ }
1108
+ if (type && amount > 0) {
1109
+ let beforeBalance;
1110
+ let afterBalance;
1111
+ const accountIndex = tx.transaction.message.accountKeys.findIndex(
1112
+ (key) => key.pubkey.equals(ValidatorBondAccount)
1113
+ );
1114
+ if (accountIndex !== -1 && tx.meta.preBalances && tx.meta.postBalances) {
1115
+ beforeBalance = Number(tx.meta.preBalances[accountIndex] || 0) / web3_js.LAMPORTS_PER_SOL;
1116
+ afterBalance = Number(tx.meta.postBalances[accountIndex] || 0) / web3_js.LAMPORTS_PER_SOL;
1117
+ }
1118
+ history.push({
1119
+ signature: sigInfo.signature,
1120
+ slot,
1121
+ epoch: slotToEpoch(slot, cluster),
1122
+ type,
1123
+ amount,
1124
+ beforeBalance,
1125
+ afterBalance
1126
+ });
1127
+ }
1128
+ }
1129
+ }
1130
+ } catch (error) {
1131
+ console.error(`Error processing transaction ${sigInfo.signature}:`, error);
1132
+ }
1133
+ }
1134
+ return history.toSorted((a, b) => b.slot - a.slot);
1135
+ }
1136
+ // Helper method to get paginated history
1137
+ async getFullHistory(voteAccount, pageSize = 100) {
1138
+ const allHistory = [];
1139
+ let before;
1140
+ while (true) {
1141
+ const batch = await this.getHistory(voteAccount, {
1142
+ limit: pageSize,
1143
+ before
1144
+ });
1145
+ if (batch.length === 0) {
1146
+ break;
1147
+ }
1148
+ allHistory.push(...batch);
1149
+ before = batch.at(-1)?.signature;
1150
+ if (batch.length < pageSize) {
1151
+ break;
1152
+ }
1153
+ }
1154
+ return allHistory;
1155
+ }
1156
+ getInstructionDiscriminator(instructionName) {
1157
+ const instruction = this.program.idl.instructions.find((ix) => ix.name === instructionName);
1158
+ if (!instruction) {
1159
+ throw new Error(`Instruction ${instructionName} not found in IDL`);
1160
+ }
1161
+ if (!instruction.discriminator || !Array.isArray(instruction.discriminator)) {
1162
+ throw new Error(`Discriminator not found for instruction ${instructionName}`);
1163
+ }
1164
+ return new Uint8Array(instruction.discriminator);
1165
+ }
1166
+ };
1167
+
1168
+ // src/common.ts
1169
+ var PROGRAM_ID = "4a3YovKEfm4jWhczCzJciHXL1xVkXWfGQjRCaMft7M4G";
1170
+ var RESERVE_ADDRESS = "61mS9nEir6jx6cvte6NzQpyrFk3Fj4krMNLuHhi4tjJz";
1171
+ function loadConfig() {
1172
+ const rpcUrl = process.env.SOLANA_RPC_URL || "https://api.devnet.solana.com";
1173
+ const programId = new web3_js.PublicKey(
1174
+ PROGRAM_ID
1175
+ );
1176
+ const reserveAddress = new web3_js.PublicKey(
1177
+ RESERVE_ADDRESS
1178
+ );
1179
+ return {
1180
+ rpcUrl,
1181
+ programId,
1182
+ reserveAddress
1183
+ };
1184
+ }
1185
+ function loadKeypair(keypairPath) {
1186
+ try {
1187
+ const keypairString = fs.readFileSync(keypairPath, "utf8");
1188
+ const keypairData = JSON.parse(keypairString);
1189
+ return web3_js.Keypair.fromSecretKey(new Uint8Array(keypairData));
1190
+ } catch (error) {
1191
+ throw new Error(`Failed to load keypair from ${keypairPath}: ${error}`);
1192
+ }
1193
+ }
1194
+
1195
+ exports.BondTransactionType = BondTransactionType;
1196
+ exports.JBondClient = JBondClient;
1197
+ exports.PROGRAM_ID = PROGRAM_ID;
1198
+ exports.RESERVE_ADDRESS = RESERVE_ADDRESS;
1199
+ exports.loadConfig = loadConfig;
1200
+ exports.loadKeypair = loadKeypair;
1201
+ //# sourceMappingURL=index.js.map
1202
+ //# sourceMappingURL=index.js.map