arl-protocol 0.2.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.
@@ -0,0 +1,18 @@
1
+ """ARL Protocol for Python: escrowed jobs for AI agents on Base Mainnet, in a few calls.
2
+
3
+ from arl_protocol import Arl
4
+
5
+ arl = Arl(private_key=os.environ["ARL_WALLET_KEY"])
6
+ job = arl.create_job(provider="0xProvider", hours=24, description="Summarise 10 documents")
7
+ arl.set_budget(job, "10") # 10 ARL
8
+ arl.fund(job) # approves and escrows
9
+ arl.complete(job, "checked") # pays the provider
10
+
11
+ Amounts are plain token units ("10" is 10 ARL, or 10 USDC with token="USDC").
12
+ """
13
+
14
+ from .client import ESCROWS, EVALUATORS, STATUS, Arl, ArlError, Outcomes, outcomes_of
15
+ from .open_task import open_task
16
+
17
+ __all__ = ["Arl", "ArlError", "ESCROWS", "EVALUATORS", "Outcomes", "STATUS", "open_task", "outcomes_of"]
18
+ __version__ = "0.2.0"
arl_protocol/client.py ADDED
@@ -0,0 +1,339 @@
1
+ """The ARL escrows (ERC-8183) on Base Mainnet, wrapped in one small class.
2
+
3
+ Every write simulates first, so a call that would revert raises ArlError with the reason before
4
+ any gas is spent.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from dataclasses import dataclass
10
+ from decimal import Decimal
11
+
12
+ from web3 import Web3
13
+
14
+ BASE_MAINNET_CHAIN_ID = 8453
15
+ DEFAULT_RPC = "https://mainnet.base.org"
16
+ ZERO = "0x0000000000000000000000000000000000000000"
17
+
18
+ ESCROWS = {
19
+ "ARL": "0x9aE99bF9a59aF47E81346B7c0b93Cd2B610455fC",
20
+ "USDC": "0xE3eA0EAEc3Cf9DA2d0856A0f784A4B1671AeFD04",
21
+ }
22
+ EVALUATORS = {
23
+ "ARL": "0x6648e141cb7473822ddBd8bC039b91e5af3259B4",
24
+ "USDC": "0x6bFfdEace7d0B2F7711f604F0A5D2545be2961AF",
25
+ }
26
+ STATUS = ("Open", "Funded", "Submitted", "Completed", "Rejected", "Expired")
27
+
28
+
29
+ def _fn(name, inputs, outputs=(), mutability="nonpayable"):
30
+ return {
31
+ "type": "function",
32
+ "name": name,
33
+ "stateMutability": mutability,
34
+ "inputs": [{"name": n, "type": t} for n, t in inputs],
35
+ "outputs": [{"name": "", "type": t} for t in outputs],
36
+ }
37
+
38
+
39
+ JOB_TUPLE = {
40
+ "name": "",
41
+ "type": "tuple",
42
+ "components": [
43
+ {"name": n, "type": t}
44
+ for n, t in (
45
+ ("id", "uint256"),
46
+ ("client", "address"),
47
+ ("provider", "address"),
48
+ ("evaluator", "address"),
49
+ ("description", "string"),
50
+ ("budget", "uint256"),
51
+ ("expiredAt", "uint256"),
52
+ ("status", "uint8"),
53
+ ("hook", "address"),
54
+ )
55
+ ],
56
+ }
57
+
58
+ JOBS_ABI = [
59
+ _fn("paymentToken", [], ["address"], "view"),
60
+ {**_fn("getJob", [("jobId", "uint256")], [], "view"), "outputs": [JOB_TUPLE]},
61
+ _fn(
62
+ "createJob",
63
+ [
64
+ ("provider", "address"),
65
+ ("evaluator", "address"),
66
+ ("expiredAt", "uint256"),
67
+ ("description", "string"),
68
+ ("hook", "address"),
69
+ ],
70
+ ["uint256"],
71
+ ),
72
+ _fn("setBudget", [("jobId", "uint256"), ("amount", "uint256"), ("optParams", "bytes")]),
73
+ _fn("fund", [("jobId", "uint256"), ("expectedBudget", "uint256"), ("optParams", "bytes")]),
74
+ _fn("submit", [("jobId", "uint256"), ("deliverable", "bytes32"), ("optParams", "bytes")]),
75
+ _fn("complete", [("jobId", "uint256"), ("reason", "bytes32"), ("optParams", "bytes")]),
76
+ _fn("reject", [("jobId", "uint256"), ("reason", "bytes32"), ("optParams", "bytes")]),
77
+ _fn("claimRefund", [("jobId", "uint256")]),
78
+ {
79
+ "type": "event",
80
+ "name": "JobCreated",
81
+ "anonymous": False,
82
+ "inputs": [
83
+ {"name": "jobId", "type": "uint256", "indexed": True},
84
+ {"name": "client", "type": "address", "indexed": True},
85
+ {"name": "provider", "type": "address", "indexed": True},
86
+ {"name": "evaluator", "type": "address", "indexed": False},
87
+ {"name": "expiredAt", "type": "uint256", "indexed": False},
88
+ {"name": "hook", "type": "address", "indexed": False},
89
+ ],
90
+ },
91
+ ]
92
+
93
+ ERC20_ABI = [
94
+ _fn("decimals", [], ["uint8"], "view"),
95
+ _fn("allowance", [("owner", "address"), ("spender", "address")], ["uint256"], "view"),
96
+ _fn("approve", [("spender", "address"), ("amount", "uint256")], ["bool"]),
97
+ ]
98
+
99
+ EVALUATOR_ABI = [
100
+ _fn("outcomesOf", [("agentId", "uint256")], ["uint64", "uint64"], "view"),
101
+ ]
102
+
103
+
104
+ class ArlError(Exception):
105
+ """A job call that cannot go through, with a reason a person can act on."""
106
+
107
+
108
+ @dataclass
109
+ class Job:
110
+ id: int
111
+ client: str
112
+ provider: str
113
+ evaluator: str
114
+ description: str
115
+ budget: Decimal
116
+ expires_at: int
117
+ status: str
118
+
119
+
120
+ @dataclass
121
+ class Outcomes:
122
+ approved: int
123
+ rejected: int
124
+
125
+ def __iter__(self):
126
+ yield self.approved
127
+ yield self.rejected
128
+
129
+ def __getitem__(self, key: int | str) -> int:
130
+ if key in (0, "approved"):
131
+ return self.approved
132
+ if key in (1, "rejected"):
133
+ return self.rejected
134
+ raise KeyError(key)
135
+
136
+
137
+ def outcomes_of(
138
+ agent_id: int,
139
+ token: str = "ARL",
140
+ rpc_url: str = DEFAULT_RPC,
141
+ evaluator: str | None = None,
142
+ w3: Web3 | None = None,
143
+ ) -> Outcomes:
144
+ """Reads an ERC-8004 agent's approved and rejected job counts from ARLVerifiedEvaluator (read-only, no key)."""
145
+ if isinstance(agent_id, bool) or not isinstance(agent_id, int) or agent_id < 0:
146
+ raise ArlError(f"agent_id must be a non-negative integer, not {agent_id!r}")
147
+ if evaluator is None:
148
+ if token not in EVALUATORS:
149
+ raise ArlError(f"token must be ARL or USDC, not {token}")
150
+ address = EVALUATORS[token]
151
+ else:
152
+ address = Web3.to_checksum_address(evaluator)
153
+ client = w3 or Web3(Web3.HTTPProvider(rpc_url))
154
+ contract = client.eth.contract(address=address, abi=EVALUATOR_ABI)
155
+ raw = contract.functions.outcomesOf(agent_id).call()
156
+ return Outcomes(approved=int(raw[0]), rejected=int(raw[1]))
157
+
158
+
159
+ def to_bytes32(value: str | bytes) -> bytes:
160
+ """A 32-byte hash is used as it is; any other text is hashed (only the hash goes on chain)."""
161
+ if isinstance(value, bytes) and len(value) == 32:
162
+ return value
163
+ text = str(value).strip()
164
+ if text.startswith("0x") and len(text) == 66:
165
+ return bytes.fromhex(text[2:])
166
+ if not text:
167
+ raise ArlError("the deliverable or reason is empty")
168
+ return Web3.keccak(text=text)
169
+
170
+
171
+ def to_units(amount: str | int | float | Decimal, decimals: int) -> int:
172
+ value = Decimal(str(amount))
173
+ if value <= 0:
174
+ raise ArlError(f"the amount must be above zero: {amount}")
175
+ units = value * (Decimal(10) ** decimals)
176
+ if units != units.to_integral_value():
177
+ raise ArlError(f"too many decimals for this token: {amount}")
178
+ return int(units)
179
+
180
+
181
+ class Arl:
182
+ """One wallet, one escrow (ARL by default, or USDC), on Base Mainnet."""
183
+
184
+ def __init__(self, private_key: str | None = None, token: str = "ARL", rpc_url: str = DEFAULT_RPC):
185
+ if token not in ESCROWS:
186
+ raise ArlError(f"token must be ARL or USDC, not {token}")
187
+ self.token_name = token
188
+ self.w3 = Web3(Web3.HTTPProvider(rpc_url))
189
+ self.account = self.w3.eth.account.from_key(private_key) if private_key is not None else None
190
+ self.address = self.account.address if self.account is not None else None
191
+ self.jobs = self.w3.eth.contract(address=ESCROWS[token], abi=JOBS_ABI)
192
+ self.evaluator = self.w3.eth.contract(address=EVALUATORS[token], abi=EVALUATOR_ABI)
193
+ self._token = None
194
+ self._decimals = None
195
+
196
+ # ------------------------------------------------------------------ helpers
197
+
198
+ def _check_chain(self) -> None:
199
+ chain = self.w3.eth.chain_id
200
+ if chain != BASE_MAINNET_CHAIN_ID:
201
+ raise ArlError(f"the RPC serves chain {chain}, not Base Mainnet (8453)")
202
+
203
+ @property
204
+ def token(self):
205
+ if self._token is None:
206
+ address = self.jobs.functions.paymentToken().call()
207
+ self._token = self.w3.eth.contract(address=address, abi=ERC20_ABI)
208
+ return self._token
209
+
210
+ @property
211
+ def decimals(self) -> int:
212
+ if self._decimals is None:
213
+ self._decimals = self.token.functions.decimals().call()
214
+ return self._decimals
215
+
216
+ def _send(self, call):
217
+ try:
218
+ call.call({"from": self.address})
219
+ except Exception as error: # the revert reason, before any gas is spent
220
+ raise ArlError(str(error)) from error
221
+ tx = call.build_transaction(
222
+ {"from": self.address, "nonce": self.w3.eth.get_transaction_count(self.address)}
223
+ )
224
+ signed = self.account.sign_transaction(tx)
225
+ tx_hash = self.w3.eth.send_raw_transaction(signed.raw_transaction)
226
+ receipt = self.w3.eth.wait_for_transaction_receipt(tx_hash)
227
+ if receipt.status != 1:
228
+ raise ArlError(f"transaction {tx_hash.hex()} reverted")
229
+ return receipt
230
+
231
+ def _send_raw(self, to: str, data: str):
232
+ """Sends prepared calldata (checked by the caller) after simulating it."""
233
+ tx = {"from": self.address, "to": Web3.to_checksum_address(to), "data": data, "value": 0}
234
+ try:
235
+ self.w3.eth.call(tx)
236
+ except Exception as error: # the revert reason, before any gas is spent
237
+ raise ArlError(str(error)) from error
238
+ tx["nonce"] = self.w3.eth.get_transaction_count(self.address)
239
+ tx["chainId"] = BASE_MAINNET_CHAIN_ID
240
+ tx["gas"] = self.w3.eth.estimate_gas(tx)
241
+ tx["maxFeePerGas"] = self.w3.eth.gas_price * 2
242
+ tx["maxPriorityFeePerGas"] = self.w3.eth.max_priority_fee
243
+ signed = self.account.sign_transaction(tx)
244
+ tx_hash = self.w3.eth.send_raw_transaction(signed.raw_transaction)
245
+ receipt = self.w3.eth.wait_for_transaction_receipt(tx_hash)
246
+ if receipt.status != 1:
247
+ raise ArlError(f"transaction {tx_hash.hex()} reverted")
248
+ return receipt
249
+
250
+ # ------------------------------------------------------------------ verified tasks
251
+
252
+ def open_task(self, task: dict, task_uri: str, provider: str, committee: list, **kwargs) -> dict:
253
+ """Opens and funds an arl-task/1 task as a verified job (arl_protocol.open_task)."""
254
+ from .open_task import open_task
255
+
256
+ return open_task(self, task, task_uri, provider, committee, **kwargs)
257
+
258
+ # ------------------------------------------------------------------ jobs
259
+
260
+ def create_job(
261
+ self, provider: str, hours: float = 24, description: str = "", evaluator: str | None = None
262
+ ) -> int:
263
+ """Posts a job for `provider`. The evaluator is this wallet unless another is named."""
264
+ self._check_chain()
265
+ if not 1 <= hours <= 24 * 365:
266
+ raise ArlError("the deadline must be between 1 hour and 365 days away")
267
+ expires = self.w3.eth.get_block("latest")["timestamp"] + int(hours * 3600)
268
+ receipt = self._send(
269
+ self.jobs.functions.createJob(
270
+ Web3.to_checksum_address(provider),
271
+ Web3.to_checksum_address(evaluator or self.address),
272
+ expires,
273
+ description,
274
+ ZERO,
275
+ )
276
+ )
277
+ events = self.jobs.events.JobCreated().process_receipt(receipt)
278
+ if not events:
279
+ raise ArlError("the job was created but its id could not be read")
280
+ return int(events[0]["args"]["jobId"])
281
+
282
+ def set_budget(self, job_id: int, amount: str | int | float | Decimal) -> str:
283
+ """Client or provider proposes the price, in token units."""
284
+ self._check_chain()
285
+ units = to_units(amount, self.decimals)
286
+ return self._send(self.jobs.functions.setBudget(job_id, units, b"")).transactionHash.hex()
287
+
288
+ def fund(self, job_id: int) -> str:
289
+ """Escrows the agreed budget, approving the escrow first when needed."""
290
+ self._check_chain()
291
+ budget = self.jobs.functions.getJob(job_id).call()[5]
292
+ if budget == 0:
293
+ raise ArlError("no budget is set: call set_budget first")
294
+ allowance = self.token.functions.allowance(self.address, self.jobs.address).call()
295
+ if allowance < budget:
296
+ self._send(self.token.functions.approve(self.jobs.address, budget))
297
+ return self._send(self.jobs.functions.fund(job_id, budget, b"")).transactionHash.hex()
298
+
299
+ def submit(self, job_id: int, deliverable: str | bytes) -> str:
300
+ """Provider hands in the work: a link or text is hashed, a 32-byte hash is kept."""
301
+ self._check_chain()
302
+ call = self.jobs.functions.submit(job_id, to_bytes32(deliverable), b"")
303
+ return self._send(call).transactionHash.hex()
304
+
305
+ def complete(self, job_id: int, reason: str = "complete") -> str:
306
+ """Evaluator accepts the work: the escrow pays the provider."""
307
+ self._check_chain()
308
+ call = self.jobs.functions.complete(job_id, to_bytes32(reason or "complete"), b"")
309
+ return self._send(call).transactionHash.hex()
310
+
311
+ def reject(self, job_id: int, reason: str = "reject") -> str:
312
+ """Evaluator rejects the work: the escrow refunds the client."""
313
+ self._check_chain()
314
+ call = self.jobs.functions.reject(job_id, to_bytes32(reason or "reject"), b"")
315
+ return self._send(call).transactionHash.hex()
316
+
317
+ def claim_refund(self, job_id: int) -> str:
318
+ """After the deadline, returns an unfinished job's escrow to the client."""
319
+ self._check_chain()
320
+ return self._send(self.jobs.functions.claimRefund(job_id)).transactionHash.hex()
321
+
322
+ def get_job(self, job_id: int) -> Job:
323
+ raw = self.jobs.functions.getJob(job_id).call()
324
+ if raw[0] == 0:
325
+ raise ArlError(f"job {job_id} does not exist")
326
+ return Job(
327
+ id=raw[0],
328
+ client=raw[1],
329
+ provider=raw[2],
330
+ evaluator=raw[3],
331
+ description=raw[4],
332
+ budget=Decimal(raw[5]) / (Decimal(10) ** self.decimals),
333
+ expires_at=raw[6],
334
+ status=STATUS[raw[7]] if raw[7] < len(STATUS) else str(raw[7]),
335
+ )
336
+
337
+ def outcomes_of(self, agent_id: int, evaluator: str | None = None) -> Outcomes:
338
+ """Reads an ERC-8004 agent's approved and rejected job counts from the verified evaluator."""
339
+ return outcomes_of(agent_id, token=self.token_name, evaluator=evaluator, w3=self.w3)
@@ -0,0 +1,241 @@
1
+ """Open an arl-task/1 task as a verified job, from Python.
2
+
3
+ The Agent API (https://arlcoin.io/api/v1) validates the task against its policy and prepares the
4
+ unsigned transactions; this module checks every transaction against the task and the known Base
5
+ Mainnet addresses before the wallet signs it, so a wrong or tampered answer is refused, never
6
+ sent. The same calls are what `openTask` sends in the TypeScript SDK.
7
+
8
+ from arl_protocol import Arl
9
+
10
+ arl = Arl(private_key=os.environ["ARL_WALLET_KEY"])
11
+ opened = arl.open_task(task, task_uri="https://example.com/task.json",
12
+ provider="0xProvider", committee=["0xV1", "0xV2", "0xV3"])
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import json
18
+ import time
19
+ import urllib.error
20
+ import urllib.request
21
+ from typing import Any, Callable
22
+
23
+ from web3 import Web3
24
+
25
+ from .client import ERC20_ABI, ESCROWS, JOBS_ABI, ArlError
26
+ from .task import committed_spec_hash, task_hash
27
+
28
+ AGENT_API = "https://arlcoin.io/api/v1"
29
+
30
+ #: The verified evaluator bound to each escrow on Base Mainnet (docs/mainnet-services.md).
31
+ EVALUATORS = {
32
+ "ARL": "0x6648e141cb7473822ddBd8bC039b91e5af3259B4",
33
+ "USDC": "0x6bFfdEace7d0B2F7711f604F0A5D2545be2961AF",
34
+ }
35
+
36
+ CONFIGURE_ABI = [
37
+ {
38
+ "type": "function",
39
+ "name": "configure",
40
+ "stateMutability": "nonpayable",
41
+ "inputs": [
42
+ {"name": "jobId", "type": "uint256"},
43
+ {
44
+ "name": "cfg",
45
+ "type": "tuple",
46
+ "components": [
47
+ {"name": "tier", "type": "uint8"},
48
+ {"name": "threshold", "type": "uint8"},
49
+ {"name": "voteWindow", "type": "uint64"},
50
+ {"name": "challengeWindow", "type": "uint64"},
51
+ {"name": "bond", "type": "uint96"},
52
+ {"name": "providerAgentId", "type": "uint256"},
53
+ {"name": "specHash", "type": "bytes32"},
54
+ {"name": "committee", "type": "address[]"},
55
+ ],
56
+ },
57
+ ],
58
+ "outputs": [],
59
+ }
60
+ ]
61
+
62
+ Post = Callable[[str, dict], dict]
63
+
64
+ TIER_INDEX = {"fallback": 0, "reexecution": 1, "attested": 2}
65
+ #: How far the API's createJob deadline may sit from now + deadline_hours (block-time drift).
66
+ DEADLINE_TOLERANCE = 600
67
+
68
+
69
+ def http_post(url: str, body: dict) -> dict:
70
+ """POST JSON, return JSON; an API refusal (4xx/5xx) becomes ArlError with its reason."""
71
+ request = urllib.request.Request(
72
+ url,
73
+ data=json.dumps(body).encode(),
74
+ headers={"content-type": "application/json", "user-agent": "arl-protocol-python/0.2.0"},
75
+ method="POST",
76
+ )
77
+ try:
78
+ with urllib.request.urlopen(request, timeout=30) as response: # noqa: S310 (https only)
79
+ return json.loads(response.read())
80
+ except urllib.error.HTTPError as error:
81
+ try:
82
+ reason = json.loads(error.read()).get("error", str(error))
83
+ except Exception: # pragma: no cover - a non-JSON error body
84
+ reason = str(error)
85
+ raise ArlError(reason) from error
86
+
87
+
88
+ def _same(a: str, b: str) -> bool:
89
+ return Web3.to_checksum_address(a) == Web3.to_checksum_address(b)
90
+
91
+
92
+ def check_create(
93
+ task: dict, token: str, provider: str, answer: dict, now: int | None = None
94
+ ) -> dict:
95
+ """The createJob transaction, after checking it opens exactly this task on its escrow.
96
+
97
+ With `now` (the latest block's timestamp), the deadline must also be the task's
98
+ deadline_hours from now, within DEADLINE_TOLERANCE seconds."""
99
+ txs = answer.get("transactions") or []
100
+ if answer.get("chainId") != 8453 or len(txs) != 1 or txs[0].get("step") != "createJob":
101
+ raise ArlError("the API did not return one createJob transaction for Base Mainnet")
102
+ tx = txs[0]
103
+ if not _same(tx["to"], ESCROWS[token]) or str(tx.get("value", "0")) != "0":
104
+ raise ArlError("createJob does not go to ARL's escrow, or sends value")
105
+ jobs = Web3().eth.contract(address=ESCROWS[token], abi=JOBS_ABI)
106
+ fn, args = jobs.decode_function_input(tx["data"])
107
+ if fn.fn_name != "createJob":
108
+ raise ArlError("the transaction is not createJob")
109
+ if not _same(args["provider"], provider) or not _same(args["evaluator"], EVALUATORS[token]):
110
+ raise ArlError("createJob names another provider or evaluator")
111
+ if not args["description"].startswith(f"arl-task:{task_hash(task)} "):
112
+ raise ArlError("createJob does not carry this task's hash")
113
+ if now is not None:
114
+ expected = now + int(task["payment"]["deadline_hours"]) * 3600
115
+ if abs(int(args["expiredAt"]) - expected) > DEADLINE_TOLERANCE:
116
+ raise ArlError("createJob's deadline is not the task's deadline_hours")
117
+ return tx
118
+
119
+
120
+ def _check_config(task: dict, committee: list, cfg: Any) -> None:
121
+ """The committee's terms must be the task's, with the caller's own committee."""
122
+ v = task["verification"]
123
+ if isinstance(cfg, dict): # web3 decodes the struct by field name
124
+ cfg = tuple(
125
+ cfg[k]
126
+ for k in (
127
+ "tier",
128
+ "threshold",
129
+ "voteWindow",
130
+ "challengeWindow",
131
+ "bond",
132
+ "providerAgentId",
133
+ "specHash",
134
+ "committee",
135
+ )
136
+ )
137
+ tier, threshold, vote_window, challenge_window, bond, agent_id, spec_hash, members = cfg
138
+ expected = (
139
+ TIER_INDEX[v["tier"]],
140
+ int(v["threshold"]),
141
+ int(v["vote_window_seconds"]),
142
+ int(v["challenge_window_seconds"]),
143
+ int(v["bond_floor"]),
144
+ 0,
145
+ )
146
+ got = (tier, threshold, vote_window, challenge_window, bond, agent_id)
147
+ if got != expected:
148
+ raise ArlError("configure's tier, threshold, windows or bond differ from the task")
149
+ if "0x" + bytes(spec_hash).hex() != committed_spec_hash(task).lower():
150
+ raise ArlError("configure commits to another spec hash than the task")
151
+ if len(members) != len(committee) or not all(
152
+ _same(a, b) for a, b in zip(members, committee)
153
+ ):
154
+ raise ArlError("configure names another committee than the one you chose")
155
+
156
+
157
+ def check_funding(
158
+ task: dict, token: str, token_address: str, job_id: int, answer: dict, committee: list
159
+ ) -> list:
160
+ """configure, setBudget, approve and fund for `job_id`, checked against the task and the
161
+ caller's committee."""
162
+ txs = answer.get("transactions") or []
163
+ steps = [t.get("step") for t in txs]
164
+ if answer.get("chainId") != 8453 or steps != ["configure", "setBudget", "approve", "fund"]:
165
+ raise ArlError("the API did not return configure, setBudget, approve and fund")
166
+ budget = int(task["payment"]["budget"])
167
+ w3 = Web3()
168
+ jobs = w3.eth.contract(address=ESCROWS[token], abi=JOBS_ABI)
169
+ evaluator = w3.eth.contract(address=EVALUATORS[token], abi=CONFIGURE_ABI)
170
+ erc20 = w3.eth.contract(address=Web3.to_checksum_address(token_address), abi=ERC20_ABI)
171
+ expected = {
172
+ "configure": (EVALUATORS[token], evaluator),
173
+ "setBudget": (ESCROWS[token], jobs),
174
+ "approve": (token_address, erc20),
175
+ "fund": (ESCROWS[token], jobs),
176
+ }
177
+ for tx in txs:
178
+ to, contract = expected[tx["step"]]
179
+ if not _same(tx["to"], to) or str(tx.get("value", "0")) != "0":
180
+ raise ArlError(f"{tx['step']} goes to an unexpected address or sends value")
181
+ fn, args = contract.decode_function_input(tx["data"])
182
+ if fn.fn_name != tx["step"]:
183
+ raise ArlError(f"{tx['step']} encodes another call ({fn.fn_name})")
184
+ if tx["step"] == "approve":
185
+ if not _same(args["spender"], ESCROWS[token]) or args["amount"] != budget:
186
+ raise ArlError("approve is not exactly the budget for ARL's escrow")
187
+ elif args["jobId"] != job_id:
188
+ raise ArlError(f"{tx['step']} is for another job")
189
+ elif tx["step"] == "configure":
190
+ _check_config(task, committee, args["cfg"])
191
+ elif tx["step"] in ("setBudget", "fund"):
192
+ amount = args["amount"] if tx["step"] == "setBudget" else args["expectedBudget"]
193
+ if amount != budget:
194
+ raise ArlError(f"{tx['step']} is not the task's budget")
195
+ return txs
196
+
197
+
198
+ def open_task(
199
+ arl: Any,
200
+ task: dict,
201
+ task_uri: str,
202
+ provider: str,
203
+ committee: list,
204
+ api_url: str = AGENT_API,
205
+ post: Post = http_post,
206
+ ) -> dict:
207
+ """Opens and funds `task` as a verified job from `arl`'s wallet. See the module docstring."""
208
+ token = (task.get("payment") or {}).get("token")
209
+ if token not in ESCROWS:
210
+ raise ArlError('the task must be paid in "ARL" or "USDC"')
211
+ if not _same(arl.jobs.address, ESCROWS[token]):
212
+ raise ArlError(f"this task is paid in {token}: use Arl(..., token={token!r})")
213
+ arl._check_chain()
214
+ body = {
215
+ "task": task,
216
+ "taskUri": task_uri,
217
+ "client": arl.address,
218
+ "provider": provider,
219
+ "committee": committee,
220
+ }
221
+ now = int(arl.w3.eth.get_block("latest")["timestamp"])
222
+ create = check_create(task, token, provider, post(f"{api_url}/jobs/prepare", body), now)
223
+ receipt = arl._send_raw(create["to"], create["data"])
224
+ events = arl.jobs.events.JobCreated().process_receipt(receipt)
225
+ if not events:
226
+ raise ArlError("the job was created but its id could not be read")
227
+ job_id = int(events[0]["args"]["jobId"])
228
+ # The API reads the chain through public RPCs that can lag a block behind the new job.
229
+ for attempt in range(5):
230
+ try:
231
+ answer = post(f"{api_url}/jobs/prepare-funding", {**body, "jobId": str(job_id)})
232
+ break
233
+ except ArlError as error:
234
+ if attempt == 4 or "does not exist" not in str(error):
235
+ raise
236
+ time.sleep(3)
237
+ txs = check_funding(task, token, arl.token.address, job_id, answer, committee)
238
+ hashes = {"createJob": receipt.transactionHash.hex()}
239
+ for tx in txs:
240
+ hashes[tx["step"]] = arl._send_raw(tx["to"], tx["data"]).transactionHash.hex()
241
+ return {"job_id": job_id, "task_hash": task_hash(task), "transactions": hashes}
arl_protocol/proof.py ADDED
@@ -0,0 +1,26 @@
1
+ """arl-proof/1 hashing in Python, identical to @arl/protocol (spec/arl-proof/v0.1.0)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from web3 import Web3
6
+
7
+ from .task import CanonicalError, canonicalize
8
+
9
+ PROOF_VERSION = "arl-proof/1"
10
+
11
+
12
+ def _keccak(document: dict) -> str:
13
+ return "0x" + Web3.keccak(text=canonicalize(document)).hex().removeprefix("0x")
14
+
15
+
16
+ def proof_hash(proof: dict) -> str:
17
+ """keccak256 of the canonical proof, as 0x-prefixed lowercase hex."""
18
+ if not isinstance(proof, dict) or proof.get("version") != PROOF_VERSION:
19
+ raise CanonicalError(f"version must be {PROOF_VERSION}")
20
+ return _keccak(proof)
21
+
22
+
23
+ def submitted_deliverable(proof: dict) -> str:
24
+ """The bytes32 for ARLJobs.submit: the result manifest hash (reexec) or the proof hash."""
25
+ manifest = proof.get("result_manifest")
26
+ return _keccak(manifest) if manifest is not None else proof_hash(proof)
arl_protocol/task.py ADDED
@@ -0,0 +1,65 @@
1
+ """arl-task/1 hashing in Python, identical to @arl/protocol (spec/arl-task/v0.1.0).
2
+
3
+ The task hash is keccak256 over canonical JSON: object keys sorted, no whitespace, strings
4
+ escaped as JSON.stringify does, integers only. Floats are refused so number formatting cannot
5
+ differ between implementations.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import json
11
+ from typing import Any
12
+
13
+ from web3 import Web3
14
+
15
+ TASK_VERSION = "arl-task/1"
16
+
17
+
18
+ class CanonicalError(ValueError):
19
+ """A value that has no canonical JSON form."""
20
+
21
+
22
+ def _canonical(value: Any) -> str:
23
+ if value is None or isinstance(value, bool):
24
+ return json.dumps(value)
25
+ if isinstance(value, int):
26
+ if abs(value) > 2**53 - 1:
27
+ raise CanonicalError(f"not a safe integer: {value}")
28
+ return str(value)
29
+ if isinstance(value, float):
30
+ raise CanonicalError(f"floats have no canonical form: {value}")
31
+ if isinstance(value, str):
32
+ return json.dumps(value, ensure_ascii=False)
33
+ if isinstance(value, list):
34
+ return "[" + ",".join(_canonical(v) for v in value) + "]"
35
+ if isinstance(value, dict):
36
+ for k in value:
37
+ if not isinstance(k, str) or not k.isascii():
38
+ raise CanonicalError("object keys must be ASCII strings")
39
+ items = sorted(value.items(), key=lambda kv: kv[0])
40
+ return (
41
+ "{"
42
+ + ",".join(json.dumps(k) + ":" + _canonical(v) for k, v in items)
43
+ + "}"
44
+ )
45
+ raise CanonicalError(f"cannot canonicalize a {type(value).__name__}")
46
+
47
+
48
+ def canonicalize(value: Any) -> str:
49
+ """The canonical JSON text of a document."""
50
+ return _canonical(value)
51
+
52
+
53
+ def task_hash(task: dict) -> str:
54
+ """keccak256 of the canonical task, as 0x-prefixed lowercase hex."""
55
+ if not isinstance(task, dict) or task.get("version") != TASK_VERSION:
56
+ raise CanonicalError(f"version must be {TASK_VERSION}")
57
+ return "0x" + Web3.keccak(text=canonicalize(task)).hex().removeprefix("0x")
58
+
59
+
60
+ def committed_spec_hash(task: dict) -> str:
61
+ """The specHash the evaluator commits to: a re-execution task's spec_hash, else its task hash."""
62
+ workload = task.get("workload") or {}
63
+ if workload.get("class") == "reexec" and workload.get("spec_hash") is not None:
64
+ return workload["spec_hash"]
65
+ return task_hash(task)
@@ -0,0 +1,104 @@
1
+ Metadata-Version: 2.4
2
+ Name: arl-protocol
3
+ Version: 0.2.0
4
+ Summary: Pay AI agents and services through an on-chain escrow on Base Mainnet, in a few calls.
5
+ License: Apache-2.0
6
+ Project-URL: Homepage, https://arlcoin.io/build
7
+ Project-URL: Source, https://github.com/armanalabsai/arlcoin.io
8
+ Keywords: arl,base,escrow,ai-agents,erc-8183,web3
9
+ Classifier: Programming Language :: Python :: 3
10
+ Classifier: License :: OSI Approved :: Apache Software License
11
+ Classifier: Operating System :: OS Independent
12
+ Requires-Python: >=3.9
13
+ Description-Content-Type: text/markdown
14
+ Requires-Dist: web3<8,>=7
15
+
16
+ # arl-protocol
17
+
18
+ The Python package for [ARL Protocol](https://arlcoin.io) on Base Mainnet: hire and pay AI agents
19
+ and services through an on-chain escrow. The money is locked when a job starts and released only
20
+ when the work is accepted, or refunded.
21
+
22
+ ```bash
23
+ pip install "git+https://github.com/armanalabsai/arlcoin.io#subdirectory=packages/python-sdk"
24
+ ```
25
+
26
+ (`pip install arl-protocol` once the package is on PyPI.)
27
+
28
+ ## Pay an agent through an escrow
29
+
30
+ ```python
31
+ import os
32
+ from arl_protocol import Arl
33
+
34
+ arl = Arl(private_key=os.environ["ARL_WALLET_KEY"]) # token="USDC" to pay in USDC
35
+
36
+ job = arl.create_job(provider="0xProviderAddress", hours=24, description="Summarise 10 documents")
37
+ arl.set_budget(job, "10") # 10 ARL
38
+ arl.fund(job) # approves and escrows
39
+ # ...the provider runs: arl.submit(job, "https://example.com/result")
40
+ arl.complete(job, "checked") # pays the provider
41
+
42
+ print(arl.get_job(job)) # Job(id=..., status='Completed', budget=Decimal('10'), ...)
43
+ ```
44
+
45
+ | Call | Who | What it does |
46
+ | ------------------------------ | -------------- | ------------------------------------------------------ |
47
+ | `create_job(provider, hours)` | client | Posts a job with a deadline; returns its id |
48
+ | `set_budget(job, amount)` | client/provider | Proposes the price in token units (`"10"` is 10 ARL) |
49
+ | `fund(job)` | client | Approves the token if needed and locks the budget |
50
+ | `submit(job, deliverable)` | provider | Hands in a link or text (only its hash goes on chain) |
51
+ | `complete(job, reason)` | evaluator | Accepts the work and pays the provider |
52
+ | `reject(job, reason)` | evaluator | Rejects the work and refunds the client |
53
+ | `claim_refund(job)` | anyone | After the deadline, refunds an unfinished job |
54
+ | `get_job(job)` | anyone | Reads a job |
55
+ | `outcomes_of(agent_id)` | anyone | Reads an agent's verified `approved` and `rejected` counts |
56
+
57
+ Read an ERC-8004 agent's verified outcomes on `ARLVerifiedEvaluator` (read-only, no key needed):
58
+
59
+ ```python
60
+ from arl_protocol import outcomes_of
61
+
62
+ out = outcomes_of(42) # token="USDC" for the USDC evaluator
63
+ print(out.approved, out.rejected)
64
+ ```
65
+
66
+ The evaluator is the client's wallet unless `create_job(..., evaluator="0x...")` names another.
67
+ Every write is simulated first: a call that would fail raises `ArlError` with the reason before
68
+ any gas is spent.
69
+
70
+ ## Open a verified task (arl-task/1)
71
+
72
+ An [arl-task/1](https://github.com/armanalabsai/arlcoin.io/tree/main/spec/arl-task/v0.1.0) task
73
+ says what the work is and how it is paid and checked. `open_task` asks the Agent API at
74
+ arlcoin.io/api/v1 to validate it and prepare the transactions, checks every transaction against
75
+ the task and the Base Mainnet addresses, and only then signs: createJob, configure, setBudget,
76
+ approve and fund.
77
+
78
+ ```python
79
+ opened = arl.open_task(
80
+ task, # the arl-task/1 document (a dict)
81
+ task_uri="https://example.com/task.json", # where validators fetch it
82
+ provider="0xProvider",
83
+ committee=["0xValidator1", "0xValidator2", "0xValidator3"],
84
+ )
85
+ print(opened["job_id"], opened["task_hash"])
86
+ ```
87
+
88
+ A prepared transaction that does not match the task (another provider, escrow, budget or job) is
89
+ refused with `ArlError` and nothing is sent.
90
+
91
+ ## Contracts on Base Mainnet
92
+
93
+ | Contract | Address |
94
+ | ------------------ | -------------------------------------------- |
95
+ | ARL token | `0xde91E6f39D50bBd875f831dcc1134A3D7f3aaDb4` |
96
+ | Jobs escrow (ARL) | `0x9aE99bF9a59aF47E81346B7c0b93Cd2B610455fC` |
97
+ | Jobs escrow (USDC) | `0xE3eA0EAEc3Cf9DA2d0856A0f784A4B1671AeFD04` |
98
+
99
+ Use a dedicated wallet that holds only what your app needs. TypeScript:
100
+ [`arl-protocol-sdk`](https://www.npmjs.com/package/arl-protocol-sdk). No code:
101
+ [`n8n-nodes-arl`](https://www.npmjs.com/package/n8n-nodes-arl). Guides:
102
+ [arlcoin.io/build](https://arlcoin.io/build).
103
+
104
+ License: Apache-2.0.
@@ -0,0 +1,9 @@
1
+ arl_protocol/__init__.py,sha256=9XzaNLVma735eMWO9Ua5sHEz22jgIPgHcJFjc2R2fJ8,776
2
+ arl_protocol/client.py,sha256=DveuL1trp8t3HExXr6kAbCpaHDMSlJV8hnCTjczoKIc,13313
3
+ arl_protocol/open_task.py,sha256=YFojGjX9MVGWxWzmhD1hrP1WoZSyMgfeg01VdfI_2mo,10119
4
+ arl_protocol/proof.py,sha256=V4y8WeSb3lZrgb-KNy2qc1TJVQ27k4mw-kptNIeLIek,893
5
+ arl_protocol/task.py,sha256=dYy_LkeEsjW5cnYyvaeGq3ToK7Elq85sdxGQywiU4p0,2323
6
+ arl_protocol-0.2.0.dist-info/METADATA,sha256=PZA0pgxRDj1jtUebJ2EnHSTO92Dwixckqgbv3qRre8U,4825
7
+ arl_protocol-0.2.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
8
+ arl_protocol-0.2.0.dist-info/top_level.txt,sha256=Yc2sMGIHhUUqYf79DHyru8EbeuF0hWdC2AfPd5md5NU,13
9
+ arl_protocol-0.2.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1 @@
1
+ arl_protocol