-
Notifications
You must be signed in to change notification settings - Fork 2k
/
Copy pathnft_wallet.py
1703 lines (1542 loc) · 79.3 KB
/
nft_wallet.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 dataclasses
import json
import logging
import math
import time
from typing import TYPE_CHECKING, Any, ClassVar, Dict, List, Optional, Set, Tuple, Type, TypeVar, cast
from chia_rs import AugSchemeMPL, G1Element, G2Element
from clvm.casts import int_from_bytes, int_to_bytes
from typing_extensions import Unpack
import chia.wallet.singleton
from chia.protocols.wallet_protocol import CoinState
from chia.server.ws_connection import WSChiaConnection
from chia.types.blockchain_format.coin import Coin
from chia.types.blockchain_format.program import Program
from chia.types.blockchain_format.sized_bytes import bytes32
from chia.types.coin_spend import CoinSpend, compute_additions, make_spend
from chia.types.signing_mode import CHIP_0002_SIGN_MESSAGE_PREFIX, SigningMode
from chia.types.spend_bundle import SpendBundle
from chia.util.hash import std_hash
from chia.util.ints import uint16, uint32, uint64, uint128
from chia.wallet.conditions import (
AssertCoinAnnouncement,
AssertPuzzleAnnouncement,
Condition,
CreateCoinAnnouncement,
CreatePuzzleAnnouncement,
UnknownCondition,
parse_timelock_info,
)
from chia.wallet.derivation_record import DerivationRecord
from chia.wallet.did_wallet import did_wallet_puzzles
from chia.wallet.did_wallet.did_info import DIDInfo
from chia.wallet.lineage_proof import LineageProof
from chia.wallet.nft_wallet import nft_puzzles
from chia.wallet.nft_wallet.nft_info import NFTCoinInfo, NFTWalletInfo
from chia.wallet.nft_wallet.nft_puzzles import NFT_METADATA_UPDATER, create_ownership_layer_puzzle, get_metadata_and_phs
from chia.wallet.nft_wallet.uncurry_nft import NFTCoinData, UncurriedNFT
from chia.wallet.outer_puzzles import AssetType, construct_puzzle, match_puzzle, solve_puzzle
from chia.wallet.payment import Payment
from chia.wallet.puzzle_drivers import PuzzleInfo, Solver
from chia.wallet.puzzles.p2_delegated_puzzle_or_hidden_puzzle import (
DEFAULT_HIDDEN_PUZZLE_HASH,
calculate_synthetic_secret_key,
puzzle_for_pk,
)
from chia.wallet.trading.offer import OFFER_MOD, OFFER_MOD_HASH, NotarizedPayment, Offer
from chia.wallet.transaction_record import TransactionRecord
from chia.wallet.uncurried_puzzle import uncurry_puzzle
from chia.wallet.util.compute_memos import compute_memos
from chia.wallet.util.transaction_type import TransactionType
from chia.wallet.util.tx_config import CoinSelectionConfig, TXConfig
from chia.wallet.util.wallet_types import WalletType
from chia.wallet.wallet import Wallet
from chia.wallet.wallet_action_scope import WalletActionScope
from chia.wallet.wallet_coin_record import WalletCoinRecord
from chia.wallet.wallet_info import WalletInfo
from chia.wallet.wallet_nft_store import WalletNftStore
from chia.wallet.wallet_protocol import GSTOptionalArgs, WalletProtocol
_T_NFTWallet = TypeVar("_T_NFTWallet", bound="NFTWallet")
class NFTWallet:
if TYPE_CHECKING:
_protocol_check: ClassVar[WalletProtocol[NFTCoinData]] = cast("NFTWallet", None)
wallet_state_manager: Any
log: logging.Logger
wallet_info: WalletInfo
nft_wallet_info: NFTWalletInfo
standard_wallet: Wallet
wallet_id: int
nft_store: WalletNftStore
@property
def did_id(self) -> Optional[bytes32]:
return self.nft_wallet_info.did_id
@classmethod
async def create_new_nft_wallet(
cls: Type[_T_NFTWallet],
wallet_state_manager: Any,
wallet: Wallet,
did_id: Optional[bytes32] = None,
name: Optional[str] = None,
) -> _T_NFTWallet:
"""
This must be called under the wallet state manager lock
"""
self = cls()
self.standard_wallet = wallet
if name is None:
name = "NFT Wallet"
self.log = logging.getLogger(name if name else __name__)
self.wallet_state_manager = wallet_state_manager
self.nft_wallet_info = NFTWalletInfo(did_id)
info_as_string = json.dumps(self.nft_wallet_info.to_json_dict())
self.wallet_info = await wallet_state_manager.user_store.create_wallet(
name, uint32(WalletType.NFT.value), info_as_string
)
self.wallet_id = self.wallet_info.id
self.nft_store = wallet_state_manager.nft_store
self.log.debug("NFT wallet id: %r and standard wallet id: %r", self.wallet_id, self.standard_wallet.wallet_id)
await self.wallet_state_manager.add_new_wallet(self)
self.log.debug("Generated a new NFT wallet: %s", self.__dict__)
return self
@classmethod
async def create(
cls: Type[_T_NFTWallet],
wallet_state_manager: Any,
wallet: Wallet,
wallet_info: WalletInfo,
name: Optional[str] = None,
) -> _T_NFTWallet:
self = cls()
self.log = logging.getLogger(name if name else __name__)
self.wallet_state_manager = wallet_state_manager
self.wallet_info = wallet_info
self.wallet_id = wallet_info.id
self.standard_wallet = wallet
self.wallet_info = wallet_info
self.nft_store = wallet_state_manager.nft_store
self.nft_wallet_info = NFTWalletInfo.from_json_dict(json.loads(wallet_info.data))
return self
@classmethod
def type(cls) -> WalletType:
return WalletType.NFT
def id(self) -> uint32:
return self.wallet_info.id
def get_did(self) -> Optional[bytes32]:
return self.did_id
async def get_confirmed_balance(self, record_list: Optional[Set[WalletCoinRecord]] = None) -> uint128:
"""The NFT wallet doesn't really have a balance."""
return uint128(0)
async def get_unconfirmed_balance(self, record_list: Optional[Set[WalletCoinRecord]] = None) -> uint128:
"""The NFT wallet doesn't really have a balance."""
return uint128(0)
async def get_spendable_balance(self, unspent_records: Optional[Set[WalletCoinRecord]] = None) -> uint128:
"""The NFT wallet doesn't really have a balance."""
return uint128(0)
async def get_pending_change_balance(self) -> uint64:
return uint64(0)
async def get_max_send_amount(self, records: Optional[Set[WalletCoinRecord]] = None) -> uint128:
"""This is the confirmed balance, which we set to 0 as the NFT wallet doesn't have one."""
return uint128(0)
async def get_nft_coin_by_id(self, nft_coin_id: bytes32) -> NFTCoinInfo:
nft_coin = await self.nft_store.get_nft_by_coin_id(nft_coin_id)
if nft_coin is None:
raise KeyError(f"Couldn't find coin with id: {nft_coin_id}")
return nft_coin
async def coin_added(
self, coin: Coin, height: uint32, peer: WSChiaConnection, parent_coin_data: Optional[NFTCoinData]
) -> None:
"""Notification from wallet state manager that wallet has been received."""
self.log.info(f"NFT wallet %s has been notified that {coin} was added", self.get_name())
if await self.nft_store.exists(coin.name()):
# already added
return
assert isinstance(parent_coin_data, NFTCoinData), f"Invalid NFT coin data: {parent_coin_data}"
await self.puzzle_solution_received(coin, parent_coin_data, peer)
async def puzzle_solution_received(self, coin: Coin, data: NFTCoinData, peer: WSChiaConnection) -> None:
self.log.debug("Puzzle solution received to wallet: %s", self.wallet_info)
# At this point, the puzzle must be a NFT puzzle.
# This method will be called only when the wallet state manager uncurried this coin as a NFT puzzle.
uncurried_nft: UncurriedNFT = data.uncurried_nft
self.log.debug(
"found the info for NFT coin %s %s %s",
coin.name().hex(),
uncurried_nft.inner_puzzle,
uncurried_nft.singleton_struct,
)
singleton_id = uncurried_nft.singleton_launcher_id
parent_inner_puzhash = uncurried_nft.nft_state_layer.get_tree_hash()
metadata, p2_puzzle_hash = get_metadata_and_phs(uncurried_nft, data.parent_coin_spend.solution)
self.log.debug("Got back puzhash from solution: %s", p2_puzzle_hash)
self.log.debug("Got back updated metadata: %s", metadata)
derivation_record: Optional[DerivationRecord] = (
await self.wallet_state_manager.puzzle_store.get_derivation_record_for_puzzle_hash(p2_puzzle_hash)
)
self.log.debug("Record for %s is: %s", p2_puzzle_hash, derivation_record)
if derivation_record is None:
self.log.debug("Not our NFT, pointing to %s, skipping", p2_puzzle_hash)
return
p2_puzzle = puzzle_for_pk(derivation_record.pubkey)
launcher_coin_states: List[CoinState] = await self.wallet_state_manager.wallet_node.get_coin_state(
[singleton_id], peer=peer
)
assert (
launcher_coin_states is not None
and len(launcher_coin_states) == 1
and launcher_coin_states[0].spent_height is not None
)
mint_height: uint32 = uint32(launcher_coin_states[0].spent_height)
minter_did = None
if uncurried_nft.supports_did:
inner_puzzle = nft_puzzles.recurry_nft_puzzle(
uncurried_nft, data.parent_coin_spend.solution.to_program(), p2_puzzle
)
minter_did = await self.wallet_state_manager.get_minter_did(launcher_coin_states[0].coin, peer)
else:
inner_puzzle = p2_puzzle
child_puzzle: Program = nft_puzzles.create_full_puzzle(
singleton_id,
Program.to(metadata),
bytes32(uncurried_nft.metadata_updater_hash.as_atom()),
inner_puzzle,
)
self.log.debug(
"Created NFT full puzzle with inner: %s",
nft_puzzles.create_full_puzzle_with_nft_puzzle(singleton_id, uncurried_nft.inner_puzzle),
)
child_puzzle_hash = child_puzzle.get_tree_hash()
for new_coin in compute_additions(data.parent_coin_spend):
self.log.debug(
"Comparing addition: %s with %s, amount: %s ",
new_coin.puzzle_hash,
child_puzzle_hash,
new_coin.amount,
)
if new_coin.puzzle_hash == child_puzzle_hash:
child_coin = new_coin
break
else:
raise ValueError("Couldn't generate child puzzle for NFT")
self.log.info("Adding a new NFT to wallet: %s", child_coin)
# all is well, lets add NFT to our local db
parent_coin = data.parent_coin_state.coin
confirmed_height = (
None if data.parent_coin_state.spent_height is None else uint32(data.parent_coin_state.spent_height)
)
if confirmed_height is None:
raise ValueError("Error finding parent")
await self.add_coin(
child_coin,
singleton_id,
child_puzzle,
LineageProof(parent_coin.parent_coin_info, parent_inner_puzhash, uint64(parent_coin.amount)),
mint_height,
minter_did,
confirmed_height,
)
async def add_coin(
self,
coin: Coin,
nft_id: bytes32,
puzzle: Program,
lineage_proof: LineageProof,
mint_height: uint32,
minter_did: Optional[bytes32],
confirmed_height: uint32,
) -> None:
new_nft = NFTCoinInfo(nft_id, coin, lineage_proof, puzzle, mint_height, minter_did, confirmed_height)
await self.wallet_state_manager.nft_store.save_nft(self.id(), self.get_did(), new_nft)
await self.wallet_state_manager.add_interested_coin_ids([coin.name()])
self.wallet_state_manager.state_changed("nft_coin_added", self.wallet_info.id)
async def remove_coin(self, coin: Coin, height: uint32) -> None:
nft_coin_info = await self.nft_store.get_nft_by_coin_id(coin.name())
if nft_coin_info:
await self.nft_store.delete_nft_by_coin_id(coin.name(), height)
self.wallet_state_manager.state_changed("nft_coin_removed", self.wallet_info.id)
num = await self.get_nft_count()
if num == 0 and self.did_id is not None:
# Check if the wallet owns the DID
for did_wallet in await self.wallet_state_manager.get_all_wallet_info_entries(
wallet_type=WalletType.DECENTRALIZED_ID
):
did_wallet_info: DIDInfo = DIDInfo.from_json_dict(json.loads(did_wallet.data))
assert did_wallet_info.origin_coin is not None
if did_wallet_info.origin_coin.name() == self.did_id:
return
self.log.info(f"No NFT, deleting wallet {self.wallet_info.name} ...")
await self.wallet_state_manager.user_store.delete_wallet(self.wallet_info.id)
self.wallet_state_manager.wallets.pop(self.wallet_info.id)
else:
self.log.info("Tried removing NFT coin that doesn't exist: %s", coin.name())
async def get_did_approval_info(
self,
nft_ids: List[bytes32],
tx_config: TXConfig,
action_scope: WalletActionScope,
did_id: Optional[bytes32] = None,
) -> bytes32:
"""Get DID spend with announcement created we need to transfer NFT with did with current inner hash of DID
We also store `did_id` and then iterate to find the did wallet as we'd otherwise have to subscribe to
any changes to DID wallet and storing wallet_id is not guaranteed to be consistent on wallet crash/reset.
"""
if did_id is None:
did_id = self.did_id
did_inner_hash: bytes32
for _, wallet in self.wallet_state_manager.wallets.items():
self.log.debug("Checking wallet type %s", wallet.type())
if wallet.type() == WalletType.DECENTRALIZED_ID:
self.log.debug("Found a DID wallet, checking did: %r == %r", wallet.get_my_DID(), did_id)
if bytes32.fromhex(wallet.get_my_DID()) == did_id:
self.log.debug("Creating announcement from DID for nft_ids: %s", nft_ids)
await wallet.create_message_spend(
tx_config, action_scope, extra_conditions=(CreatePuzzleAnnouncement(id) for id in nft_ids)
)
did_inner_hash = wallet.did_info.current_inner.get_tree_hash()
break
else:
raise ValueError(f"Missing DID Wallet for did_id: {did_id}")
return did_inner_hash
async def generate_new_nft(
self,
metadata: Program,
tx_config: TXConfig,
action_scope: WalletActionScope,
target_puzzle_hash: Optional[bytes32] = None,
royalty_puzzle_hash: Optional[bytes32] = None,
percentage: uint16 = uint16(0),
did_id: Optional[bytes] = None,
fee: uint64 = uint64(0),
extra_conditions: Tuple[Condition, ...] = tuple(),
) -> bytes32:
"""
This must be called under the wallet state manager lock
"""
if self.did_id is not None and did_id is None:
# For a DID enabled NFT wallet it cannot mint NFT0. Mint NFT1 instead.
did_id = self.did_id
amount = uint64(1)
# ensure percentage is uint16
try:
percentage = uint16(percentage)
except ValueError:
raise ValueError("Percentage must be lower than 655%")
coins = await self.standard_wallet.select_coins(uint64(amount + fee), tx_config.coin_selection_config)
if coins is None:
return None
origin = coins.copy().pop()
genesis_launcher_puz = nft_puzzles.LAUNCHER_PUZZLE
# nft_id == singleton_id == launcher_id == launcher_coin.name()
launcher_coin = Coin(origin.name(), nft_puzzles.LAUNCHER_PUZZLE_HASH, uint64(amount))
self.log.debug("Generating NFT with launcher coin %s and metadata: %s", launcher_coin, metadata)
p2_inner_puzzle = await self.standard_wallet.get_puzzle(new=not tx_config.reuse_puzhash)
if not target_puzzle_hash:
target_puzzle_hash = p2_inner_puzzle.get_tree_hash()
self.log.debug("Attempt to generate a new NFT to %s", target_puzzle_hash.hex())
if did_id is not None:
self.log.debug("Creating provenant NFT")
# eve coin DID can be set to whatever so we keep it empty
# WARNING: wallets should always ignore DID value for eve coins as they can be set
# to any DID without approval
inner_puzzle = create_ownership_layer_puzzle(
launcher_coin.name(), b"", p2_inner_puzzle, percentage, royalty_puzzle_hash=royalty_puzzle_hash
)
self.log.debug("Got back ownership inner puzzle: %s", inner_puzzle)
else:
self.log.debug("Creating standard NFT")
inner_puzzle = p2_inner_puzzle
# singleton eve puzzle
eve_fullpuz = nft_puzzles.create_full_puzzle(
launcher_coin.name(), metadata, NFT_METADATA_UPDATER.get_tree_hash(), inner_puzzle
)
eve_fullpuz_hash = eve_fullpuz.get_tree_hash()
# launcher announcement
announcement_message = Program.to([eve_fullpuz_hash, amount, []]).get_tree_hash()
self.log.debug(
"Creating transaction for launcher: %s and other coins: %s (%s)", origin, coins, announcement_message
)
# store the launcher transaction in the wallet state
await self.standard_wallet.generate_signed_transaction(
uint64(amount),
nft_puzzles.LAUNCHER_PUZZLE_HASH,
tx_config,
action_scope,
fee,
coins,
None,
origin_id=origin.name(),
extra_conditions=(
*extra_conditions,
AssertCoinAnnouncement(asserted_id=launcher_coin.name(), asserted_msg=announcement_message),
),
)
genesis_launcher_solution = Program.to([eve_fullpuz_hash, amount, []])
# launcher spend to generate the singleton
launcher_cs = make_spend(launcher_coin, genesis_launcher_puz, genesis_launcher_solution)
launcher_sb = SpendBundle([launcher_cs], AugSchemeMPL.aggregate([]))
eve_coin = Coin(launcher_coin.name(), eve_fullpuz_hash, uint64(amount))
async with action_scope.use() as interface:
interface.side_effects.extra_spends.append(launcher_sb)
# Create inner solution for eve spend
did_inner_hash = b""
if did_id is not None:
if did_id != b"":
did_inner_hash = await self.get_did_approval_info([launcher_coin.name()], tx_config, action_scope)
nft_coin = NFTCoinInfo(
nft_id=launcher_coin.name(),
coin=eve_coin,
lineage_proof=LineageProof(parent_name=launcher_coin.parent_coin_info, amount=uint64(launcher_coin.amount)),
full_puzzle=eve_fullpuz,
mint_height=uint32(0),
minter_did=bytes32(did_id) if did_id is not None and did_id != b"" else None,
)
# Don't set fee, it is covered in the tx_record
await self.generate_signed_transaction(
[uint64(eve_coin.amount)],
[target_puzzle_hash],
tx_config,
action_scope,
nft_coin=nft_coin,
new_owner=did_id,
new_did_inner_hash=did_inner_hash,
memos=[[target_puzzle_hash]],
)
return launcher_coin.name()
async def update_metadata(
self,
nft_coin_info: NFTCoinInfo,
key: str,
uri: str,
tx_config: TXConfig,
action_scope: WalletActionScope,
fee: uint64 = uint64(0),
extra_conditions: Tuple[Condition, ...] = tuple(),
) -> None:
uncurried_nft = UncurriedNFT.uncurry(*nft_coin_info.full_puzzle.uncurry())
assert uncurried_nft is not None
puzzle_hash = uncurried_nft.p2_puzzle.get_tree_hash()
self.log.info(
"Attempting to add urls to NFT coin %s in the metadata: %s",
nft_coin_info.coin.name(),
uncurried_nft.metadata,
)
await self.generate_signed_transaction(
[uint64(nft_coin_info.coin.amount)],
[puzzle_hash],
tx_config,
action_scope,
fee,
{nft_coin_info.coin},
metadata_update=(key, uri),
extra_conditions=extra_conditions,
)
await self.update_coin_status(nft_coin_info.coin.name(), True)
self.wallet_state_manager.state_changed("nft_coin_updated", self.wallet_info.id)
async def get_current_nfts(self, start_index: int = 0, count: int = 50) -> List[NFTCoinInfo]:
return await self.nft_store.get_nft_list(wallet_id=self.id(), start_index=start_index, count=count)
async def get_nft_count(self) -> int:
return await self.nft_store.count(wallet_id=self.id())
async def is_empty(self) -> bool:
return await self.nft_store.is_empty(wallet_id=self.id())
async def update_coin_status(self, coin_id: bytes32, pending_transaction: bool) -> None:
await self.nft_store.update_pending_transaction(coin_id, pending_transaction)
async def save_info(self, nft_info: NFTWalletInfo) -> None:
self.nft_wallet_info = nft_info
current_info = self.wallet_info
data_str = json.dumps(nft_info.to_json_dict())
wallet_info = WalletInfo(current_info.id, current_info.name, current_info.type, data_str)
self.wallet_info = wallet_info
await self.wallet_state_manager.user_store.update_wallet(wallet_info)
async def convert_puzzle_hash(self, puzhash: bytes32) -> bytes32:
return puzhash
async def get_nft(self, launcher_id: bytes32) -> Optional[NFTCoinInfo]:
return await self.nft_store.get_nft_by_id(launcher_id)
async def get_puzzle_info(self, nft_id: bytes32) -> PuzzleInfo:
nft_coin: Optional[NFTCoinInfo] = await self.get_nft(nft_id)
if nft_coin is None:
raise ValueError("An asset ID was specified that this wallet doesn't track")
puzzle_info: Optional[PuzzleInfo] = match_puzzle(uncurry_puzzle(nft_coin.full_puzzle))
if puzzle_info is None:
raise ValueError("Internal Error: NFT wallet is tracking a non NFT coin")
else:
return puzzle_info
async def sign_message(self, message: str, nft: NFTCoinInfo, mode: SigningMode) -> Tuple[G1Element, G2Element]:
uncurried_nft = UncurriedNFT.uncurry(*nft.full_puzzle.uncurry())
if uncurried_nft is not None:
p2_puzzle = uncurried_nft.p2_puzzle
puzzle_hash = p2_puzzle.get_tree_hash()
private = await self.wallet_state_manager.get_private_key(puzzle_hash)
synthetic_secret_key = calculate_synthetic_secret_key(private, DEFAULT_HIDDEN_PUZZLE_HASH)
synthetic_pk = synthetic_secret_key.get_g1()
if mode == SigningMode.CHIP_0002_HEX_INPUT:
hex_message: bytes = Program.to((CHIP_0002_SIGN_MESSAGE_PREFIX, bytes.fromhex(message))).get_tree_hash()
elif mode == SigningMode.BLS_MESSAGE_AUGMENTATION_UTF8_INPUT:
hex_message = bytes(message, "utf-8")
elif mode == SigningMode.BLS_MESSAGE_AUGMENTATION_HEX_INPUT:
hex_message = bytes.fromhex(message)
else:
hex_message = Program.to((CHIP_0002_SIGN_MESSAGE_PREFIX, message)).get_tree_hash()
return synthetic_pk, AugSchemeMPL.sign(synthetic_secret_key, hex_message)
else:
raise ValueError("Invalid NFT puzzle.")
async def get_coins_to_offer(
self,
nft_id: bytes32,
*args: Any,
**kwargs: Any,
) -> Set[Coin]:
nft_coin: Optional[NFTCoinInfo] = await self.get_nft(nft_id)
if nft_coin is None:
raise ValueError("An asset ID was specified that this wallet doesn't track")
return {nft_coin.coin}
async def match_puzzle_info(self, puzzle_driver: PuzzleInfo) -> bool:
return (
AssetType(puzzle_driver.type()) == AssetType.SINGLETON
and puzzle_driver.also() is not None
and AssetType(puzzle_driver.also().type()) == AssetType.METADATA # type: ignore
and puzzle_driver.also().also() is None # type: ignore
and await self.get_nft(puzzle_driver["launcher_id"]) is not None
)
@classmethod
async def create_from_puzzle_info(
cls: Any,
wallet_state_manager: Any,
wallet: Wallet,
puzzle_driver: PuzzleInfo,
name: Optional[str] = None,
) -> Any:
# Off the bat we don't support multiple profile but when we do this will have to change
for wallet in wallet_state_manager.wallets.values():
if wallet.type() == WalletType.NFT.value:
return wallet
# TODO: These are not the arguments to this function yet but they will be
return await cls.create_new_nft_wallet(
wallet_state_manager,
wallet,
None,
name,
)
async def generate_signed_transaction(
self,
amounts: List[uint64],
puzzle_hashes: List[bytes32],
tx_config: TXConfig,
action_scope: WalletActionScope,
fee: uint64 = uint64(0),
coins: Optional[Set[Coin]] = None,
memos: Optional[List[List[bytes]]] = None,
extra_conditions: Tuple[Condition, ...] = tuple(),
**kwargs: Unpack[GSTOptionalArgs],
) -> None:
nft_coin: Optional[NFTCoinInfo] = kwargs.get("nft_coin", None)
new_owner: Optional[bytes] = kwargs.get("new_owner", None)
new_did_inner_hash: Optional[bytes] = kwargs.get("new_did_inner_hash", None)
trade_prices_list: Optional[Program] = kwargs.get("trade_prices_list", None)
additional_bundles: List[SpendBundle] = kwargs.get("additional_bundles", [])
metadata_update: Optional[Tuple[str, str]] = kwargs.get("metadata_update", None)
if memos is None:
memos = [[] for _ in range(len(puzzle_hashes))]
if not (len(memos) == len(puzzle_hashes) == len(amounts)):
raise ValueError("Memos, puzzle_hashes, and amounts must have the same length")
payments = []
for amount, puzhash, memo_list in zip(amounts, puzzle_hashes, memos):
memos_with_hint: List[bytes] = [puzhash]
memos_with_hint.extend(memo_list)
payments.append(Payment(puzhash, amount, memos_with_hint))
payment_sum = sum(p.amount for p in payments)
unsigned_spend_bundle = await self.generate_unsigned_spendbundle(
payments,
tx_config,
action_scope,
fee,
coins=coins,
nft_coin=nft_coin,
new_owner=new_owner,
new_did_inner_hash=new_did_inner_hash,
trade_prices_list=trade_prices_list,
metadata_update=metadata_update,
extra_conditions=extra_conditions,
)
spend_bundle = SpendBundle.aggregate([unsigned_spend_bundle] + additional_bundles)
async with action_scope.use() as interface:
other_tx_removals: Set[Coin] = {
removal for tx in interface.side_effects.transactions for removal in tx.removals
}
other_tx_additions: Set[Coin] = {
addition for tx in interface.side_effects.transactions for addition in tx.additions
}
tx = TransactionRecord(
confirmed_at_height=uint32(0),
created_at_time=uint64(int(time.time())),
to_puzzle_hash=puzzle_hashes[0],
amount=uint64(payment_sum),
fee_amount=fee,
confirmed=False,
sent=uint32(0),
spend_bundle=spend_bundle,
additions=list(set(spend_bundle.additions()) - other_tx_additions),
removals=list(set(spend_bundle.removals()) - other_tx_removals),
wallet_id=self.id(),
sent_to=[],
trade_id=None,
type=uint32(TransactionType.OUTGOING_TX.value),
name=spend_bundle.name(),
memos=list(compute_memos(spend_bundle).items()),
valid_times=parse_timelock_info(extra_conditions),
)
interface.side_effects.transactions.append(tx)
async def generate_unsigned_spendbundle(
self,
payments: List[Payment],
tx_config: TXConfig,
action_scope: WalletActionScope,
fee: uint64 = uint64(0),
coins: Optional[Set[Coin]] = None,
new_owner: Optional[bytes] = None,
new_did_inner_hash: Optional[bytes] = None,
trade_prices_list: Optional[Program] = None,
metadata_update: Optional[Tuple[str, str]] = None,
nft_coin: Optional[NFTCoinInfo] = None,
extra_conditions: Tuple[Condition, ...] = tuple(),
) -> SpendBundle:
if nft_coin is None:
if coins is None or not len(coins) == 1:
# Make sure the user is specifying which specific NFT coin to use
raise ValueError("NFT spends require a single selected coin")
elif len(payments) > 1:
raise ValueError("NFTs can only be sent to one party")
nft_coin = await self.nft_store.get_nft_by_coin_id(coins.pop().name())
assert nft_coin
coin_name = nft_coin.coin.name()
if fee > 0:
await self.standard_wallet.create_tandem_xch_tx(
fee,
tx_config,
action_scope,
extra_conditions=(AssertCoinAnnouncement(asserted_id=coin_name, asserted_msg=coin_name),),
)
unft = UncurriedNFT.uncurry(*nft_coin.full_puzzle.uncurry())
assert unft is not None
if unft.supports_did:
if new_owner is None:
# If no new owner was specified and we're sending this to ourselves, let's not reset the DID
derivation_record: Optional[DerivationRecord] = (
await self.wallet_state_manager.puzzle_store.get_derivation_record_for_puzzle_hash(
payments[0].puzzle_hash
)
)
if derivation_record is not None:
new_owner = unft.owner_did
extra_conditions = (
*extra_conditions,
UnknownCondition(
opcode=Program.to(-10),
args=[
Program.to(new_owner),
Program.to(trade_prices_list),
Program.to(new_did_inner_hash),
],
),
)
if metadata_update is not None:
extra_conditions = (
*extra_conditions,
UnknownCondition(
opcode=Program.to(-24),
args=[
NFT_METADATA_UPDATER,
Program.to(metadata_update),
],
),
)
innersol: Program = self.standard_wallet.make_solution(
primaries=payments,
conditions=(*extra_conditions, CreateCoinAnnouncement(coin_name)) if fee > 0 else extra_conditions,
)
if unft.supports_did:
innersol = Program.to([innersol])
nft_layer_solution = Program.to([innersol])
assert isinstance(nft_coin.lineage_proof, LineageProof)
singleton_solution = Program.to([nft_coin.lineage_proof.to_program(), nft_coin.coin.amount, nft_layer_solution])
coin_spend = make_spend(nft_coin.coin, nft_coin.full_puzzle, singleton_solution)
nft_spend_bundle = SpendBundle([coin_spend], G2Element())
return nft_spend_bundle
@staticmethod
def royalty_calculation(
royalty_assets_dict: Dict[Any, Tuple[Any, uint16]],
fungible_asset_dict: Dict[Any, uint64],
) -> Dict[Any, List[Dict[str, Any]]]:
summary_dict: Dict[Any, List[Dict[str, Any]]] = {}
for id, royalty_info in royalty_assets_dict.items():
address, percentage = royalty_info
summary_dict[id] = []
for name, amount in fungible_asset_dict.items():
summary_dict[id].append(
{
"asset": name,
"address": address,
"amount": math.floor(math.floor(abs(amount) / len(royalty_assets_dict)) * (percentage / 10000)),
}
)
return summary_dict
@staticmethod
async def make_nft1_offer(
wallet_state_manager: Any,
offer_dict: Dict[Optional[bytes32], int],
driver_dict: Dict[bytes32, PuzzleInfo],
tx_config: TXConfig,
action_scope: WalletActionScope,
fee: uint64,
extra_conditions: Tuple[Condition, ...],
) -> Offer:
# First, let's take note of all the royalty enabled NFTs
royalty_nft_asset_dict: Dict[bytes32, int] = {}
for asset, amount in offer_dict.items():
if asset is not None and driver_dict[asset].check_type( # check if asset is an Royalty Enabled NFT
[
AssetType.SINGLETON.value,
AssetType.METADATA.value,
AssetType.OWNERSHIP.value,
]
):
driver_dict[asset].info["also"]["also"]["owner"] = "()"
royalty_nft_asset_dict[asset] = amount
# Then, all of the things that trigger royalties
fungible_asset_dict: Dict[Optional[bytes32], int] = {}
for asset, amount in offer_dict.items():
if asset is None or driver_dict[asset].type() != AssetType.SINGLETON.value:
fungible_asset_dict[asset] = amount
# Let's gather some information about the royalties
offer_side_royalty_split: int = 0
request_side_royalty_split: int = 0
for asset, amount in royalty_nft_asset_dict.items(): # requested non fungible items
if amount > 0:
request_side_royalty_split += 1
elif amount < 0:
offer_side_royalty_split += 1
trade_prices: List[Tuple[uint64, bytes32]] = []
for asset, amount in fungible_asset_dict.items(): # requested fungible items
if amount > 0 and offer_side_royalty_split > 0:
settlement_ph: bytes32 = (
OFFER_MOD_HASH if asset is None else construct_puzzle(driver_dict[asset], OFFER_MOD).get_tree_hash()
)
trade_prices.append((uint64(math.floor(amount / offer_side_royalty_split)), settlement_ph))
required_royalty_info: List[Tuple[bytes32, bytes32, uint16]] = [] # [(launcher_id, address, percentage)]
offered_royalty_percentages: Dict[bytes32, uint16] = {}
for asset, amount in royalty_nft_asset_dict.items(): # royalty enabled NFTs
transfer_info = driver_dict[asset].also().also() # type: ignore
assert isinstance(transfer_info, PuzzleInfo)
royalty_percentage_raw = transfer_info["transfer_program"]["royalty_percentage"]
assert royalty_percentage_raw is not None
# clvm encodes large ints as bytes
if isinstance(royalty_percentage_raw, bytes):
royalty_percentage = int_from_bytes(royalty_percentage_raw)
else:
royalty_percentage = int(royalty_percentage_raw)
if amount > 0:
required_royalty_info.append(
(
asset,
bytes32(transfer_info["transfer_program"]["royalty_address"]),
uint16(royalty_percentage),
)
)
else:
offered_royalty_percentages[asset] = uint16(royalty_percentage)
royalty_payments: Dict[Optional[bytes32], List[Tuple[bytes32, Payment]]] = {}
for asset, amount in fungible_asset_dict.items(): # offered fungible items
if amount < 0 and request_side_royalty_split > 0:
payment_list: List[Tuple[bytes32, Payment]] = []
for launcher_id, address, percentage in required_royalty_info:
extra_royalty_amount = uint64(
math.floor(math.floor(abs(amount) / request_side_royalty_split) * (percentage / 10000))
)
if extra_royalty_amount == abs(amount):
raise ValueError("Amount offered and amount paid in royalties are equal")
payment_list.append((launcher_id, Payment(address, extra_royalty_amount, [address])))
royalty_payments[asset] = payment_list
# Generate the requested_payments to be notarized
p2_ph = await wallet_state_manager.main_wallet.get_puzzle_hash(new=not tx_config.reuse_puzhash)
requested_payments: Dict[Optional[bytes32], List[Payment]] = {}
for asset, amount in offer_dict.items():
if amount > 0:
requested_payments[asset] = [Payment(p2_ph, uint64(amount), [p2_ph] if asset is not None else [])]
# Find all the coins we're offering
offered_coins_by_asset: Dict[Optional[bytes32], Set[Coin]] = {}
all_offered_coins: Set[Coin] = set()
for asset, amount in offer_dict.items():
if amount < 0:
if asset is None:
wallet = wallet_state_manager.main_wallet
else:
wallet = await wallet_state_manager.get_wallet_for_asset_id(asset.hex())
if asset in royalty_payments:
royalty_amount: int = sum(p.amount for _, p in royalty_payments[asset])
else:
royalty_amount = 0
if asset is None:
coin_amount_needed: int = abs(amount) + royalty_amount + fee
else:
coin_amount_needed = abs(amount) + royalty_amount
offered_coins: Set[Coin] = await wallet.get_coins_to_offer(
asset, coin_amount_needed, tx_config.coin_selection_config
)
if len(offered_coins) == 0:
raise ValueError(f"Did not have asset ID {asset.hex() if asset is not None else 'XCH'} to offer")
offered_coins_by_asset[asset] = offered_coins
all_offered_coins.update(offered_coins)
# Notarize the payments and get the announcements for the bundle
notarized_payments: Dict[Optional[bytes32], List[NotarizedPayment]] = Offer.notarize_payments(
requested_payments, list(all_offered_coins)
)
announcements_to_assert: List[AssertPuzzleAnnouncement] = Offer.calculate_announcements(
notarized_payments, driver_dict
)
for asset, payments in royalty_payments.items():
if asset is None: # xch offer
offer_puzzle = OFFER_MOD
royalty_ph = OFFER_MOD_HASH
else:
offer_puzzle = construct_puzzle(driver_dict[asset], OFFER_MOD)
royalty_ph = offer_puzzle.get_tree_hash()
announcements_to_assert.extend(
[
AssertPuzzleAnnouncement(
asserted_ph=royalty_ph,
asserted_msg=Program.to((launcher_id, [p.as_condition_args()])).get_tree_hash(),
)
for launcher_id, p in payments
if p.amount > 0
]
)
# Create all of the transactions
all_transactions: List[TransactionRecord] = []
additional_bundles: List[SpendBundle] = []
# standard pays the fee if possible
fee_left_to_pay: uint64 = uint64(0) if None in offer_dict and offer_dict[None] < 0 else fee
for asset, amount in offer_dict.items():
if amount < 0:
if asset is None:
wallet = wallet_state_manager.main_wallet
else:
wallet = await wallet_state_manager.get_wallet_for_asset_id(asset.hex())
# First, sending all the coins to the OFFER_MOD
async with wallet_state_manager.new_action_scope(push=False) as inner_action_scope:
if wallet.type() == WalletType.STANDARD_WALLET:
payments = royalty_payments[asset] if asset in royalty_payments else []
payment_sum = sum(p.amount for _, p in payments)
await wallet.generate_signed_transaction(
abs(amount),
OFFER_MOD_HASH,
tx_config,
inner_action_scope,
primaries=[Payment(OFFER_MOD_HASH, uint64(payment_sum))] if payment_sum > 0 else [],
fee=fee,
coins=offered_coins_by_asset[asset],
extra_conditions=(*extra_conditions, *announcements_to_assert),
)
elif asset not in fungible_asset_dict:
assert asset is not None
await wallet.generate_signed_transaction(
[abs(amount)],
[OFFER_MOD_HASH],
tx_config,
inner_action_scope,
fee=fee_left_to_pay,
coins=offered_coins_by_asset[asset],
trade_prices_list=[
list(price)
for price in trade_prices
if math.floor(price[0] * (offered_royalty_percentages[asset] / 10000)) != 0
],
extra_conditions=(*extra_conditions, *announcements_to_assert),
)
else:
payments = royalty_payments[asset] if asset in royalty_payments else []
await wallet.generate_signed_transaction(
[abs(amount), sum(p.amount for _, p in payments)],
[OFFER_MOD_HASH, OFFER_MOD_HASH],
tx_config,
inner_action_scope,
fee=fee_left_to_pay,
coins=offered_coins_by_asset[asset],
extra_conditions=(*extra_conditions, *announcements_to_assert),
)
all_transactions.extend(inner_action_scope.side_effects.transactions)
fee_left_to_pay = uint64(0)
extra_conditions = tuple()
# Then, adding in the spends for the royalty offer mod
if asset in fungible_asset_dict:
# Create a coin_spend for the royalty payout from OFFER MOD
# Skip it if we're paying 0 royalties
payments = royalty_payments[asset] if asset in royalty_payments else []
if sum(p.amount for _, p in payments) == 0:
continue
# We cannot create coins with the same puzzle hash and amount
# So if there's multiple NFTs with the same royalty puzhash/percentage, we must create multiple
# generations of offer coins
royalty_coin: Optional[Coin] = None
parent_spend: Optional[CoinSpend] = None
while True:
duplicate_payments: List[Tuple[bytes32, Payment]] = []
deduped_payment_list: List[Tuple[bytes32, Payment]] = []
for launcher_id, payment in payments:
if payment in [p for _, p in deduped_payment_list]:
duplicate_payments.append((launcher_id, payment))
else:
deduped_payment_list.append((launcher_id, payment))
# ((nft_launcher_id . ((ROYALTY_ADDRESS, royalty_amount, memos) ...)))
inner_royalty_sol = Program.to(
[
(launcher_id, [payment.as_condition_args()])
for launcher_id, payment in deduped_payment_list
]
)
if duplicate_payments != []:
inner_royalty_sol = Program.to(
(
None,
[
Payment(
OFFER_MOD_HASH,
uint64(sum(p.amount for _, p in duplicate_payments)),
).as_condition_args()
],
)
).cons(inner_royalty_sol)
if asset is None: # xch offer
offer_puzzle = OFFER_MOD
royalty_ph = OFFER_MOD_HASH
else:
offer_puzzle = construct_puzzle(driver_dict[asset], OFFER_MOD)
royalty_ph = offer_puzzle.get_tree_hash()
if royalty_coin is None:
for tx in inner_action_scope.side_effects.transactions: