-
Notifications
You must be signed in to change notification settings - Fork 873
/
connection.ts
4367 lines (4019 loc) · 117 KB
/
connection.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import bs58 from 'bs58';
import {Buffer} from 'buffer';
import fetch from 'cross-fetch';
import type {Response} from 'cross-fetch';
import {
type as pick,
number,
string,
array,
boolean,
literal,
record,
union,
optional,
nullable,
coerce,
instance,
create,
tuple,
unknown,
any,
} from 'superstruct';
import type {Struct} from 'superstruct';
import {Client as RpcWebSocketClient} from 'rpc-websockets';
import RpcClient from 'jayson/lib/client/browser';
import {IWSRequestParams} from 'rpc-websockets/dist/lib/client';
import {AgentManager} from './agent-manager';
import {EpochSchedule} from './epoch-schedule';
import {SendTransactionError} from './errors';
import {NonceAccount} from './nonce-account';
import {PublicKey} from './publickey';
import {Signer} from './keypair';
import {MS_PER_SLOT} from './timing';
import {Transaction} from './transaction';
import {Message} from './message';
import assert from './util/assert';
import {sleep} from './util/sleep';
import {promiseTimeout} from './util/promise-timeout';
import {toBuffer} from './util/to-buffer';
import {makeWebsocketUrl} from './util/url';
import type {Blockhash} from './blockhash';
import type {FeeCalculator} from './fee-calculator';
import type {TransactionSignature} from './transaction';
import type {CompiledInstruction} from './message';
const PublicKeyFromString = coerce(
instance(PublicKey),
string(),
value => new PublicKey(value),
);
const RawAccountDataResult = tuple([string(), literal('base64')]);
const BufferFromRawAccountData = coerce(
instance(Buffer),
RawAccountDataResult,
value => Buffer.from(value[0], 'base64'),
);
/**
* Attempt to use a recent blockhash for up to 30 seconds
* @internal
*/
export const BLOCKHASH_CACHE_TIMEOUT_MS = 30 * 1000;
type RpcRequest = (methodName: string, args: Array<any>) => any;
type RpcBatchRequest = (requests: RpcParams[]) => any;
/**
* @internal
*/
export type RpcParams = {
methodName: string;
args: Array<any>;
};
export type TokenAccountsFilter =
| {
mint: PublicKey;
}
| {
programId: PublicKey;
};
/**
* Extra contextual information for RPC responses
*/
export type Context = {
slot: number;
};
/**
* Options for sending transactions
*/
export type SendOptions = {
/** disable transaction verification step */
skipPreflight?: boolean;
/** preflight commitment level */
preflightCommitment?: Commitment;
};
/**
* Options for confirming transactions
*/
export type ConfirmOptions = {
/** disable transaction verification step */
skipPreflight?: boolean;
/** desired commitment level */
commitment?: Commitment;
/** preflight commitment level */
preflightCommitment?: Commitment;
};
/**
* Options for getConfirmedSignaturesForAddress2
*/
export type ConfirmedSignaturesForAddress2Options = {
/**
* Start searching backwards from this transaction signature.
* @remark If not provided the search starts from the highest max confirmed block.
*/
before?: TransactionSignature;
/** Search until this transaction signature is reached, if found before `limit`. */
until?: TransactionSignature;
/** Maximum transaction signatures to return (between 1 and 1,000, default: 1,000). */
limit?: number;
};
/**
* Options for getSignaturesForAddress
*/
export type SignaturesForAddressOptions = {
/**
* Start searching backwards from this transaction signature.
* @remark If not provided the search starts from the highest max confirmed block.
*/
before?: TransactionSignature;
/** Search until this transaction signature is reached, if found before `limit`. */
until?: TransactionSignature;
/** Maximum transaction signatures to return (between 1 and 1,000, default: 1,000). */
limit?: number;
};
/**
* RPC Response with extra contextual information
*/
export type RpcResponseAndContext<T> = {
/** response context */
context: Context;
/** response value */
value: T;
};
/**
* @internal
*/
function createRpcResult<T, U>(result: Struct<T, U>) {
return union([
pick({
jsonrpc: literal('2.0'),
id: string(),
result,
}),
pick({
jsonrpc: literal('2.0'),
id: string(),
error: pick({
code: unknown(),
message: string(),
data: optional(any()),
}),
}),
]);
}
const UnknownRpcResult = createRpcResult(unknown());
/**
* @internal
*/
function jsonRpcResult<T, U>(schema: Struct<T, U>) {
return coerce(createRpcResult(schema), UnknownRpcResult, value => {
if ('error' in value) {
return value;
} else {
return {
...value,
result: create(value.result, schema),
};
}
});
}
/**
* @internal
*/
function jsonRpcResultAndContext<T, U>(value: Struct<T, U>) {
return jsonRpcResult(
pick({
context: pick({
slot: number(),
}),
value,
}),
);
}
/**
* @internal
*/
function notificationResultAndContext<T, U>(value: Struct<T, U>) {
return pick({
context: pick({
slot: number(),
}),
value,
});
}
/**
* The level of commitment desired when querying state
* <pre>
* 'processed': Query the most recent block which has reached 1 confirmation by the connected node
* 'confirmed': Query the most recent block which has reached 1 confirmation by the cluster
* 'finalized': Query the most recent block which has been finalized by the cluster
* </pre>
*/
export type Commitment =
| 'processed'
| 'confirmed'
| 'finalized'
| 'recent' // Deprecated as of v1.5.5
| 'single' // Deprecated as of v1.5.5
| 'singleGossip' // Deprecated as of v1.5.5
| 'root' // Deprecated as of v1.5.5
| 'max'; // Deprecated as of v1.5.5
/**
* A subset of Commitment levels, which are at least optimistically confirmed
* <pre>
* 'confirmed': Query the most recent block which has reached 1 confirmation by the cluster
* 'finalized': Query the most recent block which has been finalized by the cluster
* </pre>
*/
export type Finality = 'confirmed' | 'finalized';
/**
* Filter for largest accounts query
* <pre>
* 'circulating': Return the largest accounts that are part of the circulating supply
* 'nonCirculating': Return the largest accounts that are not part of the circulating supply
* </pre>
*/
export type LargestAccountsFilter = 'circulating' | 'nonCirculating';
/**
* Configuration object for changing `getLargestAccounts` query behavior
*/
export type GetLargestAccountsConfig = {
/** The level of commitment desired */
commitment?: Commitment;
/** Filter largest accounts by whether they are part of the circulating supply */
filter?: LargestAccountsFilter;
};
/**
* Configuration object for changing `getSupply` request behavior
*/
export type GetSupplyConfig = {
/** The level of commitment desired */
commitment?: Commitment;
/** Exclude non circulating accounts list from response */
excludeNonCirculatingAccountsList?: boolean;
};
/**
* Configuration object for changing query behavior
*/
export type SignatureStatusConfig = {
/** enable searching status history, not needed for recent transactions */
searchTransactionHistory: boolean;
};
/**
* Information describing a cluster node
*/
export type ContactInfo = {
/** Identity public key of the node */
pubkey: string;
/** Gossip network address for the node */
gossip: string | null;
/** TPU network address for the node (null if not available) */
tpu: string | null;
/** JSON RPC network address for the node (null if not available) */
rpc: string | null;
/** Software version of the node (null if not available) */
version: string | null;
};
/**
* Information describing a vote account
*/
export type VoteAccountInfo = {
/** Public key of the vote account */
votePubkey: string;
/** Identity public key of the node voting with this account */
nodePubkey: string;
/** The stake, in lamports, delegated to this vote account and activated */
activatedStake: number;
/** Whether the vote account is staked for this epoch */
epochVoteAccount: boolean;
/** Recent epoch voting credit history for this voter */
epochCredits: Array<[number, number, number]>;
/** A percentage (0-100) of rewards payout owed to the voter */
commission: number;
/** Most recent slot voted on by this vote account */
lastVote: number;
};
/**
* A collection of cluster vote accounts
*/
export type VoteAccountStatus = {
/** Active vote accounts */
current: Array<VoteAccountInfo>;
/** Inactive vote accounts */
delinquent: Array<VoteAccountInfo>;
};
/**
* Network Inflation
* (see https://docs.solana.com/implemented-proposals/ed_overview)
*/
export type InflationGovernor = {
foundation: number;
foundationTerm: number;
initial: number;
taper: number;
terminal: number;
};
const GetInflationGovernorResult = pick({
foundation: number(),
foundationTerm: number(),
initial: number(),
taper: number(),
terminal: number(),
});
/**
* The inflation reward for an epoch
*/
export type InflationReward = {
/** epoch for which the reward occurs */
epoch: number;
/** the slot in which the rewards are effective */
effectiveSlot: number;
/** reward amount in lamports */
amount: number;
/** post balance of the account in lamports */
postBalance: number;
};
/**
* Expected JSON RPC response for the "getInflationReward" message
*/
const GetInflationRewardResult = jsonRpcResult(
array(
nullable(
pick({
epoch: number(),
effectiveSlot: number(),
amount: number(),
postBalance: number(),
}),
),
),
);
/**
* Information about the current epoch
*/
export type EpochInfo = {
epoch: number;
slotIndex: number;
slotsInEpoch: number;
absoluteSlot: number;
blockHeight?: number;
transactionCount?: number;
};
const GetEpochInfoResult = pick({
epoch: number(),
slotIndex: number(),
slotsInEpoch: number(),
absoluteSlot: number(),
blockHeight: optional(number()),
transactionCount: optional(number()),
});
const GetEpochScheduleResult = pick({
slotsPerEpoch: number(),
leaderScheduleSlotOffset: number(),
warmup: boolean(),
firstNormalEpoch: number(),
firstNormalSlot: number(),
});
/**
* Leader schedule
* (see https://docs.solana.com/terminology#leader-schedule)
*/
export type LeaderSchedule = {
[address: string]: number[];
};
const GetLeaderScheduleResult = record(string(), array(number()));
/**
* Transaction error or null
*/
const TransactionErrorResult = nullable(union([pick({}), string()]));
/**
* Signature status for a transaction
*/
const SignatureStatusResult = pick({
err: TransactionErrorResult,
});
/**
* Transaction signature received notification
*/
const SignatureReceivedResult = literal('receivedSignature');
/**
* Version info for a node
*/
export type Version = {
/** Version of solana-core */
'solana-core': string;
'feature-set'?: number;
};
const VersionResult = pick({
'solana-core': string(),
'feature-set': optional(number()),
});
export type SimulatedTransactionAccountInfo = {
/** `true` if this account's data contains a loaded program */
executable: boolean;
/** Identifier of the program that owns the account */
owner: string;
/** Number of lamports assigned to the account */
lamports: number;
/** Optional data assigned to the account */
data: string[];
/** Optional rent epoch info for account */
rentEpoch?: number;
};
export type SimulatedTransactionResponse = {
err: TransactionError | string | null;
logs: Array<string> | null;
accounts?: SimulatedTransactionAccountInfo[] | null;
unitsConsumed?: number;
};
const SimulatedTransactionResponseStruct = jsonRpcResultAndContext(
pick({
err: nullable(union([pick({}), string()])),
logs: nullable(array(string())),
accounts: optional(
nullable(
array(
pick({
executable: boolean(),
owner: string(),
lamports: number(),
data: array(string()),
rentEpoch: optional(number()),
}),
),
),
),
unitsConsumed: optional(number()),
}),
);
export type ParsedInnerInstruction = {
index: number;
instructions: (ParsedInstruction | PartiallyDecodedInstruction)[];
};
export type TokenBalance = {
accountIndex: number;
mint: string;
uiTokenAmount: TokenAmount;
};
/**
* Metadata for a parsed confirmed transaction on the ledger
*/
export type ParsedConfirmedTransactionMeta = {
/** The fee charged for processing the transaction */
fee: number;
/** An array of cross program invoked parsed instructions */
innerInstructions?: ParsedInnerInstruction[] | null;
/** The balances of the transaction accounts before processing */
preBalances: Array<number>;
/** The balances of the transaction accounts after processing */
postBalances: Array<number>;
/** An array of program log messages emitted during a transaction */
logMessages?: Array<string> | null;
/** The token balances of the transaction accounts before processing */
preTokenBalances?: Array<TokenBalance> | null;
/** The token balances of the transaction accounts after processing */
postTokenBalances?: Array<TokenBalance> | null;
/** The error result of transaction processing */
err: TransactionError | null;
};
export type CompiledInnerInstruction = {
index: number;
instructions: CompiledInstruction[];
};
/**
* Metadata for a confirmed transaction on the ledger
*/
export type ConfirmedTransactionMeta = {
/** The fee charged for processing the transaction */
fee: number;
/** An array of cross program invoked instructions */
innerInstructions?: CompiledInnerInstruction[] | null;
/** The balances of the transaction accounts before processing */
preBalances: Array<number>;
/** The balances of the transaction accounts after processing */
postBalances: Array<number>;
/** An array of program log messages emitted during a transaction */
logMessages?: Array<string> | null;
/** The token balances of the transaction accounts before processing */
preTokenBalances?: Array<TokenBalance> | null;
/** The token balances of the transaction accounts after processing */
postTokenBalances?: Array<TokenBalance> | null;
/** The error result of transaction processing */
err: TransactionError | null;
};
/**
* A processed transaction from the RPC API
*/
export type TransactionResponse = {
/** The slot during which the transaction was processed */
slot: number;
/** The transaction */
transaction: {
/** The transaction message */
message: Message;
/** The transaction signatures */
signatures: string[];
};
/** Metadata produced from the transaction */
meta: ConfirmedTransactionMeta | null;
/** The unix timestamp of when the transaction was processed */
blockTime?: number | null;
};
/**
* A confirmed transaction on the ledger
*/
export type ConfirmedTransaction = {
/** The slot during which the transaction was processed */
slot: number;
/** The details of the transaction */
transaction: Transaction;
/** Metadata produced from the transaction */
meta: ConfirmedTransactionMeta | null;
/** The unix timestamp of when the transaction was processed */
blockTime?: number | null;
};
/**
* A partially decoded transaction instruction
*/
export type PartiallyDecodedInstruction = {
/** Program id called by this instruction */
programId: PublicKey;
/** Public keys of accounts passed to this instruction */
accounts: Array<PublicKey>;
/** Raw base-58 instruction data */
data: string;
};
/**
* A parsed transaction message account
*/
export type ParsedMessageAccount = {
/** Public key of the account */
pubkey: PublicKey;
/** Indicates if the account signed the transaction */
signer: boolean;
/** Indicates if the account is writable for this transaction */
writable: boolean;
};
/**
* A parsed transaction instruction
*/
export type ParsedInstruction = {
/** Name of the program for this instruction */
program: string;
/** ID of the program for this instruction */
programId: PublicKey;
/** Parsed instruction info */
parsed: any;
};
/**
* A parsed transaction message
*/
export type ParsedMessage = {
/** Accounts used in the instructions */
accountKeys: ParsedMessageAccount[];
/** The atomically executed instructions for the transaction */
instructions: (ParsedInstruction | PartiallyDecodedInstruction)[];
/** Recent blockhash */
recentBlockhash: string;
};
/**
* A parsed transaction
*/
export type ParsedTransaction = {
/** Signatures for the transaction */
signatures: Array<string>;
/** Message of the transaction */
message: ParsedMessage;
};
/**
* A parsed and confirmed transaction on the ledger
*/
export type ParsedConfirmedTransaction = {
/** The slot during which the transaction was processed */
slot: number;
/** The details of the transaction */
transaction: ParsedTransaction;
/** Metadata produced from the transaction */
meta: ParsedConfirmedTransactionMeta | null;
/** The unix timestamp of when the transaction was processed */
blockTime?: number | null;
};
/**
* A processed block fetched from the RPC API
*/
export type BlockResponse = {
/** Blockhash of this block */
blockhash: Blockhash;
/** Blockhash of this block's parent */
previousBlockhash: Blockhash;
/** Slot index of this block's parent */
parentSlot: number;
/** Vector of transactions with status meta and original message */
transactions: Array<{
/** The transaction */
transaction: {
/** The transaction message */
message: Message;
/** The transaction signatures */
signatures: string[];
};
/** Metadata produced from the transaction */
meta: ConfirmedTransactionMeta | null;
}>;
/** Vector of block rewards */
rewards?: Array<{
/** Public key of reward recipient */
pubkey: string;
/** Reward value in lamports */
lamports: number;
/** Account balance after reward is applied */
postBalance: number | null;
/** Type of reward received */
rewardType: string | null;
}>;
/** The unix timestamp of when the block was processed */
blockTime: number | null;
};
/**
* A ConfirmedBlock on the ledger
*/
export type ConfirmedBlock = {
/** Blockhash of this block */
blockhash: Blockhash;
/** Blockhash of this block's parent */
previousBlockhash: Blockhash;
/** Slot index of this block's parent */
parentSlot: number;
/** Vector of transactions and status metas */
transactions: Array<{
transaction: Transaction;
meta: ConfirmedTransactionMeta | null;
}>;
/** Vector of block rewards */
rewards?: Array<{
pubkey: string;
lamports: number;
postBalance: number | null;
rewardType: string | null;
}>;
/** The unix timestamp of when the block was processed */
blockTime: number | null;
};
/**
* A ConfirmedBlock on the ledger with signatures only
*/
export type ConfirmedBlockSignatures = {
/** Blockhash of this block */
blockhash: Blockhash;
/** Blockhash of this block's parent */
previousBlockhash: Blockhash;
/** Slot index of this block's parent */
parentSlot: number;
/** Vector of signatures */
signatures: Array<string>;
/** The unix timestamp of when the block was processed */
blockTime: number | null;
};
/**
* A performance sample
*/
export type PerfSample = {
/** Slot number of sample */
slot: number;
/** Number of transactions in a sample window */
numTransactions: number;
/** Number of slots in a sample window */
numSlots: number;
/** Sample window in seconds */
samplePeriodSecs: number;
};
function createRpcClient(
url: string,
useHttps: boolean,
httpHeaders?: HttpHeaders,
fetchMiddleware?: FetchMiddleware,
disableRetryOnRateLimit?: boolean,
): RpcClient {
let agentManager: AgentManager | undefined;
if (!process.env.BROWSER) {
agentManager = new AgentManager(useHttps);
}
let fetchWithMiddleware:
| ((url: string, options: any) => Promise<Response>)
| undefined;
if (fetchMiddleware) {
fetchWithMiddleware = async (url: string, options: any) => {
const modifiedFetchArgs = await new Promise<[string, any]>(
(resolve, reject) => {
try {
fetchMiddleware(url, options, (modifiedUrl, modifiedOptions) =>
resolve([modifiedUrl, modifiedOptions]),
);
} catch (error) {
reject(error);
}
},
);
return await fetch(...modifiedFetchArgs);
};
}
const clientBrowser = new RpcClient(async (request, callback) => {
const agent = agentManager ? agentManager.requestStart() : undefined;
const options = {
method: 'POST',
body: request,
agent,
headers: Object.assign(
{
'Content-Type': 'application/json',
},
httpHeaders || {},
),
};
try {
let too_many_requests_retries = 5;
let res: Response;
let waitTime = 500;
for (;;) {
if (fetchWithMiddleware) {
res = await fetchWithMiddleware(url, options);
} else {
res = await fetch(url, options);
}
if (res.status !== 429 /* Too many requests */) {
break;
}
if (disableRetryOnRateLimit === true) {
break;
}
too_many_requests_retries -= 1;
if (too_many_requests_retries === 0) {
break;
}
console.log(
`Server responded with ${res.status} ${res.statusText}. Retrying after ${waitTime}ms delay...`,
);
await sleep(waitTime);
waitTime *= 2;
}
const text = await res.text();
if (res.ok) {
callback(null, text);
} else {
callback(new Error(`${res.status} ${res.statusText}: ${text}`));
}
} catch (err) {
if (err instanceof Error) callback(err);
} finally {
agentManager && agentManager.requestEnd();
}
}, {});
return clientBrowser;
}
function createRpcRequest(client: RpcClient): RpcRequest {
return (method, args) => {
return new Promise((resolve, reject) => {
client.request(method, args, (err: any, response: any) => {
if (err) {
reject(err);
return;
}
resolve(response);
});
});
};
}
function createRpcBatchRequest(client: RpcClient): RpcBatchRequest {
return (requests: RpcParams[]) => {
return new Promise((resolve, reject) => {
// Do nothing if requests is empty
if (requests.length === 0) resolve([]);
const batch = requests.map((params: RpcParams) => {
return client.request(params.methodName, params.args);
});
client.request(batch, (err: any, response: any) => {
if (err) {
reject(err);
return;
}
resolve(response);
});
});
};
}
/**
* Expected JSON RPC response for the "getInflationGovernor" message
*/
const GetInflationGovernorRpcResult = jsonRpcResult(GetInflationGovernorResult);
/**
* Expected JSON RPC response for the "getEpochInfo" message
*/
const GetEpochInfoRpcResult = jsonRpcResult(GetEpochInfoResult);
/**
* Expected JSON RPC response for the "getEpochSchedule" message
*/
const GetEpochScheduleRpcResult = jsonRpcResult(GetEpochScheduleResult);
/**
* Expected JSON RPC response for the "getLeaderSchedule" message
*/
const GetLeaderScheduleRpcResult = jsonRpcResult(GetLeaderScheduleResult);
/**
* Expected JSON RPC response for the "minimumLedgerSlot" and "getFirstAvailableBlock" messages
*/
const SlotRpcResult = jsonRpcResult(number());
/**
* Supply
*/
export type Supply = {
/** Total supply in lamports */
total: number;
/** Circulating supply in lamports */
circulating: number;
/** Non-circulating supply in lamports */
nonCirculating: number;
/** List of non-circulating account addresses */
nonCirculatingAccounts: Array<PublicKey>;
};
/**
* Expected JSON RPC response for the "getSupply" message
*/
const GetSupplyRpcResult = jsonRpcResultAndContext(
pick({
total: number(),
circulating: number(),
nonCirculating: number(),
nonCirculatingAccounts: array(PublicKeyFromString),
}),
);
/**
* Token amount object which returns a token amount in different formats
* for various client use cases.
*/
export type TokenAmount = {
/** Raw amount of tokens as string ignoring decimals */
amount: string;
/** Number of decimals configured for token's mint */
decimals: number;
/** Token amount as float, accounts for decimals */
uiAmount: number | null;
/** Token amount as string, accounts for decimals */
uiAmountString?: string;
};
/**
* Expected JSON RPC structure for token amounts
*/
const TokenAmountResult = pick({
amount: string(),
uiAmount: nullable(number()),
decimals: number(),
uiAmountString: optional(string()),
});
/**
* Token address and balance.
*/
export type TokenAccountBalancePair = {
/** Address of the token account */
address: PublicKey;
/** Raw amount of tokens as string ignoring decimals */
amount: string;
/** Number of decimals configured for token's mint */
decimals: number;
/** Token amount as float, accounts for decimals */
uiAmount: number | null;
/** Token amount as string, accounts for decimals */
uiAmountString?: string;
};
/**
* Expected JSON RPC response for the "getTokenLargestAccounts" message
*/
const GetTokenLargestAccountsResult = jsonRpcResultAndContext(
array(
pick({
address: PublicKeyFromString,
amount: string(),
uiAmount: nullable(number()),
decimals: number(),
uiAmountString: optional(string()),
}),
),
);
/**
* Expected JSON RPC response for the "getTokenAccountsByOwner" message
*/
const GetTokenAccountsByOwner = jsonRpcResultAndContext(
array(
pick({
pubkey: PublicKeyFromString,
account: pick({
executable: boolean(),
owner: PublicKeyFromString,
lamports: number(),
data: BufferFromRawAccountData,
rentEpoch: number(),
}),
}),
),
);