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/__init__.py ADDED
@@ -0,0 +1,703 @@
1
+ # Copyright 2025 - present Trilitech Limited, 2022-2024 Morum LLC, 2019-2022 Smart Chain Arena LLC
2
+
3
+ from types import FunctionType
4
+ import atexit
5
+ import importlib
6
+ import importlib.metadata
7
+ import inspect
8
+ import os
9
+ import pathlib
10
+ import sys
11
+ import traceback
12
+ import subprocess
13
+ import typing
14
+ from enum import Enum, unique, auto
15
+ from collections import OrderedDict
16
+
17
+ from smartpy.metadata import (
18
+ normalize_micheline,
19
+ CodeMismatchException,
20
+ are_equivalent_micheline,
21
+ check_sp_version,
22
+ # Exposed to users
23
+ create_tzip16_metadata,
24
+ pin_on_ipfs,
25
+ get_metadata_uri,
26
+ get_ipfs_data,
27
+ get_metadata,
28
+ get_metadata_code,
29
+ get_michelson_code,
30
+ )
31
+ from smartpy.environment import (
32
+ Environment,
33
+ init_environment,
34
+ get_disabled_server,
35
+ get_debug,
36
+ get_make_file_dependencies,
37
+ )
38
+ from smartpy.utils import (
39
+ showTraceback,
40
+ LineNo,
41
+ get_file_line_no,
42
+ make_relative,
43
+ )
44
+ from smartpy.state import init_state, get_state
45
+ from smartpy.types import *
46
+ import smartpy.scenario_utils as scenario_utils
47
+ from smartpy.syntax import *
48
+ from smartpy.services import *
49
+ from smartpy.modules import Module, read_smartpy_code, ParseKind
50
+
51
+
52
+ __version__ = importlib.metadata.version("smartpy-tezos")
53
+
54
+
55
+ stdlib = None
56
+
57
+ init_state()
58
+ init_environment()
59
+
60
+
61
+ def evalRun(withTests):
62
+ get_state().unknownIds = 0
63
+ if "main" in sys.modules:
64
+ import main
65
+
66
+ importlib.reload(main)
67
+ else:
68
+ import main
69
+
70
+
71
+ def toException(x):
72
+ return Exception(x)
73
+
74
+
75
+ def shutdown():
76
+ interact({"request": "exit"})
77
+
78
+
79
+ if not get_disabled_server():
80
+ atexit.register(shutdown)
81
+
82
+
83
+ exception_optimization_levels = [
84
+ "full-debug",
85
+ "debug-message",
86
+ "verify-or-line",
87
+ "default-line",
88
+ "line",
89
+ "default-unit",
90
+ "unit",
91
+ ]
92
+
93
+
94
+ default_verify_message = None
95
+ wrap_verify_messages = None
96
+
97
+ normalMax = max
98
+ max = spmax
99
+ min = spmin
100
+
101
+
102
+ class Dynamic_contract:
103
+ def __init__(self, scenario, id, views):
104
+ self.contractId = static_contract_id(id)
105
+ self.data = contract_data(self.contractId)
106
+ self.balance = contract_balance(self.contractId)
107
+ self.address = contract_address(self.contractId)
108
+ self.baker = contract_baker(self.contractId)
109
+ self.typed = contract_typed(self.contractId)
110
+ self.scenario = scenario
111
+ self.views = views
112
+
113
+ # TODO __getattribute__, to hide "name", "args" etc.
114
+ def __getattr__(self, attr):
115
+ if attr in self.views:
116
+ return View(self, attr)
117
+ if attr == "address":
118
+ return contract_address(self.contractId)
119
+ if attr == "baker":
120
+ return contract_baker(self.contractId)
121
+ if attr == "balance":
122
+ return contract_balance(self.contractId)
123
+ if attr == "data":
124
+ return contract_data(self.contractId)
125
+ if attr == "private":
126
+ return contract_private(self.contractId)
127
+ if attr == "instantiation_result":
128
+ return self.__dict__["instantiation_result"]
129
+ return Method(self, attr) # TODO limit to parser-obtained list of methods
130
+
131
+
132
+ @unique
133
+ class SimulationMode(Enum):
134
+ NATIVE = "native"
135
+ MOCKUP = "mockup"
136
+ GHOSTNET = "ghostnet"
137
+
138
+ @classmethod
139
+ def from_string(cls, s):
140
+ return cls(s.lower())
141
+
142
+
143
+ def test_account(seed):
144
+ return TestAccount(seed)
145
+
146
+
147
+ class Scenario:
148
+ # special modules that need to behave like inline modules with a certain name
149
+ STDLIB_MODULES = {
150
+ "smartpy/stdlib/utils.spy": "utils",
151
+ "smartpy/stdlib/statistics.spy": "statistics",
152
+ "smartpy/stdlib/math.spy": "math",
153
+ "smartpy/stdlib/rational.spy": "rational",
154
+ "smartpy/stdlib/fixed_point.spy": "fp",
155
+ "smartpy/stdlib/list_utils.spy": "list_utils",
156
+ "smartpy/stdlib/string_utils.spy": "string_utils",
157
+ "smartpy/stdlib/address_utils.spy": "address_utils",
158
+ }
159
+
160
+ # holds sets of deps for each module added with add_module
161
+ _FILE_DEPENDENCIES = {}
162
+
163
+ def __init__(self):
164
+ self.messages = []
165
+ self.exceptions = []
166
+ self.nextId = 0
167
+ self.failed = False
168
+ self.entrypoint_calls = []
169
+ self.modules = []
170
+
171
+ @staticmethod
172
+ def _load(fn):
173
+ if get_disabled_server():
174
+ return None
175
+ else:
176
+ # Backward compatibility for old stdlib
177
+ fn_path = fn if isinstance(fn, pathlib.Path) else pathlib.Path(fn)
178
+ if fn_path.is_relative_to(pathlib.Path("smartpy/lib/")):
179
+ fn = pathlib.Path("smartpy/stdlib/") / fn_path.relative_to(
180
+ pathlib.Path("smartpy/lib/")
181
+ )
182
+ filename, code = read_smartpy_code(fn)
183
+ name = Scenario.STDLIB_MODULES.get(str(fn))
184
+ if name:
185
+ return Module.make_smartpy_stdlib_module(filename, code, name)
186
+ else:
187
+ return Module.make_smartpy_module(filename, code)
188
+
189
+ def simulation_mode(self):
190
+ data = {}
191
+ data["action"] = "get_config"
192
+ self.messages += [data]
193
+ r = self.action(data)
194
+ return SimulationMode.from_string(r["mode"][0])
195
+
196
+ def add_module(self, m):
197
+ load_library_id_needed()
198
+ if not isinstance(m, Module):
199
+ p = pathlib.Path(m)
200
+ m = Scenario._load(p)
201
+ assert m is not None
202
+ if m in self.modules:
203
+ return m
204
+ data = {}
205
+ data["action"] = "add_module"
206
+ data["module_id"] = m.module_id.export()
207
+ data["module"] = m.sexpr
208
+ data["imports"] = m.export_imports()
209
+ data["line_no"] = get_file_line_no().export()
210
+ self.messages += [data]
211
+ self.action(data)
212
+ self._get_dependencies(m)
213
+ self.modules.append(m)
214
+ return m
215
+
216
+ def _gen_dependencies(self, module):
217
+ filenames = pySet()
218
+ for m in module.ordered_imports():
219
+ filename = m.module_id.filename
220
+ if filename not in filenames:
221
+ filenames.add(filename)
222
+ yield filename, [
223
+ Module._make_filename(mm)[0] for mm in m.ordered_imports()
224
+ ]
225
+ filename = module.module_id.filename
226
+ # last one shouldnt be in here - that would indicate a circular import - but check anyway
227
+ if filename not in filenames:
228
+ filenames.add(filename)
229
+ yield filename, [
230
+ Module._make_filename(mm)[0] for mm in module.ordered_imports()
231
+ ]
232
+
233
+ def _clean(self, nm):
234
+ # note this is specific to our CI setup
235
+ if "templates" in nm:
236
+ return "templates" + nm.split("templates")[-1]
237
+ x = "wheels/smartpy-tezos/"
238
+ if "smartpy" in nm:
239
+ return x + "smartpy" + nm.split("smartpy")[-1]
240
+ return nm
241
+
242
+ def _get_dependencies(self, m):
243
+ if get_make_file_dependencies() is None:
244
+ return
245
+
246
+ ky = self._clean(make_relative(m.module_id.filename))
247
+ self._FILE_DEPENDENCIES[ky] = pySet()
248
+ sections = pyList()
249
+ for nm, deps in self._gen_dependencies(m):
250
+ if not deps:
251
+ continue
252
+ nm = self._clean(make_relative(nm))
253
+ if nm in self._FILE_DEPENDENCIES[ky]:
254
+ continue
255
+ self._FILE_DEPENDENCIES[ky].add(nm)
256
+ deps = [self._clean(make_relative(d)) for d in deps]
257
+ sections.append((nm, [d for d in deps]))
258
+ try:
259
+ # the scenario file that is calling this run
260
+ # if multiple calls to add_module then last one overrides others
261
+ nm = self._clean(make_relative(sys.argv[0]))
262
+ sections.append(
263
+ (nm, [ky for ky in self._FILE_DEPENDENCIES.keys() if ky != nm])
264
+ )
265
+ except IndexError as e:
266
+ print(e, file=sys.stderr)
267
+
268
+ try:
269
+ # we need append mode as there maybe multiple calls to add_module
270
+ # each make_file_dependencies is specific to a scenario
271
+ # so append mode is ok here
272
+ if sections and any(s for _, s in sections):
273
+ with open(get_make_file_dependencies(), "a") as fh:
274
+ for nm, deps in sections:
275
+ if not deps:
276
+ continue
277
+ fh.write(f"\n{nm}:\n")
278
+ for d in deps:
279
+ fh.write(f" {d}\n")
280
+ except OSError as e:
281
+ print(e, file=sys.stderr)
282
+
283
+ def action(self, x):
284
+ if not self.failed:
285
+ return interact({"request": "scenario_action", "ix": self.ix, "action": x})
286
+
287
+ def __iadd__(self, x):
288
+ if isinstance(x, Instance):
289
+ if x.scenario != self:
290
+ raise Exception("The contract was instantiated in a different scenario")
291
+ x.originate()
292
+ else:
293
+ raise Exception("Cannot add value of type %s to scenario" % str(type(x)))
294
+ return self
295
+
296
+ def dynamic_contract(self, template_ref, offset=None):
297
+ data = {}
298
+ data["action"] = "dynamic_contract"
299
+ data["offset"] = str(offset) if offset is not None else "-1"
300
+ data["line_no"] = get_file_line_no().export()
301
+ data["module_id"] = template_ref.module.module_id.export()
302
+ data["contract_name"] = template_ref.name
303
+ self.messages += [data]
304
+ id_ = self.action(data)
305
+
306
+ # NOTE this returns all views, not just offchain ones
307
+ data = {
308
+ "action": "getOffchainViews",
309
+ "id": static_contract_id(id_).export(),
310
+ "line_no": get_file_line_no().export(),
311
+ }
312
+ self.messages += [data]
313
+ xs = self.action(data)
314
+ views = {x["name"] for x in xs}
315
+
316
+ return Dynamic_contract(self, id_, views)
317
+
318
+ def verify(self, condition):
319
+ if isinstance(condition, pyBool):
320
+ if not condition:
321
+ raise Exception("Assert Failure")
322
+ else:
323
+ data = {}
324
+ data["action"] = "verify"
325
+ data["condition"] = spExpr(condition).export()
326
+ data["line_no"] = get_file_line_no().export()
327
+ self.messages += [data]
328
+ self.action(data)
329
+
330
+ def verify_equal(self, v1, v2):
331
+ data = {}
332
+ data["action"] = "verify"
333
+ data["condition"] = poly_equal_expr(v1, v2).export()
334
+ data["line_no"] = get_file_line_no().export()
335
+ self.messages += [data]
336
+ self.action(data)
337
+
338
+ def compute(
339
+ self,
340
+ expression,
341
+ sender=None,
342
+ source=None,
343
+ now=None,
344
+ level=None,
345
+ chain_id=None,
346
+ voting_powers=None,
347
+ ):
348
+ id = "scenario_var" + str(self.nextId)
349
+ self.nextId += 1
350
+ data = {}
351
+ data["action"] = "compute"
352
+ data["expression"] = spExpr(expression).export()
353
+ data["id"] = id
354
+ data["line_no"] = get_file_line_no().export()
355
+ if chain_id is not None:
356
+ data["chain_id"] = spExpr(chain_id).export()
357
+ if level is not None:
358
+ data["level"] = spExpr(level).export()
359
+ if sender is not None:
360
+ data["sender"] = parse_account_or_address(sender)
361
+ if source is not None:
362
+ data["source"] = parse_account_or_address(source)
363
+ if now is not None:
364
+ data["time"] = spExpr(now).export()
365
+ if voting_powers is not None:
366
+ data["voting_powers"] = spExpr(voting_powers).export()
367
+ self.messages += [data]
368
+ self.action(data)
369
+ return Expr("var", [id], get_file_line_no())
370
+
371
+ def show(self, expression, html=True, stripStrings=False, compile=False):
372
+ data = {}
373
+ data["action"] = "show"
374
+ data["compile"] = compile
375
+ data["expression"] = spExpr(expression).export()
376
+ data["html"] = html
377
+ data["line_no"] = get_file_line_no().export()
378
+ self.messages += [data]
379
+ self.action(data)
380
+
381
+ def p(self, s):
382
+ return self.tag("p", s)
383
+
384
+ def h1(self, s):
385
+ return self.tag("h1", s)
386
+
387
+ def h2(self, s):
388
+ return self.tag("h2", s)
389
+
390
+ def h3(self, s):
391
+ return self.tag("h3", s)
392
+
393
+ def h4(self, s):
394
+ return self.tag("h4", s)
395
+
396
+ def tag(self, tag, s):
397
+ data = {}
398
+ data["action"] = "textBlock"
399
+ data["inner"] = s
400
+ data["line_no"] = get_file_line_no().export()
401
+ data["tag"] = tag
402
+ self.messages += [data]
403
+ self.action(data)
404
+ return self
405
+
406
+ def add_flag(self, flag, *args):
407
+ data = {}
408
+ data["action"] = "flag"
409
+ data["flag"] = [flag] + pyList(args)
410
+ data["line_no"] = get_file_line_no().export()
411
+ self.action(data)
412
+ self.messages += [data]
413
+
414
+ def prepare_constant_value(self, value, hash=None):
415
+ id = "scenario_var" + str(self.nextId)
416
+ self.nextId += 1
417
+ data = {}
418
+ data["id"] = id
419
+ data["action"] = "constant"
420
+ data["kind"] = "value"
421
+ data["hash"] = "None" if hash is None else hash
422
+ data["expression"] = spExpr(value).export()
423
+ data["line_no"] = get_file_line_no().export()
424
+ self.messages += [data]
425
+ self.action(data)
426
+ return Expr("var", [id], get_file_line_no())
427
+
428
+ def simulation(self, c):
429
+ self.p("No interactive simulation available out of browser.")
430
+
431
+ def test_account(self, seed, initial_balance=None, as_delegate=None):
432
+ data = {}
433
+ data["action"] = "register_account"
434
+ data["seed"] = seed
435
+ if initial_balance is not None:
436
+ data["initial_balance"] = spExpr(initial_balance).export()
437
+ if as_delegate is not None:
438
+ data["as_delegate"] = pyBool(as_delegate)
439
+ data["line_no"] = get_file_line_no().export()
440
+ self.messages += [data]
441
+ self.action(data)
442
+ return test_account(seed)
443
+
444
+
445
+ def test_scenario(name, modules=None):
446
+ load_library_id_needed()
447
+ if modules is None:
448
+ modules = []
449
+ name = name.replace(" ", "_")
450
+ scenario = Scenario()
451
+ action = {"request": "new_scenario"}
452
+ flags = []
453
+ output_dir = os.environ.get("SMARTPY_OUTPUT_DIR")
454
+ if name is not None:
455
+ if output_dir is None:
456
+ output_dir = name
457
+ else:
458
+ output_dir = str(pathlib.Path(output_dir, name))
459
+ if get_state().environment == Environment.NATIVE and output_dir is not None:
460
+ r = subprocess.run(["mkdir", "-p", output_dir])
461
+ assert r.returncode == 0
462
+ flags += ["--output", output_dir]
463
+ more_flags = os.environ.get("SMARTPY_FLAGS")
464
+ if more_flags is not None:
465
+ flags += more_flags.split()
466
+ action["flags"] = flags
467
+ r = interact(action)
468
+ scenario.ix = r
469
+
470
+ if type(modules) != pyList:
471
+ modules = [modules]
472
+ for module in modules:
473
+ scenario.add_module(module)
474
+ get_state().current_scenario = scenario
475
+ return scenario
476
+
477
+
478
+ def add_test(name=None):
479
+ if name:
480
+ raise Exception(
481
+ "sp.add_test no longer takes the name argument. Please provide it to sp.test_scenario instead."
482
+ )
483
+
484
+ def r(f):
485
+ if not get_disabled_server():
486
+ get_state().current_scenario = None
487
+ f()
488
+ get_state().current_scenario = None
489
+
490
+ return r
491
+
492
+
493
+ class Verbatim:
494
+ def __init__(self, s):
495
+ self.s = s
496
+
497
+ def export(self):
498
+ return self.s
499
+
500
+
501
+ def load_module_from_metadata(module):
502
+ filename, line = module["line_no"][0], module["line_no"][1]
503
+ line_no = LineNo(filename, line)
504
+ code = module["source"]
505
+ kind = module["module_kind"]
506
+ name = module["name"]
507
+ if kind == "inline_python":
508
+ return Module.make_inline_module(filename, line - 3, 0, code)
509
+ elif kind == "smartpy":
510
+ return Module.make_smartpy_module(filename, code)
511
+ elif kind == "smartpy_stdlib":
512
+ return Module.make_smartpy_stdlib_module(filename, code, name)
513
+ else:
514
+ raise ValueError(f"Unknown module ID kind: {kind} for {name}")
515
+
516
+
517
+ def instantiate_from_metadata(
518
+ metadata: typing.Dict[str, typing.Any], code_metadata: typing.Dict[str, typing.Any]
519
+ ):
520
+ check_sp_version(metadata)
521
+ offset = 0
522
+ file = get_file_line_no().filename
523
+ args = [
524
+ parse_via_exe_or_js(file, offset, 0, ParseKind.EXPR, p)
525
+ for p in code_metadata["param"]
526
+ ]
527
+ sc = test_scenario("Check validity")
528
+ sc.h2("Check validity")
529
+ # Add flags
530
+ for flag in code_metadata["flags"]:
531
+ sc.add_flag(*flag)
532
+ # Add modules - imports first
533
+ for module in code_metadata["imports"]:
534
+ m = load_module_from_metadata(module)
535
+ sc.add_module(m)
536
+ # Add modules - then main one
537
+ main_module = load_module_from_metadata(code_metadata["module_"])
538
+ sc.add_module(main_module)
539
+ # Instantiate the contract
540
+ c1 = main_module.__getattr__(code_metadata["name"])(*args)
541
+ # Originate the contract
542
+ sc += c1
543
+ return c1.get_generated_michelson()
544
+
545
+
546
+ def check_validity(
547
+ metadata: typing.Dict[str, typing.Any],
548
+ code_metadata: typing.Dict[str, typing.Any],
549
+ onchain_michelson: typing.List[typing.Any],
550
+ ):
551
+ """Checks that the code given in the metadata generates the same onchain code.
552
+
553
+ Args:
554
+ metadata (dict): Metadata dictionary.
555
+ Can be obtained from `sp.get_metadata()`.
556
+ code_metadata (dict): Code metadata dictionary.
557
+ Can be obtained from `sp.get_metadata_code()`.
558
+ onchain_michelson (List[any]): On-chain Michelson representation in the micheline (JSON) format.
559
+ Can be obtained from `sp.get_michelson_code()`.
560
+
561
+ Returns:
562
+ A tuple containing the generated michelson and details of the first difference
563
+ if a mismatch is found (diff path, generated value, onchain value), or None if
564
+ the generated code matches the on-chain code.
565
+
566
+ Raises:
567
+ CodeMismatchException: If the generated code from metadata does not match the on-chain code.
568
+ The exception contains the generated michelson and details of the first difference.
569
+
570
+ Example:
571
+ >>> import smartpy as sp
572
+ ...
573
+ ... address = "KT1EQLe6AbouoX9RhFYHKeYQUAGAdGyFJXoi"
574
+ ... metadata = sp.get_metadata(address, network="ghostnet")
575
+ ... code_metadata = sp.get_metadata_code(metadata)
576
+ ... onchain_michelson = sp.get_michelson_code(address, network="ghostnet")
577
+ ... try:
578
+ ... sp.check_validity(metadata, code_metadata, onchain_michelson)
579
+ ... print("Metadata code is valid")
580
+ ... except CodeMismatchException as e:
581
+ ... print(e)
582
+ ... print("Generated michelson:", e.generated_michelson)
583
+ ... print("Details of the first difference:", e.diff_details)
584
+ """
585
+
586
+ def get_value_at_path(micheline, diff_path):
587
+ for p in diff_path:
588
+ micheline = micheline[p]
589
+ return micheline
590
+
591
+ generated_michelson = normalize_micheline(
592
+ instantiate_from_metadata(metadata, code_metadata)
593
+ )
594
+ onchain_michelson = normalize_micheline(onchain_michelson)
595
+ is_equal, first_diff = are_equivalent_micheline(
596
+ generated_michelson, onchain_michelson
597
+ )
598
+ if not is_equal:
599
+ raise CodeMismatchException(
600
+ generated_michelson,
601
+ (
602
+ first_diff,
603
+ get_value_at_path(generated_michelson, first_diff),
604
+ get_value_at_path(onchain_michelson, first_diff),
605
+ get_value_at_path(generated_michelson, first_diff),
606
+ ),
607
+ )
608
+
609
+
610
+ # decorator for inline modules
611
+ def module(f):
612
+ load_library_id_needed()
613
+ if get_disabled_server():
614
+ return None
615
+ else:
616
+ filename = make_relative(f.__code__.co_filename)
617
+ line_no = LineNo(filename, f.__code__.co_firstlineno)
618
+ code = inspect.getsource(f.__code__)
619
+ return Module.make_inline_module(filename, line_no.line_no - 1, 0, code)
620
+
621
+
622
+ class _Stdlib:
623
+ def __init__(self):
624
+ self.utils = Scenario._load("smartpy/stdlib/utils.spy")
625
+ self.statistics = Scenario._load("smartpy/stdlib/statistics.spy")
626
+ self.math = Scenario._load("smartpy/stdlib/math.spy")
627
+ self.rational = Scenario._load("smartpy/stdlib/rational.spy")
628
+ self.fp = Scenario._load("smartpy/stdlib/fixed_point.spy")
629
+ self.list_utils = Scenario._load("smartpy/stdlib/list_utils.spy")
630
+ self.string_utils = Scenario._load("smartpy/stdlib/string_utils.spy")
631
+ self.address_utils = Scenario._load("smartpy/stdlib/address_utils.spy")
632
+
633
+
634
+ def load_library_id_needed():
635
+ global stdlib, utils, statistics, math, rational, fp, list_utils, string_utils, address_utils
636
+ if stdlib is None:
637
+ if os.environ.get("SMARTPY_NEW_TYPE_CHECKER") is None:
638
+ stdlib = _Stdlib()
639
+ utils = stdlib.utils
640
+ statistics = stdlib.statistics
641
+ math = stdlib.math
642
+ rational = stdlib.rational
643
+ fp = stdlib.fp
644
+ list_utils = stdlib.list_utils
645
+ string_utils = stdlib.string_utils
646
+ address_utils = stdlib.address_utils
647
+ _library_loaded = True
648
+
649
+
650
+ class ParsedExpr(BaseParsedExpr):
651
+ def __init__(self, sexpr):
652
+ self.sexpr = sexpr
653
+
654
+ def export(self):
655
+ return self.sexpr
656
+
657
+
658
+ def expr(e):
659
+ sexpr = parse_via_exe_or_js("<expr>", 0, 0, ParseKind.EXPR, e)
660
+ return ParsedExpr(sexpr)
661
+
662
+
663
+ class Contract:
664
+ def __init_subclass__(cls, **kwargs):
665
+ raise ModuleNotFoundError(
666
+ "`sp.Contract` can only be accessed within a .spy file or a function decorated with @sp.module. Please refer to the SmartPy documentation for more information."
667
+ )
668
+
669
+
670
+ if get_state().environment == Environment.IDE:
671
+ import js
672
+
673
+ js.window.evalRun = evalRun
674
+ js.window.showTraceback = showTraceback
675
+ js.window.toException = toException
676
+
677
+ if hasattr(js.window, "dispatchEvent"):
678
+ js.window.dispatchEvent(js.window.CustomEvent.new("smartpy_ready"))
679
+
680
+
681
+ # -- Handling exceptions --
682
+ def scrub_traceback(tb):
683
+ while tb and tb.tb_frame.f_code.co_filename == __file__:
684
+ tb = tb.tb_next
685
+ if tb:
686
+ tb.tb_next = scrub_traceback(tb.tb_next)
687
+ return tb
688
+
689
+
690
+ def handle_exception(exc_type, exc_value, exc_traceback):
691
+ if not get_debug():
692
+ exc_traceback = scrub_traceback(exc_traceback)
693
+ tb_list = traceback.extract_tb(exc_traceback)
694
+ print("Traceback (most recent call last):", file=sys.stderr)
695
+ for item in tb_list:
696
+ print(
697
+ f' File "{item.filename}", line {item.lineno}, in {item.name}\n {item.line}',
698
+ file=sys.stderr,
699
+ )
700
+ print(f"{exc_type.__name__}: {exc_value}", file=sys.stderr)
701
+
702
+
703
+ sys.excepthook = handle_exception
smartpy/config.py ADDED
@@ -0,0 +1,2 @@
1
+ docker_image = "smartpy"
2
+ version = "0.0.1"