autonomo-sdk 0.1.2 → 0.1.4
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.
- package/README.md +19 -6
- package/dist/cli.js +120 -22
- package/dist/index.d.ts +66 -10
- package/dist/index.js +141 -46
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -4,7 +4,7 @@ One call for AI agents. Say what you need, and the SDK:
|
|
|
4
4
|
|
|
5
5
|
1. **Finds the right API** on [Autonomo](https://autonomo.fun), from your words and the kind of input you give
|
|
6
6
|
(a token or wallet address, a transaction hash, a link).
|
|
7
|
-
2. **Pays for it** with x402 on Robinhood Chain,
|
|
7
|
+
2. **Pays for it** with x402, in USDG or $AUTONOMO on Robinhood Chain, or USDC on Base, whichever the wallet can afford.
|
|
8
8
|
3. **Pays privately through [Gloam](https://gloam.trade)** when you ask, so the payment doesn't link to your wallet.
|
|
9
9
|
4. **Borrows from a [Borro](https://borro.markets) credit line** when the wallet is short of USDG.
|
|
10
10
|
5. **Keeps to your caps**: a most-per-call and a daily budget, checked before anything is signed.
|
|
@@ -41,6 +41,9 @@ await autonomo.quote("explain this transaction", { input: "0x…" }); // the API
|
|
|
41
41
|
|
|
42
42
|
To skip the search, name the API: `autonomo.call("", { slug: "token-risk", path: "/risk/0x…" })`.
|
|
43
43
|
|
|
44
|
+
To see what the wallet can pay with, `await autonomo.balances()` returns what it holds on both chains: USDG,
|
|
45
|
+
$AUTONOMO and ETH on Robinhood Chain, and USDC on Base. It only reads.
|
|
46
|
+
|
|
44
47
|
## From the terminal
|
|
45
48
|
|
|
46
49
|
The package also installs a command, for people and for agents that run shell commands. `find`, `quote`, `spend` and
|
|
@@ -64,8 +67,13 @@ npx autonomo-sdk call "explain this transaction" 0x… --max 0.02 --daily 0.5 --
|
|
|
64
67
|
| `find [words] [input]` | List APIs, best matches first |
|
|
65
68
|
| `quote <words> [input]` | The API a call would use, and its prices |
|
|
66
69
|
| `call <words> [input]` | Find the right API, pay for one call, print the answer |
|
|
67
|
-
| `price [token]`, `launches [n]`, `risk <token>`, `tx <hash>`, `portfolio <wallet>`, `read <link>`, `
|
|
70
|
+
| `price [token]`, `launches [n]`, `risk <token>`, `holders <token>`, `dev <token>`, `tx <hash>`, `payment <hash>`, `portfolio <wallet>`, `gas`, `read <link>`, `site <link or domain>`, `health <link>`, `jobs <words>` | Shortcuts for the official APIs |
|
|
68
71
|
| `spend` | Today's spending against your limits |
|
|
72
|
+
| `wallet` | What the wallet holds on Robinhood Chain and Base |
|
|
73
|
+
|
|
74
|
+
`--chain base` (or `robinhood`) goes with the shortcuts that read a chain: `price` with a token, `launches`, `risk`,
|
|
75
|
+
`holders`, `dev`, `tx`, `payment`, `portfolio` and `gas`. Left out, they read Robinhood Chain, and Base when the
|
|
76
|
+
token, wallet or transaction is only there.
|
|
69
77
|
|
|
70
78
|
`--max` and `--daily` set the USDG limits (`--max-autonomo` and `--daily-autonomo` for $AUTONOMO), `--pay-with`
|
|
71
79
|
picks the token and `--borro <credit line>` borrows when the wallet is short. At a terminal it shows the price and
|
|
@@ -100,7 +108,7 @@ own server (`npx -y @gloamtrade/mcp`) on your machine for that one payment and s
|
|
|
100
108
|
```ts
|
|
101
109
|
new Autonomo({
|
|
102
110
|
privateKey,
|
|
103
|
-
payWith: "auto", // or "usdg" / "autonomo"
|
|
111
|
+
payWith: "auto", // or "usdg" / "autonomo" / "usdc" (USDC on Base)
|
|
104
112
|
limits: {
|
|
105
113
|
perCall: { usdg: "0.05", autonomo: "5000" }, // the defaults
|
|
106
114
|
daily: { usdg: "1", autonomo: "10000" }, // per UTC day; Gloam and Borro count as USDG
|
|
@@ -145,15 +153,20 @@ When the wallet can't afford a call, the SDK asks Borro's MCP server to prepare
|
|
|
145
153
|
sends it from the wallet (this needs a little ETH for gas), waits for the USDG and pays. The line needs x402 bills
|
|
146
154
|
turned on; see [Pay with a Borro credit line](https://autonomo.fun/docs/borro). Borro's own daily limit still applies.
|
|
147
155
|
|
|
156
|
+
Borro's answer is checked before anything is signed. The SDK sends only one transaction: a `borrow` on your own credit
|
|
157
|
+
line, into this wallet, with no ETH attached, of no more than the call's price. Anything else in the answer, such as a
|
|
158
|
+
transfer, an approval or a second transaction, is refused with `borro_unsafe` and nothing is sent. The call's price is
|
|
159
|
+
still checked against your caps first.
|
|
160
|
+
|
|
148
161
|
## The receipt
|
|
149
162
|
|
|
150
163
|
| Field | |
|
|
151
164
|
| --- | --- |
|
|
152
165
|
| `api` | The API's slug and name |
|
|
153
|
-
| `route` | `usdg`, `autonomo`, `gloam` or `borro` |
|
|
154
|
-
| `amount`, `token` | What was paid |
|
|
166
|
+
| `route` | `usdg`, `autonomo`, `usdc`, `gloam` or `borro` |
|
|
167
|
+
| `amount`, `token`, `chain` | What was paid, and on which chain: `Robinhood Chain` or `Base` |
|
|
155
168
|
| `payer`, `payTo` | The wallet (or "private (Gloam)") and the API's payment address |
|
|
156
|
-
| `tx`, `explorer` | The payment transaction and its Blockscout
|
|
169
|
+
| `tx`, `explorer` | The payment transaction and its link on Blockscout, or on Basescan for Base |
|
|
157
170
|
| `borrowTxs`, `approveTx` | Borro borrows and the one-time Permit2 approval, when there were any |
|
|
158
171
|
| `spentToday` | Today's total against the daily budget |
|
|
159
172
|
|
package/dist/cli.js
CHANGED
|
@@ -25,22 +25,32 @@ Usage
|
|
|
25
25
|
autonomo quote <words> [input] The API a call would use and its prices. Free.
|
|
26
26
|
autonomo call <words> [input] Find the right API, pay for one call, print the answer.
|
|
27
27
|
autonomo spend Today's spending against your limits.
|
|
28
|
+
autonomo wallet What the wallet holds on Robinhood Chain and Base.
|
|
28
29
|
|
|
29
30
|
Shortcuts for the official APIs
|
|
30
|
-
autonomo price [token address] $AUTONOMO's price, or any
|
|
31
|
+
autonomo price [token address] $AUTONOMO's price, or any token's
|
|
31
32
|
autonomo launches [how many] Newest token launches
|
|
32
33
|
autonomo risk <token address> Rug-risk check
|
|
34
|
+
autonomo holders <token address> Top holders, bundles and snipers
|
|
35
|
+
autonomo dev <token address> What the token's creator did
|
|
33
36
|
autonomo tx <transaction hash> A transaction in plain words
|
|
37
|
+
autonomo payment <tx hash> Did an x402 payment settle, and who paid whom
|
|
34
38
|
autonomo portfolio <wallet> What a wallet holds
|
|
39
|
+
autonomo gas The gas price and what common actions cost
|
|
35
40
|
autonomo read <https link> A web page's text
|
|
36
|
-
autonomo
|
|
41
|
+
autonomo site <link or domain> Trust check for a website
|
|
42
|
+
autonomo health <https link> Is an x402 API up and payable
|
|
43
|
+
autonomo jobs <the work> Open paid jobs on Tokyo Futuro
|
|
37
44
|
|
|
38
45
|
Options
|
|
39
|
-
--max <
|
|
40
|
-
--daily <
|
|
46
|
+
--max <dollars> Most to pay for one call in USDG or USDC (default ${DEFAULT_LIMITS.perCall.usdg})
|
|
47
|
+
--daily <dollars> Most to spend per UTC day in USDG and USDC together (default ${DEFAULT_LIMITS.daily.usdg})
|
|
41
48
|
--max-autonomo <amount> The same two limits when paying in $AUTONOMO
|
|
42
49
|
--daily-autonomo <amount> (defaults ${DEFAULT_LIMITS.perCall.autonomo} and ${DEFAULT_LIMITS.daily.autonomo})
|
|
43
|
-
--pay-with <token> usdg, autonomo or auto (default: USDG, then $AUTONOMO)
|
|
50
|
+
--pay-with <token> usdg, autonomo, usdc or auto (default: USDG, then $AUTONOMO, then USDC on Base)
|
|
51
|
+
--chain <chain> robinhood or base, for the shortcuts that read a chain: price with a token, launches, risk,
|
|
52
|
+
holders, dev, tx, payment, portfolio and gas. Left out: Robinhood Chain, and Base when the
|
|
53
|
+
token, wallet or transaction is only there
|
|
44
54
|
--borro <credit line> Borrow from this Borro line when the wallet is short of USDG
|
|
45
55
|
--private Pay from your private Gloam balance, so the payment doesn't link to a wallet
|
|
46
56
|
--retry-header <header> With --private: finish a call Gloam paid for but the API didn't answer, without paying again
|
|
@@ -52,7 +62,8 @@ Options
|
|
|
52
62
|
|
|
53
63
|
Wallet
|
|
54
64
|
Set AUTONOMO_WALLET_KEY to the private key of a wallet made just for the agent, holding only what it may spend.
|
|
55
|
-
|
|
65
|
+
The same wallet pays with USDG or $AUTONOMO on Robinhood Chain, or with USDC on Base; it needs no ETH on either.
|
|
66
|
+
find, quote, spend and --dry-run need no wallet. wallet only reads balances and signs nothing.
|
|
56
67
|
|
|
57
68
|
Private payments
|
|
58
69
|
--private starts Gloam's own server on this machine (npx @gloamtrade/mcp) and has it pay in USDG. It needs no
|
|
@@ -71,40 +82,80 @@ class UsageError extends Error {
|
|
|
71
82
|
const usage = (message) => {
|
|
72
83
|
throw new UsageError(message);
|
|
73
84
|
};
|
|
74
|
-
/**
|
|
85
|
+
/**
|
|
86
|
+
* Each shortcut names its API and builds the path, so nothing is searched. `chain` marks the APIs that read a chain
|
|
87
|
+
* and so take --chain.
|
|
88
|
+
*/
|
|
75
89
|
const SHORTCUTS = {
|
|
76
90
|
price: ([token]) => {
|
|
91
|
+
// $AUTONOMO is a Robinhood Chain token, so on its own price takes no --chain.
|
|
77
92
|
if (token === undefined)
|
|
78
|
-
return { slug: "token-
|
|
93
|
+
return { slug: "token-lookup", path: `/price/${TOKENS.autonomo.address}` };
|
|
79
94
|
if (!ADDRESS.test(token))
|
|
80
95
|
usage("price takes a token contract address (0x and 40 hex characters), or nothing for $AUTONOMO.");
|
|
81
|
-
return { slug: "token-lookup", path: `/price/${token}
|
|
96
|
+
return { slug: "token-lookup", path: `/price/${token}`, chain: true };
|
|
82
97
|
},
|
|
83
98
|
launches: ([count = "10"]) => {
|
|
84
99
|
if (!/^\d{1,3}$/.test(count) || Number(count) < 1)
|
|
85
100
|
usage("launches takes how many to show, e.g. autonomo launches 5.");
|
|
86
|
-
return { slug: "new-launches", path: `/launches?limit=${Number(count)}
|
|
101
|
+
return { slug: "new-launches", path: `/launches?limit=${Number(count)}`, chain: true };
|
|
87
102
|
},
|
|
88
103
|
risk: ([token]) => {
|
|
89
104
|
if (!token || !ADDRESS.test(token))
|
|
90
105
|
usage("risk takes a token contract address: autonomo risk 0x…");
|
|
91
|
-
return { slug: "token-risk", path: `/risk/${token}
|
|
106
|
+
return { slug: "token-risk", path: `/risk/${token}`, chain: true };
|
|
107
|
+
},
|
|
108
|
+
holders: ([token]) => {
|
|
109
|
+
if (!token || !ADDRESS.test(token))
|
|
110
|
+
usage("holders takes a token contract address: autonomo holders 0x…");
|
|
111
|
+
return { slug: "holders-bundles", path: `/holders/${token}`, chain: true };
|
|
112
|
+
},
|
|
113
|
+
dev: ([token]) => {
|
|
114
|
+
if (!token || !ADDRESS.test(token))
|
|
115
|
+
usage("dev takes a token contract address: autonomo dev 0x…");
|
|
116
|
+
return { slug: "dev-wallet", path: `/dev/${token}`, chain: true };
|
|
92
117
|
},
|
|
93
118
|
tx: ([hash]) => {
|
|
94
119
|
if (!hash || !TX_HASH.test(hash))
|
|
95
120
|
usage("tx takes a transaction hash (0x and 64 hex characters).");
|
|
96
|
-
return { slug: "tx-explainer", path: `/tx/${hash}
|
|
121
|
+
return { slug: "tx-explainer", path: `/tx/${hash}`, chain: true };
|
|
122
|
+
},
|
|
123
|
+
payment: ([hash]) => {
|
|
124
|
+
if (!hash || !TX_HASH.test(hash))
|
|
125
|
+
usage("payment takes the payment's transaction hash (0x and 64 hex characters).");
|
|
126
|
+
return { slug: "payment-check", path: `/payment/${hash}`, chain: true };
|
|
97
127
|
},
|
|
98
128
|
portfolio: ([wallet]) => {
|
|
99
129
|
if (!wallet || !ADDRESS.test(wallet))
|
|
100
130
|
usage("portfolio takes a wallet address: autonomo portfolio 0x…");
|
|
101
|
-
return { slug: "wallet-portfolio", path: `/portfolio/${wallet}
|
|
131
|
+
return { slug: "wallet-portfolio", path: `/portfolio/${wallet}`, chain: true };
|
|
132
|
+
},
|
|
133
|
+
gas: (args) => {
|
|
134
|
+
if (args.length)
|
|
135
|
+
usage("gas takes nothing: autonomo gas, or autonomo gas --chain base.");
|
|
136
|
+
return { slug: "gas-now", path: "/gas", chain: true };
|
|
102
137
|
},
|
|
103
138
|
read: ([link]) => {
|
|
104
139
|
if (!link || !/^https:\/\/\S+$/i.test(link))
|
|
105
140
|
usage("read takes an https:// link.");
|
|
106
141
|
return { slug: "page-reader", path: `/page?url=${encodeURIComponent(link)}` };
|
|
107
142
|
},
|
|
143
|
+
site: ([site]) => {
|
|
144
|
+
if (!site || /\s/.test(site) || !/^(https?:\/\/)?[a-z0-9-]+(\.[a-z0-9-]+)+/i.test(site))
|
|
145
|
+
usage("site takes a website link or a domain: autonomo site example.com");
|
|
146
|
+
return { slug: "website-check", path: `/site?url=${encodeURIComponent(site)}` };
|
|
147
|
+
},
|
|
148
|
+
health: ([link]) => {
|
|
149
|
+
if (!link || !/^https:\/\/\S+$/i.test(link))
|
|
150
|
+
usage("health takes the https:// address of an x402 API.");
|
|
151
|
+
return { slug: "endpoint-health", path: `/endpoint?url=${encodeURIComponent(link)}` };
|
|
152
|
+
},
|
|
153
|
+
jobs: (words) => {
|
|
154
|
+
const q = words.join(" ").trim();
|
|
155
|
+
if (!q)
|
|
156
|
+
usage('jobs takes the work you are after: autonomo jobs "write a summary"');
|
|
157
|
+
return { slug: "tokyo-futuro-job-finder", path: `/jobs?q=${encodeURIComponent(q)}` };
|
|
158
|
+
},
|
|
108
159
|
offers: (words) => {
|
|
109
160
|
const q = words.join(" ").trim();
|
|
110
161
|
if (!q)
|
|
@@ -113,7 +164,11 @@ const SHORTCUTS = {
|
|
|
113
164
|
},
|
|
114
165
|
};
|
|
115
166
|
const price = (api) => {
|
|
116
|
-
const parts = [
|
|
167
|
+
const parts = [
|
|
168
|
+
api.price.usdg !== undefined && api.price.usdg !== null && `${api.price.usdg} USDG`,
|
|
169
|
+
api.price.autonomo !== undefined && api.price.autonomo !== null && `${api.price.autonomo} AUTONOMO`,
|
|
170
|
+
api.price.usdcBase !== undefined && api.price.usdcBase !== null && `${api.price.usdcBase} USDC on Base`,
|
|
171
|
+
].filter(Boolean);
|
|
117
172
|
return parts.join(" or ") || "see quote";
|
|
118
173
|
};
|
|
119
174
|
function exitFor(e) {
|
|
@@ -148,6 +203,7 @@ export async function run(argv, io) {
|
|
|
148
203
|
"daily-autonomo": { type: "string" },
|
|
149
204
|
"pay-with": { type: "string" },
|
|
150
205
|
borro: { type: "string" },
|
|
206
|
+
chain: { type: "string" },
|
|
151
207
|
private: { type: "boolean" },
|
|
152
208
|
"retry-header": { type: "string" },
|
|
153
209
|
slug: { type: "string" },
|
|
@@ -173,7 +229,7 @@ export async function run(argv, io) {
|
|
|
173
229
|
const amount = (flag) => {
|
|
174
230
|
const v = values[flag];
|
|
175
231
|
if (v !== undefined && !AMOUNT.test(v))
|
|
176
|
-
usage(`--${flag} takes an amount in whole tokens, e.g. --${flag} 0.05.`);
|
|
232
|
+
usage(`--${flag} takes an amount in whole tokens or dollars, e.g. --${flag} 0.05.`);
|
|
177
233
|
return v;
|
|
178
234
|
};
|
|
179
235
|
const limits = {
|
|
@@ -181,8 +237,8 @@ export async function run(argv, io) {
|
|
|
181
237
|
daily: { usdg: amount("daily") ?? DEFAULT_LIMITS.daily.usdg, autonomo: amount("daily-autonomo") ?? DEFAULT_LIMITS.daily.autonomo },
|
|
182
238
|
};
|
|
183
239
|
const payWith = values["pay-with"] ?? "auto";
|
|
184
|
-
if (payWith !== "usdg" && payWith !== "autonomo" && payWith !== "auto")
|
|
185
|
-
usage("--pay-with takes usdg, autonomo or auto.");
|
|
240
|
+
if (payWith !== "usdg" && payWith !== "autonomo" && payWith !== "usdc" && payWith !== "auto")
|
|
241
|
+
usage("--pay-with takes usdg, autonomo, usdc or auto.");
|
|
186
242
|
const borro = values.borro ?? io.env.AUTONOMO_BORRO_ACCOUNT;
|
|
187
243
|
if (borro !== undefined && !ADDRESS.test(borro))
|
|
188
244
|
usage("--borro takes the credit line's address.");
|
|
@@ -224,16 +280,45 @@ export async function run(argv, io) {
|
|
|
224
280
|
io.out(`${a.slug} ${price(a)}${a.verified ? " verified" : ""}\n ${a.name}: ${a.description}\n ${a.path}`);
|
|
225
281
|
return EXIT.ok;
|
|
226
282
|
}
|
|
283
|
+
if (command === "wallet") {
|
|
284
|
+
const b = await client(true).balances();
|
|
285
|
+
if (json)
|
|
286
|
+
return print(b), EXIT.ok;
|
|
287
|
+
const shown = (v) => Number(v).toLocaleString("en-US", { maximumFractionDigits: 6 });
|
|
288
|
+
io.out(`Wallet ${b.address}`);
|
|
289
|
+
io.out(` Robinhood Chain ${b.robinhood ? `${shown(b.robinhood.usdg)} USDG, ${shown(b.robinhood.autonomo)} AUTONOMO, ${shown(b.robinhood.eth)} ETH` : "couldn't be read just now"}`);
|
|
290
|
+
io.out(` Base ${b.base ? `${shown(b.base.usdc)} USDC` : "couldn't be read just now"}`);
|
|
291
|
+
if (b.robinhood && Number(b.robinhood.autonomo) > 0 && Number(b.robinhood.eth) === 0) {
|
|
292
|
+
io.err("Paying in $AUTONOMO needs a little ETH on Robinhood Chain once, for the Permit2 approval. USDG and USDC need none.");
|
|
293
|
+
}
|
|
294
|
+
return EXIT.ok;
|
|
295
|
+
}
|
|
227
296
|
if (command === "spend") {
|
|
228
297
|
const day = new Date().toISOString().slice(0, 10);
|
|
229
298
|
const spent = await store.get(day);
|
|
230
|
-
const
|
|
231
|
-
|
|
299
|
+
const usd = (t) => formatUnits(spent[t] ?? 0n, TOKENS[t].decimals);
|
|
300
|
+
// USDG and USDC on Base share the dollar limits.
|
|
301
|
+
const dollars = {
|
|
302
|
+
spent: formatUnits((spent.usdg ?? 0n) + (spent.usdc ?? 0n), 6),
|
|
303
|
+
usdg: usd("usdg"),
|
|
304
|
+
usdcBase: usd("usdc"),
|
|
305
|
+
daily: limits.daily.usdg,
|
|
306
|
+
perCall: limits.perCall.usdg,
|
|
307
|
+
};
|
|
308
|
+
const autonomo = { spent: usd("autonomo"), daily: limits.daily.autonomo, perCall: limits.perCall.autonomo };
|
|
309
|
+
// `usdg` keeps its shape from earlier versions and now holds the dollar limits: USDG and USDC on Base together.
|
|
310
|
+
const report = {
|
|
311
|
+
day,
|
|
312
|
+
wallet: client(true).address,
|
|
313
|
+
usdg: { spent: dollars.spent, daily: dollars.daily, perCall: dollars.perCall },
|
|
314
|
+
autonomo,
|
|
315
|
+
spentByToken: { usdg: dollars.usdg, usdcBase: dollars.usdcBase, autonomo: autonomo.spent },
|
|
316
|
+
};
|
|
232
317
|
if (json)
|
|
233
318
|
return print(report), EXIT.ok;
|
|
234
319
|
io.out(`Today (${day}, UTC)`);
|
|
235
|
-
io.out(`
|
|
236
|
-
io.out(` AUTONOMO ${
|
|
320
|
+
io.out(` Dollars ${dollars.spent} of ${dollars.daily} spent (USDG ${dollars.usdg}, USDC on Base ${dollars.usdcBase}), up to ${dollars.perCall} a call`);
|
|
321
|
+
io.out(` AUTONOMO ${autonomo.spent} of ${autonomo.daily} spent, up to ${autonomo.perCall} a call`);
|
|
237
322
|
io.out(` Wallet ${report.wallet ?? "none set (AUTONOMO_WALLET_KEY)"}`);
|
|
238
323
|
return EXIT.ok;
|
|
239
324
|
}
|
|
@@ -259,11 +344,24 @@ export async function run(argv, io) {
|
|
|
259
344
|
else if (Object.hasOwn(SHORTCUTS, command)) {
|
|
260
345
|
if (values.slug || values.path)
|
|
261
346
|
usage(`${command} already names its API. Use call with --slug and --path instead.`);
|
|
262
|
-
|
|
347
|
+
const shortcut = SHORTCUTS[command](rest);
|
|
348
|
+
let path = shortcut.path;
|
|
349
|
+
if (values.chain !== undefined) {
|
|
350
|
+
const chain = values.chain.toLowerCase();
|
|
351
|
+
if (chain !== "robinhood" && chain !== "base")
|
|
352
|
+
usage("--chain takes robinhood or base.");
|
|
353
|
+
if (!shortcut.chain)
|
|
354
|
+
usage(`${command}${rest.length ? "" : " on its own"} doesn't read a chain, so it takes no --chain.`);
|
|
355
|
+
path += `${path.includes("?") ? "&" : "?"}chain=${chain}`;
|
|
356
|
+
}
|
|
357
|
+
opts = { slug: shortcut.slug, path };
|
|
263
358
|
}
|
|
264
359
|
else {
|
|
265
360
|
return usage(`Unknown command "${command}". Run autonomo --help.`);
|
|
266
361
|
}
|
|
362
|
+
if (values.chain !== undefined && (command === "call" || command === "quote")) {
|
|
363
|
+
usage("--chain goes with the shortcuts. With call or quote, put chain=base in --path instead.");
|
|
364
|
+
}
|
|
267
365
|
if (quoteOnly) {
|
|
268
366
|
const q = await client(false).quote(words, opts);
|
|
269
367
|
if (json)
|
package/dist/index.d.ts
CHANGED
|
@@ -1,11 +1,18 @@
|
|
|
1
1
|
import { type Hex } from "viem";
|
|
2
|
-
export declare const VERSION = "0.1.
|
|
3
|
-
export type TokenName = "usdg" | "autonomo";
|
|
2
|
+
export declare const VERSION = "0.1.4";
|
|
3
|
+
export type TokenName = "usdg" | "autonomo" | "usdc";
|
|
4
|
+
/** The tokens with limits of their own. USDC on Base is held to the USDG (dollar) limits. */
|
|
5
|
+
type LimitName = "usdg" | "autonomo";
|
|
6
|
+
export type ChainName = "Robinhood Chain" | "Base";
|
|
4
7
|
type Token = {
|
|
5
8
|
name: TokenName;
|
|
6
9
|
symbol: string;
|
|
7
10
|
address: Hex;
|
|
8
11
|
decimals: number;
|
|
12
|
+
network: string;
|
|
13
|
+
chainId: number;
|
|
14
|
+
chain: ChainName;
|
|
15
|
+
explorer: string;
|
|
9
16
|
};
|
|
10
17
|
export declare const TOKENS: Record<TokenName, Token>;
|
|
11
18
|
export declare const DEFAULT_LIMITS: {
|
|
@@ -19,10 +26,10 @@ export declare const DEFAULT_LIMITS: {
|
|
|
19
26
|
};
|
|
20
27
|
};
|
|
21
28
|
export type Limits = {
|
|
22
|
-
/** Most to pay for one call, in whole tokens, e.g. { usdg: "0.05" }. */
|
|
23
|
-
perCall?: Partial<Record<
|
|
24
|
-
/** Most to spend per UTC day, in whole tokens. Gloam and Borro payments count
|
|
25
|
-
daily?: Partial<Record<
|
|
29
|
+
/** Most to pay for one call, in whole tokens, e.g. { usdg: "0.05" }. The usdg limit covers USDC on Base too. */
|
|
30
|
+
perCall?: Partial<Record<LimitName, string>>;
|
|
31
|
+
/** Most to spend per UTC day, in whole tokens. USDC on Base, Gloam and Borro payments count against the usdg limit. */
|
|
32
|
+
daily?: Partial<Record<LimitName, string>>;
|
|
26
33
|
};
|
|
27
34
|
/**
|
|
28
35
|
* Runs Gloam's `gloam_fetch_paid` tool (from `npx -y @gloamtrade/mcp`) with these arguments and returns its result:
|
|
@@ -52,7 +59,7 @@ export type SpendStore = {
|
|
|
52
59
|
export type AutonomoOptions = {
|
|
53
60
|
/** The agent wallet's private key. Use a wallet just for the agent, holding only what it may spend. */
|
|
54
61
|
privateKey?: Hex | string;
|
|
55
|
-
/** Which token to pay with. "auto" (default) tries USDG, then $AUTONOMO. */
|
|
62
|
+
/** Which token to pay with. "auto" (default) tries USDG, then $AUTONOMO, then USDC on Base. */
|
|
56
63
|
payWith?: TokenName | "auto";
|
|
57
64
|
limits?: Limits;
|
|
58
65
|
/** Pay privately through Gloam when a call asks for `private: true`. */
|
|
@@ -66,7 +73,10 @@ export type AutonomoOptions = {
|
|
|
66
73
|
};
|
|
67
74
|
spendStore?: SpendStore;
|
|
68
75
|
baseUrl?: string;
|
|
76
|
+
/** Robinhood Chain RPC. */
|
|
69
77
|
rpcUrl?: string;
|
|
78
|
+
/** Base RPC, for USDC balances. Defaults to https://mainnet.base.org. */
|
|
79
|
+
baseRpcUrl?: string;
|
|
70
80
|
fetch?: typeof fetch;
|
|
71
81
|
};
|
|
72
82
|
export type Api = {
|
|
@@ -77,6 +87,7 @@ export type Api = {
|
|
|
77
87
|
price: {
|
|
78
88
|
usdg?: number;
|
|
79
89
|
autonomo?: number;
|
|
90
|
+
usdcBase?: number;
|
|
80
91
|
};
|
|
81
92
|
verified: boolean;
|
|
82
93
|
successRate: number | null;
|
|
@@ -94,7 +105,7 @@ export type CallOptions = {
|
|
|
94
105
|
/** Override payWith for this call. */
|
|
95
106
|
payWith?: TokenName | "auto";
|
|
96
107
|
};
|
|
97
|
-
export type Route = "usdg" | "autonomo" | "gloam" | "borro";
|
|
108
|
+
export type Route = "usdg" | "autonomo" | "usdc" | "gloam" | "borro";
|
|
98
109
|
export type Receipt = {
|
|
99
110
|
api: {
|
|
100
111
|
slug: string;
|
|
@@ -104,6 +115,8 @@ export type Receipt = {
|
|
|
104
115
|
route: Route;
|
|
105
116
|
amount: string;
|
|
106
117
|
token: string;
|
|
118
|
+
/** The chain the payment was made on. */
|
|
119
|
+
chain: ChainName;
|
|
107
120
|
payer: string;
|
|
108
121
|
payTo: string;
|
|
109
122
|
tx: string | null;
|
|
@@ -117,6 +130,18 @@ export type CallResult<T = unknown> = {
|
|
|
117
130
|
data: T;
|
|
118
131
|
receipt: Receipt;
|
|
119
132
|
};
|
|
133
|
+
/** What the wallet holds, in whole tokens. A chain that couldn't be read is null. */
|
|
134
|
+
export type Balances = {
|
|
135
|
+
address: string;
|
|
136
|
+
robinhood: {
|
|
137
|
+
usdg: string;
|
|
138
|
+
autonomo: string;
|
|
139
|
+
eth: string;
|
|
140
|
+
} | null;
|
|
141
|
+
base: {
|
|
142
|
+
usdc: string;
|
|
143
|
+
} | null;
|
|
144
|
+
};
|
|
120
145
|
export declare class AutonomoError extends Error {
|
|
121
146
|
readonly code: string;
|
|
122
147
|
constructor(message: string, code: string);
|
|
@@ -129,6 +154,7 @@ export declare function memoryStore(): SpendStore;
|
|
|
129
154
|
export declare class Autonomo {
|
|
130
155
|
private readonly base;
|
|
131
156
|
private readonly rpc;
|
|
157
|
+
private readonly baseRpc;
|
|
132
158
|
private readonly fetch;
|
|
133
159
|
private readonly account;
|
|
134
160
|
private readonly payWith;
|
|
@@ -138,9 +164,15 @@ export declare class Autonomo {
|
|
|
138
164
|
private readonly gloam?;
|
|
139
165
|
private readonly borro?;
|
|
140
166
|
private readonly chain;
|
|
167
|
+
private readonly baseChain;
|
|
141
168
|
constructor(opts?: AutonomoOptions);
|
|
142
169
|
/** The wallet that pays, or null when no key is set. */
|
|
143
170
|
get address(): Hex | null;
|
|
171
|
+
/**
|
|
172
|
+
* What the wallet holds on both chains: USDG, $AUTONOMO and ETH on Robinhood Chain, and USDC on Base. Free, and it
|
|
173
|
+
* signs nothing. A chain that can't be read right now comes back as null instead of failing the whole answer.
|
|
174
|
+
*/
|
|
175
|
+
balances(): Promise<Balances>;
|
|
144
176
|
/** Every Autonomo API, or the best matches for a query and input. Free. */
|
|
145
177
|
find(query?: string, input?: string): Promise<Api[]>;
|
|
146
178
|
/** What a call would cost, without paying. */
|
|
@@ -156,11 +188,16 @@ export declare class Autonomo {
|
|
|
156
188
|
}>;
|
|
157
189
|
/** Finds the right API, pays for one call and returns its answer with a receipt. */
|
|
158
190
|
call<T = unknown>(query: string, opts?: CallOptions): Promise<CallResult<T>>;
|
|
191
|
+
/** Read-only clients for both chains. */
|
|
192
|
+
private clients;
|
|
159
193
|
private get;
|
|
160
194
|
private gatewayUrl;
|
|
161
195
|
private resolve;
|
|
162
196
|
private priceList;
|
|
163
|
-
/**
|
|
197
|
+
/**
|
|
198
|
+
* Signs an x402 exact payment (EIP-3009 for USDG and USDC on Base, Permit2 for $AUTONOMO) and sends the request with
|
|
199
|
+
* it. `chainId` is the chain the offer is paid on; a Permit2 approval is only ever sent on Robinhood Chain.
|
|
200
|
+
*/
|
|
164
201
|
private payExact;
|
|
165
202
|
/** Asks Borro for the borrow that covers what the wallet is short, sends it and waits for the USDG to land. */
|
|
166
203
|
private borrow;
|
|
@@ -172,7 +209,7 @@ export declare function eip3009TypedData(auth: {
|
|
|
172
209
|
validAfter: string;
|
|
173
210
|
validBefore: string;
|
|
174
211
|
nonce: string;
|
|
175
|
-
}, asset: string, name: string, version: string): {
|
|
212
|
+
}, asset: string, name: string, version: string, chainId?: number): {
|
|
176
213
|
domain: {
|
|
177
214
|
name: string;
|
|
178
215
|
version: string;
|
|
@@ -242,6 +279,25 @@ export declare function permit2TypedData(auth: {
|
|
|
242
279
|
};
|
|
243
280
|
};
|
|
244
281
|
};
|
|
282
|
+
/**
|
|
283
|
+
* The one transaction an honest Borro `credit_bill` answer holds: "one unsigned borrow of just what it is short, from the
|
|
284
|
+
* line to the wallet itself". Anything else is refused before it is signed: another target, ETH value, another function,
|
|
285
|
+
* another recipient, more than the call's price, or more than one transaction. A borrow's USDG lands in the agent's own
|
|
286
|
+
* wallet, so the caps on the call still bound what can be spent.
|
|
287
|
+
*/
|
|
288
|
+
export declare function checkBorrow(txs: Array<{
|
|
289
|
+
to: string;
|
|
290
|
+
data: string;
|
|
291
|
+
value?: string;
|
|
292
|
+
}>, opts: {
|
|
293
|
+
line: string;
|
|
294
|
+
wallet: string;
|
|
295
|
+
most: bigint;
|
|
296
|
+
}): {
|
|
297
|
+
to: Hex;
|
|
298
|
+
data: Hex;
|
|
299
|
+
amount: bigint;
|
|
300
|
+
};
|
|
245
301
|
/** Every transaction ({ to, data }) inside a tool result, in order. */
|
|
246
302
|
export declare function findTransactions(value: unknown): Array<{
|
|
247
303
|
to: string;
|
package/dist/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
// Autonomo SDK: one call that finds the right paid API on Autonomo, pays for it on Robinhood Chain and returns
|
|
2
|
-
// answer with a receipt.
|
|
1
|
+
// Autonomo SDK: one call that finds the right paid API on Autonomo, pays for it on Robinhood Chain or Base and returns
|
|
2
|
+
// the answer with a receipt.
|
|
3
3
|
//
|
|
4
4
|
// const autonomo = new Autonomo({ privateKey });
|
|
5
5
|
// const { data, receipt } = await autonomo.call("is this token safe", { input: "0x…" });
|
|
@@ -7,25 +7,31 @@
|
|
|
7
7
|
// How a call is paid, in order:
|
|
8
8
|
// private: true Only through Gloam, from a private balance, so the payment doesn't link to the wallet. Never
|
|
9
9
|
// falls back to a public payment.
|
|
10
|
-
// otherwise USDG, then $AUTONOMO (or just the one set in payWith), from
|
|
11
|
-
//
|
|
12
|
-
//
|
|
10
|
+
// otherwise USDG, then $AUTONOMO on Robinhood Chain, then USDC on Base (or just the one set in payWith), from
|
|
11
|
+
// the wallet, whichever it can afford. The same key is the same wallet on both chains. If it can't
|
|
12
|
+
// afford any and a Borro credit line is set, it borrows the USDG it's short and pays.
|
|
13
|
+
// Every route checks the per-call cap and the daily budget before anything is signed or sent. USDG and USDC are both
|
|
14
|
+
// dollars, so they share the dollar limits (limits.perCall.usdg and limits.daily.usdg).
|
|
13
15
|
import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
14
16
|
import { homedir } from "node:os";
|
|
15
17
|
import { dirname, join } from "node:path";
|
|
16
|
-
import { createPublicClient, createWalletClient, defineChain, erc20Abi, formatUnits, getAddress, http, maxUint256, parseUnits, toHex, } from "viem";
|
|
18
|
+
import { createPublicClient, createWalletClient, defineChain, erc20Abi, formatEther, formatUnits, getAddress, http, maxUint256, parseUnits, toHex, } from "viem";
|
|
17
19
|
import { privateKeyToAccount } from "viem/accounts";
|
|
18
|
-
export const VERSION = "0.1.
|
|
20
|
+
export const VERSION = "0.1.4";
|
|
19
21
|
const NETWORK = "eip155:4663";
|
|
20
22
|
const CHAIN_ID = 4663;
|
|
21
23
|
const EXPLORER = "https://robinhoodchain.blockscout.com";
|
|
24
|
+
const BASE_CHAIN_ID = 8453;
|
|
25
|
+
const BASE_RPC = "https://mainnet.base.org";
|
|
22
26
|
const PERMIT2 = "0x000000000022D473030F116dDEE9F6B43aC78BA3";
|
|
23
27
|
const PERMIT2_PROXY = "0x402085c248EeA27D92E8b30b2C58ed07f9E20001"; // x402's exact-scheme Permit2 proxy
|
|
24
28
|
const BORRO_MCP = "https://borro.markets/mcp";
|
|
25
29
|
export const TOKENS = {
|
|
26
|
-
usdg: { name: "usdg", symbol: "USDG", address: "0x5fc5360D0400a0Fd4f2af552ADD042D716F1d168", decimals: 6 },
|
|
27
|
-
autonomo: { name: "autonomo", symbol: "AUTONOMO", address: "0xe83c85e1ead16fcfe85401e2b337fb4fb5b5cc96", decimals: 18 },
|
|
30
|
+
usdg: { name: "usdg", symbol: "USDG", address: "0x5fc5360D0400a0Fd4f2af552ADD042D716F1d168", decimals: 6, network: NETWORK, chainId: CHAIN_ID, chain: "Robinhood Chain", explorer: EXPLORER },
|
|
31
|
+
autonomo: { name: "autonomo", symbol: "AUTONOMO", address: "0xe83c85e1ead16fcfe85401e2b337fb4fb5b5cc96", decimals: 18, network: NETWORK, chainId: CHAIN_ID, chain: "Robinhood Chain", explorer: EXPLORER },
|
|
32
|
+
usdc: { name: "usdc", symbol: "USDC", address: "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913", decimals: 6, network: "eip155:8453", chainId: BASE_CHAIN_ID, chain: "Base", explorer: "https://basescan.org" },
|
|
28
33
|
};
|
|
34
|
+
const limitOf = (t) => (t === "autonomo" ? "autonomo" : "usdg");
|
|
29
35
|
export const DEFAULT_LIMITS = {
|
|
30
36
|
perCall: { usdg: "0.05", autonomo: "5000" },
|
|
31
37
|
daily: { usdg: "1", autonomo: "10000" },
|
|
@@ -117,7 +123,7 @@ export function fileStore(file = join(homedir(), ".autonomo", "spend.json")) {
|
|
|
117
123
|
const s = read();
|
|
118
124
|
if (s.date !== day)
|
|
119
125
|
return {};
|
|
120
|
-
return { usdg: BigInt(s.usdg ?? 0), autonomo: BigInt(s.autonomo ?? 0) };
|
|
126
|
+
return { usdg: BigInt(s.usdg ?? 0), autonomo: BigInt(s.autonomo ?? 0), usdc: BigInt(s.usdc ?? 0) };
|
|
121
127
|
},
|
|
122
128
|
add(day, token, amount) {
|
|
123
129
|
const s = read();
|
|
@@ -144,6 +150,7 @@ export function memoryStore() {
|
|
|
144
150
|
export class Autonomo {
|
|
145
151
|
base;
|
|
146
152
|
rpc;
|
|
153
|
+
baseRpc;
|
|
147
154
|
fetch;
|
|
148
155
|
account;
|
|
149
156
|
payWith;
|
|
@@ -158,9 +165,16 @@ export class Autonomo {
|
|
|
158
165
|
nativeCurrency: { name: "Ether", symbol: "ETH", decimals: 18 },
|
|
159
166
|
rpcUrls: { default: { http: ["https://rpc.mainnet.chain.robinhood.com"] } },
|
|
160
167
|
});
|
|
168
|
+
baseChain = defineChain({
|
|
169
|
+
id: BASE_CHAIN_ID,
|
|
170
|
+
name: "Base",
|
|
171
|
+
nativeCurrency: { name: "Ether", symbol: "ETH", decimals: 18 },
|
|
172
|
+
rpcUrls: { default: { http: [BASE_RPC] } },
|
|
173
|
+
});
|
|
161
174
|
constructor(opts = {}) {
|
|
162
175
|
this.base = (opts.baseUrl ?? "https://autonomo.fun").replace(/\/+$/, "");
|
|
163
176
|
this.rpc = opts.rpcUrl ?? "https://rpc.mainnet.chain.robinhood.com";
|
|
177
|
+
this.baseRpc = opts.baseRpcUrl ?? BASE_RPC;
|
|
164
178
|
this.fetch = opts.fetch ?? globalThis.fetch;
|
|
165
179
|
const key = opts.privateKey?.trim();
|
|
166
180
|
if (key !== undefined && !/^0x[0-9a-fA-F]{64}$/.test(key))
|
|
@@ -185,6 +199,24 @@ export class Autonomo {
|
|
|
185
199
|
get address() {
|
|
186
200
|
return this.account?.address ?? null;
|
|
187
201
|
}
|
|
202
|
+
/**
|
|
203
|
+
* What the wallet holds on both chains: USDG, $AUTONOMO and ETH on Robinhood Chain, and USDC on Base. Free, and it
|
|
204
|
+
* signs nothing. A chain that can't be read right now comes back as null instead of failing the whole answer.
|
|
205
|
+
*/
|
|
206
|
+
async balances() {
|
|
207
|
+
const account = this.account ?? fail("no_wallet", "No wallet set. Pass privateKey (a wallet just for this agent).");
|
|
208
|
+
const { pub, basePub } = this.clients();
|
|
209
|
+
const held = (client, token) => client.readContract({ address: token.address, abi: erc20Abi, functionName: "balanceOf", args: [account.address] });
|
|
210
|
+
const [robinhood, base] = await Promise.all([
|
|
211
|
+
Promise.all([held(pub, TOKENS.usdg), held(pub, TOKENS.autonomo), pub.getBalance({ address: account.address })])
|
|
212
|
+
.then(([usdg, autonomo, eth]) => ({ usdg: formatUnits(usdg, 6), autonomo: formatUnits(autonomo, 18), eth: formatEther(eth) }))
|
|
213
|
+
.catch(() => null),
|
|
214
|
+
held(basePub, TOKENS.usdc)
|
|
215
|
+
.then((usdc) => ({ usdc: formatUnits(usdc, 6) }))
|
|
216
|
+
.catch(() => null),
|
|
217
|
+
]);
|
|
218
|
+
return { address: account.address, robinhood, base };
|
|
219
|
+
}
|
|
188
220
|
/** Every Autonomo API, or the best matches for a query and input. Free. */
|
|
189
221
|
async find(query = "", input) {
|
|
190
222
|
const res = await this.get(`${this.base}/api/v1/gateways`);
|
|
@@ -209,8 +241,9 @@ export class Autonomo {
|
|
|
209
241
|
api,
|
|
210
242
|
url,
|
|
211
243
|
offers: required.accepts.map((a) => {
|
|
212
|
-
const t = tokenByAsset(a.asset);
|
|
213
|
-
|
|
244
|
+
const t = tokenByAsset(a.asset, a.network);
|
|
245
|
+
const label = t ? (t.name === "usdc" ? "USDC on Base" : t.symbol) : a.asset;
|
|
246
|
+
return { scheme: a.scheme, token: label, amount: formatUnits(BigInt(a.amount), t?.decimals ?? 18), private: a.scheme === "gloam-cashout" };
|
|
214
247
|
}),
|
|
215
248
|
};
|
|
216
249
|
}
|
|
@@ -238,7 +271,10 @@ export class Autonomo {
|
|
|
238
271
|
fail("payment_refused", reason ? `Payment refused: ${reason}` : `The API answered ${res.status}${detail ? `: ${detail}` : ""}. You aren't charged unless it settled.`);
|
|
239
272
|
}
|
|
240
273
|
await this.store.add(day, token.name, amount);
|
|
241
|
-
const
|
|
274
|
+
const now = await this.store.get(day);
|
|
275
|
+
const limit = limitOf(token.name);
|
|
276
|
+
const after = limit === "usdg" ? (now.usdg ?? 0n) + (now.usdc ?? 0n) : (now.autonomo ?? 0n);
|
|
277
|
+
const unit = limit === "usdg" ? "USDG and USDC" : token.symbol;
|
|
242
278
|
const text = await res.text();
|
|
243
279
|
let data;
|
|
244
280
|
try {
|
|
@@ -253,25 +289,29 @@ export class Autonomo {
|
|
|
253
289
|
route,
|
|
254
290
|
amount: formatUnits(amount, token.decimals),
|
|
255
291
|
token: token.symbol,
|
|
292
|
+
chain: token.chain,
|
|
256
293
|
payer: route === "gloam" ? "private (Gloam)" : account.address,
|
|
257
294
|
payTo: "",
|
|
258
295
|
tx,
|
|
259
|
-
explorer: tx ? `${
|
|
296
|
+
explorer: tx ? `${token.explorer}/tx/${tx}` : null,
|
|
260
297
|
borrowTxs: [],
|
|
261
298
|
approveTx: null,
|
|
262
299
|
at: new Date().toISOString(),
|
|
263
|
-
spentToday: `${formatUnits(after, token.decimals)} of ${formatUnits(this.daily[
|
|
300
|
+
spentToday: `${formatUnits(after, token.decimals)} of ${formatUnits(this.daily[limit], token.decimals)} ${unit}`,
|
|
264
301
|
...extra,
|
|
265
302
|
};
|
|
266
303
|
return { data: data, receipt };
|
|
267
304
|
};
|
|
305
|
+
// USDG and USDC on Base are both dollars with 6 decimals, so they share one cap and one daily budget.
|
|
268
306
|
const within = (token, amount) => {
|
|
307
|
+
const limit = limitOf(token.name);
|
|
308
|
+
const unit = limit === "usdg" ? "dollar" : token.symbol;
|
|
269
309
|
const price = `${formatUnits(amount, token.decimals)} ${token.symbol}`;
|
|
270
|
-
if (amount > this.perCall[
|
|
271
|
-
return `${price} is above the per-call cap of ${formatUnits(this.perCall[
|
|
272
|
-
const sofar = spent
|
|
273
|
-
if (sofar + amount > this.daily[
|
|
274
|
-
return `${price} would pass today's ${
|
|
310
|
+
if (amount > this.perCall[limit])
|
|
311
|
+
return `${price} is above the per-call cap of ${formatUnits(this.perCall[limit], token.decimals)} ${limit === "usdg" ? "USDG/USDC" : token.symbol}`;
|
|
312
|
+
const sofar = limit === "usdg" ? (spent.usdg ?? 0n) + (spent.usdc ?? 0n) : (spent.autonomo ?? 0n);
|
|
313
|
+
if (sofar + amount > this.daily[limit])
|
|
314
|
+
return `${price} would pass today's ${unit} budget (${formatUnits(sofar, token.decimals)} of ${formatUnits(this.daily[limit], token.decimals)} spent)`;
|
|
275
315
|
return null;
|
|
276
316
|
};
|
|
277
317
|
// Private: Gloam only.
|
|
@@ -298,15 +338,16 @@ export class Autonomo {
|
|
|
298
338
|
}
|
|
299
339
|
// Public: the wallet's tokens, then Borro.
|
|
300
340
|
const want = opts.payWith ?? this.payWith;
|
|
301
|
-
const order = want === "auto" ? ["usdg", "autonomo"] : [want];
|
|
341
|
+
const order = want === "auto" ? ["usdg", "autonomo", "usdc"] : [want];
|
|
302
342
|
const reasons = [];
|
|
303
|
-
const pub
|
|
343
|
+
const { pub, basePub } = this.clients();
|
|
344
|
+
const clientFor = (t) => (t.chainId === BASE_CHAIN_ID ? basePub : pub);
|
|
304
345
|
let usdgShort = null;
|
|
305
346
|
for (const name of order) {
|
|
306
347
|
const token = TOKENS[name];
|
|
307
|
-
const offer = required.accepts.find((a) => a.scheme === "exact" && a.network ===
|
|
348
|
+
const offer = required.accepts.find((a) => a.scheme === "exact" && a.network === token.network && sameAddr(a.asset, token.address));
|
|
308
349
|
if (!offer) {
|
|
309
|
-
reasons.push(`${api.name} doesn't take ${token.symbol}`);
|
|
350
|
+
reasons.push(`${api.name} doesn't take ${token.name === "usdc" ? "USDC on Base" : token.symbol}`);
|
|
310
351
|
continue;
|
|
311
352
|
}
|
|
312
353
|
const amount = BigInt(offer.amount);
|
|
@@ -315,26 +356,33 @@ export class Autonomo {
|
|
|
315
356
|
reasons.push(why);
|
|
316
357
|
continue;
|
|
317
358
|
}
|
|
318
|
-
const balance = await
|
|
359
|
+
const balance = await clientFor(token).readContract({ address: token.address, abi: erc20Abi, functionName: "balanceOf", args: [account.address] });
|
|
319
360
|
if (balance < amount) {
|
|
320
|
-
reasons.push(`the wallet holds ${formatUnits(balance, token.decimals)} ${token.symbol}, the call costs ${formatUnits(amount, token.decimals)}`);
|
|
361
|
+
reasons.push(`the wallet holds ${formatUnits(balance, token.decimals)} ${token.symbol}${token.name === "usdc" ? " on Base" : ""}, the call costs ${formatUnits(amount, token.decimals)}`);
|
|
321
362
|
if (name === "usdg")
|
|
322
363
|
usdgShort = { offer, amount };
|
|
323
364
|
continue;
|
|
324
365
|
}
|
|
325
|
-
return pay(name, token, amount, () => this.payExact(url, required, offer, account, pub));
|
|
366
|
+
return pay(name, token, amount, () => this.payExact(url, required, offer, account, pub, token.chainId));
|
|
326
367
|
}
|
|
327
368
|
if (this.borro && usdgShort) {
|
|
328
369
|
const { offer, amount } = usdgShort;
|
|
329
370
|
const borrowTxs = await this.borrow(url, offer, account, pub);
|
|
330
371
|
return pay("borro", TOKENS.usdg, amount, async () => {
|
|
331
|
-
const r = await this.payExact(url, required, offer, account, pub);
|
|
372
|
+
const r = await this.payExact(url, required, offer, account, pub, CHAIN_ID);
|
|
332
373
|
return { ...r, extra: { ...r.extra, borrowTxs: borrowTxs.map((h) => `${EXPLORER}/tx/${h}`) } };
|
|
333
374
|
});
|
|
334
375
|
}
|
|
335
376
|
return fail("cannot_pay", `Not paid: ${reasons.join("; ")}.`);
|
|
336
377
|
}
|
|
337
378
|
// ---------- Internals ----------
|
|
379
|
+
/** Read-only clients for both chains. */
|
|
380
|
+
clients() {
|
|
381
|
+
return {
|
|
382
|
+
pub: createPublicClient({ chain: this.chain, transport: http(this.rpc) }),
|
|
383
|
+
basePub: createPublicClient({ chain: this.baseChain, transport: http(this.baseRpc) }),
|
|
384
|
+
};
|
|
385
|
+
}
|
|
338
386
|
async get(url, timeout = 15_000) {
|
|
339
387
|
const res = await this.fetch(url, { signal: AbortSignal.timeout(timeout) });
|
|
340
388
|
if (res.status === 503)
|
|
@@ -388,13 +436,18 @@ export class Autonomo {
|
|
|
388
436
|
fail("no_price", `Expected a 402 price list from ${url}, got ${res.status}.`);
|
|
389
437
|
return required;
|
|
390
438
|
}
|
|
391
|
-
/**
|
|
392
|
-
|
|
439
|
+
/**
|
|
440
|
+
* Signs an x402 exact payment (EIP-3009 for USDG and USDC on Base, Permit2 for $AUTONOMO) and sends the request with
|
|
441
|
+
* it. `chainId` is the chain the offer is paid on; a Permit2 approval is only ever sent on Robinhood Chain.
|
|
442
|
+
*/
|
|
443
|
+
async payExact(url, required, offer, account, pub, chainId) {
|
|
393
444
|
let approveTx = null;
|
|
394
445
|
const now = Math.floor(Date.now() / 1000);
|
|
395
446
|
const timeout = offer.maxTimeoutSeconds ?? 300;
|
|
396
447
|
let payload;
|
|
397
448
|
if (offer.extra?.assetTransferMethod === "permit2") {
|
|
449
|
+
if (chainId !== CHAIN_ID)
|
|
450
|
+
fail("bad_offer", "A Permit2 payment is only expected on Robinhood Chain.");
|
|
398
451
|
const allowance = await pub.readContract({ address: getAddress(offer.asset), abi: erc20Abi, functionName: "allowance", args: [account.address, PERMIT2] });
|
|
399
452
|
if (allowance < BigInt(offer.amount)) {
|
|
400
453
|
const wallet = createWalletClient({ account, chain: this.chain, transport: http(this.rpc) });
|
|
@@ -426,7 +479,7 @@ export class Autonomo {
|
|
|
426
479
|
validBefore: String(now + timeout),
|
|
427
480
|
nonce: randomHex(32),
|
|
428
481
|
};
|
|
429
|
-
const signature = await account.signTypedData(eip3009TypedData(auth, offer.asset, name, version));
|
|
482
|
+
const signature = await account.signTypedData(eip3009TypedData(auth, offer.asset, name, version, chainId));
|
|
430
483
|
payload = { authorization: auth, signature };
|
|
431
484
|
}
|
|
432
485
|
const envelope = required.x402Version === 1
|
|
@@ -451,32 +504,30 @@ export class Autonomo {
|
|
|
451
504
|
payment_required: raw,
|
|
452
505
|
max_usdg: formatUnits(this.perCall.usdg, 6),
|
|
453
506
|
});
|
|
454
|
-
const txs = findTransactions(result);
|
|
455
|
-
const wallet = createWalletClient({ account, chain: this.chain, transport: http(this.rpc) });
|
|
456
|
-
const hashes = [];
|
|
457
|
-
for (const t of txs) {
|
|
458
|
-
const hash = await wallet.sendTransaction({ to: getAddress(t.to), data: t.data, value: t.value ? BigInt(t.value) : 0n });
|
|
459
|
-
const r = await pub.waitForTransactionReceipt({ hash });
|
|
460
|
-
if (r.status !== "success")
|
|
461
|
-
fail("borrow_failed", `Borro's borrow transaction failed: ${EXPLORER}/tx/${hash}`);
|
|
462
|
-
hashes.push(hash);
|
|
463
|
-
}
|
|
464
507
|
const need = BigInt(offer.amount);
|
|
508
|
+
// Borro's answer is checked before anything is signed: it may only borrow, on this line, into this wallet, at most the price.
|
|
509
|
+
const tx = checkBorrow(findTransactions(result), { line: borro.account, wallet: account.address, most: need });
|
|
510
|
+
const wallet = createWalletClient({ account, chain: this.chain, transport: http(this.rpc) });
|
|
511
|
+
const hash = await wallet.sendTransaction({ to: tx.to, data: tx.data, value: 0n });
|
|
512
|
+
const link = `${EXPLORER}/tx/${hash}`;
|
|
513
|
+
const r = await pub.waitForTransactionReceipt({ hash });
|
|
514
|
+
if (r.status !== "success")
|
|
515
|
+
fail("borrow_failed", `The borrow on your Borro line failed, so nothing was borrowed and the API isn't paid: ${link}`);
|
|
465
516
|
for (let i = 0; i < 20; i++) {
|
|
466
517
|
const bal = await pub.readContract({ address: TOKENS.usdg.address, abi: erc20Abi, functionName: "balanceOf", args: [account.address] });
|
|
467
518
|
if (bal >= need)
|
|
468
|
-
return
|
|
519
|
+
return [hash];
|
|
469
520
|
await sleep(1000);
|
|
470
521
|
}
|
|
471
|
-
return fail("borrow_failed",
|
|
522
|
+
return fail("borrow_failed", `Borrowed ${formatUnits(tx.amount, 6)} USDG on your Borro line (${link}), but it hasn't reached the wallet yet. The API isn't paid; try again shortly.`);
|
|
472
523
|
}
|
|
473
524
|
}
|
|
474
525
|
// ---------- Helpers ----------
|
|
475
526
|
const sameAddr = (a, b) => a.toLowerCase() === b.toLowerCase();
|
|
476
|
-
const tokenByAsset = (asset) => Object.values(TOKENS).find((t) => sameAddr(t.address, asset));
|
|
477
|
-
export function eip3009TypedData(auth, asset, name, version) {
|
|
527
|
+
const tokenByAsset = (asset, network) => Object.values(TOKENS).find((t) => sameAddr(t.address, asset) && (network === undefined || t.network === network));
|
|
528
|
+
export function eip3009TypedData(auth, asset, name, version, chainId = CHAIN_ID) {
|
|
478
529
|
return {
|
|
479
|
-
domain: { name, version, chainId
|
|
530
|
+
domain: { name, version, chainId, verifyingContract: getAddress(asset) },
|
|
480
531
|
types: {
|
|
481
532
|
TransferWithAuthorization: [
|
|
482
533
|
{ name: "from", type: "address" },
|
|
@@ -561,6 +612,50 @@ async function mcpCall(f, url, name, args) {
|
|
|
561
612
|
return out;
|
|
562
613
|
}
|
|
563
614
|
}
|
|
615
|
+
/** borrow(uint256 amount, address to) on a Borro credit line. */
|
|
616
|
+
const BORROW_SELECTOR = "0x4b3fd148";
|
|
617
|
+
/**
|
|
618
|
+
* The one transaction an honest Borro `credit_bill` answer holds: "one unsigned borrow of just what it is short, from the
|
|
619
|
+
* line to the wallet itself". Anything else is refused before it is signed: another target, ETH value, another function,
|
|
620
|
+
* another recipient, more than the call's price, or more than one transaction. A borrow's USDG lands in the agent's own
|
|
621
|
+
* wallet, so the caps on the call still bound what can be spent.
|
|
622
|
+
*/
|
|
623
|
+
export function checkBorrow(txs, opts) {
|
|
624
|
+
const refuse = (why) => fail("borro_unsafe", `Borro's answer wasn't a plain borrow from your line into this wallet (${why}), so nothing was signed or sent.`);
|
|
625
|
+
if (txs.length === 0)
|
|
626
|
+
refuse("it held no borrow transaction");
|
|
627
|
+
if (txs.length > 1)
|
|
628
|
+
refuse(`it held ${txs.length} transactions, and a borrow is one`);
|
|
629
|
+
const [t] = txs;
|
|
630
|
+
if (!sameAddr(t.to, opts.line))
|
|
631
|
+
refuse(`it goes to ${t.to}, not your credit line ${opts.line}`);
|
|
632
|
+
let value;
|
|
633
|
+
try {
|
|
634
|
+
value = t.value === undefined || t.value === "" ? 0n : BigInt(t.value);
|
|
635
|
+
}
|
|
636
|
+
catch {
|
|
637
|
+
return refuse(`its value "${t.value}" isn't a number`);
|
|
638
|
+
}
|
|
639
|
+
if (value !== 0n)
|
|
640
|
+
refuse(`it sends ${formatEther(value)} ETH`);
|
|
641
|
+
const data = t.data.toLowerCase();
|
|
642
|
+
if (!data.startsWith(BORROW_SELECTOR))
|
|
643
|
+
refuse(`it calls ${data.slice(0, 10)}, not borrow`);
|
|
644
|
+
if (data.length !== 10 + 128)
|
|
645
|
+
refuse("its borrow arguments aren't an amount and a recipient");
|
|
646
|
+
const amount = BigInt(`0x${data.slice(10, 74)}`);
|
|
647
|
+
const word = data.slice(74);
|
|
648
|
+
if (!/^0{24}/.test(word))
|
|
649
|
+
refuse("its recipient isn't an address");
|
|
650
|
+
const to = `0x${word.slice(24)}`;
|
|
651
|
+
if (!sameAddr(to, opts.wallet))
|
|
652
|
+
refuse(`it borrows into ${getAddress(to)}, not this wallet`);
|
|
653
|
+
if (amount === 0n)
|
|
654
|
+
refuse("it borrows nothing");
|
|
655
|
+
if (amount > opts.most)
|
|
656
|
+
refuse(`it borrows ${formatUnits(amount, 6)} USDG, more than the call's ${formatUnits(opts.most, 6)}`);
|
|
657
|
+
return { to: getAddress(t.to), data: data, amount };
|
|
658
|
+
}
|
|
564
659
|
/** Every transaction ({ to, data }) inside a tool result, in order. */
|
|
565
660
|
export function findTransactions(value) {
|
|
566
661
|
const out = [];
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "autonomo-sdk",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.4",
|
|
4
4
|
"description": "One call for AI agents: find the right paid API on Autonomo, pay in USDG or $AUTONOMO (privately through Gloam, or on Borro credit), within spending caps, and get a receipt.",
|
|
5
5
|
"homepage": "https://autonomo.fun",
|
|
6
6
|
"author": "Autonomo (https://autonomo.fun)",
|