-
Notifications
You must be signed in to change notification settings - Fork 301
/
Copy pathasync_api.py
1120 lines (957 loc) · 50.6 KB
/
async_api.py
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
"""Async API client to interact with the Solana JSON RPC Endpoint.""" # pylint: disable=too-many-lines
import asyncio
from time import time
from typing import Dict, List, Optional, Sequence, Union
from solders.message import VersionedMessage
from solders.pubkey import Pubkey
from solders.rpc.responses import (
GetAccountInfoMaybeJsonParsedResp,
GetAccountInfoResp,
GetBalanceResp,
GetBlockCommitmentResp,
GetBlockHeightResp,
GetBlockResp,
GetBlocksResp,
GetBlockTimeResp,
GetClusterNodesResp,
GetEpochInfoResp,
GetEpochScheduleResp,
GetFeeForMessageResp,
GetFirstAvailableBlockResp,
GetGenesisHashResp,
GetHealthResp,
GetIdentityResp,
GetInflationGovernorResp,
GetInflationRateResp,
GetInflationRewardResp,
GetLargestAccountsResp,
GetLatestBlockhashResp,
GetLeaderScheduleResp,
GetMinimumBalanceForRentExemptionResp,
GetMultipleAccountsMaybeJsonParsedResp,
GetMultipleAccountsResp,
GetProgramAccountsMaybeJsonParsedResp,
GetProgramAccountsResp,
GetRecentPerformanceSamplesResp,
GetSignaturesForAddressResp,
GetSignatureStatusesResp,
GetSlotLeaderResp,
GetSlotResp,
GetSupplyResp,
GetTokenAccountBalanceResp,
GetTokenAccountsByDelegateJsonParsedResp,
GetTokenAccountsByDelegateResp,
GetTokenAccountsByOwnerJsonParsedResp,
GetTokenAccountsByOwnerResp,
GetTokenLargestAccountsResp,
GetTokenSupplyResp,
GetTransactionCountResp,
GetTransactionResp,
GetVersionResp,
GetVoteAccountsResp,
MinimumLedgerSlotResp,
RequestAirdropResp,
SendTransactionResp,
SimulateTransactionResp,
ValidatorExitResp,
)
from solders.signature import Signature
from solders.transaction import Transaction, VersionedTransaction
from solana.rpc import types
from .commitment import Commitment
from .core import (
_COMMITMENT_TO_SOLDERS,
TransactionExpiredBlockheightExceededError,
UnconfirmedTxError,
_ClientCore,
)
from .providers import async_http
class AsyncClient(_ClientCore): # pylint: disable=too-many-public-methods
"""Async client class.
Args:
endpoint: URL of the RPC endpoint.
commitment: Default bank state to query. It can be either "finalized", "confirmed" or "processed".
timeout: HTTP request timeout in seconds.
extra_headers: Extra headers to pass for HTTP request.
"""
def __init__(
self,
endpoint: Optional[str] = None,
commitment: Optional[Commitment] = None,
timeout: float = 10,
extra_headers: Optional[Dict[str, str]] = None,
proxy: Optional[str] = None,
) -> None:
"""Init API client."""
super().__init__(commitment)
self._provider = async_http.AsyncHTTPProvider(
endpoint, timeout=timeout, extra_headers=extra_headers, proxy=proxy
)
async def __aenter__(self) -> "AsyncClient":
"""Use as a context manager."""
await self._provider.__aenter__()
return self
async def __aexit__(self, _exc_type, _exc, _tb):
"""Exits the context manager."""
await self.close()
async def close(self) -> None:
"""Use this when you are done with the client."""
await self._provider.close()
async def is_connected(self) -> bool:
"""Health check.
>>> solana_client = AsyncClient("http://localhost:8899")
>>> asyncio.run(solana_client.is_connected()) # doctest: +SKIP
True
Returns:
True if the client is connected.
"""
body = self._get_health_body()
response = await self._provider.make_request(body, GetHealthResp)
return response.value == "ok"
async def get_balance(self, pubkey: Pubkey, commitment: Optional[Commitment] = None) -> GetBalanceResp:
"""Returns the balance of the account of provided Pubkey.
Args:
pubkey: Pubkey of account to query
commitment: Bank state to query. It can be either "finalized", "confirmed" or "processed".
Example:
>>> from solders.pubkey import Pubkey
>>> solana_client = AsyncClient("http://localhost:8899")
>>> (await solana_client.get_balance(Pubkey([0] * 31 + [1]))).value # doctest: +SKIP
0
"""
body = self._get_balance_body(pubkey, commitment)
return await self._provider.make_request(body, GetBalanceResp)
async def get_account_info(
self,
pubkey: Pubkey,
commitment: Optional[Commitment] = None,
encoding: str = "base64",
data_slice: Optional[types.DataSliceOpts] = None,
) -> GetAccountInfoResp:
"""Returns all the account info for the specified public key.
Args:
pubkey: Pubkey of account to query
commitment: Bank state to query. It can be either "finalized", "confirmed" or "processed".
encoding: (optional) Encoding for Account data, either "base58" (slow), "base64", or
"jsonParsed". Default is "base64".
- "base58" is limited to Account data of less than 128 bytes.
- "base64" will return base64 encoded data for Account data of any size.
- "jsonParsed" encoding attempts to use program-specific state parsers to return more human-readable and explicit account state data.
If jsonParsed is requested but a parser cannot be found, the field falls back to base64 encoding,
detectable when the data field is type. (jsonParsed encoding is UNSTABLE).
data_slice: (optional) Option to limit the returned account data using the provided `offset`: <usize> and
`length`: <usize> fields; only available for "base58" or "base64" encoding.
Example:
>>> from solders.pubkey import Pubkey
>>> solana_client = AsyncClient("http://localhost:8899")
>>> (await solana_client.get_account_info(Pubkey([0] * 31 + [1]))).value # doctest: +SKIP
Account(
Account {
lamports: 4104230290,
data.len: 0,
owner: 11111111111111111111111111111111,
executable: false,
rent_epoch: 371,
},
)
""" # noqa: E501 # pylint: disable=line-too-long
body = self._get_account_info_body(
pubkey=pubkey,
commitment=commitment,
encoding=encoding,
data_slice=data_slice,
)
return await self._provider.make_request(body, GetAccountInfoResp)
async def get_account_info_json_parsed(
self,
pubkey: Pubkey,
commitment: Optional[Commitment] = None,
) -> GetAccountInfoMaybeJsonParsedResp:
"""Returns all the account info for the specified public key.
If JSON formatting is not available for this account, base64 is returned.
Args:
pubkey: Pubkey of account to query
commitment: Bank state to query. It can be either "finalized", "confirmed" or "processed".
Example:
>>> from solders.pubkey import Pubkey
>>> solana_client = AsyncClient("http://localhost:8899")
>>> (await solana_client.get_account_info_json_parsed(Pubkey([0] * 31 + [1]))).value.owner # doctest: +SKIP
Pubkey(
11111111111111111111111111111111,
)
"""
body = self._get_account_info_body(pubkey=pubkey, commitment=commitment, encoding="jsonParsed", data_slice=None)
return await self._provider.make_request(body, GetAccountInfoMaybeJsonParsedResp)
async def get_block_commitment(self, slot: int) -> GetBlockCommitmentResp:
"""Fetch the commitment for particular block.
Args:
slot: Block, identified by Slot.
Example:
>>> solana_client = AsyncClient("http://localhost:8899")
>>> (await solana_client.get_block_commitment(0)).total_stake # doctest: +SKIP
497717120
"""
body = self._get_block_commitment_body(slot)
return await self._provider.make_request(body, GetBlockCommitmentResp)
async def get_block_time(self, slot: int) -> GetBlockTimeResp:
"""Fetch the estimated production time of a block.
Args:
slot: Block, identified by Slot.
Example:
>>> solana_client = AsyncClient("http://localhost:8899")
>>> (await solana_client.get_block_time(5)).value # doctest: +SKIP
1598400007
"""
body = self._get_block_time_body(slot)
return await self._provider.make_request(body, GetBlockTimeResp)
async def get_cluster_nodes(self) -> GetClusterNodesResp:
"""Returns information about all the nodes participating in the cluster.
Example:
>>> solana_client = AsyncClient("http://localhost:8899")
>>> (await solana_client.get_cluster_nodes()).value[0].tpu # doctest: +SKIP
'139.178.65.155:8004'
"""
return await self._provider.make_request(self._get_cluster_nodes, GetClusterNodesResp)
async def get_block(
self,
slot: int,
encoding: str = "json",
max_supported_transaction_version: Union[int, None] = None,
) -> GetBlockResp:
"""Returns identity and transaction information about a confirmed block in the ledger.
Args:
slot: Slot, as u64 integer.
encoding: (optional) Encoding for the returned Transaction, either "json", "jsonParsed",
"base58" (slow), or "base64". If parameter not provided, the default encoding is JSON.
max_supported_transaction_version: (optional) The max transaction version to return in
responses. If the requested transaction is a higher version, an error will be returned
Example:
>>> solana_client = AsyncClient("http://localhost:8899")
>>> (await solana_client.get_block(1)).value.blockhash # doctest: +SKIP
Hash(
EtWTRABZaYq6iMfeYKouRu166VU2xqa1wcaWoxPkrZBG,
)
"""
body = self._get_block_body(slot, encoding, max_supported_transaction_version)
return await self._provider.make_request(body, GetBlockResp)
async def get_recent_performance_samples(self, limit: Optional[int] = None) -> GetRecentPerformanceSamplesResp:
"""Returns a list of recent performance samples, in reverse slot order.
Performance samples are taken every 60 seconds and include the number of transactions and slots that occur in a given time window.
Args:
limit: Limit (optional) number of samples to return (maximum 720)
Examples:
>>> solana_client = AsyncClient("http://localhost:8899")
>>> (await solana_client.get_recent_performance_samples(1)).value[0] # doctest: +SKIP
RpcPerfSample(
RpcPerfSample {
slot: 168036172,
num_transactions: 7159,
num_slots: 158,
sample_period_secs: 60,
},
)
""" # noqa: E501 # pylint: disable=line-too-long
body = self._get_recent_performance_samples_body(limit)
return await self._provider.make_request(body, GetRecentPerformanceSamplesResp)
async def get_block_height(self, commitment: Optional[Commitment] = None) -> GetBlockHeightResp:
"""Returns the current block height of the node.
Args:
commitment: Bank state to query. It can be either "finalized", "confirmed" or "processed".
Example:
>>> solana_client = AsyncClient("http://localhost:8899")
>>> (await solana_client.get_block_height()).value # doctest: +SKIP
1233
"""
body = self._get_block_height_body(commitment)
return await self._provider.make_request(body, GetBlockHeightResp)
async def get_blocks(self, start_slot: int, end_slot: Optional[int] = None) -> GetBlocksResp:
"""Returns a list of confirmed blocks.
Args:
start_slot: Start slot, as u64 integer.
end_slot: (optional) End slot, as u64 integer.
Example:
>>> solana_client = AsyncClient("http://localhost:8899")
>>> (await solana_client.get_blocks(5, 10)).value # doctest: +SKIP
[5, 6, 7, 8, 9, 10]
"""
body = self._get_blocks_body(start_slot, end_slot)
return await self._provider.make_request(body, GetBlocksResp)
async def get_signatures_for_address(
self,
account: Pubkey,
before: Optional[Signature] = None,
until: Optional[Signature] = None,
limit: Optional[int] = None,
commitment: Optional[Commitment] = None,
) -> GetSignaturesForAddressResp:
"""Returns confirmed signatures for transactions involving an address.
Signatures are returned backwards in time from the provided signature or
most recent confirmed block.
Args:
account: Account to be queried.
before: (optional) Start searching backwards from this transaction signature.
If not provided the search starts from the top of the highest max confirmed block.
until: (optional) Search until this transaction signature, if found before limit reached.
limit: (optional) Maximum transaction signatures to return (between 1 and 1,000, default: 1,000).
commitment: (optional) Bank state to query. It can be either "finalized", "confirmed" or "processed".
Example:
>>> solana_client = AsyncClient("http://localhost:8899")
>>> from solders.pubkey import Pubkey
>>> pubkey = Pubkey.from_string("Vote111111111111111111111111111111111111111")
>>> (await solana_client.get_signatures_for_address(pubkey, limit=1)).value[0].signature # doctest: +SKIP
Signature(
1111111111111111111111111111111111111111111111111111111111111111,
)
"""
body = self._get_signatures_for_address_body(account, before, until, limit, commitment)
return await self._provider.make_request(body, GetSignaturesForAddressResp)
async def get_transaction(
self,
tx_sig: Signature,
encoding: str = "json",
commitment: Optional[Commitment] = None,
max_supported_transaction_version: Optional[int] = None,
) -> GetTransactionResp:
"""Returns transaction details for a confirmed transaction.
Args:
tx_sig: Transaction signature as base-58 encoded string N encoding attempts to use program-specific
instruction parsers to return more human-readable and explicit data in the
`transaction.message.instructions` list.
encoding: (optional) Encoding for the returned Transaction, either "json", "jsonParsed",
"base58" (slow), or "base64". If parameter not provided, the default encoding is JSON.
commitment: Bank state to query. It can be either "finalized", "confirmed" or "processed".
max_supported_transaction_version: (optional) The max transaction version to return in responses.
If the requested transaction is a higher version, an error will be returned
Example:
>>> solana_client = AsyncClient("http://localhost:8899")
>>> from solders.signature import Signature
>>> sig = Signature.from_string("3PtGYH77LhhQqTXP4SmDVJ85hmDieWsgXCUbn14v7gYyVYPjZzygUQhTk3bSTYnfA48vCM1rmWY7zWL3j1EVKmEy")
>>> (await solana_client.get_transaction(sig)).value.block_time # doctest: +SKIP
1234
""" # noqa: E501 # pylint: disable=line-too-long
body = self._get_transaction_body(tx_sig, encoding, commitment, max_supported_transaction_version)
return await self._provider.make_request(body, GetTransactionResp)
async def get_epoch_info(self, commitment: Optional[Commitment] = None) -> GetEpochInfoResp:
"""Returns information about the current epoch.
Args:
commitment: Bank state to query. It can be either "finalized", "confirmed" or "processed".
Example:
>>> solana_client = AsyncClient("http://localhost:8899")
>>> (await solana_client.get_epoch_info()).value.epoch # doctest: +SKIP
0
"""
body = self._get_epoch_info_body(commitment)
return await self._provider.make_request(body, GetEpochInfoResp)
async def get_epoch_schedule(self) -> GetEpochScheduleResp:
"""Returns epoch schedule information from this cluster's genesis config.
Example:
>>> solana_client = AsyncClient("http://localhost:8899")
>>> (await solana_client.get_epoch_schedule()).value.slots_per_epoch # doctest: +SKIP
8192
"""
return await self._provider.make_request(self._get_epoch_schedule, GetEpochScheduleResp)
async def get_fee_for_message(
self, message: VersionedMessage, commitment: Optional[Commitment] = None
) -> GetFeeForMessageResp:
"""Returns the fee for a message.
Args:
message: Message that the fee is requested for.
commitment: Bank state to query. It can be either "finalized", "confirmed" or "processed".
Example:
>>> from solders.keypair import Keypair
>>> from solders.system_program import TransferParams, transfer
>>> from solders.message import Message
>>> leading_zeros = [0] * 31
>>> sender, receiver = Keypair.from_seed(leading_zeros + [1]), Keypair.from_seed(leading_zeros + [2])
>>> msg = Message([transfer(TransferParams(
... from_pubkey=sender.pubkey(), to_pubkey=receiver.pubkey(), lamports=1000))])
>>> solana_client = AsyncClient("http://localhost:8899")
>>> (await solana_client.get_fee_for_message(msg)).value # doctest: +SKIP
5000
"""
body = self._get_fee_for_message_body(message, commitment)
return await self._provider.make_request(body, GetFeeForMessageResp)
async def get_first_available_block(self) -> GetFirstAvailableBlockResp:
"""Returns the slot of the lowest confirmed block that has not been purged from the ledger.
Example:
>>> solana_client = AsyncClient("http://localhost:8899")
>>> (await solana_client.get_first_available_block()).value # doctest: +SKIP
1
"""
return await self._provider.make_request(self._get_first_available_block, GetFirstAvailableBlockResp)
async def get_genesis_hash(self) -> GetGenesisHashResp:
"""Returns the genesis hash.
Example:
>>> solana_client = AsyncClient("http://localhost:8899")
>>> (await solana_client.get_genesis_hash()).value # doctest: +SKIP
Hash(
EtWTRABZaYq6iMfeYKouRu166VU2xqa1wcaWoxPkrZBG,
)
"""
return await self._provider.make_request(self._get_genesis_hash, GetGenesisHashResp)
async def get_identity(self) -> GetIdentityResp:
"""Returns the identity pubkey for the current node.
Example:
>>> solana_client = AsyncClient("http://localhost:8899")
>>> (await solana_client.get_identity()).value.identity # doctest: +SKIP
Pubkey(
2LVtX3Wq5bhqAYYaUYBRknWaYrsfYiXLQBHTxtHWD2mv,
)
"""
return await self._provider.make_request(self._get_identity, GetIdentityResp)
async def get_inflation_governor(self, commitment: Optional[Commitment] = None) -> GetInflationGovernorResp:
"""Returns the current inflation governor.
Args:
commitment: Bank state to query. It can be either "finalized", "confirmed" or "processed".
Example:
>>> solana_client = AsyncClient("http://localhost:8899")
>>> await (solana_client.get_inflation_governor()).value.foundation # doctest: +SKIP
0.05
"""
body = self._get_inflation_governor_body(commitment)
return await self._provider.make_request(body, GetInflationGovernorResp)
async def get_inflation_rate(self) -> GetInflationRateResp:
"""Returns the specific inflation values for the current epoch.
Example:
>>> solana_client = AsyncClient("http://localhost:8899")
>>> (await solana_client.get_inflation_rate()).value.epoch # doctest: +SKIP
1
"""
return await self._provider.make_request(self._get_inflation_rate, GetInflationRateResp)
async def get_inflation_reward(
self, pubkeys: List[Pubkey], epoch: Optional[int] = None, commitment: Optional[Commitment] = None
) -> GetInflationRewardResp:
"""Returns the inflation / staking reward for a list of addresses for an epoch.
Args:
pubkeys: An array of addresses to query, as base-58 encoded strings
epoch: (optional) An epoch for which the reward occurs. If omitted, the previous epoch will be used
commitment: Bank state to query. It can be either "finalized" or "confirmed".
Example:
>>> solana_client = AsyncClient("http://localhost:8899")
>>> (await solana_client.get_inflation_reward()).value.amount # doctest: +SKIP
2500
"""
body = self._get_inflation_reward_body(pubkeys, epoch, commitment)
return await self._provider.make_request(body, GetInflationRewardResp)
async def get_largest_accounts(
self, filter_opt: Optional[str] = None, commitment: Optional[Commitment] = None
) -> GetLargestAccountsResp:
"""Returns the 20 largest accounts, by lamport balance.
Args:
filter_opt: Filter results by account type; currently supported: circulating|nonCirculating.
commitment: Bank state to query. It can be either "finalized", "confirmed" or "processed".
Example:
>>> solana_client = AsyncClient("http://localhost:8899")
>>> (await solana_client.get_largest_accounts()).value[0].lamports # doctest: +SKIP
500000000000000000
"""
body = self._get_largest_accounts_body(filter_opt, commitment)
return await self._provider.make_request(body, GetLargestAccountsResp)
async def get_leader_schedule(
self, epoch: Optional[int] = None, commitment: Optional[Commitment] = None
) -> GetLeaderScheduleResp:
"""Returns the leader schedule for an epoch.
Args:
epoch: Fetch the leader schedule for the epoch that corresponds to the provided slot.
If unspecified, the leader schedule for the current epoch is fetched.
commitment: Bank state to query. It can be either "finalized", "confirmed" or "processed".
Example:
>>> solana_client = AsyncClient("http://localhost:8899")
>>> resp = await solana_client.get_leader_schedule() # doctest: +SKIP
>>> list(resp.value.items())[0] # doctest: +SKIP
(Pubkey(
HMU77m6WSL9Xew9YvVCgz1hLuhzamz74eD9avi4XPdr,
), [346448, 346449, 346450, 346451, 369140, 369141, 369142, 369143, 384204, 384205, 384206, 384207])
"""
body = self._get_leader_schedule_body(epoch, commitment)
return await self._provider.make_request(body, GetLeaderScheduleResp)
async def get_minimum_balance_for_rent_exemption(
self, usize: int, commitment: Optional[Commitment] = None
) -> GetMinimumBalanceForRentExemptionResp:
"""Returns minimum balance required to make account rent exempt.
Args:
usize: Account data length.
commitment: Bank state to query. It can be either "finalized", "confirmed" or "processed".
Example:
>>> solana_client = AsyncClient("http://localhost:8899")
>>> (await solana_client.get_minimum_balance_for_rent_exemption(50)).value # doctest: +SKIP
1238880
"""
body = self._get_minimum_balance_for_rent_exemption_body(usize, commitment)
return await self._provider.make_request(body, GetMinimumBalanceForRentExemptionResp)
async def get_multiple_accounts(
self,
pubkeys: List[Pubkey],
commitment: Optional[Commitment] = None,
encoding: str = "base64",
data_slice: Optional[types.DataSliceOpts] = None,
) -> GetMultipleAccountsResp:
"""Returns all the account info for a list of public keys.
Args:
pubkeys: list of Pubkeys to query
commitment: Bank state to query. It can be either "finalized", "confirmed" or "processed".
encoding: (optional) Encoding for Account data, either "base58" (slow) or "base64".
- "base58" is limited to Account data of less than 128 bytes.
- "base64" will return base64 encoded data for Account data of any size.
data_slice: (optional) Option to limit the returned account data using the provided `offset`: <usize> and
`length`: <usize> fields; only available for "base58" or "base64" encoding.
Example:
>>> from solders.pubkey import Pubkey
>>> solana_client = AsyncClient("http://localhost:8899")
>>> pubkeys = [Pubkey.from_string("6ZWcsUiWJ63awprYmbZgBQSreqYZ4s6opowP4b7boUdh"), Pubkey.from_string("HkcE9sqQAnjJtECiFsqGMNmUho3ptXkapUPAqgZQbBSY")]
>>> (await solana_client.get_multiple_accounts(pubkeys)).value[0].lamports # doctest: +SKIP
1
""" # noqa: E501 # pylint: disable=line-too-long
body = self._get_multiple_accounts_body(
pubkeys=pubkeys,
commitment=commitment,
encoding=encoding,
data_slice=data_slice,
)
return await self._provider.make_request(body, GetMultipleAccountsResp)
async def get_multiple_accounts_json_parsed(
self,
pubkeys: List[Pubkey],
commitment: Optional[Commitment] = None,
) -> GetMultipleAccountsMaybeJsonParsedResp:
"""Returns all the account info for a list of public keys.
Args:
pubkeys: list of Pubkeys to query
commitment: Bank state to query. It can be either "finalized", "confirmed" or "processed".
Example:
>>> from solders.pubkey import Pubkey
>>> solana_client = AsyncClient("http://localhost:8899")
>>> pubkeys = [Pubkey.from_string("6ZWcsUiWJ63awprYmbZgBQSreqYZ4s6opowP4b7boUdh"), Pubkey.from_string("HkcE9sqQAnjJtECiFsqGMNmUho3ptXkapUPAqgZQbBSY")]
>>> asyncio.run(solana_client.get_multiple_accounts(pubkeys)).value[0].lamports # doctest: +SKIP
1
""" # noqa: E501 # pylint: disable=line-too-long
body = self._get_multiple_accounts_body(
pubkeys=pubkeys,
commitment=commitment,
encoding="jsonParsed",
data_slice=None,
)
return await self._provider.make_request(body, GetMultipleAccountsMaybeJsonParsedResp)
async def get_program_accounts( # pylint: disable=too-many-arguments
self,
pubkey: Pubkey,
commitment: Optional[Commitment] = None,
encoding: Optional[str] = None,
data_slice: Optional[types.DataSliceOpts] = None,
filters: Optional[Sequence[Union[int, types.MemcmpOpts]]] = None,
) -> GetProgramAccountsResp:
"""Returns all accounts owned by the provided program Pubkey.
Args:
pubkey: Pubkey of program
commitment: Bank state to query. It can be either "finalized", "confirmed" or "processed".
encoding: (optional) Encoding for the returned Transaction, either jsonParsed",
"base58" (slow), or "base64".
data_slice: (optional) Limit the returned account data using the provided `offset`: <usize> and
`length`: <usize> fields; only available for "base58" or "base64" encoding.
filters: (optional) Options to compare a provided series of bytes with program account data at a particular offset.
Note: an int entry is converted to a `dataSize` filter.
Example:
>>> from typing import List, Union
>>> solana_client = AsyncClient("http://localhost:8899")
>>> memcmp_opts = types.MemcmpOpts(offset=4, bytes="3Mc6vR")
>>> pubkey = Pubkey.from_string("4Nd1mBQtrMJVYVfKf2PJy9NZUZdTAsp7D4xWLs4gDB4T")
>>> filters: List[Union[int, types.MemcmpOpts]] = [17, memcmp_opts]
>>> (await solana_client.get_program_accounts(pubkey, filters=filters)).value[0].account.lamports # doctest: +SKIP
1
""" # noqa: E501 # pylint: disable=line-too-long
body = self._get_program_accounts_body(
pubkey=pubkey,
commitment=commitment,
encoding=encoding,
data_slice=data_slice,
filters=filters,
)
return await self._provider.make_request(body, GetProgramAccountsResp)
async def get_program_accounts_json_parsed( # pylint: disable=too-many-arguments
self,
pubkey: Pubkey,
commitment: Optional[Commitment] = None,
filters: Optional[Sequence[Union[int, types.MemcmpOpts]]] = None,
) -> GetProgramAccountsMaybeJsonParsedResp:
"""Returns all accounts owned by the provided program Pubkey.
Args:
pubkey: Pubkey of program
commitment: Bank state to query. It can be either "finalized", "confirmed" or "processed".
filters: (optional) Options to compare a provided series of bytes with program account data at a particular offset.
Note: an int entry is converted to a `dataSize` filter.
Example:
>>> from typing import List, Union
>>> solana_client = AsyncClient("http://localhost:8899")
>>> memcmp_opts = types.MemcmpOpts(offset=4, bytes="3Mc6vR")
>>> pubkey = Pubkey.from_string("4Nd1mBQtrMJVYVfKf2PJy9NZUZdTAsp7D4xWLs4gDB4T")
>>> filters: List[Union[int, types.MemcmpOpts]] = [17, memcmp_opts]
>>> (await solana_client.get_program_accounts(pubkey, filters=filters)).value[0].account.lamports # doctest: +SKIP
1
""" # noqa: E501 # pylint: disable=line-too-long
body = self._get_program_accounts_body(
pubkey=pubkey,
commitment=commitment,
encoding="jsonParsed",
data_slice=None,
filters=filters,
)
return await self._provider.make_request(body, GetProgramAccountsMaybeJsonParsedResp)
async def get_latest_blockhash(self, commitment: Optional[Commitment] = None) -> GetLatestBlockhashResp:
"""Returns the latest block hash from the ledger.
Response also includes the last valid block height.
Args:
commitment: Bank state to query. It can be either "finalized", "confirmed" or "processed".
Example:
>>> solana_client = AsyncClient("http://localhost:8899")
>>> (await solana_client.get_latest_blockhash()).value # doctest: +SKIP
RpcBlockhash {
blockhash: Hash(
4TLzN2RAACFnd5TYpHcUi76pC3V1qkggRF29HWk2VLeT,
),
last_valid_block_height: 158286487,
}
"""
body = self._get_latest_blockhash_body(commitment)
return await self._provider.make_request(body, GetLatestBlockhashResp)
async def get_signature_statuses(
self, signatures: List[Signature], search_transaction_history: bool = False
) -> GetSignatureStatusesResp:
"""Returns the statuses of a list of signatures.
Unless the `search_transaction_history` configuration parameter is included, this method only
searches the recent status cache of signatures, which retains statuses for all active slots plus
`MAX_RECENT_BLOCKHASHES` rooted slots.
Args:
signatures: An array of transaction signatures to confirm.
search_transaction_history: If true, a Solana node will search its ledger cache for
any signatures not found in the recent status cache.
Example:
>>> solana_client = AsyncClient("http://localhost:8899")
>>> raw_sigs = [
... "5VERv8NMvzbJMEkV8xnrLkEaWRtSz9CosKDYjCJjBRnbJLgp8uirBgmQpjKhoR4tjF3ZpRzrFmBV6UjKdiSZkQUW",
... "5j7s6NiJS3JAkvgkoc18WVAsiSaci2pxB2A6ueCJP4tprA2TFg9wSyTLeYouxPBJEMzJinENTkpA52YStRW5Dia7"]
>>> sigs = [Signature.from_string(sig) for sig in raw_sigs]
>>> (await solana_client.get_signature_statuses(sigs)).value[0].confirmations # doctest: +SKIP
10
"""
body = self._get_signature_statuses_body(signatures, search_transaction_history)
return await self._provider.make_request(body, GetSignatureStatusesResp)
async def get_slot(self, commitment: Optional[Commitment] = None) -> GetSlotResp:
"""Returns the current slot the node is processing.
Args:
commitment: Bank state to query. It can be either "finalized", "confirmed" or "processed".
Example:
>>> solana_client = AsyncClient("http://localhost:8899")
>>> (await solana_client.get_slot()).value # doctest: +SKIP
7515
"""
body = self._get_slot_body(commitment)
return await self._provider.make_request(body, GetSlotResp)
async def get_slot_leader(self, commitment: Optional[Commitment] = None) -> GetSlotLeaderResp:
"""Returns the current slot leader.
Args:
commitment: Bank state to query. It can be either "finalized", "confirmed" or "processed".
Example:
>>> solana_client = AsyncClient("http://localhost:8899")
>>> (await solana_client.get_slot_leader()).value # doctest: +SKIP
Pubkey(
dv2eQHeP4RFrJZ6UeiZWoc3XTtmtZCUKxxCApCDcRNV,
)
"""
body = self._get_slot_leader_body(commitment)
return await self._provider.make_request(body, GetSlotLeaderResp)
async def get_supply(self, commitment: Optional[Commitment] = None) -> GetSupplyResp:
"""Returns information about the current supply.
Args:
commitment: Bank state to query. It can be either "finalized", "confirmed" or "processed".
Example:
>>> solana_client = AsyncClient("http://localhost:8899")
>>> (await solana_client.get_supply()).value.circulating # doctest: +SKIP
683635192454157660
"""
body = self._get_supply_body(commitment)
return await self._provider.make_request(body, GetSupplyResp)
async def get_token_account_balance(
self, pubkey: Pubkey, commitment: Optional[Commitment] = None
) -> GetTokenAccountBalanceResp:
"""Returns the token balance of an SPL Token account (UNSTABLE).
Args:
pubkey: Pubkey of Token account to query
commitment: Bank state to query. It can be either "finalized", "confirmed" or "processed".
Example:
>>> solana_client = AsyncClient("http://localhost:8899")
>>> pubkey = Pubkey.from_string("7fUAJdStEuGbc3sM84cKRL6yYaaSstyLSU4ve5oovLS7")
>>> (await solana_client.get_token_account_balance(pubkey)).value.amount # noqa: E501 # doctest: +SKIP
'9864'
"""
body = self._get_token_account_balance_body(pubkey, commitment)
return await self._provider.make_request(body, GetTokenAccountBalanceResp)
async def get_token_accounts_by_delegate(
self,
delegate: Pubkey,
opts: types.TokenAccountOpts,
commitment: Optional[Commitment] = None,
) -> GetTokenAccountsByDelegateResp:
"""Returns all SPL Token accounts by approved Delegate (UNSTABLE).
Args:
delegate: Public key of the delegate owner to query.
opts: Token account option specifying at least one of `mint` or `program_id`.
commitment: Bank state to query. It can be either "finalized", "confirmed" or "processed".
"""
body = self._get_token_accounts_by_delegate_body(delegate, opts, commitment)
return await self._provider.make_request(body, GetTokenAccountsByDelegateResp)
async def get_token_accounts_by_delegate_json_parsed(
self,
delegate: Pubkey,
opts: types.TokenAccountOpts,
commitment: Optional[Commitment] = None,
) -> GetTokenAccountsByDelegateJsonParsedResp:
"""Returns all SPL Token accounts by approved delegate in JSON format (UNSTABLE).
Args:
delegate: Public key of the delegate owner to query.
opts: Token account option specifying at least one of `mint` or `program_id`.
commitment: Bank state to query. It can be either "finalized", "confirmed" or "processed".
"""
body = self._get_token_accounts_by_delegate_json_parsed_body(delegate, opts, commitment)
return await self._provider.make_request(body, GetTokenAccountsByDelegateJsonParsedResp)
async def get_token_accounts_by_owner_json_parsed(
self,
owner: Pubkey,
opts: types.TokenAccountOpts,
commitment: Optional[Commitment] = None,
) -> GetTokenAccountsByOwnerJsonParsedResp:
"""Returns all SPL Token accounts by token owner in JSON format (UNSTABLE).
Args:
owner: Public key of the account owner to query.
opts: Token account option specifying at least one of `mint` or `program_id`.
commitment: Bank state to query. It can be either "finalized", "confirmed" or "processed".
"""
body = self._get_token_accounts_by_owner_json_parsed_body(owner, opts, commitment)
return await self._provider.make_request(body, GetTokenAccountsByOwnerJsonParsedResp)
async def get_token_accounts_by_owner(
self,
owner: Pubkey,
opts: types.TokenAccountOpts,
commitment: Optional[Commitment] = None,
) -> GetTokenAccountsByOwnerResp:
"""Returns all SPL Token accounts by token owner (UNSTABLE).
Args:
owner: Public key of the account owner to query.
opts: Token account option specifying at least one of `mint` or `program_id`.
commitment: Bank state to query. It can be either "finalized", "confirmed" or "processed".
"""
body = self._get_token_accounts_by_owner_body(owner, opts, commitment)
return await self._provider.make_request(body, GetTokenAccountsByOwnerResp)
async def get_token_largest_accounts(
self, pubkey: Pubkey, commitment: Optional[Commitment] = None
) -> GetTokenLargestAccountsResp:
"""Returns the 20 largest accounts of a particular SPL Token type."""
body = self._get_token_largest_accounts_body(pubkey, commitment)
return await self._provider.make_request(body, GetTokenLargestAccountsResp)
async def get_token_supply(self, pubkey: Pubkey, commitment: Optional[Commitment] = None) -> GetTokenSupplyResp:
"""Returns the total supply of an SPL Token type."""
body = self._get_token_supply_body(pubkey, commitment)
return await self._provider.make_request(body, GetTokenSupplyResp)
async def get_transaction_count(self, commitment: Optional[Commitment] = None) -> GetTransactionCountResp:
"""Returns the current Transaction count from the ledger.
Args:
commitment: Bank state to query. It can be either "finalized", "confirmed" or "processed".
Example:
>>> solana_client = AsyncClient("http://localhost:8899")
>>> (await solana_client.get_transaction_count()).value # doctest: +SKIP
4554
"""
body = self._get_transaction_count_body(commitment)
return await self._provider.make_request(body, GetTransactionCountResp)
async def get_minimum_ledger_slot(self) -> MinimumLedgerSlotResp:
"""Returns the lowest slot that the node has information about in its ledger.
This value may increase over time if the node is configured to purge older ledger data.
Example:
>>> solana_client = AsyncClient("http://localhost:8899")
>>> (await solana_client.get_minimum_ledger_slot()).value # doctest: +SKIP
1234
"""
return await self._provider.make_request(self._minimum_ledger_slot, MinimumLedgerSlotResp)
async def get_version(self) -> GetVersionResp:
"""Returns the current solana versions running on the node.
Example:
>>> solana_client = AsyncClient("http://localhost:8899")
>>> (await solana_client.get_version()).value.solana_core # doctest: +SKIP
'1.13.2'
"""
return await self._provider.make_request(self._get_version, GetVersionResp)
async def get_vote_accounts(self, commitment: Optional[Commitment] = None) -> GetVoteAccountsResp:
"""Returns the account info and associated stake for all the voting accounts in the current bank.
Args:
commitment: Bank state to query. It can be either "finalized", "confirmed" or "processed".
Example:
>>> solana_client = AsyncClient("http://localhost:8899")
>>> (await solana_client.get_vote_accounts()).value.current[0].commission # doctest: +SKIP
100
"""
body = self._get_vote_accounts_body(commitment)
return await self._provider.make_request(body, GetVoteAccountsResp)
async def request_airdrop(
self, pubkey: Pubkey, lamports: int, commitment: Optional[Commitment] = None
) -> RequestAirdropResp:
"""Requests an airdrop of lamports to a Pubkey.
Args:
pubkey: Pubkey of account to receive lamports, as base-58 encoded string or public key object.
lamports: Amount of lamports.
commitment: Bank state to query. It can be either "finalized", "confirmed" or "processed".
Example:
>>> from solders.pubkey import Pubkey
>>> solana_client = AsyncClient("http://localhost:8899")
>>> (await solana_client.request_airdrop(Pubkey([0] * 31 + [1]), 10000)).value # doctest: +SKIP
Signature(
1111111111111111111111111111111111111111111111111111111111111111,
)
"""
body = self._request_airdrop_body(pubkey, lamports, commitment)
return await self._provider.make_request(body, RequestAirdropResp)
async def send_raw_transaction(self, txn: bytes, opts: Optional[types.TxOpts] = None) -> SendTransactionResp:
"""Send a transaction that has already been signed and serialized into the wire format.
Args:
txn: Transaction bytes.
opts: (optional) Transaction options.
Before submitting, the following preflight checks are performed (unless disabled with the `skip_preflight` option):
- The transaction signatures are verified.
- The transaction is simulated against the latest max confirmed bank and on failure an error
will be returned. Preflight checks may be disabled if desired.
Example:
>>> solana_client = AsyncClient("http://localhost:8899")
>>> full_signed_tx_hex = (
... '01b3795ccfaac3eee838bb05c3b8284122c18acedcd645c914fe8e178c3b62640d8616d061cc818b26cab8ecf3855ecc'
... '72fa113f731ecbd0215e88edc0309d6f0a010001031398f62c6d1a457c51ba6a4b5f3dbd2f69fca93216218dc8997e41'
... '6bd17d93ca68ab4677ffb1f2894dd0a6153c231d45ec436ae53ae60149dbe15f32e4b8703f0000000000000000000000'
... '000000000000000000000000000000000000000000839618f701ba7e9ba27ae59825dd6d6bb66d14f6d5d0eae215161d7'
... '1851a106901020200010c0200000040420f0000000000'
... )
>>> (await solana_client.send_raw_transaction(bytes.fromhex(full_signed_tx_hex))).value # doctest: +SKIP
Signature(
1111111111111111111111111111111111111111111111111111111111111111,
)
""" # noqa: E501 # pylint: disable=line-too-long
opts_to_use = types.TxOpts(preflight_commitment=self._commitment) if opts is None else opts
body = self._send_raw_transaction_body(txn, opts_to_use)
resp = await self._provider.make_request(body, SendTransactionResp)
if opts_to_use.skip_confirmation:
return self._post_send(resp)
post_send_args = self._send_raw_transaction_post_send_args(resp, opts_to_use)
return await self.__post_send_with_confirm(*post_send_args)
async def send_transaction(
self,
txn: Union[VersionedTransaction, Transaction],
opts: Optional[types.TxOpts] = None,
) -> SendTransactionResp:
"""Send a transaction.
Args: