diff --git a/pages/developers/intelligent-contracts/examples/_meta.json b/pages/developers/intelligent-contracts/examples/_meta.json index b525e808..d1d94f5e 100644 --- a/pages/developers/intelligent-contracts/examples/_meta.json +++ b/pages/developers/intelligent-contracts/examples/_meta.json @@ -1,4 +1,5 @@ { + "snippets": "Code Snippets", "storage": "Storage", "user-storage": "User Storage", "llm-hello-world": "LLM Hello World", diff --git a/pages/developers/intelligent-contracts/examples/snippets.mdx b/pages/developers/intelligent-contracts/examples/snippets.mdx new file mode 100644 index 00000000..8154dd5e --- /dev/null +++ b/pages/developers/intelligent-contracts/examples/snippets.mdx @@ -0,0 +1,248 @@ +--- +description: "Explained code snippets for common Intelligent Contract patterns: factory deployment, passing web content to an LLM, and reading from and writing to another contract." +--- + +import { Callout } from 'nextra-theme-docs' + +# Code Snippets + +This page collects short, complete contracts for patterns that come up in almost every GenLayer project. Each snippet is followed by a line-by-line explanation of what it does and why. + +| Snippet | What it shows | +| --- | --- | +| [Factory Pattern](#factory-pattern) | Deploying child contracts from a parent contract with `gl.deploy_contract()` | +| [Pass Web Content to an LLM](#pass-web-content-to-an-llm) | Fetching a page with `gl.nondet.web.get()` and asking an LLM about it | +| [Read from Another Contract](#read-from-another-contract) | Calling another contract's view methods with `.view()` | +| [Write to Another Contract](#write-to-another-contract) | Sending a write call to another contract with `.emit()` | + +For the reference behind these snippets, see [Interacting with Intelligent Contracts](/developers/intelligent-contracts/features/interacting-with-intelligent-contracts), [Web Access](/developers/intelligent-contracts/features/web-access), [Calling LLMs](/developers/intelligent-contracts/features/calling-llms) and the [Equivalence Principle](/developers/intelligent-contracts/equivalence-principle). + +## Factory Pattern + +A factory is a contract that deploys other contracts. Use it when you need many instances of the same contract, for example one escrow per deal or one market per question, and want a single on-chain registry of every instance. + +```python +# { "Depends": "py-genlayer:1jb45aa8ynh2a9c9xn3b7qqh8sm5q93hwfp7jqmwsfhh8jpz09h6" } + +from genlayer import * + + +CHILD_CODE = """ +# { "Depends": "py-genlayer:1jb45aa8ynh2a9c9xn3b7qqh8sm5q93hwfp7jqmwsfhh8jpz09h6" } + +from genlayer import * + + +class Market(gl.Contract): + question: str + owner: Address + + def __init__(self, question: str, owner: str): + self.question = question + self.owner = Address(owner) + + @gl.public.view + def get_question(self) -> str: + return self.question +""" + + +class MarketFactory(gl.Contract): + markets: DynArray[Address] + + def __init__(self): + pass + + @gl.public.write + def create_market(self, question: str) -> None: + child_address = gl.deploy_contract( + code=CHILD_CODE.encode("utf-8"), + args=[question, gl.message.sender_address.as_hex], + salt_nonce=u256(len(self.markets) + 1), + on="accepted", + ) + self.markets.append(child_address) + + @gl.public.view + def get_markets(self) -> list[str]: + return [address.as_hex for address in self.markets] +``` + +### How it works + +- **`CHILD_CODE`**: the source of the contract the factory deploys. It is a regular contract, including its own `Depends` header, stored as a string. You can also read it from a file bundled with the factory, or accept it as a constructor argument and keep it in storage. +- **`markets: DynArray[Address]`**: the factory's registry. Every deployed child address is appended here so clients can discover all instances by calling `get_markets()`. +- **`gl.deploy_contract(...)`** deploys a new contract: + - `code` is the child source as `bytes`, hence `.encode("utf-8")`. + - `args` are passed to the child's `__init__`. Here the caller of `create_market` becomes the market owner. `gl.message.sender_address` is the account that called the factory, not the factory itself. + - `salt_nonce` makes the deployment deterministic: the child address is derived from the factory address and the salt, and `gl.deploy_contract` returns it immediately. Each salt can be used only once per factory, so the snippet derives it from the number of markets already created. The value must not be `0`; with `0` the address is assigned by consensus and `gl.deploy_contract` returns `None`. + - `on="accepted"` deploys the child as soon as the factory transaction is accepted. Use `on="finalized"` (the default) if the child must not exist until the factory transaction can no longer be appealed. +- **Deployment is asynchronous**: the child is created in a separate transaction after `create_market` completes, so you cannot call the child in the same transaction that deploys it. + + +Deployed children are immutable. To change their logic, deploy new children with updated code from the factory. See [Upgradability](/developers/intelligent-contracts/features/upgradability) if a single instance must be upgradable. + + +## Pass Web Content to an LLM + +The most common Intelligent Contract pattern: fetch a web page, give its content to an LLM, and store the LLM's decision on-chain. Validators must agree on the result, so the decision is wrapped in a [non-deterministic block](/developers/intelligent-contracts/features/non-determinism) with a validator function. + +```python +# { "Depends": "py-genlayer:1jb45aa8ynh2a9c9xn3b7qqh8sm5q93hwfp7jqmwsfhh8jpz09h6" } + +from genlayer import * + + +LABELS = ("finance", "sports", "technology", "other") + + +class PageClassifier(gl.Contract): + labels: TreeMap[str, str] + + def __init__(self): + pass + + @gl.public.write + def classify(self, url: str) -> None: + def leader_fn() -> str: + page = gl.nondet.web.get(url).body.decode("utf-8") + prompt = f""" + Read the web page below and classify its main topic. + Answer with exactly one of: {", ".join(LABELS)}. + + Page content: + {page[:5000]} + + Respond only with JSON: {{"label": ""}} + """ + result = gl.nondet.exec_prompt(prompt, response_format="json") + label = result.get("label") if isinstance(result, dict) else None + if label not in LABELS: + raise gl.vm.UserError(f"LLM returned an invalid label: {label!r}") + return label + + def validator_fn(leader_result) -> bool: + if not isinstance(leader_result, gl.vm.Return): + return False + if leader_result.calldata not in LABELS: + return False + try: + return leader_result.calldata == leader_fn() + except gl.vm.UserError: + return False + + self.labels[url] = gl.vm.run_nondet_unsafe(leader_fn, validator_fn) + + @gl.public.view + def get_label(self, url: str) -> str: + return self.labels.get(url, "") +``` + +### How it works + +- **`gl.nondet.web.get(url)`** fetches the page. The response `body` is `bytes`, so it is decoded to text before it goes into the prompt. Use `gl.nondet.web.render(url, mode="text")` instead for pages that need a browser to run JavaScript. +- **`page[:5000]`** truncates the content. Web pages can be large, and a shorter prompt is cheaper and keeps the LLM focused. Pick a limit that fits your use case. +- **`gl.nondet.exec_prompt(prompt, response_format="json")`** runs the prompt and returns the parsed JSON as a `dict`, so there is no manual `json.loads()` on the LLM output. +- **The label is checked against `LABELS`**: asking for one of four labels in the prompt does not guarantee the LLM complies. The leader raises `gl.vm.UserError` if the response is not a `dict` or its `label` is not in the allowed set, so an off-list answer such as `"hacked"` is never returned. +- **The leader returns only the label**, not the whole page or the LLM's wording. Returning a small, well-defined value is what makes consensus possible: two validators can easily agree on `"sports"`, but never on two paragraphs of free text. +- **`validator_fn`** runs on every validator. It rejects the leader's result if the leader failed (`leader_result` is not a `gl.vm.Return`) or returned a label outside `LABELS`. Otherwise it fetches the page, asks the LLM itself and agrees only if it gets the same valid label. Checking the leader's value too means that a faulty or malicious leader cannot get an off-list label accepted, even if a validator's LLM happens to give the same answer. +- **`gl.vm.run_nondet_unsafe(leader_fn, validator_fn)`** ties the two together and returns the agreed label, which is then written to storage. Storage writes happen outside the non-deterministic functions. + + +Web content is untrusted input. A page can contain text that tries to override your instructions. Constrain the output to a fixed set of values, as above, and read [Prompt Injection](/developers/intelligent-contracts/security-and-best-practices/prompt-injection) before using this pattern with user-supplied URLs. + + +If the LLM output is free text and two validators cannot be expected to produce the same value, see [non-comparative validation](/developers/intelligent-contracts/equivalence-principle) and the [GitHub Profile Summary](/developers/intelligent-contracts/examples/github-profile-summary) example. + +## Read from Another Contract + +A contract can call the view methods of any other Intelligent Contract and use the returned value in the same transaction. + +```python +# { "Depends": "py-genlayer:1jb45aa8ynh2a9c9xn3b7qqh8sm5q93hwfp7jqmwsfhh8jpz09h6" } + +from genlayer import * + + +@gl.contract_interface +class Token: + class View: + def get_balance_of(self, owner: str) -> int: ... + + class Write: + pass + + +class BalanceReader(gl.Contract): + token: Address + last_balance: u256 + + def __init__(self, token: str): + self.token = Address(token) + self.last_balance = u256(0) + + @gl.public.write + def record_balance(self, owner: str) -> None: + balance = Token(self.token).view().get_balance_of(owner) + self.last_balance = u256(balance) + + @gl.public.view + def get_balance(self, owner: str) -> int: + return gl.get_contract_at(self.token).view().get_balance_of(owner) +``` + +### How it works + +- **`@gl.contract_interface`** describes the methods of the other contract. Methods under `View` can be called with `.view()`, methods under `Write` with `.emit()`. The interface only gives you type checking and IDE autocompletion; the method bodies are `...`. +- **`Token(self.token)`** creates a typed reference to the contract at that address. +- **`gl.get_contract_at(self.token)`**, used in `get_balance`, is the untyped alternative. It needs no interface and lets you call any method by name, but without type checking. Both produce the same calls at runtime. +- **`.view().get_balance_of(owner)`** calls the view method synchronously and returns its result immediately. The call cannot modify the other contract's state. +- **Reads work from both write and view methods**: `record_balance` stores the value it read, while `get_balance` simply passes it through. +- **Arguments and return values** must be types that can be encoded as calldata, such as `int`, `str`, `bool`, `bytes`, `Address`, lists and dicts. + +## Write to Another Contract + +A contract cannot change another contract's state directly. Instead, it emits a message: a write call that is executed as a separate transaction after the current one. + +```python +# { "Depends": "py-genlayer:1jb45aa8ynh2a9c9xn3b7qqh8sm5q93hwfp7jqmwsfhh8jpz09h6" } + +from genlayer import * + + +@gl.contract_interface +class Counter: + class View: + def get_count(self) -> int: ... + + class Write: + def increment(self, amount: int) -> None: ... + + +class CounterCaller(gl.Contract): + counter: Address + + def __init__(self, counter: str): + self.counter = Address(counter) + + @gl.public.write + def bump(self, amount: int) -> None: + Counter(self.counter).emit(on="finalized").increment(amount) + + @gl.public.write + def bump_untyped(self, amount: int) -> None: + gl.get_contract_at(self.counter).emit(on="accepted").increment(amount) +``` + +### How it works + +- **`.emit(...)`** returns a proxy for the target's write methods. Calling `increment(amount)` on it does not run `increment` now: it queues a message that runs `increment` on the `Counter` contract in a new transaction once the current transaction is accepted or finalized. +- **Nothing is returned**: because the call runs later, you cannot use its result in `bump`. If you need a value back, read it later with `.view()`, or have the target contract emit a message back to the caller. +- **`on="finalized"`** (the default) sends the message only after the current transaction can no longer be appealed. This is the safe choice. +- **`on="accepted"`** sends the message as soon as the transaction is accepted, which is faster. If the transaction is then appealed and re-executed, the message can be sent again, so the receiving method must tolerate duplicate calls. See [Accepted vs Finalized](/developers/intelligent-contracts/features/interacting-with-intelligent-contracts#accepted-vs-finalized). +- **Sending value**: `emit(value=u256(100))` also transfers GEN with the call. The receiving method must be marked `@gl.public.write.payable`. See [Value Transfers](/developers/intelligent-contracts/features/value-transfers). +- **Sender**: inside `increment`, `gl.message.sender_address` is the address of `CounterCaller`, not the account that called `bump`. + + +To call a contract on the EVM chain instead of another Intelligent Contract, use `@gl.evm.contract_interface`. See [Interacting with EVM Contracts](/developers/intelligent-contracts/features/interacting-with-evm-contracts). + diff --git a/pages/developers/intelligent-contracts/features/interacting-with-intelligent-contracts.mdx b/pages/developers/intelligent-contracts/features/interacting-with-intelligent-contracts.mdx index 4c1108fc..0353fb9d 100644 --- a/pages/developers/intelligent-contracts/features/interacting-with-intelligent-contracts.mdx +++ b/pages/developers/intelligent-contracts/features/interacting-with-intelligent-contracts.mdx @@ -6,7 +6,7 @@ description: "Interacting with Intelligent Contracts: get references, call view Interacting with Intelligent Contracts means referencing another contract by address, calling its read-only `view()` methods, emitting asynchronous write messages with `emit()`, and deploying child contracts. -> This page covers syntax for internal messages (IC → IC). See [Messages](/developers/intelligent-contracts/features/messages) for the conceptual model and [Value Transfers](/developers/intelligent-contracts/features/value-transfers) for sending GEN. +> This page covers syntax for internal messages (IC → IC). See [Messages](/developers/intelligent-contracts/features/messages) for the conceptual model and [Value Transfers](/developers/intelligent-contracts/features/value-transfers) for sending GEN. For complete, explained contracts, see [Code Snippets](/developers/intelligent-contracts/examples/snippets). ## Getting Contract References @@ -58,8 +58,8 @@ other.emit(value=u256(100), on='finalized').deposit() ```python gl.deploy_contract(code=contract_code) -salt: u256 = u256(1) # not zero -child_address = gl.deploy_contract(code=contract_code, salt=salt) +salt_nonce: u256 = u256(1) # not zero +child_address = gl.deploy_contract(code=contract_code, salt_nonce=salt_nonce) ``` ## View vs Emit diff --git a/scripts/lint-code-examples.py b/scripts/lint-code-examples.py index dce2221e..b2077dd6 100644 --- a/scripts/lint-code-examples.py +++ b/scripts/lint-code-examples.py @@ -13,6 +13,7 @@ 3. Runner versions should be consistent across all examples 4. GenLayer snippets must be valid Python (syntax check) 5. Marked snippets must pass lint and API checks by default; others are advisory (--lint-snippets) + 6. Behavioural tests for the Code Snippets page (scripts/test-snippets.py) """ import argparse @@ -441,6 +442,15 @@ def main(): print(f" {snippet_warnings} snippet(s) had lint issues (advisory)") print() + # Behavioural tests for the Code Snippets page + if not args.check_versions_only: + print("Running snippet behaviour tests...", flush=True) + test_script = Path(__file__).parent / "test-snippets.py" + result = subprocess.run([sys.executable, str(test_script)]) + if result.returncode != 0: + errors.append("scripts/test-snippets.py failed") + print() + if errors: print(f"✗ {len(errors)} issue(s) found") sys.exit(1) diff --git a/scripts/test-snippets.py b/scripts/test-snippets.py new file mode 100644 index 00000000..a8689f48 --- /dev/null +++ b/scripts/test-snippets.py @@ -0,0 +1,156 @@ +#!/usr/bin/env python3 +"""Behavioural regression tests for contracts on the Code Snippets docs page. + +The snippets are extracted from the MDX source and executed against a minimal +mock of the `genlayer` module, so the tests check the code readers copy. + +Usage: + python scripts/test-snippets.py +""" + +import re +import sys +import types +from pathlib import Path + +SNIPPETS_MDX = ( + Path(__file__).parent.parent + / "pages/developers/intelligent-contracts/examples/snippets.mdx" +) +CODE_BLOCK_RE = re.compile(r"```python\n(.*?)```", re.DOTALL) + + +def extract_contract(class_name: str) -> str: + for code in CODE_BLOCK_RE.findall(SNIPPETS_MDX.read_text()): + if f"class {class_name}(" in code: + return code + raise AssertionError(f"{class_name} snippet not found in {SNIPPETS_MDX}") + + +class Return: + def __init__(self, calldata): + self.calldata = calldata + + +class UserError(Exception): + pass + + +class ConsensusRejected(Exception): + pass + + +def make_genlayer(llm_responses: list): + """Mock genlayer module. `llm_responses` is consumed in call order.""" + + def exec_prompt(prompt, **kwargs): + assert kwargs.get("response_format") == "json" + return llm_responses.pop(0) + + def run_nondet_unsafe(leader_fn, validator_fn): + try: + leader_result = Return(leader_fn()) + except UserError as e: + leader_result = e + if not validator_fn(leader_result): + raise ConsensusRejected(leader_result) + if isinstance(leader_result, UserError): + raise leader_result + return leader_result.calldata + + page = types.SimpleNamespace(body=b"some page") + identity = lambda f: f # noqa: E731 + gl = types.SimpleNamespace( + Contract=object, + public=types.SimpleNamespace(write=identity, view=identity), + nondet=types.SimpleNamespace( + web=types.SimpleNamespace(get=lambda url: page), + exec_prompt=exec_prompt, + ), + vm=types.SimpleNamespace( + Return=Return, UserError=UserError, run_nondet_unsafe=run_nondet_unsafe + ), + ) + module = types.ModuleType("genlayer") + module.gl = gl + module.TreeMap = dict + module.__all__ = ["gl", "TreeMap"] + return module + + +def run_classifier(leader_response, validator_response): + code = extract_contract("PageClassifier") + sys.modules["genlayer"] = make_genlayer([leader_response, validator_response]) + namespace: dict = {} + exec(compile(code, str(SNIPPETS_MDX), "exec"), namespace) + contract = namespace["PageClassifier"]() + contract.labels = {} + contract.classify("https://example.com/") + return contract.get_label("https://example.com/") + + +def expect_rejected(leader_response, validator_response): + try: + label = run_classifier(leader_response, validator_response) + except (UserError, ConsensusRejected): + return + raise AssertionError( + f"expected rejection for leader={leader_response!r} " + f"validator={validator_response!r}, but stored {label!r}" + ) + + +def test_valid_label_is_stored(): + assert run_classifier({"label": "sports"}, {"label": "sports"}) == "sports" + + +def test_out_of_set_label_is_rejected_even_if_validators_agree(): + expect_rejected({"label": "hacked"}, {"label": "hacked"}) + + +def test_validator_rejects_out_of_set_leader_value(): + code = extract_contract("PageClassifier") + sys.modules["genlayer"] = make_genlayer([{"label": "hacked"}]) + namespace: dict = {} + exec(compile(code, str(SNIPPETS_MDX), "exec"), namespace) + gl = sys.modules["genlayer"].gl + captured = {} + + def capture(leader_fn, validator_fn): + captured["validator_fn"] = validator_fn + return "unused" + + gl.vm.run_nondet_unsafe = capture + contract = namespace["PageClassifier"]() + contract.labels = {} + contract.classify("https://example.com/") + # A malicious leader bypasses its own check and returns an off-list label. + assert captured["validator_fn"](Return("hacked")) is False + + +def test_malformed_responses_are_rejected(): + expect_rejected({}, {"label": "sports"}) + expect_rejected(["sports"], {"label": "sports"}) + expect_rejected({"label": None}, {"label": None}) + + +def test_disagreeing_validator_rejects(): + expect_rejected({"label": "sports"}, {"label": "finance"}) + + +def main() -> int: + tests = [(n, f) for n, f in globals().items() if n.startswith("test_")] + failed = 0 + for name, fn in tests: + try: + fn() + print(f" ✓ {name}") + except Exception as e: # noqa: BLE001 - report every failure + failed += 1 + print(f" ✗ {name}: {e}") + print(f"\n{len(tests) - failed}/{len(tests)} snippet tests passed") + return 1 if failed else 0 + + +if __name__ == "__main__": + sys.exit(main())