|
| 1 | +""" |
| 2 | +Featured App Activity Marker Emission |
| 3 | +
|
| 4 | +Creates FeaturedAppActivityMarker contracts on Canton ledger by exercising |
| 5 | +the FeaturedAppRight_CreateActivityMarker choice. This is how featured apps |
| 6 | +earn rewards — SV automation converts markers into AppRewardCoupons for CC minting. |
| 7 | +
|
| 8 | +Flow: |
| 9 | + 1. At startup, query the ledger for the FeaturedAppRight contract (granted by DSO governance) |
| 10 | + 2. After each billable tool call, exercise FeaturedAppRight_CreateActivityMarker |
| 11 | + 3. SV automation handles marker → AppRewardCoupon → CC minting (automatic) |
| 12 | +
|
| 13 | +Non-blocking: marker creation never fails a tool call. |
| 14 | +""" |
| 15 | + |
| 16 | +import logging |
| 17 | +import os |
| 18 | +from typing import Optional |
| 19 | + |
| 20 | +from canton_mcp_server.canton_billing import ( |
| 21 | + CANTON_PROVIDER_PARTY, |
| 22 | + CANTON_USER_ID, |
| 23 | + _make_ledger_request, |
| 24 | + get_ledger_offset, |
| 25 | +) |
| 26 | + |
| 27 | +logger = logging.getLogger(__name__) |
| 28 | + |
| 29 | +# Feature gate |
| 30 | +FEATURED_APP_REWARDS_ENABLED = ( |
| 31 | + os.getenv("FEATURED_APP_REWARDS_ENABLED", "false").lower() == "true" |
| 32 | +) |
| 33 | + |
| 34 | +# Cached FeaturedAppRight contract |
| 35 | +_featured_app_right_cache: dict = { |
| 36 | + "contract_id": None, |
| 37 | + "template_id": None, |
| 38 | +} |
| 39 | + |
| 40 | + |
| 41 | +async def init_featured_app_right() -> bool: |
| 42 | + """ |
| 43 | + Query the ledger for the FeaturedAppRight contract belonging to our provider party. |
| 44 | + Called at startup and on contract-not-found errors. |
| 45 | +
|
| 46 | + Returns True if found, False otherwise. |
| 47 | + """ |
| 48 | + if not CANTON_PROVIDER_PARTY: |
| 49 | + logger.warning("CANTON_PROVIDER_PARTY not set — cannot query FeaturedAppRight") |
| 50 | + return False |
| 51 | + |
| 52 | + try: |
| 53 | + offset = await get_ledger_offset() |
| 54 | + data = await _make_ledger_request( |
| 55 | + "POST", |
| 56 | + "/v2/state/active-contracts", |
| 57 | + { |
| 58 | + "filter": { |
| 59 | + "filtersByParty": { |
| 60 | + CANTON_PROVIDER_PARTY: {"cumulative": []}, |
| 61 | + }, |
| 62 | + }, |
| 63 | + "activeAtOffset": offset, |
| 64 | + "verbose": False, |
| 65 | + }, |
| 66 | + ) |
| 67 | + |
| 68 | + contracts = data if isinstance(data, list) else data.get("activeContracts", data.get("result", [])) |
| 69 | + |
| 70 | + for c in contracts: |
| 71 | + # Canton JSON API v2 wraps contracts in contractEntry.JsActiveContract.createdEvent |
| 72 | + ce = c.get("contractEntry", {}) |
| 73 | + ac = ce.get("JsActiveContract", {}) |
| 74 | + event = ac.get("createdEvent", {}) or c.get("createdEvent", c) |
| 75 | + template_id = event.get("templateId", "") |
| 76 | + if "FeaturedAppRight" in template_id: |
| 77 | + contract_id = event.get("contractId", "") |
| 78 | + _featured_app_right_cache["contract_id"] = contract_id |
| 79 | + _featured_app_right_cache["template_id"] = template_id |
| 80 | + logger.info( |
| 81 | + f"FeaturedAppRight contract found: {contract_id[:40]}... " |
| 82 | + f"(template: {template_id})" |
| 83 | + ) |
| 84 | + return True |
| 85 | + |
| 86 | + logger.warning( |
| 87 | + f"FeaturedAppRight not found for {CANTON_PROVIDER_PARTY}. " |
| 88 | + "Activity markers will not be emitted. " |
| 89 | + "Ensure the DSO has granted FeaturedAppRight to this party." |
| 90 | + ) |
| 91 | + return False |
| 92 | + |
| 93 | + except Exception as e: |
| 94 | + logger.error(f"Failed to query FeaturedAppRight: {e}") |
| 95 | + return False |
| 96 | + |
| 97 | + |
| 98 | +async def create_activity_marker(request_id: str) -> Optional[str]: |
| 99 | + """ |
| 100 | + Exercise FeaturedAppRight_CreateActivityMarker to emit an activity marker. |
| 101 | +
|
| 102 | + Args: |
| 103 | + request_id: Unique request ID (used for command deduplication) |
| 104 | +
|
| 105 | + Returns: |
| 106 | + Contract ID of the created marker, or None on failure. |
| 107 | + """ |
| 108 | + if not FEATURED_APP_REWARDS_ENABLED: |
| 109 | + return None |
| 110 | + |
| 111 | + contract_id = _featured_app_right_cache.get("contract_id") |
| 112 | + template_id = _featured_app_right_cache.get("template_id") |
| 113 | + |
| 114 | + if not contract_id or not template_id: |
| 115 | + return None |
| 116 | + |
| 117 | + try: |
| 118 | + data = await _make_ledger_request( |
| 119 | + "POST", |
| 120 | + "/v2/commands/submit-and-wait-for-transaction", |
| 121 | + { |
| 122 | + "commands": { |
| 123 | + "userId": CANTON_USER_ID, |
| 124 | + "commandId": f"activity-marker-{request_id}", |
| 125 | + "actAs": [CANTON_PROVIDER_PARTY], |
| 126 | + "readAs": [CANTON_PROVIDER_PARTY], |
| 127 | + "commands": [ |
| 128 | + { |
| 129 | + "ExerciseCommand": { |
| 130 | + "templateId": template_id, |
| 131 | + "contractId": contract_id, |
| 132 | + "choice": "FeaturedAppRight_CreateActivityMarker", |
| 133 | + "choiceArgument": { |
| 134 | + "beneficiaries": [ |
| 135 | + { |
| 136 | + "beneficiary": CANTON_PROVIDER_PARTY, |
| 137 | + "weight": "1.0", |
| 138 | + } |
| 139 | + ], |
| 140 | + }, |
| 141 | + } |
| 142 | + } |
| 143 | + ], |
| 144 | + } |
| 145 | + }, |
| 146 | + ) |
| 147 | + |
| 148 | + # Extract marker contract IDs from the exercise result |
| 149 | + events = data.get("transaction", {}).get("events", []) |
| 150 | + marker_cids = [] |
| 151 | + for event in events: |
| 152 | + created = event.get("CreatedEvent") or event.get("createdEvent", {}) |
| 153 | + if created.get("contractId") and "ActivityMarker" in created.get("templateId", ""): |
| 154 | + marker_cids.append(created["contractId"]) |
| 155 | + |
| 156 | + if marker_cids: |
| 157 | + logger.info(f"ActivityMarker created: {marker_cids[0][:40]}...") |
| 158 | + return marker_cids[0] |
| 159 | + |
| 160 | + # Even without recognizing the marker template, success means it worked |
| 161 | + logger.info(f"FeaturedAppRight_CreateActivityMarker exercised for request {request_id}") |
| 162 | + return "exercised" |
| 163 | + |
| 164 | + except Exception as e: |
| 165 | + error_str = str(e) |
| 166 | + |
| 167 | + # Contract archived / not found — re-query and retry once |
| 168 | + if "CONTRACT_NOT_FOUND" in error_str or "not found" in error_str.lower(): |
| 169 | + logger.warning("FeaturedAppRight contract may have been archived, re-querying...") |
| 170 | + found = await init_featured_app_right() |
| 171 | + if found: |
| 172 | + try: |
| 173 | + return await create_activity_marker(f"{request_id}-retry") |
| 174 | + except Exception as retry_err: |
| 175 | + logger.warning(f"ActivityMarker retry failed: {retry_err}") |
| 176 | + return None |
| 177 | + |
| 178 | + # Auth / permission errors — don't retry |
| 179 | + if "403" in error_str or "PERMISSION_DENIED" in error_str: |
| 180 | + logger.warning(f"ActivityMarker permission denied (FeaturedAppRight may have been revoked): {e}") |
| 181 | + return None |
| 182 | + |
| 183 | + logger.warning(f"ActivityMarker creation failed (non-fatal): {e}") |
| 184 | + return None |
0 commit comments