@agentbadge/circle-payments 0.1.25 → 0.1.28
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 +0 -31
- package/dist/buyer/accepts.js +0 -8
- package/dist/buyer/client.d.ts +1 -16
- package/dist/buyer/client.js +21 -59
- package/dist/cli/pay.js +5 -36
- package/dist/counterparty/policy.d.ts +1 -0
- package/dist/counterparty/policy.js +9 -0
- package/dist/counterparty/sanitize-url.js +44 -11
- package/dist/counterparty/terms.js +1 -1
- package/dist/counterparty/types.d.ts +8 -3
- package/dist/counterparty/vet402-client.d.ts +6 -1
- package/dist/counterparty/vet402-client.js +91 -21
- package/dist/gateway/deposit.d.ts +0 -9
- package/dist/gateway/deposit.js +6 -33
- package/dist/index.d.ts +0 -2
- package/dist/index.js +0 -2
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -260,37 +260,6 @@ const items = await paginateAll(async (cursor) =>
|
|
|
260
260
|
Errors: `PaymentRefusedError{field,value}` (challenge refused),
|
|
261
261
|
`CapExceededError`, `BudgetExhaustedError`, `PaymentNotAcceptedError`.
|
|
262
262
|
|
|
263
|
-
### Pre-payment risk guard (EPIC-204)
|
|
264
|
-
|
|
265
|
-
`beforePayment` vets every `payTo` advertised in the 402 BEFORE signing —
|
|
266
|
-
a `{block: reason}` becomes `PaymentRefusedError` and no money moves.
|
|
267
|
-
`createRiskGuard` wraps a payment-forensics risk API
|
|
268
|
-
(`GET /api/v1/risk/:address`); the endpoint is pluggable (ours on Arc or
|
|
269
|
-
any compatible service).
|
|
270
|
-
|
|
271
|
-
```ts
|
|
272
|
-
import { createPayingClient, createRiskGuard, viemSigner }
|
|
273
|
-
from "@agentbadge/circle-payments";
|
|
274
|
-
|
|
275
|
-
const client = createPayingClient({
|
|
276
|
-
caps,
|
|
277
|
-
signer: viemSigner(walletClient),
|
|
278
|
-
beforePayment: createRiskGuard({
|
|
279
|
-
endpoint: "https://agentbadge.xyz/api/v1/risk", // or any compatible API
|
|
280
|
-
minOrganicShare: 0.3, // organic revenue floor
|
|
281
|
-
allowNoData: true, // new sellers have to start somewhere
|
|
282
|
-
onRiskError: "allow", // "block" = fail-closed
|
|
283
|
-
timeoutMs: 2000, // never hang the 402-loop
|
|
284
|
-
}),
|
|
285
|
-
checkAllOffers: true, // default: vet every accepts[] payTo
|
|
286
|
-
});
|
|
287
|
-
```
|
|
288
|
-
|
|
289
|
-
Verdicts: `block` (or `caution` below the floor) refuses; `no_data`
|
|
290
|
-
follows `allowNoData`; endpoint errors/429s follow `onRiskError`.
|
|
291
|
-
CLI: `agentbadge pay <url> --risk-check`
|
|
292
|
-
(`AGENTBADGE_RISK_ENDPOINT` to override).
|
|
293
|
-
|
|
294
263
|
### CLI: `agentbadge pay`
|
|
295
264
|
|
|
296
265
|
```bash
|
package/dist/buyer/accepts.js
CHANGED
|
@@ -99,14 +99,6 @@ function checkEntry(e, caps, allowedNetworks, allowedSchemes, capAtomic) {
|
|
|
99
99
|
reason: `amount ${JSON.stringify(e.amount)} is not an atomic integer string`,
|
|
100
100
|
};
|
|
101
101
|
}
|
|
102
|
-
if (amount <= 0n) {
|
|
103
|
-
return {
|
|
104
|
-
ok: false,
|
|
105
|
-
field: "amount",
|
|
106
|
-
value: e.amount,
|
|
107
|
-
reason: `amount ${e.amount} is not positive — refusing zero-amount charge`,
|
|
108
|
-
};
|
|
109
|
-
}
|
|
110
102
|
if (amount > capAtomic) {
|
|
111
103
|
return {
|
|
112
104
|
ok: false,
|
package/dist/buyer/client.d.ts
CHANGED
|
@@ -1,5 +1,4 @@
|
|
|
1
1
|
import { type PaymentCaps } from "./caps.js";
|
|
2
|
-
import type { BeforePaymentFn } from "./guard.js";
|
|
3
2
|
import { type CounterpartyGateOptions } from "./counterparty.js";
|
|
4
3
|
import { type SpendTracker } from "./session.js";
|
|
5
4
|
import { type DepositResult } from "../gateway/deposit.js";
|
|
@@ -20,15 +19,6 @@ export interface BuyerSigner {
|
|
|
20
19
|
signMessage?: (args: {
|
|
21
20
|
message: string;
|
|
22
21
|
}) => Promise<`0x${string}`>;
|
|
23
|
-
readContract?: (args: {
|
|
24
|
-
address: `0x${string}`;
|
|
25
|
-
abi: unknown;
|
|
26
|
-
functionName: string;
|
|
27
|
-
args: readonly unknown[];
|
|
28
|
-
}) => Promise<unknown>;
|
|
29
|
-
waitForTransactionReceipt?: (args: {
|
|
30
|
-
hash: `0x${string}`;
|
|
31
|
-
}) => Promise<unknown>;
|
|
32
22
|
}
|
|
33
23
|
export declare function viemSigner(client: {
|
|
34
24
|
account?: {
|
|
@@ -37,8 +27,6 @@ export declare function viemSigner(client: {
|
|
|
37
27
|
signTypedData?: BuyerSigner["signTypedData"];
|
|
38
28
|
writeContract?: BuyerSigner["writeContract"];
|
|
39
29
|
signMessage?: BuyerSigner["signMessage"];
|
|
40
|
-
readContract?: BuyerSigner["readContract"];
|
|
41
|
-
waitForTransactionReceipt?: BuyerSigner["waitForTransactionReceipt"];
|
|
42
30
|
}): BuyerSigner;
|
|
43
31
|
export declare class PaymentRefusedError extends Error {
|
|
44
32
|
readonly field: string;
|
|
@@ -49,7 +37,6 @@ export interface GatewayFundingOptions {
|
|
|
49
37
|
autoDepositUsd?: string;
|
|
50
38
|
minDepositUsd?: string;
|
|
51
39
|
apiUrl?: string;
|
|
52
|
-
creditTimeoutSec?: number;
|
|
53
40
|
}
|
|
54
41
|
export interface PayingClientOptions {
|
|
55
42
|
caps: PaymentCaps;
|
|
@@ -61,10 +48,8 @@ export interface PayingClientOptions {
|
|
|
61
48
|
scheme?: string;
|
|
62
49
|
resource?: string;
|
|
63
50
|
}) => void;
|
|
64
|
-
gateway?: GatewayFundingOptions;
|
|
65
|
-
beforePayment?: BeforePaymentFn;
|
|
66
|
-
checkAllOffers?: boolean;
|
|
67
51
|
counterparty?: CounterpartyGateOptions;
|
|
52
|
+
gateway?: GatewayFundingOptions;
|
|
68
53
|
}
|
|
69
54
|
export interface PayingClient {
|
|
70
55
|
request(url: string, init?: RequestInit): Promise<Response>;
|
package/dist/buyer/client.js
CHANGED
|
@@ -2,8 +2,8 @@ import { BatchEvmScheme } from "@circle-fin/x402-batching/client";
|
|
|
2
2
|
import { getChain } from "../chains.js";
|
|
3
3
|
import { decode402 } from "../identity/verify-passport.js";
|
|
4
4
|
import { signPayerChallenge } from "../payer-bind.js";
|
|
5
|
-
import { assertCaps, PaymentNotAcceptedError,
|
|
6
|
-
import {
|
|
5
|
+
import { assertCaps, PaymentNotAcceptedError, } from "./caps.js";
|
|
6
|
+
import { validateAccepts } from "./accepts.js";
|
|
7
7
|
import { applyCounterpartyGate, } from "./counterparty.js";
|
|
8
8
|
import { createCounterpartyPolicy } from "../counterparty/policy.js";
|
|
9
9
|
import { createSpendTracker } from "./session.js";
|
|
@@ -19,8 +19,6 @@ export function viemSigner(client) {
|
|
|
19
19
|
signTypedData: client.signTypedData?.bind(client),
|
|
20
20
|
writeContract: client.writeContract?.bind(client),
|
|
21
21
|
signMessage: client.signMessage?.bind(client),
|
|
22
|
-
readContract: client.readContract?.bind(client),
|
|
23
|
-
waitForTransactionReceipt: client.waitForTransactionReceipt?.bind(client),
|
|
24
22
|
};
|
|
25
23
|
}
|
|
26
24
|
export class PaymentRefusedError extends Error {
|
|
@@ -130,31 +128,25 @@ async function broadcastTransferAuth(signer, req, signature, authorization) {
|
|
|
130
128
|
],
|
|
131
129
|
});
|
|
132
130
|
}
|
|
133
|
-
async function signGatewayBatch(signer, req) {
|
|
134
|
-
if (!signer.signTypedData) {
|
|
135
|
-
throw new PaymentRefusedError("signer", undefined, "signer lacks signTypedData — cannot sign gateway-batch authorization");
|
|
136
|
-
}
|
|
137
|
-
const scheme = new BatchEvmScheme({
|
|
138
|
-
address: signer.address,
|
|
139
|
-
signTypedData: signer.signTypedData.bind(signer),
|
|
140
|
-
});
|
|
141
|
-
const { payload } = await scheme.createPaymentPayload(2, req);
|
|
142
|
-
return {
|
|
143
|
-
payload: payload,
|
|
144
|
-
committed: false,
|
|
145
|
-
};
|
|
146
|
-
}
|
|
147
131
|
async function buildPayment(signer, req) {
|
|
148
132
|
switch (req.scheme) {
|
|
149
133
|
case "exact": {
|
|
150
|
-
if (isGatewayBatch(req)) {
|
|
151
|
-
return signGatewayBatch(signer, req);
|
|
152
|
-
}
|
|
153
134
|
const { signature, authorization } = await signTransferAuth(signer, req);
|
|
154
135
|
return { payload: { signature, authorization }, committed: false };
|
|
155
136
|
}
|
|
156
137
|
case "gateway-batch": {
|
|
157
|
-
|
|
138
|
+
if (!signer.signTypedData) {
|
|
139
|
+
throw new PaymentRefusedError("signer", undefined, "signer lacks signTypedData — cannot sign gateway-batch authorization");
|
|
140
|
+
}
|
|
141
|
+
const scheme = new BatchEvmScheme({
|
|
142
|
+
address: signer.address,
|
|
143
|
+
signTypedData: signer.signTypedData.bind(signer),
|
|
144
|
+
});
|
|
145
|
+
const { payload } = await scheme.createPaymentPayload(2, req);
|
|
146
|
+
return {
|
|
147
|
+
payload: payload,
|
|
148
|
+
committed: false,
|
|
149
|
+
};
|
|
158
150
|
}
|
|
159
151
|
case "eip3009-client-broadcast": {
|
|
160
152
|
const { signature, authorization } = await signTransferAuth(signer, req);
|
|
@@ -190,17 +182,18 @@ export function createPayingClient(opts) {
|
|
|
190
182
|
if (!g?.autoDepositUsd)
|
|
191
183
|
return;
|
|
192
184
|
const chain = getChain(req.network);
|
|
193
|
-
if (!chain
|
|
185
|
+
if (!chain?.domain === undefined || !chain)
|
|
194
186
|
return;
|
|
195
|
-
const
|
|
187
|
+
const info = await gatewayBalance({
|
|
196
188
|
depositor: signer.address,
|
|
197
189
|
chain,
|
|
198
190
|
...(g.apiUrl ? { apiUrl: g.apiUrl } : {}),
|
|
199
191
|
fetchImpl,
|
|
200
192
|
});
|
|
201
|
-
|
|
193
|
+
if (!info)
|
|
194
|
+
return;
|
|
202
195
|
const need = BigInt(req.amount);
|
|
203
|
-
const available = BigInt(
|
|
196
|
+
const available = BigInt(info.available ?? "0");
|
|
204
197
|
if (available >= need)
|
|
205
198
|
return;
|
|
206
199
|
if (!signer.writeContract) {
|
|
@@ -215,16 +208,6 @@ export function createPayingClient(opts) {
|
|
|
215
208
|
amountUsd: g.autoDepositUsd,
|
|
216
209
|
});
|
|
217
210
|
deposits.push(result);
|
|
218
|
-
const creditTimeoutSec = g.creditTimeoutSec ?? 120;
|
|
219
|
-
const deadline = Date.now() + creditTimeoutSec * 1000;
|
|
220
|
-
while (Date.now() < deadline) {
|
|
221
|
-
const next = await readBalance();
|
|
222
|
-
if (next && BigInt(usdToAtomic(next.available ?? "0")) >= need) {
|
|
223
|
-
return;
|
|
224
|
-
}
|
|
225
|
-
await new Promise((r) => setTimeout(r, 3000));
|
|
226
|
-
}
|
|
227
|
-
throw new PaymentRefusedError("gatewayBalance", info?.available ?? null, `gateway deposit ${result.txHash} not credited within ${creditTimeoutSec}s — retry later`);
|
|
228
211
|
}
|
|
229
212
|
async function request(url, init = {}) {
|
|
230
213
|
const first = await fetchImpl(url, init);
|
|
@@ -238,22 +221,6 @@ export function createPayingClient(opts) {
|
|
|
238
221
|
throw new PaymentRefusedError(verdict.field, verdict.value, verdict.reason);
|
|
239
222
|
}
|
|
240
223
|
const req = verdict.requirements;
|
|
241
|
-
if (opts.beforePayment) {
|
|
242
|
-
const targets = new Map();
|
|
243
|
-
if (opts.checkAllOffers !== false && pr) {
|
|
244
|
-
for (const a of pr.accepts ?? []) {
|
|
245
|
-
if (a?.payTo)
|
|
246
|
-
targets.set(`${a.payTo}:${a.network}`, { payTo: a.payTo, accept: a });
|
|
247
|
-
}
|
|
248
|
-
}
|
|
249
|
-
targets.set(`${req.payTo}:${req.network}`, { payTo: req.payTo, accept: req });
|
|
250
|
-
for (const { payTo, accept } of targets.values()) {
|
|
251
|
-
const decision = await opts.beforePayment(payTo, accept);
|
|
252
|
-
if (decision !== "allow") {
|
|
253
|
-
throw new PaymentRefusedError("payTo", payTo, decision.block);
|
|
254
|
-
}
|
|
255
|
-
}
|
|
256
|
-
}
|
|
257
224
|
if (opts.counterparty) {
|
|
258
225
|
await applyCounterpartyGate({
|
|
259
226
|
opts: opts.counterparty,
|
|
@@ -263,7 +230,7 @@ export function createPayingClient(opts) {
|
|
|
263
230
|
});
|
|
264
231
|
}
|
|
265
232
|
tracker.tryReserve(req.amount);
|
|
266
|
-
if (req.scheme === "gateway-batch"
|
|
233
|
+
if (req.scheme === "gateway-batch") {
|
|
267
234
|
await ensureGatewayFunds(req);
|
|
268
235
|
}
|
|
269
236
|
const signed = await buildPayment(signer, req);
|
|
@@ -271,12 +238,7 @@ export function createPayingClient(opts) {
|
|
|
271
238
|
recordSpend(req, url);
|
|
272
239
|
}
|
|
273
240
|
const headers = new Headers(init.headers);
|
|
274
|
-
headers.set("payment-signature", b64encode({
|
|
275
|
-
x402Version: 2,
|
|
276
|
-
accepted: req,
|
|
277
|
-
...(pr?.resource ? { resource: pr.resource } : {}),
|
|
278
|
-
payload: signed.payload,
|
|
279
|
-
}));
|
|
241
|
+
headers.set("payment-signature", b64encode({ x402Version: 2, accepted: req, payload: signed.payload }));
|
|
280
242
|
if (req.extra?.payerBinding && signed.txHash && signer.signMessage) {
|
|
281
243
|
const timestamp = Math.floor(Date.now() / 1000);
|
|
282
244
|
const msgSigner = signer;
|
package/dist/cli/pay.js
CHANGED
|
@@ -4,10 +4,8 @@ import { privateKeyToAccount } from "viem/accounts";
|
|
|
4
4
|
import { getChain } from "../chains.js";
|
|
5
5
|
import { decode402 } from "../identity/verify-passport.js";
|
|
6
6
|
import { assertCaps, BudgetExhaustedError, CapExceededError, PaymentNotAcceptedError, } from "../buyer/caps.js";
|
|
7
|
-
import { atomicToUsd,
|
|
8
|
-
import { usdToAtomic } from "../buyer/caps.js";
|
|
7
|
+
import { atomicToUsd, validateAccepts, } from "../buyer/accepts.js";
|
|
9
8
|
import { createPayingClient, PaymentRefusedError, } from "../buyer/client.js";
|
|
10
|
-
import { createRiskGuard } from "../buyer/risk-guard.js";
|
|
11
9
|
import { createCounterpartyPolicy } from "../counterparty/policy.js";
|
|
12
10
|
import { Vet402Client, vet402ClientOptionsFromEnv, } from "../counterparty/vet402-client.js";
|
|
13
11
|
import { gatewayBalance } from "../gateway/deposit.js";
|
|
@@ -25,8 +23,6 @@ Optional:
|
|
|
25
23
|
--body <json> request body
|
|
26
24
|
--network <caip2> restrict to one network (e.g. eip155:5042002)
|
|
27
25
|
--auto-deposit <usd> auto top-up Gateway balance when short
|
|
28
|
-
--risk-check vet every payTo via risk API before signing
|
|
29
|
-
(AGENTBADGE_RISK_ENDPOINT to override)
|
|
30
26
|
--skip-counterparty-check
|
|
31
27
|
skip the vet402 counterparty check (default on;
|
|
32
28
|
COUNTERPARTY_CHECK_MODE=off|shadow|enforce,
|
|
@@ -39,7 +35,7 @@ Secrets:
|
|
|
39
35
|
|
|
40
36
|
Exit codes: 0 ok · 2 refusal/cap/budget/usage · 3 transport`;
|
|
41
37
|
function parseArgs(argv) {
|
|
42
|
-
const args = { method: "GET", printOnly: false, help: false,
|
|
38
|
+
const args = { method: "GET", printOnly: false, help: false, skipCounterpartyCheck: false };
|
|
43
39
|
const takeValue = (i, flag) => {
|
|
44
40
|
const v = argv[i + 1];
|
|
45
41
|
if (v === undefined || v.startsWith("--")) {
|
|
@@ -70,9 +66,6 @@ function parseArgs(argv) {
|
|
|
70
66
|
case "--auto-deposit":
|
|
71
67
|
args.autoDeposit = takeValue(i++, a);
|
|
72
68
|
break;
|
|
73
|
-
case "--risk-check":
|
|
74
|
-
args.riskCheck = true;
|
|
75
|
-
break;
|
|
76
69
|
case "--skip-counterparty-check":
|
|
77
70
|
args.skipCounterpartyCheck = true;
|
|
78
71
|
break;
|
|
@@ -203,30 +196,22 @@ export async function runPay(argv, env = process.env, io = {}) {
|
|
|
203
196
|
return EXIT_REFUSED;
|
|
204
197
|
}
|
|
205
198
|
const account = privateKeyToAccount((key.startsWith("0x") ? key : `0x${key}`));
|
|
206
|
-
if (
|
|
207
|
-
!args.autoDeposit &&
|
|
208
|
-
chain) {
|
|
199
|
+
if (req.scheme === "gateway-batch" && !args.autoDeposit && chain) {
|
|
209
200
|
const gw = await gatewayBalance({
|
|
210
201
|
depositor: account.address,
|
|
211
202
|
chain,
|
|
212
203
|
fetchImpl,
|
|
213
204
|
});
|
|
214
205
|
const need = BigInt(req.amount);
|
|
215
|
-
if (gw && BigInt(
|
|
206
|
+
if (gw && BigInt(gw.available ?? "0") < need) {
|
|
216
207
|
const eoa = await eoaUsdcBalance(chain, account.address);
|
|
217
208
|
const suggestion = eoa !== undefined && eoa >= need
|
|
218
|
-
? `
|
|
209
|
+
? `run: agentbadge gateway deposit --amount ${verdict.priceUsd} --network ${req.network}`
|
|
219
210
|
: `deposit USDC to GatewayWallet ${chain.gatewayWallet} on ${chain.name}`;
|
|
220
211
|
err(`gateway balance ${gw.available} < price ${req.amount} — ${suggestion}`);
|
|
221
212
|
return EXIT_REFUSED;
|
|
222
213
|
}
|
|
223
214
|
}
|
|
224
|
-
const publicClient = chain
|
|
225
|
-
? createPublicClient({
|
|
226
|
-
chain: toViemChain(chain),
|
|
227
|
-
transport: http(chain.rpcUrl),
|
|
228
|
-
})
|
|
229
|
-
: undefined;
|
|
230
215
|
const signer = {
|
|
231
216
|
address: account.address,
|
|
232
217
|
signTypedData: (a) => account.signTypedData(a),
|
|
@@ -242,12 +227,6 @@ export async function runPay(argv, env = process.env, io = {}) {
|
|
|
242
227
|
});
|
|
243
228
|
return wc.writeContract(wcArgs);
|
|
244
229
|
},
|
|
245
|
-
...(publicClient
|
|
246
|
-
? {
|
|
247
|
-
readContract: (rcArgs) => publicClient.readContract(rcArgs),
|
|
248
|
-
waitForTransactionReceipt: (rArgs) => publicClient.waitForTransactionReceipt(rArgs),
|
|
249
|
-
}
|
|
250
|
-
: {}),
|
|
251
230
|
};
|
|
252
231
|
let counterparty;
|
|
253
232
|
if (args.skipCounterpartyCheck) {
|
|
@@ -285,16 +264,6 @@ export async function runPay(argv, env = process.env, io = {}) {
|
|
|
285
264
|
...(args.autoDeposit
|
|
286
265
|
? { gateway: { autoDepositUsd: args.autoDeposit } }
|
|
287
266
|
: {}),
|
|
288
|
-
...(args.riskCheck
|
|
289
|
-
? {
|
|
290
|
-
beforePayment: createRiskGuard({
|
|
291
|
-
...(env.AGENTBADGE_RISK_ENDPOINT
|
|
292
|
-
? { endpoint: env.AGENTBADGE_RISK_ENDPOINT }
|
|
293
|
-
: {}),
|
|
294
|
-
fetchImpl,
|
|
295
|
-
}),
|
|
296
|
-
}
|
|
297
|
-
: {}),
|
|
298
267
|
...(counterparty ? { counterparty } : {}),
|
|
299
268
|
});
|
|
300
269
|
try {
|
|
@@ -3,6 +3,12 @@ const UNMEASURED = hold("counterparty_unmeasured", "counterparty_unmeasured");
|
|
|
3
3
|
const TERMS_UNCOMPARABLE = hold("terms_uncomparable", "counterparty_unmeasured");
|
|
4
4
|
const WARN = hold("counterparty_warn", "counterparty_warn");
|
|
5
5
|
const TERMS_DENY = { action: "deny", reasonCode: "terms_mismatch" };
|
|
6
|
+
const DEGRADED = {
|
|
7
|
+
action: "hold",
|
|
8
|
+
reasonCode: "counterparty_degraded",
|
|
9
|
+
holdHint: "counterparty_unmeasured",
|
|
10
|
+
};
|
|
11
|
+
export const EVIDENCE_STALE_SECONDS = 30 * 86_400;
|
|
6
12
|
const BLOCK_DENY = { action: "deny", reasonCode: "counterparty_blocked" };
|
|
7
13
|
const UNAVAILABLE = {
|
|
8
14
|
action: "unavailable",
|
|
@@ -25,6 +31,8 @@ function fromVerdict(a, termsMatch) {
|
|
|
25
31
|
const terms = fromTerms(termsMatch);
|
|
26
32
|
if (terms)
|
|
27
33
|
return terms;
|
|
34
|
+
if (a.degraded || (a.evidenceAgeSeconds ?? 0) > EVIDENCE_STALE_SECONDS)
|
|
35
|
+
return DEGRADED;
|
|
28
36
|
if (a.verdict === "WARN")
|
|
29
37
|
return WARN;
|
|
30
38
|
if (termsMatch.result === "unmeasured")
|
|
@@ -37,6 +45,7 @@ class CounterpartyPolicyImpl {
|
|
|
37
45
|
switch (assessment.kind) {
|
|
38
46
|
case "unavailable":
|
|
39
47
|
return UNAVAILABLE;
|
|
48
|
+
case "rejected":
|
|
40
49
|
case "not_in_catalog":
|
|
41
50
|
case "privacy_unmeasurable":
|
|
42
51
|
return UNMEASURED;
|
|
@@ -1,6 +1,34 @@
|
|
|
1
1
|
const JWT_RE = /^eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/;
|
|
2
2
|
const HEX_LIKE_RE = /^(?:0x)?[0-9a-f]{32,}$/i;
|
|
3
3
|
const B64URL_RE = /^[A-Za-z0-9_-]+$/;
|
|
4
|
+
const B64_RE = /^[A-Za-z0-9+/]+={0,2}$/;
|
|
5
|
+
const TOKEN_PREFIX_RE = /^(?:sk[-_]|xox[abprs]?[-_]|gh[opsur]_|github_pat_|AKIA[0-9A-Z]{16}|AIza|ya29\.|npm_[A-Za-z0-9]{30,}|dop_v1_|eyJ[A-Za-z0-9_-]{8,}\.)/;
|
|
6
|
+
const PARAM_NAME_RE = /(?:^|;)\s*(?:jsessionid|key|token|sig|signature|auth|secret|passwd|password|session|sid|api[-_]?key|access[-_]?token|bearer)\s*=/i;
|
|
7
|
+
function looksSecretValue(s) {
|
|
8
|
+
if (s === "")
|
|
9
|
+
return false;
|
|
10
|
+
if (JWT_RE.test(s))
|
|
11
|
+
return true;
|
|
12
|
+
if (TOKEN_PREFIX_RE.test(s))
|
|
13
|
+
return true;
|
|
14
|
+
if (HEX_LIKE_RE.test(s))
|
|
15
|
+
return true;
|
|
16
|
+
if (s.length >= 32) {
|
|
17
|
+
if (B64URL_RE.test(s) &&
|
|
18
|
+
/\d/.test(s) &&
|
|
19
|
+
(/[A-Z]/.test(s) || /^[a-z0-9]+$/.test(s))) {
|
|
20
|
+
return true;
|
|
21
|
+
}
|
|
22
|
+
if (B64_RE.test(s) && /[a-zA-Z]/.test(s) && /\d/.test(s))
|
|
23
|
+
return true;
|
|
24
|
+
const parts = s.split(".");
|
|
25
|
+
if (parts.length >= 3 &&
|
|
26
|
+
parts.every((p) => p.length >= 8 && B64URL_RE.test(p))) {
|
|
27
|
+
return true;
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
return false;
|
|
31
|
+
}
|
|
4
32
|
function looksSecretSegment(segment) {
|
|
5
33
|
if (segment === "")
|
|
6
34
|
return false;
|
|
@@ -10,20 +38,18 @@ function looksSecretSegment(segment) {
|
|
|
10
38
|
}
|
|
11
39
|
catch {
|
|
12
40
|
}
|
|
13
|
-
if (
|
|
14
|
-
return true;
|
|
15
|
-
if (HEX_LIKE_RE.test(s))
|
|
16
|
-
return true;
|
|
17
|
-
if (s.length >= 32 && B64URL_RE.test(s) && /[A-Z]/.test(s) && /\d/.test(s)) {
|
|
41
|
+
if (PARAM_NAME_RE.test(s) || s.includes(";"))
|
|
18
42
|
return true;
|
|
43
|
+
return looksSecretValue(s);
|
|
44
|
+
}
|
|
45
|
+
function looksSecretHostname(hostname) {
|
|
46
|
+
let h = hostname;
|
|
47
|
+
try {
|
|
48
|
+
h = decodeURIComponent(hostname);
|
|
19
49
|
}
|
|
20
|
-
|
|
21
|
-
if (parts.length >= 3 &&
|
|
22
|
-
s.length >= 30 &&
|
|
23
|
-
parts.every((p) => p.length >= 8 && B64URL_RE.test(p))) {
|
|
24
|
-
return true;
|
|
50
|
+
catch {
|
|
25
51
|
}
|
|
26
|
-
return
|
|
52
|
+
return h.split(".").some((label) => looksSecretValue(label));
|
|
27
53
|
}
|
|
28
54
|
export function sanitizeUrlForCheck(raw) {
|
|
29
55
|
let u;
|
|
@@ -45,6 +71,13 @@ export function sanitizeUrlForCheck(raw) {
|
|
|
45
71
|
if (raw.includes("#")) {
|
|
46
72
|
return { ok: false, block: "fragment" };
|
|
47
73
|
}
|
|
74
|
+
if (looksSecretHostname(u.hostname)) {
|
|
75
|
+
return {
|
|
76
|
+
ok: false,
|
|
77
|
+
block: "secret_hostname_label",
|
|
78
|
+
segmentLength: u.hostname.length,
|
|
79
|
+
};
|
|
80
|
+
}
|
|
48
81
|
for (const seg of u.pathname.split("/")) {
|
|
49
82
|
if (looksSecretSegment(seg)) {
|
|
50
83
|
return { ok: false, block: "secret_path_segment", segmentLength: seg.length };
|
|
@@ -62,7 +62,7 @@ export function normalizeAddress(addr, network) {
|
|
|
62
62
|
}
|
|
63
63
|
export function normalizeAmount(amount) {
|
|
64
64
|
const t = amount.trim();
|
|
65
|
-
if (!/^\d
|
|
65
|
+
if (!/^\d{1,78}$/.test(t)) {
|
|
66
66
|
throw new TermsUncomparableError(`amount ${JSON.stringify(amount)} is not an atomic integer string`);
|
|
67
67
|
}
|
|
68
68
|
return BigInt(t).toString();
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
export type Vet402Verdict = "ALLOW" | "WARN" | "BLOCK";
|
|
2
2
|
export type CounterpartyVerdict = "allow" | "hold" | "deny" | "unavailable";
|
|
3
|
-
export type CounterpartyReasonCode = "allowed" | "terms_mismatch" | "terms_uncomparable" | "counterparty_blocked" | "counterparty_warn" | "counterparty_unmeasured" | "counterparty_unavailable";
|
|
3
|
+
export type CounterpartyReasonCode = "allowed" | "terms_mismatch" | "terms_uncomparable" | "counterparty_blocked" | "counterparty_warn" | "counterparty_unmeasured" | "counterparty_degraded" | "counterparty_unavailable";
|
|
4
4
|
export type ApprovalReason = "amount_threshold" | "counterparty_warn" | "counterparty_unmeasured";
|
|
5
5
|
export type CounterpartyCheckMode = "off" | "shadow" | "enforce";
|
|
6
6
|
export interface DealTerms {
|
|
@@ -43,7 +43,11 @@ export interface Vet402UnavailableAssessment extends AssessmentBase {
|
|
|
43
43
|
kind: "unavailable";
|
|
44
44
|
failure: Vet402UnavailableFailure;
|
|
45
45
|
}
|
|
46
|
-
export
|
|
46
|
+
export interface Vet402RejectedAssessment extends AssessmentBase {
|
|
47
|
+
kind: "rejected";
|
|
48
|
+
httpStatus?: number;
|
|
49
|
+
}
|
|
50
|
+
export type Vet402Assessment = Vet402VerdictAssessment | Vet402NotInCatalogAssessment | Vet402RejectedAssessment | Vet402PrivacyUnmeasurableAssessment | Vet402UnavailableAssessment;
|
|
47
51
|
export type TermsMatchResult = "match" | "mismatch" | "uncomparable" | "unmeasured";
|
|
48
52
|
export interface TermsFieldDiff {
|
|
49
53
|
verified: string;
|
|
@@ -62,6 +66,7 @@ export interface PaymentDecision {
|
|
|
62
66
|
export interface CounterpartyCheckInput {
|
|
63
67
|
resourceUrl: string;
|
|
64
68
|
signal?: AbortSignal;
|
|
69
|
+
wallet?: string;
|
|
65
70
|
}
|
|
66
71
|
export interface CounterpartyChecker {
|
|
67
72
|
check(input: CounterpartyCheckInput): Promise<Vet402Assessment>;
|
|
@@ -72,7 +77,7 @@ export interface CounterpartyPolicy {
|
|
|
72
77
|
termsMatch: TermsMatch;
|
|
73
78
|
}): PaymentDecision;
|
|
74
79
|
}
|
|
75
|
-
export type SanitizeUrlBlock = "unparseable" | "non_https_scheme" | "credentials" | "query" | "fragment" | "secret_path_segment";
|
|
80
|
+
export type SanitizeUrlBlock = "unparseable" | "non_https_scheme" | "credentials" | "query" | "fragment" | "secret_path_segment" | "secret_hostname_label";
|
|
76
81
|
export type SanitizeUrlResult = {
|
|
77
82
|
ok: true;
|
|
78
83
|
url: string;
|
|
@@ -8,6 +8,7 @@ export interface Vet402ClientOptions {
|
|
|
8
8
|
decisionTtlMs?: number;
|
|
9
9
|
blockTtlMs?: number;
|
|
10
10
|
maxRpm?: number;
|
|
11
|
+
perWalletRpm?: number;
|
|
11
12
|
connectTimeoutMs?: number;
|
|
12
13
|
totalTimeoutMs?: number;
|
|
13
14
|
resolveCacheSize?: number;
|
|
@@ -19,7 +20,7 @@ export interface CounterpartyMetricsHooks {
|
|
|
19
20
|
onCache?(result: "hit" | "miss"): void;
|
|
20
21
|
onRateLimited?(endpoint: "resolve" | "decision"): void;
|
|
21
22
|
}
|
|
22
|
-
export declare function vet402ClientOptionsFromEnv(env: Record<string, string | undefined>): Pick<Vet402ClientOptions, "decisionTtlMs" | "blockTtlMs" | "maxRpm" | "connectTimeoutMs" | "totalTimeoutMs">;
|
|
23
|
+
export declare function vet402ClientOptionsFromEnv(env: Record<string, string | undefined>): Pick<Vet402ClientOptions, "decisionTtlMs" | "blockTtlMs" | "maxRpm" | "perWalletRpm" | "connectTimeoutMs" | "totalTimeoutMs">;
|
|
23
24
|
export declare class Vet402Client implements CounterpartyChecker {
|
|
24
25
|
private baseUrl;
|
|
25
26
|
private fetch;
|
|
@@ -34,7 +35,10 @@ export declare class Vet402Client implements CounterpartyChecker {
|
|
|
34
35
|
private decisionCache;
|
|
35
36
|
private inflight;
|
|
36
37
|
private bucket;
|
|
38
|
+
private perWalletRpm;
|
|
39
|
+
private walletBuckets;
|
|
37
40
|
constructor(opts?: Vet402ClientOptions);
|
|
41
|
+
private walletBucketFor;
|
|
38
42
|
check(input: CounterpartyCheckInput): Promise<Vet402Assessment>;
|
|
39
43
|
private runCheck;
|
|
40
44
|
private emitCheck;
|
|
@@ -42,6 +46,7 @@ export declare class Vet402Client implements CounterpartyChecker {
|
|
|
42
46
|
private fetchDecision;
|
|
43
47
|
private parseVerifiedTerms;
|
|
44
48
|
private unavailable;
|
|
49
|
+
private rejected;
|
|
45
50
|
private iso;
|
|
46
51
|
private outbound;
|
|
47
52
|
}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { sanitizeUrlForCheck } from "./sanitize-url.js";
|
|
2
|
+
import { normalizeNetwork } from "./terms.js";
|
|
2
3
|
export function vet402ClientOptionsFromEnv(env) {
|
|
3
4
|
const int = (k) => {
|
|
4
5
|
const v = env[k];
|
|
@@ -11,6 +12,7 @@ export function vet402ClientOptionsFromEnv(env) {
|
|
|
11
12
|
decisionTtlMs: int("COUNTERPARTY_DECISION_TTL_MS"),
|
|
12
13
|
blockTtlMs: int("COUNTERPARTY_BLOCK_TTL_MS"),
|
|
13
14
|
maxRpm: int("COUNTERPARTY_MAX_RPM"),
|
|
15
|
+
perWalletRpm: int("COUNTERPARTY_WALLET_RPM"),
|
|
14
16
|
connectTimeoutMs: int("COUNTERPARTY_CONNECT_TIMEOUT_MS"),
|
|
15
17
|
totalTimeoutMs: int("COUNTERPARTY_TOTAL_TIMEOUT_MS"),
|
|
16
18
|
};
|
|
@@ -66,6 +68,13 @@ class TokenBucket {
|
|
|
66
68
|
const rate = this.capacity / 60_000;
|
|
67
69
|
return { ok: false, waitMs: Math.ceil((1 - this.tokens) / rate) };
|
|
68
70
|
}
|
|
71
|
+
peekWaitMs() {
|
|
72
|
+
this.refill();
|
|
73
|
+
if (this.tokens >= 1)
|
|
74
|
+
return 0;
|
|
75
|
+
const rate = this.capacity / 60_000;
|
|
76
|
+
return Math.ceil((1 - this.tokens) / rate);
|
|
77
|
+
}
|
|
69
78
|
}
|
|
70
79
|
const LEDGER_UNIT_FACTOR = {
|
|
71
80
|
"eip155:56": 10n ** 12n,
|
|
@@ -87,6 +96,8 @@ export class Vet402Client {
|
|
|
87
96
|
decisionCache;
|
|
88
97
|
inflight = new Map();
|
|
89
98
|
bucket;
|
|
99
|
+
perWalletRpm;
|
|
100
|
+
walletBuckets;
|
|
90
101
|
constructor(opts = {}) {
|
|
91
102
|
this.baseUrl = (opts.baseUrl ?? "https://vet402.com").replace(/\/+$/, "");
|
|
92
103
|
this.fetch = opts.fetchImpl ?? fetch;
|
|
@@ -94,13 +105,26 @@ export class Vet402Client {
|
|
|
94
105
|
this.sleep =
|
|
95
106
|
opts.sleepImpl ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
|
|
96
107
|
this.decisionTtlMs = opts.decisionTtlMs ?? 5 * 60_000;
|
|
97
|
-
this.blockTtlMs = opts.blockTtlMs ??
|
|
108
|
+
this.blockTtlMs = Math.max(opts.blockTtlMs ?? this.decisionTtlMs, this.decisionTtlMs);
|
|
98
109
|
this.connectTimeoutMs = opts.connectTimeoutMs ?? 2_000;
|
|
99
110
|
this.totalTimeoutMs = opts.totalTimeoutMs ?? 8_000;
|
|
100
111
|
this.metrics = opts.metrics;
|
|
101
112
|
this.resolveCache = new LruCache(opts.resolveCacheSize ?? 1024);
|
|
102
113
|
this.decisionCache = new LruCache(opts.decisionCacheSize ?? 1024);
|
|
103
114
|
this.bucket = new TokenBucket(Math.max(1, opts.maxRpm ?? 11), this.now);
|
|
115
|
+
this.perWalletRpm = Math.max(1, opts.perWalletRpm ?? 4);
|
|
116
|
+
this.walletBuckets = new LruCache(opts.decisionCacheSize ?? 1024);
|
|
117
|
+
}
|
|
118
|
+
walletBucketFor(wallet) {
|
|
119
|
+
if (!wallet)
|
|
120
|
+
return undefined;
|
|
121
|
+
const key = wallet.toLowerCase();
|
|
122
|
+
let b = this.walletBuckets.get(key);
|
|
123
|
+
if (!b) {
|
|
124
|
+
b = new TokenBucket(this.perWalletRpm, this.now);
|
|
125
|
+
this.walletBuckets.set(key, b);
|
|
126
|
+
}
|
|
127
|
+
return b;
|
|
104
128
|
}
|
|
105
129
|
async check(input) {
|
|
106
130
|
const t0 = this.now();
|
|
@@ -121,16 +145,16 @@ export class Vet402Client {
|
|
|
121
145
|
this.emitCheck(a, t0, true);
|
|
122
146
|
return a;
|
|
123
147
|
}
|
|
124
|
-
const p = this.runCheck(s.url, t0, input.signal)
|
|
148
|
+
const p = this.runCheck(s.url, t0, input.signal, input.wallet)
|
|
125
149
|
.finally(() => this.inflight.delete(key));
|
|
126
150
|
this.inflight.set(key, p);
|
|
127
151
|
return p;
|
|
128
152
|
}
|
|
129
|
-
async runCheck(url, t0, callerSignal) {
|
|
153
|
+
async runCheck(url, t0, callerSignal, wallet) {
|
|
130
154
|
const deadline = t0 + this.totalTimeoutMs;
|
|
131
155
|
let rereolved = false;
|
|
132
156
|
for (;;) {
|
|
133
|
-
const resolved = await this.resolveResourceId(url, deadline, callerSignal);
|
|
157
|
+
const resolved = await this.resolveResourceId(url, deadline, callerSignal, wallet);
|
|
134
158
|
if (resolved.assessment) {
|
|
135
159
|
this.emitCheck(resolved.assessment, t0, resolved.cacheHit === true);
|
|
136
160
|
return resolved.assessment;
|
|
@@ -142,7 +166,7 @@ export class Vet402Client {
|
|
|
142
166
|
this.emitCheck(a, t0, true);
|
|
143
167
|
return a;
|
|
144
168
|
}
|
|
145
|
-
const out = await this.fetchDecision(resourceId, url, deadline, callerSignal);
|
|
169
|
+
const out = await this.fetchDecision(resourceId, url, deadline, callerSignal, wallet);
|
|
146
170
|
if (out.assessment) {
|
|
147
171
|
if (out.assessment.kind === "unavailable" &&
|
|
148
172
|
out.assessment.failure === "invalid_response" &&
|
|
@@ -178,7 +202,7 @@ export class Vet402Client {
|
|
|
178
202
|
this.metrics?.onCheck?.(outcome, this.now() - t0);
|
|
179
203
|
this.metrics?.onCache?.(cacheHit ? "hit" : "miss");
|
|
180
204
|
}
|
|
181
|
-
async resolveResourceId(url, deadline, callerSignal) {
|
|
205
|
+
async resolveResourceId(url, deadline, callerSignal, wallet) {
|
|
182
206
|
const cached = this.resolveCache.get(url);
|
|
183
207
|
if (cached && cached.expiresAt > this.now()) {
|
|
184
208
|
if (cached.notInCatalog) {
|
|
@@ -189,11 +213,17 @@ export class Vet402Client {
|
|
|
189
213
|
}
|
|
190
214
|
return { resourceId: cached.resourceId, cacheHit: true };
|
|
191
215
|
}
|
|
192
|
-
const r = await this.outbound(`${this.baseUrl}/api/v1/resolve?q=${encodeURIComponent(url)}`, "resolve", deadline, callerSignal);
|
|
216
|
+
const r = await this.outbound(`${this.baseUrl}/api/v1/resolve?q=${encodeURIComponent(url)}`, "resolve", deadline, callerSignal, wallet);
|
|
193
217
|
if (r.failure)
|
|
194
218
|
return { assessment: this.unavailable(r.failure) };
|
|
195
|
-
if (r.status !== 200)
|
|
196
|
-
|
|
219
|
+
if (r.status !== 200) {
|
|
220
|
+
const st = r.status ?? 0;
|
|
221
|
+
return {
|
|
222
|
+
assessment: st >= 400 && st < 500
|
|
223
|
+
? this.rejected(st)
|
|
224
|
+
: this.unavailable("invalid_response"),
|
|
225
|
+
};
|
|
226
|
+
}
|
|
197
227
|
const body = r.body;
|
|
198
228
|
if (body?.not_found?.reason === "not_in_catalog") {
|
|
199
229
|
this.resolveCache.set(url, {
|
|
@@ -209,9 +239,9 @@ export class Vet402Client {
|
|
|
209
239
|
}
|
|
210
240
|
return { assessment: this.unavailable("invalid_response") };
|
|
211
241
|
}
|
|
212
|
-
async fetchDecision(resourceId, url, deadline, callerSignal) {
|
|
242
|
+
async fetchDecision(resourceId, url, deadline, callerSignal, wallet) {
|
|
213
243
|
const qs = new URLSearchParams({ role: "payer", url });
|
|
214
|
-
const r = await this.outbound(`${this.baseUrl}/api/v1/resources/${resourceId}/decision?${qs}`, "decision", deadline, callerSignal);
|
|
244
|
+
const r = await this.outbound(`${this.baseUrl}/api/v1/resources/${resourceId}/decision?${qs}`, "decision", deadline, callerSignal, wallet);
|
|
215
245
|
if (r.failure)
|
|
216
246
|
return { assessment: this.unavailable(r.failure) };
|
|
217
247
|
if (r.status === 404) {
|
|
@@ -224,8 +254,14 @@ export class Vet402Client {
|
|
|
224
254
|
}
|
|
225
255
|
return { assessment: this.unavailable("invalid_response") };
|
|
226
256
|
}
|
|
227
|
-
if (r.status !== 200)
|
|
228
|
-
|
|
257
|
+
if (r.status !== 200) {
|
|
258
|
+
const st = r.status ?? 0;
|
|
259
|
+
return {
|
|
260
|
+
assessment: st >= 400 && st < 500
|
|
261
|
+
? this.rejected(st)
|
|
262
|
+
: this.unavailable("invalid_response"),
|
|
263
|
+
};
|
|
264
|
+
}
|
|
229
265
|
const b = r.body;
|
|
230
266
|
if (b?.recommendation !== "ALLOW" && b?.recommendation !== "WARN" && b?.recommendation !== "BLOCK") {
|
|
231
267
|
return { assessment: this.unavailable("invalid_response") };
|
|
@@ -238,7 +274,9 @@ export class Vet402Client {
|
|
|
238
274
|
kind: "verdict",
|
|
239
275
|
verdict: b.recommendation,
|
|
240
276
|
reasonCodes: Array.isArray(b.reason_codes)
|
|
241
|
-
? b.reason_codes
|
|
277
|
+
? b.reason_codes
|
|
278
|
+
.filter((c) => typeof c === "string")
|
|
279
|
+
.map((c) => c.replace(/[\u0000-\u001F\u007F]+/g, " ").slice(0, 200))
|
|
242
280
|
: [],
|
|
243
281
|
verifiedTerms: vt,
|
|
244
282
|
evidenceAgeSeconds: typeof b.evidence_age?.days_since_last_delivery === "number"
|
|
@@ -260,11 +298,18 @@ export class Vet402Client {
|
|
|
260
298
|
typeof asset !== "string" ||
|
|
261
299
|
typeof amount !== "string" ||
|
|
262
300
|
!/^\d+$/.test(amount) ||
|
|
301
|
+
amount.length > 78 ||
|
|
263
302
|
typeof network !== "string" ||
|
|
264
303
|
typeof scheme !== "string") {
|
|
265
304
|
return "invalid";
|
|
266
305
|
}
|
|
267
|
-
|
|
306
|
+
let factor = 1n;
|
|
307
|
+
try {
|
|
308
|
+
factor = LEDGER_UNIT_FACTOR[normalizeNetwork(network)] ?? 1n;
|
|
309
|
+
}
|
|
310
|
+
catch {
|
|
311
|
+
return "invalid";
|
|
312
|
+
}
|
|
268
313
|
return {
|
|
269
314
|
payTo: pay_to,
|
|
270
315
|
asset,
|
|
@@ -276,20 +321,27 @@ export class Vet402Client {
|
|
|
276
321
|
unavailable(failure) {
|
|
277
322
|
return { kind: "unavailable", failure, checkedAt: this.iso() };
|
|
278
323
|
}
|
|
324
|
+
rejected(httpStatus) {
|
|
325
|
+
return { kind: "rejected", httpStatus, checkedAt: this.iso() };
|
|
326
|
+
}
|
|
279
327
|
iso() {
|
|
280
328
|
return new Date(this.now()).toISOString();
|
|
281
329
|
}
|
|
282
|
-
async outbound(url, endpoint, deadline, callerSignal) {
|
|
330
|
+
async outbound(url, endpoint, deadline, callerSignal, wallet) {
|
|
331
|
+
const wb = this.walletBucketFor(wallet);
|
|
283
332
|
for (;;) {
|
|
284
333
|
const remaining = deadline - this.now();
|
|
285
334
|
if (remaining <= 0)
|
|
286
335
|
return { failure: "timeout" };
|
|
287
|
-
const
|
|
288
|
-
if (
|
|
336
|
+
const waitMs = Math.max(this.bucket.peekWaitMs(), wb?.peekWaitMs() ?? 0);
|
|
337
|
+
if (waitMs === 0) {
|
|
338
|
+
this.bucket.tryAcquire();
|
|
339
|
+
wb?.tryAcquire();
|
|
289
340
|
break;
|
|
290
|
-
|
|
341
|
+
}
|
|
342
|
+
if (this.now() + waitMs > deadline)
|
|
291
343
|
return { failure: "rate_limited" };
|
|
292
|
-
await this.sleep(
|
|
344
|
+
await this.sleep(waitMs);
|
|
293
345
|
}
|
|
294
346
|
const remaining = deadline - this.now();
|
|
295
347
|
if (remaining <= 0)
|
|
@@ -319,7 +371,25 @@ export class Vet402Client {
|
|
|
319
371
|
}
|
|
320
372
|
if (res.status === 429) {
|
|
321
373
|
this.metrics?.onRateLimited?.(endpoint);
|
|
322
|
-
|
|
374
|
+
const ra = Number(res.headers.get("retry-after"));
|
|
375
|
+
if (Number.isFinite(ra) && ra > 0 && ra * 1000 < deadline - this.now()) {
|
|
376
|
+
await this.sleep(ra * 1000);
|
|
377
|
+
try {
|
|
378
|
+
res = await this.fetch(url, {
|
|
379
|
+
method: "GET",
|
|
380
|
+
headers: { accept: "application/json" },
|
|
381
|
+
signal: AbortSignal.timeout(Math.max(0, deadline - this.now())),
|
|
382
|
+
});
|
|
383
|
+
}
|
|
384
|
+
catch {
|
|
385
|
+
return { failure: "rate_limited" };
|
|
386
|
+
}
|
|
387
|
+
if (res.status === 429)
|
|
388
|
+
return { failure: "rate_limited" };
|
|
389
|
+
}
|
|
390
|
+
else {
|
|
391
|
+
return { failure: "rate_limited" };
|
|
392
|
+
}
|
|
323
393
|
}
|
|
324
394
|
if (res.status === 503)
|
|
325
395
|
return { failure: "degraded" };
|
|
@@ -10,15 +10,6 @@ export interface DepositWalletClient {
|
|
|
10
10
|
functionName: string;
|
|
11
11
|
args: readonly unknown[];
|
|
12
12
|
}): Promise<`0x${string}`>;
|
|
13
|
-
readContract?(args: {
|
|
14
|
-
address: `0x${string}`;
|
|
15
|
-
abi: unknown;
|
|
16
|
-
functionName: string;
|
|
17
|
-
args: readonly unknown[];
|
|
18
|
-
}): Promise<unknown>;
|
|
19
|
-
waitForTransactionReceipt?(args: {
|
|
20
|
-
hash: `0x${string}`;
|
|
21
|
-
}): Promise<unknown>;
|
|
22
13
|
}
|
|
23
14
|
export interface DepositResult {
|
|
24
15
|
txHash: `0x${string}`;
|
package/dist/gateway/deposit.js
CHANGED
|
@@ -50,45 +50,18 @@ export async function depositToGateway(args) {
|
|
|
50
50
|
if (amount <= 0n) {
|
|
51
51
|
throw new Error(`deposit amount must be > 0 (got ${args.amountUsd})`);
|
|
52
52
|
}
|
|
53
|
-
const
|
|
54
|
-
|
|
55
|
-
:
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
const allowance = (await wallet.readContract({
|
|
60
|
-
address: chain.usdc,
|
|
61
|
-
abi: erc20Abi,
|
|
62
|
-
functionName: "allowance",
|
|
63
|
-
args: [depositor, chain.gatewayWallet],
|
|
64
|
-
}));
|
|
65
|
-
needsApproval = allowance < amount;
|
|
66
|
-
}
|
|
67
|
-
catch {
|
|
68
|
-
needsApproval = true;
|
|
69
|
-
}
|
|
70
|
-
}
|
|
71
|
-
let approvalTxHash;
|
|
72
|
-
if (needsApproval) {
|
|
73
|
-
approvalTxHash = await wallet.writeContract({
|
|
74
|
-
address: chain.usdc,
|
|
75
|
-
abi: erc20Abi,
|
|
76
|
-
functionName: "approve",
|
|
77
|
-
args: [chain.gatewayWallet, amount],
|
|
78
|
-
});
|
|
79
|
-
if (wallet.waitForTransactionReceipt) {
|
|
80
|
-
await wallet.waitForTransactionReceipt({ hash: approvalTxHash });
|
|
81
|
-
}
|
|
82
|
-
}
|
|
53
|
+
const approvalTxHash = await wallet.writeContract({
|
|
54
|
+
address: chain.usdc,
|
|
55
|
+
abi: erc20Abi,
|
|
56
|
+
functionName: "approve",
|
|
57
|
+
args: [chain.gatewayWallet, amount],
|
|
58
|
+
});
|
|
83
59
|
const txHash = await wallet.writeContract({
|
|
84
60
|
address: chain.gatewayWallet,
|
|
85
61
|
abi: GATEWAY_WALLET_ABI,
|
|
86
62
|
functionName: "deposit",
|
|
87
63
|
args: [chain.usdc, amount],
|
|
88
64
|
});
|
|
89
|
-
if (wallet.waitForTransactionReceipt) {
|
|
90
|
-
await wallet.waitForTransactionReceipt({ hash: txHash });
|
|
91
|
-
}
|
|
92
65
|
const eta = new Date(Date.now() + estimateFor(chain) * 1000);
|
|
93
66
|
return {
|
|
94
67
|
txHash,
|
package/dist/index.d.ts
CHANGED
|
@@ -30,8 +30,6 @@ export * from "./buyer/caps.js";
|
|
|
30
30
|
export * from "./buyer/session.js";
|
|
31
31
|
export * from "./buyer/accepts.js";
|
|
32
32
|
export * from "./buyer/client.js";
|
|
33
|
-
export * from "./buyer/guard.js";
|
|
34
|
-
export * from "./buyer/risk-guard.js";
|
|
35
33
|
export * from "./buyer/paginate.js";
|
|
36
34
|
export * from "./buyer/counterparty.js";
|
|
37
35
|
export * from "./counterparty/index.js";
|
package/dist/index.js
CHANGED
|
@@ -30,8 +30,6 @@ export * from "./buyer/caps.js";
|
|
|
30
30
|
export * from "./buyer/session.js";
|
|
31
31
|
export * from "./buyer/accepts.js";
|
|
32
32
|
export * from "./buyer/client.js";
|
|
33
|
-
export * from "./buyer/guard.js";
|
|
34
|
-
export * from "./buyer/risk-guard.js";
|
|
35
33
|
export * from "./buyer/paginate.js";
|
|
36
34
|
export * from "./buyer/counterparty.js";
|
|
37
35
|
export * from "./counterparty/index.js";
|
package/package.json
CHANGED