@priors/agentkit 0.2.3 → 0.2.5
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 +12 -6
- package/dist/priorsActionProvider.d.ts +46 -10
- package/dist/priorsActionProvider.js +159 -47
- package/dist/schemas.js +1 -1
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -43,8 +43,12 @@ priorsActionProvider(undefined, { autoBorrow: { perCall: "5", perDay: "10", host
|
|
|
43
43
|
|
|
44
44
|
With it, `pay_x402_with_priors_credit` borrows the gap on its own when the wallet is short, for the listed hosts only.
|
|
45
45
|
There is no default host: `hosts` names each one, exactly (here `models.example` stands for the model API you choose).
|
|
46
|
-
The limits are `perCall` USDG a call and `perDay` USDG a UTC day
|
|
47
|
-
term
|
|
46
|
+
The limits are `perCall` USDG a call and `perDay` USDG a UTC day (each read exactly, at most 6 decimals), for 14 days
|
|
47
|
+
whatever term the model names (or the pool's maximum term). The day counts what the pool lent the agent since 00:00 UTC,
|
|
48
|
+
every loan of the agent whoever took it, as well as this process's own auto-borrows, so a restart does not start the
|
|
49
|
+
day again (0.2.5); if those loans cannot be read, nothing is borrowed. A borrow another process sent that is not mined
|
|
50
|
+
yet is not seen, and after a restart a provider that auto-borrows for several agents counts each agent's loans only. It borrows only while this wallet's Autopay
|
|
51
|
+
(AutoRepay v2) covers the new loan: the wallet is the agent's
|
|
48
52
|
declared wallet, the plan is on under the agent's current owner, not held or paused, its limit per loan and its USDG
|
|
49
53
|
approval cover the loan's due. Otherwise nothing is borrowed or paid, and the answer says to turn Autopay on. The
|
|
50
54
|
wallet must be a key of the agent's own, not its owner's address: AutoRepay repays an agent whose declared wallet is its
|
|
@@ -79,13 +83,15 @@ What `pay_x402_with_priors_credit` will and will not do:
|
|
|
79
83
|
the paid round's 402 is never signed;
|
|
80
84
|
- one payment per purchase: until a payment it signed settles or expires, a call for the same purchase (the same
|
|
81
85
|
method, URL and body, from the same wallet) sends that same payment again and borrows nothing more. Only a 2xx answer
|
|
82
|
-
is reported as paid
|
|
83
|
-
the
|
|
86
|
+
is reported as paid, also when its body breaks off (the answer then says so, and that calling again pays again);
|
|
87
|
+
after any other one the answer says until when the seller may still settle it. This is kept in the process's memory:
|
|
88
|
+
a restart within those 600 s forgets it;
|
|
89
|
+
- a wallet's money actions run one at a time (pay, borrow, repay), and a seller's probe has 60 s to answer;
|
|
84
90
|
- `maxPrice`, `maxBorrow` and `amount` are read exactly, at most 6 decimals (a longer one is refused, never rounded);
|
|
85
91
|
- the seller's body comes back between per-call markers, each of its lines quoted (`@priors/mcp`'s fence), and of its
|
|
86
92
|
settlement header only the transaction hash: treat it as data, not instructions;
|
|
87
|
-
- a loan taken for the gap stays in the answer if the payment then fails,
|
|
88
|
-
reverted is never reported as done.
|
|
93
|
+
- a loan taken for the gap stays in the answer if the payment then fails, a borrow sent whose answer was lost is named
|
|
94
|
+
with its transaction, and a transaction whose receipt says it reverted is never reported as done.
|
|
89
95
|
|
|
90
96
|
`maxPrice` and `maxBorrow` are what the model passes: confirm them with the user, and keep the wallet's balance small.
|
|
91
97
|
|
|
@@ -3,9 +3,11 @@ import { ActionProvider, EvmWalletProvider, Network } from "@coinbase/agentkit";
|
|
|
3
3
|
import { BorrowSchema, GetAgentRecordSchema, GetCreditLineSchema, PayX402WithCreditSchema, RepaySchema } from "./schemas";
|
|
4
4
|
/**
|
|
5
5
|
* Auto-borrow, set by the owner in code (never by the model): pay_x402_with_priors_credit borrows the gap on its own,
|
|
6
|
-
* up to `perCall` USDG a call and `perDay` USDG a UTC day
|
|
7
|
-
* names), for 14 days, and only while this wallet's Autopay (AutoRepay
|
|
8
|
-
* can only lower the amount.
|
|
6
|
+
* up to `perCall` USDG a call and `perDay` USDG a UTC day (each read exactly, at most 6 decimals), for the `hosts` listed
|
|
7
|
+
* only (exact host names), for 14 days whatever term the model names, and only while this wallet's Autopay (AutoRepay
|
|
8
|
+
* v2) covers the new loan. The model's maxBorrow can only lower the amount. The day counts what the pool lent the agent
|
|
9
|
+
* since 00:00 UTC, every loan of the agent whoever took it, as well as this process's own auto-borrows, so a restart
|
|
10
|
+
* does not start the day again (GHSA-j679).
|
|
9
11
|
*/
|
|
10
12
|
export type AutoBorrowOptions = {
|
|
11
13
|
perCall: string;
|
|
@@ -24,7 +26,7 @@ export declare class PriorsActionProvider extends ActionProvider<EvmWalletProvid
|
|
|
24
26
|
private readonly auto;
|
|
25
27
|
private borrowedToday;
|
|
26
28
|
private readonly unsettled;
|
|
27
|
-
/** The call under way for each
|
|
29
|
+
/** The money call under way for each wallet: another one of that wallet waits for it (onePerWallet). */
|
|
28
30
|
private readonly running;
|
|
29
31
|
/**
|
|
30
32
|
* Constructor for the PriorsActionProvider.
|
|
@@ -65,6 +67,14 @@ export declare class PriorsActionProvider extends ActionProvider<EvmWalletProvid
|
|
|
65
67
|
* @returns The repayment, or an error message.
|
|
66
68
|
*/
|
|
67
69
|
repay(walletProvider: EvmWalletProvider, args: z.infer<typeof RepaySchema>): Promise<string>;
|
|
70
|
+
/**
|
|
71
|
+
* repay_priors_loan's work, run as the wallet's one money call (onePerWallet).
|
|
72
|
+
*
|
|
73
|
+
* @param walletProvider - The wallet provider.
|
|
74
|
+
* @param args - The loan id, and optionally its agent id.
|
|
75
|
+
* @returns The repayment, or an error message.
|
|
76
|
+
*/
|
|
77
|
+
private repayLoan;
|
|
68
78
|
/**
|
|
69
79
|
* Pays an x402 URL in USDG on Robinhood Chain, borrowing the gap from the Priors line when the wallet is short.
|
|
70
80
|
*
|
|
@@ -84,6 +94,26 @@ export declare class PriorsActionProvider extends ActionProvider<EvmWalletProvid
|
|
|
84
94
|
* @param due - The new loan's principal plus fee, atomic USDG.
|
|
85
95
|
*/
|
|
86
96
|
private autopayCovers;
|
|
97
|
+
/**
|
|
98
|
+
* Auto-borrow's day limit as the pool records the day (GHSA-j679): `amount` more on top of what the pool lent agent
|
|
99
|
+
* `agentId` since 00:00 UTC of `day` must stay within `perDay`. Every loan of the agent issued that day counts, whoever
|
|
100
|
+
* took it (the pool records the agent and its owner, not the key that borrowed), so a restart, or another process of
|
|
101
|
+
* this wallet, starts the day where the pool is; that can only lower auto-borrow's room. A read that fails, or a loan
|
|
102
|
+
* whose record does not read as one, refuses (nothing is sent). The pool lists an agent's loans oldest first
|
|
103
|
+
* (CreditPoolV2 appends each in borrow), so they are read from the newest back to the first one issued before the day.
|
|
104
|
+
*
|
|
105
|
+
* SHORTCUT: what the pool shows: a borrow another process sent and the chain has not mined yet is not seen, and after a
|
|
106
|
+
* restart a provider that auto-borrows for several agents counts each agent's own loans only (its count across agents
|
|
107
|
+
* starts again). Upgrade when the provider gets a place to keep state (@priors/mcp's daily ledger under
|
|
108
|
+
* PRIORS_STATE_DIR), or on a report of either.
|
|
109
|
+
*
|
|
110
|
+
* @param walletProvider - The wallet provider.
|
|
111
|
+
* @param agentId - The agent id.
|
|
112
|
+
* @param amount - The borrow about to be sent, atomic USDG.
|
|
113
|
+
* @param perDay - The owner's limit a UTC day, atomic USDG.
|
|
114
|
+
* @param day - The UTC day the borrow counts in (YYYY-MM-DD).
|
|
115
|
+
*/
|
|
116
|
+
private dayRoom;
|
|
87
117
|
/**
|
|
88
118
|
* Before this wallet's money moves for agent `agentId` (a borrow into it, a repayment from it), @priors/mcp's rule
|
|
89
119
|
* (needController, GHSA-9pw7): the wallet controls the agent at the pool AND is its current owner or its declared
|
|
@@ -107,23 +137,28 @@ export declare class PriorsActionProvider extends ActionProvider<EvmWalletProvid
|
|
|
107
137
|
/**
|
|
108
138
|
* What became of a payment sent: paid only on a 2xx answer. Anything else (a dropped connection, no answer in time,
|
|
109
139
|
* a 5xx, a 402, a redirect) leaves it signed and sent, cashable by the seller until it expires, and a later call for
|
|
110
|
-
* the purchase sends it again (@priors/mcp's pay_url answer).
|
|
140
|
+
* the purchase sends it again (@priors/mcp's pay_url answer). A body that fails mid-read (a reset, or the request's
|
|
141
|
+
* time bound firing during a long answer) is said, never an error that hides the payment (@priors/mcp's issue #19,
|
|
142
|
+
* GHSA-87h5): once paid, the purchase is complete, so a call again for it pays again.
|
|
111
143
|
*
|
|
144
|
+
* @param X - @priors/x402 (its readCapped and SKEW_SECONDS).
|
|
112
145
|
* @param r - What @priors/x402's resend answered.
|
|
113
146
|
* @param s - The payment sent.
|
|
114
|
-
* @param skew - @priors/x402's SKEW_SECONDS, the margin kept past validBefore.
|
|
115
147
|
* @returns The answer's words for it.
|
|
116
148
|
*/
|
|
117
149
|
private outcome;
|
|
118
150
|
/**
|
|
119
|
-
* Runs
|
|
120
|
-
*
|
|
151
|
+
* Runs a wallet's money calls (pay, borrow, repay) one at a time, as @priors/x402's createPayer queues its payments
|
|
152
|
+
* and @priors/mcp runs its money calls: two calls at once on a short wallet would each read the balance short and each
|
|
153
|
+
* borrow, both passing auto-borrow's Autopay check on an approval that covers one loan (GHSA-482p F3, GHSA-87h5). A
|
|
154
|
+
* call for a purchase another call is paying waits for it, then finds its payment while that may still settle; once
|
|
155
|
+
* it is paid (a 2xx), the purchase is complete and a call for it is a new one.
|
|
121
156
|
*
|
|
122
|
-
* @param
|
|
157
|
+
* @param walletProvider - The wallet whose calls queue.
|
|
123
158
|
* @param fn - The call.
|
|
124
159
|
* @returns What the call answers.
|
|
125
160
|
*/
|
|
126
|
-
private
|
|
161
|
+
private onePerWallet;
|
|
127
162
|
/**
|
|
128
163
|
* Borrows `amount` atomic USDG for `days` from the agent's line into this wallet.
|
|
129
164
|
*
|
|
@@ -133,6 +168,7 @@ export declare class PriorsActionProvider extends ActionProvider<EvmWalletProvid
|
|
|
133
168
|
* @param days - The term in days.
|
|
134
169
|
* @param check - Called with the quoted fee before the borrow is sent; a throw refuses it.
|
|
135
170
|
* @param did - What did not happen when the borrow is refused ("borrowed", "borrowed or paid").
|
|
171
|
+
* @param onSend - Called once every check has passed, right before the borrow's transaction is sent.
|
|
136
172
|
* @returns The loan.
|
|
137
173
|
*/
|
|
138
174
|
private borrowAmount;
|
|
@@ -31,20 +31,27 @@ const utcDay = () => new Date().toISOString().slice(0, 10);
|
|
|
31
31
|
/** A refusal before anything is sent (its message is the answer). */
|
|
32
32
|
class Refusal extends Error {
|
|
33
33
|
}
|
|
34
|
+
/** A transaction mined and reverted: the chain shows it moved nothing. */
|
|
35
|
+
class Reverted extends Error {
|
|
36
|
+
}
|
|
37
|
+
/** A borrow sent whose answer was lost: it may have opened a loan (its message says so, with its transaction). */
|
|
38
|
+
class Unconfirmed extends Error {
|
|
39
|
+
}
|
|
34
40
|
/**
|
|
35
41
|
* Atomic USDG from an amount the model gives: a plain decimal of at most 6 places, read exactly. viem's parseUnits
|
|
36
42
|
* rounds a longer one to the nearest unit, so a cap of 0.0999999 would admit 0.10 (@priors/mcp's P-28).
|
|
37
43
|
*
|
|
38
44
|
* @param value - The amount, e.g. "0.10".
|
|
39
45
|
* @param name - Its argument's name, for the refusal.
|
|
46
|
+
* @param after - The refusal's last words.
|
|
40
47
|
* @returns Atomic USDG.
|
|
41
48
|
*/
|
|
42
|
-
function exactUsdg(value, name) {
|
|
49
|
+
function exactUsdg(value, name, after = " Nothing was sent.") {
|
|
43
50
|
const s = String(value).trim();
|
|
44
51
|
if (!/^\d+(\.\d+)?$/.test(s))
|
|
45
|
-
throw new Refusal(`${name} must be a plain amount of USDG, such as 0.10
|
|
52
|
+
throw new Refusal(`${name} must be a plain amount of USDG, such as 0.10.${after}`);
|
|
46
53
|
if ((s.split(".")[1] ?? "").length > constants_1.USDG_DECIMALS)
|
|
47
|
-
throw new Refusal(`${name} ${s} has more than ${constants_1.USDG_DECIMALS} decimals, and USDG counts in millionths: give at most 6 decimals
|
|
54
|
+
throw new Refusal(`${name} ${s} has more than ${constants_1.USDG_DECIMALS} decimals, and USDG counts in millionths: give at most 6 decimals.${after}`);
|
|
48
55
|
return (0, viem_1.parseUnits)(s, constants_1.USDG_DECIMALS);
|
|
49
56
|
}
|
|
50
57
|
/**
|
|
@@ -59,7 +66,7 @@ function mined(receipt, what, hash) {
|
|
|
59
66
|
if (status === "success" || status === 1 || status === 1n || status === "0x1")
|
|
60
67
|
return;
|
|
61
68
|
if (status === "reverted" || status === 0 || status === 0n || status === "0x0")
|
|
62
|
-
throw new
|
|
69
|
+
throw new Reverted(`the ${what} transaction ${hash} reverted on chain: it moved nothing`);
|
|
63
70
|
throw new Error(`the ${what} transaction ${hash} could not be confirmed (its receipt has no status): check it before acting on it`);
|
|
64
71
|
}
|
|
65
72
|
/** Whether an IPv4 address (four numbers) is not a public one: this host, private, CGNAT, link-local, test or reserved. */
|
|
@@ -167,6 +174,8 @@ function settledTx(header) {
|
|
|
167
174
|
class PriorsActionProvider extends agentkit_1.ActionProvider {
|
|
168
175
|
fetchImpl;
|
|
169
176
|
auto;
|
|
177
|
+
// what this process auto-borrowed today, sent or about to be: the borrows the pool does not list yet. The pool's own
|
|
178
|
+
// record of the agent's loans today is read before each auto-borrow too (dayRoom), so a restart starts from it.
|
|
170
179
|
borrowedToday = { day: "", amount: 0n };
|
|
171
180
|
// One signature per purchase (GHSA-pr4v), @priors/x402's rule (createPayer's unsettled payments, @priors/mcp's
|
|
172
181
|
// outstanding ones): a payment this provider signed for a wallet's purchase (the method, the URL as the seller reads
|
|
@@ -177,7 +186,7 @@ class PriorsActionProvider extends agentkit_1.ActionProvider {
|
|
|
177
186
|
// purchase after the restart signs again: at most one more payment of at most maxPrice, to the seller the call named
|
|
178
187
|
// (P-15's class). Upgrade when the provider gets a place to keep state, or on a report of it.
|
|
179
188
|
unsettled = new Map();
|
|
180
|
-
/** The call under way for each
|
|
189
|
+
/** The money call under way for each wallet: another one of that wallet waits for it (onePerWallet). */
|
|
181
190
|
running = new Map();
|
|
182
191
|
/**
|
|
183
192
|
* Constructor for the PriorsActionProvider.
|
|
@@ -193,8 +202,9 @@ class PriorsActionProvider extends agentkit_1.ActionProvider {
|
|
|
193
202
|
this.auto = null;
|
|
194
203
|
return;
|
|
195
204
|
}
|
|
196
|
-
|
|
197
|
-
const
|
|
205
|
+
// read exactly, as the model's amounts are: a limit is never rounded up to the next unit (RT-4's rule)
|
|
206
|
+
const perCall = exactUsdg(String(a.perCall), "autoBorrow.perCall", "");
|
|
207
|
+
const perDay = exactUsdg(String(a.perDay), "autoBorrow.perDay", "");
|
|
198
208
|
if (perCall <= 0n)
|
|
199
209
|
throw new Error("autoBorrow.perCall must be above 0");
|
|
200
210
|
if (perDay < perCall)
|
|
@@ -266,15 +276,17 @@ class PriorsActionProvider extends agentkit_1.ActionProvider {
|
|
|
266
276
|
* @returns The loan, or an error message.
|
|
267
277
|
*/
|
|
268
278
|
async borrow(walletProvider, args) {
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
279
|
+
return this.onePerWallet(walletProvider, async () => {
|
|
280
|
+
try {
|
|
281
|
+
const loan = await this.borrowAmount(walletProvider, args.agentId, exactUsdg(args.amount, "amount"), args.days);
|
|
282
|
+
return `Borrowed ${usdg(loan.amount)} USDG from agent #${args.agentId}'s Priors line: loan #${loan.loanId}, fee ${usdg(loan.fee)} USDG, due ${loan.dueAt}. Transaction: ${loan.hash}`;
|
|
283
|
+
}
|
|
284
|
+
catch (error) {
|
|
285
|
+
if (error instanceof Refusal || error instanceof Unconfirmed)
|
|
286
|
+
return `Error: ${error.message}`;
|
|
287
|
+
return `Error borrowing from Priors: ${(0, fence_js_1.unfenced)(String(error))}`;
|
|
288
|
+
}
|
|
289
|
+
});
|
|
278
290
|
}
|
|
279
291
|
/**
|
|
280
292
|
* Repays a Priors loan in full from this wallet.
|
|
@@ -284,6 +296,16 @@ class PriorsActionProvider extends agentkit_1.ActionProvider {
|
|
|
284
296
|
* @returns The repayment, or an error message.
|
|
285
297
|
*/
|
|
286
298
|
async repay(walletProvider, args) {
|
|
299
|
+
return this.onePerWallet(walletProvider, () => this.repayLoan(walletProvider, args));
|
|
300
|
+
}
|
|
301
|
+
/**
|
|
302
|
+
* repay_priors_loan's work, run as the wallet's one money call (onePerWallet).
|
|
303
|
+
*
|
|
304
|
+
* @param walletProvider - The wallet provider.
|
|
305
|
+
* @param args - The loan id, and optionally its agent id.
|
|
306
|
+
* @returns The repayment, or an error message.
|
|
307
|
+
*/
|
|
308
|
+
async repayLoan(walletProvider, args) {
|
|
287
309
|
try {
|
|
288
310
|
const loan = (await walletProvider.readContract({
|
|
289
311
|
address: constants_1.PRIORS_POOL,
|
|
@@ -389,11 +411,12 @@ class PriorsActionProvider extends agentkit_1.ActionProvider {
|
|
|
389
411
|
: args.maxBorrow === undefined || named > auto.perCall
|
|
390
412
|
? auto.perCall
|
|
391
413
|
: named;
|
|
392
|
-
|
|
414
|
+
// auto-borrow's term is the owner's (14 days, brought down to the pool's maxTerm below), never the model's days
|
|
415
|
+
const days = auto ? constants_1.AUTO_TERM_DAYS : args.days ?? constants_1.DEFAULT_TERM_DAYS;
|
|
393
416
|
const X = await x402();
|
|
394
417
|
const me = walletProvider.getAddress();
|
|
395
418
|
const purchase = `${me.toLowerCase()} ${await X.purchaseKey(new Request(args.url, init()))}`;
|
|
396
|
-
return await this.
|
|
419
|
+
return await this.onePerWallet(walletProvider, async () => {
|
|
397
420
|
// a payment signed for this purchase that may still settle is sent again, before anything is probed or borrowed
|
|
398
421
|
const now = Math.floor(Date.now() / 1000);
|
|
399
422
|
for (const [k, v] of this.unsettled)
|
|
@@ -405,22 +428,41 @@ class PriorsActionProvider extends agentkit_1.ActionProvider {
|
|
|
405
428
|
if (r.response.ok)
|
|
406
429
|
this.unsettled.delete(purchase);
|
|
407
430
|
const first = out.borrowed ? `Its first attempt: ${out.borrowed}` : "\n";
|
|
408
|
-
return (0, fence_js_1.guarded)(`No new payment was signed: the payment of ${usdg(out.price)} USDG to ${out.payTo} signed earlier for this purchase was sent again. ${first}${await this.outcome(r, out
|
|
431
|
+
return (0, fence_js_1.guarded)(`No new payment was signed: the payment of ${usdg(out.price)} USDG to ${out.payTo} signed earlier for this purchase was sent again. ${first}${await this.outcome(X, r, out)}`);
|
|
432
|
+
}
|
|
433
|
+
// the probe has a time bound of its own, as the payer's (DEFAULT_TIMEOUT_MS), its body included: the wallet's
|
|
434
|
+
// other money calls wait for this one
|
|
435
|
+
let probe;
|
|
436
|
+
try {
|
|
437
|
+
probe = await this.fetchImpl(args.url, { ...init(), signal: AbortSignal.timeout(X.DEFAULT_TIMEOUT_MS) });
|
|
409
438
|
}
|
|
410
|
-
|
|
439
|
+
catch (error) {
|
|
440
|
+
const name = error?.name;
|
|
441
|
+
if (name === "TimeoutError" || name === "AbortError")
|
|
442
|
+
return `Error: ${host} did not answer within ${X.DEFAULT_TIMEOUT_MS / 1000} s. Nothing was signed or paid.`;
|
|
443
|
+
throw error;
|
|
444
|
+
}
|
|
445
|
+
const probeText = async () => {
|
|
446
|
+
try {
|
|
447
|
+
return (await X.readCapped(probe)).text;
|
|
448
|
+
}
|
|
449
|
+
catch {
|
|
450
|
+
return "";
|
|
451
|
+
}
|
|
452
|
+
};
|
|
411
453
|
if (probe.status >= 300 && probe.status < 400) {
|
|
412
454
|
const to = probe.headers.get("location");
|
|
413
455
|
return (0, fence_js_1.guarded)(`The URL answered a redirect (HTTP ${probe.status}), not followed: nothing was paid.${to ? `\n${(0, fence_js_1.fenced)(to.slice(0, 500), "redirect target")}` : ""}`);
|
|
414
456
|
}
|
|
415
457
|
if (probe.status !== 402)
|
|
416
|
-
return (0, fence_js_1.guarded)(`No payment asked (HTTP ${probe.status}). Response:\n${(0, fence_js_1.fenced)((await
|
|
458
|
+
return (0, fence_js_1.guarded)(`No payment asked (HTTP ${probe.status}). Response:\n${(0, fence_js_1.fenced)((await probeText()).slice(0, 2000), "response body")}`);
|
|
417
459
|
// the 402 as @priors/x402's payer reads it (the PAYMENT-REQUIRED header, else a v2 body), and its requirement as
|
|
418
460
|
// the payer picks it: exact USDG on Robinhood Chain by EIP-3009, on USDG's own EIP-712 domain, to a 0x payTo
|
|
419
461
|
const { x402Client, x402HTTPClient } = await x402Fetch();
|
|
420
462
|
const http = new x402HTTPClient(new x402Client());
|
|
421
463
|
let body;
|
|
422
464
|
try {
|
|
423
|
-
const text = await
|
|
465
|
+
const text = await probeText();
|
|
424
466
|
body = text ? JSON.parse(text) : undefined;
|
|
425
467
|
}
|
|
426
468
|
catch {
|
|
@@ -470,8 +512,11 @@ class PriorsActionProvider extends agentkit_1.ActionProvider {
|
|
|
470
512
|
return `Error: the wallet holds ${usdg(balance)} USDG, short of ${usdg(price)}; borrowing ${usdg(amount)} (the pool's minimum loan is ${usdg(params.minLoan)}) is above ${auto ? `the most this call may borrow, ${usdg(maxBorrow)}` : `maxBorrow ${args.maxBorrow || "0"}`}. Nothing was paid.`;
|
|
471
513
|
}
|
|
472
514
|
// auto: the day's room is taken here, before any await, so two calls running at once never both pass the
|
|
473
|
-
// limit; it is given back whenever the borrow stops before it is sent, refused or a read failing
|
|
474
|
-
//
|
|
515
|
+
// limit; it is given back whenever the borrow stops before it is sent, refused or a read failing, the
|
|
516
|
+
// controller check's included (GHSA-q4cg, GHSA-87h5), and when it is mined and reverts (it moved nothing:
|
|
517
|
+
// GHSA-mc89); a borrow whose sending began and whose answer is lost stays counted (the safe direction).
|
|
518
|
+
// Before it is sent, what the pool lent the agent today is checked against the same limit (dayRoom), so a
|
|
519
|
+
// restart, which starts this count at 0, does not start the day again (GHSA-j679)
|
|
475
520
|
let reserved = null;
|
|
476
521
|
let sending = false;
|
|
477
522
|
if (auto) {
|
|
@@ -479,20 +524,23 @@ class PriorsActionProvider extends agentkit_1.ActionProvider {
|
|
|
479
524
|
if (this.borrowedToday.day !== today)
|
|
480
525
|
this.borrowedToday = { day: today, amount: 0n };
|
|
481
526
|
if (this.borrowedToday.amount + amount > auto.perDay)
|
|
482
|
-
return `Error: the wallet holds ${usdg(balance)} USDG, short of ${usdg(price)}, and auto-borrow's limit of ${usdg(auto.perDay)} USDG a day has ${usdg(auto.perDay - this.borrowedToday.amount)} left
|
|
527
|
+
return `Error: the wallet holds ${usdg(balance)} USDG, short of ${usdg(price)}, and auto-borrow's limit of ${usdg(auto.perDay)} USDG a day has ${usdg(auto.perDay - this.borrowedToday.amount)} left, after what this process borrowed today, less than ${usdg(amount)}. Nothing was borrowed or paid.`;
|
|
483
528
|
this.borrowedToday.amount += amount;
|
|
484
529
|
reserved = { day: today, amount };
|
|
485
530
|
}
|
|
531
|
+
const day = reserved?.day ?? "";
|
|
486
532
|
// auto: 14 days, brought down to the pool's maxTerm; otherwise the term asked, as before
|
|
487
533
|
const termDays = auto && params.maxTerm !== undefined && BigInt(days) * 86400n > BigInt(params.maxTerm) ? Number(BigInt(params.maxTerm) / 86400n) : days;
|
|
488
534
|
const loan = await this.borrowAmount(walletProvider, args.agentId, amount, termDays, auto
|
|
489
535
|
? async (fee) => {
|
|
490
536
|
await this.autopayCovers(walletProvider, args.agentId, amount + fee);
|
|
491
|
-
|
|
537
|
+
await this.dayRoom(walletProvider, args.agentId, amount, auto.perDay, day);
|
|
492
538
|
}
|
|
493
|
-
: undefined, "borrowed or paid")
|
|
539
|
+
: undefined, "borrowed or paid", () => {
|
|
540
|
+
sending = true; // right before the borrow's transaction is sent, every check passed
|
|
541
|
+
})
|
|
494
542
|
.catch((error) => {
|
|
495
|
-
if (reserved && !sending && this.borrowedToday.day === reserved.day)
|
|
543
|
+
if (reserved && (!sending || error instanceof Reverted) && this.borrowedToday.day === reserved.day)
|
|
496
544
|
this.borrowedToday.amount -= reserved.amount;
|
|
497
545
|
throw error;
|
|
498
546
|
});
|
|
@@ -514,12 +562,14 @@ class PriorsActionProvider extends agentkit_1.ActionProvider {
|
|
|
514
562
|
const r = await X.resend(args.url, signed.paymentHeaders, { ...RESEND, init: init(), fetchImpl: this.fetchImpl, timeoutMs: X.DEFAULT_TIMEOUT_MS });
|
|
515
563
|
if (r.response.ok)
|
|
516
564
|
this.unsettled.delete(purchase);
|
|
517
|
-
return (0, fence_js_1.guarded)(`${borrowed}${await this.outcome(r, signed
|
|
565
|
+
return (0, fence_js_1.guarded)(`${borrowed}${await this.outcome(X, r, signed)}`);
|
|
518
566
|
});
|
|
519
567
|
}
|
|
520
568
|
catch (error) {
|
|
521
569
|
if (error instanceof Refusal)
|
|
522
570
|
return (0, fence_js_1.guarded)(`${borrowed}Error: ${error.message}`);
|
|
571
|
+
if (error instanceof Unconfirmed)
|
|
572
|
+
return (0, fence_js_1.guarded)(`Error: ${error.message} Nothing was signed or paid.`);
|
|
523
573
|
return (0, fence_js_1.guarded)(`${borrowed}Error paying ${(0, fence_js_1.unfenced)(args.url)} with Priors credit: ${(0, fence_js_1.unfenced)(String(error))}`);
|
|
524
574
|
}
|
|
525
575
|
}
|
|
@@ -576,6 +626,44 @@ class PriorsActionProvider extends agentkit_1.ActionProvider {
|
|
|
576
626
|
if (BigInt(allowance) < owed + due)
|
|
577
627
|
throw no(`Autopay may pull ${usdg(BigInt(allowance))} USDG from this wallet, and its open loans already need ${usdg(owed)} USDG`);
|
|
578
628
|
}
|
|
629
|
+
/**
|
|
630
|
+
* Auto-borrow's day limit as the pool records the day (GHSA-j679): `amount` more on top of what the pool lent agent
|
|
631
|
+
* `agentId` since 00:00 UTC of `day` must stay within `perDay`. Every loan of the agent issued that day counts, whoever
|
|
632
|
+
* took it (the pool records the agent and its owner, not the key that borrowed), so a restart, or another process of
|
|
633
|
+
* this wallet, starts the day where the pool is; that can only lower auto-borrow's room. A read that fails, or a loan
|
|
634
|
+
* whose record does not read as one, refuses (nothing is sent). The pool lists an agent's loans oldest first
|
|
635
|
+
* (CreditPoolV2 appends each in borrow), so they are read from the newest back to the first one issued before the day.
|
|
636
|
+
*
|
|
637
|
+
* SHORTCUT: what the pool shows: a borrow another process sent and the chain has not mined yet is not seen, and after a
|
|
638
|
+
* restart a provider that auto-borrows for several agents counts each agent's own loans only (its count across agents
|
|
639
|
+
* starts again). Upgrade when the provider gets a place to keep state (@priors/mcp's daily ledger under
|
|
640
|
+
* PRIORS_STATE_DIR), or on a report of either.
|
|
641
|
+
*
|
|
642
|
+
* @param walletProvider - The wallet provider.
|
|
643
|
+
* @param agentId - The agent id.
|
|
644
|
+
* @param amount - The borrow about to be sent, atomic USDG.
|
|
645
|
+
* @param perDay - The owner's limit a UTC day, atomic USDG.
|
|
646
|
+
* @param day - The UTC day the borrow counts in (YYYY-MM-DD).
|
|
647
|
+
*/
|
|
648
|
+
async dayRoom(walletProvider, agentId, amount, perDay, day) {
|
|
649
|
+
const id = BigInt(agentId);
|
|
650
|
+
let lent = 0n;
|
|
651
|
+
try {
|
|
652
|
+
const start = BigInt(Date.parse(`${day}T00:00:00Z`) / 1000);
|
|
653
|
+
const ids = (await walletProvider.readContract({ address: constants_1.PRIORS_POOL, abi: constants_1.POOL_ABI, functionName: "loansOf", args: [id] }));
|
|
654
|
+
for (let i = ids.length - 1; i >= 0; i--) {
|
|
655
|
+
const l = (await walletProvider.readContract({ address: constants_1.PRIORS_POOL, abi: constants_1.POOL_ABI, functionName: "getLoan", args: [ids[i]] }));
|
|
656
|
+
if (BigInt(l.issuedAt) < start)
|
|
657
|
+
break;
|
|
658
|
+
lent += BigInt(l.principal);
|
|
659
|
+
}
|
|
660
|
+
}
|
|
661
|
+
catch (error) {
|
|
662
|
+
throw new Refusal(`auto-borrow's day limit could not be checked: agent #${agentId}'s loans of today could not be read from the pool (${(0, fence_js_1.unfenced)(String(error))}). Nothing was borrowed or paid.`);
|
|
663
|
+
}
|
|
664
|
+
if (lent + amount > perDay)
|
|
665
|
+
throw new Refusal(`auto-borrow's limit of ${usdg(perDay)} USDG a day has ${usdg(lent < perDay ? perDay - lent : 0n)} left: the pool lent agent #${agentId} ${usdg(lent)} USDG since 00:00 UTC (every loan of the agent today counts, whoever took it, so a restart does not start the day again), less than ${usdg(amount)}. Nothing was borrowed or paid.`);
|
|
666
|
+
}
|
|
579
667
|
/**
|
|
580
668
|
* Before this wallet's money moves for agent `agentId` (a borrow into it, a repayment from it), @priors/mcp's rule
|
|
581
669
|
* (needController, GHSA-9pw7): the wallet controls the agent at the pool AND is its current owner or its declared
|
|
@@ -610,44 +698,58 @@ class PriorsActionProvider extends agentkit_1.ActionProvider {
|
|
|
610
698
|
/**
|
|
611
699
|
* What became of a payment sent: paid only on a 2xx answer. Anything else (a dropped connection, no answer in time,
|
|
612
700
|
* a 5xx, a 402, a redirect) leaves it signed and sent, cashable by the seller until it expires, and a later call for
|
|
613
|
-
* the purchase sends it again (@priors/mcp's pay_url answer).
|
|
701
|
+
* the purchase sends it again (@priors/mcp's pay_url answer). A body that fails mid-read (a reset, or the request's
|
|
702
|
+
* time bound firing during a long answer) is said, never an error that hides the payment (@priors/mcp's issue #19,
|
|
703
|
+
* GHSA-87h5): once paid, the purchase is complete, so a call again for it pays again.
|
|
614
704
|
*
|
|
705
|
+
* @param X - @priors/x402 (its readCapped and SKEW_SECONDS).
|
|
615
706
|
* @param r - What @priors/x402's resend answered.
|
|
616
707
|
* @param s - The payment sent.
|
|
617
|
-
* @param skew - @priors/x402's SKEW_SECONDS, the margin kept past validBefore.
|
|
618
708
|
* @returns The answer's words for it.
|
|
619
709
|
*/
|
|
620
|
-
async outcome(r, s
|
|
710
|
+
async outcome(X, r, s) {
|
|
621
711
|
const res = r.response;
|
|
622
712
|
// of the settlement header, only its transaction hash: the rest is the seller's words
|
|
623
713
|
const tx = settledTx(res.headers.get("payment-response") || res.headers.get("x-payment-response"));
|
|
624
|
-
|
|
625
|
-
|
|
714
|
+
let text = "";
|
|
715
|
+
let unread = false;
|
|
716
|
+
try {
|
|
717
|
+
({ text } = await X.readCapped(res));
|
|
718
|
+
}
|
|
719
|
+
catch {
|
|
720
|
+
unread = true;
|
|
721
|
+
}
|
|
722
|
+
const lost = "\nThe response body could not be read completely (the connection failed while it was sent).";
|
|
723
|
+
const body = text ? `\nResponse:\n${(0, fence_js_1.fenced)(text.slice(0, 2000), "response body")}` : unread ? lost : "";
|
|
626
724
|
const status = r.timedOut ? "no answer in time" : r.transportError ? "the connection was lost" : `HTTP ${res.status}`;
|
|
627
725
|
if (res.ok)
|
|
628
|
-
return `Paid ${usdg(s.price)} USDG to ${s.payTo} (${status})${tx ? `; settled in ${tx}` : ""}.${body}`;
|
|
629
|
-
const until = new Date((s.validBefore +
|
|
726
|
+
return `Paid ${usdg(s.price)} USDG to ${s.payTo} (${status})${tx ? `; settled in ${tx}` : ""}.${body}${unread ? " This does not undo the payment, and calling again for this purchase pays again: ask the seller for the result instead." : ""}`;
|
|
727
|
+
const until = new Date((s.validBefore + X.SKEW_SECONDS) * 1000).toISOString();
|
|
630
728
|
const redirect = res.status >= 300 && res.status < 400 ? ", a redirect, not followed" : "";
|
|
631
729
|
return `The payment of ${usdg(s.price)} USDG to ${s.payTo} was signed and sent (${status}${redirect}), and the seller may still settle it until ${until}${tx ? ` (it names ${tx})` : ""}: do NOT call pay_x402_with_priors_credit again for this purchase (the same method, URL and body) before then. A later call for it sends this same payment again, never a new one.${body}`;
|
|
632
730
|
}
|
|
633
731
|
/**
|
|
634
|
-
* Runs
|
|
635
|
-
*
|
|
732
|
+
* Runs a wallet's money calls (pay, borrow, repay) one at a time, as @priors/x402's createPayer queues its payments
|
|
733
|
+
* and @priors/mcp runs its money calls: two calls at once on a short wallet would each read the balance short and each
|
|
734
|
+
* borrow, both passing auto-borrow's Autopay check on an approval that covers one loan (GHSA-482p F3, GHSA-87h5). A
|
|
735
|
+
* call for a purchase another call is paying waits for it, then finds its payment while that may still settle; once
|
|
736
|
+
* it is paid (a 2xx), the purchase is complete and a call for it is a new one.
|
|
636
737
|
*
|
|
637
|
-
* @param
|
|
738
|
+
* @param walletProvider - The wallet whose calls queue.
|
|
638
739
|
* @param fn - The call.
|
|
639
740
|
* @returns What the call answers.
|
|
640
741
|
*/
|
|
641
|
-
async
|
|
642
|
-
const
|
|
742
|
+
async onePerWallet(walletProvider, fn) {
|
|
743
|
+
const key = String(walletProvider.getAddress()).toLowerCase();
|
|
744
|
+
const run = (this.running.get(key) ?? Promise.resolve()).then(fn);
|
|
643
745
|
const done = run.then(() => undefined, () => undefined);
|
|
644
|
-
this.running.set(
|
|
746
|
+
this.running.set(key, done);
|
|
645
747
|
try {
|
|
646
748
|
return await run;
|
|
647
749
|
}
|
|
648
750
|
finally {
|
|
649
|
-
if (this.running.get(
|
|
650
|
-
this.running.delete(
|
|
751
|
+
if (this.running.get(key) === done)
|
|
752
|
+
this.running.delete(key);
|
|
651
753
|
}
|
|
652
754
|
}
|
|
653
755
|
/**
|
|
@@ -659,9 +761,10 @@ class PriorsActionProvider extends agentkit_1.ActionProvider {
|
|
|
659
761
|
* @param days - The term in days.
|
|
660
762
|
* @param check - Called with the quoted fee before the borrow is sent; a throw refuses it.
|
|
661
763
|
* @param did - What did not happen when the borrow is refused ("borrowed", "borrowed or paid").
|
|
764
|
+
* @param onSend - Called once every check has passed, right before the borrow's transaction is sent.
|
|
662
765
|
* @returns The loan.
|
|
663
766
|
*/
|
|
664
|
-
async borrowAmount(walletProvider, agentId, amount, days, check, did = "borrowed") {
|
|
767
|
+
async borrowAmount(walletProvider, agentId, amount, days, check, did = "borrowed", onSend) {
|
|
665
768
|
const me = walletProvider.getAddress();
|
|
666
769
|
const term = BigInt(days * 86400);
|
|
667
770
|
const [fee] = (await walletProvider.readContract({
|
|
@@ -675,6 +778,7 @@ class PriorsActionProvider extends agentkit_1.ActionProvider {
|
|
|
675
778
|
// the same rule as repay, before anything is sent: no key borrows here for an agent it would then be refused to
|
|
676
779
|
// repay for
|
|
677
780
|
await this.control(walletProvider, BigInt(agentId), did);
|
|
781
|
+
onSend?.();
|
|
678
782
|
const hash = await walletProvider.sendTransaction({
|
|
679
783
|
to: constants_1.PRIORS_POOL,
|
|
680
784
|
data: (0, viem_1.encodeFunctionData)({
|
|
@@ -683,7 +787,15 @@ class PriorsActionProvider extends agentkit_1.ActionProvider {
|
|
|
683
787
|
args: [BigInt(agentId), amount, term, me, fee],
|
|
684
788
|
}),
|
|
685
789
|
});
|
|
686
|
-
|
|
790
|
+
// sent: an answer lost from here on may hide a loan, so it is said with its transaction, never a bare error (P-18's
|
|
791
|
+
// rule, GHSA-87h5)
|
|
792
|
+
let receipt;
|
|
793
|
+
try {
|
|
794
|
+
receipt = await walletProvider.waitForTransactionReceipt(hash);
|
|
795
|
+
}
|
|
796
|
+
catch (error) {
|
|
797
|
+
throw new Unconfirmed(`the borrow of ${usdg(amount)} USDG was sent (transaction ${hash}) and its answer was lost (${(0, fence_js_1.unfenced)(String(error))}), so it may have opened a loan: check that transaction before calling again, and repay the loan with repay_priors_loan before its due date.`);
|
|
798
|
+
}
|
|
687
799
|
mined(receipt, "borrow", hash);
|
|
688
800
|
let loanId = "?";
|
|
689
801
|
let dueAt = "?";
|
|
@@ -784,7 +896,7 @@ Inputs:
|
|
|
784
896
|
- maxPrice: the most to pay for this call, in USDG (e.g. 0.10).
|
|
785
897
|
- maxBorrow: the most to borrow if the wallet is short, in USDG (default 0: never borrow; with autoBorrow, its amount
|
|
786
898
|
per call, which this can only lower).
|
|
787
|
-
- days: the term of a loan taken for the gap (default 7; 14
|
|
899
|
+
- days: the term of a loan taken for the gap (default 7; with autoBorrow always 14, the owner's setting).
|
|
788
900
|
- method, body: POST and its body (default GET with no body).`,
|
|
789
901
|
schema: schemas_1.PayX402WithCreditSchema,
|
|
790
902
|
}),
|
package/dist/schemas.js
CHANGED
|
@@ -43,7 +43,7 @@ exports.PayX402WithCreditSchema = zod_1.z
|
|
|
43
43
|
.positive()
|
|
44
44
|
.max(90)
|
|
45
45
|
.optional()
|
|
46
|
-
.describe("Term of a loan taken for the gap (default 7
|
|
46
|
+
.describe("Term of a loan taken for the gap (default 7); with the provider's autoBorrow always 14, the owner's setting"),
|
|
47
47
|
method: zod_1.z
|
|
48
48
|
.enum(["GET", "POST"])
|
|
49
49
|
.optional()
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@priors/agentkit",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.5",
|
|
4
4
|
"description": "Priors action provider for Coinbase AgentKit: pay x402 APIs in USDG on Robinhood Chain and borrow the gap from an ERC-8004 agent's Priors credit line, repay, and read another agent's repayment record before paying it.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"author": "Priors <contact@priors.trade>",
|
|
@@ -16,7 +16,7 @@
|
|
|
16
16
|
"prepack": "npm run build"
|
|
17
17
|
},
|
|
18
18
|
"dependencies": {
|
|
19
|
-
"@priors/x402": "0.8.
|
|
19
|
+
"@priors/x402": "0.8.8",
|
|
20
20
|
"@x402/fetch": "^2.29.0",
|
|
21
21
|
"viem": "^2.38.3"
|
|
22
22
|
},
|