-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathIPAsset.py
More file actions
2301 lines (2114 loc) · 104 KB
/
IPAsset.py
File metadata and controls
2301 lines (2114 loc) · 104 KB
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
"""Module for handling IP Account operations and transactions."""
from dataclasses import asdict, is_dataclass, replace
from typing import cast
from ens.ens import Address, HexStr
from typing_extensions import deprecated
from web3 import Web3
from story_protocol_python_sdk.abi.AccessController.AccessController_client import (
AccessControllerClient,
)
from story_protocol_python_sdk.abi.CoreMetadataModule.CoreMetadataModule_client import (
CoreMetadataModuleClient,
)
from story_protocol_python_sdk.abi.DerivativeWorkflows.DerivativeWorkflows_client import (
DerivativeWorkflowsClient,
)
from story_protocol_python_sdk.abi.IPAccountImpl.IPAccountImpl_client import (
IPAccountImplClient,
)
from story_protocol_python_sdk.abi.IPAssetRegistry.IPAssetRegistry_client import (
IPAssetRegistryClient,
)
from story_protocol_python_sdk.abi.IpRoyaltyVaultImpl.IpRoyaltyVaultImpl_client import (
IpRoyaltyVaultImplClient,
)
from story_protocol_python_sdk.abi.LicenseAttachmentWorkflows.LicenseAttachmentWorkflows_client import (
LicenseAttachmentWorkflowsClient,
)
from story_protocol_python_sdk.abi.LicenseRegistry.LicenseRegistry_client import (
LicenseRegistryClient,
)
from story_protocol_python_sdk.abi.LicenseToken.LicenseToken_client import (
LicenseTokenClient,
)
from story_protocol_python_sdk.abi.LicensingModule.LicensingModule_client import (
LicensingModuleClient,
)
from story_protocol_python_sdk.abi.ModuleRegistry.ModuleRegistry_client import (
ModuleRegistryClient,
)
from story_protocol_python_sdk.abi.Multicall3.Multicall3_client import Multicall3Client
from story_protocol_python_sdk.abi.PILicenseTemplate.PILicenseTemplate_client import (
PILicenseTemplateClient,
)
from story_protocol_python_sdk.abi.RegistrationWorkflows.RegistrationWorkflows_client import (
RegistrationWorkflowsClient,
)
from story_protocol_python_sdk.abi.RoyaltyModule.RoyaltyModule_client import (
RoyaltyModuleClient,
)
from story_protocol_python_sdk.abi.RoyaltyTokenDistributionWorkflows.RoyaltyTokenDistributionWorkflows_client import (
RoyaltyTokenDistributionWorkflowsClient,
)
from story_protocol_python_sdk.abi.SPGNFTImpl.SPGNFTImpl_client import SPGNFTImplClient
from story_protocol_python_sdk.types.common import AccessPermission
from story_protocol_python_sdk.types.resource.IPAsset import (
BatchMintAndRegisterIPInput,
BatchMintAndRegisterIPResponse,
LicenseTermsDataInput,
LinkDerivativeResponse,
MintedNFT,
MintNFT,
RegisterAndAttachAndDistributeRoyaltyTokensResponse,
RegisterDerivativeIPAndAttachAndDistributeRoyaltyTokensResponse,
RegisterDerivativeIpAssetResponse,
RegisteredIP,
RegisterIpAssetResponse,
RegisterPILTermsAndAttachResponse,
RegistrationResponse,
RegistrationWithRoyaltyVaultAndLicenseTermsResponse,
RegistrationWithRoyaltyVaultResponse,
)
from story_protocol_python_sdk.types.resource.License import LicenseTermsInput
from story_protocol_python_sdk.types.resource.Royalty import RoyaltyShareInput
from story_protocol_python_sdk.utils.constants import (
DEADLINE,
MAX_ROYALTY_TOKEN,
ZERO_ADDRESS,
ZERO_HASH,
)
from story_protocol_python_sdk.utils.derivative_data import (
DerivativeData,
DerivativeDataInput,
)
from story_protocol_python_sdk.utils.function_signature import get_function_signature
from story_protocol_python_sdk.utils.ip_metadata import (
IPMetadata,
IPMetadataInput,
get_ip_metadata_dict,
is_initial_ip_metadata,
)
from story_protocol_python_sdk.utils.licensing_config_data import LicensingConfigData
from story_protocol_python_sdk.utils.pil_flavor import PILFlavor
from story_protocol_python_sdk.utils.royalty import get_royalty_shares
from story_protocol_python_sdk.utils.sign import Sign
from story_protocol_python_sdk.utils.transaction_utils import build_and_send_transaction
from story_protocol_python_sdk.utils.util import convert_dict_keys_to_camel_case
from story_protocol_python_sdk.utils.validation import (
get_revenue_share,
validate_address,
validate_max_rts,
)
class IPAsset:
"""
IPAssetClient allows you to create, get, and list IP Assets with Story
Protocol.
:param web3 Web3: An instance of Web3.
:param account: The account to use for transactions.
:param chain_id int: The ID of the blockchain network.
"""
def __init__(self, web3: Web3, account, chain_id: int):
self.web3 = web3
self.account = account
self.chain_id = chain_id
self.ip_asset_registry_client = IPAssetRegistryClient(web3)
self.licensing_module_client = LicensingModuleClient(web3)
self.license_token_client = LicenseTokenClient(web3)
self.license_registry_client = LicenseRegistryClient(web3)
self.registration_workflows_client = RegistrationWorkflowsClient(web3)
self.license_attachment_workflows_client = LicenseAttachmentWorkflowsClient(
web3
)
self.derivative_workflows_client = DerivativeWorkflowsClient(web3)
self.core_metadata_module_client = CoreMetadataModuleClient(web3)
self.access_controller_client = AccessControllerClient(web3)
self.pi_license_template_client = PILicenseTemplateClient(web3)
self.royalty_token_distribution_workflows_client = (
RoyaltyTokenDistributionWorkflowsClient(web3)
)
self.royalty_module_client = RoyaltyModuleClient(web3)
self.multicall3_client = Multicall3Client(web3)
self.sign_util = Sign(web3, self.chain_id, self.account)
self.module_registry_client = ModuleRegistryClient(web3)
def mint(
self,
nft_contract: str,
to_address: str,
metadata_uri: str,
metadata_hash: bytes,
allow_duplicates: bool = False,
tx_options: dict | None = None,
):
spg_nft_client = SPGNFTImplClient(self.web3, contract_address=nft_contract)
def build_mint_transaction(
to, metadata_uri, metadata_hash, allow_duplicates, transaction_options
):
return spg_nft_client.contract.functions.mint(
to, metadata_uri, metadata_hash, allow_duplicates
).build_transaction(transaction_options)
response = build_and_send_transaction(
self.web3,
self.account,
build_mint_transaction,
to_address,
metadata_uri,
metadata_hash,
allow_duplicates,
tx_options=tx_options,
)
tx_hash = response["tx_hash"]
# Ensure the transaction hash starts with "0x"
if isinstance(tx_hash, str) and not tx_hash.startswith("0x"):
tx_hash = "0x" + tx_hash
return tx_hash
@deprecated("Use register_ip_asset() instead.")
def register(
self,
nft_contract: str,
token_id: int,
ip_metadata: dict | None = None,
deadline: int | None = None,
tx_options: dict | None = None,
) -> dict:
"""
Register an NFT as IP, creating a corresponding IP record.
:param nft_contract str: The address of the NFT.
:param token_id int: The token identifier of the NFT.
:param ip_metadata dict: [Optional] Metadata for the IP.
:param ip_metadata_uri str: [Optional] Metadata URI for the IP.
:param ip_metadata_hash str: [Optional] Metadata hash for the IP.
:param nft_metadata_uri str: [Optional] Metadata URI for the NFT.
:param nft_metadata_hash str: [Optional] Metadata hash for the NFT.
:param deadline int: [Optional] Signature deadline in seconds. (default: 1000 seconds)
:param tx_options dict: [Optional] Transaction options.
:return dict: Dictionary with the transaction hash and IP ID.
"""
try:
ip_id = self._get_ip_id(nft_contract, token_id)
if self.is_registered(ip_id):
return {"tx_hash": None, "ip_id": ip_id}
req_object: dict = {
"tokenId": token_id,
"nftContract": self.web3.to_checksum_address(nft_contract),
"ipMetadata": {
"ipMetadataURI": "",
"ipMetadataHash": ZERO_HASH,
"nftMetadataURI": "",
"nftMetadataHash": ZERO_HASH,
},
"sigMetadata": {
"signer": ZERO_ADDRESS,
"deadline": 0,
"signature": ZERO_HASH,
},
}
if not is_initial_ip_metadata(ip_metadata) and ip_metadata:
req_object["ipMetadata"].update(
{
"ipMetadataURI": ip_metadata.get("ip_metadata_uri", ""),
"ipMetadataHash": ip_metadata.get(
"ip_metadata_hash", ZERO_HASH
),
"nftMetadataURI": ip_metadata.get("nft_metadata_uri", ""),
"nftMetadataHash": ip_metadata.get(
"nft_metadata_hash", ZERO_HASH
),
}
)
calculated_deadline = self.sign_util.get_deadline(deadline=deadline)
signature_response = self.sign_util.get_permission_signature(
ip_id=ip_id,
deadline=calculated_deadline,
state=self.web3.to_bytes(hexstr=HexStr(ZERO_HASH)),
permissions=[
{
"ipId": ip_id,
"signer": self.registration_workflows_client.contract.address,
"to": self.core_metadata_module_client.contract.address,
"func": "setAll(address,string,bytes32,bytes32)",
"permission": AccessPermission.ALLOW,
}
],
)
req_object["sigMetadata"] = {
"signer": self.web3.to_checksum_address(self.account.address),
"deadline": calculated_deadline,
"signature": signature_response["signature"],
}
response = build_and_send_transaction(
self.web3,
self.account,
self.registration_workflows_client.build_registerIp_transaction,
req_object["nftContract"],
req_object["tokenId"],
req_object["ipMetadata"],
req_object["sigMetadata"],
tx_options=tx_options,
)
else:
response = build_and_send_transaction(
self.web3,
self.account,
self.ip_asset_registry_client.build_register_transaction,
self.chain_id,
nft_contract,
token_id,
tx_options=tx_options,
)
ip_registered = self._parse_tx_ip_registered_event(response["tx_receipt"])[
0
]
return {"tx_hash": response["tx_hash"], "ip_id": ip_registered["ip_id"]}
except Exception as e:
raise e
@deprecated("Use link_derivative() instead.")
def register_derivative(
self,
child_ip_id: str,
parent_ip_ids: list,
license_terms_ids: list,
max_minting_fee: int = 0,
max_rts: int = MAX_ROYALTY_TOKEN,
max_revenue_share: int = 100,
license_template: str | None = None,
tx_options: dict | None = None,
) -> dict:
"""
Registers a derivative directly with parent IP's license terms, without needing license tokens,
and attaches the license terms of the parent IPs to the derivative IP.
The license terms must be attached to the parent IP before calling this function.
All IPs attached default license terms by default.
The derivative IP owner must be the caller or an authorized operator.
:param child_ip_id str: The derivative IP ID
:param parent_ip_ids list: The parent IP IDs
:param license_terms_ids list: The IDs of the license terms that the parent IP supports
:param max_minting_fee int: The maximum minting fee that the caller is willing to pay.
if set to 0 then no limit. (default: 0)
:param max_rts int: The maximum number of royalty tokens that can be distributed
(max: 100,000,000) (default: 100,000,000)
:param max_revenue_share int: The maximum revenue share percentage allowed. Must be between 0 and 100 (where 100% represents 100,000,000). (default: 100)
:param license_template str: [Optional] The license template address. Defaults to [License Template](https://docs.story.foundation/docs/programmable-ip-license) address if not provided.
:param tx_options dict: [Optional] Transaction options
:return dict: A dictionary with the transaction hash
"""
try:
if not self.is_registered(child_ip_id):
raise ValueError(
f"The child IP with id {child_ip_id} is not registered."
)
derivative_data = DerivativeData.from_input(
web3=self.web3,
input_data=DerivativeDataInput(
parent_ip_ids=parent_ip_ids,
license_terms_ids=license_terms_ids,
max_minting_fee=max_minting_fee,
max_rts=max_rts,
max_revenue_share=max_revenue_share,
license_template=license_template,
),
).get_validated_data()
response = build_and_send_transaction(
self.web3,
self.account,
self.licensing_module_client.build_registerDerivative_transaction,
child_ip_id,
derivative_data["parentIpIds"],
derivative_data["licenseTermsIds"],
derivative_data["licenseTemplate"],
derivative_data["royaltyContext"],
derivative_data["maxMintingFee"],
derivative_data["maxRts"],
derivative_data["maxRevenueShare"],
tx_options=tx_options,
)
return {"tx_hash": response["tx_hash"]}
except Exception as e:
raise ValueError(f"Failed to register derivative: {str(e)}") from e
@deprecated("Use link_derivative() instead.")
def register_derivative_with_license_tokens(
self,
child_ip_id: str,
license_token_ids: list,
max_rts: int = 0,
tx_options: dict | None = None,
) -> dict:
"""
Registers a derivative with license tokens. The derivative IP is registered with license tokens
minted from the parent IP's license terms.
The license terms of the parent IPs issued with license tokens are attached to the derivative IP.
The caller must be the derivative IP owner or an authorized operator.
:param child_ip_id str: The derivative IP ID.
:param license_token_ids list: The IDs of the license tokens.
:param max_rts int: The maximum number of royalty tokens that can be distributed to the
external royalty policies (max: 100,000,000).
:param tx_options dict: [Optional] The transaction options.
:return dict: A dictionary with the transaction hash.
"""
try:
# Validate max_rts
validate_max_rts(max_rts)
# Validate child IP registration
if not self.is_registered(child_ip_id):
raise ValueError(
f"The child IP with id {child_ip_id} is not registered."
)
# Validate license token IDs and ownership
validated_token_ids = self._validate_license_token_ids(license_token_ids)
# Build and send transaction
response = build_and_send_transaction(
self.web3,
self.account,
self.licensing_module_client.build_registerDerivativeWithLicenseTokens_transaction,
child_ip_id,
validated_token_ids,
ZERO_ADDRESS,
max_rts,
tx_options=tx_options,
)
return {"tx_hash": response["tx_hash"]}
except Exception as e:
raise ValueError(
f"Failed to register derivative with license tokens: {str(e)}"
)
def link_derivative(
self,
child_ip_id: Address,
parent_ip_ids: list[Address] | None = None,
license_terms_ids: list[int] | None = None,
license_token_ids: list[int] | None = None,
max_minting_fee: int = 0,
max_rts: int = MAX_ROYALTY_TOKEN,
max_revenue_share: int = 100,
license_template: str | None = None,
tx_options: dict | None = None,
) -> LinkDerivativeResponse:
"""
Link a derivative IP asset using parent IP's license terms or license tokens.
Supports the following workflows:
- If `parent_ip_ids` is provided, calls `registerDerivative`(contract method)
- If `license_token_ids` is provided, calls `registerDerivativeWithLicenseTokens`(contract method)
:param child_ip_id Address: The derivative IP ID.
:param parent_ip_ids list[Address]: [Optional] The parent IP IDs. Required if using license terms.
:param license_terms_ids list[int]: [Optional] The IDs of the license terms that the parent IP supports. Required if `parent_ip_ids` is provided.
:param license_token_ids list[int]: [Optional] The IDs of the license tokens.
:param max_minting_fee int: [Optional] The maximum minting fee that the caller is willing to pay.
if set to 0 then no limit. (default: 0) Only used with `parent_ip_ids`.
:param max_rts int: [Optional] The maximum number of royalty tokens that can be distributed
(max: 100,000,000) (default: 100,000,000)
:param max_revenue_share int: [Optional] The maximum revenue share percentage allowed.
Must be between 0 and 100. (default: 100) Only used with `parent_ip_ids`.
:param license_template str: [Optional] The license template address.
Only used with `parent_ip_ids`.
:param tx_options dict: [Optional] Transaction options.
:return `LinkDerivativeResponse`: A dictionary with the transaction hash.
"""
try:
if parent_ip_ids is not None:
if license_terms_ids is None:
raise ValueError(
"license_terms_ids is required when parent_ip_ids is provided."
)
response = self.register_derivative(
child_ip_id=child_ip_id,
parent_ip_ids=parent_ip_ids,
license_terms_ids=license_terms_ids,
max_minting_fee=max_minting_fee,
max_rts=max_rts,
max_revenue_share=max_revenue_share,
license_template=license_template,
tx_options=tx_options,
)
return LinkDerivativeResponse(tx_hash=response["tx_hash"])
elif license_token_ids is not None:
response = self.register_derivative_with_license_tokens(
child_ip_id=child_ip_id,
license_token_ids=license_token_ids,
max_rts=max_rts,
tx_options=tx_options,
)
return LinkDerivativeResponse(tx_hash=response["tx_hash"])
else:
raise ValueError(
"either parent_ip_ids or license_token_ids must be provided."
)
except Exception as e:
raise ValueError(f"Failed to link derivative: {str(e)}") from e
@deprecated("Use register_ip_asset() instead.")
def mint_and_register_ip_asset_with_pil_terms(
self,
spg_nft_contract: str,
terms: list,
ip_metadata: dict | None = None,
recipient: str | None = None,
allow_duplicates: bool = False,
tx_options: dict | None = None,
) -> dict:
"""
Mint an NFT from a collection and register it as an IP.
:param spg_nft_contract str: The address of the NFT collection.
:param terms list: An array of license terms to attach.
:param terms dict: The license terms configuration.
:param transferable bool: Transferability of the license.
:param royalty_policy str: Address of the royalty policy contract.
:param default_minting_fee int: Fee for minting a license.
:param expiration int: License expiration.
:param commercial_use bool: Whether commercial use is allowed.
:param commercial_attribution bool: Whether attribution is needed
for commercial use.
:param commercializer_checker str: Allowed commercializers or zero
address for none.
:param commercializer_checker_data str: Data for checker contract.
:param commercial_rev_share int: Percentage of revenue that must be shared with the licensor. Must be between 0 and 100 (where 100% represents 100,000,000).
:param commercial_rev_ceiling int: Maximum commercial revenue.
:param derivatives_allowed bool: Whether derivatives are allowed.
:param derivatives_attribution bool: Whether attribution is needed
for derivatives.
:param derivatives_approval bool: Whether licensor approval is
required for derivatives.
:param derivatives_reciprocal bool: Whether derivatives must use
the same license terms.
:param derivative_rev_ceiling int: Max derivative revenue.
:param currency str: ERC20 token for the minting fee.
:param uri str: URI for offchain license terms.
:param licensing_config dict: The configuration for the license.
:param is_set bool: Whether the configuration is set or not.
:param minting_fee int: The fee to be paid when minting tokens.
:param hook_data str: The data used by the licensing hook.
:param licensing_hook str: The licensing hook contract address or
address(0) if none.
:param commercial_rev_share int: Percentage of revenue that must be shared with the licensor. Must be between 0 and 100 (where 100% represents 100,000,000).
:param disabled bool: Whether the license is disabled.
:param expect_minimum_group_reward_share int: Minimum group reward share percentage. Must be between 0 and 100 (where 100% represents 100,000,000).
:param expect_group_reward_pool str: Address of the expected group reward pool.
:param ip_metadata dict: [Optional] NFT and IP metadata.
:param ip_metadata_uri str: [Optional] IP metadata URI.
:param ip_metadata_hash str: [Optional] IP metadata hash.
:param nft_metadata_uri str: [Optional] NFT metadata URI.
:param nft_metadata_hash str: [Optional] NFT metadata hash.
:param recipient str: [Optional] Recipient address (defaults to caller).
:param allow_duplicates bool: [Optional] Whether to allow duplicates.
:param tx_options dict: [Optional] Transaction options.
:return dict: Dictionary with tx hash, IP ID, token ID, and license term IDs.
"""
try:
if not self.web3.is_address(spg_nft_contract):
raise ValueError(
f"The NFT contract address {spg_nft_contract} is not valid."
)
license_terms = self._validate_license_terms_data(terms)
metadata = {
"ipMetadataURI": "",
"ipMetadataHash": ZERO_HASH,
"nftMetadataURI": "",
"nftMetadataHash": ZERO_HASH,
}
if ip_metadata:
metadata.update(
{
"ipMetadataURI": ip_metadata.get("ip_metadata_uri", ""),
"ipMetadataHash": ip_metadata.get(
"ip_metadata_hash", ZERO_HASH
),
"nftMetadataURI": ip_metadata.get("nft_metadata_uri", ""),
"nftMetadataHash": ip_metadata.get(
"nft_metadata_hash", ZERO_HASH
),
}
)
response = build_and_send_transaction(
self.web3,
self.account,
self.license_attachment_workflows_client.build_mintAndRegisterIpAndAttachPILTerms_transaction,
spg_nft_contract,
self._validate_recipient(recipient),
metadata,
license_terms,
allow_duplicates,
tx_options=tx_options,
)
ip_registered = self._parse_tx_ip_registered_event(response["tx_receipt"])[
0
]
license_terms_ids = self._parse_tx_license_terms_attached_event(
response["tx_receipt"]
)
return {
"tx_hash": response["tx_hash"],
"ip_id": ip_registered["ip_id"],
"license_terms_ids": license_terms_ids,
"token_id": ip_registered["token_id"],
}
except Exception as e:
raise e
@deprecated("Use register_ip_asset() instead.")
def mint_and_register_ip(
self,
spg_nft_contract: str,
recipient: str | None = None,
ip_metadata: dict | None = None,
allow_duplicates: bool = True,
tx_options: dict | None = None,
) -> dict:
"""
Mint an NFT from a SPGNFT collection and register it with metadata as an IP.
:param spg_nft_contract str: The address of the SPGNFT collection.
:param recipient str: [Optional] The address of the recipient of the minted NFT,
default value is your wallet address.
:param ip_metadata dict: [Optional] The desired metadata for the newly minted NFT
and newly registered IP.
:param ip_metadata_uri str: [Optional] The URI of the metadata for the IP.
:param ip_metadata_hash str: [Optional] The hash of the metadata for the IP.
:param nft_metadata_uri str: [Optional] The URI of the metadata for the NFT.
:param nft_metadata_hash str: [Optional] The hash of the metadata for the IP NFT.
:param allow_duplicates bool: Set to true to allow minting an NFT with a duplicate
metadata hash.
:param tx_options dict: [Optional] The transaction options.
:return dict: A dictionary with the transaction hash, IP ID and token ID.
"""
try:
metadata = {
"ipMetadataURI": "",
"ipMetadataHash": ZERO_HASH,
"nftMetadataURI": "",
"nftMetadataHash": ZERO_HASH,
}
if ip_metadata:
metadata.update(
{
"ipMetadataURI": ip_metadata.get("ip_metadata_uri", ""),
"ipMetadataHash": ip_metadata.get(
"ip_metadata_hash", ZERO_HASH
),
"nftMetadataURI": ip_metadata.get("nft_metadata_uri", ""),
"nftMetadataHash": ip_metadata.get(
"nft_metadata_hash", ZERO_HASH
),
}
)
response = build_and_send_transaction(
self.web3,
self.account,
self.registration_workflows_client.build_mintAndRegisterIp_transaction,
spg_nft_contract,
self._validate_recipient(recipient),
metadata,
allow_duplicates,
tx_options=tx_options,
)
ip_registered = self._parse_tx_ip_registered_event(response["tx_receipt"])[
0
]
return {
"tx_hash": response["tx_hash"],
"ip_id": ip_registered["ip_id"],
"token_id": ip_registered["token_id"],
}
except Exception as e:
raise ValueError(f"Failed to mint and register IP: {str(e)}")
def batch_mint_and_register_ip(
self,
requests: list[BatchMintAndRegisterIPInput],
tx_options: dict | None = None,
) -> BatchMintAndRegisterIPResponse:
"""
Batch mints NFTs from SPGNFT collections and registers them as IP assets.
Optimizes transaction processing by grouping requests and Uses `RegistrationWorkflows's multicall` for minting contracts.
:param requests list[BatchMintAndRegisterIPInput]: The list of batch mint and register IP requests.
:param tx_options: [Optional] The transaction options.
:return `BatchMintAndRegisterIPResponse`: A response with transaction hash and list of `RegisteredIP` which includes IP ID and token ID.
"""
try:
encoded_data = []
for request in requests:
encoded_data.append(
self.registration_workflows_client.contract.encode_abi(
abi_element_identifier="mintAndRegisterIp",
args=[
validate_address(request.spg_nft_contract),
self._validate_recipient(request.recipient),
IPMetadata.from_input(
request.ip_metadata
).get_validated_data(),
request.allow_duplicates,
],
)
)
response = build_and_send_transaction(
self.web3,
self.account,
self.registration_workflows_client.build_multicall_transaction,
encoded_data,
tx_options=tx_options,
)
registered_ips = self._parse_tx_ip_registered_event(response["tx_receipt"])
return BatchMintAndRegisterIPResponse(
tx_hash=response["tx_hash"],
registered_ips=registered_ips,
)
except Exception as e:
raise ValueError(f"Failed to batch mint and register IP: {str(e)}")
@deprecated("Use register_ip_asset() instead.")
def register_ip_and_attach_pil_terms(
self,
nft_contract: str,
token_id: int,
license_terms_data: list,
ip_metadata: dict | None = None,
deadline: int | None = None,
tx_options: dict | None = None,
) -> dict:
"""
Register a given NFT as an IP and attach Programmable IP License Terms.
:param nft_contract str: The address of the NFT collection.
:param token_id int: The ID of the NFT.
:param license_terms_data list: The PIL terms and licensing configuration data to be attached to the IP.
:param terms dict: The PIL terms to be used for the licensing.
:param transferable bool: Indicates whether the license is transferable or not.
:param royalty_policy str: The address of the royalty policy contract which required to StoryProtocol in advance.
:param minting_fee int: The fee to be paid when minting a license.
:param expiration int: The expiration period of the license.
:param commercial_use bool: Indicates whether the work can be used commercially or not.
:param commercial_attribution bool: Whether attribution is required when reproducing the work commercially or not.
:param commercializer_checker str: Commercializers that are allowed to commercially exploit the work.
:param commercializer_checker_data str: The data to be passed to the commercializer checker contract.
:param commercial_rev_share int: Percentage of revenue that must be shared with the licensor. Must be between 0 and 100 (where 100% represents 100,000,000).
:param commercial_rev_ceiling int: The maximum revenue that can be generated from the commercial use of the work.
:param derivatives_allowed bool: Indicates whether the licensee can create derivatives of his work or not.
:param derivatives_attribution bool: Indicates whether attribution is required for derivatives of the work or not.
:param derivatives_approval bool: Indicates whether the licensor must approve derivatives of the work before they can be linked.
:param derivatives_reciprocal bool: Indicates whether the licensee must license derivatives under the same terms.
:param derivative_rev_ceiling int: The maximum revenue that can be generated from the derivative use of the work.
:param currency str: The ERC20 token to be used to pay the minting fee.
:param uri str: The URI of the license terms.
:param licensing_config dict: The PIL terms and licensing configuration data to attach to the IP.
:param is_set bool: Whether the configuration is set or not.
:param minting_fee int: The minting fee to be paid when minting license tokens.
:param licensing_hook str: The hook contract address for the licensing module.
:param hook_data str: The data to be used by the licensing hook.
:param commercial_rev_share int: Percentage of revenue that must be shared with the licensor. Must be between 0 and 100 (where 100% represents 100,000,000).
:param disabled bool: Whether the licensing is disabled or not.
:param expect_minimum_group_reward_share int: The minimum percentage of the group's reward share. Must be between 0 and 100 (where 100% represents 100,000,000).
:param expect_group_reward_pool str: The address of the expected group reward pool.
:param ip_metadata dict: [Optional] The metadata for the newly registered IP.
:param ip_metadata_uri str: [Optional] The URI of the metadata for the IP.
:param ip_metadata_hash str: [Optional] The hash of the metadata for the IP.
:param nft_metadata_uri str: [Optional] The URI of the metadata for the NFT.
:param nft_metadata_hash str: [Optional] The hash of the metadata for the IP NFT.
:param deadline int: [Optional] The deadline for the signature in seconds. (default: 1000 seconds)
:param tx_options dict: [Optional] The transaction options.
:return dict: A dictionary with the transaction hash, license terms ID, and IP ID.
"""
try:
ip_id = self._get_ip_id(nft_contract, token_id)
if self.is_registered(ip_id):
raise ValueError(
f"The NFT with id {token_id} is already registered as IP."
)
license_terms = self._validate_license_terms_data(license_terms_data)
calculated_deadline = self.sign_util.get_deadline(deadline=deadline)
# Get permission signature for all required permissions
signature_response = self.sign_util.get_permission_signature(
ip_id=ip_id,
deadline=calculated_deadline,
state=self.web3.to_bytes(hexstr=HexStr(ZERO_HASH)),
permissions=[
{
"ipId": ip_id,
"signer": self.license_attachment_workflows_client.contract.address,
"to": self.core_metadata_module_client.contract.address,
"permission": AccessPermission.ALLOW,
"func": "setAll(address,string,bytes32,bytes32)",
},
{
"ipId": ip_id,
"signer": self.license_attachment_workflows_client.contract.address,
"to": self.licensing_module_client.contract.address,
"permission": AccessPermission.ALLOW,
"func": "attachLicenseTerms(address,address,uint256)",
},
{
"ipId": ip_id,
"signer": self.license_attachment_workflows_client.contract.address,
"to": self.licensing_module_client.contract.address,
"permission": AccessPermission.ALLOW,
"func": "setLicensingConfig(address,address,uint256,(bool,uint256,address,bytes,uint32,bool,uint32,address))",
},
],
)
metadata = {
"ipMetadataURI": "",
"ipMetadataHash": ZERO_HASH,
"nftMetadataURI": "",
"nftMetadataHash": ZERO_HASH,
}
if ip_metadata:
metadata.update(
{
"ipMetadataURI": ip_metadata.get("ip_metadata_uri", ""),
"ipMetadataHash": ip_metadata.get(
"ip_metadata_hash", ZERO_HASH
),
"nftMetadataURI": ip_metadata.get("nft_metadata_uri", ""),
"nftMetadataHash": ip_metadata.get(
"nft_metadata_hash", ZERO_HASH
),
}
)
response = build_and_send_transaction(
self.web3,
self.account,
self.license_attachment_workflows_client.build_registerIpAndAttachPILTerms_transaction,
nft_contract,
token_id,
metadata,
license_terms,
{
"signer": self.web3.to_checksum_address(self.account.address),
"deadline": calculated_deadline,
"signature": signature_response["signature"],
},
tx_options=tx_options,
)
ip_registered = self._parse_tx_ip_registered_event(response["tx_receipt"])[
0
]
license_terms_ids = self._parse_tx_license_terms_attached_event(
response["tx_receipt"]
)
return {
"tx_hash": response["tx_hash"],
"ip_id": ip_registered["ip_id"],
"license_terms_ids": license_terms_ids,
"token_id": ip_registered["token_id"],
}
except Exception as e:
raise e
@deprecated("Deprecated: Use register_derivative_ip_asset instead.")
def register_derivative_ip(
self,
nft_contract: str,
token_id: int,
deriv_data: DerivativeDataInput,
metadata: IPMetadataInput | None = None,
deadline: int | None = None,
tx_options: dict | None = None,
) -> dict:
"""
Register the given NFT as a derivative IP with metadata without using
license tokens.
:param nft_contract str: The address of the NFT collection.
:param token_id int: The ID of the NFT.
:param deriv_data `DerivativeDataInput`: The derivative data for registerDerivative.
:param metadata `IPMetadataInput`: [Optional] Desired IP metadata.
:param deadline int: [Optional] Signature deadline in seconds. (default: 1000 seconds)
:param tx_options dict: [Optional] Transaction options.
:return dict: Dictionary with the tx hash and IP ID.
"""
try:
ip_id = self._get_ip_id(nft_contract, token_id)
if self.is_registered(ip_id):
raise ValueError(
f"The NFT with id {token_id} is already registered as IP."
)
validated_deriv_data = DerivativeData.from_input(
web3=self.web3, input_data=deriv_data
).get_validated_data()
calculated_deadline = self.sign_util.get_deadline(deadline=deadline)
sig_register_signature = self.sign_util.get_permission_signature(
ip_id=ip_id,
deadline=calculated_deadline,
state=Web3.to_bytes(0),
permissions=[
{
"ipId": ip_id,
"signer": self.derivative_workflows_client.contract.address,
"to": self.core_metadata_module_client.contract.address,
"permission": AccessPermission.ALLOW,
"func": get_function_signature(
self.core_metadata_module_client.contract.abi,
"setAll",
),
},
{
"ipId": ip_id,
"signer": self.derivative_workflows_client.contract.address,
"to": self.licensing_module_client.contract.address,
"permission": AccessPermission.ALLOW,
"func": get_function_signature(
self.licensing_module_client.contract.abi,
"registerDerivative",
),
},
],
)
response = build_and_send_transaction(
self.web3,
self.account,
self.derivative_workflows_client.build_registerIpAndMakeDerivative_transaction,
nft_contract,
token_id,
validated_deriv_data,
IPMetadata.from_input(metadata).get_validated_data(),
{
"signer": self.account.address,
"deadline": calculated_deadline,
"signature": sig_register_signature["signature"],
},
tx_options=tx_options,
)
ip_registered = self._parse_tx_ip_registered_event(response["tx_receipt"])[
0
]
return {
"tx_hash": response["tx_hash"],
"ip_id": ip_registered["ip_id"],
"token_id": ip_registered["token_id"],
}
except Exception as e:
raise e
@deprecated("Deprecated: Use register_derivative_ip_asset instead.")
def mint_and_register_ip_and_make_derivative(
self,
spg_nft_contract: str,
deriv_data: DerivativeDataInput,
ip_metadata: IPMetadataInput | None = None,
recipient: Address | None = None,
allow_duplicates: bool = True,
tx_options: dict | None = None,
) -> RegistrationResponse:
"""
Mint an NFT from a collection and register it as a derivative IP without license tokens.
:param spg_nft_contract str: The address of the SPGNFT collection.
:param deriv_data `DerivativeDataInput`: The derivative data to be used for register derivative.
:param ip_metadata `IPMetadataInput`: [Optional] The desired metadata for the newly minted NFT and newly registered IP.
:param recipient str: [Optional] The address to receive the minted NFT. If not provided, the client's own wallet address will be used.
:param allow_duplicates bool: [Optional] Set to true to allow minting an NFT with a duplicate metadata hash. (default: True)
:param tx_options dict: [Optional] Transaction options.
:return RegistrationResponse: Dictionary with the tx hash, IP ID and token ID.
"""
try:
validated_deriv_data = DerivativeData.from_input(
web3=self.web3, input_data=deriv_data
).get_validated_data()
response = build_and_send_transaction(
self.web3,
self.account,
self.derivative_workflows_client.build_mintAndRegisterIpAndMakeDerivative_transaction,
validate_address(spg_nft_contract),
validated_deriv_data,
IPMetadata.from_input(ip_metadata).get_validated_data(),
self._validate_recipient(recipient),
allow_duplicates,
tx_options=tx_options,
)
ip_registered = self._parse_tx_ip_registered_event(response["tx_receipt"])[
0
]
return RegistrationResponse(
tx_hash=response["tx_hash"],
ip_id=ip_registered["ip_id"],
token_id=ip_registered["token_id"],
)
except Exception as e:
raise e
@deprecated("Deprecated: Use register_derivative_ip_asset instead.")
def mint_and_register_ip_and_make_derivative_with_license_tokens(
self,
spg_nft_contract: Address,
license_token_ids: list[int],
max_rts: int = MAX_ROYALTY_TOKEN,
recipient: Address | None = None,
allow_duplicates: bool = True,
ip_metadata: IPMetadataInput | None = None,
tx_options: dict | None = None,
) -> RegistrationResponse:
"""
Mint an NFT from a collection and register it as a derivative IP with license tokens.