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