-
Notifications
You must be signed in to change notification settings - Fork 2k
/
wallet_funcs.py
1761 lines (1584 loc) · 72.5 KB
/
wallet_funcs.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
from __future__ import annotations
import asyncio
import json
import os
import pathlib
import sys
import time
from datetime import datetime
from decimal import Decimal
from typing import Any, Awaitable, Callable, Dict, List, Optional, Sequence, Tuple, Union
from chia.cmds.cmds_util import (
CMDTXConfigLoader,
cli_confirm,
get_wallet_client,
transaction_status_msg,
transaction_submitted_msg,
)
from chia.cmds.peer_funcs import print_connections
from chia.cmds.units import units
from chia.rpc.wallet_request_types import CATSpendResponse, GetNotifications, SendTransactionResponse
from chia.rpc.wallet_rpc_client import WalletRpcClient
from chia.types.blockchain_format.sized_bytes import bytes32
from chia.util.bech32m import bech32_decode, decode_puzzle_hash, encode_puzzle_hash
from chia.util.byte_types import hexstr_to_bytes
from chia.util.config import selected_network_address_prefix
from chia.util.ints import uint16, uint32, uint64
from chia.wallet.conditions import CreateCoinAnnouncement, CreatePuzzleAnnouncement
from chia.wallet.nft_wallet.nft_info import NFTInfo
from chia.wallet.outer_puzzles import AssetType
from chia.wallet.puzzle_drivers import PuzzleInfo
from chia.wallet.trade_record import TradeRecord
from chia.wallet.trading.offer import Offer
from chia.wallet.trading.trade_status import TradeStatus
from chia.wallet.transaction_record import TransactionRecord
from chia.wallet.transaction_sorting import SortKey
from chia.wallet.util.address_type import AddressType, ensure_valid_address
from chia.wallet.util.puzzle_decorator_type import PuzzleDecoratorType
from chia.wallet.util.query_filter import HashFilter, TransactionTypeFilter
from chia.wallet.util.transaction_type import CLAWBACK_INCOMING_TRANSACTION_TYPES, TransactionType
from chia.wallet.util.wallet_types import WalletType
from chia.wallet.vc_wallet.vc_store import VCProofs
from chia.wallet.wallet_coin_store import GetCoinRecords
CATNameResolver = Callable[[bytes32], Awaitable[Optional[Tuple[Optional[uint32], str]]]]
transaction_type_descriptions = {
TransactionType.INCOMING_TX: "received",
TransactionType.OUTGOING_TX: "sent",
TransactionType.COINBASE_REWARD: "rewarded",
TransactionType.FEE_REWARD: "rewarded",
TransactionType.INCOMING_TRADE: "received in trade",
TransactionType.OUTGOING_TRADE: "sent in trade",
TransactionType.INCOMING_CLAWBACK_RECEIVE: "received in clawback as recipient",
TransactionType.INCOMING_CLAWBACK_SEND: "received in clawback as sender",
TransactionType.OUTGOING_CLAWBACK: "claim/clawback",
}
def transaction_description_from_type(tx: TransactionRecord) -> str:
return transaction_type_descriptions.get(TransactionType(tx.type), "(unknown reason)")
def print_transaction(
tx: TransactionRecord,
verbose: bool,
name: str,
address_prefix: str,
mojo_per_unit: int,
coin_record: Optional[Dict[str, Any]] = None,
) -> None: # pragma: no cover
if verbose:
print(tx)
else:
chia_amount = Decimal(int(tx.amount)) / mojo_per_unit
to_address = encode_puzzle_hash(tx.to_puzzle_hash, address_prefix)
print(f"Transaction {tx.name}")
print(f"Status: {'Confirmed' if tx.confirmed else ('In mempool' if tx.is_in_mempool() else 'Pending')}")
description = transaction_description_from_type(tx)
print(f"Amount {description}: {chia_amount} {name}")
print(f"To address: {to_address}")
print("Created at:", datetime.fromtimestamp(tx.created_at_time).strftime("%Y-%m-%d %H:%M:%S"))
if coin_record is not None:
print(
"Recipient claimable time:",
datetime.fromtimestamp(tx.created_at_time + coin_record["metadata"]["time_lock"]).strftime(
"%Y-%m-%d %H:%M:%S"
),
)
print("")
def get_mojo_per_unit(wallet_type: WalletType) -> int: # pragma: no cover
mojo_per_unit: int
if wallet_type in {
WalletType.STANDARD_WALLET,
WalletType.POOLING_WALLET,
WalletType.DATA_LAYER,
WalletType.VC,
WalletType.DAO,
}:
mojo_per_unit = units["chia"]
elif wallet_type in {WalletType.CAT, WalletType.CRCAT}:
mojo_per_unit = units["cat"]
elif wallet_type in {WalletType.NFT, WalletType.DECENTRALIZED_ID, WalletType.DAO_CAT}:
mojo_per_unit = units["mojo"]
else:
raise LookupError(f"Operation is not supported for Wallet type {wallet_type.name}")
return mojo_per_unit
async def get_wallet_type(wallet_id: int, wallet_client: WalletRpcClient) -> WalletType:
summaries_response = await wallet_client.get_wallets()
for summary in summaries_response:
summary_id: int = summary["id"]
summary_type: int = summary["type"]
if wallet_id == summary_id:
return WalletType(summary_type)
raise LookupError(f"Wallet ID not found: {wallet_id}")
async def get_unit_name_for_wallet_id(
config: Dict[str, Any],
wallet_type: WalletType,
wallet_id: int,
wallet_client: WalletRpcClient,
) -> str: # pragma: no cover
if wallet_type in {
WalletType.STANDARD_WALLET,
WalletType.POOLING_WALLET,
WalletType.DATA_LAYER,
WalletType.VC,
}: # pragma: no cover
name: str = config["network_overrides"]["config"][config["selected_network"]]["address_prefix"].upper()
elif wallet_type in {WalletType.CAT, WalletType.CRCAT}:
name = await wallet_client.get_cat_name(wallet_id=wallet_id)
else:
raise LookupError(f"Operation is not supported for Wallet type {wallet_type.name}")
return name
async def get_transaction(
*, wallet_rpc_port: Optional[int], fingerprint: Optional[int], tx_id: str, verbose: int
) -> None:
async with get_wallet_client(wallet_rpc_port, fingerprint) as (wallet_client, fingerprint, config):
transaction_id = bytes32.from_hexstr(tx_id)
address_prefix = selected_network_address_prefix(config)
tx: TransactionRecord = await wallet_client.get_transaction(transaction_id=transaction_id)
try:
wallet_type = await get_wallet_type(wallet_id=tx.wallet_id, wallet_client=wallet_client)
mojo_per_unit = get_mojo_per_unit(wallet_type=wallet_type)
name = await get_unit_name_for_wallet_id(
config=config,
wallet_type=wallet_type,
wallet_id=tx.wallet_id,
wallet_client=wallet_client,
)
except LookupError as e:
print(e.args[0])
return
print_transaction(
tx,
verbose=(verbose > 0),
name=name,
address_prefix=address_prefix,
mojo_per_unit=mojo_per_unit,
)
async def get_transactions(
*,
wallet_rpc_port: Optional[int],
fp: Optional[int],
wallet_id: int,
verbose: int,
paginate: Optional[bool],
offset: int,
limit: int,
sort_key: SortKey,
reverse: bool,
clawback: bool,
) -> None: # pragma: no cover
async with get_wallet_client(wallet_rpc_port, fp) as (wallet_client, fingerprint, config):
if paginate is None:
paginate = sys.stdout.isatty()
type_filter = (
None
if not clawback
else TransactionTypeFilter.include(
[TransactionType.INCOMING_CLAWBACK_RECEIVE, TransactionType.INCOMING_CLAWBACK_SEND]
)
)
txs: List[TransactionRecord] = await wallet_client.get_transactions(
wallet_id, start=offset, end=(offset + limit), sort_key=sort_key, reverse=reverse, type_filter=type_filter
)
address_prefix = selected_network_address_prefix(config)
if len(txs) == 0:
print("There are no transactions to this address")
try:
wallet_type = await get_wallet_type(wallet_id=wallet_id, wallet_client=wallet_client)
mojo_per_unit = get_mojo_per_unit(wallet_type=wallet_type)
name = await get_unit_name_for_wallet_id(
config=config,
wallet_type=wallet_type,
wallet_id=wallet_id,
wallet_client=wallet_client,
)
except LookupError as e:
print(e.args[0])
return
skipped = 0
num_per_screen = 5 if paginate else len(txs)
for i in range(0, len(txs), num_per_screen):
for j in range(0, num_per_screen):
if i + j + skipped >= len(txs):
break
coin_record: Optional[Dict[str, Any]] = None
if txs[i + j + skipped].type in CLAWBACK_INCOMING_TRANSACTION_TYPES:
coin_records = await wallet_client.get_coin_records(
GetCoinRecords(coin_id_filter=HashFilter.include([txs[i + j + skipped].additions[0].name()]))
)
if len(coin_records["coin_records"]) > 0:
coin_record = coin_records["coin_records"][0]
else:
j -= 1
skipped += 1
continue
print_transaction(
txs[i + j + skipped],
verbose=(verbose > 0),
name=name,
address_prefix=address_prefix,
mojo_per_unit=mojo_per_unit,
coin_record=coin_record,
)
if i + num_per_screen >= len(txs):
return None
print("Press q to quit, or c to continue")
while True:
entered_key = sys.stdin.read(1)
if entered_key == "q":
return None
elif entered_key == "c":
break
def check_unusual_transaction(amount: Decimal, fee: Decimal) -> bool:
return fee >= amount
async def send(
*,
wallet_rpc_port: Optional[int],
fp: Optional[int],
wallet_id: int,
amount: Decimal,
memo: Optional[str],
fee: Decimal,
address: str,
override: bool,
min_coin_amount: str,
max_coin_amount: Optional[str],
excluded_coin_ids: Sequence[str],
reuse_puzhash: Optional[bool],
clawback_time_lock: int,
push: bool,
) -> List[TransactionRecord]:
async with get_wallet_client(wallet_rpc_port, fp) as (wallet_client, fingerprint, config):
if memo is None:
memos = None
else:
memos = [memo]
if not override and check_unusual_transaction(amount, fee):
print(
f"A transaction of amount {amount} and fee {fee} is unusual.\n"
f"Pass in --override if you are sure you mean to do this."
)
return []
if amount == 0:
print("You can not send an empty transaction")
return []
if clawback_time_lock < 0:
print("Clawback time lock seconds cannot be negative.")
return []
try:
typ = await get_wallet_type(wallet_id=wallet_id, wallet_client=wallet_client)
mojo_per_unit = get_mojo_per_unit(typ)
except LookupError:
print(f"Wallet id: {wallet_id} not found.")
return []
final_fee: uint64 = uint64(int(fee * units["chia"])) # fees are always in XCH mojos
final_amount: uint64 = uint64(int(amount * mojo_per_unit))
if typ == WalletType.STANDARD_WALLET:
print("Submitting transaction...")
res: Union[CATSpendResponse, SendTransactionResponse] = await wallet_client.send_transaction(
wallet_id,
final_amount,
address,
CMDTXConfigLoader(
min_coin_amount=min_coin_amount,
max_coin_amount=max_coin_amount,
excluded_coin_ids=list(excluded_coin_ids),
reuse_puzhash=reuse_puzhash,
).to_tx_config(mojo_per_unit, config, fingerprint),
final_fee,
memos,
puzzle_decorator_override=(
[{"decorator": PuzzleDecoratorType.CLAWBACK.name, "clawback_timelock": clawback_time_lock}]
if clawback_time_lock > 0
else None
),
push=push,
)
elif typ in {WalletType.CAT, WalletType.CRCAT}:
print("Submitting transaction...")
res = await wallet_client.cat_spend(
wallet_id,
CMDTXConfigLoader(
min_coin_amount=min_coin_amount,
max_coin_amount=max_coin_amount,
excluded_coin_ids=list(excluded_coin_ids),
reuse_puzhash=reuse_puzhash,
).to_tx_config(mojo_per_unit, config, fingerprint),
final_amount,
address,
final_fee,
memos,
push=push,
)
else:
print("Only standard wallet and CAT wallets are supported")
return []
tx_id = res.transaction.name
if push:
start = time.time()
while time.time() - start < 10:
await asyncio.sleep(0.1)
tx = await wallet_client.get_transaction(tx_id)
if len(tx.sent_to) > 0:
print(transaction_submitted_msg(tx))
print(transaction_status_msg(fingerprint, tx_id))
return res.transactions
print("Transaction not yet submitted to nodes")
if push: # pragma: no cover
print(f"To get status, use command: chia wallet get_transaction -f {fingerprint} -tx 0x{tx_id}")
return res.transactions # pragma: no cover
async def get_address(wallet_rpc_port: Optional[int], fp: Optional[int], wallet_id: int, new_address: bool) -> None:
async with get_wallet_client(wallet_rpc_port, fp) as (wallet_client, fingerprint, config):
res = await wallet_client.get_next_address(wallet_id, new_address)
print(res)
async def delete_unconfirmed_transactions(wallet_rpc_port: Optional[int], fp: Optional[int], wallet_id: int) -> None:
async with get_wallet_client(wallet_rpc_port, fp) as (wallet_client, fingerprint, _):
await wallet_client.delete_unconfirmed_transactions(wallet_id)
print(f"Successfully deleted all unconfirmed transactions for wallet id {wallet_id} on key {fingerprint}")
async def get_derivation_index(wallet_rpc_port: Optional[int], fp: Optional[int]) -> None:
async with get_wallet_client(wallet_rpc_port, fp) as (wallet_client, _, _):
res = await wallet_client.get_current_derivation_index()
print(f"Last derivation index: {res}")
async def update_derivation_index(wallet_rpc_port: Optional[int], fp: Optional[int], index: int) -> None:
async with get_wallet_client(wallet_rpc_port, fp) as (wallet_client, _, _):
print("Updating derivation index... This may take a while.")
res = await wallet_client.extend_derivation_index(index)
print(f"Updated derivation index: {res}")
print("Your balances may take a while to update.")
async def add_token(wallet_rpc_port: Optional[int], fp: Optional[int], asset_id: str, token_name: str) -> None:
async with get_wallet_client(wallet_rpc_port, fp) as (wallet_client, fingerprint, _):
try:
asset_id_bytes: bytes32 = bytes32.from_hexstr(asset_id)
existing_info: Optional[Tuple[Optional[uint32], str]] = await wallet_client.cat_asset_id_to_name(
asset_id_bytes
)
if existing_info is None or existing_info[0] is None:
response = await wallet_client.create_wallet_for_existing_cat(asset_id_bytes)
wallet_id = response["wallet_id"]
await wallet_client.set_cat_name(wallet_id, token_name)
print(f"Successfully added {token_name} with wallet id {wallet_id} on key {fingerprint}")
else:
wallet_id, old_name = existing_info
await wallet_client.set_cat_name(wallet_id, token_name)
print(
f"Successfully renamed {old_name} with wallet_id {wallet_id} on key {fingerprint} to {token_name}"
)
except ValueError as e:
if "fromhex()" in str(e):
print(f"{asset_id} is not a valid Asset ID")
else:
raise
async def make_offer(
*,
wallet_rpc_port: Optional[int],
fp: Optional[int],
d_fee: Decimal,
offers: Sequence[str],
requests: Sequence[str],
filepath: pathlib.Path,
reuse_puzhash: Optional[bool],
) -> None:
async with get_wallet_client(wallet_rpc_port, fp) as (wallet_client, fingerprint, config):
fee: int = int(d_fee * units["chia"])
if offers == [] or requests == []:
print("Not creating offer: Must be offering and requesting at least one asset")
else:
offer_dict: Dict[Union[uint32, str], int] = {}
driver_dict: Dict[str, Any] = {}
printable_dict: Dict[str, Tuple[str, int, int]] = {} # Dict[asset_name, Tuple[amount, unit, multiplier]]
royalty_asset_dict: Dict[Any, Tuple[Any, uint16]] = {}
fungible_asset_dict: Dict[Any, uint64] = {}
for item in [*offers, *requests]:
name, amount = tuple(item.split(":")[0:2])
try:
b32_id = bytes32.from_hexstr(name)
id: Union[uint32, str] = b32_id.hex()
result = await wallet_client.cat_asset_id_to_name(b32_id)
if result is not None:
name = result[1]
else:
name = "Unknown CAT"
unit = units["cat"]
if item in offers:
fungible_asset_dict[name] = uint64(abs(int(Decimal(amount) * unit)))
except ValueError:
try:
hrp, _ = bech32_decode(name)
if hrp == "nft":
coin_id = decode_puzzle_hash(name)
unit = 1
info = NFTInfo.from_json_dict((await wallet_client.get_nft_info(coin_id.hex()))["nft_info"])
id = info.launcher_id.hex()
assert isinstance(id, str)
if item in requests:
driver_dict[id] = {
"type": "singleton",
"launcher_id": "0x" + id,
"launcher_ph": "0x" + info.launcher_puzhash.hex(),
"also": {
"type": "metadata",
"metadata": info.chain_info,
"updater_hash": "0x" + info.updater_puzhash.hex(),
},
}
if info.supports_did:
assert info.royalty_puzzle_hash is not None
assert info.royalty_percentage is not None
driver_dict[id]["also"]["also"] = {
"type": "ownership",
"owner": "()",
"transfer_program": {
"type": "royalty transfer program",
"launcher_id": "0x" + info.launcher_id.hex(),
"royalty_address": "0x" + info.royalty_puzzle_hash.hex(),
"royalty_percentage": str(info.royalty_percentage),
},
}
royalty_asset_dict[name] = (
encode_puzzle_hash(info.royalty_puzzle_hash, AddressType.XCH.hrp(config)),
info.royalty_percentage,
)
else:
id = decode_puzzle_hash(name).hex()
assert hrp is not None
unit = units[hrp]
except ValueError:
id = uint32(int(name))
if id == 1:
name = "XCH"
unit = units["chia"]
else:
name = await wallet_client.get_cat_name(id)
unit = units["cat"]
if item in offers:
fungible_asset_dict[name] = uint64(abs(int(Decimal(amount) * unit)))
multiplier: int = -1 if item in offers else 1
printable_dict[name] = (amount, unit, multiplier)
if id in offer_dict:
print("Not creating offer: Cannot offer and request the same asset in a trade")
break
else:
offer_dict[id] = int(Decimal(amount) * unit) * multiplier
else:
print("Creating Offer")
print("--------------")
print()
print("OFFERING:")
for name, data in printable_dict.items():
amount, unit, multiplier = data
if multiplier < 0:
print(f" - {amount} {name} ({int(Decimal(amount) * unit)} mojos)")
print("REQUESTING:")
for name, data in printable_dict.items():
amount, unit, multiplier = data
if multiplier > 0:
print(f" - {amount} {name} ({int(Decimal(amount) * unit)} mojos)")
if fee > 0:
print()
print(f"Including Fees: {Decimal(fee) / units['chia']} XCH, {fee} mojos")
if royalty_asset_dict != {}:
royalty_summary: Dict[Any, List[Dict[str, Any]]] = await wallet_client.nft_calculate_royalties(
royalty_asset_dict, fungible_asset_dict
)
total_amounts_requested: Dict[Any, int] = {}
print()
print("Royalties Summary:")
for nft_id, summaries in royalty_summary.items():
print(f" - For {nft_id}:")
for summary in summaries:
divisor = units["chia"] if summary["asset"] == "XCH" else units["cat"]
converted_amount = Decimal(summary["amount"]) / divisor
total_amounts_requested.setdefault(summary["asset"], fungible_asset_dict[summary["asset"]])
total_amounts_requested[summary["asset"]] += summary["amount"]
print(
f" - {converted_amount} {summary['asset']} ({summary['amount']} mojos) to {summary['address']}" # noqa
)
print()
print("Total Amounts Offered:")
for asset, requested_amount in total_amounts_requested.items():
divisor = units["chia"] if asset == "XCH" else units["cat"]
converted_amount = Decimal(requested_amount) / divisor
print(f" - {converted_amount} {asset} ({requested_amount} mojos)")
cli_confirm(
"\nOffers for NFTs will have royalties automatically added. "
"Are you sure you would like to continue? (y/n): ",
"Not creating offer...",
)
cli_confirm("Confirm (y/n): ", "Not creating offer...")
with filepath.open(mode="w") as file:
res = await wallet_client.create_offer_for_ids(
offer_dict,
driver_dict=driver_dict,
fee=fee,
tx_config=CMDTXConfigLoader(
reuse_puzhash=reuse_puzhash,
).to_tx_config(units["chia"], config, fingerprint),
)
if res.offer is not None:
file.write(res.offer.to_bech32())
print(f"Created offer with ID {res.trade_record.trade_id}")
print(
f"Use chia wallet get_offers --id "
f"{res.trade_record.trade_id} -f {fingerprint} to view status"
)
else:
print("Error creating offer")
def timestamp_to_time(timestamp: int) -> str:
return datetime.fromtimestamp(timestamp).strftime("%Y-%m-%d %H:%M:%S")
async def print_offer_summary(
cat_name_resolver: CATNameResolver, sum_dict: Dict[str, int], has_fee: bool = False, network_xch: str = "XCH"
) -> None:
for asset_id, amount in sum_dict.items():
description: str = ""
unit: int = units["chia"]
wid: str = "1" if asset_id == "xch" else ""
mojo_amount: int = int(Decimal(amount))
name: str = network_xch
if asset_id != "xch":
name = asset_id
if asset_id == "unknown":
name = "Unknown"
unit = units["mojo"]
if has_fee:
description = " [Typically represents change returned from the included fee]"
else:
unit = units["cat"]
result = await cat_name_resolver(bytes32.from_hexstr(asset_id))
if result is not None:
wid = str(result[0])
name = result[1]
output: str = f" - {name}"
mojo_str: str = f"{mojo_amount} {'mojo' if mojo_amount == 1 else 'mojos'}"
if len(wid) > 0:
output += f" (Wallet ID: {wid})"
if unit == units["mojo"]:
output += f": {mojo_str}"
else:
output += f": {mojo_amount / unit} ({mojo_str})"
if len(description) > 0:
output += f" {description}"
print(output)
async def print_trade_record(record: TradeRecord, wallet_client: WalletRpcClient, summaries: bool = False) -> None:
print()
print(f"Record with id: {record.trade_id}")
print("---------------")
print(f"Created at: {timestamp_to_time(record.created_at_time)}")
print(f"Confirmed at: {record.confirmed_at_index if record.confirmed_at_index > 0 else 'Not confirmed'}")
print(f"Accepted at: {timestamp_to_time(record.accepted_at_time) if record.accepted_at_time else 'N/A'}")
print(f"Status: {TradeStatus(record.status).name}")
if summaries:
print("Summary:")
offer = Offer.from_bytes(record.offer)
offered, requested, _, _ = offer.summary()
outbound_balances: Dict[str, int] = offer.get_pending_amounts()
fees: Decimal = Decimal(offer.fees())
cat_name_resolver = wallet_client.cat_asset_id_to_name
print(" OFFERED:")
await print_offer_summary(cat_name_resolver, offered)
print(" REQUESTED:")
await print_offer_summary(cat_name_resolver, requested)
print("Pending Outbound Balances:")
await print_offer_summary(cat_name_resolver, outbound_balances, has_fee=(fees > 0))
print(f"Included Fees: {fees / units['chia']} XCH, {fees} mojos")
print("---------------")
async def get_offers(
*,
wallet_rpc_port: Optional[int],
fp: Optional[int],
offer_id: Optional[str],
filepath: Optional[str],
exclude_my_offers: bool = False,
exclude_taken_offers: bool = False,
include_completed: bool = False,
summaries: bool = False,
reverse: bool = False,
) -> None:
async with get_wallet_client(wallet_rpc_port, fp) as (wallet_client, fingerprint, config):
file_contents: bool = (filepath is not None) or summaries
records: List[TradeRecord] = []
if offer_id is None:
batch_size: int = 10
start: int = 0
end: int = start + batch_size
# Traverse offers page by page
while True:
new_records: List[TradeRecord] = await wallet_client.get_all_offers(
start,
end,
reverse=reverse,
file_contents=file_contents,
exclude_my_offers=exclude_my_offers,
exclude_taken_offers=exclude_taken_offers,
include_completed=include_completed,
)
records.extend(new_records)
# If fewer records were returned than requested, we're done
if len(new_records) < batch_size:
break
start = end
end += batch_size
else:
records = [await wallet_client.get_offer(bytes32.from_hexstr(offer_id), file_contents)]
if filepath is not None:
with open(pathlib.Path(filepath), "w") as file:
file.write(Offer.from_bytes(records[0].offer).to_bech32())
file.close()
for record in records:
await print_trade_record(record, wallet_client, summaries=summaries)
async def take_offer(
wallet_rpc_port: Optional[int],
fp: Optional[int],
d_fee: Decimal,
file: str,
examine_only: bool,
push: bool = True,
) -> List[TransactionRecord]:
async with get_wallet_client(wallet_rpc_port, fp) as (wallet_client, fingerprint, config):
if os.path.exists(file):
filepath = pathlib.Path(file)
with open(filepath) as ffile:
offer_hex: str = ffile.read()
ffile.close()
else:
offer_hex = file
fee: int = int(d_fee * units["chia"])
try:
offer = Offer.from_bech32(offer_hex)
except ValueError:
print("Please enter a valid offer file or hex blob")
return []
offered, requested, _, _ = offer.summary()
cat_name_resolver = wallet_client.cat_asset_id_to_name
network_xch = AddressType.XCH.hrp(config).upper()
print("Summary:")
print(" OFFERED:")
await print_offer_summary(cat_name_resolver, offered, network_xch=network_xch)
print(" REQUESTED:")
await print_offer_summary(cat_name_resolver, requested, network_xch=network_xch)
print()
royalty_asset_dict: Dict[Any, Tuple[Any, uint16]] = {}
for royalty_asset_id in nft_coin_ids_supporting_royalties_from_offer(offer):
if royalty_asset_id.hex() in offered:
percentage, address = await get_nft_royalty_percentage_and_address(royalty_asset_id, wallet_client)
royalty_asset_dict[encode_puzzle_hash(royalty_asset_id, AddressType.NFT.hrp(config))] = (
encode_puzzle_hash(address, AddressType.XCH.hrp(config)),
percentage,
)
if royalty_asset_dict != {}:
fungible_asset_dict: Dict[Any, uint64] = {}
for fungible_asset_id in fungible_assets_from_offer(offer):
fungible_asset_id_str = fungible_asset_id.hex() if fungible_asset_id is not None else "xch"
if fungible_asset_id_str in requested:
nft_royalty_currency: str = "Unknown CAT"
if fungible_asset_id is None:
nft_royalty_currency = network_xch
else:
result = await wallet_client.cat_asset_id_to_name(fungible_asset_id)
if result is not None:
nft_royalty_currency = result[1]
fungible_asset_dict[nft_royalty_currency] = uint64(requested[fungible_asset_id_str])
if fungible_asset_dict != {}:
royalty_summary: Dict[Any, List[Dict[str, Any]]] = await wallet_client.nft_calculate_royalties(
royalty_asset_dict, fungible_asset_dict
)
total_amounts_requested: Dict[Any, int] = {}
print("Royalties Summary:")
for nft_id, summaries in royalty_summary.items():
print(f" - For {nft_id}:")
for summary in summaries:
divisor = units["chia"] if summary["asset"] == network_xch else units["cat"]
converted_amount = Decimal(summary["amount"]) / divisor
total_amounts_requested.setdefault(summary["asset"], fungible_asset_dict[summary["asset"]])
total_amounts_requested[summary["asset"]] += summary["amount"]
print(
f" - {converted_amount} {summary['asset']} ({summary['amount']} mojos) to {summary['address']}" # noqa
)
print()
print("Total Amounts Requested:")
for asset, amount in total_amounts_requested.items():
divisor = units["chia"] if asset == network_xch else units["cat"]
converted_amount = Decimal(amount) / divisor
print(f" - {converted_amount} {asset} ({amount} mojos)")
print(f"Included Fees: {Decimal(offer.fees()) / units['chia']} {network_xch}, {offer.fees()} mojos")
if not examine_only:
print()
cli_confirm("Would you like to take this offer? (y/n): ")
res = await wallet_client.take_offer(
offer,
fee=fee,
tx_config=CMDTXConfigLoader().to_tx_config(units["chia"], config, fingerprint),
push=push,
)
if push:
print(f"Accepted offer with ID {res.trade_record.trade_id}")
print(
f"Use chia wallet get_offers --id {res.trade_record.trade_id} -f {fingerprint} to view its status"
)
return res.transactions
else:
return []
async def cancel_offer(
wallet_rpc_port: Optional[int],
fp: Optional[int],
d_fee: Decimal,
offer_id_hex: str,
secure: bool,
push: bool = True,
) -> List[TransactionRecord]:
async with get_wallet_client(wallet_rpc_port, fp) as (wallet_client, fingerprint, config):
offer_id = bytes32.from_hexstr(offer_id_hex)
fee: int = int(d_fee * units["chia"])
trade_record = await wallet_client.get_offer(offer_id, file_contents=True)
await print_trade_record(trade_record, wallet_client, summaries=True)
cli_confirm(f"Are you sure you wish to cancel offer with ID: {trade_record.trade_id}? (y/n): ")
res = await wallet_client.cancel_offer(
offer_id,
CMDTXConfigLoader().to_tx_config(units["chia"], config, fingerprint),
secure=secure,
fee=fee,
push=push,
)
if push or not secure:
print(f"Cancelled offer with ID {trade_record.trade_id}")
if secure and push:
print(f"Use chia wallet get_offers --id {trade_record.trade_id} -f {fingerprint} to view cancel status")
return res.transactions
def wallet_coin_unit(typ: WalletType, address_prefix: str) -> Tuple[str, int]: # pragma: no cover
if typ in {WalletType.CAT, WalletType.CRCAT}:
return "", units["cat"]
if typ in [WalletType.STANDARD_WALLET, WalletType.POOLING_WALLET, WalletType.MULTI_SIG]:
return address_prefix, units["chia"]
return "", units["mojo"]
def print_balance(amount: int, scale: int, address_prefix: str, *, decimal_only: bool = False) -> str:
if decimal_only: # dont use scientific notation.
final_amount = f"{amount / scale:.12f}"
else:
final_amount = f"{amount / scale}"
ret = f"{final_amount} {address_prefix} "
if scale > 1:
ret += f"({amount} mojo)"
return ret
async def print_balances(
wallet_rpc_port: Optional[int], fp: Optional[int], wallet_type: Optional[WalletType] = None
) -> None: # pragma: no cover
async with get_wallet_client(wallet_rpc_port, fp) as (wallet_client, fingerprint, config):
summaries_response = await wallet_client.get_wallets(wallet_type)
address_prefix = selected_network_address_prefix(config)
is_synced: bool = await wallet_client.get_synced()
is_syncing: bool = await wallet_client.get_sync_status()
print(f"Wallet height: {await wallet_client.get_height_info()}")
if is_syncing:
print("Sync status: Syncing...")
elif is_synced:
print("Sync status: Synced")
else:
print("Sync status: Not synced")
if not is_syncing and is_synced:
if len(summaries_response) == 0:
type_hint = " " if wallet_type is None else f" from type {wallet_type.name} "
print(f"\nNo wallets{type_hint}available for fingerprint: {fingerprint}")
else:
print(f"Balances, fingerprint: {fingerprint}")
for summary in summaries_response:
indent: str = " "
# asset_id currently contains both the asset ID and TAIL program bytes concatenated together.
# A future RPC update may split them apart, but for now we'll show the first 32 bytes (64 chars)
asset_id = summary["data"][:64]
wallet_id = summary["id"]
balances = await wallet_client.get_wallet_balance(wallet_id)
typ = WalletType(int(summary["type"]))
address_prefix, scale = wallet_coin_unit(typ, address_prefix)
total_balance: str = print_balance(balances["confirmed_wallet_balance"], scale, address_prefix)
unconfirmed_wallet_balance: str = print_balance(
balances["unconfirmed_wallet_balance"], scale, address_prefix
)
spendable_balance: str = print_balance(balances["spendable_balance"], scale, address_prefix)
my_did: Optional[str] = None
ljust = 23
if typ == WalletType.CRCAT:
ljust = 36
print()
print(f"{summary['name']}:")
print(f"{indent}{'-Total Balance:'.ljust(ljust)} {total_balance}")
if typ == WalletType.CRCAT:
print(
f"{indent}{'-Balance Pending VC Approval:'.ljust(ljust)} "
f"{print_balance(balances['pending_approval_balance'], scale, address_prefix)}"
)
print(f"{indent}{'-Pending Total Balance:'.ljust(ljust)} {unconfirmed_wallet_balance}")
print(f"{indent}{'-Spendable:'.ljust(ljust)} {spendable_balance}")
print(f"{indent}{'-Type:'.ljust(ljust)} {typ.name}")
if typ == WalletType.DECENTRALIZED_ID:
get_did_response = await wallet_client.get_did_id(wallet_id)
my_did = get_did_response["my_did"]
print(f"{indent}{'-DID ID:'.ljust(ljust)} {my_did}")
elif typ == WalletType.NFT:
get_did_response = await wallet_client.get_nft_wallet_did(wallet_id)
my_did = get_did_response["did_id"]
if my_did is not None and len(my_did) > 0:
print(f"{indent}{'-DID ID:'.ljust(ljust)} {my_did}")
elif typ == WalletType.DAO:
get_id_response = await wallet_client.dao_get_treasury_id(wallet_id)
treasury_id = get_id_response["treasury_id"][2:]
print(f"{indent}{'-Treasury ID:'.ljust(ljust)} {treasury_id}")
elif typ == WalletType.DAO_CAT:
cat_asset_id = summary["data"][32:96]
print(f"{indent}{'-Asset ID:'.ljust(ljust)} {cat_asset_id}")
elif len(asset_id) > 0:
print(f"{indent}{'-Asset ID:'.ljust(ljust)} {asset_id}")
print(f"{indent}{'-Wallet ID:'.ljust(ljust)} {wallet_id}")
print(" ")
trusted_peers: dict[str, str] = config["wallet"].get("trusted_peers", {})
await print_connections(wallet_client, trusted_peers)
async def create_did_wallet(
wallet_rpc_port: Optional[int], fp: Optional[int], d_fee: Decimal, name: Optional[str], amount: int, push: bool
) -> List[TransactionRecord]:
async with get_wallet_client(wallet_rpc_port, fp) as (wallet_client, fingerprint, config):
fee: int = int(d_fee * units["chia"])
try:
response = await wallet_client.create_new_did_wallet(amount, fee, name, push=push)
wallet_id = response["wallet_id"]
my_did = response["my_did"]
print(f"Successfully created a DID wallet with name {name} and id {wallet_id} on key {fingerprint}")
print(f"Successfully created a DID {my_did} in the newly created DID wallet")
return [] # TODO: fix this endpoint to return transactions
except Exception as e:
print(f"Failed to create DID wallet: {e}")
return []
async def did_set_wallet_name(wallet_rpc_port: Optional[int], fp: Optional[int], wallet_id: int, name: str) -> None:
async with get_wallet_client(wallet_rpc_port, fp) as (wallet_client, fingerprint, config):
try:
await wallet_client.did_set_wallet_name(wallet_id, name)
print(f"Successfully set a new name for DID wallet with id {wallet_id}: {name}")
except Exception as e:
print(f"Failed to set DID wallet name: {e}")
async def get_did(wallet_rpc_port: Optional[int], fp: Optional[int], did_wallet_id: int) -> None:
async with get_wallet_client(wallet_rpc_port, fp) as (wallet_client, fingerprint, config):
try:
response = await wallet_client.get_did_id(did_wallet_id)
my_did = response["my_did"]
coin_id = response["coin_id"]
print(f"{'DID:'.ljust(23)} {my_did}")
print(f"{'Coin ID:'.ljust(23)} {coin_id}")
except Exception as e:
print(f"Failed to get DID: {e}")
async def get_did_info(wallet_rpc_port: Optional[int], fp: Optional[int], coin_id: str, latest: bool) -> None:
async with get_wallet_client(wallet_rpc_port, fp) as (wallet_client, fingerprint, config):
did_padding_length = 23
try:
response = await wallet_client.get_did_info(coin_id, latest)
print(f"{'DID:'.ljust(did_padding_length)} {response['did_id']}")
print(f"{'Coin ID:'.ljust(did_padding_length)} {response['latest_coin']}")
print(f"{'Inner P2 Address:'.ljust(did_padding_length)} {response['p2_address']}")
print(f"{'Public Key:'.ljust(did_padding_length)} {response['public_key']}")
print(f"{'Launcher ID:'.ljust(did_padding_length)} {response['launcher_id']}")
print(f"{'DID Metadata:'.ljust(did_padding_length)} {response['metadata']}")
print(f"{'Recovery List Hash:'.ljust(did_padding_length)} {response['recovery_list_hash']}")
print(f"{'Recovery Required Verifications:'.ljust(did_padding_length)} {response['num_verification']}")
print(f"{'Last Spend Puzzle:'.ljust(did_padding_length)} {response['full_puzzle']}")
print(f"{'Last Spend Solution:'.ljust(did_padding_length)} {response['solution']}")
print(f"{'Last Spend Hints:'.ljust(did_padding_length)} {response['hints']}")
except Exception as e:
print(f"Failed to get DID details: {e}")
async def update_did_metadata(
wallet_rpc_port: Optional[int],
fp: Optional[int],
did_wallet_id: int,
metadata: str,
reuse_puzhash: bool,
push: bool = True,
) -> List[TransactionRecord]:
async with get_wallet_client(wallet_rpc_port, fp) as (wallet_client, fingerprint, config):
try:
response = await wallet_client.update_did_metadata(
did_wallet_id,
json.loads(metadata),
tx_config=CMDTXConfigLoader(
reuse_puzhash=reuse_puzhash,
).to_tx_config(units["chia"], config, fingerprint),
)