smartpy-tezos 0.0.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of smartpy-tezos might be problematic. Click here for more details.

Files changed (201) hide show
  1. smartpy/__init__.py +703 -0
  2. smartpy/config.py +2 -0
  3. smartpy/environment.py +130 -0
  4. smartpy/metadata.py +430 -0
  5. smartpy/modules.py +309 -0
  6. smartpy/scenario_utils.py +39 -0
  7. smartpy/services.py +198 -0
  8. smartpy/sexp.py +45 -0
  9. smartpy/smartpy-docker +65 -0
  10. smartpy/state.py +23 -0
  11. smartpy/stdlib/address_utils.spy +28 -0
  12. smartpy/stdlib/fixed_point.spy +148 -0
  13. smartpy/stdlib/list_utils.spy +271 -0
  14. smartpy/stdlib/math.spy +74 -0
  15. smartpy/stdlib/rational.spy +229 -0
  16. smartpy/stdlib/statistics.spy +21 -0
  17. smartpy/stdlib/string_utils.spy +350 -0
  18. smartpy/stdlib/utils.spy +90 -0
  19. smartpy/syntax.py +1821 -0
  20. smartpy/templates/admin_hand_over.py +158 -0
  21. smartpy/templates/admin_multisig.py +760 -0
  22. smartpy/templates/atomicSwap.py +79 -0
  23. smartpy/templates/baking_swap.py +323 -0
  24. smartpy/templates/bls12_381.py +226 -0
  25. smartpy/templates/bridge.py +81 -0
  26. smartpy/templates/calculator.py +64 -0
  27. smartpy/templates/calculator_main.spy +47 -0
  28. smartpy/templates/calculator_new.py +31 -0
  29. smartpy/templates/chain_id.py +20 -0
  30. smartpy/templates/check_dfs.py +45 -0
  31. smartpy/templates/chess.py +1078 -0
  32. smartpy/templates/chess_test_3_repeat.py +72 -0
  33. smartpy/templates/chess_test_checkmate.py +80 -0
  34. smartpy/templates/chess_test_game1.py +214 -0
  35. smartpy/templates/chess_test_game2.py +105 -0
  36. smartpy/templates/collatz.py +72 -0
  37. smartpy/templates/contract_metadata.py +61 -0
  38. smartpy/templates/create_contract.py +388 -0
  39. smartpy/templates/effectful_apply.py +172 -0
  40. smartpy/templates/escrow.py +75 -0
  41. smartpy/templates/events.py +20 -0
  42. smartpy/templates/example_cyclic1.spy +8 -0
  43. smartpy/templates/example_cyclic2.spy +7 -0
  44. smartpy/templates/example_cyclic3.spy +7 -0
  45. smartpy/templates/example_import.spy +8 -0
  46. smartpy/templates/fa1_2.py +444 -0
  47. smartpy/templates/fa2_1_lib.py +1457 -0
  48. smartpy/templates/fa2_1_lib_test_fungible.py +134 -0
  49. smartpy/templates/fa2_1_lib_test_nft.py +134 -0
  50. smartpy/templates/fa2_1_lib_test_single_asset.py +127 -0
  51. smartpy/templates/fa2_fungible_minimal.py +285 -0
  52. smartpy/templates/fa2_lib.py +941 -0
  53. smartpy/templates/fa2_lib_fungible.py +208 -0
  54. smartpy/templates/fa2_lib_nft.py +216 -0
  55. smartpy/templates/fa2_lib_single_asset.py +211 -0
  56. smartpy/templates/fa2_lib_test_fungible.py +142 -0
  57. smartpy/templates/fa2_lib_test_nft.py +138 -0
  58. smartpy/templates/fa2_lib_test_single_asset.py +141 -0
  59. smartpy/templates/fa2_lib_testing.py +2723 -0
  60. smartpy/templates/fa2_lib_testing_fa2_1_helpers.py +153 -0
  61. smartpy/templates/fa2_nft_minimal.py +266 -0
  62. smartpy/templates/fa2_types.py +131 -0
  63. smartpy/templates/fibonacci.py +158 -0
  64. smartpy/templates/fibonacci_view.py +35 -0
  65. smartpy/templates/fifo.py +46 -0
  66. smartpy/templates/fixed_precision.py +83 -0
  67. smartpy/templates/game_of_life.py +86 -0
  68. smartpy/templates/inheritance.py +176 -0
  69. smartpy/templates/inlineMichelson.py +190 -0
  70. smartpy/templates/instantiate_from_metadata.py +82 -0
  71. smartpy/templates/inter_contract_calls.py +108 -0
  72. smartpy/templates/invalid_mutation_tests.py +249 -0
  73. smartpy/templates/jingleBells.py +65 -0
  74. smartpy/templates/lambdas.py +256 -0
  75. smartpy/templates/layout.py +46 -0
  76. smartpy/templates/minikitties.py +184 -0
  77. smartpy/templates/minimal.py +20 -0
  78. smartpy/templates/multisig.py +170 -0
  79. smartpy/templates/multisig_action.py +149 -0
  80. smartpy/templates/multisig_lambda.py +153 -0
  81. smartpy/templates/multisig_view.py +111 -0
  82. smartpy/templates/nim.py +87 -0
  83. smartpy/templates/nimLift.py +104 -0
  84. smartpy/templates/price_feed.py +1305 -0
  85. smartpy/templates/price_feed_multisign_admin.py +824 -0
  86. smartpy/templates/rng.spy +43 -0
  87. smartpy/templates/self_entrypoint.py +47 -0
  88. smartpy/templates/send_back.py +21 -0
  89. smartpy/templates/send_twice.py +52 -0
  90. smartpy/templates/shuffle.py +29 -0
  91. smartpy/templates/storeValue.py +43 -0
  92. smartpy/templates/stringManipulations.py +164 -0
  93. smartpy/templates/sub_entrypoint.py +42 -0
  94. smartpy/templates/syntax.py +157 -0
  95. smartpy/templates/test_address_comparison.py +90 -0
  96. smartpy/templates/test_address_utils.py +66 -0
  97. smartpy/templates/test_annots.py +20 -0
  98. smartpy/templates/test_big.py +1015 -0
  99. smartpy/templates/test_bitwise.py +185 -0
  100. smartpy/templates/test_calls.py +189 -0
  101. smartpy/templates/test_check_signature.py +90 -0
  102. smartpy/templates/test_closer.py +22 -0
  103. smartpy/templates/test_compare.py +81 -0
  104. smartpy/templates/test_compute_exception.py +49 -0
  105. smartpy/templates/test_conditionals.py +23 -0
  106. smartpy/templates/test_contract_hierarchy.py +120 -0
  107. smartpy/templates/test_convert.py +46 -0
  108. smartpy/templates/test_deprecated_syntax.py +24 -0
  109. smartpy/templates/test_div.py +66 -0
  110. smartpy/templates/test_docstrings.py +43 -0
  111. smartpy/templates/test_effects.py +406 -0
  112. smartpy/templates/test_empty.py +37 -0
  113. smartpy/templates/test_errors.py +172 -0
  114. smartpy/templates/test_errors_metadata.py +216 -0
  115. smartpy/templates/test_eval_order.py +424 -0
  116. smartpy/templates/test_factory_balance.py +24 -0
  117. smartpy/templates/test_failwith.py +58 -0
  118. smartpy/templates/test_fixed_point.py +78 -0
  119. smartpy/templates/test_for.py +119 -0
  120. smartpy/templates/test_hash_functions.py +62 -0
  121. smartpy/templates/test_import.py +21 -0
  122. smartpy/templates/test_imported.py +22 -0
  123. smartpy/templates/test_inheritance.py +61 -0
  124. smartpy/templates/test_initial_balance.py +41 -0
  125. smartpy/templates/test_inner_invalid.py +38 -0
  126. smartpy/templates/test_keywords.py +18 -0
  127. smartpy/templates/test_list_utils.py +233 -0
  128. smartpy/templates/test_lists.py +187 -0
  129. smartpy/templates/test_local_record.py +21 -0
  130. smartpy/templates/test_logs.py +42 -0
  131. smartpy/templates/test_maps.py +64 -0
  132. smartpy/templates/test_match.py +80 -0
  133. smartpy/templates/test_math.py +51 -0
  134. smartpy/templates/test_michelson_error.py +22 -0
  135. smartpy/templates/test_min.py +48 -0
  136. smartpy/templates/test_misc.py +51 -0
  137. smartpy/templates/test_modify.py +121 -0
  138. smartpy/templates/test_modules1.py +56 -0
  139. smartpy/templates/test_modules10.py +35 -0
  140. smartpy/templates/test_modules11.py +52 -0
  141. smartpy/templates/test_modules2.py +29 -0
  142. smartpy/templates/test_modules3.py +79 -0
  143. smartpy/templates/test_modules4.py +24 -0
  144. smartpy/templates/test_modules5.py +31 -0
  145. smartpy/templates/test_modules6.py +145 -0
  146. smartpy/templates/test_modules7.py +54 -0
  147. smartpy/templates/test_modules8.py +65 -0
  148. smartpy/templates/test_modules9.py +25 -0
  149. smartpy/templates/test_mutez.py +62 -0
  150. smartpy/templates/test_never.py +29 -0
  151. smartpy/templates/test_new_private.py +24 -0
  152. smartpy/templates/test_new_syntax.py +243 -0
  153. smartpy/templates/test_onchain_views.py +243 -0
  154. smartpy/templates/test_onchain_views_not_found.py +37 -0
  155. smartpy/templates/test_operation_order.py +80 -0
  156. smartpy/templates/test_option.py +40 -0
  157. smartpy/templates/test_pack.py +689 -0
  158. smartpy/templates/test_pattern_matching.py +92 -0
  159. smartpy/templates/test_poly.py +22 -0
  160. smartpy/templates/test_private_lambda.py +82 -0
  161. smartpy/templates/test_rational.py +131 -0
  162. smartpy/templates/test_rng.py +27 -0
  163. smartpy/templates/test_runtime_errors.py +60 -0
  164. smartpy/templates/test_scenario.py +172 -0
  165. smartpy/templates/test_scenario_context.py +48 -0
  166. smartpy/templates/test_self_data_set.py +25 -0
  167. smartpy/templates/test_send.py +63 -0
  168. smartpy/templates/test_set_contract_data.py +58 -0
  169. smartpy/templates/test_statistics.py +31 -0
  170. smartpy/templates/test_string_utils.py +147 -0
  171. smartpy/templates/test_threefry.py +34 -0
  172. smartpy/templates/test_ticket.py +173 -0
  173. smartpy/templates/test_timestamp.py +37 -0
  174. smartpy/templates/test_trace.py +18 -0
  175. smartpy/templates/test_transfers_to_accounts.py +38 -0
  176. smartpy/templates/test_type_abbrevs.py +63 -0
  177. smartpy/templates/test_type_errors.py +713 -0
  178. smartpy/templates/test_unification.py +23 -0
  179. smartpy/templates/test_variant.py +87 -0
  180. smartpy/templates/test_view_inheritance.py +57 -0
  181. smartpy/templates/test_void.py +20 -0
  182. smartpy/templates/test_with_storage.py +101 -0
  183. smartpy/templates/test_xss.py +42 -0
  184. smartpy/templates/threefry.spy +372 -0
  185. smartpy/templates/tictactoe.py +120 -0
  186. smartpy/templates/tictactoeFactory.py +146 -0
  187. smartpy/templates/toto.py +26 -0
  188. smartpy/templates/trilitech_tutorial_fa2_fungible_part1_complete.py +140 -0
  189. smartpy/templates/trilitech_tutorial_fa2_fungible_part2_complete.py +216 -0
  190. smartpy/templates/trilitech_tutorial_fa2_fungible_part3_complete.py +250 -0
  191. smartpy/templates/trilitech_tutorial_fa2_fungible_part4_complete.py +313 -0
  192. smartpy/templates/upgradable_lambdas.py +53 -0
  193. smartpy/templates/voting.py +28 -0
  194. smartpy/templates/voting_power.py +30 -0
  195. smartpy/templates/welcome.py +52 -0
  196. smartpy/types.py +391 -0
  197. smartpy/utils.py +133 -0
  198. smartpy_tezos-0.0.1.dist-info/LICENSE.md +21 -0
  199. smartpy_tezos-0.0.1.dist-info/METADATA +52 -0
  200. smartpy_tezos-0.0.1.dist-info/RECORD +201 -0
  201. smartpy_tezos-0.0.1.dist-info/WHEEL +4 -0
