-
Notifications
You must be signed in to change notification settings - Fork 6
/
tibet.py
1059 lines (853 loc) · 42.1 KB
/
tibet.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 asyncio
import json
import os
import sys
import click
from chia.wallet.util.wallet_types import WalletType
from chia.wallet.util.tx_config import CoinSelectionConfig, TXConfig
from private_key_things import *
from tibet_lib import *
tx_config = TXConfig(
1,
1337 * 10 ** 15,
[],
[],
True
)
@click.group()
def cli():
pass
cached_config = None
def get_config_item(*args):
global cached_config
if cached_config is None:
get_config()
ret = cached_config
for arg in args:
if ret is None:
return ret
ret = ret.get(arg, None)
return ret
def get_config():
global cached_config
if cached_config is None:
try:
cached_config = json.loads(open("config.json", "r").read())
except:
open("config.json", "w").write("{}")
cached_config = {}
return cached_config
def save_config(config):
cached_config = config
open("config.json", "w").write(
json.dumps(config, sort_keys=True, indent=4))
@click.command()
@click.option('--chia-root', default=None, help='Chia root directory (e.g., ~/.chia/mainnet)')
@click.option('--use-preset', default='custom', type=click.Choice(['custom', 'simulator', 'testnet10', 'mainnet'], case_sensitive=False))
@click.option('--fireacademyio-api-key', default=None, help='FireAcademy API key (if you want to use FireAcademy.io instead of your local full node.')
@click.option('--fireacademyio-network', default='testnet10', type=click.Choice(['mainnet', 'testnet10'], case_sensitive=False))
def config_node(chia_root, use_preset, fireacademyio_api_key, fireacademyio_network):
if use_preset == 'custom' and (chia_root is None or full_node_rpc_port is None or wallet_rpc_port is None):
click.echo("Use a preset or fill out all options.")
sys.exit(1)
if use_preset in ["mainnet", "testnet10"]:
chia_root = os.getenv('CHIA_ROOT', default="~/.chia/mainnet")
elif use_preset == "simulator":
chia_root = "~/.chia/simulator/main"
chia_root = os.path.expanduser(chia_root)
root_path = Path(chia_root)
config = load_config(root_path, "config.yaml")
selected_network = config["selected_network"]
agg_sig_me_additional_data = DEFAULT_CONSTANTS.AGG_SIG_ME_ADDITIONAL_DATA.hex()
try:
agg_sig_me_additional_data = config['full_node']['network_overrides'][
'constants'][selected_network]['AGG_SIG_ME_ADDITIONAL_DATA']
except:
pass
config = get_config()
config["chia_root"] = chia_root
if fireacademyio_api_key is not None:
if len(fireacademyio_api_key) != 36:
print(
"Invalid API key for FireAcademy.io :(")
sys.exit(1)
leaflet_url = f"https://kraken.fireacademy.io/{fireacademyio_api_key}/"
if fireacademyio_network == "mainnet" or use_preset == "mainnet":
leaflet_url += "leaflet/"
else:
leaflet_url += "leaflet-testnet10/"
config["leaflet_url"] = leaflet_url
else:
if config.get("leaflet_url", -1) != -1:
del config["leaflet_url"]
config["agg_sig_me_additional_data"] = agg_sig_me_additional_data
save_config(config)
click.echo("Config updated and saved successfully.")
@click.command()
def test_node_config():
asyncio.run(_test_node_config())
async def _test_node_config():
full_node_client = await get_full_node_client(get_config_item("chia_root"), get_config_item("leaflet_url"))
full_node_client_status = await full_node_client.healthz()
click.echo("full node client... " + str(full_node_client_status))
full_node_client.close()
await full_node_client.await_closed()
wallet_client = await get_wallet_client(get_config_item("chia_root"))
wallet_client_status = await wallet_client.healthz()
click.echo("wallet client... " + str(wallet_client_status))
wallet_client.close()
await wallet_client.await_closed()
@click.command()
@click.option("--push-tx", is_flag=True, show_default=True, default=False, help="Push the signed spend bundle to the network and update launcher is in config.")
@click.option('--fee', default=0, help='Fee to use for transaction')
def launch_router(push_tx, fee):
asyncio.run(_launch_router(push_tx, fee))
async def _launch_router(push_tx, fee):
wallet_client = await get_wallet_client(get_config_item("chia_root"))
# wallet id 1, amount 2 (+ fee)
coins = await wallet_client.select_coins(2 + fee, 1, min_coin_amount=2 + fee, coin_selection_config=CoinSelectionConfig(
min_coin_amount=fee + 3,
max_coin_amount=1337 * 10 ** 12,
excluded_coin_amounts=[],
excluded_coin_ids=[]
))
coin = coins[0]
coin_puzzle = await get_standard_coin_puzzle(wallet_client, coin)
click.echo(f"Using coin 0x{coin.name().hex()}...")
launcher_id, sb = await launch_router_from_coin(coin, coin_puzzle, fee=fee)
click.echo(f"Router launcher id: {launcher_id}")
signed_sb = await sign_spend_bundle(wallet_client, sb, additional_data=bytes.fromhex(get_config_item("agg_sig_me_additional_data")))
if push_tx:
click.echo(f"Pushing tx...")
full_node_client = await get_full_node_client(get_config_item("chia_root"), get_config_item("leaflet_url"))
resp = await full_node_client.push_tx(signed_sb)
click.echo(resp)
full_node_client.close()
await full_node_client.await_closed()
click.echo("Saving config...")
config = get_config()
config["router_launcher_id"] = launcher_id
config["router_last_processed_id"] = launcher_id
config["pairs"] = {}
save_config(config)
click.echo("Done.")
else:
open("spend_bundle.json", "w").write(json.dumps(
signed_sb.to_json_dict(), sort_keys=True, indent=4))
click.echo("Spend bundle written to spend_bundle.json.")
click.echo("Use --push-tx to broadcast this spend.")
wallet_client.close()
await wallet_client.await_closed()
@click.command()
@click.option('--launcher-id', required=True, help='Launcher coin id of the router.')
def set_router(launcher_id):
asyncio.run(_set_router(launcher_id))
async def _set_router(router_launcher_id):
click.echo("Saving config...")
config = get_config()
config["router_launcher_id"] = router_launcher_id
config["router_last_processed_id"] = router_launcher_id
config["pairs"] = {}
save_config(config)
click.echo("Done.")
@click.command()
@click.option('--amount', default=1000000, help='Amount, in CATs (1 CAT = 1000 mojos)')
@click.option("--push-tx", is_flag=True, show_default=True, default=False, help="Push the signed spend bundle to the network and add cat to wallet.")
def launch_test_token(amount, push_tx):
asyncio.run(_launch_test_token(amount, push_tx))
async def _launch_test_token(amount, push_tx):
click.echo(
f"Creating test CAT with a supply of {amount} ({amount * 1000} mojos used)...")
wallet_client = await get_wallet_client(get_config_item("chia_root"))
# wallet id 1 = XCH
coins = await wallet_client.select_coins(amount * 1000, 1, min_coin_amount=amount * 1000, coin_selection_config=CoinSelectionConfig(
min_coin_amount=amount * 1000,
max_coin_amount=1337 * 10 ** 12,
excluded_coin_amounts=[],
excluded_coin_ids=[]
))
coin = coins[0]
coin_puzzle = await get_standard_coin_puzzle(wallet_client, coin)
click.echo(f"Using coin 0x{coin.name().hex()}...")
tail_id, sb = await create_test_cat(amount, coin, coin_puzzle)
click.echo(f"Token asset id: {tail_id}")
signed_sb = await sign_spend_bundle(wallet_client, sb, additional_data=bytes.fromhex(get_config_item("agg_sig_me_additional_data")))
if push_tx:
click.echo(f"Pushing tx...")
full_node_client = await get_full_node_client(get_config_item("chia_root"), get_config_item("leaflet_url"))
resp = await full_node_client.push_tx(signed_sb)
click.echo(resp)
full_node_client.close()
await full_node_client.await_closed()
click.echo("Adding asset id to wallet...")
resp = await wallet_client.create_wallet_for_existing_cat(bytes.fromhex(tail_id))
click.echo(resp)
click.echo("Done.")
else:
open("spend_bundle.json", "w").write(json.dumps(
signed_sb.to_json_dict(), sort_keys=True, indent=4))
click.echo("Spend bundle written to spend_bundle.json.")
click.echo("Use --push-tx to broadcast this spend.")
wallet_client.close()
await wallet_client.await_closed()
@click.command()
@click.option('--asset-id', required=True, help='Asset id (TAIL hash) of token to be offered in pair (token-XCH)')
@click.option("--push-tx", is_flag=True, show_default=True, default=False, help="Push the signed spend bundle to the network and add liquidity CAT to wallet.")
@click.option('--fee', default=ROUTER_MIN_FEE, help=f'Fee to use for transaction (min fee: {ROUTER_MIN_FEE} = 0.042 XCH)')
def create_pair(asset_id, push_tx, fee):
# very basic check to prevent most mistakes
if len(asset_id) != 64:
click.echo("Oops! That asset id doesn't look right...")
sys.exit(1)
asyncio.run(_create_pair(asset_id, push_tx, fee))
async def _create_pair(tail_hash, push_tx, fee):
if fee < ROUTER_MIN_FEE:
click.echo(
"The router imposes a minimum fee of 42000000000 mojos (0.042 XCH)")
sys.exit(1)
click.echo(f"Creating pair for {tail_hash}...")
router_launcher_id = get_config_item("router_launcher_id")
router_last_processed_id = get_config_item("router_last_processed_id")
if router_launcher_id is None or router_last_processed_id is None:
click.echo("Oops - looks like someone forgot to launch their router.")
sys.exit(1)
click.echo("But first, we do a little sync")
full_node_client = await get_full_node_client(get_config_item("chia_root"), get_config_item("leaflet_url"))
current_router_coin, latest_creation_spend, pairs = await sync_router(
full_node_client, bytes.fromhex(router_last_processed_id)
)
router_last_processed_id_new = current_router_coin.name().hex()
click.echo(f"Last router id: {router_last_processed_id_new}")
if len(pairs) != 0 or router_last_processed_id_new != router_last_processed_id:
click.echo("New pairs found! Saving them...")
router_last_processed_id = router_last_processed_id_new
config = get_config()
config["router_last_processed_id"] = router_last_processed_id
config["pairs"] = config.get("pairs", {})
for pair in pairs:
if config["pairs"].get(pair[0], -1) == -1:
config["pairs"][pair[0]] = pair[1]
save_config(config)
wallet_client = await get_wallet_client(get_config_item("chia_root"))
print(f"Fee: {fee}")
# wallet id 1 = XCH
coins = await wallet_client.select_coins(fee + 1, 1, coin_selection_config=CoinSelectionConfig(
min_coin_amount=fee + 1,
max_coin_amount=1337 * 10 ** 12,
excluded_coin_amounts=[],
excluded_coin_ids=[]
))
coin = coins[0]
coin_puzzle = await get_standard_coin_puzzle(wallet_client, coin)
click.echo(f"Using coin 0x{coin.name().hex()} (amount: {coin.amount})...")
pair_launcher_id, sb = await create_pair_from_coin(
coin,
coin_puzzle,
bytes.fromhex(tail_hash),
bytes.fromhex(router_launcher_id),
current_router_coin,
latest_creation_spend,
fee=fee
)
click.echo(f"Pair launcher id: {pair_launcher_id}")
pair_liquidity_tail_hash = pair_liquidity_tail_puzzle(
bytes.fromhex(pair_launcher_id)).get_tree_hash().hex()
click.echo(f"Liquidity asset id: {pair_liquidity_tail_hash}")
signed_sb = await sign_spend_bundle(wallet_client, sb, additional_data=bytes.fromhex(get_config_item("agg_sig_me_additional_data")))
if push_tx:
click.echo(f"Pushing tx...")
resp = await full_node_client.push_tx(signed_sb)
click.echo(resp)
click.echo("Adding liquidity asset id to wallet...")
resp = await wallet_client.create_wallet_for_existing_cat(bytes.fromhex(pair_liquidity_tail_hash))
click.echo(resp)
click.echo("Done.")
else:
open("spend_bundle.json", "w").write(json.dumps(
signed_sb.to_json_dict(), sort_keys=True, indent=4))
click.echo("Spend bundle written to spend_bundle.json.")
click.echo("Use --push-tx to broadcast this spend.")
wallet_client.close()
await wallet_client.await_closed()
full_node_client.close()
await full_node_client.await_closed()
@click.command()
def sync_pairs():
asyncio.run(_sync_pairs())
async def _sync_pairs():
router_last_processed_id = get_config_item("router_last_processed_id")
if router_last_processed_id is None or len(router_last_processed_id) != 64:
click.echo(
"No router launcher id. Please either set it or launch a new router.")
sys.exit(1)
full_node_client = await get_full_node_client(get_config_item("chia_root"), get_config_item("leaflet_url"))
current_router_coin, latest_creation_spend, pairs = await sync_router(
full_node_client, bytes.fromhex(router_last_processed_id)
)
router_last_processed_id_new = current_router_coin.name().hex()
click.echo(f"Last router id: {router_last_processed_id_new}")
if len(pairs) != 0 or router_last_processed_id_new != router_last_processed_id:
click.echo("New pairs found! Saving them...")
router_last_processed_id = router_last_processed_id_new
config = get_config()
config["router_last_processed_id"] = router_last_processed_id
config["pairs"] = config.get("pairs", {})
for pair in pairs:
if config["pairs"].get(pair[0], -1) == -1:
config["pairs"][pair[0]] = pair[1]
save_config(config)
click.echo("Bye!")
full_node_client.close()
await full_node_client.await_closed()
@click.command()
@click.option("--asset-id", required=True, help='Asset id (TAIL hash) of token to be offered in pair (token-XCH)')
def get_pair_info(asset_id):
if len(asset_id) != 64:
click.echo("Oops! That asset id doesn't look right...")
sys.exit(1)
asyncio.run(_get_pair_info(asset_id))
async def _get_pair_info(token_tail_hash):
click.echo("Getting info...")
offer_str = ""
pair_launcher_id = get_config_item("pairs", token_tail_hash)
if pair_launcher_id is None:
click.echo(
"Corresponding pair launcher id not found in config - you might want to sync-pairs or create-pair.")
sys.exit(1)
full_node_client = await get_full_node_client(get_config_item("chia_root"), get_config_item("leaflet_url"))
last_synced_pair_id = get_config_item("pair_sync", pair_launcher_id)
last_synced_pair_id_not_none = last_synced_pair_id
if last_synced_pair_id_not_none is None:
last_synced_pair_id_not_none = pair_launcher_id
current_pair_coin, creation_spend, pair_state, sb_to_aggregate, last_synced_pair_id_on_blockchain = await sync_pair(
full_node_client, bytes.fromhex(last_synced_pair_id_not_none)
)
current_pair_coin_id = current_pair_coin.name().hex()
click.echo(f"Current pair coin id: {current_pair_coin_id}")
click.echo(f"XCH reserve: {pair_state['xch_reserve'] / 10 ** 12} XCH")
click.echo(f"Token reserve: {pair_state['token_reserve'] / 1000} tokens")
click.echo(f"Total liquidity: {pair_state['liquidity'] / 1000} tokens")
full_node_client.close()
await full_node_client.await_closed()
@click.command()
@click.option("--asset-id", required=True, help='Asset id (TAIL hash) of token to be offered in pair (token-XCH)')
@click.option("--offer", default=None, help='Offer to build liquidity tx from. By default, a new offer will be generated. You can also provide the offer directly or the path to a file containing the offer.')
@click.option("--token-amount", default=0, help="If offer is none, this amount of tokens will be asked for in the offer. Unit is mojos (1 CAT = 1000 mojos).")
@click.option("--xch-amount", default=0, help="Only required if pair has no liquidity. If offer is none, this amount of XCH will be asked for in the generated offer. Unit is mojos.")
@click.option("--push-tx", is_flag=True, show_default=True, default=False, help="Push the signed spend bundle to the network and add liquidity CAT to wallet.")
@click.option('--fee', default=0, help='Fee to use for transaction; only used if offer is generated')
@click.option('--use-fee-estimate', is_flag=True, default=False, show_default=True, help='Estimate required fee when generating offer')
def deposit_liquidity(asset_id, offer, xch_amount, token_amount, push_tx, fee, use_fee_estimate):
if len(asset_id) != 64:
click.echo("Oops! That asset id doesn't look right...")
sys.exit(1)
asyncio.run(_deposit_liquidity(asset_id, offer, xch_amount,
token_amount, push_tx, fee, use_fee_estimate))
async def _deposit_liquidity(token_tail_hash, offer, xch_amount, token_amount, push_tx, fee, use_fee_estimate):
click.echo("Depositing liquidity...")
offer_str = ""
pair_launcher_id = get_config_item("pairs", token_tail_hash)
if pair_launcher_id is None:
click.echo(
"Corresponding pair launcher id not found in config - you might want to sync-pairs or create-pair.")
sys.exit(1)
full_node_client = await get_full_node_client(get_config_item("chia_root"), get_config_item("leaflet_url"))
last_synced_pair_id = get_config_item("pair_sync", pair_launcher_id)
last_synced_pair_id_not_none = last_synced_pair_id
if last_synced_pair_id_not_none is None:
last_synced_pair_id_not_none = pair_launcher_id
current_pair_coin, creation_spend, pair_state, sb_to_aggregate, last_synced_pair_id_on_blockchain = await sync_pair(
full_node_client, bytes.fromhex(last_synced_pair_id_not_none)
)
current_pair_coin_id = current_pair_coin.name().hex()
click.echo(f"Current pair coin id: {current_pair_coin_id}")
if offer is not None:
click.echo("No need to generate new offer.")
if os.path.isfile(offer):
offer_str = open(offer, "r").read().strip()
else:
offer_str = offer
else:
click.echo("Generating new offer...")
if token_amount == 0:
click.echo("Please set ---token-amount to use this option.")
full_node_client.close()
await full_node_client.await_closed()
sys.exit(1)
pair_liquidity_tail_hash = pair_liquidity_tail_puzzle(
bytes.fromhex(pair_launcher_id)).get_tree_hash().hex()
click.echo(f"Liquidity asset id: {pair_liquidity_tail_hash}")
wallet_client = await get_wallet_client(get_config_item("chia_root"))
wallets = await wallet_client.get_wallets(wallet_type=WalletType.CAT)
token_wallet_id = next((_['id'] for _ in wallets if _[
'data'].startswith(token_tail_hash)), None)
liquidity_wallet_id = next((_['id'] for _ in wallets if _[
'data'].startswith(pair_liquidity_tail_hash)), None)
if token_wallet_id is None or liquidity_wallet_id is None:
click.echo(
"You don't have a wallet for the token and/or the pair liquidity token. Please set them up before using this command.")
wallet_client.close()
await wallet_client.await_closed()
full_node_client.close()
await full_node_client.await_closed()
sys.exit(1)
liquidity_token_amount = token_amount
if pair_state['liquidity'] != 0:
liquidity_token_amount = pair_state['liquidity'] * \
token_amount // pair_state['token_reserve']
xch_amount = pair_state['xch_reserve'] * \
token_amount // pair_state['token_reserve']
if use_fee_estimate:
fee = await get_fee_estimate(sb_to_aggregate, full_node_client)
print(f"[!] Using estimated fee: {fee / 10 ** 12} XCH")
offer_dict = {}
# also for liqiudity TAIL creation
offer_dict[1] = - xch_amount - liquidity_token_amount
offer_dict[token_wallet_id] = -token_amount
offer_dict[liquidity_wallet_id] = liquidity_token_amount
offer_resp = await wallet_client.create_offer_for_ids(offer_dict, tx_config=tx_config, fee=fee)
offer = offer_resp[0]
offer_str = offer.to_bech32()
open("offer.txt", "w").write(offer_str)
click.echo("Offer successfully generated and saved to offer.txt.")
wallet_client.close()
await wallet_client.await_closed()
xch_reserve_coin, token_reserve_coin, token_reserve_lineage_proof = await get_pair_reserve_info(
full_node_client,
bytes.fromhex(pair_launcher_id),
current_pair_coin,
bytes.fromhex(token_tail_hash),
creation_spend,
sb_to_aggregate
)
if last_synced_pair_id_on_blockchain != last_synced_pair_id:
click.echo("Pair state updated since last sync; saving it...")
config = get_config()
config["pair_sync"] = config.get("pair_sync", {})
config["pair_sync"][pair_launcher_id] = last_synced_pair_id_on_blockchain.hex()
save_config(config)
sb = await respond_to_deposit_liquidity_offer(
bytes.fromhex(pair_launcher_id),
current_pair_coin,
creation_spend,
bytes.fromhex(token_tail_hash),
pair_state["liquidity"],
pair_state["xch_reserve"],
pair_state["token_reserve"],
offer_str,
xch_reserve_coin,
token_reserve_coin,
token_reserve_lineage_proof
)
if sb_to_aggregate is not None:
sb = SpendBundle.aggregate([sb, sb_to_aggregate])
if push_tx:
resp = input("Are you sure you want to broadcast this spend? (Yes): ")
if resp == "Yes":
click.echo(f"Pushing tx...")
resp = await full_node_client.push_tx(sb)
click.echo(resp)
click.echo("Enjoy your lp fees!")
else:
click.echo("That's not a clear 'Yes'!")
else:
open("spend_bundle.json", "w").write(json.dumps(
sb.to_json_dict(), sort_keys=True, indent=4))
click.echo("Spend bundle written to spend_bundle.json.")
click.echo("Use --push-tx to broadcast this spend.")
full_node_client.close()
await full_node_client.await_closed()
@click.command()
@click.option("--asset-id", required=True, help='Asset id (TAIL hash) of token part of the pair (token-XCH)')
@click.option("--offer", default=None, help='Offer to build liquidity removal tx from. By default, a new offer will be generated. You can also provide the offer directly or the path to a file containing the offer.')
@click.option("--liquidity-token-amount", default=0, help="If offer is none, this amount of liqudity tokens will be included in the offer. Unit is mojos (1 CAT = 1000 mojos).")
@click.option("--push-tx", is_flag=True, show_default=True, default=False, help="Push the signed spend bundle to the network.")
@click.option('--fee', default=0, help='Fee to use for transaction; only used if offer is generated')
@click.option('--use-fee-estimate', is_flag=True, default=False, show_default=True, help='Estimate required fee when generating offer')
def remove_liquidity(asset_id, offer, liquidity_token_amount, push_tx, fee, use_fee_estimate):
if len(asset_id) != 64:
click.echo("Oops! That asset id doesn't look right...")
sys.exit(1)
asyncio.run(_remove_liquidity(asset_id, offer,
liquidity_token_amount, push_tx, fee, use_fee_estimate))
async def _remove_liquidity(token_tail_hash, offer, liquidity_token_amount, push_tx, fee, use_fee_estimate):
click.echo("Removing liquidity...")
offer_str = ""
pair_launcher_id = get_config_item("pairs", token_tail_hash)
if pair_launcher_id is None:
click.echo(
"Corresponding pair launcher id not found in config - you might want to sync-pairs.")
sys.exit(1)
full_node_client = await get_full_node_client(get_config_item("chia_root"), get_config_item("leaflet_url"))
last_synced_pair_id = get_config_item("pair_sync", pair_launcher_id)
last_synced_pair_id_not_none = last_synced_pair_id
if last_synced_pair_id_not_none is None:
last_synced_pair_id_not_none = pair_launcher_id
current_pair_coin, creation_spend, pair_state, sb_to_aggregate, last_synced_pair_id_on_blockchain = await sync_pair(
full_node_client, bytes.fromhex(last_synced_pair_id_not_none)
)
current_pair_coin_id = current_pair_coin.name().hex()
click.echo(f"Current pair coin id: {current_pair_coin_id}")
if offer is not None:
click.echo("No need to generate new offer.")
if os.path.isfile(offer):
offer_str = open(offer, "r").read().strip()
else:
offer_str = offer
else:
click.echo("Generating new offer...")
if liquidity_token_amount == 0:
click.echo(
"Please set ---liquidity-token-amount to use this option.")
full_node_client.close()
await full_node_client.await_closed()
sys.exit(1)
pair_liquidity_tail_hash = pair_liquidity_tail_puzzle(
bytes.fromhex(pair_launcher_id)).get_tree_hash().hex()
click.echo(f"Liquidity asset id: {pair_liquidity_tail_hash}")
wallet_client = await get_wallet_client(get_config_item("chia_root"))
wallets = await wallet_client.get_wallets(wallet_type=WalletType.CAT)
token_wallet_id = next((_['id'] for _ in wallets if _[
'data'].startswith(token_tail_hash)), None)
liquidity_wallet_id = next((_['id'] for _ in wallets if _[
'data'].startswith(pair_liquidity_tail_hash)), None)
if token_wallet_id is None or liquidity_wallet_id is None:
click.echo(
"You don't have a wallet for the token and/or the pair liquidity token. Please set them up before using this command.")
wallet_client.close()
await wallet_client.await_closed()
full_node_client.close()
await full_node_client.await_closed()
sys.exit(1)
token_amount = pair_state['token_reserve'] * \
liquidity_token_amount // pair_state['liquidity']
xch_amount = pair_state['xch_reserve'] * \
liquidity_token_amount // pair_state['liquidity']
if use_fee_estimate:
fee = await get_fee_estimate(sb_to_aggregate, full_node_client)
print(f"[!] Using estimated fee: {fee / 10 ** 12} XCH")
offer_dict = {}
# also ask for xch from liquidity cat burn
offer_dict[1] = xch_amount + liquidity_token_amount
offer_dict[token_wallet_id] = token_amount
offer_dict[liquidity_wallet_id] = -liquidity_token_amount
offer_resp = await wallet_client.create_offer_for_ids(offer_dict, tx_config=tx_config, fee=fee)
offer = offer_resp[0]
offer_str = offer.to_bech32()
open("offer.txt", "w").write(offer_str)
click.echo("Offer successfully generated and saved to offer.txt.")
wallet_client.close()
await wallet_client.await_closed()
xch_reserve_coin, token_reserve_coin, token_reserve_lineage_proof = await get_pair_reserve_info(
full_node_client,
bytes.fromhex(pair_launcher_id),
current_pair_coin,
bytes.fromhex(token_tail_hash),
creation_spend,
sb_to_aggregate
)
if last_synced_pair_id_on_blockchain != last_synced_pair_id:
click.echo("Pair state updated since last sync; saving it...")
config = get_config()
config["pair_sync"] = config.get("pair_sync", {})
config["pair_sync"][pair_launcher_id] = last_synced_pair_id_on_blockchain.hex()
save_config(config)
sb = await respond_to_remove_liquidity_offer(
bytes.fromhex(pair_launcher_id),
current_pair_coin,
creation_spend,
bytes.fromhex(token_tail_hash),
pair_state["liquidity"],
pair_state["xch_reserve"],
pair_state["token_reserve"],
offer_str,
xch_reserve_coin,
token_reserve_coin,
token_reserve_lineage_proof
)
if sb_to_aggregate is not None:
sb = SpendBundle.aggregate([sb, sb_to_aggregate])
if push_tx:
resp = input("Are you sure you want to broadcast this spend? (Yes): ")
if resp == "Yes":
click.echo(f"Pushing tx...")
resp = await full_node_client.push_tx(sb)
click.echo(resp)
click.echo("We're extremely sorry to see your liquidity go :(")
else:
click.echo("That's not a clear 'Yes'!")
else:
open("spend_bundle.json", "w").write(json.dumps(
sb.to_json_dict(), sort_keys=True, indent=4))
click.echo("Spend bundle written to spend_bundle.json.")
click.echo("Use --push-tx to broadcast this spend.")
full_node_client.close()
await full_node_client.await_closed()
@click.command()
@click.option("--asset-id", required=True, help='Asset id (TAIL hash) of token part of the pair (token-XCH)')
@click.option("--offer", default=None, help='Offer to build tx from. By default, a new offer will be generated. You can also provide the offer directly or the path to a file containing the offer.')
@click.option("--xch-amount", default=0, help="If offer is none, this amount of xch will be included in the offer. Unit is mojos.")
@click.option("--push-tx", is_flag=True, show_default=True, default=False, help="Push the spend bundle to the network.")
@click.option('--fee', default=0, help='Fee to use for transaction; only used if offer is generated')
@click.option('--use-fee-estimate', is_flag=True, default=False, show_default=True, help='Estimate required fee when generating offer')
def xch_to_token(asset_id, offer, xch_amount, push_tx, fee, use_fee_estimate):
if len(asset_id) != 64:
click.echo("Oops! That asset id doesn't look right...")
sys.exit(1)
asyncio.run(_xch_to_token(asset_id, offer, xch_amount,
push_tx, fee, use_fee_estimate))
async def _xch_to_token(token_tail_hash, offer, xch_amount, push_tx, fee, use_fee_estimate):
click.echo("Swapping XCH for token...")
offer_str = ""
pair_launcher_id = get_config_item("pairs", token_tail_hash)
if pair_launcher_id is None:
click.echo(
"Corresponding pair launcher id not found in config - you might want to sync-pairs.")
sys.exit(1)
full_node_client = await get_full_node_client(get_config_item("chia_root"), get_config_item("leaflet_url"))
last_synced_pair_id = get_config_item("pair_sync", pair_launcher_id)
last_synced_pair_id_not_none = last_synced_pair_id
if last_synced_pair_id_not_none is None:
last_synced_pair_id_not_none = pair_launcher_id
current_pair_coin, creation_spend, pair_state, sb_to_aggregate, last_synced_pair_id_on_blockchain = await sync_pair(
full_node_client, bytes.fromhex(last_synced_pair_id_not_none)
)
current_pair_coin_id = current_pair_coin.name().hex()
click.echo(f"Current pair coin id: {current_pair_coin_id}")
if offer is not None:
click.echo("No need to generate new offer.")
if os.path.isfile(offer):
offer_str = open(offer, "r").read().strip()
else:
offer_str = offer
else:
click.echo("Generating new offer...")
if xch_amount == 0:
click.echo("Please set ---xch-amount to use this option.")
full_node_client.close()
await full_node_client.await_closed()
sys.exit(1)
pair_liquidity_tail_hash = pair_liquidity_tail_puzzle(
bytes.fromhex(pair_launcher_id)).get_tree_hash().hex()
click.echo(f"Liquidity asset id: {pair_liquidity_tail_hash}")
wallet_client = await get_wallet_client(get_config_item("chia_root"))
wallets = await wallet_client.get_wallets(wallet_type=WalletType.CAT)
token_wallet_id = next((_['id'] for _ in wallets if _[
'data'].startswith(token_tail_hash)), None)
if token_wallet_id is None:
click.echo(
"You don't have a wallet for the token offered in the pair. Please set them up before using this command.")
wallet_client.close()
await wallet_client.await_closed()
full_node_client.close()
await full_node_client.await_closed()
sys.exit(1)
token_amount = 993 * xch_amount * \
pair_state['token_reserve'] // (1000 *
pair_state['xch_reserve'] + 993 * xch_amount)
click.echo(
f"You'll receive {token_amount / 1000} tokens from this trade.")
if token_amount == 0:
wallet_client.close()
await wallet_client.await_closed()
full_node_client.close()
await full_node_client.await_closed()
if use_fee_estimate:
fee = await get_fee_estimate(sb_to_aggregate, full_node_client)
print(f"[!] Using estimated fee: {fee / 10 ** 12} XCH")
offer_dict = {}
offer_dict[1] = -xch_amount # offer XCH
offer_dict[token_wallet_id] = token_amount # ask for token
offer_resp = await wallet_client.create_offer_for_ids(offer_dict, tx_config=tx_config, fee=fee)
offer = offer_resp[0]
offer_str = offer.to_bech32()
open("offer.txt", "w").write(offer_str)
click.echo("Offer successfully generated and saved to offer.txt.")
wallet_client.close()
await wallet_client.await_closed()
xch_reserve_coin, token_reserve_coin, token_reserve_lineage_proof = await get_pair_reserve_info(
full_node_client,
bytes.fromhex(pair_launcher_id),
current_pair_coin,
bytes.fromhex(token_tail_hash),
creation_spend,
sb_to_aggregate
)
if last_synced_pair_id_on_blockchain != last_synced_pair_id:
click.echo("Pair state updated since last sync; saving it...")
config = get_config()
config["pair_sync"] = config.get("pair_sync", {})
config["pair_sync"][pair_launcher_id] = last_synced_pair_id_on_blockchain.hex()
save_config(config)
sb = await respond_to_swap_offer(
bytes.fromhex(pair_launcher_id),
current_pair_coin,
creation_spend,
bytes.fromhex(token_tail_hash),
pair_state["liquidity"],
pair_state["xch_reserve"],
pair_state["token_reserve"],
offer_str,
xch_reserve_coin,
token_reserve_coin,
token_reserve_lineage_proof
)
if sb_to_aggregate is not None:
sb = SpendBundle.aggregate([sb, sb_to_aggregate])
if push_tx:
resp = input("Are you sure you want to broadcast this spend? (Yes): ")
if resp == "Yes":
click.echo(f"Pushing tx...")
resp = await full_node_client.push_tx(sb)
click.echo(resp)
click.echo("Enjoy your shiny new tokens!")
else:
click.echo("That's not a clear 'Yes'!")
else:
open("spend_bundle.json", "w").write(json.dumps(
sb.to_json_dict(), sort_keys=True, indent=4))
click.echo("Spend bundle written to spend_bundle.json.")
click.echo("Use --push-tx to broadcast this spend.")
full_node_client.close()
await full_node_client.await_closed()
@click.command()
@click.option("--asset-id", required=True, help='Asset id (TAIL hash) of token part of the pair (token-XCH)')
@click.option("--offer", default=None, help='Offer to build tx from. By default, a new offer will be generated. You can also provide the offer directly or the path to a file containing the offer.')
@click.option("--token-amount", default=0, help="If offer is none, this amount of tokens will be included in the offer. Unit is mojos (1 CAT = 1000 mojos).")
@click.option("--push-tx", is_flag=True, show_default=True, default=False, help="Push the spend bundle to the network.")
@click.option('--fee', default=0, help='Fee to use for transaction; only used if offer is generated')
@click.option('--use-fee-estimate', is_flag=True, default=False, show_default=True, help='Estimate required fee when generating offer')
def token_to_xch(asset_id, offer, token_amount, push_tx, fee, use_fee_estimate):
if len(asset_id) != 64:
click.echo("Oops! That asset id doesn't look right...")
sys.exit(1)
asyncio.run(_token_to_xch(asset_id, offer, token_amount,
push_tx, fee, use_fee_estimate))
async def _token_to_xch(token_tail_hash, offer, token_amount, push_tx, fee, use_fee_estimate):
click.echo("Swapping token for XCH...")
offer_str = ""
pair_launcher_id = get_config_item("pairs", token_tail_hash)
if pair_launcher_id is None:
click.echo(
"Corresponding pair launcher id not found in config - you might want to sync-pairs.")
sys.exit(1)
full_node_client = await get_full_node_client(get_config_item("chia_root"), get_config_item("leaflet_url"))
last_synced_pair_id = get_config_item("pair_sync", pair_launcher_id)
last_synced_pair_id_not_none = last_synced_pair_id
if last_synced_pair_id_not_none is None:
last_synced_pair_id_not_none = pair_launcher_id
current_pair_coin, creation_spend, pair_state, sb_to_aggregate, last_synced_pair_id_on_blockchain = await sync_pair(
full_node_client, bytes.fromhex(last_synced_pair_id_not_none)
)
current_pair_coin_id = current_pair_coin.name().hex()
click.echo(f"Current pair coin id: {current_pair_coin_id}")
if offer is not None:
click.echo("No need to generate new offer.")
if os.path.isfile(offer):
offer_str = open(offer, "r").read().strip()
else:
offer_str = offer
else:
click.echo("Generating new offer...")
if token_amount == 0:
click.echo("Please set ---token-amount to use this option.")
full_node_client.close()
await full_node_client.await_closed()
sys.exit(1)
pair_liquidity_tail_hash = pair_liquidity_tail_puzzle(
bytes.fromhex(pair_launcher_id)).get_tree_hash().hex()
click.echo(f"Liquidity asset id: {pair_liquidity_tail_hash}")
wallet_client = await get_wallet_client(get_config_item("chia_root"))
wallets = await wallet_client.get_wallets(wallet_type=WalletType.CAT)
token_wallet_id = next((_['id'] for _ in wallets if _[
'data'].startswith(token_tail_hash)), None)
if token_wallet_id is None:
click.echo(
"You don't have a wallet for the token offered in the pair. Please set them up before using this command.")
wallet_client.close()
await wallet_client.await_closed()
full_node_client.close()
await full_node_client.await_closed()
sys.exit(1)
xch_amount = 993 * token_amount * \
pair_state['xch_reserve'] // (1000 *
pair_state['token_reserve'] + 993 * token_amount)
click.echo(
f"You'll receive {xch_amount / 1000000000000} XCH from this trade.")
if token_amount == 0:
wallet_client.close()
await wallet_client.await_closed()
full_node_client.close()
await full_node_client.await_closed()
if use_fee_estimate:
fee = await get_fee_estimate(sb_to_aggregate, full_node_client)
print(f"[!] Using estimated fee: {fee / 10 ** 12} XCH")
offer_dict = {}
offer_dict[1] = xch_amount # ask for XCH
offer_dict[token_wallet_id] = -token_amount # offer tokens
offer_resp = await wallet_client.create_offer_for_ids(offer_dict, tx_config=tx_config, fee=fee)
offer = offer_resp[0]
offer_str = offer.to_bech32()
open("offer.txt", "w").write(offer_str)
click.echo("Offer successfully generated and saved to offer.txt.")
wallet_client.close()
await wallet_client.await_closed()
xch_reserve_coin, token_reserve_coin, token_reserve_lineage_proof = await get_pair_reserve_info(
full_node_client,
bytes.fromhex(pair_launcher_id),
current_pair_coin,
bytes.fromhex(token_tail_hash),
creation_spend,
sb_to_aggregate