moonproof 0.2.1__py3-none-win_amd64.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.
moonproof/sdk.py ADDED
@@ -0,0 +1,1684 @@
1
+ """Idiomatic Python facade over the generated UniFFI bindings (`_native`).
2
+
3
+ Provides:
4
+ - Native Python value coercion (`to_runtime_value` / `from_runtime_value`) so
5
+ callers pass and receive plain `int`, `str`, `bytes`, `bool`, `list`, `dict`,
6
+ and `None` rather than raw `RuntimeValue` sum wrappers.
7
+ - Synchronous `Chain` / `Contract` (ideal for `pytest`, `unittest`, and CLI
8
+ scripts) AND asynchronous `AsyncChain` / `AsyncContract` (for `asyncio`
9
+ apps and servers), sharing the exact `@moonproof/node` mental model.
10
+ - Context managers (`with chain.batch():`, `with chain.snapshot():`).
11
+ - `iter_stream(stream)` async generator for UniFFI subscription streams.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ from collections.abc import AsyncIterator, Callable, Iterable, Iterator, Mapping
17
+ from contextlib import asynccontextmanager, contextmanager
18
+ from dataclasses import asdict, dataclass, fields, is_dataclass
19
+ import inspect
20
+ from typing import Any, Optional, Union
21
+
22
+ from . import _native
23
+ from ._native import (
24
+ Account,
25
+ ActionRecordDto,
26
+ Artifact,
27
+ BalanceChange,
28
+ CallEffects,
29
+ CallWithDiffResult,
30
+ CircuitProfileRecord,
31
+ ContractEvent,
32
+ ContractStateDiffRecord,
33
+ DeployOptions,
34
+ FieldChangeRecord,
35
+ HolderRef,
36
+ InvariantActionSpec,
37
+ InvariantConfigRecord,
38
+ InvariantFailureDto,
39
+ InvariantReportDto,
40
+ InvariantSession,
41
+ InvariantStep,
42
+ LandedTx,
43
+ LedgerContractSnapshotRecord,
44
+ RuntimeValue,
45
+ RuntimeValueEntry,
46
+ StaticAuditReportRecord,
47
+ StaticFindingRecord,
48
+ TestkitError,
49
+ WitnessCallRecord,
50
+ Witnesses,
51
+ ZkirCheckReportRecord,
52
+ )
53
+
54
+ NIGHT: str = _native.night_token()
55
+
56
+
57
+ def to_runtime_value(value: Any) -> RuntimeValue:
58
+ """Convert a native Python value (or existing RuntimeValue) to RuntimeValue."""
59
+ if isinstance(value, RuntimeValue):
60
+ return value
61
+ if value is None:
62
+ return RuntimeValue.NULL()
63
+ if isinstance(value, bool):
64
+ return RuntimeValue.BOOL(value=value)
65
+ if isinstance(value, int):
66
+ return RuntimeValue.INT(value=str(value))
67
+ if isinstance(value, (bytes, bytearray, memoryview)):
68
+ return RuntimeValue.BYTES(value=bytes(value))
69
+ if isinstance(value, str):
70
+ return RuntimeValue.STR(value=value)
71
+ if isinstance(value, (list, tuple)):
72
+ return RuntimeValue.ARRAY(items=[to_runtime_value(v) for v in value])
73
+ if isinstance(value, dict):
74
+ return RuntimeValue.OBJECT(
75
+ entries=[
76
+ RuntimeValueEntry(key=str(k), value=to_runtime_value(v))
77
+ for k, v in value.items()
78
+ ]
79
+ )
80
+ if hasattr(_native, "JubjubPoint") and isinstance(value, (_native.JubjubPoint, _native.Curve25519Point)):
81
+ return RuntimeValue.OBJECT(
82
+ entries=[
83
+ RuntimeValueEntry(key="x", value=RuntimeValue.BYTES(value=bytes(value.x))),
84
+ RuntimeValueEntry(key="y", value=RuntimeValue.BYTES(value=bytes(value.y))),
85
+ ]
86
+ )
87
+ if hasattr(_native, "Secp256k1Point") and isinstance(value, (_native.Secp256k1Point, _native.Secp256r1Point)):
88
+ return RuntimeValue.OBJECT(
89
+ entries=[
90
+ RuntimeValueEntry(key="x", value=RuntimeValue.BYTES(value=bytes(value.x))),
91
+ RuntimeValueEntry(key="y", value=RuntimeValue.BYTES(value=bytes(value.y))),
92
+ RuntimeValueEntry(key="identity", value=RuntimeValue.BOOL(value=value.identity)),
93
+ ]
94
+ )
95
+ if not isinstance(value, type) and hasattr(value, "to_runtime_value") and callable(value.to_runtime_value):
96
+ return value.to_runtime_value()
97
+ if is_dataclass(value) and not isinstance(value, type):
98
+ return RuntimeValue.OBJECT(
99
+ entries=[
100
+ RuntimeValueEntry(key=f.name, value=to_runtime_value(getattr(value, f.name)))
101
+ for f in fields(value)
102
+ ]
103
+ )
104
+ raise TypeError(f"cannot convert {type(value).__name__!r} to moonproof RuntimeValue")
105
+
106
+
107
+ def from_runtime_value(value: RuntimeValue) -> Any:
108
+ """Convert a RuntimeValue into a native Python value."""
109
+ if isinstance(value, RuntimeValue.NULL):
110
+ return None
111
+ if isinstance(value, RuntimeValue.BOOL):
112
+ return value.value
113
+ if isinstance(value, RuntimeValue.INT):
114
+ return int(value.value)
115
+ if isinstance(value, RuntimeValue.BYTES):
116
+ return bytes(value.value)
117
+ if isinstance(value, RuntimeValue.STR):
118
+ return value.value
119
+ if isinstance(value, RuntimeValue.ARRAY):
120
+ return [from_runtime_value(item) for item in value.items]
121
+ if isinstance(value, RuntimeValue.OBJECT):
122
+ return {entry.key: from_runtime_value(entry.value) for entry in value.entries}
123
+ return value
124
+
125
+
126
+ def _holder_of(
127
+ chain: _native.Chain,
128
+ target: HolderRef | Account | Contract | AsyncContract | ContractHandle | str,
129
+ ) -> HolderRef:
130
+ if isinstance(target, HolderRef):
131
+ return target
132
+ if isinstance(target, (Contract, AsyncContract)):
133
+ return target.holder
134
+ if isinstance(target, ContractHandle):
135
+ return target.holder
136
+ if isinstance(target, Account):
137
+ return HolderRef.USER(address=target.user_address_hex)
138
+ if isinstance(target, str):
139
+ return chain.holder_for_account(target)
140
+ raise TypeError(
141
+ f"expected HolderRef, Account, Contract, ContractHandle, or account name; got {type(target).__name__}"
142
+ )
143
+
144
+
145
+ def _account_of(chain: _native.Chain, account: str | Account) -> Account:
146
+ if isinstance(account, Account):
147
+ return account
148
+ if isinstance(account, str):
149
+ return chain.account(account)
150
+ raise TypeError(f"expected Account or account name str; got {type(account).__name__}")
151
+
152
+
153
+ def _deploy_options(
154
+ account: str | None = None,
155
+ args: Any = None,
156
+ private_state: Any = None,
157
+ ) -> DeployOptions:
158
+ return DeployOptions(
159
+ account=account,
160
+ args=None if args is None else to_runtime_value(args),
161
+ private_state=None if private_state is None else to_runtime_value(private_state),
162
+ )
163
+
164
+
165
+ class _CallableList(list):
166
+ """A `list` that also supports zero-arg call syntax (`x()` == `x`)."""
167
+
168
+ def __call__(self) -> _CallableList:
169
+ return self
170
+
171
+
172
+ class Receipt:
173
+ """Ergonomic wrapper over a UniFFI `Receipt`."""
174
+
175
+ def __init__(self, raw: _native.Receipt) -> None:
176
+ self._raw = raw
177
+
178
+ @property
179
+ def raw(self) -> _native.Receipt:
180
+ return self._raw
181
+
182
+ @property
183
+ def value(self) -> Any:
184
+ """Decoded Python value returned by the circuit."""
185
+ return from_runtime_value(self._raw.result())
186
+
187
+ @property
188
+ def zkir_reports(self) -> list[ZkirCheckReportRecord]:
189
+ return _CallableList(self._raw.zkir_reports())
190
+
191
+ @property
192
+ def state_diffs(self) -> list[ContractStateDiffRecord]:
193
+ return _CallableList(self._raw.state_diffs())
194
+
195
+ def result(self) -> RuntimeValue:
196
+ return self._raw.result()
197
+
198
+ def tx_hash(self) -> str | None:
199
+ return self._raw.tx_hash()
200
+
201
+ def block_height(self) -> int | None:
202
+ return self._raw.block_height()
203
+
204
+ def effects(self) -> CallEffects:
205
+ return self._raw.effects()
206
+
207
+ def events(self) -> list[ContractEvent]:
208
+ return self._raw.events()
209
+
210
+ def emitted_kind(self, kind: str) -> bool:
211
+ return self._raw.emitted_kind(kind)
212
+
213
+ def emitted_tag(self, tag: int) -> bool:
214
+ return self._raw.emitted_tag(tag)
215
+
216
+ def balance_change(self, holder: HolderRef, token: str | None = None) -> str:
217
+ return self._raw.balance_change(holder, token)
218
+
219
+ def balance_changes(self) -> list[BalanceChange]:
220
+ return self._raw.balance_changes()
221
+
222
+ def calls(self) -> list[Any]:
223
+ return self._raw.calls()
224
+
225
+ def public_data(self) -> bytes:
226
+ return bytes(self._raw.public_data())
227
+
228
+ def exposes_bytes(self, secret: bytes) -> bool:
229
+ return self._raw.exposes_bytes(bytes(secret))
230
+
231
+ def exposes_string(self, secret: str) -> bool:
232
+ return self._raw.exposes_string(secret)
233
+
234
+ def exposes_int(self, secret: int | str) -> bool:
235
+ return self._raw.exposes_int(str(secret))
236
+
237
+ def exposes(self, secret: bytes | str | int) -> bool:
238
+ if isinstance(secret, (bytes, bytearray)):
239
+ return self._raw.exposes_bytes(bytes(secret))
240
+ if isinstance(secret, str):
241
+ return self._raw.exposes_string(secret)
242
+ if isinstance(secret, int) and not isinstance(secret, bool):
243
+ return self._raw.exposes_int(str(secret))
244
+ raise TypeError("secret must be bytes, str, or int")
245
+
246
+ def __repr__(self) -> str:
247
+ return f"Receipt(tx_hash={self.tx_hash()!r}, block_height={self.block_height()!r})"
248
+
249
+
250
+ class Contract:
251
+ """Synchronous handle to a deployed or joined contract on a [`Chain`]."""
252
+
253
+ def __init__(self, raw: _native.Contract, active_batch_ref: list[int | None] | None = None) -> None:
254
+ self._raw = raw
255
+ self._active_batch = active_batch_ref if active_batch_ref is not None else [None]
256
+
257
+ @property
258
+ def raw(self) -> _native.Contract:
259
+ return self._raw
260
+
261
+ @property
262
+ def name(self) -> str:
263
+ return self._raw.name()
264
+
265
+ @property
266
+ def address(self) -> str:
267
+ return self._raw.address()
268
+
269
+ @property
270
+ def holder(self) -> HolderRef:
271
+ return self._raw.holder()
272
+
273
+ @property
274
+ def account(self) -> Account:
275
+ return self._raw.account()
276
+
277
+ def as_(self, account: str | Account) -> Contract:
278
+ name = account.name if isinstance(account, Account) else account
279
+ return Contract(self._raw.as_account(name), self._active_batch)
280
+
281
+ def as_account(self, account: str | Account) -> Contract:
282
+ return self.as_(account)
283
+
284
+ def call(self, circuit: str, *args: Any) -> Any:
285
+ rv_args = [to_runtime_value(a) for a in args]
286
+ batch_id = self._active_batch[0]
287
+ if batch_id is not None:
288
+ receipt = self._raw.call_in_batch_sync(batch_id, circuit, rv_args)
289
+ return from_runtime_value(receipt.result())
290
+ return from_runtime_value(self._raw.call_sync(circuit, rv_args))
291
+
292
+ def tx(self, circuit: str, *args: Any) -> Receipt:
293
+ rv_args = [to_runtime_value(a) for a in args]
294
+ batch_id = self._active_batch[0]
295
+ if batch_id is not None:
296
+ return Receipt(self._raw.call_in_batch_sync(batch_id, circuit, rv_args))
297
+ return Receipt(self._raw.tx_sync(circuit, rv_args))
298
+
299
+ def tx_with_diff(self, circuit: str, *args: Any) -> CallWithDiffResult:
300
+ """Call `circuit` and return both the `Receipt` and per-contract ledger state diffs."""
301
+ rv_args = [to_runtime_value(a) for a in args]
302
+ res = self._raw.call_with_diff_sync(circuit, rv_args)
303
+ return CallWithDiffResult(receipt=Receipt(res.receipt), diffs=res.diffs)
304
+
305
+ def call_with_diff(self, circuit: str, *args: Any) -> CallWithDiffResult:
306
+ """Call `circuit` and return both the `Receipt` and per-contract ledger state diffs."""
307
+ return self.tx_with_diff(circuit, *args)
308
+
309
+ def prove(self, circuit: str, *args: Any) -> bytes:
310
+ """Generate an unbalanced, ZK-proven `ProvenTx` payload without submitting."""
311
+ rv_args = [to_runtime_value(a) for a in args]
312
+ return bytes(self._raw.prove_sync(circuit, rv_args))
313
+
314
+ def read(self, field: str) -> Any:
315
+ return from_runtime_value(self._raw.read_sync(field))
316
+
317
+ def state(self) -> dict[str, Any]:
318
+ return from_runtime_value(self._raw.state_sync())
319
+
320
+ def private_state(self) -> Any:
321
+ return from_runtime_value(self._raw.private_state_sync())
322
+
323
+ def public_state(self) -> bytes:
324
+ return bytes(self._raw.public_state_sync())
325
+
326
+ def minted_token(self, domain_sep: bytes) -> str:
327
+ return self._raw.minted_token_sync(domain_sep)
328
+
329
+ def merkle_path(self, field: str, leaf: Any, index: int | None = None) -> Any:
330
+ path = self._raw.merkle_path_sync(field, to_runtime_value(leaf), index)
331
+ return None if path is None else from_runtime_value(path)
332
+
333
+ def exposes(self, secret: bytes | str | int) -> bool:
334
+ if isinstance(secret, (bytes, bytearray)):
335
+ return self._raw.exposes_bytes_sync(bytes(secret))
336
+ if isinstance(secret, str):
337
+ return self._raw.exposes_string_sync(secret)
338
+ if isinstance(secret, int) and not isinstance(secret, bool):
339
+ return self._raw.exposes_int_sync(str(secret))
340
+ raise TypeError("secret must be bytes, str, or int")
341
+
342
+ def set_witness(self, name: str, value: Any) -> Contract:
343
+ """Override witness `name` to return `value` on subsequent calls."""
344
+ self._raw.set_witness_sync(name, to_runtime_value(value))
345
+ return self
346
+
347
+ def set_witness_with_state(self, name: str, value: Any, next_state: Any) -> Contract:
348
+ """Override witness `name` to return `value` and advance private state to `next_state`."""
349
+ self._raw.set_witness_with_state_sync(
350
+ name, to_runtime_value(value), to_runtime_value(next_state)
351
+ )
352
+ return self
353
+
354
+ def set_witness_sequence(self, name: str, values: Iterable[Any]) -> Contract:
355
+ """Queue a FIFO sequence of return values for witness `name`."""
356
+ self._raw.set_witness_sequence_sync(name, [to_runtime_value(v) for v in values])
357
+ return self
358
+
359
+ def remove_witness(self, name: str) -> Contract:
360
+ """Remove any dynamic override for witness `name`."""
361
+ self._raw.remove_witness_sync(name)
362
+ return self
363
+
364
+ def clear_witnesses(self) -> Contract:
365
+ """Clear all dynamic witness overrides on this contract."""
366
+ self._raw.clear_witnesses_sync()
367
+ return self
368
+
369
+ def witness_calls(self) -> list[WitnessCallRecord]:
370
+ """Return the recorded log of witness invocations for this contract."""
371
+ return self._raw.witness_calls_sync()
372
+
373
+ def clear_witness_log(self) -> None:
374
+ """Clear the recorded witness invocation log for this contract."""
375
+ self._raw.clear_witness_log_sync()
376
+
377
+ def snapshot_witnesses(self) -> int:
378
+ """Snapshot the current dynamic witness override table."""
379
+ return int(self._raw.snapshot_witnesses_sync())
380
+
381
+ def revert_witnesses(self, snapshot_id: int) -> None:
382
+ """Revert dynamic witness overrides to a previously captured snapshot."""
383
+ self._raw.revert_witnesses_sync(snapshot_id)
384
+
385
+ @contextmanager
386
+ def witness(
387
+ self,
388
+ overrides: Mapping[str, Any] | None = None,
389
+ /,
390
+ **kwargs: Any,
391
+ ) -> Iterator[Contract]:
392
+ """Temporarily override witnesses for the duration of a `with` block; always reverts on exit."""
393
+ merged: dict[str, Any] = {}
394
+ if overrides is not None:
395
+ if not isinstance(overrides, Mapping):
396
+ raise TypeError(f"witness overrides must be a mapping; got {type(overrides).__name__}")
397
+ merged.update(overrides)
398
+ merged.update(kwargs)
399
+ snap = self._raw.snapshot_witnesses_sync()
400
+ try:
401
+ for w_name, w_val in merged.items():
402
+ self._raw.set_witness_sync(w_name, to_runtime_value(w_val))
403
+ yield self
404
+ finally:
405
+ self._raw.revert_witnesses_sync(snap)
406
+
407
+ def static_audit(self) -> StaticAuditReportRecord:
408
+ """Run the static MP001-MP005 privacy and soundness audit on this contract."""
409
+ return self._raw.static_audit_sync()
410
+
411
+ def audit(self) -> StaticAuditReportRecord:
412
+ """Alias for `static_audit()`."""
413
+ return self._raw.static_audit_sync()
414
+
415
+ def assert_privacy_clean(self) -> StaticAuditReportRecord:
416
+ """Run the static privacy audit and raise if any finding fails the threshold."""
417
+ return self._raw.assert_privacy_clean_sync()
418
+
419
+ def remove_verifier_key(self, circuit: str) -> LandedTx | None:
420
+ return self._raw.remove_verifier_key_sync(circuit)
421
+
422
+ def insert_verifier_key(self, circuit: str, verifier_key: bytes) -> LandedTx | None:
423
+ return self._raw.insert_verifier_key_sync(circuit, verifier_key)
424
+
425
+ def replace_authority(self, signing_key: bytes) -> LandedTx | None:
426
+ return self._raw.replace_authority_sync(signing_key)
427
+
428
+
429
+ class Chain:
430
+ """Synchronous simulator or network chain for Python tests and scripts."""
431
+
432
+ def __init__(self, raw: _native.Chain) -> None:
433
+ self._raw = raw
434
+ self._active_batch: list[int | None] = [None]
435
+
436
+ @property
437
+ def raw(self) -> _native.Chain:
438
+ return self._raw
439
+
440
+ @property
441
+ def kind(self) -> str:
442
+ return self._raw.kind()
443
+
444
+ @property
445
+ def zkir_check_enabled(self) -> bool:
446
+ """Whether live ZKIR v3.2 verification runs on every simulated call."""
447
+ return bool(self._raw.zkir_check_enabled())
448
+
449
+ @zkir_check_enabled.setter
450
+ def zkir_check_enabled(self, enabled: bool) -> None:
451
+ self._raw.set_zkir_check(bool(enabled))
452
+
453
+ def set_zkir_check(self, enabled: bool) -> Chain:
454
+ """Enable or disable live ZKIR v3.2 verification on simulated calls."""
455
+ self._raw.set_zkir_check(bool(enabled))
456
+ return self
457
+
458
+ def zkir_check(self, enabled: bool = True) -> Chain:
459
+ """Fluent alias for `set_zkir_check(enabled)`."""
460
+ self._raw.set_zkir_check(bool(enabled))
461
+ return self
462
+
463
+ def deploy(
464
+ self,
465
+ contract: str | Artifact,
466
+ *,
467
+ as_: str | Account | None = None,
468
+ args: Any = None,
469
+ private_state: Any = None,
470
+ witnesses: Witnesses | None = None,
471
+ ) -> Contract:
472
+ account_name = as_.name if isinstance(as_, Account) else as_
473
+ has_opts = (
474
+ account_name is not None
475
+ or args is not None
476
+ or private_state is not None
477
+ or witnesses is not None
478
+ )
479
+ if isinstance(contract, Artifact):
480
+ raw = (
481
+ self._raw.deploy_artifact_with_sync(
482
+ contract, _deploy_options(account_name, args, private_state), witnesses
483
+ )
484
+ if has_opts
485
+ else self._raw.deploy_artifact_sync(contract)
486
+ )
487
+ else:
488
+ raw = (
489
+ self._raw.deploy_with_sync(
490
+ contract, _deploy_options(account_name, args, private_state), witnesses
491
+ )
492
+ if has_opts
493
+ else self._raw.deploy_sync(contract)
494
+ )
495
+ return Contract(raw, self._active_batch)
496
+
497
+ def join(
498
+ self,
499
+ contract: str | Artifact,
500
+ address: str,
501
+ *,
502
+ private_state: Any = None,
503
+ witnesses: Witnesses | None = None,
504
+ ) -> Contract:
505
+ has_opts = private_state is not None or witnesses is not None
506
+ ps = None if private_state is None else to_runtime_value(private_state)
507
+ if isinstance(contract, Artifact):
508
+ raw = (
509
+ self._raw.join_artifact_with_sync(contract, address, ps, witnesses)
510
+ if has_opts
511
+ else self._raw.join_artifact_sync(contract, address)
512
+ )
513
+ else:
514
+ raw = (
515
+ self._raw.join_with_sync(contract, address, ps, witnesses)
516
+ if has_opts
517
+ else self._raw.join_sync(contract, address)
518
+ )
519
+ return Contract(raw, self._active_batch)
520
+
521
+ def account(self, name: str) -> Account:
522
+ return self._raw.account(name)
523
+
524
+ def fund(
525
+ self,
526
+ holder: HolderRef | Account | Contract | ContractHandle | str,
527
+ amount: int,
528
+ token: str | None = None,
529
+ ) -> None:
530
+ self._raw.fund_sync(_holder_of(self._raw, holder), str(amount), token)
531
+
532
+ def deal(
533
+ self,
534
+ holder: HolderRef | Account | Contract | ContractHandle | str,
535
+ amount: int,
536
+ token: str | None = None,
537
+ ) -> None:
538
+ """Set `holder`'s exact balance of `token` (NIGHT by default) to `amount`."""
539
+ self._raw.deal_sync(_holder_of(self._raw, holder), str(amount), token)
540
+
541
+ def balance(
542
+ self,
543
+ holder: HolderRef | Account | Contract | ContractHandle | str,
544
+ token: str | None = None,
545
+ ) -> int:
546
+ return int(self._raw.balance_sync(_holder_of(self._raw, holder), token))
547
+
548
+ def now(self) -> int:
549
+ return int(self._raw.now_sync())
550
+
551
+ def advance(self, seconds: int) -> None:
552
+ self._raw.advance_sync(seconds)
553
+
554
+ def warp(self, timestamp_secs: int) -> None:
555
+ """Set the simulated block timestamp directly to `timestamp_secs`."""
556
+ self._raw.warp_sync(int(timestamp_secs))
557
+
558
+ def prank(self, account: str | Account) -> None:
559
+ """Override the caller identity for the next call only."""
560
+ self._raw.prank_sync(_account_of(self._raw, account))
561
+
562
+ def start_prank(self, account: str | Account) -> None:
563
+ """Override the caller identity for all subsequent calls until `stop_prank()`."""
564
+ self._raw.start_prank_sync(_account_of(self._raw, account))
565
+
566
+ def stop_prank(self) -> None:
567
+ """Clear any active caller-identity override."""
568
+ self._raw.stop_prank_sync()
569
+
570
+ def snapshot(self) -> int:
571
+ return int(self._raw.snapshot_sync())
572
+
573
+ def revert(self, snapshot_id: int) -> None:
574
+ self._raw.revert_sync(snapshot_id)
575
+
576
+ def diff_since(self, snapshot_id: int) -> list[ContractStateDiffRecord]:
577
+ """Compute structured per-contract ledger state diffs since `snapshot_id`."""
578
+ return self._raw.diff_since_sync(snapshot_id)
579
+
580
+ def profiler_summary(self) -> list[CircuitProfileRecord]:
581
+ """Return per-circuit 5D execution & cost profile records."""
582
+ return self._raw.profiler_summary_sync()
583
+
584
+ def profiler_table(self) -> str:
585
+ """Return a formatted Markdown table of per-circuit profiler metrics."""
586
+ return self._raw.profiler_table_sync()
587
+
588
+ def profiler_json(self) -> str:
589
+ """Return profiler metrics serialized as JSON."""
590
+ return self._raw.profiler_json_sync()
591
+
592
+ def reset_profiler(self) -> None:
593
+ """Reset all accumulated profiler metrics on this chain."""
594
+ self._raw.reset_profiler_sync()
595
+
596
+ def inspect_all_ledgers(self) -> list[LedgerContractSnapshotRecord]:
597
+ """Inspect the public ledger fields of every deployed contract on this chain."""
598
+ return self._raw.inspect_all_ledgers_sync()
599
+
600
+ def invariants(self) -> InvariantSuite:
601
+ """Create a declarative/fluent stateful invariant fuzzing suite bound to this chain."""
602
+ return InvariantSuite(self)
603
+
604
+ @contextmanager
605
+ def batch(self) -> Iterator[int]:
606
+ """Run calls inside an atomic batch; commits on clean exit, aborts on exception."""
607
+ batch_id = self._raw.begin_batch_sync()
608
+ prev = self._active_batch[0]
609
+ self._active_batch[0] = batch_id
610
+ try:
611
+ yield batch_id
612
+ except BaseException:
613
+ self._active_batch[0] = prev
614
+ self._raw.abort_batch_sync(batch_id)
615
+ raise
616
+ else:
617
+ self._active_batch[0] = prev
618
+ self._raw.commit_batch_sync(batch_id)
619
+
620
+ @contextmanager
621
+ def snapshot_scope(self) -> Iterator[int]:
622
+ """Take a snapshot and automatically revert when exiting the `with` block."""
623
+ snap = self._raw.snapshot_sync()
624
+ try:
625
+ yield snap
626
+ finally:
627
+ self._raw.revert_sync(snap)
628
+
629
+ @contextmanager
630
+ def prank_scope(self, account: str | Account) -> Iterator[Account]:
631
+ """Act as `account` for the duration of the `with` block; always stops on exit."""
632
+ acc = _account_of(self._raw, account)
633
+ self._raw.start_prank_sync(acc)
634
+ try:
635
+ yield acc
636
+ finally:
637
+ self._raw.stop_prank_sync()
638
+
639
+
640
+ class AsyncContract:
641
+ """Asynchronous handle to a deployed or joined contract on an [`AsyncChain`]."""
642
+
643
+ def __init__(self, raw: _native.Contract, active_batch_ref: list[int | None] | None = None) -> None:
644
+ self._raw = raw
645
+ self._active_batch = active_batch_ref if active_batch_ref is not None else [None]
646
+
647
+ @property
648
+ def raw(self) -> _native.Contract:
649
+ return self._raw
650
+
651
+ @property
652
+ def name(self) -> str:
653
+ return self._raw.name()
654
+
655
+ @property
656
+ def address(self) -> str:
657
+ return self._raw.address()
658
+
659
+ @property
660
+ def holder(self) -> HolderRef:
661
+ return self._raw.holder()
662
+
663
+ @property
664
+ def account(self) -> Account:
665
+ return self._raw.account()
666
+
667
+ def as_(self, account: str | Account) -> AsyncContract:
668
+ name = account.name if isinstance(account, Account) else account
669
+ return AsyncContract(self._raw.as_account(name), self._active_batch)
670
+
671
+ def as_account(self, account: str | Account) -> AsyncContract:
672
+ return self.as_(account)
673
+
674
+ async def call(self, circuit: str, *args: Any) -> Any:
675
+ rv_args = [to_runtime_value(a) for a in args]
676
+ batch_id = self._active_batch[0]
677
+ if batch_id is not None:
678
+ receipt = await self._raw.call_in_batch(batch_id, circuit, rv_args)
679
+ return from_runtime_value(receipt.result())
680
+ return from_runtime_value(await self._raw.call(circuit, rv_args))
681
+
682
+ async def tx(self, circuit: str, *args: Any) -> Receipt:
683
+ rv_args = [to_runtime_value(a) for a in args]
684
+ batch_id = self._active_batch[0]
685
+ if batch_id is not None:
686
+ return Receipt(await self._raw.call_in_batch(batch_id, circuit, rv_args))
687
+ return Receipt(await self._raw.tx(circuit, rv_args))
688
+
689
+ async def tx_with_diff(self, circuit: str, *args: Any) -> CallWithDiffResult:
690
+ """Call `circuit` and return both the `Receipt` and per-contract ledger state diffs."""
691
+ rv_args = [to_runtime_value(a) for a in args]
692
+ res = await self._raw.call_with_diff(circuit, rv_args)
693
+ return CallWithDiffResult(receipt=Receipt(res.receipt), diffs=res.diffs)
694
+
695
+ async def call_with_diff(self, circuit: str, *args: Any) -> CallWithDiffResult:
696
+ """Call `circuit` and return both the `Receipt` and per-contract ledger state diffs."""
697
+ return await self.tx_with_diff(circuit, *args)
698
+
699
+ async def prove(self, circuit: str, *args: Any) -> bytes:
700
+ """Generate an unbalanced, ZK-proven `ProvenTx` payload without submitting."""
701
+ rv_args = [to_runtime_value(a) for a in args]
702
+ return bytes(await self._raw.prove(circuit, rv_args))
703
+
704
+ async def merkle_path(self, field: str, leaf: Any, index: int | None = None) -> Any:
705
+ path = await self._raw.merkle_path(field, to_runtime_value(leaf), index)
706
+ return None if path is None else from_runtime_value(path)
707
+
708
+ async def read(self, field: str) -> Any:
709
+ return from_runtime_value(await self._raw.read(field))
710
+
711
+ async def state(self) -> dict[str, Any]:
712
+ return from_runtime_value(await self._raw.state())
713
+
714
+ async def private_state(self) -> Any:
715
+ return from_runtime_value(await self._raw.private_state())
716
+
717
+ async def public_state(self) -> bytes:
718
+ return bytes(await self._raw.public_state())
719
+
720
+ async def exposes(self, secret: bytes | str | int) -> bool:
721
+ if isinstance(secret, (bytes, bytearray)):
722
+ return await self._raw.exposes_bytes(bytes(secret))
723
+ if isinstance(secret, str):
724
+ return await self._raw.exposes_string(secret)
725
+ if isinstance(secret, int) and not isinstance(secret, bool):
726
+ return await self._raw.exposes_int(str(secret))
727
+ raise TypeError("secret must be bytes, str, or int")
728
+
729
+ async def set_witness(self, name: str, value: Any) -> AsyncContract:
730
+ await self._raw.set_witness(name, to_runtime_value(value))
731
+ return self
732
+
733
+ async def set_witness_with_state(self, name: str, value: Any, next_state: Any) -> AsyncContract:
734
+ await self._raw.set_witness_with_state(
735
+ name, to_runtime_value(value), to_runtime_value(next_state)
736
+ )
737
+ return self
738
+
739
+ async def set_witness_sequence(self, name: str, values: Iterable[Any]) -> AsyncContract:
740
+ await self._raw.set_witness_sequence(name, [to_runtime_value(v) for v in values])
741
+ return self
742
+
743
+ async def remove_witness(self, name: str) -> AsyncContract:
744
+ await self._raw.remove_witness(name)
745
+ return self
746
+
747
+ async def clear_witnesses(self) -> AsyncContract:
748
+ await self._raw.clear_witnesses()
749
+ return self
750
+
751
+ async def witness_calls(self) -> list[WitnessCallRecord]:
752
+ return await self._raw.witness_calls()
753
+
754
+ async def clear_witness_log(self) -> None:
755
+ await self._raw.clear_witness_log()
756
+
757
+ async def snapshot_witnesses(self) -> int:
758
+ return int(await self._raw.snapshot_witnesses())
759
+
760
+ async def revert_witnesses(self, snapshot_id: int) -> None:
761
+ await self._raw.revert_witnesses(snapshot_id)
762
+
763
+ @asynccontextmanager
764
+ async def witness(
765
+ self,
766
+ overrides: Mapping[str, Any] | None = None,
767
+ /,
768
+ **kwargs: Any,
769
+ ) -> AsyncIterator[AsyncContract]:
770
+ """Temporarily override witnesses for an `async with` block; always reverts on exit."""
771
+ merged: dict[str, Any] = {}
772
+ if overrides is not None:
773
+ if not isinstance(overrides, Mapping):
774
+ raise TypeError(f"witness overrides must be a mapping; got {type(overrides).__name__}")
775
+ merged.update(overrides)
776
+ merged.update(kwargs)
777
+ snap = await self._raw.snapshot_witnesses()
778
+ try:
779
+ for w_name, w_val in merged.items():
780
+ await self._raw.set_witness(w_name, to_runtime_value(w_val))
781
+ yield self
782
+ finally:
783
+ await self._raw.revert_witnesses(snap)
784
+
785
+ async def static_audit(self) -> StaticAuditReportRecord:
786
+ return await self._raw.static_audit()
787
+
788
+ async def audit(self) -> StaticAuditReportRecord:
789
+ return await self._raw.static_audit()
790
+
791
+ async def assert_privacy_clean(self) -> StaticAuditReportRecord:
792
+ return await self._raw.assert_privacy_clean()
793
+
794
+
795
+ class AsyncChain:
796
+ """Asynchronous simulator or network chain for `asyncio` applications."""
797
+
798
+ def __init__(self, raw: _native.Chain) -> None:
799
+ self._raw = raw
800
+ self._active_batch: list[int | None] = [None]
801
+
802
+ @property
803
+ def raw(self) -> _native.Chain:
804
+ return self._raw
805
+
806
+ @property
807
+ def kind(self) -> str:
808
+ return self._raw.kind()
809
+
810
+ @property
811
+ def zkir_check_enabled(self) -> bool:
812
+ """Whether live ZKIR v3.2 verification runs on every simulated call."""
813
+ return bool(self._raw.zkir_check_enabled())
814
+
815
+ @zkir_check_enabled.setter
816
+ def zkir_check_enabled(self, enabled: bool) -> None:
817
+ self._raw.set_zkir_check(bool(enabled))
818
+
819
+ def set_zkir_check(self, enabled: bool) -> AsyncChain:
820
+ """Enable or disable live ZKIR v3.2 verification on simulated calls."""
821
+ self._raw.set_zkir_check(bool(enabled))
822
+ return self
823
+
824
+ def zkir_check(self, enabled: bool = True) -> AsyncChain:
825
+ """Fluent alias for `set_zkir_check(enabled)`."""
826
+ self._raw.set_zkir_check(bool(enabled))
827
+ return self
828
+
829
+ async def deploy(
830
+ self,
831
+ contract: str | Artifact,
832
+ *,
833
+ as_: str | Account | None = None,
834
+ args: Any = None,
835
+ private_state: Any = None,
836
+ witnesses: Witnesses | None = None,
837
+ ) -> AsyncContract:
838
+ account_name = as_.name if isinstance(as_, Account) else as_
839
+ has_opts = (
840
+ account_name is not None
841
+ or args is not None
842
+ or private_state is not None
843
+ or witnesses is not None
844
+ )
845
+ if isinstance(contract, Artifact):
846
+ raw = (
847
+ await self._raw.deploy_artifact_with(
848
+ contract, _deploy_options(account_name, args, private_state), witnesses
849
+ )
850
+ if has_opts
851
+ else await self._raw.deploy_artifact(contract)
852
+ )
853
+ else:
854
+ raw = (
855
+ await self._raw.deploy_with(
856
+ contract, _deploy_options(account_name, args, private_state), witnesses
857
+ )
858
+ if has_opts
859
+ else await self._raw.deploy(contract)
860
+ )
861
+ return AsyncContract(raw, self._active_batch)
862
+
863
+ async def join(
864
+ self,
865
+ contract: str | Artifact,
866
+ address: str,
867
+ *,
868
+ private_state: Any = None,
869
+ witnesses: Witnesses | None = None,
870
+ ) -> AsyncContract:
871
+ has_opts = private_state is not None or witnesses is not None
872
+ ps = None if private_state is None else to_runtime_value(private_state)
873
+ if isinstance(contract, Artifact):
874
+ raw = (
875
+ await self._raw.join_artifact_with(contract, address, ps, witnesses)
876
+ if has_opts
877
+ else await self._raw.join_artifact(contract, address)
878
+ )
879
+ else:
880
+ raw = (
881
+ await self._raw.join_with(contract, address, ps, witnesses)
882
+ if has_opts
883
+ else await self._raw.join(contract, address)
884
+ )
885
+ return AsyncContract(raw, self._active_batch)
886
+
887
+ def account(self, name: str) -> Account:
888
+ return self._raw.account(name)
889
+
890
+ async def fund(
891
+ self,
892
+ holder: HolderRef | Account | AsyncContract | ContractHandle | str,
893
+ amount: int,
894
+ token: str | None = None,
895
+ ) -> None:
896
+ await self._raw.fund(_holder_of(self._raw, holder), str(amount), token)
897
+
898
+ async def deal(
899
+ self,
900
+ holder: HolderRef | Account | AsyncContract | ContractHandle | str,
901
+ amount: int,
902
+ token: str | None = None,
903
+ ) -> None:
904
+ """Set `holder`'s exact balance of `token` (NIGHT by default) to `amount`."""
905
+ await self._raw.deal(_holder_of(self._raw, holder), str(amount), token)
906
+
907
+ async def balance(
908
+ self,
909
+ holder: HolderRef | Account | AsyncContract | ContractHandle | str,
910
+ token: str | None = None,
911
+ ) -> int:
912
+ return int(await self._raw.balance(_holder_of(self._raw, holder), token))
913
+
914
+ async def now(self) -> int:
915
+ return int(await self._raw.now())
916
+
917
+ async def advance(self, seconds: int) -> None:
918
+ await self._raw.advance(seconds)
919
+
920
+ async def warp(self, timestamp_secs: int) -> None:
921
+ """Set the simulated block timestamp directly to `timestamp_secs`."""
922
+ await self._raw.warp(int(timestamp_secs))
923
+
924
+ async def prank(self, account: str | Account) -> None:
925
+ """Override the caller identity for the next call only."""
926
+ await self._raw.prank(_account_of(self._raw, account))
927
+
928
+ async def start_prank(self, account: str | Account) -> None:
929
+ """Override the caller identity for all subsequent calls until `stop_prank()`."""
930
+ await self._raw.start_prank(_account_of(self._raw, account))
931
+
932
+ async def stop_prank(self) -> None:
933
+ """Clear any active caller-identity override."""
934
+ await self._raw.stop_prank()
935
+
936
+ async def snapshot(self) -> int:
937
+ return int(await self._raw.snapshot())
938
+
939
+ async def revert(self, snapshot_id: int) -> None:
940
+ await self._raw.revert(snapshot_id)
941
+
942
+ async def diff_since(self, snapshot_id: int) -> list[ContractStateDiffRecord]:
943
+ return await self._raw.diff_since(snapshot_id)
944
+
945
+ async def profiler_summary(self) -> list[CircuitProfileRecord]:
946
+ return await self._raw.profiler_summary()
947
+
948
+ async def profiler_table(self) -> str:
949
+ return await self._raw.profiler_table()
950
+
951
+ async def profiler_json(self) -> str:
952
+ return await self._raw.profiler_json()
953
+
954
+ async def reset_profiler(self) -> None:
955
+ await self._raw.reset_profiler()
956
+
957
+ async def inspect_all_ledgers(self) -> list[LedgerContractSnapshotRecord]:
958
+ return await self._raw.inspect_all_ledgers()
959
+
960
+ def invariants(self) -> AsyncInvariantSuite:
961
+ """Create a declarative/fluent async stateful invariant fuzzing suite bound to this chain."""
962
+ return AsyncInvariantSuite(self)
963
+
964
+ @asynccontextmanager
965
+ async def batch(self) -> AsyncIterator[int]:
966
+ batch_id = await self._raw.begin_batch()
967
+ prev = self._active_batch[0]
968
+ self._active_batch[0] = batch_id
969
+ try:
970
+ yield batch_id
971
+ except BaseException:
972
+ self._active_batch[0] = prev
973
+ await self._raw.abort_batch(batch_id)
974
+ raise
975
+ else:
976
+ self._active_batch[0] = prev
977
+ await self._raw.commit_batch(batch_id)
978
+
979
+ @asynccontextmanager
980
+ async def snapshot_scope(self) -> AsyncIterator[int]:
981
+ snap = await self._raw.snapshot()
982
+ try:
983
+ yield snap
984
+ finally:
985
+ await self._raw.revert(snap)
986
+
987
+ @asynccontextmanager
988
+ async def prank_scope(self, account: str | Account) -> AsyncIterator[Account]:
989
+ """Act as `account` for the duration of the `async with` block; always stops on exit."""
990
+ acc = _account_of(self._raw, account)
991
+ await self._raw.start_prank(acc)
992
+ try:
993
+ yield acc
994
+ finally:
995
+ await self._raw.stop_prank()
996
+
997
+
998
+ def _invoke_action_fn(fn: Callable[..., Any], step_seed: int, step_index: int) -> Any:
999
+ sig = inspect.signature(fn)
1000
+ positional = [
1001
+ p
1002
+ for p in sig.parameters.values()
1003
+ if p.kind in (inspect.Parameter.POSITIONAL_ONLY, inspect.Parameter.POSITIONAL_OR_KEYWORD)
1004
+ ]
1005
+ has_varargs = any(p.kind == inspect.Parameter.VAR_POSITIONAL for p in sig.parameters.values())
1006
+ if has_varargs or len(positional) == 1:
1007
+ return fn(step_seed)
1008
+ if len(positional) == 0:
1009
+ return fn()
1010
+ return fn(step_seed, step_index)
1011
+
1012
+
1013
+ class InvariantSuite:
1014
+ """Declarative and fluent stateful invariant fuzzing suite over a synchronous [`Chain`]."""
1015
+
1016
+ def __init__(self, chain: Chain) -> None:
1017
+ self._chain = chain
1018
+ self._actions: list[tuple[str, int, Callable[..., Any]]] = []
1019
+ self._invariants: list[tuple[str, Callable[[], Any]]] = []
1020
+
1021
+ def add_action(
1022
+ self,
1023
+ name: str,
1024
+ fn: Callable[..., Any],
1025
+ *,
1026
+ weight: int = 1,
1027
+ ) -> InvariantSuite:
1028
+ """Register an action callback with an optional selection `weight` (>= 1)."""
1029
+ if weight < 1:
1030
+ raise ValueError(f"action weight must be >= 1; got {weight}")
1031
+ self._actions.append((name, int(weight), fn))
1032
+ return self
1033
+
1034
+ def action(
1035
+ self,
1036
+ fn_or_name: Callable[..., Any] | str | None = None,
1037
+ *,
1038
+ weight: int = 1,
1039
+ name: str | None = None,
1040
+ ) -> Any:
1041
+ """Decorator registering an invariant action.
1042
+
1043
+ Supports `@suite.action`, `@suite.action(weight=4)`,
1044
+ `@suite.action(name="deposit", weight=4)`, and `@suite.action("deposit", weight=4)`.
1045
+ """
1046
+ if callable(fn_or_name):
1047
+ self.add_action(name or fn_or_name.__name__, fn_or_name, weight=weight)
1048
+ return fn_or_name
1049
+ explicit_name = fn_or_name if isinstance(fn_or_name, str) else name
1050
+
1051
+ def decorator(fn: Callable[..., Any]) -> Callable[..., Any]:
1052
+ self.add_action(explicit_name or fn.__name__, fn, weight=weight)
1053
+ return fn
1054
+
1055
+ return decorator
1056
+
1057
+ def add_invariant(self, name: str, fn: Callable[[], Any]) -> InvariantSuite:
1058
+ """Register an invariant predicate/assertion checked after every successful step."""
1059
+ self._invariants.append((name, fn))
1060
+ return self
1061
+
1062
+ def invariant(
1063
+ self,
1064
+ fn_or_name: Callable[[], Any] | str | None = None,
1065
+ *,
1066
+ name: str | None = None,
1067
+ ) -> Any:
1068
+ """Decorator registering an invariant check.
1069
+
1070
+ Supports `@suite.invariant`, `@suite.invariant(name="...")`, and `@suite.invariant("...")`.
1071
+ """
1072
+ if callable(fn_or_name):
1073
+ self.add_invariant(name or fn_or_name.__name__, fn_or_name)
1074
+ return fn_or_name
1075
+ explicit_name = fn_or_name if isinstance(fn_or_name, str) else name
1076
+
1077
+ def decorator(fn: Callable[[], Any]) -> Callable[[], Any]:
1078
+ self.add_invariant(explicit_name or fn.__name__, fn)
1079
+ return fn
1080
+
1081
+ return decorator
1082
+
1083
+ def run(
1084
+ self,
1085
+ *,
1086
+ runs: int = 32,
1087
+ depth: int = 16,
1088
+ seed: int = 0x5EED,
1089
+ max_shrink_steps: int = 64,
1090
+ ) -> InvariantReportDto:
1091
+ """Execute the stateful invariant fuzzing campaign and return its report."""
1092
+ specs = [
1093
+ InvariantActionSpec(name=a_name, weight=weight)
1094
+ for a_name, weight, _ in self._actions
1095
+ ]
1096
+ inv_names = [i_name for i_name, _ in self._invariants]
1097
+ cfg = InvariantConfigRecord(
1098
+ runs=int(runs),
1099
+ depth=int(depth),
1100
+ seed=int(seed),
1101
+ max_shrink_steps=int(max_shrink_steps),
1102
+ )
1103
+ session = self._chain.raw.begin_invariants(specs, inv_names, cfg)
1104
+ while True:
1105
+ step = session.next_step_sync()
1106
+ if step.is_RUN_ACTION():
1107
+ _, _, fn = self._actions[step.action_index]
1108
+ try:
1109
+ res = _invoke_action_fn(fn, step.step_seed, step.step_index)
1110
+ except Exception as exc:
1111
+ session.submit_action_sync(False, str(exc))
1112
+ else:
1113
+ detail = "" if res is None else str(res)
1114
+ session.submit_action_sync(True, detail)
1115
+ elif step.is_CHECK_INVARIANT():
1116
+ inv_name, fn = self._invariants[step.invariant_index]
1117
+ try:
1118
+ res = fn()
1119
+ except Exception as exc:
1120
+ msg = str(exc) or type(exc).__name__
1121
+ session.submit_invariant_sync(msg)
1122
+ else:
1123
+ if res is False:
1124
+ session.submit_invariant_sync(f"invariant `{inv_name}` returned False")
1125
+ else:
1126
+ session.submit_invariant_sync(None)
1127
+ elif step.is_FINISHED():
1128
+ return step.report
1129
+ else: # pragma: no cover
1130
+ raise RuntimeError(f"unexpected InvariantStep variant: {step!r}")
1131
+
1132
+ def assert_holds(
1133
+ self,
1134
+ *,
1135
+ runs: int = 32,
1136
+ depth: int = 16,
1137
+ seed: int = 0x5EED,
1138
+ max_shrink_steps: int = 64,
1139
+ ) -> InvariantReportDto:
1140
+ """Run the invariant campaign and raise `AssertionError` if any invariant fails."""
1141
+ return assert_invariants_hold(
1142
+ self.run(runs=runs, depth=depth, seed=seed, max_shrink_steps=max_shrink_steps)
1143
+ )
1144
+
1145
+
1146
+ class AsyncInvariantSuite:
1147
+ """Declarative and fluent stateful invariant fuzzing suite over an [`AsyncChain`]."""
1148
+
1149
+ def __init__(self, chain: AsyncChain) -> None:
1150
+ self._chain = chain
1151
+ self._actions: list[tuple[str, int, Callable[..., Any]]] = []
1152
+ self._invariants: list[tuple[str, Callable[[], Any]]] = []
1153
+
1154
+ def add_action(
1155
+ self,
1156
+ name: str,
1157
+ fn: Callable[..., Any],
1158
+ *,
1159
+ weight: int = 1,
1160
+ ) -> AsyncInvariantSuite:
1161
+ """Register a sync or async action callback with an optional selection `weight` (>= 1)."""
1162
+ if weight < 1:
1163
+ raise ValueError(f"action weight must be >= 1; got {weight}")
1164
+ self._actions.append((name, int(weight), fn))
1165
+ return self
1166
+
1167
+ def action(
1168
+ self,
1169
+ fn_or_name: Callable[..., Any] | str | None = None,
1170
+ *,
1171
+ weight: int = 1,
1172
+ name: str | None = None,
1173
+ ) -> Any:
1174
+ """Decorator registering a sync or async invariant action."""
1175
+ if callable(fn_or_name):
1176
+ self.add_action(name or fn_or_name.__name__, fn_or_name, weight=weight)
1177
+ return fn_or_name
1178
+ explicit_name = fn_or_name if isinstance(fn_or_name, str) else name
1179
+
1180
+ def decorator(fn: Callable[..., Any]) -> Callable[..., Any]:
1181
+ self.add_action(explicit_name or fn.__name__, fn, weight=weight)
1182
+ return fn
1183
+
1184
+ return decorator
1185
+
1186
+ def add_invariant(self, name: str, fn: Callable[[], Any]) -> AsyncInvariantSuite:
1187
+ """Register a sync or async invariant check."""
1188
+ self._invariants.append((name, fn))
1189
+ return self
1190
+
1191
+ def invariant(
1192
+ self,
1193
+ fn_or_name: Callable[[], Any] | str | None = None,
1194
+ *,
1195
+ name: str | None = None,
1196
+ ) -> Any:
1197
+ """Decorator registering a sync or async invariant check."""
1198
+ if callable(fn_or_name):
1199
+ self.add_invariant(name or fn_or_name.__name__, fn_or_name)
1200
+ return fn_or_name
1201
+ explicit_name = fn_or_name if isinstance(fn_or_name, str) else name
1202
+
1203
+ def decorator(fn: Callable[[], Any]) -> Callable[[], Any]:
1204
+ self.add_invariant(explicit_name or fn.__name__, fn)
1205
+ return fn
1206
+
1207
+ return decorator
1208
+
1209
+ async def run(
1210
+ self,
1211
+ *,
1212
+ runs: int = 32,
1213
+ depth: int = 16,
1214
+ seed: int = 0x5EED,
1215
+ max_shrink_steps: int = 64,
1216
+ ) -> InvariantReportDto:
1217
+ """Execute the async stateful invariant fuzzing campaign and return its report."""
1218
+ specs = [
1219
+ InvariantActionSpec(name=a_name, weight=weight)
1220
+ for a_name, weight, _ in self._actions
1221
+ ]
1222
+ inv_names = [i_name for i_name, _ in self._invariants]
1223
+ cfg = InvariantConfigRecord(
1224
+ runs=int(runs),
1225
+ depth=int(depth),
1226
+ seed=int(seed),
1227
+ max_shrink_steps=int(max_shrink_steps),
1228
+ )
1229
+ session = self._chain.raw.begin_invariants(specs, inv_names, cfg)
1230
+ while True:
1231
+ step = await session.next_step()
1232
+ if step.is_RUN_ACTION():
1233
+ _, _, fn = self._actions[step.action_index]
1234
+ try:
1235
+ res = _invoke_action_fn(fn, step.step_seed, step.step_index)
1236
+ if inspect.isawaitable(res):
1237
+ res = await res
1238
+ except Exception as exc:
1239
+ await session.submit_action(False, str(exc))
1240
+ else:
1241
+ detail = "" if res is None else str(res)
1242
+ await session.submit_action(True, detail)
1243
+ elif step.is_CHECK_INVARIANT():
1244
+ inv_name, fn = self._invariants[step.invariant_index]
1245
+ try:
1246
+ res = fn()
1247
+ if inspect.isawaitable(res):
1248
+ res = await res
1249
+ except Exception as exc:
1250
+ msg = str(exc) or type(exc).__name__
1251
+ await session.submit_invariant(msg)
1252
+ else:
1253
+ if res is False:
1254
+ await session.submit_invariant(f"invariant `{inv_name}` returned False")
1255
+ else:
1256
+ await session.submit_invariant(None)
1257
+ elif step.is_FINISHED():
1258
+ return step.report
1259
+ else: # pragma: no cover
1260
+ raise RuntimeError(f"unexpected InvariantStep variant: {step!r}")
1261
+
1262
+ async def assert_holds(
1263
+ self,
1264
+ *,
1265
+ runs: int = 32,
1266
+ depth: int = 16,
1267
+ seed: int = 0x5EED,
1268
+ max_shrink_steps: int = 64,
1269
+ ) -> InvariantReportDto:
1270
+ """Run the async invariant campaign and raise `AssertionError` if any invariant fails."""
1271
+ return assert_invariants_hold(
1272
+ await self.run(runs=runs, depth=depth, seed=seed, max_shrink_steps=max_shrink_steps)
1273
+ )
1274
+
1275
+
1276
+ def assert_privacy_clean(
1277
+ target: Artifact | Contract | ContractHandle | StaticAuditReportRecord,
1278
+ ) -> StaticAuditReportRecord:
1279
+ """Assert that a static privacy audit report, artifact, or contract has no failing findings."""
1280
+ if isinstance(target, StaticAuditReportRecord):
1281
+ report = target
1282
+ elif isinstance(target, (Artifact, Contract, ContractHandle)):
1283
+ report = target.static_audit()
1284
+ else:
1285
+ raise TypeError(
1286
+ "expected StaticAuditReportRecord, Artifact, Contract, or ContractHandle; "
1287
+ f"got {type(target).__name__}"
1288
+ )
1289
+ if not report.clean:
1290
+ raise AssertionError(
1291
+ f"privacy audit failed for `{report.contract_name}`:\n{report.pretty}"
1292
+ )
1293
+ return report
1294
+
1295
+
1296
+ def assert_invariants_hold(report: InvariantReportDto) -> InvariantReportDto:
1297
+ """Assert that an invariant fuzzing campaign report passed."""
1298
+ if not isinstance(report, InvariantReportDto):
1299
+ raise TypeError(f"expected InvariantReportDto; got {type(report).__name__}")
1300
+ if not report.passed:
1301
+ raise AssertionError(report.pretty or "invariant campaign failed")
1302
+ return report
1303
+
1304
+
1305
+ async def iter_stream(stream: Any) -> AsyncIterator[Any]:
1306
+ """Adapt any UniFFI subscription stream (`next()` -> `Optional[T]`) into an `async for` iterator."""
1307
+ while True:
1308
+ item = await stream.next()
1309
+ if item is None:
1310
+ break
1311
+ yield item
1312
+
1313
+
1314
+ def simulator(project_root: str | None = None, *, zkir_check: bool = False) -> Chain:
1315
+ """Open a fresh in-process simulator (synchronous)."""
1316
+ raw = _native.simulator_at(project_root) if project_root else _native.simulator()
1317
+ chain = Chain(raw)
1318
+ if zkir_check:
1319
+ chain.set_zkir_check(True)
1320
+ return chain
1321
+
1322
+
1323
+ def connect(
1324
+ network: str | None = None,
1325
+ wallet: str | None = None,
1326
+ *,
1327
+ project_root: str | None = None,
1328
+ ) -> Chain:
1329
+ """Connect synchronously to a configured network."""
1330
+ raw = (
1331
+ _native.connect_at_sync(project_root, network, wallet)
1332
+ if project_root
1333
+ else _native.connect_sync(network, wallet)
1334
+ )
1335
+ return Chain(raw)
1336
+
1337
+
1338
+ def chain_from_env() -> Chain:
1339
+ """Open the chain selected by `MOONPROOF_CHAIN` (simulator by default)."""
1340
+ return Chain(_native.chain_from_env_sync())
1341
+
1342
+
1343
+ def async_simulator(project_root: str | None = None, *, zkir_check: bool = False) -> AsyncChain:
1344
+ """Open a fresh in-process simulator with an `asyncio` API."""
1345
+ raw = _native.simulator_at(project_root) if project_root else _native.simulator()
1346
+ chain = AsyncChain(raw)
1347
+ if zkir_check:
1348
+ chain.set_zkir_check(True)
1349
+ return chain
1350
+
1351
+
1352
+ async def async_connect(
1353
+ network: str | None = None,
1354
+ wallet: str | None = None,
1355
+ *,
1356
+ project_root: str | None = None,
1357
+ ) -> AsyncChain:
1358
+ """Connect asynchronously to a configured network."""
1359
+ raw = (
1360
+ await _native.connect_at(project_root, network, wallet)
1361
+ if project_root
1362
+ else await _native.connect(network, wallet)
1363
+ )
1364
+ return AsyncChain(raw)
1365
+
1366
+
1367
+ async def async_chain_from_env() -> AsyncChain:
1368
+ """Open the chain selected by `MOONPROOF_CHAIN` with an `asyncio` API."""
1369
+ return AsyncChain(await _native.chain_from_env())
1370
+
1371
+
1372
+ def load(path: str) -> Artifact:
1373
+ """Load a compiled contract artifact from disk (`.compact`, `managed/<name>/`, or `runtime-ir.cbor`)."""
1374
+ return _native.load_artifact(path)
1375
+
1376
+
1377
+ class WitnessMap(Witnesses):
1378
+ """Declarative dict/callable-backed `Witnesses` implementation with automatic Python coercion."""
1379
+
1380
+ def __init__(self, handlers: dict[str, Any] | None = None) -> None:
1381
+ self._handlers: dict[str, Any] = dict(handlers or {})
1382
+
1383
+ def on(self, name: str, fn: Any) -> WitnessMap:
1384
+ """Register a witness handler (callable taking `()` or `(args,)` or `(args, private_state)`)."""
1385
+ self._handlers[name] = fn
1386
+ return self
1387
+
1388
+ def invoke(
1389
+ self,
1390
+ witness_name: str,
1391
+ args: RuntimeValue,
1392
+ private_state: RuntimeValue,
1393
+ ) -> _native.WitnessInvocation:
1394
+ if witness_name not in self._handlers:
1395
+ raise _native.ContractRuntimeError.Runtime(details=f"unexpected witness `{witness_name}`")
1396
+ fn = self._handlers[witness_name]
1397
+ if callable(fn):
1398
+ import inspect
1399
+
1400
+ sig = inspect.signature(fn)
1401
+ arity = len(sig.parameters)
1402
+ if arity == 0:
1403
+ res = fn()
1404
+ elif arity == 1:
1405
+ res = fn(from_runtime_value(args))
1406
+ else:
1407
+ res = fn(from_runtime_value(args), from_runtime_value(private_state))
1408
+ else:
1409
+ res = fn
1410
+ if isinstance(res, _native.WitnessInvocation):
1411
+ return res
1412
+ if isinstance(res, _native.CompactMerklePathProof):
1413
+ return _native.WitnessInvocation(observed=res.runtime_value, next_private_state=private_state)
1414
+ return _native.WitnessInvocation(observed=to_runtime_value(res), next_private_state=private_state)
1415
+
1416
+
1417
+ def witnesses(handlers: dict[str, Any]) -> WitnessMap:
1418
+ """Build a declarative `WitnessMap` from a `{witness_name: callable_or_value}` mapping."""
1419
+ return WitnessMap(handlers)
1420
+
1421
+
1422
+ def compact_merkle_path(depth: int, leaves: list[bytes], leaf_index: int) -> _native.CompactMerklePathProof:
1423
+ """Build an off-chain Compact `MerkleTreePath<depth, Bytes<32>>` proof."""
1424
+ return _native.compact_merkle_tree_path_bytes32(depth, leaves, leaf_index)
1425
+
1426
+
1427
+ def connect_endpoint(
1428
+ indexer_uri: str,
1429
+ node_ws_url: str,
1430
+ *,
1431
+ network_id: str = "undeployed",
1432
+ proof_server_url: str | None = None,
1433
+ wallet_mnemonic: str | None = None,
1434
+ wallet_seed_hex: str | None = None,
1435
+ ) -> Chain:
1436
+ """Connect synchronously to a live Midnight network without `moonproof.toml`."""
1437
+ cfg = _native.NetworkEndpointConfig(
1438
+ indexer_uri=indexer_uri,
1439
+ node_ws_url=node_ws_url,
1440
+ network_id=network_id,
1441
+ proof_server_url=proof_server_url,
1442
+ wallet_mnemonic=wallet_mnemonic,
1443
+ wallet_seed_hex=wallet_seed_hex,
1444
+ )
1445
+ return Chain(_native.connect_endpoint_sync(cfg))
1446
+
1447
+
1448
+ async def async_connect_endpoint(
1449
+ indexer_uri: str,
1450
+ node_ws_url: str,
1451
+ *,
1452
+ network_id: str = "undeployed",
1453
+ proof_server_url: str | None = None,
1454
+ wallet_mnemonic: str | None = None,
1455
+ wallet_seed_hex: str | None = None,
1456
+ ) -> AsyncChain:
1457
+ """Connect asynchronously to a live Midnight network without `moonproof.toml`."""
1458
+ cfg = _native.NetworkEndpointConfig(
1459
+ indexer_uri=indexer_uri,
1460
+ node_ws_url=node_ws_url,
1461
+ network_id=network_id,
1462
+ proof_server_url=proof_server_url,
1463
+ wallet_mnemonic=wallet_mnemonic,
1464
+ wallet_seed_hex=wallet_seed_hex,
1465
+ )
1466
+ return AsyncChain(await _native.connect_endpoint(cfg))
1467
+
1468
+
1469
+ class CompactCrypto:
1470
+ """Compact off-chain cryptography and encoding helpers matching Compact builtins."""
1471
+
1472
+ @staticmethod
1473
+ def pad32(label: str) -> bytes:
1474
+ return bytes(_native.compact_pad32(label))
1475
+
1476
+ @staticmethod
1477
+ def field_bytes32(value: int) -> bytes:
1478
+ return bytes(_native.compact_field_bytes32(value))
1479
+
1480
+ @staticmethod
1481
+ def persistent_hash(chunks: list[bytes]) -> bytes:
1482
+ return bytes(_native.compact_persistent_hash([bytes(c) for c in chunks]))
1483
+
1484
+ @staticmethod
1485
+ def degrade_to_transient(bytes32: bytes) -> bytes:
1486
+ return bytes(_native.compact_degrade_to_transient(bytes(bytes32)))
1487
+
1488
+ @staticmethod
1489
+ def transient_hash(fields: list[bytes]) -> bytes:
1490
+ return bytes(_native.compact_transient_hash([bytes(f) for f in fields]))
1491
+
1492
+ @staticmethod
1493
+ def leaf_hash(leaf: bytes) -> bytes:
1494
+ return bytes(_native.compact_leaf_hash_bytes32(bytes(leaf)))
1495
+
1496
+ @staticmethod
1497
+ def merkle_path(depth: int, leaves: list[bytes], leaf_index: int) -> _native.CompactMerklePathProof:
1498
+ return _native.compact_merkle_tree_path_bytes32(depth, [bytes(l) for l in leaves], leaf_index)
1499
+
1500
+ @staticmethod
1501
+ def owner_either_coin_pk(coin_public_key: bytes) -> RuntimeValue:
1502
+ return _native.compact_owner_either_coin_pk(bytes(coin_public_key))
1503
+
1504
+ @staticmethod
1505
+ def owner_either_contract(contract_address: bytes) -> RuntimeValue:
1506
+ return _native.compact_owner_either_contract(bytes(contract_address))
1507
+
1508
+
1509
+ def inspect_proven_tx(tx: str | bytes) -> _native.TxInspection:
1510
+ """Decode and structurally inspect a hex- or byte-encoded `ProvenTx`."""
1511
+ if isinstance(tx, (bytes, bytearray, memoryview)):
1512
+ return _native.inspect_proven_tx_bytes(bytes(tx))
1513
+ return _native.inspect_proven_tx_hex(tx)
1514
+
1515
+
1516
+ @dataclass
1517
+ class CircuitContext:
1518
+ contract_address_bytes: bytes
1519
+ contract_state_bytes: bytes
1520
+ private_state: Any
1521
+ coin_public_key_bytes: bytes
1522
+ current_time_secs: int
1523
+ ledger_parameters_bytes: Optional[bytes] = None
1524
+
1525
+
1526
+ @dataclass
1527
+ class CircuitResults:
1528
+ result: Any
1529
+ context: CircuitContext
1530
+ input_bytes: bytes
1531
+ output_bytes: bytes
1532
+
1533
+
1534
+ @dataclass
1535
+ class ConstructorContext:
1536
+ initial_private_state: Any
1537
+ coin_public_key_bytes: bytes
1538
+ signing_key_bytes: Optional[bytes] = None
1539
+
1540
+
1541
+ @dataclass
1542
+ class ConstructorResult:
1543
+ initial_contract_state_bytes: bytes
1544
+ initial_private_state: Any
1545
+
1546
+
1547
+ async def run_initialize(
1548
+ executable: Any,
1549
+ ctx: ConstructorContext,
1550
+ args: RuntimeValue,
1551
+ ) -> ConstructorResult:
1552
+ record = _native.ConstructorContextRecord(
1553
+ initial_private_state=to_runtime_value(ctx.initial_private_state),
1554
+ coin_public_key_bytes=ctx.coin_public_key_bytes,
1555
+ signing_key_bytes=ctx.signing_key_bytes,
1556
+ )
1557
+ res = await executable.initialize(record, args)
1558
+ return ConstructorResult(
1559
+ initial_contract_state_bytes=res.initial_contract_state_bytes,
1560
+ initial_private_state=from_runtime_value(res.initial_private_state),
1561
+ )
1562
+
1563
+
1564
+ async def run_circuit(
1565
+ executable: Any,
1566
+ circuit_name: str,
1567
+ ctx: CircuitContext,
1568
+ args: RuntimeValue,
1569
+ ) -> CircuitResults:
1570
+ record = _native.CircuitCallContextRecord(
1571
+ contract_address_bytes=ctx.contract_address_bytes,
1572
+ private_state=to_runtime_value(ctx.private_state),
1573
+ coin_public_key_bytes=ctx.coin_public_key_bytes,
1574
+ current_time_secs=int(ctx.current_time_secs),
1575
+ ledger_parameters_bytes=ctx.ledger_parameters_bytes,
1576
+ )
1577
+ res = await executable.execute_circuit(circuit_name, record, ctx.contract_state_bytes, args)
1578
+ next_ctx = CircuitContext(
1579
+ contract_address_bytes=ctx.contract_address_bytes,
1580
+ contract_state_bytes=res.next_contract_state_bytes,
1581
+ private_state=from_runtime_value(res.next_private_state),
1582
+ coin_public_key_bytes=ctx.coin_public_key_bytes,
1583
+ current_time_secs=ctx.current_time_secs,
1584
+ ledger_parameters_bytes=ctx.ledger_parameters_bytes,
1585
+ )
1586
+ return CircuitResults(
1587
+ result=res.result,
1588
+ context=next_ctx,
1589
+ input_bytes=res.input_bytes,
1590
+ output_bytes=res.output_bytes,
1591
+ )
1592
+
1593
+
1594
+ class ContractHandle:
1595
+ """Shared base class for codegen-emitted typed contract handles."""
1596
+
1597
+ def __init__(self, contract: Contract) -> None:
1598
+ self._contract: Contract = contract
1599
+
1600
+ @property
1601
+ def contract(self) -> Contract:
1602
+ return self._contract
1603
+
1604
+ @property
1605
+ def address(self) -> str:
1606
+ return self._contract.address
1607
+
1608
+ @property
1609
+ def name(self) -> str:
1610
+ return self._contract.name
1611
+
1612
+ @property
1613
+ def holder(self) -> HolderRef:
1614
+ return self._contract.holder
1615
+
1616
+ @property
1617
+ def account(self) -> Account:
1618
+ return self._contract.account
1619
+
1620
+ def state(self) -> dict[str, Any]:
1621
+ return self._contract.state()
1622
+
1623
+ def private_state(self) -> Any:
1624
+ return self._contract.private_state()
1625
+
1626
+ def public_state(self) -> bytes:
1627
+ return self._contract.public_state()
1628
+
1629
+ def set_witness(self, name: str, value: Any) -> ContractHandle:
1630
+ self._contract.set_witness(name, value)
1631
+ return self
1632
+
1633
+ def set_witness_with_state(self, name: str, value: Any, next_state: Any) -> ContractHandle:
1634
+ self._contract.set_witness_with_state(name, value, next_state)
1635
+ return self
1636
+
1637
+ def set_witness_sequence(self, name: str, values: Iterable[Any]) -> ContractHandle:
1638
+ self._contract.set_witness_sequence(name, values)
1639
+ return self
1640
+
1641
+ def remove_witness(self, name: str) -> ContractHandle:
1642
+ self._contract.remove_witness(name)
1643
+ return self
1644
+
1645
+ def clear_witnesses(self) -> ContractHandle:
1646
+ self._contract.clear_witnesses()
1647
+ return self
1648
+
1649
+ def witness_calls(self) -> list[WitnessCallRecord]:
1650
+ return self._contract.witness_calls()
1651
+
1652
+ def clear_witness_log(self) -> None:
1653
+ self._contract.clear_witness_log()
1654
+
1655
+ def snapshot_witnesses(self) -> int:
1656
+ return self._contract.snapshot_witnesses()
1657
+
1658
+ def revert_witnesses(self, snapshot_id: int) -> None:
1659
+ self._contract.revert_witnesses(snapshot_id)
1660
+
1661
+ @contextmanager
1662
+ def witness(
1663
+ self,
1664
+ overrides: Mapping[str, Any] | None = None,
1665
+ /,
1666
+ **kwargs: Any,
1667
+ ) -> Iterator[ContractHandle]:
1668
+ with self._contract.witness(overrides, **kwargs):
1669
+ yield self
1670
+
1671
+ def tx_with_diff(self, circuit: str, *args: Any) -> CallWithDiffResult:
1672
+ return self._contract.tx_with_diff(circuit, *args)
1673
+
1674
+ def call_with_diff(self, circuit: str, *args: Any) -> CallWithDiffResult:
1675
+ return self._contract.call_with_diff(circuit, *args)
1676
+
1677
+ def static_audit(self) -> StaticAuditReportRecord:
1678
+ return self._contract.static_audit()
1679
+
1680
+ def audit(self) -> StaticAuditReportRecord:
1681
+ return self._contract.audit()
1682
+
1683
+ def assert_privacy_clean(self) -> StaticAuditReportRecord:
1684
+ return self._contract.assert_privacy_clean()