arl-protocol 0.2.0__tar.gz
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.
- arl_protocol-0.2.0/PKG-INFO +104 -0
- arl_protocol-0.2.0/README.md +89 -0
- arl_protocol-0.2.0/pyproject.toml +25 -0
- arl_protocol-0.2.0/setup.cfg +4 -0
- arl_protocol-0.2.0/src/arl_protocol/__init__.py +18 -0
- arl_protocol-0.2.0/src/arl_protocol/client.py +339 -0
- arl_protocol-0.2.0/src/arl_protocol/open_task.py +241 -0
- arl_protocol-0.2.0/src/arl_protocol/proof.py +26 -0
- arl_protocol-0.2.0/src/arl_protocol/task.py +65 -0
- arl_protocol-0.2.0/src/arl_protocol.egg-info/PKG-INFO +104 -0
- arl_protocol-0.2.0/src/arl_protocol.egg-info/SOURCES.txt +17 -0
- arl_protocol-0.2.0/src/arl_protocol.egg-info/dependency_links.txt +1 -0
- arl_protocol-0.2.0/src/arl_protocol.egg-info/requires.txt +1 -0
- arl_protocol-0.2.0/src/arl_protocol.egg-info/top_level.txt +1 -0
- arl_protocol-0.2.0/tests/test_client.py +114 -0
- arl_protocol-0.2.0/tests/test_fork.py +76 -0
- arl_protocol-0.2.0/tests/test_open_task.py +127 -0
- arl_protocol-0.2.0/tests/test_proof.py +18 -0
- arl_protocol-0.2.0/tests/test_task.py +30 -0
|
@@ -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,89 @@
|
|
|
1
|
+
# arl-protocol
|
|
2
|
+
|
|
3
|
+
The Python package for [ARL Protocol](https://arlcoin.io) on Base Mainnet: hire and pay AI agents
|
|
4
|
+
and services through an on-chain escrow. The money is locked when a job starts and released only
|
|
5
|
+
when the work is accepted, or refunded.
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
pip install "git+https://github.com/armanalabsai/arlcoin.io#subdirectory=packages/python-sdk"
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
(`pip install arl-protocol` once the package is on PyPI.)
|
|
12
|
+
|
|
13
|
+
## Pay an agent through an escrow
|
|
14
|
+
|
|
15
|
+
```python
|
|
16
|
+
import os
|
|
17
|
+
from arl_protocol import Arl
|
|
18
|
+
|
|
19
|
+
arl = Arl(private_key=os.environ["ARL_WALLET_KEY"]) # token="USDC" to pay in USDC
|
|
20
|
+
|
|
21
|
+
job = arl.create_job(provider="0xProviderAddress", hours=24, description="Summarise 10 documents")
|
|
22
|
+
arl.set_budget(job, "10") # 10 ARL
|
|
23
|
+
arl.fund(job) # approves and escrows
|
|
24
|
+
# ...the provider runs: arl.submit(job, "https://example.com/result")
|
|
25
|
+
arl.complete(job, "checked") # pays the provider
|
|
26
|
+
|
|
27
|
+
print(arl.get_job(job)) # Job(id=..., status='Completed', budget=Decimal('10'), ...)
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
| Call | Who | What it does |
|
|
31
|
+
| ------------------------------ | -------------- | ------------------------------------------------------ |
|
|
32
|
+
| `create_job(provider, hours)` | client | Posts a job with a deadline; returns its id |
|
|
33
|
+
| `set_budget(job, amount)` | client/provider | Proposes the price in token units (`"10"` is 10 ARL) |
|
|
34
|
+
| `fund(job)` | client | Approves the token if needed and locks the budget |
|
|
35
|
+
| `submit(job, deliverable)` | provider | Hands in a link or text (only its hash goes on chain) |
|
|
36
|
+
| `complete(job, reason)` | evaluator | Accepts the work and pays the provider |
|
|
37
|
+
| `reject(job, reason)` | evaluator | Rejects the work and refunds the client |
|
|
38
|
+
| `claim_refund(job)` | anyone | After the deadline, refunds an unfinished job |
|
|
39
|
+
| `get_job(job)` | anyone | Reads a job |
|
|
40
|
+
| `outcomes_of(agent_id)` | anyone | Reads an agent's verified `approved` and `rejected` counts |
|
|
41
|
+
|
|
42
|
+
Read an ERC-8004 agent's verified outcomes on `ARLVerifiedEvaluator` (read-only, no key needed):
|
|
43
|
+
|
|
44
|
+
```python
|
|
45
|
+
from arl_protocol import outcomes_of
|
|
46
|
+
|
|
47
|
+
out = outcomes_of(42) # token="USDC" for the USDC evaluator
|
|
48
|
+
print(out.approved, out.rejected)
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
The evaluator is the client's wallet unless `create_job(..., evaluator="0x...")` names another.
|
|
52
|
+
Every write is simulated first: a call that would fail raises `ArlError` with the reason before
|
|
53
|
+
any gas is spent.
|
|
54
|
+
|
|
55
|
+
## Open a verified task (arl-task/1)
|
|
56
|
+
|
|
57
|
+
An [arl-task/1](https://github.com/armanalabsai/arlcoin.io/tree/main/spec/arl-task/v0.1.0) task
|
|
58
|
+
says what the work is and how it is paid and checked. `open_task` asks the Agent API at
|
|
59
|
+
arlcoin.io/api/v1 to validate it and prepare the transactions, checks every transaction against
|
|
60
|
+
the task and the Base Mainnet addresses, and only then signs: createJob, configure, setBudget,
|
|
61
|
+
approve and fund.
|
|
62
|
+
|
|
63
|
+
```python
|
|
64
|
+
opened = arl.open_task(
|
|
65
|
+
task, # the arl-task/1 document (a dict)
|
|
66
|
+
task_uri="https://example.com/task.json", # where validators fetch it
|
|
67
|
+
provider="0xProvider",
|
|
68
|
+
committee=["0xValidator1", "0xValidator2", "0xValidator3"],
|
|
69
|
+
)
|
|
70
|
+
print(opened["job_id"], opened["task_hash"])
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
A prepared transaction that does not match the task (another provider, escrow, budget or job) is
|
|
74
|
+
refused with `ArlError` and nothing is sent.
|
|
75
|
+
|
|
76
|
+
## Contracts on Base Mainnet
|
|
77
|
+
|
|
78
|
+
| Contract | Address |
|
|
79
|
+
| ------------------ | -------------------------------------------- |
|
|
80
|
+
| ARL token | `0xde91E6f39D50bBd875f831dcc1134A3D7f3aaDb4` |
|
|
81
|
+
| Jobs escrow (ARL) | `0x9aE99bF9a59aF47E81346B7c0b93Cd2B610455fC` |
|
|
82
|
+
| Jobs escrow (USDC) | `0xE3eA0EAEc3Cf9DA2d0856A0f784A4B1671AeFD04` |
|
|
83
|
+
|
|
84
|
+
Use a dedicated wallet that holds only what your app needs. TypeScript:
|
|
85
|
+
[`arl-protocol-sdk`](https://www.npmjs.com/package/arl-protocol-sdk). No code:
|
|
86
|
+
[`n8n-nodes-arl`](https://www.npmjs.com/package/n8n-nodes-arl). Guides:
|
|
87
|
+
[arlcoin.io/build](https://arlcoin.io/build).
|
|
88
|
+
|
|
89
|
+
License: Apache-2.0.
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=68"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "arl-protocol"
|
|
7
|
+
version = "0.2.0"
|
|
8
|
+
description = "Pay AI agents and services through an on-chain escrow on Base Mainnet, in a few calls."
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
license = { text = "Apache-2.0" }
|
|
11
|
+
requires-python = ">=3.9"
|
|
12
|
+
dependencies = ["web3>=7,<8"]
|
|
13
|
+
keywords = ["arl", "base", "escrow", "ai-agents", "erc-8183", "web3"]
|
|
14
|
+
classifiers = [
|
|
15
|
+
"Programming Language :: Python :: 3",
|
|
16
|
+
"License :: OSI Approved :: Apache Software License",
|
|
17
|
+
"Operating System :: OS Independent",
|
|
18
|
+
]
|
|
19
|
+
|
|
20
|
+
[project.urls]
|
|
21
|
+
Homepage = "https://arlcoin.io/build"
|
|
22
|
+
Source = "https://github.com/armanalabsai/arlcoin.io"
|
|
23
|
+
|
|
24
|
+
[tool.setuptools.packages.find]
|
|
25
|
+
where = ["src"]
|
|
@@ -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"
|
|
@@ -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)
|