@dvmkit/dvm-cli 0.6.0 → 0.7.0-rc.2
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/dist/{_esm-MN4BUYV6.js → _esm-KJAA4KAJ.js} +7 -7
- package/dist/{actions-LR65XILR.js → actions-J7VGYDBF.js} +4 -4
- package/dist/{ccip-JXYJSXTW.js → ccip-CJFG4PLA.js} +1 -1
- package/dist/{chains-LJ7XK6H3.js → chains-J6VIUNUB.js} +4 -4
- package/dist/{chunk-MJ4X4BEW.js → chunk-6LP4EGKA.js} +61 -61
- package/dist/chunk-6QHVPJNX.js +122 -0
- package/dist/chunk-7UAQTHNP.js +77 -0
- package/dist/{chunk-BECPI5H5.js → chunk-B4WHUMZM.js} +36 -36
- package/dist/{chunk-CJTE5TS3.js → chunk-ESOJUXVY.js} +5 -5
- package/dist/{chunk-F55NNH2F.js → chunk-FOWQ7R7S.js} +16 -16
- package/dist/{chunk-ID5G54HJ.js → chunk-FPWP4S5S.js} +5 -3
- package/dist/{chunk-EE2MREOM.js → chunk-IQV4KG63.js} +5 -3
- package/dist/{chunk-R55XNXAR.js → chunk-IUTVV6N5.js} +3 -3
- package/dist/{chunk-Z4CZUMUT.js → chunk-JBU7RKQ3.js} +15 -15
- package/dist/{chunk-SHZMNEXE.js → chunk-JTMBSEZO.js} +2770 -926
- package/dist/{chunk-ERJFRCJO.js → chunk-KDNFUDOG.js} +5 -5
- package/dist/chunk-PG7MEKJI.js +43 -0
- package/dist/{chunk-WTM2EICO.js → chunk-PUOXBKY2.js} +3 -3
- package/dist/{chunk-GZWKCIYN.js → chunk-QXMKABL7.js} +3 -3
- package/dist/chunk-R2DSAZBO.js +87 -0
- package/dist/chunk-RQYMWLX4.js +409 -0
- package/dist/{chunk-FL2ICZW5.js → chunk-SYFKO6BA.js} +3 -3
- package/dist/{chunk-LH3QPVN6.js → chunk-TAZWRWM4.js} +8060 -8058
- package/dist/chunk-U3YRNLZ5.js +262 -0
- package/dist/{chunk-QICJRKB7.js → chunk-VIYUB3XT.js} +11035 -12471
- package/dist/chunk-VLZ2K7JL.js +5460 -0
- package/dist/{chunk-TZWZTS37.js → chunk-WN5R367B.js} +57 -83
- package/dist/{chunk-EZHT2RLJ.js → chunk-X7SEGALJ.js} +3 -3
- package/dist/{chunk-XHOFQ3OS.js → chunk-Y3SQD37C.js} +9 -9
- package/dist/chunk-ZXVOMXT4.js +765 -0
- package/dist/{client-RYDA62DU.js → client-6IHIUB6J.js} +10 -10
- package/dist/client-IDO4IAXG.js +36 -0
- package/dist/{dist-GKCEIY2A.js → dist-23E7OOCA.js} +9 -9
- package/dist/dvm.js +2428 -568
- package/dist/{internal-INUTGTXQ.js → internal-7FXJTFBU.js} +325 -508
- package/dist/lifecycle-LRS3IBQL.js +36 -0
- package/dist/{payout-reporter-3Y2U55ZX-CMKACKA3.js → payout-reporter-WT7XYW42-U2QPDIYC.js} +3 -2
- package/dist/{pocket-refill-K5T4LZF6.js → pocket-refill-J5OWRBXH.js} +33 -30
- package/dist/{revenue-reporter-MAERPYGK-CCPZXGFA.js → revenue-reporter-7UR3W2SD-C5OMRGK3.js} +3 -2
- package/dist/{tempo-AXTE4ZEA.js → tempo-ORFVGUKP.js} +10 -10
- package/dist/tempo-lifecycle-HS2NIFKT.js +38 -0
- package/dist/tempo-wallet-BA2LKR45.js +43 -0
- package/dist/wallet-RPPUCQUR.js +45 -0
- package/dist/{x402-R6HPBY5D-VMSW7Z32.js → x402-ZU4GML7Z-RYEACIIT.js} +4 -19
- package/package.json +4 -2
- package/dist/chunk-3YE43JJR.js +0 -215
- package/dist/chunk-4KINCBHL.js +0 -5153
- package/dist/chunk-FSYEZERJ.js +0 -1667
- package/dist/chunk-VOO5IAK7.js +0 -2318
- package/dist/tempo-lifecycle-ZBBLFBMH-HWI4PLYP.js +0 -32
- package/dist/tempo-wallet-B5XXV3YH-SRQBMYFV.js +0 -41
|
@@ -24,7 +24,7 @@ import {
|
|
|
24
24
|
networkOf,
|
|
25
25
|
paymentMethod as paymentMethod2,
|
|
26
26
|
toSource
|
|
27
|
-
} from "./chunk-
|
|
27
|
+
} from "./chunk-SYFKO6BA.js";
|
|
28
28
|
import {
|
|
29
29
|
ExactEip3009PayloadSchema,
|
|
30
30
|
ExactPayloadSchema,
|
|
@@ -52,16 +52,16 @@ import {
|
|
|
52
52
|
syntheticChallengeIdPrefix,
|
|
53
53
|
toPaymentRequirements,
|
|
54
54
|
versions
|
|
55
|
-
} from "./chunk-
|
|
55
|
+
} from "./chunk-PUOXBKY2.js";
|
|
56
56
|
import {
|
|
57
57
|
Base64_exports
|
|
58
|
-
} from "./chunk-
|
|
58
|
+
} from "./chunk-X7SEGALJ.js";
|
|
59
59
|
import {
|
|
60
60
|
Hash_exports
|
|
61
|
-
} from "./chunk-
|
|
61
|
+
} from "./chunk-TAZWRWM4.js";
|
|
62
62
|
import {
|
|
63
63
|
Bytes_exports
|
|
64
|
-
} from "./chunk-
|
|
64
|
+
} from "./chunk-FOWQ7R7S.js";
|
|
65
65
|
import {
|
|
66
66
|
__export
|
|
67
67
|
} from "./chunk-IYHTITNZ.js";
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { createRequire as __dvmCreateRequire } from "node:module";
|
|
3
|
+
const require = __dvmCreateRequire(import.meta.url);
|
|
4
|
+
import {
|
|
5
|
+
formatUsdcMicrounits,
|
|
6
|
+
listX402Channels,
|
|
7
|
+
readX402ChannelGuardFacts
|
|
8
|
+
} from "./chunk-VIYUB3XT.js";
|
|
9
|
+
import {
|
|
10
|
+
DvmError
|
|
11
|
+
} from "./chunk-JTMBSEZO.js";
|
|
12
|
+
|
|
13
|
+
// src/lib/x402/lifecycle.ts
|
|
14
|
+
async function assertX402WalletIdle(wallet, intent) {
|
|
15
|
+
const payerAddress = wallet.address;
|
|
16
|
+
const owned = listX402Channels({ payer: payerAddress });
|
|
17
|
+
const clients = /* @__PURE__ */ new Map();
|
|
18
|
+
for (const channel of owned) {
|
|
19
|
+
const state = await readX402ChannelGuardFacts({ channel, configuredNetwork: wallet.network, clients });
|
|
20
|
+
if (state.balance === 0n && state.pendingWithdrawal === 0n) continue;
|
|
21
|
+
throw new DvmError(
|
|
22
|
+
"x402_wallet_in_use",
|
|
23
|
+
state.balance > 0n ? `The connected x402 wallet still holds ${formatUsdcMicrounits(state.balance)} USDC in an open channel with ${channel.endpoint}.` : `The connected x402 wallet has a timed withdrawal of ${formatUsdcMicrounits(state.pendingWithdrawal)} USDC still in flight on its channel with ${channel.endpoint}.`,
|
|
24
|
+
`Only this key can move those funds. Empty the channel first \u2014 'dvm credit drain' for the cooperative exit, or 'dvm wallet x402-withdraw-initiate --channel-id ${channel.channelId}' and then finalize after the delay \u2014 and ${intentClause(intent)}.`,
|
|
25
|
+
{
|
|
26
|
+
anchor: "x402_channel_live",
|
|
27
|
+
address: payerAddress,
|
|
28
|
+
channel_id: channel.channelId,
|
|
29
|
+
endpoint: channel.endpoint,
|
|
30
|
+
network: channel.network,
|
|
31
|
+
balance_micro: state.balance.toString(),
|
|
32
|
+
pending_withdrawal_micro: state.pendingWithdrawal.toString()
|
|
33
|
+
}
|
|
34
|
+
);
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
function intentClause(intent) {
|
|
38
|
+
return intent === "replace" ? "retry the replacement" : "retry 'dvm wallet x402-disconnect'";
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export {
|
|
42
|
+
assertX402WalletIdle
|
|
43
|
+
};
|
|
@@ -3,15 +3,15 @@ import { createRequire as __dvmCreateRequire } from "node:module";
|
|
|
3
3
|
const require = __dvmCreateRequire(import.meta.url);
|
|
4
4
|
import {
|
|
5
5
|
Base64_exports
|
|
6
|
-
} from "./chunk-
|
|
6
|
+
} from "./chunk-X7SEGALJ.js";
|
|
7
7
|
import {
|
|
8
8
|
Hash_exports
|
|
9
|
-
} from "./chunk-
|
|
9
|
+
} from "./chunk-TAZWRWM4.js";
|
|
10
10
|
import {
|
|
11
11
|
Bytes_exports,
|
|
12
12
|
Hex_exports,
|
|
13
13
|
Json_exports
|
|
14
|
-
} from "./chunk-
|
|
14
|
+
} from "./chunk-FOWQ7R7S.js";
|
|
15
15
|
import {
|
|
16
16
|
__export
|
|
17
17
|
} from "./chunk-IYHTITNZ.js";
|
|
@@ -37,11 +37,11 @@ import {
|
|
|
37
37
|
receiptStatuses,
|
|
38
38
|
sendTransaction,
|
|
39
39
|
uninstallFilter,
|
|
40
|
-
|
|
40
|
+
verifyHash,
|
|
41
41
|
withRetry,
|
|
42
42
|
writeContract,
|
|
43
43
|
writeContractSync
|
|
44
|
-
} from "./chunk-
|
|
44
|
+
} from "./chunk-TAZWRWM4.js";
|
|
45
45
|
import {
|
|
46
46
|
getTransactionCount,
|
|
47
47
|
getTypesForEIP712Domain,
|
|
@@ -81,7 +81,7 @@ import {
|
|
|
81
81
|
universalResolverResolveAbi,
|
|
82
82
|
universalResolverReverseAbi,
|
|
83
83
|
withResolvers
|
|
84
|
-
} from "./chunk-
|
|
84
|
+
} from "./chunk-FOWQ7R7S.js";
|
|
85
85
|
import {
|
|
86
86
|
AbiDecodingZeroDataError,
|
|
87
87
|
BaseError,
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { createRequire as __dvmCreateRequire } from "node:module";
|
|
3
|
+
const require = __dvmCreateRequire(import.meta.url);
|
|
4
|
+
|
|
5
|
+
// node_modules/@dvmkit/sdk/dist/chunk-COYKJRMM.js
|
|
6
|
+
import { AsyncLocalStorage } from "async_hooks";
|
|
7
|
+
var SDK_INIT_ADVISORY_LOCK = 17320927;
|
|
8
|
+
async function withSdkInitLock(db, fn) {
|
|
9
|
+
const context = activeInits.getStore();
|
|
10
|
+
if (context?.get(db)?.active) return fn();
|
|
11
|
+
assertPoolFitsLock(db);
|
|
12
|
+
let holder = holders.get(db);
|
|
13
|
+
if (holder) {
|
|
14
|
+
holder.refs += 1;
|
|
15
|
+
} else {
|
|
16
|
+
holder = { refs: 1, acquired: acquire(db), tail: Promise.resolve() };
|
|
17
|
+
holders.set(db, holder);
|
|
18
|
+
}
|
|
19
|
+
const predecessor = holder.tail;
|
|
20
|
+
let finishTurn;
|
|
21
|
+
holder.tail = new Promise((resolve) => {
|
|
22
|
+
finishTurn = resolve;
|
|
23
|
+
});
|
|
24
|
+
let guardedFailed = false;
|
|
25
|
+
try {
|
|
26
|
+
await holder.acquired;
|
|
27
|
+
await predecessor;
|
|
28
|
+
const token = { active: true };
|
|
29
|
+
const nextContext = new Map(context);
|
|
30
|
+
nextContext.set(db, token);
|
|
31
|
+
try {
|
|
32
|
+
return await activeInits.run(nextContext, fn);
|
|
33
|
+
} finally {
|
|
34
|
+
token.active = false;
|
|
35
|
+
}
|
|
36
|
+
} catch (err) {
|
|
37
|
+
guardedFailed = true;
|
|
38
|
+
throw err;
|
|
39
|
+
} finally {
|
|
40
|
+
try {
|
|
41
|
+
await releaseHolder(db, holder, guardedFailed);
|
|
42
|
+
} finally {
|
|
43
|
+
finishTurn();
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
var holders = /* @__PURE__ */ new WeakMap();
|
|
48
|
+
var activeInits = new AsyncLocalStorage();
|
|
49
|
+
function assertPoolFitsLock(db) {
|
|
50
|
+
const max = db.options?.max;
|
|
51
|
+
if (max === void 0 || max >= 2) return;
|
|
52
|
+
throw new Error(
|
|
53
|
+
`withSdkInitLock: the SDK boot lock needs a pool that allows at least 2 connections (got max=${max}). The lock is held on one pinned client while the guarded DDL runs on another, so boot would hang forever.`
|
|
54
|
+
);
|
|
55
|
+
}
|
|
56
|
+
async function acquire(db) {
|
|
57
|
+
const client = await db.connect();
|
|
58
|
+
try {
|
|
59
|
+
await client.query(`SELECT pg_advisory_lock(${SDK_INIT_ADVISORY_LOCK})`);
|
|
60
|
+
} catch (err) {
|
|
61
|
+
client.release();
|
|
62
|
+
throw err;
|
|
63
|
+
}
|
|
64
|
+
return client;
|
|
65
|
+
}
|
|
66
|
+
async function releaseHolder(db, holder, guardedFailed) {
|
|
67
|
+
holder.refs -= 1;
|
|
68
|
+
if (holder.refs > 0) return;
|
|
69
|
+
holders.delete(db);
|
|
70
|
+
let client;
|
|
71
|
+
try {
|
|
72
|
+
client = await holder.acquired;
|
|
73
|
+
} catch {
|
|
74
|
+
return;
|
|
75
|
+
}
|
|
76
|
+
try {
|
|
77
|
+
await client.query(`SELECT pg_advisory_unlock(${SDK_INIT_ADVISORY_LOCK})`);
|
|
78
|
+
client.release();
|
|
79
|
+
} catch (err) {
|
|
80
|
+
client.release(err instanceof Error ? err : new Error(String(err)));
|
|
81
|
+
if (!guardedFailed) throw err;
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
export {
|
|
86
|
+
withSdkInitLock
|
|
87
|
+
};
|
|
@@ -0,0 +1,409 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { createRequire as __dvmCreateRequire } from "node:module";
|
|
3
|
+
const require = __dvmCreateRequire(import.meta.url);
|
|
4
|
+
import {
|
|
5
|
+
FX_CACHE_TTL_MS,
|
|
6
|
+
X402_EXACT_AUTHORIZATION_TTL_SECONDS,
|
|
7
|
+
fetchBtcUsdRate,
|
|
8
|
+
formatFiat,
|
|
9
|
+
formatStaleness,
|
|
10
|
+
formatUsd,
|
|
11
|
+
getLastKnownBtcRate,
|
|
12
|
+
isSignableExactRequirement,
|
|
13
|
+
maxAdvertisedMicro,
|
|
14
|
+
withinAdvertisedTolerance
|
|
15
|
+
} from "./chunk-VIYUB3XT.js";
|
|
16
|
+
import {
|
|
17
|
+
DvmError,
|
|
18
|
+
X402_V1_VERSION,
|
|
19
|
+
X402_VERSION,
|
|
20
|
+
buildPaymentRequirements,
|
|
21
|
+
chainIdFromCaip2,
|
|
22
|
+
encodePayment,
|
|
23
|
+
ensureAddress,
|
|
24
|
+
msatsToUsd,
|
|
25
|
+
msatsToUsdc,
|
|
26
|
+
usdToMsats,
|
|
27
|
+
usdcContractFor,
|
|
28
|
+
usdcDomainNameFor,
|
|
29
|
+
usdcDomainVersionFor,
|
|
30
|
+
usdcToMsats,
|
|
31
|
+
x402NetworkByCaip2,
|
|
32
|
+
x402NetworkToCaip2
|
|
33
|
+
} from "./chunk-JTMBSEZO.js";
|
|
34
|
+
|
|
35
|
+
// src/lib/x402/client.ts
|
|
36
|
+
import { randomBytes } from "crypto";
|
|
37
|
+
|
|
38
|
+
// src/lib/output.ts
|
|
39
|
+
import { writeSync } from "fs";
|
|
40
|
+
var _traceId = null;
|
|
41
|
+
function setOutputTraceId(id) {
|
|
42
|
+
_traceId = id;
|
|
43
|
+
}
|
|
44
|
+
function getOutputTraceId() {
|
|
45
|
+
return _traceId;
|
|
46
|
+
}
|
|
47
|
+
function json(data) {
|
|
48
|
+
const out = _traceId !== null && typeof data === "object" && data !== null && !Array.isArray(data) && !("trace_id" in data) ? { trace_id: _traceId, ...data } : data;
|
|
49
|
+
writeAllSync(1, JSON.stringify(out) + "\n");
|
|
50
|
+
}
|
|
51
|
+
function info(msg) {
|
|
52
|
+
writeAllSync(2, msg + "\n");
|
|
53
|
+
}
|
|
54
|
+
function raw(msg) {
|
|
55
|
+
writeAllSync(1, msg + "\n");
|
|
56
|
+
}
|
|
57
|
+
function progress(event) {
|
|
58
|
+
writeAllSync(2, JSON.stringify(event) + "\n");
|
|
59
|
+
}
|
|
60
|
+
function writeAllSync(fd, text) {
|
|
61
|
+
const buf = Buffer.from(text, "utf8");
|
|
62
|
+
let offset = 0;
|
|
63
|
+
while (offset < buf.length) {
|
|
64
|
+
try {
|
|
65
|
+
offset += writeSync(fd, buf, offset, buf.length - offset);
|
|
66
|
+
} catch (err) {
|
|
67
|
+
const code = err.code;
|
|
68
|
+
if (code === "EAGAIN" || code === "EINTR") continue;
|
|
69
|
+
throw err;
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
// src/lib/btc-rate.ts
|
|
75
|
+
async function resolveBtcUsdRate(purpose) {
|
|
76
|
+
try {
|
|
77
|
+
return { rate: await fetchBtcUsdRate(), stale: false };
|
|
78
|
+
} catch {
|
|
79
|
+
const cached = getLastKnownBtcRate();
|
|
80
|
+
if (cached) {
|
|
81
|
+
warnStaleRate(cached.cachedAt);
|
|
82
|
+
return { rate: cached.rate, stale: true, cachedAt: cached.cachedAt };
|
|
83
|
+
}
|
|
84
|
+
throw rateUnavailable(purpose);
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
async function tryResolveBtcUsdRate() {
|
|
88
|
+
try {
|
|
89
|
+
return await resolveBtcUsdRate("conversion");
|
|
90
|
+
} catch {
|
|
91
|
+
return null;
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
function staleRateNotice(resolved) {
|
|
95
|
+
if (!resolved?.stale || resolved.cachedAt === void 0) return void 0;
|
|
96
|
+
const age = formatStaleness(resolved.cachedAt);
|
|
97
|
+
return {
|
|
98
|
+
cached_at: new Date(resolved.cachedAt).toISOString(),
|
|
99
|
+
age,
|
|
100
|
+
display: `Priced with a BTC/USD rate cached ${age} \u2014 the rate provider is unreachable, so dollar figures may have drifted.`
|
|
101
|
+
};
|
|
102
|
+
}
|
|
103
|
+
var warnedStale = false;
|
|
104
|
+
function warnStaleRate(cachedAt) {
|
|
105
|
+
if (warnedStale) return;
|
|
106
|
+
warnedStale = true;
|
|
107
|
+
info(
|
|
108
|
+
`Warning: the BTC/USD rate provider is unreachable \u2014 using the last rate this machine saw (cached ${formatStaleness(cachedAt)}). Dollar figures may have drifted.`
|
|
109
|
+
);
|
|
110
|
+
}
|
|
111
|
+
function rateUnavailable(purpose) {
|
|
112
|
+
const outcome = purpose === "payment" ? "nothing was paid" : "no conversion was performed";
|
|
113
|
+
const noun = purpose === "payment" ? "payment" : "conversion";
|
|
114
|
+
const capped = outcome.charAt(0).toUpperCase() + outcome.slice(1);
|
|
115
|
+
return new DvmError(
|
|
116
|
+
"rate_unavailable",
|
|
117
|
+
`Could not price this ${noun}: the BTC/USD rate provider is unreachable and no cached rate is available.`,
|
|
118
|
+
`${capped}. The rate provider (CoinGecko) is rate-limiting or down, and this machine has never cached a rate. Retry in a minute; if it keeps failing, check network access to api.coingecko.com.${purpose === "payment" ? " Budgets are denominated in dollars, so a payment cannot be authorised without a rate." : ""}`,
|
|
119
|
+
{
|
|
120
|
+
display: `BTC/USD rate unavailable \u2014 ${outcome}.`,
|
|
121
|
+
anchor: "rate_unavailable",
|
|
122
|
+
purpose,
|
|
123
|
+
provider: "coingecko",
|
|
124
|
+
retryable: true
|
|
125
|
+
}
|
|
126
|
+
);
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
// src/lib/currency.ts
|
|
130
|
+
function formatSats(msats) {
|
|
131
|
+
if (msats === 0) return "0 sats";
|
|
132
|
+
if (msats < 1e3) return `${msats.toLocaleString("en-US")} msats`;
|
|
133
|
+
if (msats % 1e3 === 0) return `${(msats / 1e3).toLocaleString("en-US")} sats`;
|
|
134
|
+
return `${Math.round(msats / 1e3 * 100) / 100} sats`;
|
|
135
|
+
}
|
|
136
|
+
function formatAmount(msats, rate, opts) {
|
|
137
|
+
const usd = msatsToUsd(msats, rate);
|
|
138
|
+
const base = `~$${formatUsd(usd)} (${formatSats(msats)})`;
|
|
139
|
+
return opts?.anchor === false ? base : `${base} \u2014 ${costAnchor(usd)}`;
|
|
140
|
+
}
|
|
141
|
+
function formatPaymentAmount(msats, fiat, opts) {
|
|
142
|
+
if (!fiat || fiat.amount <= 0) return formatAmountBestEffort(msats, opts);
|
|
143
|
+
const base = `${formatFiat(fiat.amount, fiat.currency)} (${formatSats(msats)})`;
|
|
144
|
+
return opts?.anchor === false ? base : `${base} \u2014 ${costAnchor(fiat.amount, fiat.currency)}`;
|
|
145
|
+
}
|
|
146
|
+
var COST_ANCHOR_BANDS = {
|
|
147
|
+
usd: [0.01, 0.1, 1, 10],
|
|
148
|
+
eur: [0.01, 0.1, 1, 10],
|
|
149
|
+
gbp: [0.01, 0.1, 1, 10],
|
|
150
|
+
jpy: [1, 10, 100, 1500]
|
|
151
|
+
};
|
|
152
|
+
function costAnchor(amount, currency = "usd") {
|
|
153
|
+
const bands = COST_ANCHOR_BANDS[currency] ?? COST_ANCHOR_BANDS.usd;
|
|
154
|
+
if (amount < bands[0]) return "fraction of a cent";
|
|
155
|
+
if (amount <= bands[1]) return "comparable to an API call";
|
|
156
|
+
if (amount <= bands[2]) return "comparable to a ChatGPT query";
|
|
157
|
+
if (amount <= bands[3]) return "comparable to a coffee";
|
|
158
|
+
return "significant purchase \u2014 review carefully";
|
|
159
|
+
}
|
|
160
|
+
function monetaryJson(msats, rate) {
|
|
161
|
+
const usd = msatsToUsd(msats, rate);
|
|
162
|
+
return {
|
|
163
|
+
msats,
|
|
164
|
+
usd: Math.round(usd * 100) / 100,
|
|
165
|
+
anchor: costAnchor(usd),
|
|
166
|
+
display: formatAmount(msats, rate)
|
|
167
|
+
};
|
|
168
|
+
}
|
|
169
|
+
function parseBudget(budget, rate) {
|
|
170
|
+
const value = assertValidBudget(budget);
|
|
171
|
+
return budget.startsWith("$") ? usdToMsats(value, rate) : value;
|
|
172
|
+
}
|
|
173
|
+
function assertValidBudget(budget) {
|
|
174
|
+
const value = budget.startsWith("$") ? parseFloat(budget.slice(1)) : parseInt(budget, 10);
|
|
175
|
+
if (isNaN(value)) throw new Error(`Invalid budget: ${budget}`);
|
|
176
|
+
return value;
|
|
177
|
+
}
|
|
178
|
+
function formatAmountBestEffort(msats, opts) {
|
|
179
|
+
const m = msats ?? 0;
|
|
180
|
+
const cached = getLastKnownBtcRate();
|
|
181
|
+
if (cached === null) return `${Math.round(m / 1e3)} sats`;
|
|
182
|
+
const base = formatAmount(m, cached.rate, opts);
|
|
183
|
+
if (Date.now() - cached.cachedAt < FX_CACHE_TTL_MS) return base;
|
|
184
|
+
return `${base} (rate cached ${formatStaleness(cached.cachedAt)})`;
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
// src/lib/x402/client.ts
|
|
188
|
+
async function tryX402Payment(request, wallet) {
|
|
189
|
+
const selection = selectPaymentRequirement(request);
|
|
190
|
+
let networkSlug;
|
|
191
|
+
let networkCaip2;
|
|
192
|
+
let chainId;
|
|
193
|
+
let usdc;
|
|
194
|
+
try {
|
|
195
|
+
networkCaip2 = x402NetworkToCaip2(selection.network);
|
|
196
|
+
const mapped = x402NetworkByCaip2(networkCaip2);
|
|
197
|
+
networkSlug = mapped?.slug ?? selection.network;
|
|
198
|
+
chainId = chainIdFromCaip2(networkCaip2);
|
|
199
|
+
usdc = usdcContractFor(networkSlug);
|
|
200
|
+
} catch (err) {
|
|
201
|
+
throw new DvmError(
|
|
202
|
+
"x402_build_failed",
|
|
203
|
+
`Could not resolve x402 network from '${selection.network}': ${err instanceof Error ? err.message : String(err)}`,
|
|
204
|
+
"Check that the DVM's advertised x402.network is a CAIP-2 chain id (e.g. 'eip155:8453' for Base)."
|
|
205
|
+
);
|
|
206
|
+
}
|
|
207
|
+
if (!usdc) return null;
|
|
208
|
+
const rate = await priceableRate(request.btcRate);
|
|
209
|
+
if (rate === null) return null;
|
|
210
|
+
const localUsdcMicro = BigInt(msatsToUsdc(request.amountMsats, rate));
|
|
211
|
+
const requiredUsdcMicro = resolveRequiredUsdcMicro(selection.amount, localUsdcMicro);
|
|
212
|
+
const signedAmountMsats = usdcToMsats(Number(requiredUsdcMicro) / 1e6, rate);
|
|
213
|
+
try {
|
|
214
|
+
const w = await ensureAddress(wallet);
|
|
215
|
+
const validAfter = 0n;
|
|
216
|
+
const validBefore = BigInt(
|
|
217
|
+
Math.floor(Date.now() / 1e3) + X402_EXACT_AUTHORIZATION_TTL_SECONDS
|
|
218
|
+
);
|
|
219
|
+
const nonce = request.nonce ?? `0x${randomBytes(32).toString("hex")}`;
|
|
220
|
+
const domainName = selectedDomainField(selection.accepted?.extra?.name, "name") ?? usdcDomainNameFor(networkSlug) ?? "USD Coin";
|
|
221
|
+
const domainVersion = selectedDomainField(selection.accepted?.extra?.version, "version") ?? usdcDomainVersionFor(networkSlug) ?? "2";
|
|
222
|
+
const { signTypedData } = await import("./accounts-2WZE4N5F.js");
|
|
223
|
+
const signature = await signTypedData({
|
|
224
|
+
privateKey: w.privateKey,
|
|
225
|
+
domain: {
|
|
226
|
+
name: domainName,
|
|
227
|
+
version: domainVersion,
|
|
228
|
+
chainId,
|
|
229
|
+
verifyingContract: usdc
|
|
230
|
+
},
|
|
231
|
+
types: {
|
|
232
|
+
TransferWithAuthorization: [
|
|
233
|
+
{ name: "from", type: "address" },
|
|
234
|
+
{ name: "to", type: "address" },
|
|
235
|
+
{ name: "value", type: "uint256" },
|
|
236
|
+
{ name: "validAfter", type: "uint256" },
|
|
237
|
+
{ name: "validBefore", type: "uint256" },
|
|
238
|
+
{ name: "nonce", type: "bytes32" }
|
|
239
|
+
]
|
|
240
|
+
},
|
|
241
|
+
primaryType: "TransferWithAuthorization",
|
|
242
|
+
message: {
|
|
243
|
+
from: w.address,
|
|
244
|
+
to: selection.payTo,
|
|
245
|
+
value: requiredUsdcMicro,
|
|
246
|
+
validAfter,
|
|
247
|
+
validBefore,
|
|
248
|
+
nonce
|
|
249
|
+
}
|
|
250
|
+
});
|
|
251
|
+
const exactPayload = {
|
|
252
|
+
signature,
|
|
253
|
+
payload: {
|
|
254
|
+
authorization: {
|
|
255
|
+
from: w.address,
|
|
256
|
+
to: selection.payTo,
|
|
257
|
+
value: requiredUsdcMicro.toString(),
|
|
258
|
+
validAfter: validAfter.toString(),
|
|
259
|
+
validBefore: validBefore.toString(),
|
|
260
|
+
nonce
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
};
|
|
264
|
+
const payload = selection.version === X402_V1_VERSION ? {
|
|
265
|
+
x402Version: X402_V1_VERSION,
|
|
266
|
+
scheme: "exact",
|
|
267
|
+
network: networkSlug,
|
|
268
|
+
payload: { signature: exactPayload.signature, ...exactPayload.payload }
|
|
269
|
+
} : {
|
|
270
|
+
x402Version: X402_VERSION,
|
|
271
|
+
...selection.resource ? { resource: selection.resource } : {},
|
|
272
|
+
accepted: selection.accepted ?? buildPaymentRequirements({
|
|
273
|
+
x402Config: {
|
|
274
|
+
payTo: selection.payTo,
|
|
275
|
+
network: networkCaip2,
|
|
276
|
+
...selection.asset ? { asset: selection.asset } : {}
|
|
277
|
+
},
|
|
278
|
+
requiredUsdcMicro,
|
|
279
|
+
resource: selection.resource?.url ?? "",
|
|
280
|
+
version: X402_VERSION
|
|
281
|
+
}),
|
|
282
|
+
payload: { signature: exactPayload.signature, ...exactPayload.payload },
|
|
283
|
+
extensions: selection.extensions ?? {}
|
|
284
|
+
};
|
|
285
|
+
return {
|
|
286
|
+
paymentHeader: encodePayment(payload),
|
|
287
|
+
x402Version: selection.version,
|
|
288
|
+
amountUsdcMicro: requiredUsdcMicro.toString(),
|
|
289
|
+
amountMsats: signedAmountMsats,
|
|
290
|
+
btcRate: rate
|
|
291
|
+
};
|
|
292
|
+
} catch (err) {
|
|
293
|
+
throw new DvmError(
|
|
294
|
+
"x402_build_failed",
|
|
295
|
+
`Failed to build x402 payment: ${err instanceof Error ? err.message : String(err)}`,
|
|
296
|
+
"Check the configured x402 private key and RPC reachability for the target chain."
|
|
297
|
+
);
|
|
298
|
+
}
|
|
299
|
+
}
|
|
300
|
+
function selectPaymentRequirement(request) {
|
|
301
|
+
const challenge = request.paymentRequired;
|
|
302
|
+
if (challenge?.x402Version === X402_VERSION) {
|
|
303
|
+
const accepted = challenge.accepts.find(isSignableExactRequirement);
|
|
304
|
+
if (!accepted) {
|
|
305
|
+
throw invalidChallenge("The DVM's v2 x402 challenge has no exact EIP-3009 requirement.");
|
|
306
|
+
}
|
|
307
|
+
return {
|
|
308
|
+
version: X402_VERSION,
|
|
309
|
+
network: accepted.network,
|
|
310
|
+
amount: accepted.amount,
|
|
311
|
+
payTo: accepted.payTo,
|
|
312
|
+
asset: accepted.asset,
|
|
313
|
+
accepted,
|
|
314
|
+
resource: challenge.resource,
|
|
315
|
+
extensions: challenge.extensions
|
|
316
|
+
};
|
|
317
|
+
}
|
|
318
|
+
if (challenge?.x402Version === X402_V1_VERSION) {
|
|
319
|
+
const accepted = challenge.accepts.find((candidate) => candidate.scheme === "exact");
|
|
320
|
+
if (!accepted) throw invalidChallenge("The DVM's v1 x402 challenge has no exact requirement.");
|
|
321
|
+
return {
|
|
322
|
+
version: X402_V1_VERSION,
|
|
323
|
+
network: accepted.network,
|
|
324
|
+
amount: accepted.maxAmountRequired,
|
|
325
|
+
payTo: accepted.payTo,
|
|
326
|
+
asset: accepted.asset
|
|
327
|
+
};
|
|
328
|
+
}
|
|
329
|
+
return {
|
|
330
|
+
version: request.x402Version ?? X402_V1_VERSION,
|
|
331
|
+
network: request.network,
|
|
332
|
+
amount: request.requiredUsdcMicro,
|
|
333
|
+
payTo: request.payTo,
|
|
334
|
+
asset: request.asset,
|
|
335
|
+
resource: request.resource
|
|
336
|
+
};
|
|
337
|
+
}
|
|
338
|
+
function invalidChallenge(message) {
|
|
339
|
+
return new DvmError(
|
|
340
|
+
"x402_build_failed",
|
|
341
|
+
message,
|
|
342
|
+
"Ask the DVM operator to advertise an exact x402 payment requirement."
|
|
343
|
+
);
|
|
344
|
+
}
|
|
345
|
+
function selectedDomainField(value, field) {
|
|
346
|
+
if (value === void 0 || value === null) return void 0;
|
|
347
|
+
if (typeof value === "string" && value.length > 0) return value;
|
|
348
|
+
throw invalidChallenge(`The DVM advertised an invalid x402 ${field}.`);
|
|
349
|
+
}
|
|
350
|
+
function resolveRequiredUsdcMicro(advertised, localUsdcMicro) {
|
|
351
|
+
if (advertised === void 0) return localUsdcMicro;
|
|
352
|
+
if (!/^[1-9]\d*$/.test(advertised)) {
|
|
353
|
+
throw new DvmError(
|
|
354
|
+
"x402_amount_invalid",
|
|
355
|
+
`The DVM advertised an invalid x402 maxAmountRequired: '${advertised}'.`,
|
|
356
|
+
"Do not sign this payment. Ask the DVM operator to return a positive integer number of USDC micro-units."
|
|
357
|
+
);
|
|
358
|
+
}
|
|
359
|
+
const required = BigInt(advertised);
|
|
360
|
+
if (withinAdvertisedTolerance(required, localUsdcMicro)) return required;
|
|
361
|
+
const advertisedUsd = Number(required) / 1e6;
|
|
362
|
+
const localUsd = Number(localUsdcMicro) / 1e6;
|
|
363
|
+
throw new DvmError(
|
|
364
|
+
"x402_amount_exceeds_limit",
|
|
365
|
+
`The DVM's x402 charge ($${formatUsd(advertisedUsd)} USDC) is more than 10% above the caller's local price ($${formatUsd(localUsd)} USDC).`,
|
|
366
|
+
"The payment was not signed. Refresh the quote or ask the DVM operator to check its BTC/USD rate.",
|
|
367
|
+
{
|
|
368
|
+
advertised_usdc_microunits: required.toString(),
|
|
369
|
+
local_usdc_microunits: localUsdcMicro.toString(),
|
|
370
|
+
max_usdc_microunits: maxAdvertisedMicro(localUsdcMicro).toString(),
|
|
371
|
+
anchor: costAnchor(advertisedUsd),
|
|
372
|
+
display: `Payment refused: $${formatUsd(advertisedUsd)} USDC exceeds the 10% safety margin over the caller's $${formatUsd(localUsd)} USDC estimate.`
|
|
373
|
+
}
|
|
374
|
+
);
|
|
375
|
+
}
|
|
376
|
+
async function priceableRate(btcRate) {
|
|
377
|
+
if (btcRate && btcRate > 0) return btcRate;
|
|
378
|
+
try {
|
|
379
|
+
return (await resolveBtcUsdRate("payment")).rate;
|
|
380
|
+
} catch (err) {
|
|
381
|
+
if (err instanceof DvmError && err.code === "rate_unavailable") {
|
|
382
|
+
info(
|
|
383
|
+
"Skipping the x402 rail: it prices in USDC and the BTC/USD rate is unavailable (no cached rate on this machine). Trying the remaining rails."
|
|
384
|
+
);
|
|
385
|
+
return null;
|
|
386
|
+
}
|
|
387
|
+
throw err;
|
|
388
|
+
}
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
export {
|
|
392
|
+
setOutputTraceId,
|
|
393
|
+
getOutputTraceId,
|
|
394
|
+
json,
|
|
395
|
+
info,
|
|
396
|
+
raw,
|
|
397
|
+
progress,
|
|
398
|
+
formatAmount,
|
|
399
|
+
formatPaymentAmount,
|
|
400
|
+
costAnchor,
|
|
401
|
+
monetaryJson,
|
|
402
|
+
parseBudget,
|
|
403
|
+
assertValidBudget,
|
|
404
|
+
formatAmountBestEffort,
|
|
405
|
+
resolveBtcUsdRate,
|
|
406
|
+
tryResolveBtcUsdRate,
|
|
407
|
+
staleRateNotice,
|
|
408
|
+
tryX402Payment
|
|
409
|
+
};
|
|
@@ -18,14 +18,14 @@ import {
|
|
|
18
18
|
signature,
|
|
19
19
|
string,
|
|
20
20
|
transform
|
|
21
|
-
} from "./chunk-
|
|
21
|
+
} from "./chunk-PUOXBKY2.js";
|
|
22
22
|
import {
|
|
23
23
|
Hash_exports,
|
|
24
24
|
parseUnits
|
|
25
|
-
} from "./chunk-
|
|
25
|
+
} from "./chunk-TAZWRWM4.js";
|
|
26
26
|
import {
|
|
27
27
|
Bytes_exports
|
|
28
|
-
} from "./chunk-
|
|
28
|
+
} from "./chunk-FOWQ7R7S.js";
|
|
29
29
|
import {
|
|
30
30
|
getAddress
|
|
31
31
|
} from "./chunk-MLDUKBU3.js";
|