-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathdeso_sdk.py
1291 lines (1118 loc) · 52.8 KB
/
deso_sdk.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
import hashlib
import json
import requests
from typing import Optional, Dict, Any, List, Union
from pprint import pprint
import sys
from typing import Tuple, Optional
import binascii
from bip32 import BIP32, base58
from mnemonic import Mnemonic
from coincurve import PrivateKey
import hashlib
from typing import Optional
from ecdsa import SigningKey, SECP256k1
from ecdsa.util import sigencode_der
import time
from requests.exceptions import RequestException
class DeSoDexClient:
"""
A Python client for interacting with the DeSo DEX endpoints on a DeSo node.
"""
def __init__(self, is_testnet: bool=False, seed_phrase_or_hex=None, passphrase=None, index=0, node_url=None):
self.is_testnet = is_testnet
desoKeyPair, err = create_key_pair_from_seed_or_seed_hex(
seed_phrase_or_hex, passphrase, index, is_testnet,
)
if desoKeyPair is None:
raise ValueError(err)
self.deso_keypair = desoKeyPair
if node_url is None:
if is_testnet:
node_url = "https://test.deso.org"
else:
node_url = "https://node.deso.org"
self.node_url = node_url.rstrip("/")
def sign_single_txn(self, unsigned_txn_hex: str) -> str:
try:
# Decode hex transaction to bytes
txn_bytes = bytes.fromhex(unsigned_txn_hex)
# Double SHA256 hash of the transaction bytes
first_hash = hashlib.sha256(txn_bytes).digest()
txn_hash = hashlib.sha256(first_hash).digest()
# Create signing key from private key bytes
signing_key = SigningKey.from_string(self.deso_keypair.private_key, curve=SECP256k1)
# Sign the hash
signature = signing_key.sign_digest(txn_hash, sigencode=sigencode_der)
# Convert signature to hex
signature_hex = signature.hex()
return signature_hex
except Exception as e:
return None
def submit_txn(self, unsigned_txn_hex: str, signature_hex: str) -> dict:
"""
Submit a transaction with signature to the specified node URL.
Args:
node_url: Base URL of the node
unsigned_txn_hex: Hex string of unsigned transaction
signature_hex: Hex string of transaction signature
Returns:
dict: Parsed response from the server
Raises:
requests.exceptions.RequestException: If request fails
json.JSONDecodeError: If response parsing fails
ValueError: If server returns non-200 status code
"""
submit_url = f"{self.node_url}/api/v0/submit-transaction"
payload = {
"UnsignedTransactionHex": unsigned_txn_hex,
"TransactionSignatureHex": signature_hex
}
headers = {
"Origin": self.node_url,
"Content-Type": "application/json"
}
response = requests.post(
submit_url,
data=json.dumps(payload),
headers=headers
)
if response.status_code != 200:
raise ValueError(
f"Error status returned from {submit_url}: "
f"{response.status_code}, {response.text}"
)
return response.json()
from typing import Dict, List, Any
def submit_atomic_txn(
self,
incomplete_atomic_txn_hex: str,
unsigned_inner_txn_hexes: List[str],
txn_signatures_hex: List[str]
) -> Dict[str, Any]:
"""
Submit an atomic transaction using the designated endpoint.
Args:
node_url: Base URL of the node
transaction_hex: Hex string of the incomplete atomic transaction
unsigned_inner_txn_hexes: List of unsigned inner transaction hex strings
txn_signatures_hex: List of transaction signatures in hex
Returns:
dict: Parsed JSON response
Raises:
requests.exceptions.RequestException: If request fails
json.JSONDecodeError: If response parsing fails
ValueError: If server returns non-200 status code
"""
endpoint = "/api/v0/submit-atomic-transaction"
url = f"{self.node_url}{endpoint}"
payload = {
"IncompleteAtomicTransactionHex": incomplete_atomic_txn_hex,
"UnsignedInnerTransactionsHex": unsigned_inner_txn_hexes,
"TransactionSignaturesHex": txn_signatures_hex
}
response = requests.post(url, json=payload)
try:
response.raise_for_status()
except requests.exceptions.HTTPError as e:
try:
error_json = response.json()
except ValueError:
error_json = response.text
raise requests.exceptions.HTTPError(
f"Error status returned from {url}: {response.status_code}, {error_json}"
)
return response.json()
def sign_and_submit_txn(self, resp):
unsigned_txn_hex = resp.get('TransactionHex')
if unsigned_txn_hex is None:
raise ValueError("TransactionHex not found in response")
if 'InnerTransactionHexes' in resp:
unsigned_inner_txn_hexes = resp.get('InnerTransactionHexes')
signature_hexes = []
for unsigned_inner_txn_hex in unsigned_inner_txn_hexes:
signature_hex = self.sign_single_txn(unsigned_inner_txn_hex)
signature_hexes.append(signature_hex)
return self.submit_atomic_txn(
unsigned_txn_hex, unsigned_inner_txn_hexes, signature_hexes
)
signature_hex = self.sign_single_txn(unsigned_txn_hex)
return self.submit_txn(unsigned_txn_hex, signature_hex)
def create_unsigned_atomic_txn(self, unsigned_transaction_hexes: List[Dict[str, Any]]) -> Dict[str, Any]:
"""
Creates an unsigned atomic transaction from a list of transactions.
Args:
unsigned_transaction_hexes (List[Dict[str, Any]]): A list of transactions represented as dictionaries.
Returns:
Dict[str, Any]: The parsed response containing the atomic transaction details.
Raises:
Exception: If the request fails or the response cannot be parsed.
"""
route_path = "/api/v0/create-atomic-txns-wrapper"
url = f"{self.node_url}{route_path}"
payload = {
"UnsignedTransactionHexes": unsigned_transaction_hexes
}
headers = {
"Content-Type": "application/json"
}
response = requests.post(url, json=payload, headers=headers)
try:
response.raise_for_status()
except requests.exceptions.HTTPError as e:
try:
error_json = response.json()
except ValueError:
error_json = response.text
raise requests.exceptions.HTTPError(
f"CreateUnsignedAtomicTxn: Error status returned from {url}: {response.status_code}, {error_json}"
)
try:
response_data = response.json()
except json.JSONDecodeError as e:
raise Exception(f"CreateUnsignedAtomicTxn: Error parsing JSON response: {str(e)}")
if "InnerTransactionHexes" not in response_data:
raise Exception("CreateUnsignedAtomicTxn: Missing 'InnerTransactionHexes' in response")
return response_data
def get_transaction(self, txn_hash_hex: str, committed_txns_only: bool) -> Dict[str, Any]:
"""
Fetch a transaction by its hash with an optional filter for committed transactions.
Args:
txn_hash_hex (str): The hex string of the transaction hash.
committed_txns_only (bool): If True, fetch only committed transactions;
otherwise, fetch transactions in mempool.
Returns:
Dict[str, Any]: The JSON response containing transaction details.
Raises:
requests.exceptions.RequestException: If the request fails.
json.JSONDecodeError: If the response parsing fails.
ValueError: If the server returns a non-200 status code.
"""
url = f"{self.node_url}/api/v0/get-txn"
# Determine the transaction status based on the argument
txn_status = "Committed" if committed_txns_only else "InMempool"
payload = {
"TxnHashHex": txn_hash_hex,
"TxnStatus": txn_status,
}
headers = {
"Origin": self.node_url,
"Content-Type": "application/json",
}
response = requests.post(url, json=payload, headers=headers)
try:
response.raise_for_status()
except requests.exceptions.HTTPError as e:
error_json = response.json() # Get the error response JSON
raise requests.exceptions.HTTPError(f"HTTP Error: {e}, Response: {error_json}")
return response.json()
def wait_for_commitment_with_timeout(self, txn_hash_hex: str, timeout_seconds: float) -> None:
"""
Waits for a transaction to commit within a specified timeout period. DeSo txns commit
within two blocks, with 1s block times, so within 3s. Note you don't necessarily need
to wait for commitment. You can "fire and forget" your txns if best-effort is OK, or
use get_transaction to check that it entered the mempool, which is sufficient for most
use-cases (and mempool txns almost always commit within a few seconds).
Args:
txn_hash_hex (str): The transaction hash in hex format.
timeout_seconds (float): The maximum time to wait for confirmation, in seconds.
Raises:
TimeoutError: If the transaction does not confirm within the timeout period.
Exception: If there is an error fetching the transaction from the node.
"""
start_time = time.time()
while True:
try:
txn_response = self.get_transaction(txn_hash_hex, committed_txns_only=True)
if txn_response.get("TxnFound", False):
return # Transaction is confirmed
except RequestException as e:
raise Exception(f"Error getting txn from node: {str(e)}")
if time.time() - start_time > timeout_seconds:
raise TimeoutError(f"Timeout waiting for txn to confirm: {txn_hash_hex}")
time.sleep(0.1) # Sleep for 100 milliseconds before retrying
def coins_to_base_units(self, coin_amount: float, is_deso: bool, hex_encode: bool = False) -> str:
if is_deso:
base_units = int(coin_amount * 1e9)
else:
base_units = int(coin_amount * 1e18)
if hex_encode:
return hex(base_units)
return str(base_units)
def base_units_to_coins(self, coin_base_units: str | int, is_deso: bool) -> float:
# Decode hex if needed
if str(coin_base_units).startswith("0x"):
coin_base_units = int(coin_base_units, 16)
if is_deso:
return float(coin_base_units) / 1e9
return float(coin_base_units) / 1e18
def mint_or_burn_tokens(
self,
updater_pubkey_base58check: str,
profile_pubkey_base58check: str,
operation_type: str, # 'mint' or 'burn'
coins_to_mint_or_burn_nanos: str,
min_fee_rate_nanos_per_kb: int = 1000,
extra_headers: Optional[Dict[str, str]] = None,
) -> Dict[str, Any]:
url = f"{self.node_url}/api/v0/dao-coin"
payload = {
"UpdaterPublicKeyBase58Check": updater_pubkey_base58check,
"ProfilePublicKeyBase58CheckOrUsername": profile_pubkey_base58check,
"OperationType": operation_type,
}
if operation_type.lower() == "mint":
payload["CoinsToMintNanos"] = coins_to_mint_or_burn_nanos
elif operation_type.lower() == "burn":
payload["CoinsToBurnNanos"] = coins_to_mint_or_burn_nanos
else:
raise ValueError('operation_type must be "mint" or "burn".')
payload["MinFeeRateNanosPerKB"] = min_fee_rate_nanos_per_kb
headers = {
"Content-Type": "application/json",
}
if extra_headers:
headers.update(extra_headers)
resp = requests.post(url, json=payload, headers=headers)
try:
resp.raise_for_status()
except requests.exceptions.HTTPError as e:
error_json = resp.json() # Get the error response JSON
raise requests.exceptions.HTTPError(f"HTTP Error: {e}, Response: {error_json}")
return resp.json()
def send_deso(
self,
sender_pubkey_base58check: str,
recipient_pubkey_or_username: str,
amount_nanos: int,
min_fee_rate_nanos_per_kb: int = 1000,
extra_headers: Optional[Dict[str, str]] = None
) -> Dict[str, Any]:
"""
Sends DESO from one account to another.
Args:
sender_pubkey_base58check: Public key of the sender in Base58Check format.
recipient_pubkey_or_username: Public key or username of the recipient.
amount_nanos: Amount to send in nanos.
min_fee_rate_nanos_per_kb: Minimum fee rate in nanos per KB.
extra_headers: Optional headers to include in the request.
Returns:
dict: Parsed response from the API.
"""
url = f"{self.node_url}/api/v0/send-deso"
payload = {
"SenderPublicKeyBase58Check": sender_pubkey_base58check,
"RecipientPublicKeyOrUsername": recipient_pubkey_or_username,
"AmountNanos": amount_nanos,
"MinFeeRateNanosPerKB": min_fee_rate_nanos_per_kb
}
headers = {
"Content-Type": "application/json",
}
if extra_headers:
headers.update(extra_headers)
response = requests.post(url, json=payload, headers=headers)
try:
response.raise_for_status()
except requests.exceptions.HTTPError as e:
error_json = response.json() # Get the error response JSON
raise requests.exceptions.HTTPError(f"HTTP Error: {e}, Response: {error_json}")
return response.json()
def transfer_tokens(
self,
sender_pubkey_base58check: str,
profile_pubkey_base58check: str,
receiver_pubkey_base58check: str,
token_to_transfer_base_units: str,
min_fee_rate_nanos_per_kb: int = 1000,
extra_headers: Optional[Dict[str, str]] = None,
) -> Dict[str, Any]:
url = f"{self.node_url}/api/v0/transfer-dao-coin"
payload = {
"SenderPublicKeyBase58Check": sender_pubkey_base58check,
"ProfilePublicKeyBase58CheckOrUsername": profile_pubkey_base58check,
"ReceiverPublicKeyBase58CheckOrUsername": receiver_pubkey_base58check,
"DAOCoinToTransferNanos": token_to_transfer_base_units,
"MinFeeRateNanosPerKB": min_fee_rate_nanos_per_kb,
}
headers = {
"Content-Type": "application/json",
}
if extra_headers:
headers.update(extra_headers)
resp = requests.post(url, json=payload, headers=headers)
try:
resp.raise_for_status()
except requests.exceptions.HTTPError as e:
error_json = resp.json() # Get the error response JSON
raise requests.exceptions.HTTPError(f"HTTP Error: {e}, Response: {error_json}")
return resp.json()
def update_transfer_restriction_status(
self,
updater_pubkey_base58check: str,
profile_pubkey_base58check: str,
transfer_restriction_status: str, # e.g. "profile_owner_only"
min_fee_rate_nanos_per_kb: int = 1000,
extra_headers: Optional[Dict[str, str]] = None,
) -> Dict[str, Any]:
url = f"{self.node_url}/api/v0/dao-coin"
payload = {
"TransferRestrictionStatus": transfer_restriction_status,
"UpdaterPublicKeyBase58Check": updater_pubkey_base58check,
"ProfilePublicKeyBase58CheckOrUsername": profile_pubkey_base58check,
"OperationType": "update_transfer_restriction_status",
"MinFeeRateNanosPerKB": min_fee_rate_nanos_per_kb,
}
headers = {
"Content-Type": "application/json",
}
if extra_headers:
headers.update(extra_headers)
resp = requests.post(url, json=payload, headers=headers)
try:
resp.raise_for_status()
except requests.exceptions.HTTPError as e:
error_json = resp.json() # Get the error response JSON
raise requests.exceptions.HTTPError(f"HTTP Error: {e}, Response: {error_json}")
return resp.json()
def create_limit_order_with_fee(
self,
transactor_public_key: str,
quote_currency_public_key: str,
base_currency_public_key: str,
operation_type: str, # "BID" or "ASK"
price: str,
price_currency_type: str,
quantity: str,
fill_type: str,
quantity_currency_type: str,
min_fee_rate_nanos_per_kb: int = 0,
extra_fees: Optional[List[Dict[str, Any]]] = None,
optional_preceding_txs: Optional[List[Dict[str, Any]]] = None,
extra_headers: Optional[Dict[str, str]] = None,
) -> Dict[str, Any]:
url = f"{self.node_url}/api/v0/create-dao-coin-limit-order-with-fee"
payload = {
"OperationType": operation_type,
"TransactorPublicKeyBase58Check": transactor_public_key,
"QuoteCurrencyPublicKeyBase58Check": quote_currency_public_key,
"BaseCurrencyPublicKeyBase58Check": base_currency_public_key,
"Price": price,
"PriceCurrencyType": price_currency_type,
"Quantity": quantity,
"FillType": fill_type,
"MinFeeRateNanosPerKB": min_fee_rate_nanos_per_kb,
"TransactionFees": extra_fees,
"OptionalPrecedingTransactions": optional_preceding_txs,
"QuantityCurrencyType": quantity_currency_type,
}
headers = {
"Content-Type": "application/json",
}
if extra_headers:
headers.update(extra_headers)
resp = requests.post(url, json=payload, headers=headers)
try:
resp.raise_for_status()
except requests.exceptions.HTTPError as e:
error_json = resp.json() # Get the error response JSON
raise requests.exceptions.HTTPError(f"HTTP Error: {e}, Response: {error_json}")
return resp.json()
def cancel_limit_order(
self,
transactor_public_key: str,
cancel_order_id: str,
min_fee_rate_nanos_per_kb: int = 1000,
extra_fees: Optional[List[Dict[str, Any]]] = None,
extra_headers: Optional[Dict[str, str]] = None,
) -> Dict[str, Any]:
url = f"{self.node_url}/api/v0/cancel-dao-coin-limit-order"
payload = {
"TransactorPublicKeyBase58Check": transactor_public_key,
"CancelOrderID": cancel_order_id,
"MinFeeRateNanosPerKB": min_fee_rate_nanos_per_kb,
"TransactionFees": extra_fees,
}
headers = {
"Content-Type": "application/json",
}
if extra_headers:
headers.update(extra_headers)
resp = requests.post(url, json=payload, headers=headers)
try:
resp.raise_for_status()
except requests.exceptions.HTTPError as e:
error_json = resp.json() # Get the error response JSON
raise requests.exceptions.HTTPError(f"HTTP Error: {e}, Response: {error_json}")
return resp.json()
def get_token_balances(
self,
user_public_key: str,
creator_public_keys: List[str],
txn_status: str = "Committed",
extra_headers: Optional[Dict[str, str]] = None,
) -> Dict[str, Any]:
"""
Fetches token balances for a given user public key and a list of creator public keys.
Args:
user_public_key (str): The base58 public key of the user.
creator_public_keys (List[str]): List of creator public keys to query balances for.
txn_status (str): The transaction status filter. Default is 'Committed'.
extra_headers (Optional[Dict[str, str]]): Additional headers for the HTTP request.
Returns:
Dict[str, Any]: The token balances in a structured dictionary format.
Raises:
requests.exceptions.RequestException: If the request fails.
json.JSONDecodeError: If the response is not valid JSON.
ValueError: If the server returns a non-200 status code.
"""
url = f"{self.node_url}/api/v0/get-token-balances-for-public-key"
payload = {
"UserPublicKey": user_public_key,
"CreatorPublicKeys": creator_public_keys,
"TxnStatus": txn_status,
}
headers = {
"Content-Type": "application/json",
"Origin": self.node_url,
}
if extra_headers:
headers.update(extra_headers)
response = requests.post(url, json=payload, headers=headers)
try:
response.raise_for_status()
except requests.exceptions.HTTPError as e:
error_json = response.json() # Get the error response JSON
raise requests.exceptions.HTTPError(f"HTTP Error: {e}, Response: {error_json}")
return response.json()
def get_single_profile(
self,
public_key_base58check: Optional[str] = None,
username: Optional[str] = None,
extra_headers: Optional[Dict[str, str]] = None,
) -> Dict[str, Any] | None:
"""
Fetches a single profile from the DeSo node.
Args:
public_key_base58check (str, optional): The public key of the user to fetch.
username (str, optional): The username of the user to fetch.
no_error_on_missing (bool): If true, suppresses errors when the profile is missing.
extra_headers (dict, optional): Additional headers to include in the request.
Returns:
dict: The profile data from the node.
Raises:
requests.exceptions.RequestException: If the request fails.
json.JSONDecodeError: If response parsing fails.
ValueError: If the server returns a non-200 status code.
"""
url = f"{self.node_url}/api/v0/get-single-profile"
payload = {
"PublicKeyBase58Check": public_key_base58check or "",
"Username": username or "",
"NoErrorOnMissing": False,
}
headers = {
"Content-Type": "application/json",
}
if extra_headers:
headers.update(extra_headers)
try:
response = requests.post(url, json=payload, headers=headers)
response.raise_for_status()
except requests.exceptions.HTTPError as err:
# Handle 404 gracefully.
# TODO: This is a hack but fine for now...
if "404" in str(err):
return None
raise ValueError(f"get_single_profile: Error making request to node: {err}")
try:
response_data = response.json()
except json.JSONDecodeError as err:
raise ValueError(f"get_single_profile: Error unmarshalling response: {err}")
return response_data.get("Profile")
def get_limit_orders(
self,
coin1_creator_pubkey: str,
coin2_creator_pubkey: str,
extra_headers: Optional[Dict[str, str]] = None,
) -> Dict[str, Any]:
url = f"{self.node_url}/api/v0/get-dao-coin-limit-orders"
payload = {
"DAOCoin1CreatorPublicKeyBase58Check": coin1_creator_pubkey,
"DAOCoin2CreatorPublicKeyBase58Check": coin2_creator_pubkey,
}
headers = {
"Content-Type": "application/json",
}
if extra_headers:
headers.update(extra_headers)
resp = requests.post(url, json=payload, headers=headers)
try:
resp.raise_for_status()
except requests.exceptions.HTTPError as e:
error_json = resp.json() # Get the error response JSON
raise requests.exceptions.HTTPError(f"HTTP Error: {e}, Response: {error_json}")
return resp.json()
def get_transactor_limit_orders(
self,
transactor_pubkey_base58check: str,
extra_headers: Optional[Dict[str, str]] = None,
) -> Dict[str, Any]:
url = f"{self.node_url}/api/v0/get-transactor-dao-coin-limit-orders"
payload = {
"TransactorPublicKeyBase58Check": transactor_pubkey_base58check,
}
headers = {
"Content-Type": "application/json",
}
if extra_headers:
headers.update(extra_headers)
resp = requests.post(url, json=payload, headers=headers)
try:
resp.raise_for_status()
except requests.exceptions.HTTPError as e:
error_json = resp.json() # Get the error response JSON
raise requests.exceptions.HTTPError(f"HTTP Error: {e}, Response: {error_json}")
return resp.json()
def submit_post(
self,
updater_public_key_base58check: str,
body: str,
parent_post_hash_hex: Optional[str] = None,
reposted_post_hash_hex: Optional[str] = None,
title: Optional[str] = "",
image_urls: Optional[List[str]] = None,
video_urls: Optional[List[str]] = None,
post_extra_data: Optional[Dict[str, Any]] = None,
min_fee_rate_nanos_per_kb: int = 1000,
is_hidden: bool = False,
in_tutorial: bool = False
) -> Dict[str, Any]:
"""
Submit a post or repost to the DeSo blockchain.
Args:
updater_public_key_base58check: Public key of the updater.
body: The content of the post.
parent_post_hash_hex: The hash of the parent post for replies.
reposted_post_hash_hex: The hash of the post being reposted.
title: An optional title for the post.
image_urls: Optional list of image URLs.
video_urls: Optional list of video URLs.
post_extra_data: Optional additional data for the post.
min_fee_rate_nanos_per_kb: Minimum fee rate in nanos per KB.
is_hidden: Boolean to indicate if the post is hidden.
in_tutorial: Boolean to indicate if the post is part of a tutorial.
Returns:
Dict[str, Any]: Response from the DeSo node.
Raises:
ValueError: If the request fails.
"""
url = f"{self.node_url}/api/v0/submit-post"
payload = {
"UpdaterPublicKeyBase58Check": updater_public_key_base58check,
"PostHashHexToModify": "",
"ParentStakeID": parent_post_hash_hex or "",
"RepostedPostHashHex": reposted_post_hash_hex or "",
"Title": title or "",
"BodyObj": {
"Body": body,
"ImageURLs": image_urls or [],
"VideoURLs": video_urls or [],
},
"PostExtraData": post_extra_data or {"Node": "1"},
"Sub": "",
"IsHidden": is_hidden,
"MinFeeRateNanosPerKB": min_fee_rate_nanos_per_kb,
"InTutorial": in_tutorial,
}
headers = {
"Content-Type": "application/json",
}
response = requests.post(url, json=payload, headers=headers)
try:
response.raise_for_status()
except requests.exceptions.HTTPError as e:
error_json = response.json() if response.content else response.text
raise ValueError(f"HTTP Error: {e}, Response: {error_json}")
return response.json()
def create_follow_transaction(
self,
follower_public_key_base58check: str,
followed_public_key_base58check: str,
is_unfollow: bool = False,
min_fee_rate_nanos_per_kb: int = 1000,
) -> Dict[str, Any]:
"""
Create a follow or unfollow transaction.
Args:
follower_public_key_base58check: Public key of the follower.
followed_public_key_base58check: Public key of the followed user.
is_unfollow: Whether to unfollow instead of follow.
min_fee_rate_nanos_per_kb: Minimum fee rate in nanos per KB.
Returns:
Dict[str, Any]: Response from the DeSo node.
Raises:
ValueError: If the request fails.
"""
url = f"{self.node_url}/api/v0/create-follow-txn-stateless"
payload = {
"FollowerPublicKeyBase58Check": follower_public_key_base58check,
"FollowedPublicKeyBase58Check": followed_public_key_base58check,
"IsUnfollow": is_unfollow,
"MinFeeRateNanosPerKB": min_fee_rate_nanos_per_kb,
}
headers = {
"Content-Type": "application/json",
}
response = requests.post(url, json=payload, headers=headers)
try:
response.raise_for_status()
except requests.exceptions.HTTPError as e:
error_json = response.json() if response.content else response.text
raise ValueError(f"HTTP Error: {e}, Response: {error_json}")
return response.json()
class DeSoKeyPair:
def __init__(self, public_key: bytes, private_key: bytes):
self.public_key = public_key
self.private_key = private_key
def create_key_pair_from_seed_or_seed_hex(
seed: str,
passphrase: str,
index: int,
is_testnet: bool
) -> Tuple[Optional[DeSoKeyPair], Optional[str]]:
"""
Creates a key pair from either a seed phrase or seed hex.
Args:
seed (str): Either a BIP39 mnemonic seed phrase or a hex string
passphrase (str): Optional passphrase for BIP39 seed
index (int): Account index for derivation path
is_testnet (bool): Whether to use testnet or mainnet parameters
Returns:
Tuple[DeSoKeyPair, Optional[str]]: Returns the key pair and any error message
"""
if not seed:
return None, "Seed must be provided"
# First try to decode as hex to determine if it's a seed hex
try:
seed_bytes = binascii.unhexlify(seed.lower())
# If we get here, it's a valid hex string
if passphrase or index != 0:
return None, "Seed hex provided, but passphrase or index params were also provided"
# Convert the seed hex directly to keys
privkey = PrivateKey(seed_bytes)
pubkey = privkey.public_key
return DeSoKeyPair(pubkey.format(), privkey.secret), None
except binascii.Error:
# Not a valid hex string, treat as mnemonic
try:
# Validate and convert mnemonic to seed
mnemo = Mnemonic("english")
if not mnemo.check(seed):
return None, "Invalid mnemonic seed phrase"
seed_bytes = mnemo.to_seed(seed, passphrase)
# Initialize BIP32 with appropriate network
network = "test" if is_testnet else "main"
bip32 = BIP32.from_seed(seed_bytes, network=network)
# Derive the key path: m/44'/0'/index'/0/0
# Note: in BIP32, hardened keys are represented with index + 0x80000000
path = f"m/44'/0'/{index}'/0/0"
derived_key = bip32.get_privkey_from_path(path)
# Convert to coincurve keys for consistent interface
privkey = PrivateKey(derived_key)
pubkey = privkey.public_key
return DeSoKeyPair(pubkey.format(), privkey.secret), None
except Exception as e:
return None, f"Error converting seed to key pair: {str(e)}"
def base58_check_encode(input_bytes: bytes, is_testnet: bool) -> str:
"""
Encode input bytes using Base58Check encoding with a specific prefix.
Args:
input_bytes: The bytes to encode
prefix: 3-byte prefix to prepend
Returns:
Base58Check encoded string
"""
prefix = b"\x11\xc2\x00" if is_testnet else b"\xcd\x14\x00"
# Combine prefix and input bytes
combined = prefix + input_bytes
# Calculate double SHA256 checksum
first_hash = hashlib.sha256(combined).digest()
second_hash = hashlib.sha256(first_hash).digest()
checksum = second_hash[:4]
final_bytes = combined + checksum
# Encode using Base58
return base58.b58encode(final_bytes).decode()
def main():
"""
A simple main function that exercises each endpoint and prints the response.
NOTE: The parameters here are example placeholders.
If you don't have valid keys or a valid environment, these calls may fail.
"""
# This is very important: If you want to run on mainnet, you must switch this to false.
# This will switch several other params to the right values.
IS_TESTNET = True
# You can set any DeSo node you want. The nodes here are the canonical testnet and mainnet
# ones that a lot of people use for testing. If you don't pass a node_url to the DesoDexClient
# it will default to one of these depending on the value of is_testnet. We specify them here
# explicitly just to make you aware that you can set it manually if you want.
NODE_URL = "https://test.deso.org"
if not IS_TESTNET:
NODE_URL = "https://node.deso.org"
# Print the params
print(f"IS_TESTNET={IS_TESTNET}, NODE_URL={NODE_URL}")
# This pubkey is used for token-related things, such as buying or selling a token where
# DESO is the quote currency. You can see how it's used in the txn construction endpoints below.
# To denote DESO as the currency you want to transact, you must use one of these pubkeys. They
# correspond to the ZERO pubkey (a pubkey that is all zeros encoded using base58check).
DESO_TOKEN_PUBKEY = ('tBCKQud934akEwsr8AfG9BzHDWhi6CaDmjBsxGsSgfGsoxXHfVEfxP' if IS_TESTNET else
'BC1YLbnP7rndL92x7DbLp6bkUpCgKmgoHgz7xEbwhgHTps3ZrXA6LtQ')
# You can get your seed phrase OR your seed hex from the DeSo wallet. Just find
# your account and hit "Backup" to copy either you seed phrase or seed hex.
#
# Replace the below with your seed phrase. If you have "passphrase" or a different
# index you can specify it below as well.
SEED_PHRASE_OR_HEX = ""
PASSPHRASE = ""
INDEX = 0
explorer_link = "explorer-testnet.deso.com" if IS_TESTNET else "explorer.deso.com"
wallet_link = "wallet-testnet.deso.com" if IS_TESTNET else "wallet.deso.com"
openfund_link = "dev.openfund.com" if IS_TESTNET else "openfund.com"
focus_link = "beta.focus.xyz" if IS_TESTNET else "focus.xyz"
error_msg_SET_SEED = (f"ERROR: You must set SEED_PHRASE_OR_HEX to a seed that has DESO in it, or else nothing will "
f"work. Use {NODE_URL} or {openfund_link} to create an account and get starter DESO since IS_TESTNET={IS_TESTNET}. Change IS_TESTNET to switch "
f"between mainnet and testnet. See the top of main for other arguments. Read through main to see "
f"a bunch of useful transaction types. Other useful links: "
f"docs.deso.org {explorer_link}, {wallet_link}, {openfund_link}, {focus_link}. "
f"Message https://t.me/deso_pos_discussion for more help.")
if SEED_PHRASE_OR_HEX == "":
print(error_msg_SET_SEED)
sys.exit(1)
client = DeSoDexClient(
is_testnet=IS_TESTNET,
seed_phrase_or_hex=SEED_PHRASE_OR_HEX,
passphrase=PASSPHRASE,
index=INDEX,
node_url=NODE_URL)
string_pubkey = base58_check_encode(client.deso_keypair.public_key, IS_TESTNET)
print(f'Public key for seed: {string_pubkey}')
openfund_pubkey = ("tBCKWUK6mKhWpT4quLZjM2iPqPMwEWnHuj4Q99vSS4jFRLGeFJ3G3p" if IS_TESTNET else
"BC1YLj3zNA7hRAqBVkvsTeqw7oi4H6ogKiAFL1VXhZy6pYeZcZ6TDRY")
nader_pubkey = ("tBCKWkMW7SNyA4kuAHLtvFgdPRDgqS3gPfH5UWoeGZbxftkzUqpiKF" if IS_TESTNET else
"BC1YLhyuDGeWVgHmh3UQEoKstda525T1LnonYWURBdpgWbFBfRuntP5")
try:
print(f"\n---- Get balances ----")
print(f'Getting $openfund and $DESO balances for pubkey: {string_pubkey}')
balances = client.get_token_balances(
user_public_key=string_pubkey,
creator_public_keys=[openfund_pubkey, "DESO", string_pubkey],
)
# pprint(balances)
except Exception as e:
print(f"ERROR: Get token balances call failed: {e}")
deso_balance_nanos = int(balances['Balances']['DESO']['BalanceBaseUnits'])
if deso_balance_nanos == 0:
print(error_msg_SET_SEED)
sys.exit(1)
openfund_balance_base_units = int(balances['Balances'][openfund_pubkey]['BalanceBaseUnits'])
print(f'DESO balance: {deso_balance_nanos} nanos (1e9 = 1 coin) = {client.base_units_to_coins(deso_balance_nanos, is_deso=True)} coins')
print(f'OPENFUND balance: {openfund_balance_base_units} base units (1e18 = 1 token) = {client.base_units_to_coins(openfund_balance_base_units, is_deso=False)} tokens')
print('SUCCESS!')
try:
print(f"\n---- Get profile ----")
print(f'Checking profile for pubkey={string_pubkey}...')
single_profile = client.get_single_profile(
public_key_base58check=string_pubkey,
username=None, # Use this if you want to fetch by username!
)
if single_profile is None:
print(f"ERROR: Create a profile for your account so that you can mint tokens and other fun things. "
f"Use {client.node_url}/update-profile since IS_TESTNET={IS_TESTNET}. Change IS_TESTNET to switch "
f"between mainnet and testnet. See the top of main for other arguments. Other useful links: "
f"docs.deso.org {explorer_link}, {wallet_link}, {openfund_link}, {focus_link}. "
f"Message https://t.me/deso_pos_discussion for more help.")
sys.exit(1)
# pprint(single_profile)
print('SUCCESS!')
except Exception as e:
print(f"ERROR: Get profile failed: {e}")
print("\n---- Submit Post ----")
try:
print('Constructing submit-post txn...')
post_response = client.submit_post(
updater_public_key_base58check=string_pubkey,
body="IT WORKED!",
parent_post_hash_hex="", # Example parent post hash
title="",