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

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