@jpool/bond-sdk 0.0.1-next.0 → 0.1.0-next.1

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