[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M746YYWM72ZAT4GGJJ9BFBZP":3,"skill-same:01M746YYWM72ZAT4GGJJ9BFBZP":66},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":16,"sourceHtmlUrl":17,"categories":18,"keywords":19,"publishedAt":20,"linkOnly":21,"markdownContent":22,"markdownBody":23,"frontMatter":24,"refName":32,"commitSha":33,"skillDirectory":34,"forksCount":35,"repositoryHtmlUrl":36,"repositoryHomepageUrl":37,"ownerHtmlUrl":38,"ownerBlogUrl":39,"ownerDescription":40,"updatedAt":41,"install":42,"resources":55},"01M746YYWM72ZAT4GGJJ9BFBZP","write-contract",null,"Write production-quality GenLayer intelligent contracts. Always pins concrete GenVM runner version hashes and never uses local-only test\u002Flatest runner aliases. Covers equivalence principles, storage rules, LLM resilience, and cross-contract interaction.","bg-szy\u002FTOP-SKILLS","bg-szy","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F106576190?v=4","01M73A4E8KPV67SFXRY8XZGNBX","ShuZhiyong","01M73A4E96MQ294MHM74TZBVQD",6,"MIT","https:\u002F\u002Fgithub.com\u002Fbg-szy\u002FTOP-SKILLS\u002Fblob\u002Fmaster\u002Fskills\u002Fmarketplace\u002Fwrite-contract__skills-internet-court-write-contract\u002FLICENSE","https:\u002F\u002Fgithub.com\u002Fbg-szy\u002FTOP-SKILLS\u002Fblob\u002Fmaster\u002Fskills\u002Fmarketplace\u002Fwrite-contract__skills-internet-court-write-contract\u002FSKILL.md",[],[],"2026-11-11 15:11:14",false,"---\nname: write-contract\ndescription: Write production-quality GenLayer intelligent contracts. Always pins concrete GenVM runner version hashes and never uses local-only test\u002Flatest runner aliases. Covers equivalence principles, storage rules, LLM resilience, and cross-contract interaction.\nallowed-tools:\n  - Bash\n  - Read\n  - Write\n  - Edit\n  - Grep\n  - Glob\n---\n\n# Write Intelligent Contract\n\nGuidance for writing GenLayer intelligent contracts that pass consensus, handle errors correctly, and survive production.\n\n## Critical: Pin the Runner Version\n\nAll GenLayer networks reject `py-genlayer:test`, `py-genlayer:latest`, and\nunversioned runner aliases. Every generated contract MUST start with a pinned\nrunner dependency header.\n\n```python\n# { \"Depends\": \"py-genlayer:1jb45aa8ynh2a9c9xn3b7qqh8sm5q93hwfp7jqmwsfhh8jpz09h6\" }\n```\n\n`test` and `latest` are local-development aliases for GenLayer runtime\ndevelopers. They may work only in a specially configured local Studio\nenvironment with a GenLayer developer environment variable, but they do not work\non GenLayer networks and must not appear in generated user contracts.\n\nBefore returning any contract code, verify:\n\n- The first line is a pinned `Depends` runner version hash.\n- There is no `py-genlayer:test`.\n- There is no `py-genlayer:latest`.\n- There is no unversioned `py-genlayer`.\n\nAlways lint with `genvm-lint check` after writing or modifying a contract.\n\n## When to Use GenLayer\n\nBefore writing code, decide whether the feature actually needs GenLayer consensus. Recent builder feedback shows many projects start by treating GenLayer as a generic AI backend; push them toward a clear on-chain consensus role.\n\nUse GenLayer when the contract must coordinate or settle around a subjective, external, or AI-mediated judgment that multiple validators should verify independently:\n\n- Dispute resolution where evidence must be evaluated and the result affects escrow, payouts, reputation, or access.\n- Prediction\u002Foracle-style markets where the contract needs an independently validated outcome from external evidence.\n- Compliance, moderation, or scoring workflows where the final decision must be reproducible enough for validator agreement but cannot be reduced to a simple deterministic API call.\n- Autonomous agents that need transparent settlement, appeals, and auditable state transitions rather than a private off-chain decision.\n\nPrefer a normal backend, frontend, or off-chain LLM workflow when:\n\n- The frontend already computes the final answer and GenLayer would only rubber-stamp it.\n- The contract only stores user-provided data with no validator-verifiable judgment.\n- A deterministic smart contract, REST API, or database job can perform the work without AI consensus.\n- The data-fetching\u002Fprompting step is not tied to an on-chain state transition, escrow, payout, or appealable decision.\n\nFor every contract, write down the boundary before implementation:\n\n- **Frontend\u002Fbackend owns:** UI, user auth, indexing, non-authoritative previews, cached market data, and convenience analytics.\n- **GenLayer contract owns:** the minimum state transition that needs consensus, the evidence inputs, the validator comparison rule, the final settlement effect, and any appeal\u002Frotation path.\n- **External sources own:** raw facts or documents; do not treat them as trusted unless validators can re-fetch, normalize, and compare them.\n\nIf the boundary is unclear, create a one-page architecture note before coding: user action -> evidence source -> nondeterministic call -> equivalence principle -> state update -> user-visible settlement.\n\n## Contract Skeleton\n\n```python\n# { \"Depends\": \"py-genlayer:1jb45aa8ynh2a9c9xn3b7qqh8sm5q93hwfp7jqmwsfhh8jpz09h6\" }\n\nfrom genlayer import *\n\nclass MyContract(gl.Contract):\n    # Storage fields — typed, persisted on-chain\n    owner: Address\n    items: TreeMap[str, Item]\n    item_order: DynArray[str]\n\n    def __init__(self, param: str):\n        self.owner = gl.message.sender_account\n\n    @gl.public.view\n    def get_item(self, item_id: str) -> dict:\n        return {\"id\": item_id, \"value\": self.items[item_id].value}\n\n    @gl.public.write\n    def set_item(self, item_id: str, value: str) -> None:\n        if gl.message.sender_account != self.owner:\n            raise gl.UserError(\"Only owner\")\n        self.items[item_id] = Item(value=value)\n        self.item_order.append(item_id)\n```\n\n## Runner Dependencies\n\nThe first line of a contract declares the GenVM Python runner. Always pin a\nspecific runner version hash. All GenLayer networks reject `test`, `latest`, and\nunversioned runner aliases in generated contracts.\n\n### Single-file Python contracts\n\n```python\n# { \"Depends\": \"py-genlayer:1jb45aa8ynh2a9c9xn3b7qqh8sm5q93hwfp7jqmwsfhh8jpz09h6\" }\n```\n\n### Multi-file Python contract packages\n\nUse `py-genlayer-multi` when the contract is packaged across multiple files.\n\n```python\n# { \"Depends\": \"py-genlayer-multi:06zyvrlivjga0d5jlpdbprksc0pa6jmllxvp8s20hq1l512vh5yk\" }\n```\n\n### Contracts using embeddings or semantic search\n\nAdd `py-lib-genlayer-embeddings` before the main Python runner with a `Seq`\nblock.\n\n```python\n# {\n#   \"Seq\": [\n#     { \"Depends\": \"py-lib-genlayer-embeddings:0bmbm3cyfwxsyh454z53vxqjf47wz2q7smcqp1q4g4a6k2kidnyk\" },\n#     { \"Depends\": \"py-genlayer:1jb45aa8ynh2a9c9xn3b7qqh8sm5q93hwfp7jqmwsfhh8jpz09h6\" }\n#   ]\n# }\n```\n\n## Equivalence Principle — Which One to Use\n\nThis is the most critical decision. Pick wrong and consensus will fail or be trivially exploitable.\n\n### Decision Tree\n\n```\nCan validators reproduce the exact same normalized output?\n├── YES → strict_eq\n│         Exact match. Use when outputs are deterministic or can be\n│         canonicalized (e.g., JSON with sort_keys=True).\n│         Examples: blockchain RPC, stable REST APIs.\n│\n└── NO  → Write a custom validator function (run_nondet_unsafe)\n          Default: produce independent evidence. Usually rerun the same task\n          and compare decision fields, derived status, scores, or other stable\n          outputs with explicit tolerances. Only skip the second answer when the\n          validator can judge the leader output against source data and criteria.\n```\n\nGenLayer also provides `prompt_comparative` and `prompt_non_comparative` as convenience wrappers, but most contracts outgrow them quickly. Start with a custom validator function for full flexibility.\n\n### Independent verification by default\n\nFor LLM and web operations, never trust the leader. The validator must verify the substance of the leader's answer using evidence other than the leader's answer alone. In practice that means one of:\n\n- Rerun the same LLM\u002Fweb task and compare the stable decision fields.\n- Fetch the same source data and independently derive the status being stored.\n- Run an explicit comparative LLM judgment over the leader output and validator output.\n- For open-ended outputs, judge the leader output against the same input\u002Fsource data and explicit criteria.\n\nDo not write validators that only check `leader_result.calldata` for a valid JSON shape, allowed enum value, non-empty summary, or confidence in range. That is leader-output-only validation, not consensus. It trusts the leader's substantive answer 100% and only proves that the leader formatted the answer correctly.\n\nNon-comparative validation does not mean \"trust the leader.\" It means the validator does not produce a second candidate answer. It still must read the same input\u002Fsource data and ask whether the leader output is valid under clear criteria. A summary validator, for example, should check whether the proposed summary is faithful to the article, covers the material points, avoids hallucinated facts, and satisfies length\u002Fstyle constraints.\n\nClassification, scoring, extraction, authenticity decisions, safety decisions, ranking, and settlement logic almost always need comparative validation: rerun or independently derive the answer, then compare the decision field, extracted fields, score bucket, or derived status. If the validator only checks that the leader chose an allowed label such as `authentic`, `suspicious`, or `inconclusive`, the leader is deciding alone.\n\n### strict_eq — Deterministic calls only\n\n```python\ndef fetch_balance(self) -> int:\n    def call_rpc():\n        res = gl.nondet.web.post(rpc_url, body=payload, headers=headers)\n        return json.loads(res.body.decode(\"utf-8\"))[\"result\"]\n    return gl.eq_principle.strict_eq(call_rpc)\n```\n\nNever use for LLM calls or web pages that change between requests.\n\n### Custom Validator Function (most common)\n\nThe default choice for non-deterministic operations. You write the leader function and a validator function with your own comparison logic. The validator should independently perform or verify the same substantive task, then compare the result fields that matter.\n\n```python\ndef score_content(self, content: str) -> dict:\n    def leader_fn():\n        analysis = gl.nondet.exec_prompt(prompt, response_format=\"json\")\n        score = _parse_llm_score(analysis)\n        return {\"score\": score, \"analysis\": str(analysis.get(\"analysis\", \"\"))}\n\n    def validator_fn(leaders_res: gl.vm.Result) -> bool:\n        if not isinstance(leaders_res, gl.vm.Return):\n            return _handle_leader_error(leaders_res, leader_fn)\n\n        validator_result = leader_fn()\n        leader_score = leaders_res.calldata[\"score\"]\n        validator_score = validator_result[\"score\"]\n\n        # Gate check: if either is zero (reject), both must agree\n        if (leader_score == 0) != (validator_score == 0):\n            return False\n\n        # Tolerance: within 5x\u002F0.5x bounds\n        if leader_score > 0 and validator_score > 0:\n            ratio = leader_score \u002F validator_score\n            if ratio > 5.0 or ratio \u003C 0.2:\n                return False\n\n        return True\n\n    return gl.vm.run_nondet_unsafe(leader_fn, validator_fn)\n```\n\n### Convenience Wrappers\n\n`prompt_comparative` reruns the task and sends both outputs to an LLM with your principle string. `prompt_non_comparative` does not rerun the task; it asks validators to judge the leader output against input data and criteria. Both are convenient for prototyping but limited - for most production contracts, prefer a custom validator function with explicit comparison logic.\n\nPrefer `prompt_comparative` unless you can explain why independently doing the task again would be meaningless and how the validator will still verify the leader output against source data. If the only reason is \"outputs may differ,\" compare the decision fields, normalize the output, derive a status, or use tolerance instead of dropping comparison entirely.\n\n```python\ndef resolve(self) -> str:\n    def analyze():\n        page = gl.get_webpage(url, mode=\"text\")\n        return gl.exec_prompt(f\"Analyze: {page}\\nReturn JSON with outcome and reasoning.\")\n\n    return gl.eq_principle.prompt_comparative(\n        analyze,\n        principle=\"`outcome` field must be exactly the same. All other fields must be similar.\",\n    )\n```\n\n## Error Classification\n\nClassify errors so validators know how to compare them. This is critical for consensus on failure paths.\n\n```python\nERROR_EXPECTED  = \"[EXPECTED]\"   # Business logic (deterministic) — exact match required\nERROR_EXTERNAL  = \"[EXTERNAL]\"   # External API 4xx (deterministic) — exact match required\nERROR_TRANSIENT = \"[TRANSIENT]\"  # Network\u002F5xx (non-deterministic) — agree if both transient\nERROR_LLM       = \"[LLM_ERROR]\"  # LLM misbehavior — always disagree, force rotation\n```\n\n### Canonical error handler for validators\n\n```python\ndef _handle_leader_error(leaders_res, leader_fn) -> bool:\n    leader_msg = leaders_res.message if hasattr(leaders_res, 'message') else ''\n    try:\n        leader_fn()\n        return False  # Leader errored, validator succeeded — disagree\n    except gl.vm.UserError as e:\n        validator_msg = e.message if hasattr(e, 'message') else str(e)\n        # Deterministic errors: must match exactly\n        if validator_msg.startswith(ERROR_EXPECTED) or validator_msg.startswith(ERROR_EXTERNAL):\n            return validator_msg == leader_msg\n        # Transient: agree if both hit transient failure\n        if validator_msg.startswith(ERROR_TRANSIENT) and leader_msg.startswith(ERROR_TRANSIENT):\n            return True\n        # LLM or unknown: disagree — forces consensus retry\n        return False\n    except Exception:\n        return False\n```\n\n### Applying error prefixes\n\n```python\n# Web requests\nif response.status >= 400 and response.status \u003C 500:\n    raise gl.vm.UserError(f\"{ERROR_EXTERNAL} API returned {response.status}\")\nelif response.status >= 500:\n    raise gl.vm.UserError(f\"{ERROR_TRANSIENT} API temporarily unavailable\")\n\n# LLM responses\nif not isinstance(analysis, dict):\n    raise gl.vm.UserError(f\"{ERROR_LLM} LLM returned non-dict: {type(analysis)}\")\n\n# Business logic\nif user_balance \u003C amount:\n    raise gl.vm.UserError(f\"{ERROR_EXPECTED} Insufficient balance\")\n```\n\n## Storage Rules\n\n### Types — use GenLayer types, not Python builtins\n\n| Python | GenLayer | Notes |\n|--------|----------|-------|\n| `dict` | `TreeMap[K, V]` | O(log n) lookup, persisted |\n| `list` | `DynArray[T]` | Dynamic array, persisted |\n| `int` | `u256` \u002F `i256` | Sized integers for on-chain math |\n| `float` | use with care | See float guidance below |\n| `enum` | `str` | Store `.value`, not the enum itself |\n\n### Floats\n\n- **In nondet blocks**: native floats work, but they're inherently non-deterministic (hardware differences cause rounding variation). Handle this in your validator logic with tolerances or rounding before comparison.\n- **In deterministic blocks**: floats are software-emulated — deterministic but slower.\n- **For cross-chain interop \u002F money**: use `u256` with atto-scale (value × 10^18) — this is standard across all blockchains.\n\n### Dataclasses for complex state\n\n```python\n@allow_storage\n@dataclass\nclass Item:\n    name: str\n    status: str          # Use str, not Enum\n    atto_amount: u256    # Atto-scale (value * 10^18) for money\n    created_at: str      # ISO format string\n    tags: DynArray[str]\n```\n\n### Declaration rules\n\n- **Storage fields are class-level type annotations** — NOT assignments in `__init__`. The type annotation declares the storage slot; `__init__` only sets initial values.\n\n```python\nclass MyContract(gl.Contract):\n    owner: Address            # ← storage field (class-level annotation)\n    items: DynArray[str]      # ← storage field\n    count: u256               # ← storage field\n\n    def __init__(self):\n        self.owner = gl.message.sender_address   # ← initial value only\n        # DynArray\u002FTreeMap don't need initialization — they start empty\n```\n\nWrong:\n```python\ndef __init__(self):\n    self.owner: Address = gl.message.sender_address  # ← NOT a storage field!\n    self.items = []                                    # ← list is not a storage type\n```\n\n### Layout rules\n\n- **Append new fields at END only** if using upgradable contracts. Storage layout is order-sensitive — reordering or inserting fields breaks deployed contracts. See the upgradability docs for details.\n- **Default values for new fields** — existing storage reads zero\u002Fempty for fields added after deployment.\n- **Initialize DynArray\u002FTreeMap by appending** in `__init__`, not by assignment. `self.items = [x]` does not work.\n- **O(1) stat indexes** — maintain a `TreeMap[str, u256]` counter alongside collections for fast counts.\n- **Complex data in DynArray** — for storing structured data (dicts, nested objects), serialize to JSON string: `DynArray[str]` with `json.dumps()`\u002F`json.loads()`.\n\n## LLM Resilience\n\nLLMs return unpredictable formats. Always defensively parse.\n\n```python\ndef _parse_llm_score(analysis: dict) -> int:\n    \"\"\"Extract numeric score from LLM response, handling common variations.\"\"\"\n    if not isinstance(analysis, dict):\n        raise gl.vm.UserError(f\"{ERROR_LLM} Non-dict response: {type(analysis)}\")\n\n    # Key aliasing — LLMs use alternate names\n    raw = analysis.get(\"score\")\n    if raw is None:\n        for alt in (\"rating\", \"points\", \"value\", \"result\"):\n            if alt in analysis:\n                raw = analysis[alt]\n                break\n\n    if raw is None:\n        raise gl.vm.UserError(f\"{ERROR_LLM} Missing 'score'. Keys: {list(analysis.keys())}\")\n\n    # Coerce aggressively — handles int, float, \"3\", \"3.5\", whitespace\n    try:\n        return max(0, int(round(float(str(raw).strip()))))\n    except (ValueError, TypeError):\n        raise gl.vm.UserError(f\"{ERROR_LLM} Non-numeric score: {raw}\")\n```\n\n### JSON cleanup from LLM output\n\n```python\ndef _parse_json(text: str) -> dict:\n    \"\"\"Clean LLM JSON: strip wrapping text, fix trailing commas.\"\"\"\n    import re\n    first = text.find(\"{\")\n    last = text.rfind(\"}\")\n    text = text[first:last + 1]\n    text = re.sub(r\",(?!\\s*?[\\{\\[\\\"\\'\\w])\", \"\", text)  # Remove trailing commas\n    return json.loads(text)\n```\n\n### Always use response_format=\"json\"\n\n```python\nresult = gl.nondet.exec_prompt(task, response_format=\"json\")\n```\n\nThis tells the LLM to return JSON. Still validate and clean — LLMs don't always comply.\n\n## Agentic Pattern — LLM-Generated Code + Deterministic Eval\n\nLLMs can't reliably inspect characters in their input (they hallucinate em dashes, miscount characters, etc.). But they CAN generate correct Python code for these checks. Use `eval()` inside `spawn_sandbox()` to run LLM-generated code deterministically, then feed results back as ground truth.\n\n```python\ndef check_rules(self, text: str, rules: str) -> dict:\n    def run():\n        # Step 1: LLM generates Python checks from natural language rules\n        checks = gl.nondet.exec_prompt(\n            f\"\"\"Generate Python expressions to verify these rules.\nVariable `text` contains the post. Skip subjective rules.\nRules: {rules}\nOutput JSON: {{\"checks\": [{{\"rule\": \"...\", \"expression\": \"...\"}}]}}\"\"\",\n            response_format=\"json\",\n        ).get(\"checks\", [])\n\n        # Step 2: eval() all checks in one sandbox — deterministic, no hallucination\n        def eval_checks():\n            results = []\n            for c in checks:\n                try:\n                    ok = eval(c[\"expression\"], {\n                        \"__builtins__\": {\"len\": len, \"any\": any, \"all\": all, \"str\": str},\n                        \"text\": text,\n                    })\n                    results.append({\"rule\": c[\"rule\"], \"result\": \"SATISFIED\" if ok else \"VIOLATED\"})\n                except Exception:\n                    pass  # skip broken expressions, let LLM handle the rule\n            return results\n\n        check_results = gl.vm.unpack_result(gl.vm.spawn_sandbox(eval_checks))\n\n        # Step 3: LLM scores with ground truth — can't hallucinate what code already verified\n        ground_truth = \"\\n\".join(f\"- {r['rule']}: {r['result']}\" for r in check_results)\n        score = gl.nondet.exec_prompt(\n            f\"\"\"GROUND TRUTH (from code — do NOT override): {ground_truth}\nFor rules not listed, use your judgment.\nPost: {text}  Rules: {rules}\nOutput: {{\"analysis\": \"...\", \"passed\": true\u002Ffalse}}\"\"\",\n            response_format=\"json\",\n        )\n\n        return {\"passed\": score.get(\"passed\", False), \"analysis\": score.get(\"analysis\", \"\"), \"checks\": check_results}\n\n    return gl.eq_principle.prompt_comparative(run, \"Must agree on passed\u002Ffailed and same rule violations\")\n```\n\nWhen to use: any contract where rules are specified in natural language and include character-level or format checks that LLMs are unreliable at (specific punctuation, character counts, URL presence, hashtag limits, etc.).\n\n## Cross-Contract Interaction\n\n### Read from another contract (synchronous)\n\n```python\nother = gl.get_contract_at(Address(other_address))\nvalue = other.view().get_data()\n```\n\n### Write to another contract (asynchronous)\n\n```python\nother = gl.get_contract_at(Address(other_address))\nother.emit(on=\"accepted\").process_data(payload)  # Non-blocking\n```\n\n`emit()` queues the call — it executes after current transaction. Use `on=\"accepted\"` (fast) or `on=\"finalized\"` (safe).\n\n**Warning:** If the current transaction is appealed after `emit()`, the emitted call still happens but the balance may already be decremented.\n\n### Factory pattern — deploy child contracts\n\n```python\ndef __init__(self, num_workers: int):\n    with open(\"\u002Fcontract\u002FWorker.py\", \"rt\") as f:\n        worker_code = f.read()\n\n    for i in range(num_workers):\n        addr = gl.deploy_contract(\n            code=worker_code.encode(\"utf-8\"),\n            args=[i, gl.message.contract_address],\n            salt_nonce=i + 1,\n            on=\"accepted\",\n        )\n        self.worker_addresses.append(addr)\n```\n\nWorkers are immutable after deployment. Code changes require redeploying the factory.\n\n### Cross-chain RPC verification\n\n```python\ndef verify_deposit(self, rpc_url: str, contract_addr: str, call_data: bytes) -> bytes:\n    \"\"\"Verify state on another chain via eth_call.\"\"\"\n    payload = {\n        \"jsonrpc\": \"2.0\", \"id\": 1,\n        \"method\": \"eth_call\",\n        \"params\": [{\"to\": contract_addr, \"data\": \"0x\" + call_data.hex()}, \"latest\"],\n    }\n\n    def fetch():\n        res = gl.nondet.web.post(rpc_url, body=json.dumps(payload).encode(),\n                                  headers={\"Content-Type\": \"application\u002Fjson\"})\n        if res.status != 200:\n            raise gl.vm.UserError(f\"{ERROR_EXTERNAL} RPC failed: {res.status}\")\n        data = json.loads(res.body.decode(\"utf-8\"))\n        if \"error\" in data:\n            raise gl.vm.UserError(f\"{ERROR_EXTERNAL} RPC error: {data['error']}\")\n        hex_result = data.get(\"result\", \"0x\")[2:]\n        return bytes.fromhex(hex_result) if hex_result else b\"\"\n\n    return gl.eq_principle.strict_eq(fetch)\n```\n\n## Web Requests\n\n### Extracting stable fields for consensus\n\nExternal APIs return variable data (timestamps, counts). Extract only stable fields:\n\n```python\ndef leader_fn():\n    res = gl.nondet.web.get(api_url)\n    data = json.loads(res.body.decode(\"utf-8\"))\n    # Only return fields that won't change between leader and validator calls\n    return {\"id\": data[\"id\"], \"login\": data[\"login\"], \"status\": data[\"status\"]}\n    # NOT: follower_count, updated_at, online_status\n```\n\n### Deriving status from variable data\n\nWhen raw data may differ (e.g., CI check counts change), compare derived summaries:\n\n```python\ndef validator_fn(leaders_res: gl.vm.Result) -> bool:\n    validator_checks = leader_fn()\n\n    def derive(checks):\n        if not checks: return \"pending\"\n        for c in checks:\n            if c.get(\"conclusion\") != \"success\": return \"failing\"\n        return \"success\"\n\n    return derive(leaders_res.calldata) == derive(validator_checks)\n```\n\n## Anti-Patterns\n\n| Don't | Do Instead | Why |\n|-------|-----------|-----|\n| `py-genlayer:test`, `py-genlayer:latest`, or unversioned `py-genlayer` | Pin the documented runner version hash | All GenLayer networks reject runner aliases and unpinned dependencies |\n| `strict_eq()` for LLM calls | Custom validator function | LLM outputs are non-deterministic — strict_eq always fails consensus |\n| Store `list` or `dict` | `DynArray[T]` or `TreeMap[K, V]` | Python builtins aren't persistable |\n| Use native `float` for money | Atto-scale `u256` (value * 10^18) | Standard across blockchains for cross-chain interop |\n| Insert fields in the middle of a dataclass | Append at END only (for upgradable contracts) | Storage layout is positional — insertion shifts all subsequent fields |\n| Store `Enum` directly | Store `enum.value` as `str` | Enum type not supported in storage |\n| Ignore LLM response format | Validate type, sanitize JSON, alias keys | LLMs return unpredictable formats |\n| Schema-only or leader-output-only validator for LLM\u002Fweb output | Rerun the task, independently derive the result, or verify against source data | Format checks prove only that JSON is well-formed; they do not verify the leader's answer |\n| `prompt_non_comparative` for classification\u002Fscoring\u002Fextraction decisions | Comparative validator with field-level comparison or tolerance | Decisions need agreement on the substantive result; allowed-label checks let one leader decide alone |\n| Let validator agree on LLM errors | Return `False` (disagree) to force rotation | Agreeing on broken LLM output locks bad state |\n| Use bare `Exception` in contracts | Use `gl.vm.UserError` with error prefix | Bare exceptions become unrecoverable VMError |\n| Compare variable API fields in validators | Extract stable fields or derive status | Timestamps, counts change between calls |\n| O(n) scans over large collections | Maintain TreeMap indexes for O(1) lookups | Transactions have compute limits |\n\n## Testing Strategy\n\n1. **Lint first**: `genvm-lint check contracts\u002Fmy_contract.py`\n2. **Direct mode tests**: Fast (30ms), no server. Tests business logic, validation, state transitions. Validator logic NOT exercised.\n3. **Integration tests**: Slow (seconds-minutes), full consensus. Tests validator agreement, real web\u002FLLM calls. Run before deployment.\n","# Write Intelligent Contract\n\nGuidance for writing GenLayer intelligent contracts that pass consensus, handle errors correctly, and survive production.\n\n## Critical: Pin the Runner Version\n\nAll GenLayer networks reject `py-genlayer:test`, `py-genlayer:latest`, and\nunversioned runner aliases. Every generated contract MUST start with a pinned\nrunner dependency header.\n\n```python\n# { \"Depends\": \"py-genlayer:1jb45aa8ynh2a9c9xn3b7qqh8sm5q93hwfp7jqmwsfhh8jpz09h6\" }\n```\n\n`test` and `latest` are local-development aliases for GenLayer runtime\ndevelopers. They may work only in a specially configured local Studio\nenvironment with a GenLayer developer environment variable, but they do not work\non GenLayer networks and must not appear in generated user contracts.\n\nBefore returning any contract code, verify:\n\n- The first line is a pinned `Depends` runner version hash.\n- There is no `py-genlayer:test`.\n- There is no `py-genlayer:latest`.\n- There is no unversioned `py-genlayer`.\n\nAlways lint with `genvm-lint check` after writing or modifying a contract.\n\n## When to Use GenLayer\n\nBefore writing code, decide whether the feature actually needs GenLayer consensus. Recent builder feedback shows many projects start by treating GenLayer as a generic AI backend; push them toward a clear on-chain consensus role.\n\nUse GenLayer when the contract must coordinate or settle around a subjective, external, or AI-mediated judgment that multiple validators should verify independently:\n\n- Dispute resolution where evidence must be evaluated and the result affects escrow, payouts, reputation, or access.\n- Prediction\u002Foracle-style markets where the contract needs an independently validated outcome from external evidence.\n- Compliance, moderation, or scoring workflows where the final decision must be reproducible enough for validator agreement but cannot be reduced to a simple deterministic API call.\n- Autonomous agents that need transparent settlement, appeals, and auditable state transitions rather than a private off-chain decision.\n\nPrefer a normal backend, frontend, or off-chain LLM workflow when:\n\n- The frontend already computes the final answer and GenLayer would only rubber-stamp it.\n- The contract only stores user-provided data with no validator-verifiable judgment.\n- A deterministic smart contract, REST API, or database job can perform the work without AI consensus.\n- The data-fetching\u002Fprompting step is not tied to an on-chain state transition, escrow, payout, or appealable decision.\n\nFor every contract, write down the boundary before implementation:\n\n- **Frontend\u002Fbackend owns:** UI, user auth, indexing, non-authoritative previews, cached market data, and convenience analytics.\n- **GenLayer contract owns:** the minimum state transition that needs consensus, the evidence inputs, the validator comparison rule, the final settlement effect, and any appeal\u002Frotation path.\n- **External sources own:** raw facts or documents; do not treat them as trusted unless validators can re-fetch, normalize, and compare them.\n\nIf the boundary is unclear, create a one-page architecture note before coding: user action -> evidence source -> nondeterministic call -> equivalence principle -> state update -> user-visible settlement.\n\n## Contract Skeleton\n\n```python\n# { \"Depends\": \"py-genlayer:1jb45aa8ynh2a9c9xn3b7qqh8sm5q93hwfp7jqmwsfhh8jpz09h6\" }\n\nfrom genlayer import *\n\nclass MyContract(gl.Contract):\n    # Storage fields — typed, persisted on-chain\n    owner: Address\n    items: TreeMap[str, Item]\n    item_order: DynArray[str]\n\n    def __init__(self, param: str):\n        self.owner = gl.message.sender_account\n\n    @gl.public.view\n    def get_item(self, item_id: str) -> dict:\n        return {\"id\": item_id, \"value\": self.items[item_id].value}\n\n    @gl.public.write\n    def set_item(self, item_id: str, value: str) -> None:\n        if gl.message.sender_account != self.owner:\n            raise gl.UserError(\"Only owner\")\n        self.items[item_id] = Item(value=value)\n        self.item_order.append(item_id)\n```\n\n## Runner Dependencies\n\nThe first line of a contract declares the GenVM Python runner. Always pin a\nspecific runner version hash. All GenLayer networks reject `test`, `latest`, and\nunversioned runner aliases in generated contracts.\n\n### Single-file Python contracts\n\n```python\n# { \"Depends\": \"py-genlayer:1jb45aa8ynh2a9c9xn3b7qqh8sm5q93hwfp7jqmwsfhh8jpz09h6\" }\n```\n\n### Multi-file Python contract packages\n\nUse `py-genlayer-multi` when the contract is packaged across multiple files.\n\n```python\n# { \"Depends\": \"py-genlayer-multi:06zyvrlivjga0d5jlpdbprksc0pa6jmllxvp8s20hq1l512vh5yk\" }\n```\n\n### Contracts using embeddings or semantic search\n\nAdd `py-lib-genlayer-embeddings` before the main Python runner with a `Seq`\nblock.\n\n```python\n# {\n#   \"Seq\": [\n#     { \"Depends\": \"py-lib-genlayer-embeddings:0bmbm3cyfwxsyh454z53vxqjf47wz2q7smcqp1q4g4a6k2kidnyk\" },\n#     { \"Depends\": \"py-genlayer:1jb45aa8ynh2a9c9xn3b7qqh8sm5q93hwfp7jqmwsfhh8jpz09h6\" }\n#   ]\n# }\n```\n\n## Equivalence Principle — Which One to Use\n\nThis is the most critical decision. Pick wrong and consensus will fail or be trivially exploitable.\n\n### Decision Tree\n\n```\nCan validators reproduce the exact same normalized output?\n├── YES → strict_eq\n│         Exact match. Use when outputs are deterministic or can be\n│         canonicalized (e.g., JSON with sort_keys=True).\n│         Examples: blockchain RPC, stable REST APIs.\n│\n└── NO  → Write a custom validator function (run_nondet_unsafe)\n          Default: produce independent evidence. Usually rerun the same task\n          and compare decision fields, derived status, scores, or other stable\n          outputs with explicit tolerances. Only skip the second answer when the\n          validator can judge the leader output against source data and criteria.\n```\n\nGenLayer also provides `prompt_comparative` and `prompt_non_comparative` as convenience wrappers, but most contracts outgrow them quickly. Start with a custom validator function for full flexibility.\n\n### Independent verification by default\n\nFor LLM and web operations, never trust the leader. The validator must verify the substance of the leader's answer using evidence other than the leader's answer alone. In practice that means one of:\n\n- Rerun the same LLM\u002Fweb task and compare the stable decision fields.\n- Fetch the same source data and independently derive the status being stored.\n- Run an explicit comparative LLM judgment over the leader output and validator output.\n- For open-ended outputs, judge the leader output against the same input\u002Fsource data and explicit criteria.\n\nDo not write validators that only check `leader_result.calldata` for a valid JSON shape, allowed enum value, non-empty summary, or confidence in range. That is leader-output-only validation, not consensus. It trusts the leader's substantive answer 100% and only proves that the leader formatted the answer correctly.\n\nNon-comparative validation does not mean \"trust the leader.\" It means the validator does not produce a second candidate answer. It still must read the same input\u002Fsource data and ask whether the leader output is valid under clear criteria. A summary validator, for example, should check whether the proposed summary is faithful to the article, covers the material points, avoids hallucinated facts, and satisfies length\u002Fstyle constraints.\n\nClassification, scoring, extraction, authenticity decisions, safety decisions, ranking, and settlement logic almost always need comparative validation: rerun or independently derive the answer, then compare the decision field, extracted fields, score bucket, or derived status. If the validator only checks that the leader chose an allowed label such as `authentic`, `suspicious`, or `inconclusive`, the leader is deciding alone.\n\n### strict_eq — Deterministic calls only\n\n```python\ndef fetch_balance(self) -> int:\n    def call_rpc():\n        res = gl.nondet.web.post(rpc_url, body=payload, headers=headers)\n        return json.loads(res.body.decode(\"utf-8\"))[\"result\"]\n    return gl.eq_principle.strict_eq(call_rpc)\n```\n\nNever use for LLM calls or web pages that change between requests.\n\n### Custom Validator Function (most common)\n\nThe default choice for non-deterministic operations. You write the leader function and a validator function with your own comparison logic. The validator should independently perform or verify the same substantive task, then compare the result fields that matter.\n\n```python\ndef score_content(self, content: str) -> dict:\n    def leader_fn():\n        analysis = gl.nondet.exec_prompt(prompt, response_format=\"json\")\n        score = _parse_llm_score(analysis)\n        return {\"score\": score, \"analysis\": str(analysis.get(\"analysis\", \"\"))}\n\n    def validator_fn(leaders_res: gl.vm.Result) -> bool:\n        if not isinstance(leaders_res, gl.vm.Return):\n            return _handle_leader_error(leaders_res, leader_fn)\n\n        validator_result = leader_fn()\n        leader_score = leaders_res.calldata[\"score\"]\n        validator_score = validator_result[\"score\"]\n\n        # Gate check: if either is zero (reject), both must agree\n        if (leader_score == 0) != (validator_score == 0):\n            return False\n\n        # Tolerance: within 5x\u002F0.5x bounds\n        if leader_score > 0 and validator_score > 0:\n            ratio = leader_score \u002F validator_score\n            if ratio > 5.0 or ratio \u003C 0.2:\n                return False\n\n        return True\n\n    return gl.vm.run_nondet_unsafe(leader_fn, validator_fn)\n```\n\n### Convenience Wrappers\n\n`prompt_comparative` reruns the task and sends both outputs to an LLM with your principle string. `prompt_non_comparative` does not rerun the task; it asks validators to judge the leader output against input data and criteria. Both are convenient for prototyping but limited - for most production contracts, prefer a custom validator function with explicit comparison logic.\n\nPrefer `prompt_comparative` unless you can explain why independently doing the task again would be meaningless and how the validator will still verify the leader output against source data. If the only reason is \"outputs may differ,\" compare the decision fields, normalize the output, derive a status, or use tolerance instead of dropping comparison entirely.\n\n```python\ndef resolve(self) -> str:\n    def analyze():\n        page = gl.get_webpage(url, mode=\"text\")\n        return gl.exec_prompt(f\"Analyze: {page}\\nReturn JSON with outcome and reasoning.\")\n\n    return gl.eq_principle.prompt_comparative(\n        analyze,\n        principle=\"`outcome` field must be exactly the same. All other fields must be similar.\",\n    )\n```\n\n## Error Classification\n\nClassify errors so validators know how to compare them. This is critical for consensus on failure paths.\n\n```python\nERROR_EXPECTED  = \"[EXPECTED]\"   # Business logic (deterministic) — exact match required\nERROR_EXTERNAL  = \"[EXTERNAL]\"   # External API 4xx (deterministic) — exact match required\nERROR_TRANSIENT = \"[TRANSIENT]\"  # Network\u002F5xx (non-deterministic) — agree if both transient\nERROR_LLM       = \"[LLM_ERROR]\"  # LLM misbehavior — always disagree, force rotation\n```\n\n### Canonical error handler for validators\n\n```python\ndef _handle_leader_error(leaders_res, leader_fn) -> bool:\n    leader_msg = leaders_res.message if hasattr(leaders_res, 'message') else ''\n    try:\n        leader_fn()\n        return False  # Leader errored, validator succeeded — disagree\n    except gl.vm.UserError as e:\n        validator_msg = e.message if hasattr(e, 'message') else str(e)\n        # Deterministic errors: must match exactly\n        if validator_msg.startswith(ERROR_EXPECTED) or validator_msg.startswith(ERROR_EXTERNAL):\n            return validator_msg == leader_msg\n        # Transient: agree if both hit transient failure\n        if validator_msg.startswith(ERROR_TRANSIENT) and leader_msg.startswith(ERROR_TRANSIENT):\n            return True\n        # LLM or unknown: disagree — forces consensus retry\n        return False\n    except Exception:\n        return False\n```\n\n### Applying error prefixes\n\n```python\n# Web requests\nif response.status >= 400 and response.status \u003C 500:\n    raise gl.vm.UserError(f\"{ERROR_EXTERNAL} API returned {response.status}\")\nelif response.status >= 500:\n    raise gl.vm.UserError(f\"{ERROR_TRANSIENT} API temporarily unavailable\")\n\n# LLM responses\nif not isinstance(analysis, dict):\n    raise gl.vm.UserError(f\"{ERROR_LLM} LLM returned non-dict: {type(analysis)}\")\n\n# Business logic\nif user_balance \u003C amount:\n    raise gl.vm.UserError(f\"{ERROR_EXPECTED} Insufficient balance\")\n```\n\n## Storage Rules\n\n### Types — use GenLayer types, not Python builtins\n\n| Python | GenLayer | Notes |\n|--------|----------|-------|\n| `dict` | `TreeMap[K, V]` | O(log n) lookup, persisted |\n| `list` | `DynArray[T]` | Dynamic array, persisted |\n| `int` | `u256` \u002F `i256` | Sized integers for on-chain math |\n| `float` | use with care | See float guidance below |\n| `enum` | `str` | Store `.value`, not the enum itself |\n\n### Floats\n\n- **In nondet blocks**: native floats work, but they're inherently non-deterministic (hardware differences cause rounding variation). Handle this in your validator logic with tolerances or rounding before comparison.\n- **In deterministic blocks**: floats are software-emulated — deterministic but slower.\n- **For cross-chain interop \u002F money**: use `u256` with atto-scale (value × 10^18) — this is standard across all blockchains.\n\n### Dataclasses for complex state\n\n```python\n@allow_storage\n@dataclass\nclass Item:\n    name: str\n    status: str          # Use str, not Enum\n    atto_amount: u256    # Atto-scale (value * 10^18) for money\n    created_at: str      # ISO format string\n    tags: DynArray[str]\n```\n\n### Declaration rules\n\n- **Storage fields are class-level type annotations** — NOT assignments in `__init__`. The type annotation declares the storage slot; `__init__` only sets initial values.\n\n```python\nclass MyContract(gl.Contract):\n    owner: Address            # ← storage field (class-level annotation)\n    items: DynArray[str]      # ← storage field\n    count: u256               # ← storage field\n\n    def __init__(self):\n        self.owner = gl.message.sender_address   # ← initial value only\n        # DynArray\u002FTreeMap don't need initialization — they start empty\n```\n\nWrong:\n```python\ndef __init__(self):\n    self.owner: Address = gl.message.sender_address  # ← NOT a storage field!\n    self.items = []                                    # ← list is not a storage type\n```\n\n### Layout rules\n\n- **Append new fields at END only** if using upgradable contracts. Storage layout is order-sensitive — reordering or inserting fields breaks deployed contracts. See the upgradability docs for details.\n- **Default values for new fields** — existing storage reads zero\u002Fempty for fields added after deployment.\n- **Initialize DynArray\u002FTreeMap by appending** in `__init__`, not by assignment. `self.items = [x]` does not work.\n- **O(1) stat indexes** — maintain a `TreeMap[str, u256]` counter alongside collections for fast counts.\n- **Complex data in DynArray** — for storing structured data (dicts, nested objects), serialize to JSON string: `DynArray[str]` with `json.dumps()`\u002F`json.loads()`.\n\n## LLM Resilience\n\nLLMs return unpredictable formats. Always defensively parse.\n\n```python\ndef _parse_llm_score(analysis: dict) -> int:\n    \"\"\"Extract numeric score from LLM response, handling common variations.\"\"\"\n    if not isinstance(analysis, dict):\n        raise gl.vm.UserError(f\"{ERROR_LLM} Non-dict response: {type(analysis)}\")\n\n    # Key aliasing — LLMs use alternate names\n    raw = analysis.get(\"score\")\n    if raw is None:\n        for alt in (\"rating\", \"points\", \"value\", \"result\"):\n            if alt in analysis:\n                raw = analysis[alt]\n                break\n\n    if raw is None:\n        raise gl.vm.UserError(f\"{ERROR_LLM} Missing 'score'. Keys: {list(analysis.keys())}\")\n\n    # Coerce aggressively — handles int, float, \"3\", \"3.5\", whitespace\n    try:\n        return max(0, int(round(float(str(raw).strip()))))\n    except (ValueError, TypeError):\n        raise gl.vm.UserError(f\"{ERROR_LLM} Non-numeric score: {raw}\")\n```\n\n### JSON cleanup from LLM output\n\n```python\ndef _parse_json(text: str) -> dict:\n    \"\"\"Clean LLM JSON: strip wrapping text, fix trailing commas.\"\"\"\n    import re\n    first = text.find(\"{\")\n    last = text.rfind(\"}\")\n    text = text[first:last + 1]\n    text = re.sub(r\",(?!\\s*?[\\{\\[\\\"\\'\\w])\", \"\", text)  # Remove trailing commas\n    return json.loads(text)\n```\n\n### Always use response_format=\"json\"\n\n```python\nresult = gl.nondet.exec_prompt(task, response_format=\"json\")\n```\n\nThis tells the LLM to return JSON. Still validate and clean — LLMs don't always comply.\n\n## Agentic Pattern — LLM-Generated Code + Deterministic Eval\n\nLLMs can't reliably inspect characters in their input (they hallucinate em dashes, miscount characters, etc.). But they CAN generate correct Python code for these checks. Use `eval()` inside `spawn_sandbox()` to run LLM-generated code deterministically, then feed results back as ground truth.\n\n```python\ndef check_rules(self, text: str, rules: str) -> dict:\n    def run():\n        # Step 1: LLM generates Python checks from natural language rules\n        checks = gl.nondet.exec_prompt(\n            f\"\"\"Generate Python expressions to verify these rules.\nVariable `text` contains the post. Skip subjective rules.\nRules: {rules}\nOutput JSON: {{\"checks\": [{{\"rule\": \"...\", \"expression\": \"...\"}}]}}\"\"\",\n            response_format=\"json\",\n        ).get(\"checks\", [])\n\n        # Step 2: eval() all checks in one sandbox — deterministic, no hallucination\n        def eval_checks():\n            results = []\n            for c in checks:\n                try:\n                    ok = eval(c[\"expression\"], {\n                        \"__builtins__\": {\"len\": len, \"any\": any, \"all\": all, \"str\": str},\n                        \"text\": text,\n                    })\n                    results.append({\"rule\": c[\"rule\"], \"result\": \"SATISFIED\" if ok else \"VIOLATED\"})\n                except Exception:\n                    pass  # skip broken expressions, let LLM handle the rule\n            return results\n\n        check_results = gl.vm.unpack_result(gl.vm.spawn_sandbox(eval_checks))\n\n        # Step 3: LLM scores with ground truth — can't hallucinate what code already verified\n        ground_truth = \"\\n\".join(f\"- {r['rule']}: {r['result']}\" for r in check_results)\n        score = gl.nondet.exec_prompt(\n            f\"\"\"GROUND TRUTH (from code — do NOT override): {ground_truth}\nFor rules not listed, use your judgment.\nPost: {text}  Rules: {rules}\nOutput: {{\"analysis\": \"...\", \"passed\": true\u002Ffalse}}\"\"\",\n            response_format=\"json\",\n        )\n\n        return {\"passed\": score.get(\"passed\", False), \"analysis\": score.get(\"analysis\", \"\"), \"checks\": check_results}\n\n    return gl.eq_principle.prompt_comparative(run, \"Must agree on passed\u002Ffailed and same rule violations\")\n```\n\nWhen to use: any contract where rules are specified in natural language and include character-level or format checks that LLMs are unreliable at (specific punctuation, character counts, URL presence, hashtag limits, etc.).\n\n## Cross-Contract Interaction\n\n### Read from another contract (synchronous)\n\n```python\nother = gl.get_contract_at(Address(other_address))\nvalue = other.view().get_data()\n```\n\n### Write to another contract (asynchronous)\n\n```python\nother = gl.get_contract_at(Address(other_address))\nother.emit(on=\"accepted\").process_data(payload)  # Non-blocking\n```\n\n`emit()` queues the call — it executes after current transaction. Use `on=\"accepted\"` (fast) or `on=\"finalized\"` (safe).\n\n**Warning:** If the current transaction is appealed after `emit()`, the emitted call still happens but the balance may already be decremented.\n\n### Factory pattern — deploy child contracts\n\n```python\ndef __init__(self, num_workers: int):\n    with open(\"\u002Fcontract\u002FWorker.py\", \"rt\") as f:\n        worker_code = f.read()\n\n    for i in range(num_workers):\n        addr = gl.deploy_contract(\n            code=worker_code.encode(\"utf-8\"),\n            args=[i, gl.message.contract_address],\n            salt_nonce=i + 1,\n            on=\"accepted\",\n        )\n        self.worker_addresses.append(addr)\n```\n\nWorkers are immutable after deployment. Code changes require redeploying the factory.\n\n### Cross-chain RPC verification\n\n```python\ndef verify_deposit(self, rpc_url: str, contract_addr: str, call_data: bytes) -> bytes:\n    \"\"\"Verify state on another chain via eth_call.\"\"\"\n    payload = {\n        \"jsonrpc\": \"2.0\", \"id\": 1,\n        \"method\": \"eth_call\",\n        \"params\": [{\"to\": contract_addr, \"data\": \"0x\" + call_data.hex()}, \"latest\"],\n    }\n\n    def fetch():\n        res = gl.nondet.web.post(rpc_url, body=json.dumps(payload).encode(),\n                                  headers={\"Content-Type\": \"application\u002Fjson\"})\n        if res.status != 200:\n            raise gl.vm.UserError(f\"{ERROR_EXTERNAL} RPC failed: {res.status}\")\n        data = json.loads(res.body.decode(\"utf-8\"))\n        if \"error\" in data:\n            raise gl.vm.UserError(f\"{ERROR_EXTERNAL} RPC error: {data['error']}\")\n        hex_result = data.get(\"result\", \"0x\")[2:]\n        return bytes.fromhex(hex_result) if hex_result else b\"\"\n\n    return gl.eq_principle.strict_eq(fetch)\n```\n\n## Web Requests\n\n### Extracting stable fields for consensus\n\nExternal APIs return variable data (timestamps, counts). Extract only stable fields:\n\n```python\ndef leader_fn():\n    res = gl.nondet.web.get(api_url)\n    data = json.loads(res.body.decode(\"utf-8\"))\n    # Only return fields that won't change between leader and validator calls\n    return {\"id\": data[\"id\"], \"login\": data[\"login\"], \"status\": data[\"status\"]}\n    # NOT: follower_count, updated_at, online_status\n```\n\n### Deriving status from variable data\n\nWhen raw data may differ (e.g., CI check counts change), compare derived summaries:\n\n```python\ndef validator_fn(leaders_res: gl.vm.Result) -> bool:\n    validator_checks = leader_fn()\n\n    def derive(checks):\n        if not checks: return \"pending\"\n        for c in checks:\n            if c.get(\"conclusion\") != \"success\": return \"failing\"\n        return \"success\"\n\n    return derive(leaders_res.calldata) == derive(validator_checks)\n```\n\n## Anti-Patterns\n\n| Don't | Do Instead | Why |\n|-------|-----------|-----|\n| `py-genlayer:test`, `py-genlayer:latest`, or unversioned `py-genlayer` | Pin the documented runner version hash | All GenLayer networks reject runner aliases and unpinned dependencies |\n| `strict_eq()` for LLM calls | Custom validator function | LLM outputs are non-deterministic — strict_eq always fails consensus |\n| Store `list` or `dict` | `DynArray[T]` or `TreeMap[K, V]` | Python builtins aren't persistable |\n| Use native `float` for money | Atto-scale `u256` (value * 10^18) | Standard across blockchains for cross-chain interop |\n| Insert fields in the middle of a dataclass | Append at END only (for upgradable contracts) | Storage layout is positional — insertion shifts all subsequent fields |\n| Store `Enum` directly | Store `enum.value` as `str` | Enum type not supported in storage |\n| Ignore LLM response format | Validate type, sanitize JSON, alias keys | LLMs return unpredictable formats |\n| Schema-only or leader-output-only validator for LLM\u002Fweb output | Rerun the task, independently derive the result, or verify against source data | Format checks prove only that JSON is well-formed; they do not verify the leader's answer |\n| `prompt_non_comparative` for classification\u002Fscoring\u002Fextraction decisions | Comparative validator with field-level comparison or tolerance | Decisions need agreement on the substantive result; allowed-label checks let one leader decide alone |\n| Let validator agree on LLM errors | Return `False` (disagree) to force rotation | Agreeing on broken LLM output locks bad state |\n| Use bare `Exception` in contracts | Use `gl.vm.UserError` with error prefix | Bare exceptions become unrecoverable VMError |\n| Compare variable API fields in validators | Extract stable fields or derive status | Timestamps, counts change between calls |\n| O(n) scans over large collections | Maintain TreeMap indexes for O(1) lookups | Transactions have compute limits |\n\n## Testing Strategy\n\n1. **Lint first**: `genvm-lint check contracts\u002Fmy_contract.py`\n2. **Direct mode tests**: Fast (30ms), no server. Tests business logic, validation, state transitions. Validator logic NOT exercised.\n3. **Integration tests**: Slow (seconds-minutes), full consensus. Tests validator agreement, real web\u002FLLM calls. Run before deployment.\n",{"name":5,"description":7,"allowed-tools":25},[26,27,28,29,30,31],"Bash","Read","Write","Edit","Grep","Glob","master","63f17866001c5ca854bf2fa0b678ce277133de5b","skills\u002Fmarketplace\u002Fwrite-contract__skills-internet-court-write-contract",0,"https:\u002F\u002Fgithub.com\u002Fbg-szy\u002FTOP-SKILLS","https:\u002F\u002Fbg-szy.github.io\u002FTOP-SKILLS\u002F","https:\u002F\u002Fgithub.com\u002Fbg-szy","https:\u002F\u002Fwww.ecust.edu.cn\u002F","a student of East China University of Science and Technology","2026-11-15 03:38:02",{"source":8,"skillName":5,"commands":43,"prompt":53,"zipAvailable":54},[44,47,50],{"tool":45,"command":46},"npx","npx skills add bg-szy\u002FTOP-SKILLS --skill write-contract",{"tool":48,"command":49},"bunx","bunx skills add bg-szy\u002FTOP-SKILLS --skill write-contract",{"tool":51,"command":52},"pnpm","pnpm dlx skills add bg-szy\u002FTOP-SKILLS --skill write-contract","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fbg-szy\u002FTOP-SKILLS\u002Fblob\u002Fmaster\u002Fskills\u002Fmarketplace\u002Fwrite-contract__skills-internet-court-write-contract\u002FSKILL.md",true,[56,60],{"path":57,"resourceType":57,"resourceTypeDesc":58,"sizeBytes":59,"sourceHtmlUrl":16},"LICENSE","许可证",1070,{"path":61,"resourceType":62,"resourceTypeDesc":63,"sizeBytes":64,"sourceHtmlUrl":65},"skill-report.json","REFERENCE","参考文档",79885,"https:\u002F\u002Fgithub.com\u002Fbg-szy\u002FTOP-SKILLS\u002Fblob\u002Fmaster\u002Fskills\u002Fmarketplace\u002Fwrite-contract__skills-internet-court-write-contract\u002Fskill-report.json",[67,75,82,89,96,103],{"skillNo":68,"name":69,"nameZh":6,"description":70,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":71,"categories":72,"keywords":73,"publishedAt":74},"01M7DXW9N826PKXK174PVW3038","serpmaven","Scrape Google search results (SERP) to JSON with SERP Maven (serpmaven) - a real Chrome browser on a residential proxy with sticky sessions. Run it as a CLI, a Python library, a local HTTP search API (`serve`), an MCP server or a Docker image; set the proxy login, workers, pages and cost tracking. Use when the user wants Google results, rank tracking, a self-hosted SERP API, or live Google search for an AI agent.","https:\u002F\u002Fgithub.com\u002Fbg-szy\u002FTOP-SKILLS\u002Fblob\u002Fmaster\u002Fskills\u002Fmarketplace\u002Fserpmaven\u002FSKILL.md",[],[],"2026-11-15 14:19:17",{"skillNo":76,"name":77,"nameZh":6,"description":78,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":79,"categories":80,"keywords":81,"publishedAt":74},"01M7DXVHSTWDV65475QEQ915M7","revnu-landing-page-audit","Find out why a landing page isn't turning visitors into signups, demos or sales. Audits one page against what the ad, post or search that sends people there promised, then checks the first screen, proof, call to action, friction and mobile. Returns at most 7 prioritized fixes, plus what is fine and what could not be checked; rewrites specific lines and fixes the page in the repo when asked. Never promises a conversion lift. Works without a Revnu account. Use when the user says or asks: \"audit my landing page\", \"why isn't this page converting\", \"review my homepage\", \"my ads get clicks but no signups\", \"people bounce from the pricing page\", \"CRO review\", \"improve conversion rate\", \"is my hero section clear\", \"roast my landing page\", \"rewrite my headline\", \"what's wrong with this page\", \"landing page feedback\", \"make the signup page convert better\". Not for SEO or AI-search audits, page speed engineering on its own, or building a new page from scratch.","https:\u002F\u002Fgithub.com\u002Fbg-szy\u002FTOP-SKILLS\u002Fblob\u002Fmaster\u002Fskills\u002Fmarketplace\u002Frevnu-landing-page-audit\u002FSKILL.md",[],[],{"skillNo":83,"name":84,"nameZh":6,"description":85,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":86,"categories":87,"keywords":88,"publishedAt":74},"01M7DXV8X2D7B3VTD4HHYYHTGR","revnu-growth-context","Write down once who buys, what they're stuck on, what it costs, what proof you have and what you've already tried, so every growth task starts from facts instead of a questionnaire. Creates or updates .agents\u002Frevnu-growth.md from the repo, the live site and the user, and imports an existing product-marketing.md. Use when the user says \"set up our marketing context\", \"who is our ideal customer\", \"write our ICP\", \"describe the product for marketing\", \"positioning doc\", \"what's our brand voice\", \"remember this about our customers\", \"log what we tried\", \"what have we learned from marketing\", \"we changed pricing, update the context\", \"update our growth notes\", \"summarize the business for the agent\", \"import my product-marketing.md\", \"start a growth doc\", or before a first marketing, SEO, outreach or launch task when no context file exists. Works without a Revnu account.","https:\u002F\u002Fgithub.com\u002Fbg-szy\u002FTOP-SKILLS\u002Fblob\u002Fmaster\u002Fskills\u002Fmarketplace\u002Frevnu-growth-context\u002FSKILL.md",[],[],{"skillNo":90,"name":91,"nameZh":6,"description":92,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":93,"categories":94,"keywords":95,"publishedAt":74},"01M7DXV0DGJ1G0A60PAHC6J3C5","revnu-get-listed","Get onto the third-party pages AI answers and search cite when buyers ask for the best tool in your category: \"best X\" roundups, directories, review sites, GitHub awesome lists, community threads and comparison pages. Finds which ones are cited, ranks them by fit and effort, and drafts each submission, PR or pitch by the target's own rules. Use when the user says \"get us listed\", \"which directories should we submit to\", \"how do we get into best-of lists\", \"why does ChatGPT recommend competitors and not us\", \"get mentioned in AI answers\", \"submit to awesome lists\", \"get on G2\", \"where are our competitors listed\", \"pitch listicle authors\", \"find backlink opportunities\", \"launch directories\", \"get into roundups\", \"Product Hunt alternatives\", \"where should we be listed\", \"get cited by Perplexity\". Never submits, pays or posts without a yes. Works without a Revnu account.","https:\u002F\u002Fgithub.com\u002Fbg-szy\u002FTOP-SKILLS\u002Fblob\u002Fmaster\u002Fskills\u002Fmarketplace\u002Frevnu-get-listed\u002FSKILL.md",[],[],{"skillNo":97,"name":98,"nameZh":6,"description":99,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":100,"categories":101,"keywords":102,"publishedAt":74},"01M7DXTSPMGT9D6DSS0HP9BSTA","revnu-ai-readiness-audit","Audit whether your website gives ChatGPT, Perplexity, Claude, Gemini and Google's AI Overviews something worth quoting, and fix the pages that don't. Use when the user says or asks \"is my site ready for AI search\", \"audit my site for AI answers\", \"AEO audit\", \"GEO audit\", \"why doesn't ChatGPT quote our pricing\", \"make our pages citable by AI\", \"do I need llms.txt\", \"does schema help with ChatGPT\", \"check our structured data\", \"is our content visible without JavaScript\", \"AI SEO audit\", \"optimize our homepage for AI answers\", \"LLM SEO check\", \"why does AI get our product wrong\", \"fix our site for AI Overviews\". Checks fetchability and indexability, answers in the raw HTML, entity facts, schema (including JS-injected markup), headings, dates and llms.txt, then gives at most 10 prioritised fixes and edits the repo when asked. Works without a Revnu account.","https:\u002F\u002Fgithub.com\u002Fbg-szy\u002FTOP-SKILLS\u002Fblob\u002Fmaster\u002Fskills\u002Fmarketplace\u002Frevnu-ai-readiness-audit\u002FSKILL.md",[],[],{"skillNo":104,"name":105,"nameZh":6,"description":106,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":107,"categories":108,"keywords":109,"publishedAt":74},"01M7DXSZHCVTRS620GC3S97JZV","proxy-troubleshooting","Diagnose residential proxy failures, with NodeMaven's gateway as the reference - 407 with correct credentials, 406, 410, 500, a connection that hangs, ERR_TUNNEL_CONNECTION_FAILED in a browser, Playwright or Puppeteer ignoring proxy credentials, a sticky session that changes IP, geo-targeting that is silently ignored, passwords with special characters, and unexpected traffic from headless Chrome. Use when a proxy connection fails, returns the wrong location, or costs more traffic than expected.","https:\u002F\u002Fgithub.com\u002Fbg-szy\u002FTOP-SKILLS\u002Fblob\u002Fmaster\u002Fskills\u002Fmarketplace\u002Fproxy-troubleshooting\u002FSKILL.md",[],[]]