agentkoin-core 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 STOS Technologies LLC
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,9 @@
1
+ """AgentCoin core client for Python plugins. Base Sepolia testnet only."""
2
+ from .client import AgentCoin, PayResult, assert_chain_allowed
3
+ from .constants import DEFAULT_AGENTCOIN_URL, agentcoin_url, BASE_SEPOLIA, DEFAULT_MAX_PAYMENT, ESCROW_STATES, MAINNET_CHAIN_IDS
4
+ from .env import as_client, from_env
5
+ from .errors import AgentCoinError
6
+ from .tools import TOOL_NAMES, TOOL_SPECS, run_tool, run_tool_json
7
+
8
+ __all__ = ["AgentCoin", "AgentCoinError", "PayResult", "assert_chain_allowed", "BASE_SEPOLIA", "DEFAULT_AGENTCOIN_URL", "agentcoin_url", "DEFAULT_MAX_PAYMENT", "ESCROW_STATES", "MAINNET_CHAIN_IDS",
9
+ "as_client", "from_env", "TOOL_NAMES", "TOOL_SPECS", "run_tool", "run_tool_json"]
@@ -0,0 +1,36 @@
1
+ """RFC 8785 canonical JSON, keccak256 over it, and AgentCoin EIP-191 document verification."""
2
+ from __future__ import annotations
3
+
4
+ import rfc8785
5
+ from eth_account import Account
6
+ from eth_account.messages import encode_defunct
7
+ from eth_utils import keccak, to_checksum_address
8
+
9
+
10
+ def jcs(v) -> bytes:
11
+ return rfc8785.dumps(v)
12
+
13
+
14
+ def keccak_jcs(v) -> str:
15
+ return "0x" + keccak(jcs(v)).hex()
16
+
17
+
18
+ def verify_eip191_document(doc: dict) -> dict:
19
+ """personal_sign over keccak256(RFC8785(document without "signature"))."""
20
+ s = (doc or {}).get("signature")
21
+ if not isinstance(s, dict) or s.get("scheme") != "eip191":
22
+ return {"valid": False, "reason": "no eip191 signature"}
23
+ unsigned = {k: v for k, v in doc.items() if k != "signature"}
24
+ digest = keccak_jcs(unsigned)
25
+ if s.get("signedDigest") and s["signedDigest"].lower() != digest.lower():
26
+ return {"valid": False, "digest": digest, "reason": "digest mismatch (document modified)"}
27
+ signer = to_checksum_address(s["signer"])
28
+ try:
29
+ rec = Account.recover_message(encode_defunct(primitive=bytes.fromhex(digest[2:])), signature=s["value"])
30
+ except Exception:
31
+ return {"valid": False, "signer": signer, "digest": digest, "reason": "signature does not match signer"}
32
+ ok = to_checksum_address(rec) == signer
33
+ out = {"valid": ok, "signer": signer, "digest": digest}
34
+ if not ok:
35
+ out["reason"] = "signature does not match signer"
36
+ return out
@@ -0,0 +1,52 @@
1
+ """Minimal EVM access used by the client. Tests inject a fake with the same methods."""
2
+ from __future__ import annotations
3
+
4
+ from typing import Protocol
5
+
6
+ from eth_utils import to_checksum_address
7
+
8
+
9
+ class Chain(Protocol):
10
+ def block_timestamp(self) -> int: ...
11
+ def call(self, to: str, data: str, sender: str | None = None) -> bytes: ...
12
+ def send_transaction(self, account, to: str, data: str) -> str: ...
13
+ def wait_receipt(self, tx_hash: str) -> dict: ...
14
+
15
+
16
+ class Web3Chain:
17
+ """JSON-RPC chain access via web3.py. Signs locally with the eth_account LocalAccount; never sends keys anywhere."""
18
+
19
+ def __init__(self, rpc_url: str, chain_id: int, timeout: float = 120):
20
+ from web3 import Web3
21
+
22
+ self.w3 = Web3(Web3.HTTPProvider(rpc_url, request_kwargs={"timeout": 30}))
23
+ self.chain_id = chain_id
24
+ self.timeout = timeout
25
+
26
+ def block_timestamp(self) -> int:
27
+ return int(self.w3.eth.get_block("latest")["timestamp"])
28
+
29
+ def call(self, to: str, data: str, sender: str | None = None) -> bytes:
30
+ tx = {"to": to_checksum_address(to), "data": data}
31
+ if sender:
32
+ tx["from"] = to_checksum_address(sender)
33
+ return bytes(self.w3.eth.call(tx))
34
+
35
+ def send_transaction(self, account, to: str, data: str) -> str:
36
+ w3 = self.w3
37
+ tx = {"from": account.address, "to": to_checksum_address(to), "data": data, "value": 0, "chainId": self.chain_id,
38
+ "nonce": w3.eth.get_transaction_count(account.address, "pending")}
39
+ tx["gas"] = int(w3.eth.estimate_gas(tx) * 12 // 10)
40
+ base = w3.eth.get_block("latest").get("baseFeePerGas", 0)
41
+ prio = w3.eth.max_priority_fee
42
+ tx["maxPriorityFeePerGas"] = prio
43
+ tx["maxFeePerGas"] = base * 2 + prio
44
+ signed = account.sign_transaction(tx)
45
+ raw = getattr(signed, "raw_transaction", None) or signed.rawTransaction
46
+ h = w3.eth.send_raw_transaction(raw)
47
+ return "0x" + bytes(h).hex().removeprefix("0x")
48
+
49
+ def wait_receipt(self, tx_hash: str) -> dict:
50
+ rc = self.w3.eth.wait_for_transaction_receipt(tx_hash, timeout=self.timeout)
51
+ hx = lambda b: "0x" + bytes(b).hex().removeprefix("0x")
52
+ return {"status": int(rc["status"]), "logs": [{"address": l["address"], "topics": [hx(t) for t in l["topics"]], "data": hx(l["data"])} for l in rc["logs"]]}
@@ -0,0 +1,430 @@
1
+ """AgentCoin router client (Python). Same flow and guards as @agentkoin/core:
2
+ find_service / route_task -> place_order -> pay (direct x402 exact, or escrow) -> get_order / wait_for_verdict -> verify."""
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import re
7
+ import time
8
+ from dataclasses import dataclass, field
9
+ from urllib.parse import quote
10
+
11
+ import httpx
12
+ from eth_abi import decode as abi_decode, encode as abi_encode
13
+ from eth_account import Account
14
+ from eth_utils import keccak, to_checksum_address
15
+
16
+ from .canonical import keccak_jcs, verify_eip191_document
17
+ from .chain import Chain, Web3Chain
18
+ from .constants import agentcoin_url, BASE_SEPOLIA, DEFAULT_MAX_PAYMENT, ESCROW_STATES, GET_JOB_FIELDS, GET_JOB_OUTPUT, MAINNET_CHAIN_IDS
19
+ from .errors import AgentCoinError
20
+ from .x402 import escrow_payment_header, parse402, read_payment_response, sign_exact_payment
21
+
22
+
23
+ def _sel(sig: str) -> str:
24
+ return keccak(text=sig)[:4].hex()
25
+
26
+
27
+ SEL_APPROVE = _sel("approve(address,uint256)")
28
+ SEL_CREATE_AND_FUND_FOR = _sel("createAndFundFor(address,address,address,uint256,uint64,bytes32)")
29
+ SEL = {n: _sel(f"{n}(uint256)") for n in ("cancel", "claimRefund", "timeoutRelease", "finalize", "getJob")}
30
+ TOPIC_JOB_CREATED = "0x" + keccak(text="JobCreated(uint256,address,address,address,uint256,uint64,bytes32,uint32)").hex()
31
+ _HEX64 = re.compile(r"^0x[0-9a-fA-F]{64}$")
32
+
33
+
34
+ def assert_chain_allowed(chain_id: int, allow_mainnet: bool = False) -> None:
35
+ if not isinstance(chain_id, int) or chain_id <= 0:
36
+ raise AgentCoinError("bad_chain", f"invalid chainId {chain_id}")
37
+ if chain_id in MAINNET_CHAIN_IDS and not allow_mainnet:
38
+ raise AgentCoinError("mainnet_refused", f"chainId {chain_id} is a mainnet; AgentCoin v0.1 plugins run on Base Sepolia (84532) only. allow_mainnet is unsupported.")
39
+
40
+
41
+ def _decode_body(b: bytes):
42
+ try:
43
+ return json.loads(b)
44
+ except ValueError:
45
+ return b.decode("utf-8", "replace")
46
+
47
+
48
+ def _cs(a) -> str:
49
+ return to_checksum_address(a)
50
+
51
+
52
+ @dataclass
53
+ class PayResult:
54
+ order_id: str
55
+ mode: str
56
+ service_id: str
57
+ amount: str
58
+ payment_tx: str | None
59
+ job_id: str | None
60
+ deliverable: object
61
+ seller_status: int | None
62
+ order: dict
63
+ transactions: list = field(default_factory=list)
64
+ response: dict | None = None
65
+
66
+ def summary(self) -> dict:
67
+ return {"orderId": self.order_id, "mode": self.mode, "serviceId": self.service_id, "amount": self.amount, "paymentTx": self.payment_tx, "jobId": self.job_id,
68
+ "deliverable": self.deliverable, "sellerStatus": self.seller_status, "transactions": self.transactions or None}
69
+
70
+
71
+ class AgentCoin:
72
+ def __init__(self, *, base_url: str | None = None, chain_id: int = BASE_SEPOLIA["chain_id"], private_key: str | None = None, account=None,
73
+ rpc_url: str | None = None, max_payment: int | str = DEFAULT_MAX_PAYMENT, allowed_service_ids: list[str] | None = None,
74
+ origin: str | None = None, allow_mainnet: bool = False, usdc: str | None = None, escrow: str | None = None,
75
+ http: httpx.Client | None = None, chain: Chain | None = None, poll_interval: float = 15.0, verdict_timeout: float = 600.0):
76
+ """allow_mainnet is unsupported in v0.1 (default False); the hosted router serves eip155:84532 only."""
77
+ assert_chain_allowed(chain_id, allow_mainnet)
78
+ if chain_id != BASE_SEPOLIA["chain_id"] and not usdc:
79
+ raise AgentCoinError("bad_chain", f"no USDC address known for chainId {chain_id}; pass usdc")
80
+ self.chain_id = chain_id
81
+ self.caip2 = f"eip155:{chain_id}"
82
+ self.base_url = (base_url or agentcoin_url()).rstrip("/")
83
+ self.account = account or (Account.from_key(private_key) if private_key else None)
84
+ self.max_payment = int(max_payment)
85
+ self.allowed_service_ids = set(allowed_service_ids) if allowed_service_ids else None
86
+ self.origin = origin
87
+ self.usdc = _cs(usdc or BASE_SEPOLIA["usdc"])
88
+ self.escrow = _cs(escrow or BASE_SEPOLIA["escrow"])
89
+ self.http = http or httpx.Client(timeout=httpx.Timeout(300, connect=15), follow_redirects=False)
90
+ self._rpc_url = rpc_url or BASE_SEPOLIA["rpc_url"]
91
+ self._chain = chain
92
+ self.poll_interval = poll_interval
93
+ self.verdict_timeout = verdict_timeout
94
+
95
+ @property
96
+ def address(self) -> str | None:
97
+ return self.account.address if self.account else None
98
+
99
+ @property
100
+ def chain(self) -> Chain:
101
+ if self._chain is None:
102
+ self._chain = Web3Chain(self._rpc_url, self.chain_id)
103
+ return self._chain
104
+
105
+ def _need_account(self, what="payment"):
106
+ if not self.account:
107
+ raise AgentCoinError("no_account", f"{what} needs a signer (private_key)")
108
+
109
+ # ---------------------------------------------------------------- REST
110
+ def api(self, method: str, path: str, body=None) -> dict:
111
+ r = self.http.request(method, self.base_url + path, headers={"accept": "application/json"}, **({"json": body} if body is not None else {}))
112
+ try:
113
+ j = r.json()
114
+ except ValueError:
115
+ j = None
116
+ if r.status_code >= 400:
117
+ msg = (j or {}).get("error") if isinstance(j, dict) else None
118
+ raise AgentCoinError(f"http_{r.status_code}", f"{method} {path} -> {r.status_code}: {msg or json.dumps(j)[:300]}", j)
119
+ return j if j is not None else {}
120
+
121
+ def find_service(self, id: str | None = None, skills_offset: int | None = None, **q) -> dict:
122
+ if id:
123
+ return self.api("GET", f"/v1/services/{quote(id, safe='')}" + (f"?skillsOffset={skills_offset}" if skills_offset else ""))
124
+ params = {k: (str(v).lower() if isinstance(v, bool) else str(v)) for k, v in q.items() if v is not None}
125
+ qs = str(httpx.QueryParams(params))
126
+ return self.api("GET", "/v1/services" + (f"?{qs}" if qs else ""))
127
+
128
+ def route_task(self, task: str, budget: str | None = None, constraints: dict | None = None) -> dict:
129
+ body = {"task": task, "constraints": {"network": self.caip2, **(constraints or {})}}
130
+ if budget:
131
+ body["budget"] = str(budget)
132
+ return self.api("POST", "/v1/route", body)
133
+
134
+ def place_order(self, service_id: str, skill_id: str | None = None, mode: str = "direct", deadline_seconds: int | None = None) -> dict:
135
+ self.assert_service_allowed(service_id)
136
+ if mode == "escrow":
137
+ self._need_account("escrow orders")
138
+ body = {"serviceId": service_id, "mode": mode}
139
+ if skill_id:
140
+ body["skillId"] = skill_id
141
+ if self.account:
142
+ body["buyer"] = self.account.address
143
+ if deadline_seconds:
144
+ body["deadlineSeconds"] = deadline_seconds
145
+ if self.origin:
146
+ body["origin"] = self.origin
147
+ return self.api("POST", "/v1/orders", body)
148
+
149
+ def get_order(self, order_id: str) -> dict:
150
+ return self.api("GET", f"/v1/orders/{quote(order_id, safe='')}")
151
+
152
+ def submit_receipt(self, order_id: str, body: dict) -> dict:
153
+ return self.api("POST", f"/v1/orders/{quote(order_id, safe='')}/receipt", body)
154
+
155
+ def submit_listing(self, url: str) -> dict:
156
+ return self.api("POST", "/v1/services", {"url": url})
157
+
158
+ def claim_listing(self, service_id: str, sign: bool = False, method: str | None = None, expires_in_seconds: int = 3600) -> dict:
159
+ sid = quote(service_id, safe="")
160
+ if method == "well-known":
161
+ return self.api("POST", f"/v1/services/{sid}/claim/verify", {"method": "well-known", **({"claimant": self.address} if self.account else {})})
162
+ if not sign:
163
+ return self.api("POST", f"/v1/services/{sid}/claim", {"claimant": self.address} if self.account else {})
164
+ self._need_account("signing a claim")
165
+ svc = self.find_service(id=service_id)
166
+ mh = svc.get("metadataHash")
167
+ if not isinstance(mh, str) or not _HEX64.match(mh):
168
+ raise AgentCoinError("no_metadata_hash", "listing has no metadataHash")
169
+ expires_at = int(time.time()) + min(86_400, expires_in_seconds)
170
+ sig = self.account.sign_typed_data(
171
+ domain_data={"name": "AgentCoin Index", "version": "1", "chainId": self.chain_id},
172
+ message_types={"Claim": [{"name": "serviceId", "type": "string"}, {"name": "claimant", "type": "address"}, {"name": "metadataHash", "type": "bytes32"}, {"name": "expiresAt", "type": "uint256"}]},
173
+ message_data={"serviceId": service_id, "claimant": self.account.address, "metadataHash": bytes.fromhex(mh[2:]), "expiresAt": expires_at},
174
+ ).signature.hex()
175
+ sig = sig if sig.startswith("0x") else "0x" + sig
176
+ return self.api("POST", f"/v1/services/{sid}/claim/verify", {"claimant": self.account.address, "expiresAt": str(expires_at), "signature": sig})
177
+
178
+ def reputation(self, service_id: str) -> dict:
179
+ rep = self.api("GET", f"/v1/reputation/{quote(service_id, safe='')}")
180
+ score, ev = rep.get("score"), rep.get("evidence")
181
+ sig = verify_eip191_document(score) if score else {"valid": False, "reason": "no score"}
182
+ root_ok = bool(isinstance(ev, list) and score and score.get("evidenceRoot") and keccak_jcs(ev) == score["evidenceRoot"])
183
+ is_op = bool(sig.get("signer")) and _cs(sig["signer"]) == _cs(BASE_SEPOLIA["operator_signer"])
184
+ return {"serviceId": service_id, "score": score, "evidenceCount": len(ev) if isinstance(ev, list) else 0,
185
+ "checks": {"signatureValid": sig["valid"], "signer": sig.get("signer"), "signerIsOperator": is_op, "evidenceRootMatches": root_ok}, "evidence": ev}
186
+
187
+ def verify_delivery_record(self, record: dict | None) -> dict:
188
+ if not record:
189
+ return {"valid": False, "reason": "no delivery record"}
190
+ r = verify_eip191_document(record)
191
+ return {**r, "signerIsOperator": bool(r.get("signer")) and _cs(r["signer"]) == _cs(BASE_SEPOLIA["operator_signer"])}
192
+
193
+ def mcp_call(self, name: str, args: dict) -> dict:
194
+ r = self.http.post(self.base_url + "/mcp", headers={"accept": "application/json, text/event-stream"}, json={"jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": {"name": name, "arguments": args}})
195
+ text = r.text
196
+ if text.startswith("event:") or text.startswith("data:"):
197
+ text = "".join(l[5:] for l in text.split("\n") if l.startswith("data:"))
198
+ j = json.loads(text)
199
+ if j.get("error"):
200
+ raise AgentCoinError("mcp_error", j["error"].get("message", "mcp error"), j["error"])
201
+ res = j.get("result") or {}
202
+ if res.get("isError"):
203
+ raise AgentCoinError("mcp_tool_error", (res.get("content") or [{}])[0].get("text", "tool error"), res)
204
+ return res.get("structuredContent") or json.loads((res.get("content") or [{}])[0].get("text", "{}"))
205
+
206
+ def verify(self, service_id: str | None = None, order_id: str | None = None, document=None, expected_signer: str | None = None, evaluator: str | None = None) -> dict:
207
+ out: dict = {}
208
+ if service_id:
209
+ out["service"] = self.reputation(service_id)
210
+ if order_id:
211
+ o = self.get_order(order_id)
212
+ out["order"] = {"orderId": o.get("orderId"), "status": o.get("status"), "verdict": o.get("verdict"), "deliverableHash": o.get("deliverableHash"), "deliveryRecord": self.verify_delivery_record(o.get("deliveryRecord"))}
213
+ if document is not None or evaluator:
214
+ args = {}
215
+ if document is not None:
216
+ args["document"] = document
217
+ if expected_signer:
218
+ args["expectedSigner"] = expected_signer
219
+ if evaluator:
220
+ args["evaluator"] = evaluator
221
+ out.update(self.mcp_call("verify", args))
222
+ if not out:
223
+ raise AgentCoinError("bad_args", "service_id, order_id, document or evaluator required")
224
+ return out
225
+
226
+ # ---------------------------------------------------------------- guards
227
+ def assert_service_allowed(self, service_id: str) -> None:
228
+ if self.allowed_service_ids is not None and service_id not in self.allowed_service_ids:
229
+ raise AgentCoinError("service_not_allowed", f"serviceId {service_id} is not in allowed_service_ids")
230
+
231
+ def _assert_requirement(self, network: str, asset: str, amount) -> None:
232
+ if network != self.caip2:
233
+ raise AgentCoinError("wrong_network", f"payment network {network} != {self.caip2}")
234
+ if _cs(asset) != self.usdc:
235
+ raise AgentCoinError("wrong_asset", f"payment asset {asset} != USDC {self.usdc}")
236
+ if int(amount) > self.max_payment:
237
+ raise AgentCoinError("over_max_payment", f"amount {amount} > max_payment {self.max_payment}")
238
+
239
+ # ---------------------------------------------------------------- payment
240
+ def pay_direct(self, order: dict, body=None, method: str | None = None, url: str | None = None, headers: dict | None = None) -> PayResult:
241
+ self._need_account()
242
+ if order.get("mode") != "direct":
243
+ raise AgentCoinError("bad_order", "pay_direct needs a direct order")
244
+ self.assert_service_allowed(order["serviceId"])
245
+ routed = next((r for r in order.get("paymentRequirements") or [] if r.get("scheme") == "exact" and r.get("network") == self.caip2), None)
246
+ if not routed:
247
+ raise AgentCoinError("wrong_network", f"order has no exact requirement on {self.caip2}")
248
+ self._assert_requirement(routed["network"], routed["asset"], routed["amount"])
249
+ req_info = order.get("request") or {}
250
+ url = url or req_info.get("url")
251
+ if not url:
252
+ raise AgentCoinError("no_url", "order has no seller request url")
253
+ method = (method or req_info.get("method") or ("POST" if body is not None else "GET")).upper()
254
+ content = None if body is None else (body if isinstance(body, str) else json.dumps(body))
255
+ base_h = {**({"content-type": "application/json"} if body is not None else {}), **(headers or {})}
256
+ r1 = self.http.request(method, url, headers=base_h, content=content)
257
+ if r1.status_code != 402:
258
+ raise AgentCoinError("expected_402", f"seller returned {r1.status_code} before payment")
259
+ parsed = parse402(r1.headers, r1.content)
260
+ req = next((x for x in parsed.accepts if x.scheme == "exact" and x.network == self.caip2), None)
261
+ if not req:
262
+ raise AgentCoinError("wrong_network", f"seller offers no exact requirement on {self.caip2}")
263
+ self._assert_requirement(req.network, req.asset, req.amount)
264
+ if _cs(req.pay_to) != _cs(routed["payTo"]):
265
+ raise AgentCoinError("payto_mismatch", f"seller payTo {req.pay_to} != indexed payTo {routed['payTo']}")
266
+ if int(req.amount) != int(routed["amount"]):
267
+ raise AgentCoinError("amount_mismatch", f"seller amount {req.amount} != quoted {routed['amount']}")
268
+ hn, hv = sign_exact_payment(self.account, req, parsed, chain_id=self.chain_id, token_name=BASE_SEPOLIA["usdc_eip712"]["name"],
269
+ token_version=BASE_SEPOLIA["usdc_eip712"]["version"], now_seconds=self.chain.block_timestamp())
270
+ t = time.time()
271
+ r2 = self.http.request(method, url, headers={**base_h, hn: hv}, content=content)
272
+ latency_ms = int((time.time() - t) * 1000)
273
+ deliverable = _decode_body(r2.content)
274
+ if r2.status_code != 200:
275
+ raise AgentCoinError("payment_rejected", f"seller returned {r2.status_code} after payment", deliverable)
276
+ pr = read_payment_response(r2.headers) or {}
277
+ ptx = pr.get("transaction") or pr.get("txHash")
278
+ if not (isinstance(ptx, str) and _HEX64.match(ptx)):
279
+ raise AgentCoinError("no_payment_tx", "seller returned no settlement transaction in PAYMENT-RESPONSE", {"paymentResponse": pr, "deliverable": deliverable})
280
+ rec = self.submit_receipt(order["orderId"], {"paymentTx": ptx, "deliverable": deliverable, "latencyMs": latency_ms})
281
+ return PayResult(order["orderId"], "direct", order["serviceId"], req.amount, ptx, pr.get("jobId"), deliverable, r2.status_code, rec,
282
+ response={"status": r2.status_code, "headers": dict(r2.headers), "body": r2.content})
283
+
284
+ def _check_escrow_txs(self, order: dict) -> None:
285
+ e = order.get("escrow") or {}
286
+ if int(e.get("chainId", -1)) != self.chain_id:
287
+ raise AgentCoinError("wrong_network", f"escrow chainId {e.get('chainId')} != {self.chain_id}")
288
+ if _cs(e["contract"]) != self.escrow:
289
+ raise AgentCoinError("wrong_escrow", f"escrow contract {e['contract']} != {self.escrow}")
290
+ self._assert_requirement(self.caip2, e["token"], e["amount"])
291
+ txs = order.get("transactions") or []
292
+ if len(txs) != 2:
293
+ raise AgentCoinError("bad_order", "expected 2 escrow transactions")
294
+ a, f = txs
295
+ if _cs(a["to"]) != self.usdc or int(a["chainId"]) != self.chain_id or int(a.get("value") or 0) != 0:
296
+ raise AgentCoinError("bad_tx", "approve tx target/chain/value mismatch")
297
+ d = a["data"].removeprefix("0x")
298
+ if d[:8] != SEL_APPROVE:
299
+ raise AgentCoinError("bad_tx", "approve must be approve(escrow, amount)")
300
+ spender, amt = abi_decode(["address", "uint256"], bytes.fromhex(d[8:]))
301
+ if _cs(spender) != self.escrow or amt != int(e["amount"]):
302
+ raise AgentCoinError("bad_tx", "approve must be approve(escrow, amount)")
303
+ if _cs(f["to"]) != self.escrow or int(f["chainId"]) != self.chain_id or int(f.get("value") or 0) != 0:
304
+ raise AgentCoinError("bad_tx", "fund tx target/chain/value mismatch")
305
+ d = f["data"].removeprefix("0x")
306
+ if d[:8] != SEL_CREATE_AND_FUND_FOR:
307
+ raise AgentCoinError("bad_tx", "fund tx must be createAndFundFor")
308
+ client, provider, evaluator, amount, _deadline, _spec = abi_decode(["address", "address", "address", "uint256", "uint64", "bytes32"], bytes.fromhex(d[8:]))
309
+ if _cs(client) != _cs(self.account.address):
310
+ raise AgentCoinError("bad_tx", "createAndFundFor client != my address")
311
+ if _cs(provider) != _cs(e["provider"]) or _cs(evaluator) != _cs(e["evaluator"]) or amount != int(e["amount"]):
312
+ raise AgentCoinError("bad_tx", "createAndFundFor args != order escrow terms")
313
+
314
+ def pay_escrow(self, order: dict, body=None, headers: dict | None = None, seller_call: dict | None | bool = True) -> PayResult:
315
+ """seller_call: True = use the order's sellerCall; dict {url, method} = override; None/False = skip the seller call."""
316
+ self._need_account()
317
+ if order.get("mode") != "escrow":
318
+ raise AgentCoinError("bad_order", "pay_escrow needs an escrow order")
319
+ self.assert_service_allowed(order["serviceId"])
320
+ self._check_escrow_txs(order)
321
+ sent = []
322
+ job_id = None
323
+ for tx in order["transactions"]:
324
+ h = self.chain.send_transaction(self.account, tx["to"], tx["data"])
325
+ rc = self.chain.wait_receipt(h)
326
+ if int(rc["status"]) != 1:
327
+ raise AgentCoinError("tx_reverted", f"{tx.get('label')} reverted: {h}")
328
+ sent.append({"label": tx.get("label"), "hash": h})
329
+ for lg in rc.get("logs", []):
330
+ if _cs(lg["address"]) == self.escrow and lg["topics"] and lg["topics"][0].lower() == TOPIC_JOB_CREATED:
331
+ job_id = str(int(lg["topics"][1], 16))
332
+ if job_id is None:
333
+ raise AgentCoinError("no_job", "no JobCreated event in fund tx")
334
+ fund_tx = sent[1]["hash"]
335
+ rec: dict = {}
336
+ for i in range(4):
337
+ try:
338
+ rec = self.submit_receipt(order["orderId"], {"jobId": job_id, "paymentTx": fund_tx})
339
+ break
340
+ except AgentCoinError:
341
+ if i == 3:
342
+ raise
343
+ time.sleep(3)
344
+ sc = order.get("sellerCall") if seller_call is True else (seller_call or None)
345
+ deliverable, status, response = None, None, None
346
+ if sc and sc.get("url"):
347
+ content = None if body is None else (body if isinstance(body, str) else json.dumps(body))
348
+ r = self.http.request(sc.get("method") or "POST", sc["url"], content=content,
349
+ headers={"content-type": "application/json", **(headers or {}), "PAYMENT-SIGNATURE": escrow_payment_header(self.chain_id, job_id, fund_tx)})
350
+ status = r.status_code
351
+ deliverable = _decode_body(r.content)
352
+ response = {"status": r.status_code, "headers": dict(r.headers), "body": r.content}
353
+ return PayResult(order["orderId"], "escrow", order["serviceId"], str(order["escrow"]["amount"]), fund_tx, job_id, deliverable, status, rec, sent, response)
354
+
355
+ def wait_for_verdict(self, order_id: str, timeout: float | None = None, interval: float | None = None) -> dict:
356
+ end = time.time() + (self.verdict_timeout if timeout is None else timeout)
357
+ def poll():
358
+ try:
359
+ return self.get_order(order_id)
360
+ except httpx.TransportError: # slow/failed read of the order: keep polling until the deadline
361
+ if time.time() >= end:
362
+ raise
363
+ return {}
364
+ o = poll()
365
+ while not o.get("verdict") and time.time() < end:
366
+ time.sleep(self.poll_interval if interval is None else interval)
367
+ o = poll()
368
+ return o
369
+
370
+ def get_job(self, job_id) -> dict:
371
+ data = "0x" + SEL["getJob"] + abi_encode(["uint256"], [int(job_id)]).hex()
372
+ (tup,) = abi_decode([GET_JOB_OUTPUT], self.chain.call(self.escrow, data))
373
+ j = dict(zip(GET_JOB_FIELDS, tup))
374
+ j["stateName"] = ESCROW_STATES[int(j["state"])]
375
+ return j
376
+
377
+ def refund(self, job_id, send: bool = True) -> dict:
378
+ """Buyer refund path for an escrow job (cancel / claimRefund / timeoutRelease / finalize by state); simulates, then sends."""
379
+ job = self.get_job(job_id)
380
+ now = int(time.time())
381
+ st = job["stateName"]
382
+ jid = str(job_id)
383
+ fn = None
384
+ if st == "Funded" and not job["accepted"]:
385
+ fn = "cancel"
386
+ elif st == "Funded" and now >= int(job["deadline"]):
387
+ fn = "claimRefund"
388
+ elif st == "Submitted":
389
+ fn = "timeoutRelease"
390
+ elif st in ("Rejected", "Partial", "Completed"):
391
+ fn = "finalize"
392
+ if not fn:
393
+ return {"jobId": jid, "state": st, "sent": False, "reason": f"no refund action for state {st}" + (" before the deadline" if st == "Funded" else "")}
394
+ if fn == "cancel" and (not self.account or _cs(job["client"]) != _cs(self.account.address)):
395
+ return {"jobId": jid, "state": st, "sent": False, "reason": "cancel is callable by the job client only"}
396
+ data = "0x" + SEL[fn] + abi_encode(["uint256"], [int(job_id)]).hex()
397
+ if not self.account:
398
+ return {"jobId": jid, "state": st, "action": fn, "sent": False, "reason": "no signer", "data": data, "to": self.escrow}
399
+ try:
400
+ self.chain.call(self.escrow, data, sender=self.account.address)
401
+ except Exception as e: # revert
402
+ return {"jobId": jid, "state": st, "action": fn, "sent": False, "reason": f"simulation reverted: {e}"}
403
+ if not send:
404
+ return {"jobId": jid, "state": st, "action": fn, "sent": False, "reason": "send=False (simulation ok)"}
405
+ h = self.chain.send_transaction(self.account, self.escrow, data)
406
+ rc = self.chain.wait_receipt(h)
407
+ return {"jobId": jid, "state": st, "action": fn, "sent": True, "tx": h, "status": "success" if int(rc["status"]) == 1 else "reverted"}
408
+
409
+ def buy(self, service_id: str | None = None, task: str | None = None, budget: str | None = None, skill_id: str | None = None, mode: str = "direct",
410
+ body=None, wait_for_verdict: bool = True, deadline_seconds: int | None = None) -> dict:
411
+ """(route | service_id) -> place_order -> pay -> (escrow: wait for verdict) -> verify. Candidates filtered by allowed_service_ids."""
412
+ route = None
413
+ if not service_id:
414
+ if not task:
415
+ raise AgentCoinError("bad_args", "service_id or task required")
416
+ route = self.route_task(task, budget or str(self.max_payment))
417
+ cands = route.get("candidates") or []
418
+ c = next((x for x in cands if self.allowed_service_ids is None or (x.get("serviceId") or x.get("id")) in self.allowed_service_ids), None)
419
+ if not c:
420
+ raise AgentCoinError("no_candidate", "no routed candidate within allowed_service_ids and budget", {"candidates": [x.get("serviceId") or x.get("id") for x in cands]})
421
+ service_id = c.get("serviceId") or c.get("id")
422
+ order = self.place_order(service_id, skill_id, mode, deadline_seconds)
423
+ paid = self.pay_escrow(order, body) if mode == "escrow" else self.pay_direct(order, body)
424
+ final = self.wait_for_verdict(order["orderId"]) if mode == "escrow" and wait_for_verdict else self.get_order(order["orderId"])
425
+ verification = self.verify(service_id=service_id, order_id=order["orderId"])
426
+ job = final.get("job") or {}
427
+ return {"serviceId": service_id, "routedFrom": {"candidates": len(route.get("candidates") or [])} if route else None,
428
+ "order": {k: v for k, v in paid.summary().items() if k != "deliverable"}, "deliverable": paid.deliverable,
429
+ "final": {"status": final.get("status"), "verdict": final.get("verdict"), "deliverableHash": final.get("deliverableHash"), "jobState": job.get("stateName") or job.get("state")},
430
+ "verification": verification, "testnet": True}
@@ -0,0 +1,38 @@
1
+ """Deployment constants for the AgentCoin v0.5 router on Base Sepolia (chainId 84532)."""
2
+
3
+ import os as _os
4
+ from typing import Mapping as _Mapping, Optional as _Optional
5
+
6
+ #: Default AgentCoin service URL (Base Sepolia testnet router). The only place the URL is defined in Python; override with AGENTCOIN_URL.
7
+ DEFAULT_AGENTCOIN_URL = "https://agentcoinhq.com"
8
+
9
+
10
+ def agentcoin_url(env: _Optional[_Mapping[str, str]] = None) -> str:
11
+ """Service URL: AGENTCOIN_URL, else legacy AGENTCOIN_BASE_URL, else DEFAULT_AGENTCOIN_URL. Trailing slashes removed."""
12
+ e = _os.environ if env is None else env
13
+ return (e.get("AGENTCOIN_URL") or e.get("AGENTCOIN_BASE_URL") or DEFAULT_AGENTCOIN_URL).rstrip("/")
14
+
15
+
16
+ BASE_SEPOLIA = {
17
+ "chain_id": 84532,
18
+ "caip2": "eip155:84532",
19
+ "x402_network_v1": "base-sepolia",
20
+ "rpc_url": "https://sepolia.base.org",
21
+ "explorer": "https://sepolia.basescan.org",
22
+ "router_url": DEFAULT_AGENTCOIN_URL,
23
+ "usdc": "0x036CbD53842c5426634e7929541eC2318f3dCF7e",
24
+ "usdc_eip712": {"name": "USDC", "version": "2"},
25
+ "escrow": "0x4EaF6d09F8C22980Bb16E719779ACe73A7b1CB3D",
26
+ "operator_signer": "0xf1b27b5Bd659D9Bfb4835777E64B8F8e5C3eCf68",
27
+ }
28
+
29
+ #: Chain ids treated as mainnet. Refused unless allow_mainnet is set; mainnet is unsupported in v0.1.
30
+ MAINNET_CHAIN_IDS = frozenset({1, 8453, 10, 137, 42161, 43114, 56, 324, 59144, 534352, 7777777, 81457, 100, 250, 1101, 5000, 130, 480, 146, 2741})
31
+
32
+ #: Default per-order payment ceiling: 50000 base units = 0.05 test USDC.
33
+ DEFAULT_MAX_PAYMENT = 50_000
34
+
35
+ ESCROW_STATES = ["None", "Open", "Funded", "Submitted", "Completed", "Rejected", "Partial", "Disputed", "Settled", "Expired", "Cancelled"]
36
+
37
+ GET_JOB_OUTPUT = "(address,address,address,uint32,uint8,uint8,bool,bool,uint16,uint64,uint64,uint64,uint64,uint256,uint256,uint256,bytes32,bytes32,bytes32)"
38
+ GET_JOB_FIELDS = ["client", "provider", "evaluator", "configVersion", "state", "outcome", "accepted", "instant", "payoutBps", "deadline", "submittedAt", "verdictAt", "disputedAt", "amount", "providerBond", "slashBase", "specHash", "deliverableHash", "reasonHash"]
agentcoin_core/env.py ADDED
@@ -0,0 +1,37 @@
1
+ from __future__ import annotations
2
+
3
+ import os
4
+
5
+ from .client import AgentCoin
6
+ from .constants import agentcoin_url
7
+
8
+
9
+ def from_env(env: dict | None = None, **overrides) -> AgentCoin:
10
+ """AGENTCOIN_PRIVATE_KEY (optional; read-only without it), AGENTCOIN_URL (legacy alias AGENTCOIN_BASE_URL), AGENTCOIN_CHAIN_ID (default 84532), AGENTCOIN_RPC_URL,
11
+ AGENTCOIN_MAX_PAYMENT (USDC base units), AGENTCOIN_ALLOWED_SERVICE_IDS (comma-separated), AGENTCOIN_ORIGIN."""
12
+ e = os.environ if env is None else env
13
+ kw: dict = {}
14
+ if e.get("AGENTCOIN_PRIVATE_KEY"):
15
+ kw["private_key"] = e["AGENTCOIN_PRIVATE_KEY"]
16
+ kw["base_url"] = agentcoin_url(e)
17
+ if e.get("AGENTCOIN_CHAIN_ID"):
18
+ kw["chain_id"] = int(e["AGENTCOIN_CHAIN_ID"])
19
+ if e.get("AGENTCOIN_RPC_URL"):
20
+ kw["rpc_url"] = e["AGENTCOIN_RPC_URL"]
21
+ if e.get("AGENTCOIN_MAX_PAYMENT"):
22
+ kw["max_payment"] = int(e["AGENTCOIN_MAX_PAYMENT"])
23
+ if e.get("AGENTCOIN_ALLOWED_SERVICE_IDS"):
24
+ kw["allowed_service_ids"] = [s.strip() for s in e["AGENTCOIN_ALLOWED_SERVICE_IDS"].split(",") if s.strip()]
25
+ if e.get("AGENTCOIN_ORIGIN") == "agentcoin":
26
+ kw["origin"] = "agentcoin"
27
+ kw.update(overrides)
28
+ return AgentCoin(**kw)
29
+
30
+
31
+ def as_client(x=None, **kw) -> AgentCoin:
32
+ """AgentCoin instance, a dict of AgentCoin kwargs, or None (environment variables)."""
33
+ if x is not None and hasattr(x, "find_service") and hasattr(x, "place_order"):
34
+ return x
35
+ if isinstance(x, dict):
36
+ return from_env(**{**x, **kw})
37
+ return from_env(**kw)
@@ -0,0 +1,7 @@
1
+ class AgentCoinError(Exception):
2
+ """Error with a stable machine-readable code (same codes as @agentkoin/core)."""
3
+
4
+ def __init__(self, code: str, message: str, details=None):
5
+ super().__init__(message)
6
+ self.code = code
7
+ self.details = details