smartpy/environment.py ADDED
@@ -0,0 +1,130 @@
1
+ import sys
2
+ import os
3
+ from enum import Enum, unique, auto
4
+ import platform
5
+ import subprocess
6
+ import smartpy.config as config
7
+ from smartpy.state import get_state
8
+
9
+
10
+ @unique
11
+ class Environment(Enum):
12
+ JUPYTER = auto()
13
+ IDE = auto()
14
+ NATIVE = auto()
15
+
16
+
17
+ def _init_jupyter():
18
+ """Initialize Jupyter-specific settings and load necessary JavaScript files."""
19
+ from IPython.display import display, HTML
20
+ import js
21
+ import pyodide
22
+
23
+ def get_wheel_file(file_name):
24
+ """Load and evaluate a JavaScript file."""
25
+ file_path = os.path.join(os.path.dirname(__file__), "static", file_name)
26
+ with open(file_path, "r") as file:
27
+ return file.read()
28
+
29
+ oasisLibsCode = get_wheel_file("browserOasisLibs.js")
30
+ oasisCode = get_wheel_file("browserOasis.js")
31
+ canopyCode = get_wheel_file("browserCanopy.js")
32
+
33
+ js.module = pyodide.ffi.to_js({})
34
+ r = js.eval(oasisLibsCode)
35
+
36
+ js.module = pyodide.ffi.to_js({})
37
+ r = js.eval(oasisCode)
38
+ js.smartpy = js.Oasis.smartpy
39
+ js.parse = js.smartpy.step
40
+
41
+ js.module = pyodide.ffi.to_js({})
42
+ r = js.eval(canopyCode)
43
+
44
+ js.eval("globalThis.smartpyContext.addOutput = (x) => console.log(x)")
45
+
46
+ o = '<script type="module" src="../files/.static/jupyter-web-components.js" />'
47
+ display(HTML(o))
48
+ gtagEvent = """<script>
49
+ if (window.trackGoogleAnalyticsEvent) {
50
+ window.trackGoogleAnalyticsEvent({
51
+ category: 'smartpy code execution',
52
+ action: 'import smartpy',
53
+ label: 'execute the import smartpy in Jupyter',
54
+ });
55
+ }
56
+ </script>"""
57
+ display(HTML(gtagEvent))
58
+
59
+
60
+ def _init_oasis():
61
+ state = get_state()
62
+ if state.environment == Environment.NATIVE and not get_disabled_server():
63
+ state.oasis = subprocess.Popen(
64
+ get_command("oasis"),
65
+ stdin=subprocess.PIPE,
66
+ stdout=subprocess.PIPE,
67
+ encoding="utf-8",
68
+ )
69
+ else:
70
+ state.oasis = get_command("oasis")
71
+
72
+
73
+ def _init_canopy():
74
+ state = get_state()
75
+ state.canopy = get_command("canopy")
76
+
77
+
78
+ def init_environment():
79
+ # Detect the environment
80
+ state = get_state()
81
+ state.environment = (
82
+ Environment.IDE if sys.platform == "emscripten" else Environment.NATIVE
83
+ )
84
+
85
+ if state.environment == Environment.NATIVE:
86
+ _init_oasis()
87
+ _init_canopy()
88
+ else:
89
+ try:
90
+ # If ipywidgets can be imported, we're in Jupyter environment
91
+ from IPython.display import display, HTML
92
+
93
+ state.environment = Environment.JUPYTER
94
+ _init_jupyter()
95
+ except ImportError:
96
+ pass
97
+
98
+
99
+ def get_command(name):
100
+ use_docker = os.environ.get("SMARTPY_USE_DOCKER") is not None
101
+ _system = platform.system()
102
+ _machine = platform.machine()
103
+ c = os.environ.get("SMARTPY_" + name.upper())
104
+ if c:
105
+ return c.split()
106
+ else:
107
+ if use_docker or (_system, _machine) == ("Darwin", "x86_64"):
108
+ return [
109
+ os.path.dirname(__file__) + "/smartpy-docker",
110
+ config.docker_image,
111
+ name,
112
+ ]
113
+ elif (_system, _machine) == ("Linux", "x86_64"):
114
+ return [os.path.dirname(__file__) + "/smartpy-" + name + "-linux.exe"]
115
+ elif (_system, _machine) == ("Darwin", "arm64"):
116
+ return [os.path.dirname(__file__) + "/smartpy-" + name + "-macOS.exe"]
117
+ else:
118
+ raise Exception(f"Platform {_system}-{_machine} not supported.")
119
+
120
+
121
+ def get_disabled_server():
122
+ return os.environ.get("SMARTPY_DISABLE_SERVER") is not None
123
+
124
+
125
+ def get_debug():
126
+ return os.environ.get("SMARTPY_DEBUG") is not None
127
+
128
+
129
+ def get_make_file_dependencies():
130
+ return os.environ.get("SMARTPY_DEPENDENCIES_FILE")
smartpy/metadata.py ADDED
@@ -0,0 +1,430 @@
1
+ import requests
2
+ import typing
3
+ import json
4
+ import os
5
+ import smartpy.config as config
6
+ from smartpy.environment import Environment
7
+ from smartpy.state import get_state
8
+
9
+
10
+ class InstanceOffchainViewsMetadata:
11
+ def __init__(self, content):
12
+ self.content = content
13
+
14
+
15
+ def create_metadata_source(source_code_uri: str) -> typing.Dict[str, str]:
16
+ """Create the source value to be inserted in the metadata.
17
+
18
+ Args:
19
+ source_code_uri (str): The URI of the source code in the format `'ipfs://<hash>'`.
20
+ For example, `'ipfs://QmaV5gQ6p9ND9pjc1BPD3dc8oyi8CWEDdueSmkmasiaWGA'`
21
+ Note: While the standard may support `'https://<address>'`, this function is tailored for IPFS URIs.
22
+ Can be obtained with `sp.pin_on_ipfs(c1.get_source())`.
23
+
24
+ Returns:
25
+ dict: A dictionary containing:
26
+ - "tools": A list with a single string denoting the SmartPy version.
27
+ - "location": The provided source code URI.
28
+ """
29
+ if not isinstance(source_code_uri, str):
30
+ raise ValueError(
31
+ f"sp.create_metadata_source must be applied to constant strings and got ({source_code_uri})"
32
+ )
33
+ # Check the format of source_code_uri
34
+ if not source_code_uri.startswith("ipfs://"):
35
+ raise ValueError(
36
+ "source_code_uri must be in the format 'ipfs://<hash>'. For example, 'ipfs://QmaV5gQ6p9ND9pjc1BPD3dc8oyi8CWEDdueSmkmasiaWGA'. Note: 'https://<address>' may be valid per standard, but this function expects IPFS URIs."
37
+ )
38
+ return {
39
+ "tools": [f"SmartPy-{config.version}"],
40
+ "location": source_code_uri,
41
+ }
42
+
43
+
44
+ def create_errors(error_map):
45
+ return [
46
+ {"error": {"int": f"{value}"}, "expansion": {"string": key}}
47
+ for (key, value) in error_map.items()
48
+ ]
49
+
50
+
51
+ def create_tzip16_metadata(
52
+ name: typing.Optional[str] = None,
53
+ description: typing.Optional[str] = None,
54
+ version: typing.Optional[str] = None,
55
+ license_name: typing.Optional[str] = None,
56
+ license_details: typing.Optional[str] = None,
57
+ interfaces: typing.List[str] = None,
58
+ authors: typing.List[str] = None,
59
+ homepage: typing.Optional[str] = None,
60
+ source_uri: typing.Optional[str] = None,
61
+ offchain_views: typing.Optional[InstanceOffchainViewsMetadata] = None,
62
+ error_map: typing.Optional[typing.Dict[str, str]] = None,
63
+ ):
64
+ """Return a TZIP-016 compliant metadata dictionary.
65
+
66
+ Args:
67
+ name: The name of the contract
68
+ Should identify its purpose.
69
+ description: A proper natural language description of the contract.
70
+ version: The version of the contract.
71
+ The version together with the name should be unique in the chain.
72
+ For example: `"1.0.0"`.
73
+ license_name:
74
+ De facto license name when possible.
75
+ See Debian [guidelines](https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/#license-short-name)
76
+ license_details:
77
+ Optional license details
78
+ interfaces: A list of the TZIP interfaces supported by the contract.
79
+ TZIP-016 is added to this list.
80
+ For example: `["TZIP-016"]`.
81
+ authors: A list of the authors of the contract.
82
+ For example: `["SmartPy <https://smartpy.io/>"]`.
83
+ homepage: The homepage is for human-consumption.
84
+ It may be the location of the source of the contract, how to submit issue tickets, or just a more elaborate description.
85
+ source_uri: The URI of the source code in the format `'ipfs://<hash>'`.
86
+ For example, 'ipfs://QmaV5gQ6p9ND9pjc1BPD3dc8oyi8CWEDdueSmkmasiaWGA'
87
+ offchain_views: The offchain views as returned by `c.get_offchain_views()`.
88
+ error_map: A dictionary mapping error codes to error messages.
89
+
90
+ Returns:
91
+ dict: A TZIP-016 compliant metadata dictionary.
92
+ """
93
+
94
+ # Validate inputs
95
+ def validate_string(v, param_name):
96
+ if v is not None and not isinstance(v, str):
97
+ raise ValueError(f"'{param_name}' must be a string but got ({v})")
98
+
99
+ def validate_list_of_strings(v, param_name):
100
+ if v and (not isinstance(v, list) or not all(isinstance(i, str) for i in v)):
101
+ raise ValueError(f"'{param_name}' must be a list of strings.")
102
+
103
+ def validate_offchain_views(v):
104
+ if v and not isinstance(v, InstanceOffchainViewsMetadata):
105
+ raise ValueError(f"offchain_views must be `c.get_offchain_views()`")
106
+
107
+ if interfaces is None:
108
+ interfaces = []
109
+ if authors is None:
110
+ authors = []
111
+
112
+ validate_string(name, "name")
113
+ validate_string(description, "description")
114
+ validate_string(version, "version")
115
+ validate_string(license_name, "license_name")
116
+ validate_string(license_details, "license_details")
117
+ validate_list_of_strings(interfaces, "interfaces")
118
+ validate_list_of_strings(authors, "authors")
119
+ validate_string(homepage, "homepage")
120
+ validate_string(source_uri, "source_uri")
121
+ validate_offchain_views(offchain_views)
122
+
123
+ # Construct the metadata dictionary
124
+ metadata = {}
125
+ if name:
126
+ metadata["name"] = name
127
+ if description:
128
+ metadata["description"] = description
129
+ if version:
130
+ metadata["version"] = version
131
+ if license_name:
132
+ license_dict = {"name": license_name}
133
+ if license_details:
134
+ license_dict["details"] = license_details
135
+ metadata["license"] = license_dict
136
+ if "TZIP-016" not in interfaces:
137
+ interfaces.append("TZIP-016")
138
+ metadata["interfaces"] = interfaces
139
+ if authors:
140
+ metadata["authors"] = authors
141
+ if homepage:
142
+ metadata["homepage"] = homepage
143
+ if source_uri:
144
+ metadata["source"] = create_metadata_source(source_uri)
145
+ if offchain_views:
146
+ metadata["views"] = offchain_views.content
147
+ if error_map:
148
+ metadata["errors"] = create_errors(error_map)
149
+ return metadata
150
+
151
+
152
+ class _Response:
153
+ """Mimics the response object returned by requests when in browser mode."""
154
+
155
+ def __init__(self, status_code, text):
156
+ self.status_code = status_code
157
+ self.text = text
158
+ self.content = text.encode("utf-8")
159
+ self.ok = self.status_code >= 200 and self.status_code < 300
160
+
161
+ def json(self):
162
+ try:
163
+ return json.loads(self.text)
164
+ except Exception as e:
165
+ raise ValueError("Failed to decode JSON") from e
166
+
167
+ def raise_for_status(self):
168
+ if not self.ok:
169
+ raise Exception(f"HTTP error {self.status_code}: {self.text}")
170
+
171
+
172
+ def _request_post(url, payload, headers):
173
+ """Handles POST requests in native Python or browser environments."""
174
+ if (
175
+ get_state().environment == Environment.IDE
176
+ or get_state().environment == Environment.JUPYTER
177
+ ):
178
+ import js
179
+
180
+ xhr = js.XMLHttpRequest.new()
181
+ xhr.open("POST", url, False) # False makes the request synchronous
182
+ for key, value in headers.items():
183
+ xhr.setRequestHeader(key, value)
184
+ xhr.send(json.dumps(payload))
185
+ return _Response(xhr.status, xhr.responseText)
186
+ else:
187
+ response = requests.post(url, json=payload, headers=headers)
188
+ return _Response(response.status_code, response.text)
189
+
190
+
191
+ def _request_get(url):
192
+ """Handles GET requests in native Python or browser environments."""
193
+ if (
194
+ get_state().environment == Environment.IDE
195
+ or get_state().environment == Environment.JUPYTER
196
+ ):
197
+ import js
198
+
199
+ xhr = js.XMLHttpRequest.new()
200
+ xhr.open("GET", url, False) # False makes the request synchronous
201
+ xhr.send()
202
+ return _Response(xhr.status, xhr.responseText)
203
+ else:
204
+ response = requests.get(url)
205
+ return _Response(response.status_code, response.text)
206
+
207
+
208
+ def pin_on_ipfs(
209
+ data: typing.Dict[str, typing.Any],
210
+ api_key: typing.Optional[str] = None,
211
+ secret_key: typing.Optional[str] = None,
212
+ name: typing.Optional[str] = None,
213
+ ):
214
+ """Encode a dict to JSON and pin it to IPFS through Pinata.
215
+
216
+ Args:
217
+ data: The metadata to pin.
218
+ For example, the data returned by `sp.create_tzip16_metadata(...)` or by `contract.get_source()`.
219
+ api_key: The API key for the Pinata account.
220
+ secret_key: The secret key for the Pinata account.
221
+ name: An optional name for the metadata file.
222
+
223
+
224
+ Returns:
225
+ str: The IPFS uri of the pinned metadata in the form `ipfs://<hash>`.
226
+ """
227
+ if api_key is None:
228
+ api_key = str(os.environ.get("PINATA_KEY"))
229
+ if secret_key is None:
230
+ secret_key = str(os.environ.get("PINATA_SECRET"))
231
+ url = "https://api.pinata.cloud/pinning/pinJSONToIPFS"
232
+ headers = {
233
+ "pinata_api_key": api_key,
234
+ "pinata_secret_api_key": secret_key,
235
+ "Content-Type": "application/json",
236
+ }
237
+ payload = {"pinataContent": data}
238
+ if name is not None:
239
+ payload["pinataMetadata"] = {"name": name}
240
+ response = _request_post(url=url, payload=payload, headers=headers)
241
+ if not response.ok:
242
+ try:
243
+ error_message = response.json().get("error", response.text)
244
+ except ValueError:
245
+ error_message = response.text
246
+ raise Exception(f"Error from Pinata API: {error_message}")
247
+ return f"ipfs://{response.json()['IpfsHash']}"
248
+
249
+
250
+ def get_metadata_uri(contract_address: str, network="mainnet") -> str:
251
+ """Get the uri given in the metadata bigmap of the contract.
252
+
253
+ Args:
254
+ contract_address (str): The Tezos address of the contract.
255
+ For example: `"KT1EQLe6AbouoX9RhFYHKeYQUAGAdGyFJXoi"`
256
+ network (str, optional): The Tezos network.
257
+ For example: "mainnet" (default) or "ghostnet"
258
+
259
+ Returns:
260
+ str: The metadata URI, usually in the format `ipfs://<hash>`.
261
+ """
262
+ base_url = f"https://api.{network}.tzkt.io/v1/"
263
+ try:
264
+ # Get the big map
265
+ url = f"{base_url}bigmaps/?contract={contract_address}&path=metadata"
266
+ response = _request_get(url)
267
+ response.raise_for_status() # Raise an exception for HTTP errors
268
+ big_maps = response.json()
269
+ if len(big_maps) == 0:
270
+ raise Exception("Not metadata bigmap found.")
271
+ big_map = big_maps[0]
272
+ # Get the big map value
273
+ url = f"{base_url}bigmaps/{big_map['ptr']}/keys/{''}"
274
+ response = _request_get(url)
275
+ response.raise_for_status() # Raise an exception for HTTP errors
276
+ values = response.json()
277
+ if len(big_maps) == 0:
278
+ raise Exception("The metadata bigmap doesn't contain the empty key.")
279
+ value = values[0]["value"]
280
+ value = bytes.fromhex(value).decode("utf-8")
281
+ if not (value.startswith("ipfs://") or value.startswith("https://")):
282
+ raise ValueError(
283
+ f"Unexpected metadata format: {value}. Expected format: ipfs://<hash> or https://<hash>"
284
+ )
285
+ return value
286
+ except requests.exceptions.RequestException as e:
287
+ raise Exception(f"Error: {e}")
288
+
289
+
290
+ def get_ipfs_data(uri: str, ipfs_gateway_url="https://ipfs.io/ipfs/"):
291
+ """Fetches and returns the content of a file from IPFS using the provided URI.
292
+
293
+ Args:
294
+ uri (str): The IPFS URI in the format `ipfs://<CID>`.
295
+ ipfs_gateway_url (str, optional): The IPFS gateway URL to use for fetching the content.
296
+ Defaults to the public IPFS gateway "https://ipfs.io/ipfs/".
297
+
298
+ Returns:
299
+ str: The content of the file from IPFS.
300
+ """
301
+ if not uri.startswith("ipfs://"):
302
+ raise ValueError("The provided URI is not a valid IPFS URI.")
303
+
304
+ # Ensure the gateway URL has a trailing slash
305
+ if not ipfs_gateway_url.endswith("/"):
306
+ ipfs_gateway_url += "/"
307
+
308
+ cid = uri.replace("ipfs://", "")
309
+ file_url = ipfs_gateway_url + cid
310
+ try:
311
+ response = _request_get(file_url)
312
+ response.raise_for_status()
313
+ return response.content.decode("utf-8")
314
+ except requests.exceptions.RequestException as e:
315
+ raise Exception(f"Error downloading the file from IPFS: {e}")
316
+
317
+
318
+ def get_metadata(contract_address: str, network="mainnet"):
319
+ """Fetches and returns the metadata dictionary for a given contract address and network.
320
+
321
+ Args:
322
+ contract_address (str): The Tezos address of the contract.
323
+ For example: `"KT1EQLe6AbouoX9RhFYHKeYQUAGAdGyFJXoi"`
324
+ network (str, optional): The Tezos network.
325
+ For example: "mainnet" (default) or "ghostnet"
326
+
327
+ Returns:
328
+ dict: The metadata dictionary.
329
+ """
330
+ return json.loads(get_ipfs_data(get_metadata_uri(contract_address, network)))
331
+
332
+
333
+ def get_metadata_code(metadata: typing.Dict[str, typing.Any]):
334
+ """Fetches and returns the code metadata for a contract's metadata.
335
+
336
+ Args:
337
+ metadata (dict): The metadata dictionary, expected to have a "source" key with a nested "location" key.
338
+
339
+ Returns:
340
+ dict: The code metadata.
341
+ """
342
+ if not metadata.get("source") or not metadata["source"].get("location"):
343
+ raise Exception(
344
+ "The metadata doesn't contain the expected 'source' and 'location' structure."
345
+ )
346
+ code_metadata_uri = metadata["source"]["location"]
347
+ return json.loads(get_ipfs_data(code_metadata_uri))
348
+
349
+
350
+ def get_michelson_code(contract_address: str, network="mainnet"):
351
+ """Fetches and returns the Michelson code of a contract from a Tezos node.
352
+
353
+ Args:
354
+ contract_address (str): The Tezos address of the contract.
355
+ For example: `"KT1EQLe6AbouoX9RhFYHKeYQUAGAdGyFJXoi"`
356
+ network (str, optional): The Tezos network.
357
+ For example: "mainnet" (default) or "ghostnet"
358
+
359
+ Returns:
360
+ dict: The Michelson code of the contract.
361
+ """
362
+ base_url = f"https://api.{network}.tzkt.io/v1/"
363
+ try:
364
+ url = f"{base_url}contracts/{contract_address}/code?format=0"
365
+ response = _request_get(url)
366
+ response.raise_for_status() # Raise an exception for HTTP errors
367
+ code = response.json()
368
+ return code
369
+ except requests.exceptions.RequestException as e:
370
+ raise Exception(
371
+ f"Error fetching Michelson code for contract {contract_address} on {network}: {e}"
372
+ )
373
+ except json.JSONDecodeError:
374
+ raise Exception("The fetched Michelson code is not valid JSON.")
375
+
376
+
377
+ def check_sp_version(metadata: typing.Dict[str, typing.Any]):
378
+ """Checks that current SmartPy version is compatible with the metadata."""
379
+ if "source" not in metadata or "tools" not in metadata["source"]:
380
+ raise Exception("metadata doesn't contain `source.tools`.")
381
+ tools = metadata["source"]["tools"]
382
+ sp_tools = [t for t in tools if t.startswith("SmartPy")]
383
+ if len(sp_tools) == 0:
384
+ raise Exception("Cannot test: SmartPy version not found in source.tools")
385
+ if len(sp_tools) > 1:
386
+ raise Exception("Incorrect metadata: Multiple SmartPy version found.")
387
+ running = f"SmartPy-{config.version}"
388
+ expected = sp_tools[0]
389
+ if expected != running:
390
+ raise Exception(f"Cannot test: Please use {expected} and not {running}.")
391
+
392
+
393
+ def normalize_micheline(micheline):
394
+ storage = [p for p in micheline if p["prim"] == "storage"]
395
+ code = [p for p in micheline if p["prim"] == "code"]
396
+ parameter = [p for p in micheline if p["prim"] == "parameter"]
397
+ views = [p for p in micheline if p["prim"] == "views"]
398
+ return storage + code + parameter + views
399
+
400
+
401
+ def are_equivalent_micheline(m1, m2, path=[]):
402
+ if isinstance(m1, dict) and isinstance(m2, dict):
403
+ if set(m1.keys()) != set(m2.keys()):
404
+ return (False, path)
405
+ for k in m1:
406
+ are_equal, diff_path = are_equivalent_micheline(m1[k], m2[k], path + [k])
407
+ if not are_equal:
408
+ return (False, diff_path)
409
+ return (True, None)
410
+ elif isinstance(m1, list) and isinstance(m2, list):
411
+ if len(m1) != len(m2):
412
+ return (False, path)
413
+ for idx, (e1, e2) in enumerate(zip(m1, m2)):
414
+ are_equal, diff_path = are_equivalent_micheline(e1, e2, path + [idx])
415
+ if not are_equal:
416
+ return (False, diff_path)
417
+ return (True, None)
418
+ else:
419
+ return (m1 == m2, None if m1 == m2 else path)
420
+
421
+
422
+ def print_diff_path(diff_path):
423
+ return "".join([f"[{p}]" if isinstance(p, int) else f"['{p}']" for p in diff_path])
424
+
425
+
426
+ class CodeMismatchException(Exception):
427
+ def __init__(self, generated_michelson, diff_details):
428
+ self.generated_michelson = generated_michelson
429
+ self.diff_details = diff_details
430
+ super().__init__("Generated michelson does not match onchain michelson")