@jpool/bond-sdk 0.0.1-next.0

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