arl-protocol-sdk 0.0.0-stage → 0.1.0

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/abi.js ADDED
@@ -0,0 +1,465 @@
1
+ // ABI of contracts/src/ComputePayment.sol (solc 0.8.36). Generated from the Foundry artifact;
2
+ // test-anvil/streaming.anvil.test.ts fails if it drifts from the compiled contract.
3
+ export const computePaymentAbi = [
4
+ {
5
+ type: "constructor",
6
+ inputs: [
7
+ {
8
+ name: "paymentToken_",
9
+ type: "address",
10
+ internalType: "contract IERC20",
11
+ },
12
+ ],
13
+ stateMutability: "nonpayable",
14
+ },
15
+ {
16
+ type: "function",
17
+ name: "MAX_DURATION",
18
+ inputs: [],
19
+ outputs: [
20
+ {
21
+ name: "",
22
+ type: "uint40",
23
+ internalType: "uint40",
24
+ },
25
+ ],
26
+ stateMutability: "view",
27
+ },
28
+ {
29
+ type: "function",
30
+ name: "depositOf",
31
+ inputs: [
32
+ {
33
+ name: "streamId",
34
+ type: "uint256",
35
+ internalType: "uint256",
36
+ },
37
+ ],
38
+ outputs: [
39
+ {
40
+ name: "",
41
+ type: "uint256",
42
+ internalType: "uint256",
43
+ },
44
+ ],
45
+ stateMutability: "view",
46
+ },
47
+ {
48
+ type: "function",
49
+ name: "getStream",
50
+ inputs: [
51
+ {
52
+ name: "streamId",
53
+ type: "uint256",
54
+ internalType: "uint256",
55
+ },
56
+ ],
57
+ outputs: [
58
+ {
59
+ name: "",
60
+ type: "tuple",
61
+ internalType: "struct ComputePayment.Stream",
62
+ components: [
63
+ {
64
+ name: "sender",
65
+ type: "address",
66
+ internalType: "address",
67
+ },
68
+ {
69
+ name: "startTime",
70
+ type: "uint40",
71
+ internalType: "uint40",
72
+ },
73
+ {
74
+ name: "endTime",
75
+ type: "uint40",
76
+ internalType: "uint40",
77
+ },
78
+ {
79
+ name: "provider",
80
+ type: "address",
81
+ internalType: "address",
82
+ },
83
+ {
84
+ name: "stopTime",
85
+ type: "uint40",
86
+ internalType: "uint40",
87
+ },
88
+ {
89
+ name: "settled",
90
+ type: "bool",
91
+ internalType: "bool",
92
+ },
93
+ {
94
+ name: "ratePerSecond",
95
+ type: "uint128",
96
+ internalType: "uint128",
97
+ },
98
+ {
99
+ name: "withdrawn",
100
+ type: "uint128",
101
+ internalType: "uint128",
102
+ },
103
+ ],
104
+ },
105
+ ],
106
+ stateMutability: "view",
107
+ },
108
+ {
109
+ type: "function",
110
+ name: "paymentToken",
111
+ inputs: [],
112
+ outputs: [
113
+ {
114
+ name: "",
115
+ type: "address",
116
+ internalType: "contract IERC20",
117
+ },
118
+ ],
119
+ stateMutability: "view",
120
+ },
121
+ {
122
+ type: "function",
123
+ name: "refundableAmountOf",
124
+ inputs: [
125
+ {
126
+ name: "streamId",
127
+ type: "uint256",
128
+ internalType: "uint256",
129
+ },
130
+ ],
131
+ outputs: [
132
+ {
133
+ name: "",
134
+ type: "uint256",
135
+ internalType: "uint256",
136
+ },
137
+ ],
138
+ stateMutability: "view",
139
+ },
140
+ {
141
+ type: "function",
142
+ name: "stopStream",
143
+ inputs: [
144
+ {
145
+ name: "streamId",
146
+ type: "uint256",
147
+ internalType: "uint256",
148
+ },
149
+ ],
150
+ outputs: [
151
+ {
152
+ name: "providerAmount",
153
+ type: "uint256",
154
+ internalType: "uint256",
155
+ },
156
+ {
157
+ name: "refundAmount",
158
+ type: "uint256",
159
+ internalType: "uint256",
160
+ },
161
+ ],
162
+ stateMutability: "nonpayable",
163
+ },
164
+ {
165
+ type: "function",
166
+ name: "streamCompute",
167
+ inputs: [
168
+ {
169
+ name: "provider",
170
+ type: "address",
171
+ internalType: "address",
172
+ },
173
+ {
174
+ name: "ratePerSecond",
175
+ type: "uint128",
176
+ internalType: "uint128",
177
+ },
178
+ {
179
+ name: "maxDuration",
180
+ type: "uint40",
181
+ internalType: "uint40",
182
+ },
183
+ ],
184
+ outputs: [
185
+ {
186
+ name: "streamId",
187
+ type: "uint256",
188
+ internalType: "uint256",
189
+ },
190
+ ],
191
+ stateMutability: "nonpayable",
192
+ },
193
+ {
194
+ type: "function",
195
+ name: "streamCounter",
196
+ inputs: [],
197
+ outputs: [
198
+ {
199
+ name: "",
200
+ type: "uint256",
201
+ internalType: "uint256",
202
+ },
203
+ ],
204
+ stateMutability: "view",
205
+ },
206
+ {
207
+ type: "function",
208
+ name: "streamedAmountOf",
209
+ inputs: [
210
+ {
211
+ name: "streamId",
212
+ type: "uint256",
213
+ internalType: "uint256",
214
+ },
215
+ ],
216
+ outputs: [
217
+ {
218
+ name: "",
219
+ type: "uint256",
220
+ internalType: "uint256",
221
+ },
222
+ ],
223
+ stateMutability: "view",
224
+ },
225
+ {
226
+ type: "function",
227
+ name: "withdraw",
228
+ inputs: [
229
+ {
230
+ name: "streamId",
231
+ type: "uint256",
232
+ internalType: "uint256",
233
+ },
234
+ ],
235
+ outputs: [
236
+ {
237
+ name: "amount",
238
+ type: "uint256",
239
+ internalType: "uint256",
240
+ },
241
+ ],
242
+ stateMutability: "nonpayable",
243
+ },
244
+ {
245
+ type: "function",
246
+ name: "withdrawableAmountOf",
247
+ inputs: [
248
+ {
249
+ name: "streamId",
250
+ type: "uint256",
251
+ internalType: "uint256",
252
+ },
253
+ ],
254
+ outputs: [
255
+ {
256
+ name: "",
257
+ type: "uint256",
258
+ internalType: "uint256",
259
+ },
260
+ ],
261
+ stateMutability: "view",
262
+ },
263
+ {
264
+ type: "event",
265
+ name: "PaymentSettled",
266
+ inputs: [
267
+ {
268
+ name: "streamId",
269
+ type: "uint256",
270
+ indexed: true,
271
+ internalType: "uint256",
272
+ },
273
+ {
274
+ name: "provider",
275
+ type: "address",
276
+ indexed: true,
277
+ internalType: "address",
278
+ },
279
+ {
280
+ name: "providerAmount",
281
+ type: "uint256",
282
+ indexed: false,
283
+ internalType: "uint256",
284
+ },
285
+ {
286
+ name: "sender",
287
+ type: "address",
288
+ indexed: true,
289
+ internalType: "address",
290
+ },
291
+ {
292
+ name: "refundAmount",
293
+ type: "uint256",
294
+ indexed: false,
295
+ internalType: "uint256",
296
+ },
297
+ ],
298
+ anonymous: false,
299
+ },
300
+ {
301
+ type: "event",
302
+ name: "StreamStarted",
303
+ inputs: [
304
+ {
305
+ name: "streamId",
306
+ type: "uint256",
307
+ indexed: true,
308
+ internalType: "uint256",
309
+ },
310
+ {
311
+ name: "sender",
312
+ type: "address",
313
+ indexed: true,
314
+ internalType: "address",
315
+ },
316
+ {
317
+ name: "provider",
318
+ type: "address",
319
+ indexed: true,
320
+ internalType: "address",
321
+ },
322
+ {
323
+ name: "ratePerSecond",
324
+ type: "uint256",
325
+ indexed: false,
326
+ internalType: "uint256",
327
+ },
328
+ {
329
+ name: "startTime",
330
+ type: "uint256",
331
+ indexed: false,
332
+ internalType: "uint256",
333
+ },
334
+ {
335
+ name: "endTime",
336
+ type: "uint256",
337
+ indexed: false,
338
+ internalType: "uint256",
339
+ },
340
+ {
341
+ name: "deposit",
342
+ type: "uint256",
343
+ indexed: false,
344
+ internalType: "uint256",
345
+ },
346
+ ],
347
+ anonymous: false,
348
+ },
349
+ {
350
+ type: "event",
351
+ name: "StreamStopped",
352
+ inputs: [
353
+ {
354
+ name: "streamId",
355
+ type: "uint256",
356
+ indexed: true,
357
+ internalType: "uint256",
358
+ },
359
+ {
360
+ name: "stoppedBy",
361
+ type: "address",
362
+ indexed: true,
363
+ internalType: "address",
364
+ },
365
+ {
366
+ name: "stopTime",
367
+ type: "uint256",
368
+ indexed: false,
369
+ internalType: "uint256",
370
+ },
371
+ ],
372
+ anonymous: false,
373
+ },
374
+ {
375
+ type: "event",
376
+ name: "Withdrawn",
377
+ inputs: [
378
+ {
379
+ name: "streamId",
380
+ type: "uint256",
381
+ indexed: true,
382
+ internalType: "uint256",
383
+ },
384
+ {
385
+ name: "provider",
386
+ type: "address",
387
+ indexed: true,
388
+ internalType: "address",
389
+ },
390
+ {
391
+ name: "amount",
392
+ type: "uint256",
393
+ indexed: false,
394
+ internalType: "uint256",
395
+ },
396
+ ],
397
+ anonymous: false,
398
+ },
399
+ {
400
+ type: "error",
401
+ name: "AlreadySettled",
402
+ inputs: [],
403
+ },
404
+ {
405
+ type: "error",
406
+ name: "DepositTooLarge",
407
+ inputs: [],
408
+ },
409
+ {
410
+ type: "error",
411
+ name: "InvalidDuration",
412
+ inputs: [],
413
+ },
414
+ {
415
+ type: "error",
416
+ name: "InvalidProvider",
417
+ inputs: [],
418
+ },
419
+ {
420
+ type: "error",
421
+ name: "InvalidStream",
422
+ inputs: [],
423
+ },
424
+ {
425
+ type: "error",
426
+ name: "NothingToWithdraw",
427
+ inputs: [],
428
+ },
429
+ {
430
+ type: "error",
431
+ name: "ReentrancyGuardReentrantCall",
432
+ inputs: [],
433
+ },
434
+ {
435
+ type: "error",
436
+ name: "SafeERC20FailedOperation",
437
+ inputs: [
438
+ {
439
+ name: "token",
440
+ type: "address",
441
+ internalType: "address",
442
+ },
443
+ ],
444
+ },
445
+ {
446
+ type: "error",
447
+ name: "Unauthorized",
448
+ inputs: [],
449
+ },
450
+ {
451
+ type: "error",
452
+ name: "UnexpectedDeposit",
453
+ inputs: [],
454
+ },
455
+ {
456
+ type: "error",
457
+ name: "ZeroAddress",
458
+ inputs: [],
459
+ },
460
+ {
461
+ type: "error",
462
+ name: "ZeroRate",
463
+ inputs: [],
464
+ },
465
+ ];
@@ -0,0 +1,34 @@
1
+ import { type Address, type Hash } from "viem";
2
+ import { type VerifiedClients } from "./verified.ts";
3
+ /** Base Mainnet contracts the swap uses (Uniswap v3 deployments, the ARL token and quote tokens). */
4
+ export declare const ARL_SWAP: {
5
+ readonly chainId: 8453;
6
+ readonly arl: "0xde91E6f39D50bBd875f831dcc1134A3D7f3aaDb4";
7
+ readonly fee: 10000;
8
+ readonly router: "0x2626664c2603336E57B271c5C0b26F421741e481";
9
+ readonly quoter: "0x3d4e44Eb1374240CE5F1B871ab261CD16335B76a";
10
+ readonly tokens: {
11
+ readonly ETH: "0x4200000000000000000000000000000000000006";
12
+ readonly WETH: "0x4200000000000000000000000000000000000006";
13
+ readonly USDC: "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913";
14
+ readonly USDT: "0xfde4C96c8593536E31F229EA8f37b2ADa2699bb2";
15
+ readonly cbBTC: "0xcbB7C0000aB88B473b1f5aFd9ef808440eed33Bf";
16
+ };
17
+ };
18
+ export type ArlQuoteToken = keyof typeof ARL_SWAP.tokens;
19
+ export interface AcquireArlParams {
20
+ /** Exact ARL to receive, in base units (18 decimals). */
21
+ amountOut: bigint;
22
+ tokenIn: ArlQuoteToken;
23
+ /** Most of `tokenIn` the caller will spend, in its base units. */
24
+ maxAmountIn: bigint;
25
+ /** Who receives the ARL; defaults to the wallet's account. */
26
+ recipient?: Address;
27
+ }
28
+ /** The amount of `tokenIn` needed for exactly `amountOut` ARL right now. */
29
+ export declare function quoteArl(publicClient: VerifiedClients["publicClient"], tokenIn: ArlQuoteToken, amountOut: bigint): Promise<bigint>;
30
+ /** Buys exactly `amountOut` ARL with at most `maxAmountIn` of `tokenIn`. */
31
+ export declare function acquireArl({ publicClient, walletClient }: VerifiedClients, p: AcquireArlParams): Promise<{
32
+ amountIn: bigint;
33
+ swapTx: Hash;
34
+ }>;
package/acquireArl.js ADDED
@@ -0,0 +1,126 @@
1
+ // Buy an exact amount of ARL on Base Mainnet through the official Uniswap v3 pools (1% fee tier,
2
+ // docs/mainnet-plan.md), so an agent that holds ETH, USDC, USDT or cbBTC can pay a verified job.
3
+ //
4
+ // await acquireArl(clients, { amountOut: parseUnits("100", 18), tokenIn: "ETH",
5
+ // maxAmountIn: parseEther("0.02") });
6
+ //
7
+ // It quotes with QuoterV2, refuses a quote above `maxAmountIn`, then swaps with SwapRouter02
8
+ // `exactOutputSingle` (ETH is sent as value and wrapped by the router; the unused rest is
9
+ // refunded in the same transaction). Base Mainnet only, where the pools are.
10
+ import { encodeFunctionData, getAddress, parseAbi } from "viem";
11
+ import { VerifiedJobError, walletAccount } from "./verified.js";
12
+ /** Base Mainnet contracts the swap uses (Uniswap v3 deployments, the ARL token and quote tokens). */
13
+ export const ARL_SWAP = {
14
+ chainId: 8453,
15
+ arl: "0xde91E6f39D50bBd875f831dcc1134A3D7f3aaDb4",
16
+ fee: 10_000,
17
+ router: "0x2626664c2603336E57B271c5C0b26F421741e481",
18
+ quoter: "0x3d4e44Eb1374240CE5F1B871ab261CD16335B76a",
19
+ tokens: {
20
+ ETH: "0x4200000000000000000000000000000000000006",
21
+ WETH: "0x4200000000000000000000000000000000000006",
22
+ USDC: "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",
23
+ USDT: "0xfde4C96c8593536E31F229EA8f37b2ADa2699bb2",
24
+ cbBTC: "0xcbB7C0000aB88B473b1f5aFd9ef808440eed33Bf",
25
+ },
26
+ };
27
+ const quoterAbi = parseAbi([
28
+ "struct QuoteExactOutputSingleParams { address tokenIn; address tokenOut; uint256 amount; uint24 fee; uint160 sqrtPriceLimitX96; }",
29
+ "function quoteExactOutputSingle(QuoteExactOutputSingleParams params) returns (uint256 amountIn, uint160 sqrtPriceX96After, uint32 initializedTicksCrossed, uint256 gasEstimate)",
30
+ ]);
31
+ const routerAbi = parseAbi([
32
+ "struct ExactOutputSingleParams { address tokenIn; address tokenOut; uint24 fee; address recipient; uint256 amountOut; uint256 amountInMaximum; uint160 sqrtPriceLimitX96; }",
33
+ "function exactOutputSingle(ExactOutputSingleParams params) payable returns (uint256 amountIn)",
34
+ "function refundETH() payable",
35
+ "function multicall(bytes[] data) payable returns (bytes[] results)",
36
+ ]);
37
+ const erc20Abi = parseAbi(["function approve(address spender, uint256 amount) returns (bool)"]);
38
+ /** The amount of `tokenIn` needed for exactly `amountOut` ARL right now. */
39
+ export async function quoteArl(publicClient, tokenIn, amountOut) {
40
+ await checkSwapChain(publicClient);
41
+ const { result } = await publicClient.simulateContract({
42
+ address: ARL_SWAP.quoter,
43
+ abi: quoterAbi,
44
+ functionName: "quoteExactOutputSingle",
45
+ args: [
46
+ {
47
+ tokenIn: ARL_SWAP.tokens[tokenIn],
48
+ tokenOut: ARL_SWAP.arl,
49
+ amount: amountOut,
50
+ fee: ARL_SWAP.fee,
51
+ sqrtPriceLimitX96: 0n,
52
+ },
53
+ ],
54
+ });
55
+ return result[0];
56
+ }
57
+ async function checkSwapChain(publicClient) {
58
+ const id = await publicClient.getChainId();
59
+ if (id !== ARL_SWAP.chainId)
60
+ throw new VerifiedJobError(`ARL pools are on Base Mainnet, not chain ${String(id)}`);
61
+ }
62
+ /** Buys exactly `amountOut` ARL with at most `maxAmountIn` of `tokenIn`. */
63
+ export async function acquireArl({ publicClient, walletClient }, p) {
64
+ if (p.amountOut <= 0n || p.maxAmountIn <= 0n)
65
+ throw new VerifiedJobError("amounts must be positive");
66
+ const quoted = await quoteArl(publicClient, p.tokenIn, p.amountOut);
67
+ if (quoted > p.maxAmountIn) {
68
+ throw new VerifiedJobError(`the swap needs ${quoted.toString()} of ${p.tokenIn}, above maxAmountIn`);
69
+ }
70
+ const from = walletAccount(walletClient);
71
+ const recipient = getAddress(p.recipient ?? from.address);
72
+ const tokenIn = ARL_SWAP.tokens[p.tokenIn];
73
+ const native = p.tokenIn === "ETH";
74
+ const wait = async (hash, what) => {
75
+ const r = await publicClient.waitForTransactionReceipt({ hash });
76
+ if (r.status !== "success")
77
+ throw new VerifiedJobError(`${what} reverted`);
78
+ };
79
+ if (!native) {
80
+ const approveTx = await walletClient.writeContract({
81
+ account: from,
82
+ chain: walletClient.chain,
83
+ address: tokenIn,
84
+ abi: erc20Abi,
85
+ functionName: "approve",
86
+ args: [ARL_SWAP.router, p.maxAmountIn],
87
+ });
88
+ await wait(approveTx, "approve");
89
+ }
90
+ const swap = {
91
+ tokenIn,
92
+ tokenOut: ARL_SWAP.arl,
93
+ fee: ARL_SWAP.fee,
94
+ recipient,
95
+ amountOut: p.amountOut,
96
+ amountInMaximum: p.maxAmountIn,
97
+ sqrtPriceLimitX96: 0n,
98
+ };
99
+ const { request, result } = await publicClient.simulateContract({
100
+ account: from,
101
+ address: ARL_SWAP.router,
102
+ abi: routerAbi,
103
+ functionName: "exactOutputSingle",
104
+ args: [swap],
105
+ value: native ? p.maxAmountIn : 0n,
106
+ });
107
+ // With ETH, refundETH returns what the swap did not use, in the same transaction.
108
+ const swapTx = native
109
+ ? await walletClient.writeContract({
110
+ account: from,
111
+ chain: walletClient.chain,
112
+ address: ARL_SWAP.router,
113
+ abi: routerAbi,
114
+ functionName: "multicall",
115
+ args: [
116
+ [
117
+ encodeFunctionData({ abi: routerAbi, functionName: "exactOutputSingle", args: [swap] }),
118
+ encodeFunctionData({ abi: routerAbi, functionName: "refundETH" }),
119
+ ],
120
+ ],
121
+ value: p.maxAmountIn,
122
+ })
123
+ : await walletClient.writeContract({ ...request, chain: walletClient.chain });
124
+ await wait(swapTx, "exactOutputSingle");
125
+ return { amountIn: result, swapTx };
126
+ }
@@ -0,0 +1,73 @@
1
+ import { type Address, type Hash, type Hex } from "viem";
2
+ import { type EscrowOffer } from "./payVerified.ts";
3
+ import { type VerifiedClients } from "./verified.ts";
4
+ export interface EscrowOfferInput {
5
+ chainId: number;
6
+ /** The service's address: the job's provider, paid on approval. */
7
+ provider: Address;
8
+ specUri: string;
9
+ specHash: Hex;
10
+ /** Price in ARL base units. */
11
+ budget: bigint;
12
+ committee: readonly Address[];
13
+ threshold: number;
14
+ voteWindow?: bigint;
15
+ challengeWindow?: bigint;
16
+ bond?: bigint;
17
+ expiresIn?: bigint;
18
+ /** Required on the local chain; defaults to ARL's deployment elsewhere. */
19
+ jobs?: Address;
20
+ evaluator?: Address;
21
+ }
22
+ /** The 402 body offering payment through a verified job. */
23
+ export declare function buildEscrowOffer(input: EscrowOfferInput): {
24
+ x402Version: number;
25
+ accepts: {
26
+ scheme: string;
27
+ network: string;
28
+ amount: string;
29
+ payTo: `0x${string}`;
30
+ extra: {
31
+ jobs: `0x${string}`;
32
+ evaluator: `0x${string}`;
33
+ specUri: string;
34
+ specHash: `0x${string}`;
35
+ committee: `0x${string}`[];
36
+ threshold: number;
37
+ voteWindow: string;
38
+ challengeWindow: string;
39
+ bond: string;
40
+ expiresIn: string;
41
+ };
42
+ }[];
43
+ };
44
+ /**
45
+ * Checks the job named by the `X-ARL-Job` header against the offer before any work: same chain
46
+ * and escrow, the service as provider, the offer's evaluator, budget, spec, committee and
47
+ * threshold, and the job funded. Returns the job id and the client.
48
+ */
49
+ export declare function checkFundedJob(publicClient: VerifiedClients["publicClient"], offer: EscrowOffer, header: string | null | undefined): Promise<{
50
+ jobId: bigint;
51
+ client: Address;
52
+ }>;
53
+ /** As the provider: approves the committee, so the validators can accept the job. */
54
+ export declare function approveCommittee(clients: VerifiedClients, offer: EscrowOffer, jobId: bigint): Promise<Hash>;
55
+ /** How many committee members of the job have accepted it (and locked their bond). */
56
+ export declare function acceptedCount(publicClient: VerifiedClients["publicClient"], offer: EscrowOffer, jobId: bigint): Promise<number>;
57
+ /**
58
+ * Waits until `threshold` committee members have accepted the job. Submitting before then lets
59
+ * the job end undecided (the client is refunded and the provider is not paid) if not enough
60
+ * members accept in time.
61
+ */
62
+ export declare function waitForAcceptance(publicClient: VerifiedClients["publicClient"], offer: EscrowOffer, jobId: bigint, { timeoutMs, pollMs }?: {
63
+ timeoutMs?: number;
64
+ pollMs?: number;
65
+ }): Promise<number>;
66
+ /**
67
+ * As the provider: submits the deliverable hash (the result manifest's deliverable). Refuses
68
+ * while fewer than `threshold` committee members have accepted (see `waitForAcceptance`), unless
69
+ * `requireAccepted` is false.
70
+ */
71
+ export declare function submitDeliverable(clients: VerifiedClients, offer: EscrowOffer, jobId: bigint, deliverable: Hex, { requireAccepted }?: {
72
+ requireAccepted?: boolean;
73
+ }): Promise<Hash>;