@dvmkit/dvm-cli 0.4.2 → 0.6.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/README.md +18 -0
- package/dist/{chunk-JVQFBKDX.js → chunk-3YE43JJR.js} +3 -3
- package/dist/{chunk-2TKOJBBB.js → chunk-4KINCBHL.js} +53 -51
- package/dist/{chunk-CSRGRJB6.js → chunk-EE2MREOM.js} +68 -4
- package/dist/chunk-ERJFRCJO.js +150 -0
- package/dist/chunk-FL2ICZW5.js +383 -0
- package/dist/chunk-FSYEZERJ.js +1667 -0
- package/dist/{chunk-6KEZKHN7.js → chunk-ID5G54HJ.js} +211 -35
- package/dist/{chunk-4NWEJTAW.js → chunk-MJ4X4BEW.js} +7953 -8036
- package/dist/{chunk-KBFK5MM5.js → chunk-QICJRKB7.js} +6972 -1321
- package/dist/{chunk-ECEM3ZAS.js → chunk-R55XNXAR.js} +53 -185
- package/dist/{chunk-OOA6X5MI.js → chunk-SHZMNEXE.js} +58 -17
- package/dist/{chunk-PRN4FHDY.js → chunk-TZWZTS37.js} +38 -23
- package/dist/{chunk-DRO3JP42.js → chunk-VOO5IAK7.js} +582 -83
- package/dist/{chunk-2VVVWBQA.js → chunk-WTM2EICO.js} +2 -352
- package/dist/chunk-XHOFQ3OS.js +717 -0
- package/dist/{chunk-KUBOPQ3N.js → chunk-Z4CZUMUT.js} +937 -1599
- package/dist/{client-OWIOFBKS.js → client-RYDA62DU.js} +11 -8
- package/dist/{dist-2G3QBGID.js → dist-GKCEIY2A.js} +7 -4
- package/dist/dvm.js +866 -121
- package/dist/{internal-DS42OMXR.js → internal-INUTGTXQ.js} +52 -38
- package/dist/{payout-reporter-TQ3YIFLZ-64RGUGTA.js → payout-reporter-3Y2U55ZX-CMKACKA3.js} +2 -2
- package/dist/{pocket-refill-3WMWHMOT.js → pocket-refill-K5T4LZF6.js} +18 -14
- package/dist/{revenue-reporter-VN4WYN74-T7HYTIDM.js → revenue-reporter-MAERPYGK-CCPZXGFA.js} +2 -2
- package/dist/tempo-AXTE4ZEA.js +34 -0
- package/dist/{tempo-lifecycle-TJ62A7UX-OLLWSS3I.js → tempo-lifecycle-ZBBLFBMH-HWI4PLYP.js} +11 -7
- package/dist/{tempo-wallet-RCGBBAJH-TSTQAZKT.js → tempo-wallet-B5XXV3YH-SRQBMYFV.js} +2 -2
- package/dist/{x402-S47Q77UE-33J7AIH3.js → x402-R6HPBY5D-VMSW7Z32.js} +3 -3
- package/package.json +2 -2
- package/skills/dvm/calling.md +2 -0
- package/skills/dvm/credit.md +4 -0
- package/skills/dvm/wallets.md +4 -0
|
@@ -6,23 +6,29 @@ import {
|
|
|
6
6
|
from2 as from3,
|
|
7
7
|
memory,
|
|
8
8
|
serialize as serialize2
|
|
9
|
-
} from "./chunk-
|
|
9
|
+
} from "./chunk-R55XNXAR.js";
|
|
10
10
|
import {
|
|
11
11
|
Chain_exports,
|
|
12
|
+
Chain_exports2,
|
|
12
13
|
Channel_exports,
|
|
13
|
-
|
|
14
|
+
Channel_exports2,
|
|
14
15
|
Protocol_exports,
|
|
15
16
|
Runtime_exports,
|
|
16
17
|
Voucher_exports,
|
|
18
|
+
Voucher_exports2,
|
|
17
19
|
actions_exports,
|
|
18
20
|
approve,
|
|
19
21
|
assertAllowedFeeToken,
|
|
20
22
|
assertTransactionPolicy,
|
|
21
23
|
broadcastOpenTransaction,
|
|
24
|
+
broadcastOpenTransaction2,
|
|
22
25
|
broadcastTopUpTransaction,
|
|
26
|
+
broadcastTopUpTransaction2,
|
|
23
27
|
chainId,
|
|
24
28
|
charge,
|
|
29
|
+
client_exports,
|
|
25
30
|
closeOnChain,
|
|
31
|
+
closeOnChain2,
|
|
26
32
|
computeId,
|
|
27
33
|
createChannelStore,
|
|
28
34
|
createJsonChannelStore,
|
|
@@ -30,8 +36,10 @@ import {
|
|
|
30
36
|
decimals,
|
|
31
37
|
defaultAllowedFeeTokens,
|
|
32
38
|
deserializeSnapshot,
|
|
39
|
+
domain,
|
|
33
40
|
entryKey,
|
|
34
41
|
escrowAbi,
|
|
42
|
+
escrowContract,
|
|
35
43
|
extractData,
|
|
36
44
|
fillHostedFeePayerTransaction,
|
|
37
45
|
formatMessageEvent,
|
|
@@ -39,21 +47,28 @@ import {
|
|
|
39
47
|
formatReceiptEvent,
|
|
40
48
|
getChannelEvent,
|
|
41
49
|
getChannelState,
|
|
42
|
-
|
|
50
|
+
getOnChainChannel,
|
|
51
|
+
getResolver2 as getResolver,
|
|
52
|
+
getSubscriptionRpcAllowedCalls,
|
|
53
|
+
getSubscriptionScopes,
|
|
43
54
|
getTransfers,
|
|
44
55
|
hash,
|
|
45
56
|
isEqual,
|
|
46
57
|
isTempoTransaction,
|
|
58
|
+
message,
|
|
47
59
|
parseEvent,
|
|
48
60
|
parsePkhSource,
|
|
49
61
|
parseVoucherFromPayload,
|
|
62
|
+
parseVoucherFromPayload2,
|
|
50
63
|
preflightSponsorship,
|
|
51
64
|
prepareSponsoredTransaction,
|
|
65
|
+
primaryType,
|
|
66
|
+
proofSource,
|
|
52
67
|
readChannelClosedReceiptFields,
|
|
53
68
|
readSessionChallengeAmount,
|
|
54
69
|
readSettledReceiptFields,
|
|
55
70
|
requireSessionCredentialContext,
|
|
56
|
-
resolve,
|
|
71
|
+
resolve2 as resolve,
|
|
57
72
|
resolveCurrency,
|
|
58
73
|
resolveFeeToken,
|
|
59
74
|
rpcUrl,
|
|
@@ -62,21 +77,32 @@ import {
|
|
|
62
77
|
session2,
|
|
63
78
|
sessionManager,
|
|
64
79
|
settleOnChain,
|
|
80
|
+
settleOnChain2,
|
|
81
|
+
signSubscriptionKeyAuthorization,
|
|
65
82
|
simulationTransaction,
|
|
66
83
|
swapExactAmountOut,
|
|
67
84
|
tip20ChannelEscrow,
|
|
85
|
+
toSubscriptionExpiryDate,
|
|
86
|
+
toSubscriptionExpirySeconds,
|
|
87
|
+
toSubscriptionPeriodSeconds,
|
|
68
88
|
transfer,
|
|
89
|
+
transferSelector,
|
|
69
90
|
transferWithMemo,
|
|
91
|
+
transferWithMemoSelector,
|
|
70
92
|
typedData,
|
|
93
|
+
types,
|
|
71
94
|
uint96,
|
|
72
95
|
validateCalls,
|
|
73
96
|
verifyChallengeBinding,
|
|
74
97
|
verifyServer,
|
|
98
|
+
verifySubscriptionKeyAuthorization,
|
|
75
99
|
verifyVoucher,
|
|
100
|
+
verifyVoucher2,
|
|
76
101
|
waitForSuccessfulReceipt
|
|
77
|
-
} from "./chunk-
|
|
102
|
+
} from "./chunk-MJ4X4BEW.js";
|
|
78
103
|
import {
|
|
79
104
|
Abis_exports,
|
|
105
|
+
Account_exports,
|
|
80
106
|
Transaction_exports,
|
|
81
107
|
extractAddress,
|
|
82
108
|
from,
|
|
@@ -88,7 +114,6 @@ import {
|
|
|
88
114
|
BadRequestError,
|
|
89
115
|
ChannelClosedError,
|
|
90
116
|
ChannelNotFoundError,
|
|
91
|
-
Credential_exports,
|
|
92
117
|
DeltaTooSmallError,
|
|
93
118
|
Headers as Headers2,
|
|
94
119
|
InsufficientBalanceError,
|
|
@@ -107,37 +132,7 @@ import {
|
|
|
107
132
|
serialize2 as serialize,
|
|
108
133
|
toServer,
|
|
109
134
|
verify as verify2
|
|
110
|
-
} from "./chunk-
|
|
111
|
-
import {
|
|
112
|
-
costAnchor,
|
|
113
|
-
formatUsd,
|
|
114
|
-
formatUsdcMicrounits,
|
|
115
|
-
fundingReachableAt,
|
|
116
|
-
listCredits,
|
|
117
|
-
maxAdvertisedMicro,
|
|
118
|
-
normalizeCreditEndpoint,
|
|
119
|
-
withinAdvertisedTolerance
|
|
120
|
-
} from "./chunk-DRO3JP42.js";
|
|
121
|
-
import {
|
|
122
|
-
connectedTempoAccount,
|
|
123
|
-
tempoBalanceCheckHint,
|
|
124
|
-
tempoTokenReference
|
|
125
|
-
} from "./chunk-JVQFBKDX.js";
|
|
126
|
-
import {
|
|
127
|
-
DvmError,
|
|
128
|
-
IDENTITIES_FILE,
|
|
129
|
-
TEMPO_CHANNELS_FILE,
|
|
130
|
-
ensureConfigDir,
|
|
131
|
-
redactUrl,
|
|
132
|
-
redactUrlsInText,
|
|
133
|
-
require_proper_lockfile,
|
|
134
|
-
resolveRpcHttpTransportOptions,
|
|
135
|
-
resolveRpcOverride,
|
|
136
|
-
schnorr
|
|
137
|
-
} from "./chunk-2TKOJBBB.js";
|
|
138
|
-
import {
|
|
139
|
-
privateKeyToAccount
|
|
140
|
-
} from "./chunk-EVQERRCP.js";
|
|
135
|
+
} from "./chunk-WTM2EICO.js";
|
|
141
136
|
import {
|
|
142
137
|
signTransaction,
|
|
143
138
|
verifyTypedData,
|
|
@@ -145,6 +140,7 @@ import {
|
|
|
145
140
|
} from "./chunk-GZWKCIYN.js";
|
|
146
141
|
import {
|
|
147
142
|
Hash_exports,
|
|
143
|
+
Secp256k1_exports,
|
|
148
144
|
formatUnits,
|
|
149
145
|
getTransactionReceipt,
|
|
150
146
|
parseEventLogs,
|
|
@@ -165,21 +161,50 @@ import {
|
|
|
165
161
|
keccak256
|
|
166
162
|
} from "./chunk-MLDUKBU3.js";
|
|
167
163
|
import {
|
|
168
|
-
__export
|
|
169
|
-
__toESM
|
|
164
|
+
__export
|
|
170
165
|
} from "./chunk-IYHTITNZ.js";
|
|
171
166
|
|
|
172
|
-
// node_modules
|
|
173
|
-
var
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
167
|
+
// node_modules/mppx/dist/tempo/Proof.js
|
|
168
|
+
var Proof_exports = {};
|
|
169
|
+
__export(Proof_exports, {
|
|
170
|
+
domain: () => domain2,
|
|
171
|
+
hash: () => hash2,
|
|
172
|
+
message: () => message2,
|
|
173
|
+
parsePkhSource: () => parsePkhSource2,
|
|
174
|
+
parseProofSource: () => parseProofSource,
|
|
175
|
+
primaryType: () => primaryType2,
|
|
176
|
+
proofSource: () => proofSource2,
|
|
177
|
+
typedData: () => typedData2,
|
|
178
|
+
types: () => types2
|
|
179
|
+
});
|
|
180
|
+
var primaryType2 = primaryType;
|
|
181
|
+
var types2 = types;
|
|
182
|
+
function domain2(chainId2) {
|
|
183
|
+
return domain(chainId2);
|
|
184
|
+
}
|
|
185
|
+
function message2(parameters) {
|
|
186
|
+
return message(parameters);
|
|
187
|
+
}
|
|
188
|
+
function typedData2(parameters) {
|
|
189
|
+
return typedData(parameters);
|
|
190
|
+
}
|
|
191
|
+
function hash2(parameters) {
|
|
192
|
+
return hash(parameters);
|
|
193
|
+
}
|
|
194
|
+
function proofSource2(parameters) {
|
|
195
|
+
return proofSource(parameters);
|
|
196
|
+
}
|
|
197
|
+
function parsePkhSource2(source) {
|
|
198
|
+
return parsePkhSource(source);
|
|
199
|
+
}
|
|
200
|
+
function parseProofSource(source) {
|
|
201
|
+
return parsePkhSource(source);
|
|
202
|
+
}
|
|
178
203
|
|
|
179
204
|
// node_modules/mppx/dist/tempo/session/index.js
|
|
180
205
|
var session_exports = {};
|
|
181
206
|
__export(session_exports, {
|
|
182
|
-
Client: () =>
|
|
207
|
+
Client: () => client_exports2,
|
|
183
208
|
Precompile: () => precompile_exports,
|
|
184
209
|
Server: () => server_exports,
|
|
185
210
|
deserializeSnapshot: () => deserializeSnapshot,
|
|
@@ -187,8 +212,8 @@ __export(session_exports, {
|
|
|
187
212
|
});
|
|
188
213
|
|
|
189
214
|
// node_modules/mppx/dist/tempo/session/client/index.js
|
|
190
|
-
var
|
|
191
|
-
__export(
|
|
215
|
+
var client_exports2 = {};
|
|
216
|
+
__export(client_exports2, {
|
|
192
217
|
Machine: () => Runtime_exports,
|
|
193
218
|
createChannelStore: () => createChannelStore,
|
|
194
219
|
createJsonChannelStore: () => createJsonChannelStore,
|
|
@@ -338,8 +363,8 @@ function idempotencyKey(input) {
|
|
|
338
363
|
const transactionHash = Hash_exports.keccak256(Hex_exports.toBytes(payload.signature), { as: "Hex" });
|
|
339
364
|
return `mppx_${transactionHash}`;
|
|
340
365
|
}
|
|
341
|
-
const
|
|
342
|
-
return `mppx_${
|
|
366
|
+
const hash3 = Hash_exports.sha256(Bytes_exports.fromString(Json_exports.canonicalize(input)), { as: "Hex" });
|
|
367
|
+
return `mppx_${hash3}`;
|
|
343
368
|
}
|
|
344
369
|
function failure(value) {
|
|
345
370
|
const code = relayErrorCodeFrom(value);
|
|
@@ -783,8 +808,8 @@ function charge2(parameters = {}) {
|
|
|
783
808
|
const expires = challenge.expires;
|
|
784
809
|
switch (validated.type) {
|
|
785
810
|
case "hash": {
|
|
786
|
-
const { hash:
|
|
787
|
-
if (!await markHashUsed(store,
|
|
811
|
+
const { hash: hash3, receipt } = validated;
|
|
812
|
+
if (!await markHashUsed(store, hash3)) {
|
|
788
813
|
throw new VerificationFailedError({
|
|
789
814
|
reason: "Transaction hash has already been used"
|
|
790
815
|
});
|
|
@@ -806,8 +831,8 @@ function charge2(parameters = {}) {
|
|
|
806
831
|
}
|
|
807
832
|
case "transaction": {
|
|
808
833
|
const { isFeePayerTx, serializedTransaction, transaction, transfers } = validated;
|
|
809
|
-
const
|
|
810
|
-
if (!await markHashUsed(store,
|
|
834
|
+
const hash3 = keccak256(serializedTransaction);
|
|
835
|
+
if (!await markHashUsed(store, hash3)) {
|
|
811
836
|
throw new VerificationFailedError({
|
|
812
837
|
reason: "Transaction hash has already been used"
|
|
813
838
|
});
|
|
@@ -879,7 +904,7 @@ function charge2(parameters = {}) {
|
|
|
879
904
|
})();
|
|
880
905
|
const serializedTransaction_final = completedTransaction.serializedTransaction;
|
|
881
906
|
finalHash = keccak256(serializedTransaction_final);
|
|
882
|
-
if (finalHash.toLowerCase() !==
|
|
907
|
+
if (finalHash.toLowerCase() !== hash3.toLowerCase() && !await markHashUsed(store, finalHash))
|
|
883
908
|
throw new VerificationFailedError({
|
|
884
909
|
reason: "Transaction hash has already been used"
|
|
885
910
|
});
|
|
@@ -964,9 +989,9 @@ function charge2(parameters = {}) {
|
|
|
964
989
|
if (!broadcastAttempted) {
|
|
965
990
|
if (reservation)
|
|
966
991
|
await release(sponsorBudgetStore, reservation);
|
|
967
|
-
if (finalHash && finalHash.toLowerCase() !==
|
|
992
|
+
if (finalHash && finalHash.toLowerCase() !== hash3.toLowerCase())
|
|
968
993
|
await releaseHashUse(store, finalHash);
|
|
969
|
-
await releaseHashUse(store,
|
|
994
|
+
await releaseHashUse(store, hash3);
|
|
970
995
|
}
|
|
971
996
|
throw error;
|
|
972
997
|
}
|
|
@@ -1195,21 +1220,21 @@ async function isValidTransferSender(parameters) {
|
|
|
1195
1220
|
source: parameters.source
|
|
1196
1221
|
});
|
|
1197
1222
|
}
|
|
1198
|
-
function getHashStoreKey(
|
|
1199
|
-
return `mppx:charge:${
|
|
1223
|
+
function getHashStoreKey(hash3) {
|
|
1224
|
+
return `mppx:charge:${hash3.toLowerCase()}`;
|
|
1200
1225
|
}
|
|
1201
1226
|
function getProofStoreKey(challengeId) {
|
|
1202
1227
|
return `mppx:charge:proof:${challengeId}`;
|
|
1203
1228
|
}
|
|
1204
|
-
async function markHashUsed(store,
|
|
1205
|
-
return store.update(getHashStoreKey(
|
|
1229
|
+
async function markHashUsed(store, hash3) {
|
|
1230
|
+
return store.update(getHashStoreKey(hash3), (current) => {
|
|
1206
1231
|
if (current !== null)
|
|
1207
1232
|
return { op: "noop", result: false };
|
|
1208
1233
|
return { op: "set", value: Date.now(), result: true };
|
|
1209
1234
|
});
|
|
1210
1235
|
}
|
|
1211
|
-
async function releaseHashUse(store,
|
|
1212
|
-
await store.delete(getHashStoreKey(
|
|
1236
|
+
async function releaseHashUse(store, hash3) {
|
|
1237
|
+
await store.delete(getHashStoreKey(hash3));
|
|
1213
1238
|
}
|
|
1214
1239
|
function parseHashCredentialSource(parameters) {
|
|
1215
1240
|
const { chainId: chainId2, source } = parameters;
|
|
@@ -1617,10 +1642,10 @@ function favicon(theme, realm) {
|
|
|
1617
1642
|
/>`;
|
|
1618
1643
|
}
|
|
1619
1644
|
try {
|
|
1620
|
-
const
|
|
1645
|
+
const domain3 = new URL(realm).hostname;
|
|
1621
1646
|
return html2`<link
|
|
1622
1647
|
rel="icon"
|
|
1623
|
-
href="https://www.google.com/s2/favicons?domain=${
|
|
1648
|
+
href="https://www.google.com/s2/favicons?domain=${domain3}&sz=64"
|
|
1624
1649
|
/>`;
|
|
1625
1650
|
} catch {
|
|
1626
1651
|
return "";
|
|
@@ -2329,7 +2354,7 @@ async function resolveSessionPaymentRequest(parameters) {
|
|
|
2329
2354
|
const client = await getClient({ chainId: chainId2 });
|
|
2330
2355
|
if (client.chain?.id !== chainId2)
|
|
2331
2356
|
throw new Error(`Client not configured with chainId ${chainId2}.`);
|
|
2332
|
-
const
|
|
2357
|
+
const escrowContract2 = resolveRequestEscrowContract(request.escrowContract, parameterEscrowContract);
|
|
2333
2358
|
const operator = resolveRequestOperator(request.operator);
|
|
2334
2359
|
const requestAmount = parseUnits(request.amount, decimals2);
|
|
2335
2360
|
const channelId = await resolveSessionChannelId({
|
|
@@ -2346,7 +2371,7 @@ async function resolveSessionPaymentRequest(parameters) {
|
|
|
2346
2371
|
expected: {
|
|
2347
2372
|
chainId: chainId2,
|
|
2348
2373
|
currency: readChallengeAddress(request.currency, "currency"),
|
|
2349
|
-
escrowContract,
|
|
2374
|
+
escrowContract: escrowContract2,
|
|
2350
2375
|
recipient: readChallengeAddress(request.recipient, "recipient")
|
|
2351
2376
|
},
|
|
2352
2377
|
store
|
|
@@ -2355,7 +2380,7 @@ async function resolveSessionPaymentRequest(parameters) {
|
|
|
2355
2380
|
return {
|
|
2356
2381
|
...requestWithoutOperator,
|
|
2357
2382
|
chainId: chainId2,
|
|
2358
|
-
escrowContract,
|
|
2383
|
+
escrowContract: escrowContract2,
|
|
2359
2384
|
feePayer: resolveRequestFeePayer({
|
|
2360
2385
|
credential,
|
|
2361
2386
|
defaultFeePayer,
|
|
@@ -3382,7 +3407,7 @@ async function* meterIterable(options) {
|
|
|
3382
3407
|
let prepaidUnits = options.prepaidUnits ?? 0;
|
|
3383
3408
|
let reservedAmount = 0n;
|
|
3384
3409
|
let reservedUnits = 0;
|
|
3385
|
-
const
|
|
3410
|
+
const charge5 = async (amount = options.tickCost) => {
|
|
3386
3411
|
if (prepaidUnits > 0) {
|
|
3387
3412
|
prepaidUnits -= 1;
|
|
3388
3413
|
return;
|
|
@@ -3401,12 +3426,12 @@ async function* meterIterable(options) {
|
|
|
3401
3426
|
reservedUnits += 1;
|
|
3402
3427
|
};
|
|
3403
3428
|
const signal = options.signal ?? new AbortController().signal;
|
|
3404
|
-
const iterable = typeof options.generate === "function" ? options.generate({ charge:
|
|
3429
|
+
const iterable = typeof options.generate === "function" ? options.generate({ charge: charge5, signal }) : options.generate;
|
|
3405
3430
|
for await (const value of iterable) {
|
|
3406
3431
|
if (options.signal?.aborted)
|
|
3407
3432
|
break;
|
|
3408
3433
|
if (typeof options.generate !== "function")
|
|
3409
|
-
await
|
|
3434
|
+
await charge5();
|
|
3410
3435
|
await commitReservedCharges({
|
|
3411
3436
|
store: options.store,
|
|
3412
3437
|
channelId: options.channelId,
|
|
@@ -3789,7 +3814,7 @@ function readBootstrapChainId(value) {
|
|
|
3789
3814
|
throw new VerificationFailedError({ reason: "missing bootstrap chainId" });
|
|
3790
3815
|
}
|
|
3791
3816
|
async function verifyBootstrapCredential(parameters) {
|
|
3792
|
-
const { challenge, charge:
|
|
3817
|
+
const { challenge, charge: charge5, credential, rawRequest, secretKey } = parameters;
|
|
3793
3818
|
if (!verify2(credential.challenge, { secretKey }))
|
|
3794
3819
|
throw new InvalidChallengeError({
|
|
3795
3820
|
id: credential.challenge.id,
|
|
@@ -3797,7 +3822,7 @@ async function verifyBootstrapCredential(parameters) {
|
|
|
3797
3822
|
});
|
|
3798
3823
|
assert(credential.challenge.expires, credential.challenge.id);
|
|
3799
3824
|
assertBootstrapChallengeMatches(challenge, credential.challenge);
|
|
3800
|
-
return
|
|
3825
|
+
return charge5.verify({
|
|
3801
3826
|
credential: {
|
|
3802
3827
|
...credential,
|
|
3803
3828
|
payload: charge.schema.credential.payload.parse(credential.payload)
|
|
@@ -4002,1613 +4027,926 @@ function session3(p) {
|
|
|
4002
4027
|
}
|
|
4003
4028
|
});
|
|
4004
4029
|
}
|
|
4005
|
-
(function(
|
|
4006
|
-
|
|
4007
|
-
|
|
4030
|
+
(function(session5) {
|
|
4031
|
+
session5.serializeSnapshot = serializeSnapshot;
|
|
4032
|
+
session5.deserializeSnapshot = deserializeSnapshot;
|
|
4008
4033
|
})(session3 || (session3 = {}));
|
|
4009
4034
|
async function charge3(store, channelId, amount) {
|
|
4010
4035
|
return chargeSessionChannel({ store, channelId, amount });
|
|
4011
4036
|
}
|
|
4012
4037
|
|
|
4013
|
-
// node_modules
|
|
4014
|
-
var
|
|
4015
|
-
|
|
4016
|
-
|
|
4017
|
-
|
|
4018
|
-
|
|
4019
|
-
|
|
4020
|
-
|
|
4021
|
-
|
|
4022
|
-
|
|
4023
|
-
|
|
4024
|
-
|
|
4025
|
-
|
|
4026
|
-
|
|
4027
|
-
|
|
4028
|
-
|
|
4029
|
-
|
|
4030
|
-
|
|
4031
|
-
|
|
4032
|
-
|
|
4033
|
-
|
|
4034
|
-
}
|
|
4035
|
-
if (
|
|
4036
|
-
throw new
|
|
4037
|
-
|
|
4038
|
-
|
|
4039
|
-
|
|
4040
|
-
|
|
4041
|
-
|
|
4042
|
-
const version = parsed.version;
|
|
4043
|
-
if (version !== IDENTITIES_VERSION) {
|
|
4044
|
-
throw new DvmError(
|
|
4045
|
-
"identities_unknown_version",
|
|
4046
|
-
`Unknown identities file version ${String(version)} (this CLI understands version ${String(IDENTITIES_VERSION)}).`,
|
|
4047
|
-
"Upgrade dvm CLI: a newer version wrote this file."
|
|
4048
|
-
);
|
|
4049
|
-
}
|
|
4050
|
-
const identities = parsed.identities;
|
|
4051
|
-
if (typeof identities !== "object" || identities === null || Array.isArray(identities)) {
|
|
4052
|
-
throw new DvmError(
|
|
4053
|
-
"identities_corrupt",
|
|
4054
|
-
`Identities file at ${IDENTITIES_FILE} has a malformed identities map.`,
|
|
4055
|
-
"Restore a backup or delete the file and run 'dvm init'."
|
|
4056
|
-
);
|
|
4057
|
-
}
|
|
4058
|
-
return {
|
|
4059
|
-
version: IDENTITIES_VERSION,
|
|
4060
|
-
identities
|
|
4061
|
-
};
|
|
4062
|
-
}
|
|
4063
|
-
function saveIdentities(file) {
|
|
4064
|
-
ensureConfigDir();
|
|
4065
|
-
const tmp = `${IDENTITIES_FILE}.tmp`;
|
|
4066
|
-
const data = JSON.stringify(file, null, 2) + "\n";
|
|
4067
|
-
writeFileSync(tmp, data, { mode: 384 });
|
|
4068
|
-
try {
|
|
4069
|
-
renameSync(tmp, IDENTITIES_FILE);
|
|
4070
|
-
} catch (err) {
|
|
4071
|
-
try {
|
|
4072
|
-
unlinkSync(tmp);
|
|
4073
|
-
} catch {
|
|
4074
|
-
}
|
|
4075
|
-
throw err;
|
|
4076
|
-
}
|
|
4077
|
-
}
|
|
4078
|
-
async function withIdentitiesLock(fn, opts = {}) {
|
|
4079
|
-
ensureConfigDir();
|
|
4080
|
-
const lockPath = `${IDENTITIES_FILE}.lock`;
|
|
4081
|
-
const stale = opts.stale ?? DEFAULT_LOCK_STALE_MS;
|
|
4082
|
-
const retries = opts.retries ?? DEFAULT_LOCK_RETRIES;
|
|
4083
|
-
const interval = opts.retryIntervalMs ?? DEFAULT_LOCK_RETRY_INTERVAL_MS;
|
|
4084
|
-
let release2;
|
|
4085
|
-
try {
|
|
4086
|
-
release2 = await import_proper_lockfile.default.lock(IDENTITIES_FILE, {
|
|
4087
|
-
lockfilePath: lockPath,
|
|
4088
|
-
stale,
|
|
4089
|
-
realpath: false,
|
|
4090
|
-
retries: { retries, factor: 1, minTimeout: interval, maxTimeout: interval }
|
|
4091
|
-
});
|
|
4092
|
-
} catch (err) {
|
|
4093
|
-
throw new DvmError(
|
|
4094
|
-
"identities_locked",
|
|
4095
|
-
`Could not acquire the identities lock at ${lockPath} within the retry budget.`,
|
|
4096
|
-
`Another dvm CLI may be writing to ${IDENTITIES_FILE}. Wait a moment and retry. If no other dvm CLI is running, remove ${lockPath} and try again.`,
|
|
4097
|
-
{ lock_file: lockPath, underlying: err instanceof Error ? err.message : String(err) }
|
|
4098
|
-
);
|
|
4099
|
-
}
|
|
4100
|
-
try {
|
|
4101
|
-
return await fn();
|
|
4102
|
-
} finally {
|
|
4103
|
-
try {
|
|
4104
|
-
await release2();
|
|
4105
|
-
} catch {
|
|
4106
|
-
}
|
|
4107
|
-
}
|
|
4108
|
-
}
|
|
4109
|
-
function generateIdentity(now = Date.now()) {
|
|
4110
|
-
const { secretKey, publicKey } = schnorr.keygen();
|
|
4111
|
-
return {
|
|
4112
|
-
privkey: bytesToHex(secretKey),
|
|
4113
|
-
pubkey: bytesToHex(publicKey),
|
|
4114
|
-
createdAt: now
|
|
4115
|
-
};
|
|
4116
|
-
}
|
|
4117
|
-
function deriveIdentityFromPrivkey(privkeyHex, now = Date.now()) {
|
|
4118
|
-
if (!/^[0-9a-f]{64}$/.test(privkeyHex)) {
|
|
4119
|
-
throw new DvmError(
|
|
4120
|
-
"invalid_privkey",
|
|
4121
|
-
"Private key must be 64 lowercase hex characters (32 bytes).",
|
|
4122
|
-
"Generate a fresh one with 'dvm identity create <name>'."
|
|
4123
|
-
);
|
|
4124
|
-
}
|
|
4125
|
-
const privkeyBytes = hexToBytes(privkeyHex);
|
|
4126
|
-
const pubkeyBytes = schnorr.getPublicKey(privkeyBytes);
|
|
4127
|
-
return {
|
|
4128
|
-
privkey: privkeyHex,
|
|
4129
|
-
pubkey: bytesToHex(pubkeyBytes),
|
|
4130
|
-
createdAt: now
|
|
4131
|
-
};
|
|
4132
|
-
}
|
|
4133
|
-
function bytesToHex(bytes) {
|
|
4134
|
-
let s = "";
|
|
4135
|
-
for (const b of bytes) s += b.toString(16).padStart(2, "0");
|
|
4136
|
-
return s;
|
|
4137
|
-
}
|
|
4138
|
-
function hexToBytes(hex) {
|
|
4139
|
-
const out = new Uint8Array(hex.length / 2);
|
|
4140
|
-
for (let i = 0; i < out.length; i++) {
|
|
4141
|
-
out[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16);
|
|
4142
|
-
}
|
|
4143
|
-
return out;
|
|
4144
|
-
}
|
|
4145
|
-
function resolveSigningIdentity(opts) {
|
|
4146
|
-
if (opts.as !== void 0) {
|
|
4147
|
-
const file2 = loadIdentities();
|
|
4148
|
-
const entry = file2?.identities[opts.as];
|
|
4149
|
-
if (!entry) {
|
|
4150
|
-
throw new DvmError(
|
|
4151
|
-
"auth_required",
|
|
4152
|
-
`No identity named '${opts.as}' is configured.`,
|
|
4153
|
-
availableHint(file2?.identities, "create one with 'dvm identity create <name>'.")
|
|
4154
|
-
);
|
|
4155
|
-
}
|
|
4156
|
-
return {
|
|
4157
|
-
privkey: entry.privkey,
|
|
4158
|
-
pubkey: entry.pubkey,
|
|
4159
|
-
source: { kind: "flag", name: opts.as }
|
|
4160
|
-
};
|
|
4161
|
-
}
|
|
4162
|
-
const envKey = process.env.DVM_IDENTITY_KEY;
|
|
4163
|
-
if (envKey) {
|
|
4164
|
-
const derived = deriveIdentityFromPrivkey(envKey.toLowerCase());
|
|
4165
|
-
return { privkey: derived.privkey, pubkey: derived.pubkey, source: { kind: "env" } };
|
|
4166
|
-
}
|
|
4167
|
-
const file = loadIdentities();
|
|
4168
|
-
const identities = file?.identities ?? {};
|
|
4169
|
-
const names = Object.keys(identities);
|
|
4170
|
-
const configuredDefault = opts.config?.defaultIdentity;
|
|
4171
|
-
if (configuredDefault !== void 0) {
|
|
4172
|
-
if (!Object.hasOwn(identities, configuredDefault)) {
|
|
4173
|
-
throw new DvmError(
|
|
4174
|
-
"auth_required",
|
|
4175
|
-
`Configured default identity '${configuredDefault}' no longer exists.`,
|
|
4176
|
-
availableHint(identities, "set a new default with 'dvm identity use <name>'.")
|
|
4177
|
-
);
|
|
4178
|
-
}
|
|
4179
|
-
const entry = identities[configuredDefault];
|
|
4180
|
-
return {
|
|
4181
|
-
privkey: entry.privkey,
|
|
4182
|
-
pubkey: entry.pubkey,
|
|
4183
|
-
source: { kind: "default", name: configuredDefault }
|
|
4184
|
-
};
|
|
4185
|
-
}
|
|
4186
|
-
if (names.length === 1) {
|
|
4187
|
-
const onlyName = names[0];
|
|
4188
|
-
const entry = identities[onlyName];
|
|
4189
|
-
return {
|
|
4190
|
-
privkey: entry.privkey,
|
|
4191
|
-
pubkey: entry.pubkey,
|
|
4192
|
-
source: { kind: "sole", name: onlyName }
|
|
4193
|
-
};
|
|
4194
|
-
}
|
|
4195
|
-
if (names.length === 0) {
|
|
4196
|
-
throw new DvmError(
|
|
4197
|
-
"auth_required",
|
|
4198
|
-
"This DVM requires a signed request but no caller identity is configured.",
|
|
4199
|
-
"Run 'dvm identity create <name>' (or 'dvm init') to generate one, or pass DVM_IDENTITY_KEY=<hex>."
|
|
4200
|
-
);
|
|
4201
|
-
}
|
|
4202
|
-
throw new DvmError(
|
|
4203
|
-
"auth_required",
|
|
4204
|
-
"Multiple identities are configured but none is selected.",
|
|
4205
|
-
`Pass --as <name>, set a default with 'dvm identity use <name>', or export DVM_IDENTITY_KEY=<hex>. Available: ${names.join(", ")}.`
|
|
4206
|
-
);
|
|
4207
|
-
}
|
|
4208
|
-
function findSigningIdentityByPubkey(pubkey) {
|
|
4209
|
-
const wanted = pubkey.toLowerCase();
|
|
4210
|
-
const envKey = process.env.DVM_IDENTITY_KEY;
|
|
4211
|
-
if (envKey) {
|
|
4212
|
-
try {
|
|
4213
|
-
const derived = deriveIdentityFromPrivkey(envKey.toLowerCase());
|
|
4214
|
-
if (derived.pubkey === wanted) {
|
|
4215
|
-
return { privkey: derived.privkey, pubkey: derived.pubkey, source: { kind: "env" } };
|
|
4216
|
-
}
|
|
4217
|
-
} catch {
|
|
4218
|
-
}
|
|
4219
|
-
}
|
|
4220
|
-
const identities = loadIdentities()?.identities ?? {};
|
|
4221
|
-
for (const [name, entry] of Object.entries(identities)) {
|
|
4222
|
-
if (entry.pubkey.toLowerCase() === wanted) {
|
|
4223
|
-
return { privkey: entry.privkey, pubkey: entry.pubkey, source: { kind: "pubkey", name } };
|
|
4224
|
-
}
|
|
4225
|
-
}
|
|
4226
|
-
return null;
|
|
4227
|
-
}
|
|
4228
|
-
function availableHint(identities, suffix) {
|
|
4229
|
-
const names = identities ? Object.keys(identities) : [];
|
|
4230
|
-
if (names.length === 0) return `No identities are configured \u2014 ${suffix}`;
|
|
4231
|
-
return `Available identities: ${names.join(", ")}. ${suffix}`;
|
|
4232
|
-
}
|
|
4233
|
-
function shellQuoteArg(value) {
|
|
4234
|
-
if (value === "") return "''";
|
|
4235
|
-
if (SAFE_VALUE_RE.test(value)) return value;
|
|
4236
|
-
return `'${value.replace(/'/g, "'\\''")}'`;
|
|
4237
|
-
}
|
|
4238
|
-
var SAFE_VALUE_RE = /^[a-zA-Z0-9_\-./@:=,+%]+$/;
|
|
4239
|
-
var TEMPO_CHARGE_PENDING_STALE_MS = 24 * 60 * 60 * 1e3;
|
|
4240
|
-
var tempoLockOwner = new AsyncLocalStorage();
|
|
4241
|
-
async function withTempoChannelLock(operation) {
|
|
4242
|
-
if (tempoLockOwner.getStore()?.active) return operation();
|
|
4243
|
-
ensureTempoChannelFile();
|
|
4244
|
-
const release2 = await import_proper_lockfile2.default.lock(TEMPO_CHANNELS_FILE, {
|
|
4245
|
-
realpath: false,
|
|
4246
|
-
retries: { retries: 20, minTimeout: 25, maxTimeout: 250 }
|
|
4038
|
+
// node_modules/mppx/dist/tempo/legacy/index.js
|
|
4039
|
+
var legacy_exports = {};
|
|
4040
|
+
__export(legacy_exports, {
|
|
4041
|
+
Client: () => client_exports,
|
|
4042
|
+
Server: () => server_exports2,
|
|
4043
|
+
Session: () => session_exports2
|
|
4044
|
+
});
|
|
4045
|
+
|
|
4046
|
+
// node_modules/mppx/dist/tempo/legacy/server/index.js
|
|
4047
|
+
var server_exports2 = {};
|
|
4048
|
+
__export(server_exports2, {
|
|
4049
|
+
session: () => session4,
|
|
4050
|
+
settle: () => settle2
|
|
4051
|
+
});
|
|
4052
|
+
|
|
4053
|
+
// node_modules/mppx/dist/tempo/legacy/server/Session.js
|
|
4054
|
+
function session4(p) {
|
|
4055
|
+
const parameters = p;
|
|
4056
|
+
const { amount, channelStateTtl = 5e3, currency = resolveCurrency(parameters), decimals: decimals2 = decimals, feePayerPolicy, store: rawStore = memory(), suggestedDeposit, unitType, waitForConfirmation = true } = parameters;
|
|
4057
|
+
const lastOnChainVerified = /* @__PURE__ */ new Map();
|
|
4058
|
+
const store = fromStore(from2(rawStore, { keyPrefix: parameters.storeKeyPrefix }));
|
|
4059
|
+
const { account, recipient, feePayer, feePayerUrl } = resolve(parameters);
|
|
4060
|
+
if (!account)
|
|
4061
|
+
throw new Error('tempo.session() requires an `account` (viem Account, e.g. privateKeyToAccount("0x...")). An address string is not sufficient \u2014 the server needs a signing account for on-chain channel close and settlement.');
|
|
4062
|
+
const getClient = getResolver({
|
|
4063
|
+
chain: tempo,
|
|
4064
|
+
feePayerUrl,
|
|
4065
|
+
getClient: parameters.getClient,
|
|
4066
|
+
rpcUrl
|
|
4247
4067
|
});
|
|
4248
|
-
const
|
|
4249
|
-
|
|
4250
|
-
|
|
4251
|
-
}
|
|
4252
|
-
|
|
4253
|
-
|
|
4254
|
-
|
|
4255
|
-
|
|
4256
|
-
|
|
4257
|
-
|
|
4258
|
-
|
|
4259
|
-
|
|
4260
|
-
if (operator === void 0) return void 0;
|
|
4261
|
-
return loadFile().values[channelStorageKey(context.callerPubkey, operator, key2)];
|
|
4068
|
+
const transport = parameters.sse ? sse({
|
|
4069
|
+
store,
|
|
4070
|
+
...typeof parameters.sse === "object" ? parameters.sse : void 0
|
|
4071
|
+
}) : void 0;
|
|
4072
|
+
return toServer(session, {
|
|
4073
|
+
defaults: {
|
|
4074
|
+
amount,
|
|
4075
|
+
currency,
|
|
4076
|
+
decimals: decimals2,
|
|
4077
|
+
recipient,
|
|
4078
|
+
suggestedDeposit,
|
|
4079
|
+
unitType
|
|
4262
4080
|
},
|
|
4263
|
-
|
|
4264
|
-
|
|
4265
|
-
|
|
4266
|
-
const
|
|
4267
|
-
|
|
4268
|
-
|
|
4269
|
-
|
|
4270
|
-
|
|
4271
|
-
);
|
|
4272
|
-
}
|
|
4273
|
-
|
|
4274
|
-
|
|
4275
|
-
|
|
4276
|
-
|
|
4277
|
-
|
|
4278
|
-
if (typeof occupied.channelId !== "string" || occupied.channelId.toLowerCase() !== entry.channelId.toLowerCase()) {
|
|
4279
|
-
throw new DvmError(
|
|
4280
|
-
"tempo_channel_scope_occupied",
|
|
4281
|
-
"A different Tempo channel already occupies this payment scope.",
|
|
4282
|
-
"Exit the existing Tempo channel before retrying this funding. Its local recovery descriptor was preserved.",
|
|
4283
|
-
{
|
|
4284
|
-
occupied_channel_id: typeof occupied.channelId === "string" ? occupied.channelId : void 0,
|
|
4285
|
-
refused_channel_id: entry.channelId
|
|
4286
|
-
},
|
|
4287
|
-
"Funding stopped before broadcast because this Tempo payment scope still holds another recoverable channel."
|
|
4288
|
-
);
|
|
4081
|
+
transport,
|
|
4082
|
+
// TODO: dedupe `{charge,session}.request`
|
|
4083
|
+
async request({ credential, request }) {
|
|
4084
|
+
const chainId2 = await (async () => {
|
|
4085
|
+
if (request.chainId)
|
|
4086
|
+
return request.chainId;
|
|
4087
|
+
if (parameters.testnet)
|
|
4088
|
+
return chainId.testnet;
|
|
4089
|
+
return (await getClient({})).chain?.id;
|
|
4090
|
+
})();
|
|
4091
|
+
const client = await (async () => {
|
|
4092
|
+
try {
|
|
4093
|
+
return await getClient({ chainId: chainId2 });
|
|
4094
|
+
} catch {
|
|
4095
|
+
throw new Error(`No client configured with chainId ${chainId2}.`);
|
|
4289
4096
|
}
|
|
4097
|
+
})();
|
|
4098
|
+
if (client.chain?.id !== chainId2)
|
|
4099
|
+
throw new Error(`Client not configured with chainId ${chainId2}.`);
|
|
4100
|
+
const resolvedEscrow = request.escrowContract ?? parameters.escrowContract ?? escrowContract[chainId2];
|
|
4101
|
+
const resolvedFeePayer = (() => {
|
|
4102
|
+
if (request.feePayer === false)
|
|
4103
|
+
return credential ? false : void 0;
|
|
4104
|
+
const account2 = typeof request.feePayer === "object" ? request.feePayer : feePayer;
|
|
4105
|
+
const requested = account2 ?? feePayer ?? feePayerUrl;
|
|
4106
|
+
if (credential)
|
|
4107
|
+
return account2 ?? (feePayerUrl ? true : void 0);
|
|
4108
|
+
if (requested)
|
|
4109
|
+
return true;
|
|
4110
|
+
return void 0;
|
|
4111
|
+
})();
|
|
4112
|
+
return {
|
|
4113
|
+
...request,
|
|
4114
|
+
chainId: chainId2,
|
|
4115
|
+
escrowContract: resolvedEscrow,
|
|
4116
|
+
feePayer: resolvedFeePayer,
|
|
4117
|
+
sessionProtocol: SessionProtocols.v1
|
|
4118
|
+
};
|
|
4119
|
+
},
|
|
4120
|
+
async verify({ credential, envelope, request }) {
|
|
4121
|
+
const { challenge, payload } = credential;
|
|
4122
|
+
const resolvedRequest = (() => {
|
|
4123
|
+
const parsed = session.schema.request.safeParse(request);
|
|
4124
|
+
if (parsed.success)
|
|
4125
|
+
return parsed.data;
|
|
4126
|
+
return request;
|
|
4127
|
+
})();
|
|
4128
|
+
const methodDetails = resolvedRequest.methodDetails;
|
|
4129
|
+
const client = await getClient({ chainId: methodDetails.chainId });
|
|
4130
|
+
const requestAllowsFeePayer = request.feePayer !== false && (request.feePayer === void 0 || request.feePayer === true || typeof request.feePayer === "object");
|
|
4131
|
+
const resolvedFeePayer = methodDetails.feePayer === true && requestAllowsFeePayer ? typeof request.feePayer === "object" ? request.feePayer : feePayer : void 0;
|
|
4132
|
+
const minVoucherDelta = parseUnits(parameters.minVoucherDelta ?? "0", decimals2);
|
|
4133
|
+
const effectiveMinVoucherDelta = methodDetails.minVoucherDelta ? BigInt(methodDetails.minVoucherDelta) : minVoucherDelta;
|
|
4134
|
+
let sessionReceipt;
|
|
4135
|
+
switch (payload.action) {
|
|
4136
|
+
case "open":
|
|
4137
|
+
sessionReceipt = await handleOpen(store, client, challenge, payload, methodDetails, resolvedFeePayer, methodDetails.feePayer === true, feePayerPolicy, waitForConfirmation);
|
|
4138
|
+
lastOnChainVerified.set(sessionReceipt.channelId, Date.now());
|
|
4139
|
+
break;
|
|
4140
|
+
case "topUp":
|
|
4141
|
+
sessionReceipt = await handleTopUp(store, client, challenge, payload, methodDetails, resolvedFeePayer, methodDetails.feePayer === true, feePayerPolicy);
|
|
4142
|
+
lastOnChainVerified.set(sessionReceipt.channelId, Date.now());
|
|
4143
|
+
break;
|
|
4144
|
+
case "voucher":
|
|
4145
|
+
sessionReceipt = await handleVoucher(store, client, effectiveMinVoucherDelta, challenge, payload, methodDetails, channelStateTtl, lastOnChainVerified);
|
|
4146
|
+
break;
|
|
4147
|
+
case "close":
|
|
4148
|
+
sessionReceipt = await handleClose(store, client, challenge, payload, methodDetails, account, resolvedFeePayer);
|
|
4149
|
+
break;
|
|
4150
|
+
default:
|
|
4151
|
+
throw new BadRequestError({
|
|
4152
|
+
reason: `unknown action: ${payload.action}`
|
|
4153
|
+
});
|
|
4290
4154
|
}
|
|
4291
|
-
|
|
4292
|
-
|
|
4293
|
-
|
|
4294
|
-
|
|
4295
|
-
|
|
4296
|
-
|
|
4297
|
-
creditId: context.creditId,
|
|
4298
|
-
channelKey: key2.startsWith("chan:") ? key2.slice(5) : key2,
|
|
4299
|
-
operator,
|
|
4300
|
-
channelId: entry.channelId,
|
|
4301
|
-
cumulativeAmount: entry.cumulativeAmount,
|
|
4302
|
-
deposit: entry.deposit,
|
|
4303
|
-
chainId: entry.chainId,
|
|
4304
|
-
opened: entry.opened,
|
|
4305
|
-
updatedAt
|
|
4155
|
+
if (envelope && isSessionContentRequest(envelope.capturedRequest) && (payload.action === "open" || payload.action === "voucher" && !isSseNegotiationRequest(envelope.capturedRequest))) {
|
|
4156
|
+
const charged = await charge4(store, sessionReceipt.channelId, BigInt(resolvedRequest.amount));
|
|
4157
|
+
sessionReceipt = {
|
|
4158
|
+
...sessionReceipt,
|
|
4159
|
+
spent: charged.spent.toString(),
|
|
4160
|
+
units: charged.units
|
|
4306
4161
|
};
|
|
4307
|
-
|
|
4308
|
-
|
|
4309
|
-
...candidate,
|
|
4310
|
-
cumulativeAmount: association.cumulativeAmount,
|
|
4311
|
-
deposit: association.deposit,
|
|
4312
|
-
chainId: association.chainId,
|
|
4313
|
-
opened: association.opened,
|
|
4314
|
-
updatedAt
|
|
4315
|
-
} : candidate
|
|
4316
|
-
);
|
|
4317
|
-
const index = file.associations.findIndex(
|
|
4318
|
-
(candidate) => sameCredit(
|
|
4319
|
-
candidate,
|
|
4320
|
-
association.endpoint,
|
|
4321
|
-
association.callerPubkey,
|
|
4322
|
-
association.creditId
|
|
4323
|
-
)
|
|
4324
|
-
);
|
|
4325
|
-
if (index === -1) file.associations.push(association);
|
|
4326
|
-
else file.associations[index] = association;
|
|
4162
|
+
if (parameters.sse)
|
|
4163
|
+
sessionReceipt = markPrepaidSessionTick(sessionReceipt);
|
|
4327
4164
|
}
|
|
4328
|
-
|
|
4165
|
+
return sessionReceipt;
|
|
4329
4166
|
},
|
|
4330
|
-
|
|
4331
|
-
|
|
4332
|
-
|
|
4333
|
-
|
|
4334
|
-
|
|
4335
|
-
|
|
4336
|
-
|
|
4337
|
-
|
|
4338
|
-
|
|
4339
|
-
|
|
4340
|
-
|
|
4341
|
-
|
|
4342
|
-
|
|
4343
|
-
|
|
4344
|
-
|
|
4345
|
-
|
|
4346
|
-
|
|
4347
|
-
)
|
|
4348
|
-
|
|
4349
|
-
|
|
4350
|
-
|
|
4351
|
-
|
|
4352
|
-
}
|
|
4353
|
-
saveFile(file);
|
|
4167
|
+
// This hook acts as a gate: when it returns a Response, `withReceipt()`
|
|
4168
|
+
// in Mppx.ts short-circuits and returns that response directly without
|
|
4169
|
+
// invoking the user's route handler. When it returns undefined, the
|
|
4170
|
+
// user's handler runs normally and serves content.
|
|
4171
|
+
//
|
|
4172
|
+
// close and topUp are always gated (204) — they are pure management.
|
|
4173
|
+
//
|
|
4174
|
+
// open and voucher share the same captured-request classifier used
|
|
4175
|
+
// during verification. Non-billable requests are treated as management
|
|
4176
|
+
// updates; billable requests fall through to the application handler.
|
|
4177
|
+
respond({ credential, envelope, input }) {
|
|
4178
|
+
const { payload } = credential;
|
|
4179
|
+
const request = envelope?.capturedRequest ?? captureRequestBodyProbe(input);
|
|
4180
|
+
if (payload.action === "close")
|
|
4181
|
+
return new Response(null, { status: 204 });
|
|
4182
|
+
if (payload.action === "topUp")
|
|
4183
|
+
return new Response(null, { status: 204 });
|
|
4184
|
+
if (parameters.sse && payload.action === "voucher" && isSseNegotiationRequest(request))
|
|
4185
|
+
return new Response(null, { status: 204 });
|
|
4186
|
+
if (isSessionContentRequest(request))
|
|
4187
|
+
return void 0;
|
|
4188
|
+
return new Response(null, { status: 204 });
|
|
4354
4189
|
}
|
|
4355
4190
|
});
|
|
4356
4191
|
}
|
|
4357
|
-
function
|
|
4358
|
-
return
|
|
4359
|
-
}
|
|
4360
|
-
function
|
|
4361
|
-
const
|
|
4362
|
-
|
|
4363
|
-
|
|
4364
|
-
)
|
|
4365
|
-
|
|
4366
|
-
|
|
4367
|
-
|
|
4368
|
-
return loadFile().associations.find(
|
|
4369
|
-
(candidate) => candidate.callerPubkey === callerPubkey && candidate.operator === normalizedOperator && candidate.channelKey === channelKey
|
|
4370
|
-
);
|
|
4371
|
-
}
|
|
4372
|
-
async function loadTempoChannelEntry(association) {
|
|
4373
|
-
return createTempoChannelStore({
|
|
4374
|
-
callerPubkey: association.callerPubkey,
|
|
4375
|
-
endpoint: association.endpoint,
|
|
4376
|
-
creditId: association.creditId,
|
|
4377
|
-
operator: association.operator
|
|
4378
|
-
}).get(association.channelKey);
|
|
4379
|
-
}
|
|
4380
|
-
async function loadTempoChannelController(association) {
|
|
4381
|
-
const entry = await loadTempoChannelEntry(association);
|
|
4382
|
-
return entry && tempoDescriptorController(entry.descriptor);
|
|
4383
|
-
}
|
|
4384
|
-
function tempoDescriptorController(descriptor) {
|
|
4385
|
-
const payer = descriptor.payer;
|
|
4386
|
-
if (typeof payer !== "string" || !isAddress(payer, { strict: false })) return void 0;
|
|
4387
|
-
const signer = descriptor.authorizedSigner;
|
|
4388
|
-
const authorizedSigner2 = session_exports.Precompile.Channel.resolveAuthorizedSigner({
|
|
4389
|
-
...descriptor,
|
|
4390
|
-
payer,
|
|
4391
|
-
authorizedSigner: typeof signer === "string" && isAddress(signer, { strict: false }) ? signer : zeroAddress
|
|
4392
|
-
});
|
|
4393
|
-
return { payer: payer.toLowerCase(), authorizedSigner: authorizedSigner2.toLowerCase() };
|
|
4394
|
-
}
|
|
4395
|
-
function tempoChannelControlledBy(controller, address) {
|
|
4396
|
-
if (!controller) return true;
|
|
4397
|
-
if (address === void 0) return false;
|
|
4398
|
-
const candidate = address.toLowerCase();
|
|
4399
|
-
return controller.payer.toLowerCase() === candidate || controller.authorizedSigner.toLowerCase() === candidate;
|
|
4400
|
-
}
|
|
4401
|
-
async function retireTempoChannel(association) {
|
|
4402
|
-
await createTempoChannelStore({
|
|
4403
|
-
callerPubkey: association.callerPubkey,
|
|
4404
|
-
endpoint: association.endpoint,
|
|
4405
|
-
creditId: association.creditId,
|
|
4406
|
-
operator: association.operator
|
|
4407
|
-
}).delete(association.channelKey);
|
|
4408
|
-
}
|
|
4409
|
-
async function retireTempoChannelScope(association) {
|
|
4410
|
-
await createTempoChannelStore({
|
|
4411
|
-
callerPubkey: association.callerPubkey,
|
|
4412
|
-
operator: association.operator
|
|
4413
|
-
}).delete(association.channelKey);
|
|
4414
|
-
}
|
|
4415
|
-
function tempoChargeFundingStale(pending, now = Date.now()) {
|
|
4416
|
-
return now - pending.requestedAt >= TEMPO_CHARGE_PENDING_STALE_MS;
|
|
4417
|
-
}
|
|
4418
|
-
function tempoChargeCredentialSettleable(pending, now = Date.now()) {
|
|
4419
|
-
return pending.credentialValidBefore !== void 0 && now < pending.credentialValidBefore * 1e3;
|
|
4420
|
-
}
|
|
4421
|
-
function recordPendingTempoChargeFunding(pending) {
|
|
4422
|
-
const { file, credits } = loadChargeFile();
|
|
4423
|
-
const entry = { ...pending, endpoint: normalizeCreditEndpoint(pending.endpoint) };
|
|
4424
|
-
file.charges = [
|
|
4425
|
-
...file.charges.filter((candidate) => !sameChargeCredit(candidate, entry, credits)),
|
|
4426
|
-
entry
|
|
4427
|
-
];
|
|
4428
|
-
saveFile(file);
|
|
4429
|
-
}
|
|
4430
|
-
function loadResumableTempoChargeFunding(args) {
|
|
4431
|
-
const key2 = {
|
|
4432
|
-
endpoint: normalizeCreditEndpoint(args.endpoint),
|
|
4433
|
-
callerPubkey: args.callerPubkey,
|
|
4434
|
-
creditId: args.creditId
|
|
4435
|
-
};
|
|
4436
|
-
const { file, credits } = loadChargeFile();
|
|
4437
|
-
return file.charges.find(
|
|
4438
|
-
(entry) => sameChargeCredit(entry, key2, credits) && !tempoChargeFundingStale(entry, args.now)
|
|
4439
|
-
);
|
|
4440
|
-
}
|
|
4441
|
-
function listResumableTempoChargeFundings(filter = {}) {
|
|
4442
|
-
const endpoint = filter.endpoint ? normalizeCreditEndpoint(filter.endpoint) : void 0;
|
|
4443
|
-
const { file, credits } = loadChargeFile();
|
|
4444
|
-
return file.charges.filter(
|
|
4445
|
-
(entry) => (!endpoint || fundingReachableAt(entry, endpoint, credits)) && (!filter.callerPubkey || entry.callerPubkey === filter.callerPubkey) && !tempoChargeFundingStale(entry, filter.now)
|
|
4446
|
-
).sort((a, b) => a.requestedAt - b.requestedAt);
|
|
4447
|
-
}
|
|
4448
|
-
function clearPendingTempoChargeFunding(pending) {
|
|
4449
|
-
const { file, credits } = loadChargeFile();
|
|
4450
|
-
const key2 = { ...pending, endpoint: normalizeCreditEndpoint(pending.endpoint) };
|
|
4451
|
-
const remaining = file.charges.filter(
|
|
4452
|
-
(entry) => !sameChargeCredit(entry, key2, credits) || entry.fundId !== pending.fundId
|
|
4453
|
-
);
|
|
4454
|
-
if (remaining.length === file.charges.length) return;
|
|
4455
|
-
file.charges = remaining;
|
|
4456
|
-
saveFile(file);
|
|
4457
|
-
}
|
|
4458
|
-
function sameCredit(association, endpoint, callerPubkey, creditId) {
|
|
4459
|
-
return association.endpoint === endpoint && association.callerPubkey === callerPubkey && association.creditId === creditId;
|
|
4460
|
-
}
|
|
4461
|
-
function sameChargeCredit(entry, key2, credits) {
|
|
4462
|
-
return entry.callerPubkey === key2.callerPubkey && entry.creditId === key2.creditId && fundingReachableAt(entry, normalizeCreditEndpoint(key2.endpoint), credits);
|
|
4463
|
-
}
|
|
4464
|
-
function loadChargeFile() {
|
|
4465
|
-
const snapshot = collapseChargeFile();
|
|
4466
|
-
if (!snapshot.changed) return snapshot;
|
|
4467
|
-
const persisted = tryWithTempoChannelLockSync(() => {
|
|
4468
|
-
const current = collapseChargeFile();
|
|
4469
|
-
if (current.changed) saveFile(current.file);
|
|
4470
|
-
return current;
|
|
4192
|
+
function isSseNegotiationRequest(input) {
|
|
4193
|
+
return input.headers.get("Accept")?.includes("text/event-stream") ?? false;
|
|
4194
|
+
}
|
|
4195
|
+
function assertSettlementSender2(parameters) {
|
|
4196
|
+
const { operation, channelId, payee, sender } = parameters;
|
|
4197
|
+
if (!sender)
|
|
4198
|
+
return;
|
|
4199
|
+
if (sender.toLowerCase() === payee.toLowerCase())
|
|
4200
|
+
return;
|
|
4201
|
+
throw new BadRequestError({
|
|
4202
|
+
reason: `Cannot ${operation} channel ${channelId}: tx sender ${sender} is not the channel payee ${payee}. If using an access key, pass a Tempo access-key account whose address is the payee wallet, not the raw delegated key address.`
|
|
4471
4203
|
});
|
|
4472
|
-
return persisted ?? snapshot;
|
|
4473
|
-
}
|
|
4474
|
-
function collapseChargeFile() {
|
|
4475
|
-
const file = loadFile();
|
|
4476
|
-
const credits = listCredits();
|
|
4477
|
-
const charges = [];
|
|
4478
|
-
let changed = false;
|
|
4479
|
-
for (const entry of file.charges) {
|
|
4480
|
-
const index = charges.findIndex((candidate) => sameChargeCredit(candidate, entry, credits));
|
|
4481
|
-
if (index === -1) {
|
|
4482
|
-
charges.push(entry);
|
|
4483
|
-
continue;
|
|
4484
|
-
}
|
|
4485
|
-
const seenAt = Number.isFinite(charges[index].requestedAt) ? charges[index].requestedAt : 0;
|
|
4486
|
-
const entryAt = Number.isFinite(entry.requestedAt) ? entry.requestedAt : 0;
|
|
4487
|
-
if (entryAt > seenAt) charges[index] = entry;
|
|
4488
|
-
changed = true;
|
|
4489
|
-
}
|
|
4490
|
-
if (changed) file.charges = charges;
|
|
4491
|
-
return { file, credits, changed };
|
|
4492
4204
|
}
|
|
4493
|
-
function
|
|
4494
|
-
|
|
4495
|
-
|
|
4496
|
-
|
|
4497
|
-
|
|
4498
|
-
|
|
4499
|
-
|
|
4500
|
-
|
|
4501
|
-
|
|
4502
|
-
|
|
4503
|
-
|
|
4504
|
-
|
|
4505
|
-
|
|
4506
|
-
|
|
4507
|
-
|
|
4508
|
-
|
|
4509
|
-
|
|
4205
|
+
async function settle2(store, client, channelId, options) {
|
|
4206
|
+
const channel = await store.getChannel(channelId);
|
|
4207
|
+
if (!channel)
|
|
4208
|
+
throw new ChannelNotFoundError({ reason: "channel not found" });
|
|
4209
|
+
if (!channel.highestVoucher)
|
|
4210
|
+
throw new VerificationFailedError({ reason: "no voucher to settle" });
|
|
4211
|
+
const chainId2 = client.chain?.id;
|
|
4212
|
+
const resolvedEscrow = options?.escrowContract ?? escrowContract[chainId2];
|
|
4213
|
+
if (!resolvedEscrow)
|
|
4214
|
+
throw new Error(`No escrow contract for chainId ${chainId2}.`);
|
|
4215
|
+
assertSettlementSender2({
|
|
4216
|
+
operation: "settle",
|
|
4217
|
+
channelId,
|
|
4218
|
+
payee: channel.payee,
|
|
4219
|
+
sender: options?.account?.address ?? client.account?.address
|
|
4220
|
+
});
|
|
4221
|
+
const settledAmount = channel.highestVoucher.cumulativeAmount;
|
|
4222
|
+
const txHash = await settleOnChain2(client, resolvedEscrow, channel.highestVoucher, {
|
|
4223
|
+
...options?.feePayer && options?.account ? { feePayer: options.feePayer, account: options.account } : { account: options?.account },
|
|
4224
|
+
candidateFeeTokens: [channel.token]
|
|
4225
|
+
});
|
|
4226
|
+
await store.updateChannel(channelId, (current) => {
|
|
4227
|
+
if (!current)
|
|
4228
|
+
return null;
|
|
4229
|
+
const nextSettled = settledAmount > current.settledOnChain ? settledAmount : current.settledOnChain;
|
|
4230
|
+
return { ...current, settledOnChain: nextSettled };
|
|
4231
|
+
});
|
|
4232
|
+
return txHash;
|
|
4510
4233
|
}
|
|
4511
|
-
function
|
|
4512
|
-
|
|
4513
|
-
if (existsSync2(TEMPO_CHANNELS_FILE)) return;
|
|
4234
|
+
async function charge4(store, channelId, amount) {
|
|
4235
|
+
let result;
|
|
4514
4236
|
try {
|
|
4515
|
-
|
|
4516
|
-
`, {
|
|
4517
|
-
mode: 384,
|
|
4518
|
-
flag: "wx"
|
|
4519
|
-
});
|
|
4237
|
+
result = await deductFromChannel(store, channelId, amount);
|
|
4520
4238
|
} catch {
|
|
4239
|
+
throw new ChannelClosedError({ reason: "channel not found" });
|
|
4521
4240
|
}
|
|
4522
|
-
|
|
4523
|
-
|
|
4524
|
-
|
|
4525
|
-
|
|
4526
|
-
|
|
4527
|
-
|
|
4528
|
-
|
|
4529
|
-
|
|
4530
|
-
}
|
|
4531
|
-
return {
|
|
4532
|
-
version: 2,
|
|
4533
|
-
values: parsed.values,
|
|
4534
|
-
associations: parsed.associations,
|
|
4535
|
-
// Tolerated rather than required, unlike its two siblings: every file
|
|
4536
|
-
// written before lacks the key, and failing closed on it would
|
|
4537
|
-
// read as a corrupt journal on a store that is perfectly intact.
|
|
4538
|
-
charges: Array.isArray(parsed.charges) ? parsed.charges.filter(isPendingTempoCharge) : []
|
|
4539
|
-
};
|
|
4540
|
-
} catch (cause) {
|
|
4541
|
-
throw new DvmError(
|
|
4542
|
-
"tempo_channel_store_invalid",
|
|
4543
|
-
"The saved Tempo channel journal cannot be read safely.",
|
|
4544
|
-
`Do not delete ${TEMPO_CHANNELS_FILE}; restore or repair it before signing another channel credential.`,
|
|
4545
|
-
{ cause: cause instanceof Error ? cause.message : String(cause) }
|
|
4546
|
-
);
|
|
4241
|
+
if (!result.ok) {
|
|
4242
|
+
if (result.channel.finalized)
|
|
4243
|
+
throw new ChannelClosedError({ reason: "channel is finalized" });
|
|
4244
|
+
if (result.channel.closeRequestedAt !== 0n)
|
|
4245
|
+
throw new ChannelClosedError({ reason: "channel has a pending close request" });
|
|
4246
|
+
const available = result.channel.highestVoucherAmount - result.channel.spent;
|
|
4247
|
+
throw new InsufficientBalanceError({
|
|
4248
|
+
reason: `requested ${amount}, available ${available}`
|
|
4249
|
+
});
|
|
4547
4250
|
}
|
|
4251
|
+
return result.channel;
|
|
4548
4252
|
}
|
|
4549
|
-
function
|
|
4550
|
-
|
|
4551
|
-
|
|
4552
|
-
writeFileSync2(tmp, JSON.stringify(file, null, 2) + "\n", { mode: 384 });
|
|
4553
|
-
renameSync2(tmp, TEMPO_CHANNELS_FILE);
|
|
4554
|
-
}
|
|
4555
|
-
function emptyFile() {
|
|
4556
|
-
return { version: 2, values: {}, associations: [], charges: [] };
|
|
4557
|
-
}
|
|
4558
|
-
function migrateLegacyFile(parsed) {
|
|
4559
|
-
if (!isStringRecord(parsed.values) || !Array.isArray(parsed.associations) || !parsed.associations.every(isLegacyTempoChannelAssociation)) {
|
|
4560
|
-
throw new Error("unsupported Tempo channel store shape");
|
|
4253
|
+
function validateOnChainChannel(onChain, recipient, currency, amount) {
|
|
4254
|
+
if (onChain.deposit === 0n) {
|
|
4255
|
+
throw new ChannelNotFoundError({ reason: "channel not funded on-chain" });
|
|
4561
4256
|
}
|
|
4562
|
-
|
|
4563
|
-
|
|
4564
|
-
const associations = parsed.associations.map((association) => {
|
|
4565
|
-
const legacyKey = `${association.callerPubkey}:chan:${association.channelKey}`;
|
|
4566
|
-
const serialized = parsed.values?.[legacyKey];
|
|
4567
|
-
if (serialized === void 0) {
|
|
4568
|
-
throw new Error(`Tempo channel ${association.channelId} has no stored descriptor`);
|
|
4569
|
-
}
|
|
4570
|
-
const operator = serializedChannelOperator(serialized);
|
|
4571
|
-
values[channelStorageKey(association.callerPubkey, operator, `chan:${association.channelKey}`)] = serialized;
|
|
4572
|
-
consumed.add(legacyKey);
|
|
4573
|
-
return { ...association, operator };
|
|
4574
|
-
});
|
|
4575
|
-
return {
|
|
4576
|
-
version: 2,
|
|
4577
|
-
values: Object.fromEntries(Object.entries(values).filter(([key2]) => !consumed.has(key2))),
|
|
4578
|
-
associations,
|
|
4579
|
-
charges: Array.isArray(parsed.charges) ? parsed.charges.filter(isPendingTempoCharge) : []
|
|
4580
|
-
};
|
|
4581
|
-
}
|
|
4582
|
-
function channelStorageKey(callerPubkey, operator, key2) {
|
|
4583
|
-
return `${callerPubkey}:${operator}:${key2}`;
|
|
4584
|
-
}
|
|
4585
|
-
function serializedChannelOperator(value) {
|
|
4586
|
-
const parsed = JSON.parse(value);
|
|
4587
|
-
return normalizeTempoChannelOperator(parsed.descriptor?.operator);
|
|
4588
|
-
}
|
|
4589
|
-
function normalizeTempoChannelOperator(value) {
|
|
4590
|
-
if (value === void 0) return zeroAddress;
|
|
4591
|
-
if (typeof value !== "string" || !isAddress(value, { strict: false })) {
|
|
4592
|
-
throw new Error("invalid Tempo channel operator");
|
|
4257
|
+
if (onChain.finalized) {
|
|
4258
|
+
throw new ChannelClosedError({ reason: "channel is finalized on-chain" });
|
|
4593
4259
|
}
|
|
4594
|
-
|
|
4595
|
-
}
|
|
4596
|
-
function isStringRecord(value) {
|
|
4597
|
-
return !!value && typeof value === "object" && !Array.isArray(value) && Object.values(value).every((entry) => typeof entry === "string");
|
|
4598
|
-
}
|
|
4599
|
-
function isPendingTempoCharge(value) {
|
|
4600
|
-
if (!value || typeof value !== "object" || Array.isArray(value)) return false;
|
|
4601
|
-
const entry = value;
|
|
4602
|
-
return typeof entry.endpoint === "string" && typeof entry.callerPubkey === "string" && typeof entry.creditId === "string" && typeof entry.fundId === "string" && typeof entry.amountMicro === "number" && typeof entry.targetMicro === "number" && typeof entry.credential === "string" && typeof entry.signedMicro === "number" && typeof entry.amountMsats === "number" && typeof entry.btcRate === "number" && typeof entry.requestedAt === "number" && (entry.credentialValidBefore === void 0 || typeof entry.credentialValidBefore === "number");
|
|
4603
|
-
}
|
|
4604
|
-
function isTempoChannelAssociation(value) {
|
|
4605
|
-
if (!value || typeof value !== "object" || Array.isArray(value)) return false;
|
|
4606
|
-
const association = value;
|
|
4607
|
-
return typeof association.endpoint === "string" && typeof association.callerPubkey === "string" && typeof association.creditId === "string" && typeof association.channelKey === "string" && typeof association.operator === "string" && isAddress(association.operator, { strict: false }) && typeof association.channelId === "string" && typeof association.cumulativeAmount === "string" && typeof association.deposit === "string" && typeof association.chainId === "number" && typeof association.opened === "boolean" && typeof association.updatedAt === "number";
|
|
4608
|
-
}
|
|
4609
|
-
function isLegacyTempoChannelAssociation(value) {
|
|
4610
|
-
if (!value || typeof value !== "object" || Array.isArray(value)) return false;
|
|
4611
|
-
const association = value;
|
|
4612
|
-
return typeof association.endpoint === "string" && typeof association.callerPubkey === "string" && typeof association.creditId === "string" && typeof association.channelKey === "string" && typeof association.channelId === "string" && typeof association.cumulativeAmount === "string" && typeof association.deposit === "string" && typeof association.chainId === "number" && typeof association.opened === "boolean" && typeof association.updatedAt === "number";
|
|
4613
|
-
}
|
|
4614
|
-
var PAYMENT_RAIL_KEYS = ["cashu", "cashu_p2pk", "x402", "tempo"];
|
|
4615
|
-
function isPaymentRailKey(value) {
|
|
4616
|
-
return typeof value === "string" && PAYMENT_RAIL_KEYS.includes(value);
|
|
4617
|
-
}
|
|
4618
|
-
function fundingRailLabel(rail) {
|
|
4619
|
-
switch (rail) {
|
|
4620
|
-
case "cashu":
|
|
4621
|
-
return "ecash";
|
|
4622
|
-
case "lightning":
|
|
4623
|
-
return "Lightning";
|
|
4624
|
-
case "x402":
|
|
4625
|
-
return "x402 stablecoin";
|
|
4626
|
-
case "tempo":
|
|
4627
|
-
return "Tempo stablecoin";
|
|
4260
|
+
if (onChain.closeRequestedAt !== 0n) {
|
|
4261
|
+
throw new ChannelClosedError({ reason: "channel has a pending close request" });
|
|
4628
4262
|
}
|
|
4629
|
-
|
|
4630
|
-
|
|
4631
|
-
|
|
4632
|
-
|
|
4633
|
-
case "cashu_p2pk":
|
|
4634
|
-
return "ecash";
|
|
4635
|
-
case "x402":
|
|
4636
|
-
return "x402 stablecoin";
|
|
4637
|
-
case "tempo":
|
|
4638
|
-
return "Tempo stablecoin";
|
|
4263
|
+
if (onChain.payee.toLowerCase() !== recipient.toLowerCase()) {
|
|
4264
|
+
throw new VerificationFailedError({
|
|
4265
|
+
reason: "on-chain payee does not match server destination"
|
|
4266
|
+
});
|
|
4639
4267
|
}
|
|
4640
|
-
|
|
4641
|
-
|
|
4642
|
-
return rail === "lightning" ? "Lightning float" : fundingRailLabel(rail);
|
|
4643
|
-
}
|
|
4644
|
-
function railLabelAtSentenceStart(label) {
|
|
4645
|
-
return label === "ecash" ? "Ecash" : label;
|
|
4646
|
-
}
|
|
4647
|
-
function rpcEndpointSuffix(rail) {
|
|
4648
|
-
const url = rail.details?.rpc_url;
|
|
4649
|
-
return typeof url === "string" && url.length > 0 ? ` via ${url}` : "";
|
|
4650
|
-
}
|
|
4651
|
-
function rpcEndpointLine(rail) {
|
|
4652
|
-
const url = rail.details?.rpc_url;
|
|
4653
|
-
if (typeof url !== "string" || url.length === 0) return null;
|
|
4654
|
-
const source = rail.details?.rpc_source === "override" ? rpcOverrideEnvVar(rail.rail) : null;
|
|
4655
|
-
return `read from ${url} (${source ?? "bundled default"})`;
|
|
4656
|
-
}
|
|
4657
|
-
function unreachableRailDisplay(rail) {
|
|
4658
|
-
if (rail.error?.code === "x402_unsupported_network") {
|
|
4659
|
-
const network = rail.details?.network;
|
|
4660
|
-
return typeof network === "string" ? `x402 rail is configured for ${network}, a chain it can't settle on.` : "x402 rail is configured for a chain it can't settle on.";
|
|
4268
|
+
if (onChain.token.toLowerCase() !== currency.toLowerCase()) {
|
|
4269
|
+
throw new VerificationFailedError({ reason: "on-chain token does not match server token" });
|
|
4661
4270
|
}
|
|
4662
|
-
|
|
4663
|
-
|
|
4664
|
-
|
|
4665
|
-
|
|
4666
|
-
case "float_unauthorized":
|
|
4667
|
-
return "The Lightning wallet no longer recognises this connection \u2014 it looks revoked or expired.";
|
|
4668
|
-
case "float_connection_restricted":
|
|
4669
|
-
return "The Lightning wallet recognises this connection but won't let it do what the agent needs.";
|
|
4670
|
-
default:
|
|
4671
|
-
return null;
|
|
4271
|
+
if (amount !== void 0 && onChain.deposit - onChain.settled < amount) {
|
|
4272
|
+
throw new InsufficientBalanceError({
|
|
4273
|
+
reason: "channel available balance insufficient for requested amount"
|
|
4274
|
+
});
|
|
4672
4275
|
}
|
|
4673
4276
|
}
|
|
4674
|
-
function
|
|
4675
|
-
|
|
4676
|
-
|
|
4677
|
-
|
|
4678
|
-
return "Re-run 'dvm wallet connect' with the connection string piped in.";
|
|
4679
|
-
case "cashu":
|
|
4680
|
-
return "Check mint health with 'dvm wallet mint-health'.";
|
|
4681
|
-
case "x402":
|
|
4682
|
-
return "Check DVM_X402_RPC_URL, or ensure viem is installed.";
|
|
4683
|
-
case "tempo":
|
|
4684
|
-
return "Check DVM_TEMPO_RPC_URL, or ensure viem is installed.";
|
|
4277
|
+
async function verifyAndAcceptVoucher2(parameters) {
|
|
4278
|
+
const { store, minVoucherDelta, challenge, channel, channelId, voucher, onChain } = parameters;
|
|
4279
|
+
if (onChain.finalized) {
|
|
4280
|
+
throw new ChannelClosedError({ reason: "channel is finalized on-chain" });
|
|
4685
4281
|
}
|
|
4686
|
-
|
|
4687
|
-
|
|
4688
|
-
const force = opts.replacingConnectedKey ? " --force" : "";
|
|
4689
|
-
return `'dvm wallet tempo-connect --key-file <path>${force}', or DVM_TEMPO_KEY=<key> dvm wallet tempo-connect${force}`;
|
|
4690
|
-
}
|
|
4691
|
-
var TEMPO_EXIT_KEY_MISSING_HINT = `Reconnect that exact key (${tempoKeyImportRoutes({ replacingConnectedKey: false })}) before attempting an on-chain exit.`;
|
|
4692
|
-
function rpcOverrideEnvVar(rail) {
|
|
4693
|
-
switch (rail) {
|
|
4694
|
-
case "x402":
|
|
4695
|
-
return "DVM_X402_RPC_URL";
|
|
4696
|
-
case "tempo":
|
|
4697
|
-
return "DVM_TEMPO_RPC_URL";
|
|
4698
|
-
default:
|
|
4699
|
-
return null;
|
|
4282
|
+
if (onChain.closeRequestedAt !== 0n) {
|
|
4283
|
+
throw new ChannelClosedError({ reason: "channel has a pending close request" });
|
|
4700
4284
|
}
|
|
4701
|
-
|
|
4702
|
-
|
|
4703
|
-
return menu?.tempo?.methods.some(
|
|
4704
|
-
(candidate) => candidate.method === "tempo" && candidate.intent === "session"
|
|
4705
|
-
) === true;
|
|
4706
|
-
}
|
|
4707
|
-
function offersTempoCreditCharge(menu) {
|
|
4708
|
-
return menu?.tempo?.methods.some(
|
|
4709
|
-
(candidate) => candidate.method === "tempo" && candidate.intent === "charge"
|
|
4710
|
-
) === true;
|
|
4711
|
-
}
|
|
4712
|
-
function withholdsTempoCreditSession(menu) {
|
|
4713
|
-
return menu?.tempo?.withheld?.some(
|
|
4714
|
-
(candidate) => candidate.method === "tempo" && candidate.intent === "session"
|
|
4715
|
-
) === true;
|
|
4716
|
-
}
|
|
4717
|
-
function offersTempoCreditFunding(menu) {
|
|
4718
|
-
return offersTempoCreditSession(menu) || offersTempoCreditCharge(menu);
|
|
4719
|
-
}
|
|
4720
|
-
function createTempoCreditSession(args) {
|
|
4721
|
-
return session_exports.Client.session({
|
|
4722
|
-
account: privateKeyToAccount(args.account.privateKey),
|
|
4723
|
-
channelStore: createTempoChannelStore({
|
|
4724
|
-
endpoint: args.endpoint,
|
|
4725
|
-
callerPubkey: args.callerPubkey,
|
|
4726
|
-
creditId: args.creditId,
|
|
4727
|
-
operator: args.operator ?? zeroAddress
|
|
4728
|
-
}),
|
|
4729
|
-
maxDeposit: formatUnits(BigInt(args.maxDepositMicro), 6),
|
|
4730
|
-
topUpAmount: formatUnits(BigInt(args.topUpAmountMicro), 6),
|
|
4731
|
-
...args.getClient ? { getClient: args.getClient } : {}
|
|
4732
|
-
});
|
|
4733
|
-
}
|
|
4734
|
-
function createTempoSessionPaymentFetch(method, fetch) {
|
|
4735
|
-
return Mppx_exports.create({
|
|
4736
|
-
methods: [method],
|
|
4737
|
-
fetch,
|
|
4738
|
-
maxPaymentRetries: 5,
|
|
4739
|
-
polyfill: false
|
|
4740
|
-
}).fetch;
|
|
4741
|
-
}
|
|
4742
|
-
function tempoSessionChallengeChannelScope(challenge) {
|
|
4743
|
-
if (!challenge) return void 0;
|
|
4744
|
-
const request = challenge.request;
|
|
4745
|
-
if (typeof request?.recipient !== "string" || !isAddress(request.recipient, { strict: false }) || typeof request.currency !== "string" || !isAddress(request.currency, { strict: false })) {
|
|
4746
|
-
return void 0;
|
|
4285
|
+
if (onChain.deposit === 0n && onChain.payer !== zeroAddress) {
|
|
4286
|
+
throw new ChannelClosedError({ reason: "channel deposit is zero (settled)" });
|
|
4747
4287
|
}
|
|
4748
|
-
|
|
4749
|
-
|
|
4750
|
-
|
|
4751
|
-
|
|
4288
|
+
if (voucher.cumulativeAmount <= onChain.settled) {
|
|
4289
|
+
throw new VerificationFailedError({
|
|
4290
|
+
reason: "voucher cumulativeAmount is at or below on-chain settled amount"
|
|
4291
|
+
});
|
|
4752
4292
|
}
|
|
4753
|
-
|
|
4754
|
-
|
|
4755
|
-
);
|
|
4756
|
-
const escrow = challengeEscrow ?? session_exports.Precompile.Constants.tip20ChannelEscrow;
|
|
4757
|
-
const operator = methodDetails?.operator;
|
|
4758
|
-
if (operator !== void 0 && (typeof operator !== "string" || !isAddress(operator, { strict: false }))) {
|
|
4759
|
-
return void 0;
|
|
4293
|
+
if (voucher.cumulativeAmount > onChain.deposit) {
|
|
4294
|
+
throw new AmountExceedsDepositError({ reason: "voucher amount exceeds on-chain deposit" });
|
|
4760
4295
|
}
|
|
4761
|
-
|
|
4762
|
-
|
|
4763
|
-
|
|
4764
|
-
};
|
|
4765
|
-
}
|
|
4766
|
-
function tempoSessionCredentialChannelScope(credential) {
|
|
4767
|
-
try {
|
|
4768
|
-
return tempoSessionChallengeChannelScope(
|
|
4769
|
-
Credential_exports.deserialize(credential).challenge
|
|
4770
|
-
);
|
|
4771
|
-
} catch {
|
|
4772
|
-
return void 0;
|
|
4296
|
+
const isValid = await verifyVoucher2(channel.escrowContract, channel.chainId, voucher, channel.authorizedSigner);
|
|
4297
|
+
if (!isValid) {
|
|
4298
|
+
throw new InvalidSignatureError({ reason: "invalid voucher signature" });
|
|
4773
4299
|
}
|
|
4774
|
-
|
|
4775
|
-
|
|
4776
|
-
|
|
4777
|
-
|
|
4778
|
-
|
|
4779
|
-
|
|
4780
|
-
|
|
4781
|
-
}
|
|
4782
|
-
function tempoSessionPriorCumulativeMicro(args) {
|
|
4783
|
-
const association = args.association ?? loadTempoChannelAssociation(args.endpoint, args.callerPubkey, args.creditId);
|
|
4784
|
-
if (!association?.opened) return 0;
|
|
4785
|
-
const prior = BigInt(association.cumulativeAmount);
|
|
4786
|
-
if (prior < 0n || prior > BigInt(Number.MAX_SAFE_INTEGER)) {
|
|
4787
|
-
throw new DvmError("payment_invalid", "The Tempo channel's cumulative amount is out of range.");
|
|
4300
|
+
if (voucher.cumulativeAmount <= channel.highestVoucherAmount) {
|
|
4301
|
+
return createSessionReceipt({
|
|
4302
|
+
challengeId: challenge.id,
|
|
4303
|
+
channelId,
|
|
4304
|
+
acceptedCumulative: channel.highestVoucherAmount,
|
|
4305
|
+
spent: channel.spent,
|
|
4306
|
+
units: channel.units
|
|
4307
|
+
});
|
|
4788
4308
|
}
|
|
4789
|
-
|
|
4790
|
-
|
|
4791
|
-
|
|
4792
|
-
|
|
4793
|
-
|
|
4794
|
-
const explicitAllowance = BigInt(Math.max(args.allowanceMicro, args.amountMicro));
|
|
4795
|
-
const allowance = explicitAllowance > amount ? explicitAllowance : maxAdvertisedMicro(amount);
|
|
4796
|
-
const cap = prior + allowance;
|
|
4797
|
-
if (cap > BigInt(Number.MAX_SAFE_INTEGER)) {
|
|
4798
|
-
throw new DvmError("payment_invalid", "The Tempo session deposit cap is out of range.");
|
|
4309
|
+
const delta = voucher.cumulativeAmount - channel.highestVoucherAmount;
|
|
4310
|
+
if (delta < minVoucherDelta) {
|
|
4311
|
+
throw new DeltaTooSmallError({
|
|
4312
|
+
reason: `voucher delta ${delta} below minimum ${minVoucherDelta}`
|
|
4313
|
+
});
|
|
4799
4314
|
}
|
|
4800
|
-
|
|
4801
|
-
|
|
4802
|
-
|
|
4803
|
-
|
|
4804
|
-
|
|
4805
|
-
|
|
4806
|
-
|
|
4807
|
-
|
|
4808
|
-
|
|
4809
|
-
|
|
4810
|
-
args.callerPubkey,
|
|
4811
|
-
args.channelScope.operator,
|
|
4812
|
-
args.channelScope.channelKey
|
|
4813
|
-
) : loadTempoChannelAssociation(args.endpoint, args.callerPubkey, args.creditId))?.deposit ?? 0
|
|
4814
|
-
) : 0;
|
|
4815
|
-
const committedMicro = priorMicro + depositMicro;
|
|
4816
|
-
if (committedMicro <= args.capMicro) return;
|
|
4817
|
-
const committedUsd = committedMicro / 1e6;
|
|
4818
|
-
const capUsd = args.capMicro / 1e6;
|
|
4819
|
-
throw new DvmError(
|
|
4820
|
-
"tempo_session_deposit_exceeds_limit",
|
|
4821
|
-
`This Tempo session would lock $${formatUsd(committedUsd)} of channel collateral, above the $${formatUsd(capUsd)} this funding authorized.`,
|
|
4822
|
-
"Nothing was sent and no collateral moved. Fund a smaller amount, or ask the DVM operator why its session asks for a deposit this size.",
|
|
4823
|
-
{
|
|
4824
|
-
committed_usdc_microunits: String(committedMicro),
|
|
4825
|
-
max_usdc_microunits: String(args.capMicro),
|
|
4826
|
-
anchor: costAnchor(committedUsd),
|
|
4827
|
-
display: `Funding refused: the DVM's Tempo session would lock $${formatUsd(committedUsd)} of on-chain collateral, over the $${formatUsd(capUsd)} authorized for this funding.`
|
|
4315
|
+
const updated = await store.updateChannel(channelId, (current) => {
|
|
4316
|
+
if (!current)
|
|
4317
|
+
throw new ChannelNotFoundError({ reason: "channel not found" });
|
|
4318
|
+
if (voucher.cumulativeAmount > current.highestVoucherAmount) {
|
|
4319
|
+
return {
|
|
4320
|
+
...current,
|
|
4321
|
+
deposit: onChain.deposit,
|
|
4322
|
+
highestVoucherAmount: voucher.cumulativeAmount,
|
|
4323
|
+
highestVoucher: voucher
|
|
4324
|
+
};
|
|
4828
4325
|
}
|
|
4829
|
-
|
|
4830
|
-
}
|
|
4831
|
-
|
|
4832
|
-
|
|
4833
|
-
|
|
4834
|
-
|
|
4835
|
-
|
|
4836
|
-
|
|
4837
|
-
|
|
4838
|
-
|
|
4839
|
-
|
|
4840
|
-
"tempo_session_amount_exceeds_limit",
|
|
4841
|
-
`The DVM's Tempo session asks this funding to authorize $${formatUsd(advertisedUsd)}, more than 10% above the $${formatUsd(localUsd)} of credit it is buying.`,
|
|
4842
|
-
"No voucher was signed, so this DVM gained no authority to capture anything. If the funding had already opened or topped up its channel, that collateral is still yours \u2014 'dvm wallet balance' shows it and 'dvm wallet tempo-exit <dvm>' recovers it on-chain. Fund an amount this DVM prices, or ask its operator to check its BTC/USD rate.",
|
|
4843
|
-
{
|
|
4844
|
-
advertised_usdc_microunits: advertised.toString(),
|
|
4845
|
-
local_usdc_microunits: local.toString(),
|
|
4846
|
-
max_usdc_microunits: maxAdvertisedMicro(local).toString(),
|
|
4847
|
-
anchor: costAnchor(advertisedUsd),
|
|
4848
|
-
display: `Funding refused: the DVM's Tempo session wants a $${formatUsd(advertisedUsd)} voucher for $${formatUsd(localUsd)} of credit, over the 10% safety margin.`
|
|
4849
|
-
}
|
|
4850
|
-
);
|
|
4851
|
-
}
|
|
4326
|
+
return current;
|
|
4327
|
+
});
|
|
4328
|
+
if (!updated)
|
|
4329
|
+
throw new ChannelNotFoundError({ reason: "channel not found" });
|
|
4330
|
+
return createSessionReceipt({
|
|
4331
|
+
challengeId: challenge.id,
|
|
4332
|
+
channelId,
|
|
4333
|
+
acceptedCumulative: updated.highestVoucherAmount,
|
|
4334
|
+
spent: updated.spent,
|
|
4335
|
+
units: updated.units
|
|
4336
|
+
});
|
|
4852
4337
|
}
|
|
4853
|
-
function
|
|
4854
|
-
|
|
4855
|
-
|
|
4856
|
-
|
|
4857
|
-
|
|
4858
|
-
|
|
4859
|
-
|
|
4860
|
-
|
|
4861
|
-
|
|
4862
|
-
|
|
4863
|
-
|
|
4864
|
-
throw new DvmError("payment_invalid", "The Tempo session voucher amount is out of range.");
|
|
4865
|
-
}
|
|
4866
|
-
return Number(micro);
|
|
4867
|
-
}
|
|
4868
|
-
function assertTempoSessionVoucherWithinAsk(args) {
|
|
4869
|
-
const local = BigInt(Math.max(0, Math.round(args.basisMicro)));
|
|
4870
|
-
const authorized = BigInt(args.authorizedMicro);
|
|
4871
|
-
if (authorized <= 0n || withinAdvertisedTolerance(authorized, local)) return;
|
|
4872
|
-
const authorizedUsd = Number(authorized) / 1e6;
|
|
4873
|
-
const localUsd = Number(local) / 1e6;
|
|
4874
|
-
throw new DvmError(
|
|
4875
|
-
"tempo_session_amount_exceeds_limit",
|
|
4876
|
-
`This Tempo session voucher would let the DVM capture $${formatUsd(authorizedUsd)}, above the $${formatUsd(localUsd)} of credit this funding is buying.`,
|
|
4877
|
-
"The voucher never left this machine, so this DVM can capture nothing against it. Any channel collateral the funding already locked is still yours \u2014 'dvm wallet balance' shows it and 'dvm wallet tempo-exit <dvm>' recovers it on-chain. Fund an amount this DVM prices, or ask its operator why its session charges more than it quoted.",
|
|
4878
|
-
{
|
|
4879
|
-
advertised_usdc_microunits: authorized.toString(),
|
|
4880
|
-
local_usdc_microunits: local.toString(),
|
|
4881
|
-
max_usdc_microunits: maxAdvertisedMicro(local).toString(),
|
|
4882
|
-
anchor: costAnchor(authorizedUsd),
|
|
4883
|
-
display: `Funding refused: the DVM's Tempo session voucher would capture $${formatUsd(authorizedUsd)} for $${formatUsd(localUsd)} of credit, over the 10% safety margin.`
|
|
4338
|
+
async function handleOpen(store, client, challenge, payload, methodDetails, feePayer, isSponsored, feePayerPolicy, waitForConfirmation) {
|
|
4339
|
+
const channelId = normalizeChannelId(payload.channelId);
|
|
4340
|
+
const voucher = parseVoucherFromPayload2(channelId, payload.cumulativeAmount, payload.signature);
|
|
4341
|
+
const recipient = challenge.request.recipient;
|
|
4342
|
+
const currency = challenge.request.currency;
|
|
4343
|
+
const amount = challenge.request.amount ? BigInt(challenge.request.amount) : void 0;
|
|
4344
|
+
const validateOpenVoucher = async (onChain2) => {
|
|
4345
|
+
validateOnChainChannel(onChain2, recipient, currency, amount);
|
|
4346
|
+
const authorizedSigner3 = onChain2.authorizedSigner === "0x0000000000000000000000000000000000000000" ? onChain2.payer : onChain2.authorizedSigner;
|
|
4347
|
+
if (voucher.cumulativeAmount > onChain2.deposit) {
|
|
4348
|
+
throw new AmountExceedsDepositError({ reason: "voucher amount exceeds on-chain deposit" });
|
|
4884
4349
|
}
|
|
4885
|
-
|
|
4886
|
-
|
|
4887
|
-
|
|
4888
|
-
|
|
4889
|
-
const parsed = Credential_exports.deserialize(args.credential);
|
|
4890
|
-
const payload = parsed.payload;
|
|
4891
|
-
if (payload.action !== "open" || typeof payload.channelId !== "string" || typeof payload.cumulativeAmount !== "string" || !payload.descriptor || typeof payload.descriptor !== "object") {
|
|
4892
|
-
return false;
|
|
4350
|
+
if (voucher.cumulativeAmount <= onChain2.settled) {
|
|
4351
|
+
throw new VerificationFailedError({
|
|
4352
|
+
reason: "voucher cumulativeAmount is at or below on-chain settled amount"
|
|
4353
|
+
});
|
|
4893
4354
|
}
|
|
4894
|
-
const
|
|
4895
|
-
if (
|
|
4896
|
-
|
|
4897
|
-
|
|
4898
|
-
|
|
4899
|
-
|
|
4900
|
-
|
|
4901
|
-
|
|
4902
|
-
|
|
4903
|
-
|
|
4904
|
-
|
|
4905
|
-
|
|
4906
|
-
|
|
4907
|
-
|
|
4908
|
-
|
|
4909
|
-
|
|
4910
|
-
|
|
4911
|
-
|
|
4912
|
-
|
|
4913
|
-
|
|
4914
|
-
|
|
4915
|
-
|
|
4916
|
-
|
|
4355
|
+
const isValid = await verifyVoucher2(methodDetails.escrowContract, methodDetails.chainId, voucher, authorizedSigner3);
|
|
4356
|
+
if (!isValid) {
|
|
4357
|
+
throw new InvalidSignatureError({ reason: "invalid voucher signature" });
|
|
4358
|
+
}
|
|
4359
|
+
return authorizedSigner3;
|
|
4360
|
+
};
|
|
4361
|
+
const { onChain, txHash } = await broadcastOpenTransaction2({
|
|
4362
|
+
client,
|
|
4363
|
+
serializedTransaction: payload.transaction,
|
|
4364
|
+
escrowContract: methodDetails.escrowContract,
|
|
4365
|
+
channelId,
|
|
4366
|
+
recipient,
|
|
4367
|
+
currency,
|
|
4368
|
+
challengeExpires: challenge.expires,
|
|
4369
|
+
feePayerPolicy,
|
|
4370
|
+
feePayer,
|
|
4371
|
+
isSponsored,
|
|
4372
|
+
beforeBroadcast: async (pendingOnChain) => {
|
|
4373
|
+
await validateOpenVoucher(pendingOnChain);
|
|
4374
|
+
},
|
|
4375
|
+
waitForConfirmation
|
|
4376
|
+
});
|
|
4377
|
+
const authorizedSigner2 = await validateOpenVoucher(onChain);
|
|
4378
|
+
const updated = await store.updateChannel(channelId, (existing) => {
|
|
4379
|
+
if (existing) {
|
|
4380
|
+
if (voucher.cumulativeAmount <= existing.settledOnChain) {
|
|
4381
|
+
throw new VerificationFailedError({
|
|
4382
|
+
reason: "voucher amount is at or below settled on-chain amount"
|
|
4383
|
+
});
|
|
4384
|
+
}
|
|
4385
|
+
const settledOnChain = onChain.settled > existing.settledOnChain ? onChain.settled : existing.settledOnChain;
|
|
4386
|
+
const spent = settledOnChain > existing.spent ? settledOnChain : existing.spent;
|
|
4387
|
+
if (voucher.cumulativeAmount > existing.highestVoucherAmount) {
|
|
4388
|
+
return {
|
|
4389
|
+
...existing,
|
|
4390
|
+
deposit: onChain.deposit,
|
|
4391
|
+
settledOnChain,
|
|
4392
|
+
spent,
|
|
4393
|
+
highestVoucherAmount: voucher.cumulativeAmount,
|
|
4394
|
+
highestVoucher: voucher,
|
|
4395
|
+
authorizedSigner: authorizedSigner2
|
|
4396
|
+
};
|
|
4397
|
+
}
|
|
4398
|
+
return {
|
|
4399
|
+
...existing,
|
|
4400
|
+
deposit: onChain.deposit,
|
|
4401
|
+
settledOnChain,
|
|
4402
|
+
spent,
|
|
4403
|
+
authorizedSigner: authorizedSigner2
|
|
4404
|
+
};
|
|
4405
|
+
}
|
|
4406
|
+
return {
|
|
4917
4407
|
channelId,
|
|
4918
|
-
cumulativeAmount: BigInt(payload.cumulativeAmount),
|
|
4919
|
-
deposit: BigInt(depositMicro),
|
|
4920
|
-
descriptor,
|
|
4921
|
-
escrow,
|
|
4922
4408
|
chainId: methodDetails.chainId,
|
|
4923
|
-
|
|
4924
|
-
|
|
4925
|
-
|
|
4926
|
-
|
|
4927
|
-
|
|
4928
|
-
|
|
4929
|
-
|
|
4409
|
+
escrowContract: methodDetails.escrowContract,
|
|
4410
|
+
closeRequestedAt: onChain.closeRequestedAt,
|
|
4411
|
+
payer: onChain.payer,
|
|
4412
|
+
payee: onChain.payee,
|
|
4413
|
+
token: onChain.token,
|
|
4414
|
+
authorizedSigner: authorizedSigner2,
|
|
4415
|
+
deposit: onChain.deposit,
|
|
4416
|
+
settledOnChain: onChain.settled,
|
|
4417
|
+
highestVoucherAmount: voucher.cumulativeAmount,
|
|
4418
|
+
highestVoucher: voucher,
|
|
4419
|
+
spent: onChain.settled,
|
|
4420
|
+
units: 0,
|
|
4421
|
+
finalized: false,
|
|
4422
|
+
createdAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
4423
|
+
};
|
|
4424
|
+
});
|
|
4425
|
+
if (!updated)
|
|
4426
|
+
throw new VerificationFailedError({ reason: "failed to create channel" });
|
|
4427
|
+
return createSessionReceipt({
|
|
4428
|
+
challengeId: challenge.id,
|
|
4429
|
+
channelId: updated.channelId,
|
|
4430
|
+
acceptedCumulative: updated.highestVoucherAmount,
|
|
4431
|
+
spent: updated.spent,
|
|
4432
|
+
units: updated.units,
|
|
4433
|
+
txHash
|
|
4434
|
+
});
|
|
4930
4435
|
}
|
|
4931
|
-
function
|
|
4932
|
-
|
|
4933
|
-
const
|
|
4934
|
-
|
|
4935
|
-
|
|
4936
|
-
return challenge;
|
|
4937
|
-
}
|
|
4938
|
-
function tempoSessionChallengeMicro(challenge) {
|
|
4939
|
-
const advertised = challenge.request?.amount;
|
|
4940
|
-
if (typeof advertised !== "string" || !/^\d+$/.test(advertised)) {
|
|
4941
|
-
throw new DvmError(
|
|
4942
|
-
"payment_invalid",
|
|
4943
|
-
`The DVM advertised an unreadable Tempo session amount: '${String(advertised)}'.`,
|
|
4944
|
-
"Do not pay this. Ask the DVM operator to return a whole number of USDC micro-units."
|
|
4945
|
-
);
|
|
4946
|
-
}
|
|
4947
|
-
const micro = BigInt(advertised);
|
|
4948
|
-
if (micro > BigInt(Number.MAX_SAFE_INTEGER)) {
|
|
4949
|
-
throw new DvmError("payment_invalid", "The Tempo session challenge amount is out of range.");
|
|
4950
|
-
}
|
|
4951
|
-
return Number(micro);
|
|
4952
|
-
}
|
|
4953
|
-
async function createTempoCloseCredential(args) {
|
|
4954
|
-
const entry = await loadTempoChannelEntry(args.association);
|
|
4955
|
-
if (!entry) {
|
|
4956
|
-
throw new DvmError(
|
|
4957
|
-
"tempo_channel_not_found",
|
|
4958
|
-
`The Tempo channel for credit ${args.association.creditId} is missing locally.`,
|
|
4959
|
-
"Use 'dvm wallet tempo-exit <dvm>' only when the channel record is present; otherwise contact the DVM operator with the credit id."
|
|
4960
|
-
);
|
|
4961
|
-
}
|
|
4962
|
-
if (BigInt(args.cumulativeAmountMicro) > entry.cumulativeAmount) {
|
|
4963
|
-
throw new DvmError(
|
|
4964
|
-
"tempo_close_amount_unauthorized",
|
|
4965
|
-
`The DVM asked to close this Tempo channel at $${formatUsdcMicrounits(BigInt(args.cumulativeAmountMicro))}, above the $${formatUsdcMicrounits(entry.cumulativeAmount)} this wallet has authorized on it.`,
|
|
4966
|
-
`No credential was signed and nothing is stranded: run 'dvm wallet tempo-exit <dvm>' to recover the channel's unsettled balance on-chain, and tell the DVM's operator that its close request exceeded the caller's authorization.`
|
|
4967
|
-
);
|
|
4436
|
+
async function handleTopUp(store, client, challenge, payload, methodDetails, feePayer, isSponsored, feePayerPolicy) {
|
|
4437
|
+
const channelId = normalizeChannelId(payload.channelId);
|
|
4438
|
+
const channel = await store.getChannel(channelId);
|
|
4439
|
+
if (!channel) {
|
|
4440
|
+
throw new ChannelNotFoundError({ reason: "channel not found" });
|
|
4968
4441
|
}
|
|
4969
|
-
const
|
|
4970
|
-
|
|
4971
|
-
|
|
4972
|
-
|
|
4973
|
-
|
|
4442
|
+
const declaredDeposit = BigInt(payload.additionalDeposit);
|
|
4443
|
+
const { newDeposit: onChainDeposit } = await broadcastTopUpTransaction2({
|
|
4444
|
+
client,
|
|
4445
|
+
serializedTransaction: payload.transaction,
|
|
4446
|
+
escrowContract: methodDetails.escrowContract,
|
|
4447
|
+
channelId,
|
|
4448
|
+
currency: challenge.request.currency,
|
|
4449
|
+
declaredDeposit,
|
|
4450
|
+
previousDeposit: channel.deposit,
|
|
4451
|
+
challengeExpires: challenge.expires,
|
|
4452
|
+
feePayerPolicy,
|
|
4453
|
+
feePayer,
|
|
4454
|
+
isSponsored
|
|
4974
4455
|
});
|
|
4975
|
-
const
|
|
4976
|
-
|
|
4977
|
-
|
|
4978
|
-
|
|
4979
|
-
// unilateral-exit record until wallet tempo-exit independently confirms the
|
|
4980
|
-
// cooperative close on-chain and retires it.
|
|
4981
|
-
channelStore: {
|
|
4982
|
-
get: (key2) => durableStore.get(key2),
|
|
4983
|
-
set: (next) => durableStore.set(next),
|
|
4984
|
-
delete: () => void 0
|
|
4985
|
-
},
|
|
4986
|
-
...args.getClient ? { getClient: args.getClient } : {}
|
|
4456
|
+
const updated = await store.updateChannel(channelId, (current) => {
|
|
4457
|
+
if (!current)
|
|
4458
|
+
throw new ChannelNotFoundError({ reason: "channel not found" });
|
|
4459
|
+
return { ...current, deposit: onChainDeposit };
|
|
4987
4460
|
});
|
|
4988
|
-
return
|
|
4989
|
-
|
|
4990
|
-
|
|
4991
|
-
|
|
4992
|
-
|
|
4993
|
-
|
|
4994
|
-
}
|
|
4461
|
+
return createSessionReceipt({
|
|
4462
|
+
challengeId: challenge.id,
|
|
4463
|
+
channelId: updated?.channelId ?? channel.channelId,
|
|
4464
|
+
acceptedCumulative: updated?.highestVoucherAmount ?? channel.highestVoucherAmount,
|
|
4465
|
+
spent: updated?.spent ?? channel.spent,
|
|
4466
|
+
units: updated?.units ?? channel.units
|
|
4995
4467
|
});
|
|
4996
4468
|
}
|
|
4997
|
-
async function
|
|
4998
|
-
|
|
4999
|
-
|
|
5000
|
-
|
|
5001
|
-
|
|
5002
|
-
const unread = {
|
|
5003
|
-
retired: false,
|
|
5004
|
-
channelId: association.channelId,
|
|
5005
|
-
depositMicro: Number(association.deposit),
|
|
5006
|
-
settledMicro: 0
|
|
5007
|
-
};
|
|
5008
|
-
let entry;
|
|
5009
|
-
let state;
|
|
5010
|
-
try {
|
|
5011
|
-
({ entry, state } = await readTempoChannelState(args));
|
|
5012
|
-
} catch (err) {
|
|
5013
|
-
return { ...unread, status: "unreadable", error: asTempoReadError(err) };
|
|
5014
|
-
}
|
|
5015
|
-
const read = {
|
|
5016
|
-
status: classifyTempoChannelState(entry, state),
|
|
5017
|
-
channelId: entry.channelId,
|
|
5018
|
-
depositMicro: Number(state.deposit),
|
|
5019
|
-
settledMicro: Number(state.settled)
|
|
5020
|
-
};
|
|
5021
|
-
if (read.status !== "closed") return { ...read, retired: false };
|
|
5022
|
-
if (args.observeOnly) return { ...read, retired: false };
|
|
5023
|
-
try {
|
|
5024
|
-
const retired = await withTempoChannelLock(async () => {
|
|
5025
|
-
const current = loadTempoChannelAssociation(
|
|
5026
|
-
association.endpoint,
|
|
5027
|
-
association.callerPubkey,
|
|
5028
|
-
association.creditId
|
|
5029
|
-
);
|
|
5030
|
-
if (!current) return true;
|
|
5031
|
-
if (current.channelId.toLowerCase() !== association.channelId.toLowerCase()) return false;
|
|
5032
|
-
await retireTempoChannelScope(current);
|
|
5033
|
-
return true;
|
|
5034
|
-
});
|
|
5035
|
-
return { ...read, retired };
|
|
5036
|
-
} catch (err) {
|
|
5037
|
-
return { ...read, retired: false, error: asTempoReadError(err) };
|
|
4469
|
+
async function handleVoucher(store, client, minVoucherDelta, challenge, payload, methodDetails, channelStateTtl, lastOnChainVerified) {
|
|
4470
|
+
const channelId = normalizeChannelId(payload.channelId);
|
|
4471
|
+
const channel = await store.getChannel(channelId);
|
|
4472
|
+
if (!channel) {
|
|
4473
|
+
throw new ChannelNotFoundError({ reason: "channel not found" });
|
|
5038
4474
|
}
|
|
5039
|
-
|
|
5040
|
-
|
|
5041
|
-
const association = loadTempoChannelAssociation(
|
|
5042
|
-
args.association.endpoint,
|
|
5043
|
-
args.association.callerPubkey,
|
|
5044
|
-
args.association.creditId
|
|
5045
|
-
);
|
|
5046
|
-
if (association?.channelId.toLowerCase() !== args.association.channelId.toLowerCase()) {
|
|
5047
|
-
throw new DvmError(
|
|
5048
|
-
"tempo_channel_not_found",
|
|
5049
|
-
`No local Tempo channel entry remains for credit ${args.association.creditId}.`
|
|
5050
|
-
);
|
|
4475
|
+
if (channel.finalized) {
|
|
4476
|
+
throw new ChannelClosedError({ reason: "channel is finalized" });
|
|
5051
4477
|
}
|
|
5052
|
-
const
|
|
5053
|
-
|
|
5054
|
-
|
|
5055
|
-
|
|
5056
|
-
|
|
5057
|
-
|
|
5058
|
-
|
|
5059
|
-
|
|
5060
|
-
|
|
4478
|
+
const voucher = parseVoucherFromPayload2(channelId, payload.cumulativeAmount, payload.signature);
|
|
4479
|
+
const lastVerified = lastOnChainVerified.get(channelId) ?? 0;
|
|
4480
|
+
const isStale = Date.now() - lastVerified > channelStateTtl;
|
|
4481
|
+
const onChain = await (async () => {
|
|
4482
|
+
if (isStale) {
|
|
4483
|
+
const onChainChannel = await getOnChainChannel(client, channel.escrowContract, channelId);
|
|
4484
|
+
lastOnChainVerified.set(channelId, Date.now());
|
|
4485
|
+
if (onChainChannel.closeRequestedAt !== 0n) {
|
|
4486
|
+
await store.updateChannel(channelId, (current) => current ? { ...current, closeRequestedAt: onChainChannel.closeRequestedAt } : current);
|
|
4487
|
+
}
|
|
4488
|
+
return onChainChannel;
|
|
5061
4489
|
}
|
|
5062
|
-
throw new DvmError(
|
|
5063
|
-
"tempo_channel_not_found",
|
|
5064
|
-
`The Tempo channel record for credit ${association.creditId} has no stored descriptor.`,
|
|
5065
|
-
`Run 'dvm wallet tempo-exit ${association.endpoint} --abandon' to retire this unusable local record. Nothing will be broadcast, because there is no descriptor from which to address the escrow.`
|
|
5066
|
-
);
|
|
5067
|
-
}
|
|
5068
|
-
const identity = { channelId: entry.channelId, channelToken: entry.descriptor.token };
|
|
5069
|
-
const account = args.account;
|
|
5070
|
-
const controller = tempoDescriptorController(entry.descriptor);
|
|
5071
|
-
if (account && controller && !tempoChannelControlledBy(controller, account.address)) {
|
|
5072
|
-
if (!args.abandon) throw foreignChannelExitError(association, controller, account);
|
|
5073
|
-
await retireTempoChannelScope(association);
|
|
5074
4490
|
return {
|
|
5075
|
-
|
|
5076
|
-
|
|
5077
|
-
|
|
5078
|
-
|
|
5079
|
-
|
|
5080
|
-
|
|
5081
|
-
|
|
5082
|
-
|
|
5083
|
-
args.chain ?? session_exports.Precompile.Chain,
|
|
5084
|
-
rpc,
|
|
5085
|
-
entry.descriptor.token
|
|
5086
|
-
);
|
|
5087
|
-
let state = await chain.getChannelState(client, entry.channelId, entry.escrow);
|
|
5088
|
-
const amounts = () => {
|
|
5089
|
-
const authorized = entry.cumulativeAmount > state.settled ? entry.cumulativeAmount : state.settled;
|
|
5090
|
-
return {
|
|
5091
|
-
depositMicro: Number(state.deposit),
|
|
5092
|
-
settledMicro: Number(state.settled),
|
|
5093
|
-
guaranteedMicro: Number(state.deposit > authorized ? state.deposit - authorized : 0n),
|
|
5094
|
-
// Clamped because the escrow zeroes a withdrawn channel's deposit while
|
|
5095
|
-
// keeping its settled total, so a closed channel reads deposit 0 against
|
|
5096
|
-
// a positive settled and the raw subtraction goes negative.
|
|
5097
|
-
likelyMicro: Number(state.deposit > state.settled ? state.deposit - state.settled : 0n)
|
|
4491
|
+
finalized: channel.finalized,
|
|
4492
|
+
closeRequestedAt: channel.closeRequestedAt,
|
|
4493
|
+
payer: channel.payer,
|
|
4494
|
+
payee: channel.payee,
|
|
4495
|
+
token: channel.token,
|
|
4496
|
+
authorizedSigner: channel.authorizedSigner,
|
|
4497
|
+
deposit: channel.deposit,
|
|
4498
|
+
settled: channel.settledOnChain
|
|
5098
4499
|
};
|
|
5099
|
-
};
|
|
5100
|
-
|
|
5101
|
-
|
|
5102
|
-
|
|
5103
|
-
|
|
5104
|
-
|
|
5105
|
-
|
|
5106
|
-
|
|
5107
|
-
|
|
5108
|
-
|
|
5109
|
-
|
|
5110
|
-
|
|
5111
|
-
|
|
5112
|
-
|
|
5113
|
-
|
|
5114
|
-
|
|
5115
|
-
account ? `Run 'dvm wallet tempo-exit' without --abandon to close it and recover the collateral.` : `No Tempo key is connected, so this record could not be checked against one. Reconnect the key that opened this channel (${tempoKeyImportRoutes({ replacingConnectedKey: false })}) and run 'dvm wallet tempo-exit' without --abandon to recover the collateral. Retiring the record is offered only once a connected key shows the channel is not this wallet's.`
|
|
5116
|
-
);
|
|
4500
|
+
})();
|
|
4501
|
+
return verifyAndAcceptVoucher2({
|
|
4502
|
+
store,
|
|
4503
|
+
minVoucherDelta,
|
|
4504
|
+
challenge,
|
|
4505
|
+
channel,
|
|
4506
|
+
channelId,
|
|
4507
|
+
voucher,
|
|
4508
|
+
onChain
|
|
4509
|
+
});
|
|
4510
|
+
}
|
|
4511
|
+
async function handleClose(store, client, challenge, payload, methodDetails, account, feePayer) {
|
|
4512
|
+
const channelId = normalizeChannelId(payload.channelId);
|
|
4513
|
+
const channel = await store.getChannel(channelId);
|
|
4514
|
+
if (!channel) {
|
|
4515
|
+
throw new ChannelNotFoundError({ reason: "channel not found" });
|
|
5117
4516
|
}
|
|
5118
|
-
if (
|
|
5119
|
-
|
|
5120
|
-
const transactionOptions = {
|
|
5121
|
-
account: exitAccount,
|
|
5122
|
-
feePayer: exitAccount,
|
|
5123
|
-
candidateFeeTokens: [entry.descriptor.token]
|
|
5124
|
-
};
|
|
5125
|
-
if (state.closeRequestedAt === 0) {
|
|
5126
|
-
const hash22 = await chain.requestCloseOnChain(
|
|
5127
|
-
client,
|
|
5128
|
-
entry.descriptor,
|
|
5129
|
-
entry.escrow,
|
|
5130
|
-
transactionOptions
|
|
5131
|
-
);
|
|
5132
|
-
await chain.waitForSuccessfulReceipt(client, hash22);
|
|
5133
|
-
state = await chain.getChannelState(client, entry.channelId, entry.escrow);
|
|
5134
|
-
return {
|
|
5135
|
-
status: "close_requested",
|
|
5136
|
-
...identity,
|
|
5137
|
-
transactionHash: hash22,
|
|
5138
|
-
withdrawAvailableAt: (state.closeRequestedAt + 900) * 1e3,
|
|
5139
|
-
...amounts()
|
|
5140
|
-
};
|
|
4517
|
+
if (channel.finalized) {
|
|
4518
|
+
throw new ChannelClosedError({ reason: "channel is already finalized" });
|
|
5141
4519
|
}
|
|
5142
|
-
const
|
|
5143
|
-
const
|
|
5144
|
-
if (
|
|
5145
|
-
|
|
5146
|
-
status: "waiting",
|
|
5147
|
-
...identity,
|
|
5148
|
-
withdrawAvailableAt: withdrawAvailableAt * 1e3,
|
|
5149
|
-
...amounts()
|
|
5150
|
-
};
|
|
4520
|
+
const voucher = parseVoucherFromPayload2(channelId, payload.cumulativeAmount, payload.signature);
|
|
4521
|
+
const onChain = await getOnChainChannel(client, channel.escrowContract, channelId);
|
|
4522
|
+
if (onChain.finalized) {
|
|
4523
|
+
throw new ChannelClosedError({ reason: "channel is finalized on-chain" });
|
|
5151
4524
|
}
|
|
5152
|
-
|
|
5153
|
-
|
|
5154
|
-
|
|
5155
|
-
|
|
5156
|
-
entry.escrow,
|
|
5157
|
-
transactionOptions
|
|
5158
|
-
);
|
|
5159
|
-
await chain.waitForSuccessfulReceipt(client, hash2);
|
|
5160
|
-
state = await chain.getChannelState(client, entry.channelId, entry.escrow);
|
|
5161
|
-
await retireTempoChannelScope(association);
|
|
5162
|
-
return {
|
|
5163
|
-
status: "withdrawn",
|
|
5164
|
-
...identity,
|
|
5165
|
-
transactionHash: hash2,
|
|
5166
|
-
...withdrawnAmounts
|
|
5167
|
-
};
|
|
5168
|
-
}
|
|
5169
|
-
function foreignChannelExitError(association, controller, account) {
|
|
5170
|
-
const abandon = [
|
|
5171
|
-
"dvm wallet tempo-exit",
|
|
5172
|
-
shellQuoteArg(association.endpoint),
|
|
5173
|
-
"--credit-id",
|
|
5174
|
-
shellQuoteArg(association.creditId),
|
|
5175
|
-
"--abandon"
|
|
5176
|
-
].join(" ");
|
|
5177
|
-
return new DvmError(
|
|
5178
|
-
"tempo_wallet_mismatch",
|
|
5179
|
-
`The connected Tempo key ${account.address} is not the wallet recorded for the channel with ${association.endpoint} \u2014 that channel was opened by ${controller.payer}.`,
|
|
5180
|
-
// `--force` is live here and only here among the exit refusals: reaching
|
|
5181
|
-
// this error took a connected `account`, so the reconnect is a replacement
|
|
5182
|
-
// the import refuses without it.
|
|
5183
|
-
`Nothing was signed or broadcast, and the channel's collateral is untouched \u2014 only ${controller.payer} can move it. Reconnect that exact key (${tempoKeyImportRoutes({ replacingConnectedKey: true })}) and retry, or run '${abandon}' to retire the local record. Retiring it discards this machine's only descriptor for that channel, so restoring the key afterwards would no longer recover the collateral; the record blocks nothing while it stands.`,
|
|
5184
|
-
{
|
|
5185
|
-
anchor: "tempo_channel_payer_mismatch",
|
|
5186
|
-
endpoint: association.endpoint,
|
|
5187
|
-
credit_id: association.creditId,
|
|
5188
|
-
channel_id: association.channelId,
|
|
5189
|
-
recorded_payer: controller.payer,
|
|
5190
|
-
recorded_authorized_signer: controller.authorizedSigner,
|
|
5191
|
-
connected_payer: account.address
|
|
5192
|
-
}
|
|
5193
|
-
);
|
|
5194
|
-
}
|
|
5195
|
-
function tempoExitKeyMissingError() {
|
|
5196
|
-
return new DvmError(
|
|
5197
|
-
"tempo_wallet_missing",
|
|
5198
|
-
"The Tempo key that controls this channel is not connected.",
|
|
5199
|
-
TEMPO_EXIT_KEY_MISSING_HINT
|
|
5200
|
-
);
|
|
5201
|
-
}
|
|
5202
|
-
async function readTempoChannelState(args) {
|
|
5203
|
-
const entry = await loadTempoChannelEntry(args.association);
|
|
5204
|
-
if (!entry) {
|
|
5205
|
-
throw new DvmError(
|
|
5206
|
-
"tempo_channel_not_found",
|
|
5207
|
-
`The Tempo channel record for credit ${args.association.creditId} has no stored descriptor.`,
|
|
5208
|
-
`That channel can no longer be read or closed from here. Run 'dvm wallet tempo-exit ${args.association.endpoint} --abandon' to retire the unusable local record without broadcasting anything, then retry the wallet change.`
|
|
5209
|
-
);
|
|
4525
|
+
if (voucher.cumulativeAmount < channel.spent) {
|
|
4526
|
+
throw new VerificationFailedError({
|
|
4527
|
+
reason: `close voucher amount must be >= ${channel.spent} (spent)`
|
|
4528
|
+
});
|
|
5210
4529
|
}
|
|
5211
|
-
const
|
|
5212
|
-
|
|
5213
|
-
|
|
5214
|
-
|
|
5215
|
-
|
|
5216
|
-
() => chain.getChannelState(client, entry.channelId, entry.escrow)
|
|
5217
|
-
);
|
|
5218
|
-
return { entry, state };
|
|
5219
|
-
}
|
|
5220
|
-
function asTempoReadError(err) {
|
|
5221
|
-
if (err instanceof DvmError) return err;
|
|
5222
|
-
return new DvmError(
|
|
5223
|
-
"tempo_chain_read_failed",
|
|
5224
|
-
`The Tempo channel state could not be read: ${redactUrlsInText(
|
|
5225
|
-
err instanceof Error ? err.message : String(err)
|
|
5226
|
-
)}`
|
|
5227
|
-
);
|
|
5228
|
-
}
|
|
5229
|
-
function classifyTempoChannelState(entry, state) {
|
|
5230
|
-
if (state.deposit > 0n) return state.closeRequestedAt === 0 ? "open" : "closing";
|
|
5231
|
-
return entry.opened || state.settled > 0n || state.closeRequestedAt !== 0 ? "closed" : "unconfirmed";
|
|
5232
|
-
}
|
|
5233
|
-
async function guardTempoChannelRead(rpc, run) {
|
|
5234
|
-
try {
|
|
5235
|
-
return await run();
|
|
5236
|
-
} catch (err) {
|
|
5237
|
-
if (err instanceof DvmError) throw err;
|
|
5238
|
-
const cause = redactUrlsInText(err instanceof Error ? err.message : String(err));
|
|
5239
|
-
if (!isTransportFailure(err)) {
|
|
5240
|
-
throw new DvmError(
|
|
5241
|
-
"tempo_chain_read_failed",
|
|
5242
|
-
`The Tempo channel state could not be read: ${cause}`,
|
|
5243
|
-
"This failed on-chain rather than in transit, so changing DVM_TEMPO_RPC_URL will not help. The local channel record was kept; 'dvm wallet tempo-exit <dvm>' re-reads the chain and reports where the channel actually is."
|
|
5244
|
-
);
|
|
5245
|
-
}
|
|
5246
|
-
throw new DvmError(
|
|
5247
|
-
"tempo_rpc_error",
|
|
5248
|
-
`The Tempo channel state could not be read: ${cause}`,
|
|
5249
|
-
rpc.source === "override" ? `DVM_TEMPO_RPC_URL sent this read to ${redactUrl(rpc.url)}. Correct it, or unset it to fall back to Tempo's bundled endpoint, then re-run \u2014 the local channel record was kept until the chain can be read.` : `Verify connectivity to Tempo's bundled endpoint (${redactUrl(rpc.url)}), or send the read somewhere else with DVM_TEMPO_RPC_URL, then re-run \u2014 the local channel record was kept until the chain can be read.`
|
|
5250
|
-
);
|
|
4530
|
+
const isUntouchedZeroClose = voucher.cumulativeAmount === 0n && channel.spent === 0n && onChain.settled === 0n;
|
|
4531
|
+
if (!isUntouchedZeroClose && voucher.cumulativeAmount <= onChain.settled) {
|
|
4532
|
+
throw new VerificationFailedError({
|
|
4533
|
+
reason: `close voucher amount must be > ${onChain.settled} (on-chain settled)`
|
|
4534
|
+
});
|
|
5251
4535
|
}
|
|
5252
|
-
|
|
5253
|
-
|
|
5254
|
-
|
|
5255
|
-
|
|
5256
|
-
if (!chain) {
|
|
5257
|
-
throw new DvmError(
|
|
5258
|
-
"tempo_chain_unsupported",
|
|
5259
|
-
`The recorded Tempo channel uses unsupported chain ${String(chainId2)}.`
|
|
5260
|
-
);
|
|
4536
|
+
if (voucher.cumulativeAmount > onChain.deposit) {
|
|
4537
|
+
throw new AmountExceedsDepositError({
|
|
4538
|
+
reason: "close voucher amount exceeds on-chain deposit"
|
|
4539
|
+
});
|
|
5261
4540
|
}
|
|
5262
|
-
const
|
|
5263
|
-
|
|
5264
|
-
|
|
5265
|
-
);
|
|
5266
|
-
return { chain, url, source };
|
|
5267
|
-
}
|
|
5268
|
-
async function tempoPublicClient(rpc) {
|
|
5269
|
-
const { createPublicClient, http: http2 } = await import("./_esm-MN4BUYV6.js");
|
|
5270
|
-
const transportOptions = resolveRpcHttpTransportOptions(
|
|
5271
|
-
rpc.source,
|
|
5272
|
-
process.env.DVM_TEMPO_RPC_HEADERS_JSON
|
|
5273
|
-
);
|
|
5274
|
-
return createPublicClient({
|
|
5275
|
-
chain: rpc.chain,
|
|
5276
|
-
transport: transportOptions ? http2(rpc.url, transportOptions) : http2(rpc.url)
|
|
5277
|
-
});
|
|
5278
|
-
}
|
|
5279
|
-
async function tempoWalletClient(account, rpc) {
|
|
5280
|
-
const { createWalletClient, http: http2 } = await import("./_esm-MN4BUYV6.js");
|
|
5281
|
-
const transportOptions = resolveRpcHttpTransportOptions(
|
|
5282
|
-
rpc.source,
|
|
5283
|
-
process.env.DVM_TEMPO_RPC_HEADERS_JSON
|
|
5284
|
-
);
|
|
5285
|
-
return createWalletClient({
|
|
5286
|
-
account: privateKeyToAccount(account.privateKey),
|
|
5287
|
-
chain: rpc.chain,
|
|
5288
|
-
transport: transportOptions ? http2(rpc.url, transportOptions) : http2(rpc.url)
|
|
5289
|
-
});
|
|
5290
|
-
}
|
|
5291
|
-
function readSessionDeposit(credential) {
|
|
5292
|
-
let payload;
|
|
5293
|
-
try {
|
|
5294
|
-
payload = Credential_exports.deserialize(credential).payload;
|
|
5295
|
-
} catch {
|
|
5296
|
-
return { depositMicro: 0 };
|
|
4541
|
+
const isValid = await verifyVoucher2(channel.escrowContract, channel.chainId, voucher, channel.authorizedSigner);
|
|
4542
|
+
if (!isValid) {
|
|
4543
|
+
throw new InvalidSignatureError({ reason: "invalid voucher signature" });
|
|
5297
4544
|
}
|
|
5298
|
-
const
|
|
5299
|
-
|
|
5300
|
-
|
|
5301
|
-
|
|
4545
|
+
const pendingCloseStartedAt = BigInt(Math.floor(Date.now() / 1e3) || 1);
|
|
4546
|
+
const previousCloseRequestedAt = channel.closeRequestedAt;
|
|
4547
|
+
let pendingCloseMarked = false;
|
|
4548
|
+
await store.updateChannel(channelId, (current) => {
|
|
4549
|
+
if (!current)
|
|
4550
|
+
return null;
|
|
4551
|
+
if (current.finalized)
|
|
4552
|
+
throw new ChannelClosedError({ reason: "channel is already finalized" });
|
|
4553
|
+
if (current.closeRequestedAt !== 0n)
|
|
4554
|
+
throw new ChannelClosedError({ reason: "channel has a pending close request" });
|
|
4555
|
+
if (voucher.cumulativeAmount < current.spent) {
|
|
4556
|
+
throw new VerificationFailedError({
|
|
4557
|
+
reason: `close voucher amount must be >= ${current.spent} (spent)`
|
|
4558
|
+
});
|
|
5302
4559
|
}
|
|
5303
|
-
|
|
5304
|
-
|
|
5305
|
-
|
|
5306
|
-
|
|
5307
|
-
let calls = [];
|
|
4560
|
+
pendingCloseMarked = true;
|
|
4561
|
+
return { ...current, closeRequestedAt: pendingCloseStartedAt };
|
|
4562
|
+
});
|
|
4563
|
+
let txHash;
|
|
5308
4564
|
try {
|
|
5309
|
-
|
|
5310
|
-
|
|
5311
|
-
|
|
5312
|
-
|
|
5313
|
-
|
|
5314
|
-
|
|
5315
|
-
|
|
5316
|
-
|
|
5317
|
-
|
|
5318
|
-
|
|
5319
|
-
|
|
5320
|
-
|
|
5321
|
-
|
|
5322
|
-
return { action, depositMicro: depositAsMicro(decoded.args[3]) };
|
|
5323
|
-
} catch {
|
|
5324
|
-
continue;
|
|
4565
|
+
assertSettlementSender2({
|
|
4566
|
+
operation: "close",
|
|
4567
|
+
channelId: payload.channelId,
|
|
4568
|
+
payee: onChain.payee,
|
|
4569
|
+
sender: account?.address ?? client.account?.address
|
|
4570
|
+
});
|
|
4571
|
+
txHash = await closeOnChain2(client, channel.escrowContract, voucher, {
|
|
4572
|
+
...feePayer && account ? { feePayer, account } : { account },
|
|
4573
|
+
candidateFeeTokens: [channel.token]
|
|
4574
|
+
});
|
|
4575
|
+
} catch (error) {
|
|
4576
|
+
if (pendingCloseMarked) {
|
|
4577
|
+
await store.updateChannel(channelId, (current) => current && current.closeRequestedAt === pendingCloseStartedAt ? { ...current, closeRequestedAt: previousCloseRequestedAt } : current);
|
|
5325
4578
|
}
|
|
4579
|
+
throw error;
|
|
5326
4580
|
}
|
|
5327
|
-
|
|
5328
|
-
|
|
5329
|
-
|
|
5330
|
-
|
|
5331
|
-
|
|
5332
|
-
|
|
5333
|
-
|
|
5334
|
-
|
|
5335
|
-
|
|
5336
|
-
|
|
5337
|
-
|
|
5338
|
-
|
|
5339
|
-
|
|
5340
|
-
|
|
5341
|
-
|
|
5342
|
-
|
|
5343
|
-
|
|
5344
|
-
|
|
5345
|
-
|
|
5346
|
-
|
|
5347
|
-
|
|
5348
|
-
|
|
5349
|
-
"WebSocketRequestError"
|
|
5350
|
-
]);
|
|
5351
|
-
var TRANSPORT_ERROR_CODES = /* @__PURE__ */ new Set([
|
|
5352
|
-
"EAI_AGAIN",
|
|
5353
|
-
"ECONNREFUSED",
|
|
5354
|
-
"ECONNRESET",
|
|
5355
|
-
"ENOTFOUND",
|
|
5356
|
-
"EPIPE",
|
|
5357
|
-
"ETIMEDOUT"
|
|
5358
|
-
]);
|
|
5359
|
-
var REVERT_ERROR_NAMES = /* @__PURE__ */ new Set(["ContractFunctionRevertedError", "ExecutionRevertedError"]);
|
|
5360
|
-
var EXECUTION_REVERTED_RPC_CODE = 3;
|
|
5361
|
-
function isRevertLink(err) {
|
|
5362
|
-
if (REVERT_ERROR_NAMES.has(err.name)) return true;
|
|
5363
|
-
const { code } = err;
|
|
5364
|
-
return code === EXECUTION_REVERTED_RPC_CODE;
|
|
5365
|
-
}
|
|
5366
|
-
function isTransportLink(err) {
|
|
5367
|
-
if (TRANSPORT_ERROR_NAMES.has(err.name)) return true;
|
|
5368
|
-
const { code } = err;
|
|
5369
|
-
return typeof code === "string" && TRANSPORT_ERROR_CODES.has(code);
|
|
5370
|
-
}
|
|
5371
|
-
function isTransportFailure(err) {
|
|
5372
|
-
let transport = false;
|
|
5373
|
-
let cursor = err;
|
|
5374
|
-
for (let depth = 0; cursor instanceof Error && depth < 8; depth += 1) {
|
|
5375
|
-
if (isRevertLink(cursor)) return false;
|
|
5376
|
-
transport ||= isTransportLink(cursor);
|
|
5377
|
-
cursor = cursor.cause;
|
|
5378
|
-
}
|
|
5379
|
-
return transport;
|
|
4581
|
+
const updated = await store.updateChannel(channelId, (current) => {
|
|
4582
|
+
if (!current)
|
|
4583
|
+
return null;
|
|
4584
|
+
const updateVoucher = voucher.cumulativeAmount > current.highestVoucherAmount;
|
|
4585
|
+
return {
|
|
4586
|
+
...current,
|
|
4587
|
+
deposit: onChain.deposit,
|
|
4588
|
+
...updateVoucher && {
|
|
4589
|
+
highestVoucherAmount: voucher.cumulativeAmount,
|
|
4590
|
+
highestVoucher: voucher
|
|
4591
|
+
},
|
|
4592
|
+
finalized: true
|
|
4593
|
+
};
|
|
4594
|
+
});
|
|
4595
|
+
return createSessionReceipt({
|
|
4596
|
+
challengeId: challenge.id,
|
|
4597
|
+
channelId: updated?.channelId ?? channel.channelId,
|
|
4598
|
+
acceptedCumulative: voucher.cumulativeAmount,
|
|
4599
|
+
spent: updated?.spent ?? channel.spent,
|
|
4600
|
+
units: updated?.units ?? channel.units,
|
|
4601
|
+
...txHash !== void 0 && { txHash }
|
|
4602
|
+
});
|
|
5380
4603
|
}
|
|
5381
|
-
|
|
5382
|
-
|
|
5383
|
-
|
|
5384
|
-
|
|
5385
|
-
|
|
5386
|
-
|
|
5387
|
-
|
|
5388
|
-
|
|
5389
|
-
|
|
5390
|
-
|
|
5391
|
-
|
|
5392
|
-
|
|
5393
|
-
|
|
5394
|
-
|
|
5395
|
-
|
|
5396
|
-
|
|
5397
|
-
|
|
5398
|
-
|
|
5399
|
-
|
|
5400
|
-
|
|
5401
|
-
|
|
5402
|
-
|
|
4604
|
+
|
|
4605
|
+
// node_modules/mppx/dist/tempo/legacy/session/index.js
|
|
4606
|
+
var session_exports2 = {};
|
|
4607
|
+
__export(session_exports2, {
|
|
4608
|
+
Chain: () => Chain_exports2,
|
|
4609
|
+
Channel: () => Channel_exports2,
|
|
4610
|
+
Types: () => Types_exports,
|
|
4611
|
+
Voucher: () => Voucher_exports2
|
|
4612
|
+
});
|
|
4613
|
+
|
|
4614
|
+
// node_modules/mppx/dist/tempo/legacy/session/Types.js
|
|
4615
|
+
var Types_exports = {};
|
|
4616
|
+
|
|
4617
|
+
// node_modules/mppx/dist/tempo/subscription/index.js
|
|
4618
|
+
var subscription_exports = {};
|
|
4619
|
+
__export(subscription_exports, {
|
|
4620
|
+
createSubscriptionReceipt: () => createSubscriptionReceipt,
|
|
4621
|
+
fromRecord: () => fromRecord,
|
|
4622
|
+
fromStore: () => fromStore2,
|
|
4623
|
+
getSubscriptionRpcAllowedCalls: () => getSubscriptionRpcAllowedCalls,
|
|
4624
|
+
getSubscriptionScopes: () => getSubscriptionScopes,
|
|
4625
|
+
signSubscriptionKeyAuthorization: () => signSubscriptionKeyAuthorization,
|
|
4626
|
+
toSubscriptionExpiryDate: () => toSubscriptionExpiryDate,
|
|
4627
|
+
toSubscriptionExpirySeconds: () => toSubscriptionExpirySeconds,
|
|
4628
|
+
toSubscriptionPeriodSeconds: () => toSubscriptionPeriodSeconds,
|
|
4629
|
+
transferSelector: () => transferSelector,
|
|
4630
|
+
transferWithMemoSelector: () => transferWithMemoSelector,
|
|
4631
|
+
verifySubscriptionKeyAuthorization: () => verifySubscriptionKeyAuthorization
|
|
4632
|
+
});
|
|
4633
|
+
|
|
4634
|
+
// node_modules/mppx/dist/tempo/subscription/Receipt.js
|
|
4635
|
+
function createSubscriptionReceipt(parameters) {
|
|
5403
4636
|
return {
|
|
5404
|
-
|
|
5405
|
-
|
|
5406
|
-
|
|
5407
|
-
|
|
4637
|
+
method: "tempo",
|
|
4638
|
+
reference: parameters.reference,
|
|
4639
|
+
status: "success",
|
|
4640
|
+
subscriptionId: parameters.subscriptionId,
|
|
4641
|
+
timestamp: parameters.timestamp,
|
|
4642
|
+
...parameters.externalId ? { externalId: parameters.externalId } : {}
|
|
5408
4643
|
};
|
|
5409
4644
|
}
|
|
5410
|
-
|
|
5411
|
-
|
|
5412
|
-
|
|
5413
|
-
|
|
5414
|
-
|
|
5415
|
-
|
|
5416
|
-
|
|
5417
|
-
|
|
5418
|
-
|
|
5419
|
-
|
|
5420
|
-
|
|
5421
|
-
|
|
5422
|
-
|
|
5423
|
-
|
|
4645
|
+
function fromRecord(record) {
|
|
4646
|
+
return createSubscriptionReceipt(record);
|
|
4647
|
+
}
|
|
4648
|
+
|
|
4649
|
+
// node_modules/mppx/dist/tempo/subscription/Store.js
|
|
4650
|
+
var defaultRecordPrefix = "tempo:subscription:record:";
|
|
4651
|
+
var defaultKeyPrefix = "tempo:subscription:key:";
|
|
4652
|
+
var defaultActivationPrefix = "tempo:subscription:activation:";
|
|
4653
|
+
var defaultAccessKeyPrefix = "tempo:subscription:access-key:";
|
|
4654
|
+
var defaultCredentialPrefix = "tempo:subscription:credential:";
|
|
4655
|
+
var defaultActivationTimeoutMs = 15 * 60 * 1e3;
|
|
4656
|
+
var defaultRenewalTimeoutMs = 15 * 60 * 1e3;
|
|
4657
|
+
function fromStore2(store, options) {
|
|
4658
|
+
const { accessKeyPrefix = defaultAccessKeyPrefix, activationPrefix = defaultActivationPrefix, activationTimeoutMs = defaultActivationTimeoutMs, credentialPrefix = defaultCredentialPrefix, keyPrefix = defaultKeyPrefix, recordPrefix = defaultRecordPrefix, renewalTimeoutMs = defaultRenewalTimeoutMs } = options ?? {};
|
|
4659
|
+
function recordKey(subscriptionId) {
|
|
4660
|
+
return `${recordPrefix}${subscriptionId}`;
|
|
4661
|
+
}
|
|
4662
|
+
function activationKey(key2) {
|
|
4663
|
+
return `${activationPrefix}${key2}`;
|
|
4664
|
+
}
|
|
4665
|
+
function credentialKey(challengeId) {
|
|
4666
|
+
return `${credentialPrefix}${challengeId}`;
|
|
4667
|
+
}
|
|
4668
|
+
function accessKeyKey(key2) {
|
|
4669
|
+
return `${accessKeyPrefix}${key2}`;
|
|
4670
|
+
}
|
|
4671
|
+
function accessKeyAddressKey(address) {
|
|
4672
|
+
return `${accessKeyPrefix}address:${address.toLowerCase()}`;
|
|
4673
|
+
}
|
|
4674
|
+
function lookupRecordKey(key2) {
|
|
4675
|
+
return `${keyPrefix}${key2}`;
|
|
4676
|
+
}
|
|
4677
|
+
async function getByLookupKey(key2) {
|
|
4678
|
+
const subscriptionId = await store.get(lookupRecordKey(key2));
|
|
4679
|
+
if (!subscriptionId)
|
|
4680
|
+
return null;
|
|
4681
|
+
return await store.get(recordKey(subscriptionId));
|
|
5424
4682
|
}
|
|
5425
|
-
|
|
5426
|
-
|
|
5427
|
-
|
|
5428
|
-
|
|
5429
|
-
|
|
5430
|
-
|
|
5431
|
-
|
|
5432
|
-
|
|
5433
|
-
|
|
5434
|
-
|
|
5435
|
-
|
|
5436
|
-
|
|
5437
|
-
)
|
|
5438
|
-
);
|
|
5439
|
-
return records.filter((_, index) => controlled[index]);
|
|
5440
|
-
}
|
|
5441
|
-
var BLOCKING_ORDER = ["open", "closing", "unconfirmed", "unreadable"];
|
|
5442
|
-
function liveChannelError(association, chain, intent, blocking) {
|
|
5443
|
-
const depositMicro = chain.status === "unconfirmed" ? Number(association.deposit) : chain.depositMicro;
|
|
5444
|
-
const amount = `$${formatUsdcMicrounits(BigInt(depositMicro))}`;
|
|
5445
|
-
const message = chain.status === "open" ? `The connected Tempo key still holds ${amount} of collateral in an open channel with ${association.endpoint}.` : chain.status === "closing" ? `The connected Tempo key has ${amount} still escrowed on its channel with ${association.endpoint}, where a close has been requested on-chain and is in its 15-minute grace period.` : `The connected Tempo key signed an open committing ${amount} to a channel with ${association.endpoint} that the escrow has no record of, so that collateral may or may not be locked.`;
|
|
5446
|
-
const caller = findSigningIdentityByPubkey(association.callerPubkey);
|
|
5447
|
-
if (!caller) {
|
|
5448
|
-
return new DvmError(
|
|
5449
|
-
"tempo_channels_active",
|
|
5450
|
-
message,
|
|
5451
|
-
`Only this key can close that channel, but its caller identity (${association.callerPubkey}) is no longer configured. Restore that identity first, then retry the wallet ${intent === "replace" ? "replacement" : "disconnect"}; the key and channel record were left untouched.${remainingClause(blocking)}`,
|
|
5452
|
-
channelData(association, chain, depositMicro, blocking)
|
|
5453
|
-
);
|
|
4683
|
+
async function clearRenewalState(subscriptionId, periodIndex, attempt) {
|
|
4684
|
+
await store.update(recordKey(subscriptionId), (current) => {
|
|
4685
|
+
const subscription = current;
|
|
4686
|
+
if (!subscription || subscription.inFlightPeriod !== periodIndex || subscription.inFlightAttempt !== attempt) {
|
|
4687
|
+
return { op: "noop", result: void 0 };
|
|
4688
|
+
}
|
|
4689
|
+
return {
|
|
4690
|
+
op: "set",
|
|
4691
|
+
value: clearRenewal(subscription),
|
|
4692
|
+
result: void 0
|
|
4693
|
+
};
|
|
4694
|
+
});
|
|
5454
4695
|
}
|
|
5455
|
-
|
|
5456
|
-
|
|
5457
|
-
|
|
5458
|
-
|
|
5459
|
-
|
|
5460
|
-
|
|
5461
|
-
|
|
5462
|
-
// selectors keep every remedy pointed at the channel just named.
|
|
5463
|
-
`Empty the channel first \u2014 '${creditCommand("drain", association.endpoint, selectors)}' for the cooperative exit, or '${exit}' if the DVM is unavailable`
|
|
5464
|
-
) : chain.status === "closing" ? `'${exit}' withdraws what remains once the grace period ends` : `'${exit}' reads the chain and says which it is, and '${fund}' resumes a funding still pending for it. Once that open is known never to have landed, '${abandon}' retires the record`;
|
|
5465
|
-
return new DvmError(
|
|
5466
|
-
"tempo_channels_active",
|
|
5467
|
-
message,
|
|
5468
|
-
`Only this key can close that channel. ${remedy} \u2014 and ${intentClause(intent)}.${remainingClause(blocking)}`,
|
|
5469
|
-
channelData(association, chain, depositMicro, blocking)
|
|
5470
|
-
);
|
|
5471
|
-
}
|
|
5472
|
-
function tempoExitCommand(endpoint, selectors, abandon = false) {
|
|
5473
|
-
const parts = [
|
|
5474
|
-
"dvm wallet tempo-exit",
|
|
5475
|
-
shellQuoteArg(endpoint),
|
|
5476
|
-
"--credit-id",
|
|
5477
|
-
shellQuoteArg(selectors.creditId)
|
|
5478
|
-
];
|
|
5479
|
-
if (selectors.identityName !== void 0) {
|
|
5480
|
-
parts.push("--as", shellQuoteArg(selectors.identityName));
|
|
4696
|
+
async function clearActivationState(lookupKey, challengeId) {
|
|
4697
|
+
await store.update(activationKey(lookupKey), (current) => {
|
|
4698
|
+
const marker = current;
|
|
4699
|
+
if (marker?.challengeId !== challengeId)
|
|
4700
|
+
return { op: "noop", result: void 0 };
|
|
4701
|
+
return { op: "delete", result: void 0 };
|
|
4702
|
+
});
|
|
5481
4703
|
}
|
|
5482
|
-
|
|
5483
|
-
|
|
5484
|
-
|
|
5485
|
-
function creditCommand(verb, endpoint, selectors) {
|
|
5486
|
-
const parts = [
|
|
5487
|
-
`dvm credit ${verb}`,
|
|
5488
|
-
shellQuoteArg(endpoint),
|
|
5489
|
-
"--credit-id",
|
|
5490
|
-
shellQuoteArg(selectors.creditId)
|
|
5491
|
-
];
|
|
5492
|
-
if (selectors.identityName !== void 0) {
|
|
5493
|
-
parts.push("--as", shellQuoteArg(selectors.identityName));
|
|
4704
|
+
async function ownsActivation(lookupKey, challengeId) {
|
|
4705
|
+
const marker = await store.get(activationKey(lookupKey));
|
|
4706
|
+
return marker?.challengeId === challengeId;
|
|
5494
4707
|
}
|
|
5495
|
-
return
|
|
5496
|
-
}
|
|
5497
|
-
|
|
5498
|
-
|
|
5499
|
-
|
|
5500
|
-
|
|
5501
|
-
|
|
5502
|
-
|
|
5503
|
-
|
|
5504
|
-
|
|
5505
|
-
}
|
|
5506
|
-
|
|
5507
|
-
|
|
5508
|
-
|
|
5509
|
-
|
|
5510
|
-
|
|
4708
|
+
return {
|
|
4709
|
+
async activate({ challengeId, create, isReusable, lookupKey }) {
|
|
4710
|
+
const claimed = await store.update(credentialKey(challengeId), (current) => {
|
|
4711
|
+
if (current)
|
|
4712
|
+
return { op: "noop", result: false };
|
|
4713
|
+
return {
|
|
4714
|
+
op: "set",
|
|
4715
|
+
value: { claimedAt: timestamp() },
|
|
4716
|
+
result: true
|
|
4717
|
+
};
|
|
4718
|
+
});
|
|
4719
|
+
if (!claimed)
|
|
4720
|
+
return { status: "replayed" };
|
|
4721
|
+
const existing = await getByLookupKey(lookupKey);
|
|
4722
|
+
if (existing && isReusable?.(existing)) {
|
|
4723
|
+
return { status: "existing", subscription: existing };
|
|
4724
|
+
}
|
|
4725
|
+
const started = await store.update(activationKey(lookupKey), (current) => {
|
|
4726
|
+
const marker = current;
|
|
4727
|
+
if (marker && !isStaleActivation(marker, activationTimeoutMs)) {
|
|
4728
|
+
return { op: "noop", result: { status: "inFlight" } };
|
|
4729
|
+
}
|
|
4730
|
+
return {
|
|
4731
|
+
op: "set",
|
|
4732
|
+
value: {
|
|
4733
|
+
challengeId,
|
|
4734
|
+
startedAt: timestamp()
|
|
4735
|
+
},
|
|
4736
|
+
result: { status: "started" }
|
|
4737
|
+
};
|
|
4738
|
+
});
|
|
4739
|
+
if (started.status !== "started")
|
|
4740
|
+
return { status: "inFlight" };
|
|
4741
|
+
const claimedExisting = await getByLookupKey(lookupKey);
|
|
4742
|
+
if (claimedExisting && isReusable?.(claimedExisting)) {
|
|
4743
|
+
await clearActivationState(lookupKey, challengeId);
|
|
4744
|
+
return { status: "existing", subscription: claimedExisting };
|
|
4745
|
+
}
|
|
4746
|
+
const result = await create().catch(async (error) => {
|
|
4747
|
+
await clearActivationState(lookupKey, challengeId);
|
|
4748
|
+
throw error;
|
|
4749
|
+
});
|
|
4750
|
+
const { subscription } = result;
|
|
4751
|
+
const committed = await store.update(activationKey(subscription.lookupKey), (current) => {
|
|
4752
|
+
const marker = current;
|
|
4753
|
+
if (marker?.challengeId !== challengeId)
|
|
4754
|
+
return { op: "noop", result: false };
|
|
4755
|
+
return {
|
|
4756
|
+
op: "set",
|
|
4757
|
+
value: {
|
|
4758
|
+
...marker,
|
|
4759
|
+
committingAt: timestamp(),
|
|
4760
|
+
startedAt: timestamp()
|
|
4761
|
+
},
|
|
4762
|
+
result: true
|
|
4763
|
+
};
|
|
4764
|
+
});
|
|
4765
|
+
if (!committed) {
|
|
4766
|
+
await store.put(recordKey(subscription.subscriptionId), {
|
|
4767
|
+
...subscription,
|
|
4768
|
+
canceledAt: subscription.canceledAt ?? timestamp()
|
|
4769
|
+
});
|
|
4770
|
+
return { status: "claimMismatch" };
|
|
4771
|
+
}
|
|
4772
|
+
const previous = await getByLookupKey(subscription.lookupKey);
|
|
4773
|
+
if (previous && previous.subscriptionId !== subscription.subscriptionId) {
|
|
4774
|
+
if (!await ownsActivation(subscription.lookupKey, challengeId)) {
|
|
4775
|
+
return { status: "claimMismatch" };
|
|
4776
|
+
}
|
|
4777
|
+
await store.put(recordKey(previous.subscriptionId), {
|
|
4778
|
+
...previous,
|
|
4779
|
+
canceledAt: previous.canceledAt ?? timestamp()
|
|
4780
|
+
});
|
|
4781
|
+
}
|
|
4782
|
+
if (!await ownsActivation(subscription.lookupKey, challengeId)) {
|
|
4783
|
+
return { status: "claimMismatch" };
|
|
4784
|
+
}
|
|
4785
|
+
await store.put(recordKey(subscription.subscriptionId), subscription);
|
|
4786
|
+
if (!await ownsActivation(subscription.lookupKey, challengeId)) {
|
|
4787
|
+
return { status: "claimMismatch" };
|
|
4788
|
+
}
|
|
4789
|
+
await store.put(lookupRecordKey(subscription.lookupKey), subscription.subscriptionId);
|
|
4790
|
+
await clearActivationState(subscription.lookupKey, challengeId);
|
|
4791
|
+
return { status: "activated", result };
|
|
4792
|
+
},
|
|
4793
|
+
async get(subscriptionId) {
|
|
4794
|
+
return await store.get(recordKey(subscriptionId));
|
|
4795
|
+
},
|
|
4796
|
+
async getAccessKey(key2) {
|
|
4797
|
+
return await store.get(accessKeyKey(key2));
|
|
4798
|
+
},
|
|
4799
|
+
async getAccessKeyByAddress(address) {
|
|
4800
|
+
return await store.get(accessKeyAddressKey(address));
|
|
4801
|
+
},
|
|
4802
|
+
async getByKey(key2) {
|
|
4803
|
+
return getByLookupKey(key2);
|
|
4804
|
+
},
|
|
4805
|
+
async getOrCreateAccessKey(key2) {
|
|
4806
|
+
const existing = await store.get(accessKeyKey(key2));
|
|
4807
|
+
if (existing)
|
|
4808
|
+
return existing;
|
|
4809
|
+
const privateKey = Secp256k1_exports.randomPrivateKey();
|
|
4810
|
+
const account = Account_exports.fromSecp256k1(privateKey);
|
|
4811
|
+
const candidate = {
|
|
4812
|
+
accessKeyAddress: account.address.toLowerCase(),
|
|
4813
|
+
keyType: account.keyType,
|
|
4814
|
+
privateKey
|
|
4815
|
+
};
|
|
4816
|
+
return store.update(accessKeyKey(key2), (current) => {
|
|
4817
|
+
if (current) {
|
|
4818
|
+
return { op: "noop", result: current };
|
|
4819
|
+
}
|
|
4820
|
+
return { op: "set", value: candidate, result: candidate };
|
|
4821
|
+
}).then(async (record) => {
|
|
4822
|
+
await store.update(accessKeyAddressKey(record.accessKeyAddress), (current) => {
|
|
4823
|
+
if (current)
|
|
4824
|
+
return { op: "noop", result: void 0 };
|
|
4825
|
+
return { op: "set", value: record, result: void 0 };
|
|
4826
|
+
});
|
|
4827
|
+
return record;
|
|
4828
|
+
});
|
|
4829
|
+
},
|
|
4830
|
+
async put(record) {
|
|
4831
|
+
await store.put(recordKey(record.subscriptionId), record);
|
|
4832
|
+
await store.put(lookupRecordKey(record.lookupKey), record.subscriptionId);
|
|
4833
|
+
},
|
|
4834
|
+
async renew({ inFlightReference, periodIndex, renew, subscriptionId }) {
|
|
4835
|
+
const attempt = createAttemptToken();
|
|
4836
|
+
const started = await store.update(recordKey(subscriptionId), (current) => {
|
|
4837
|
+
const subscription = current;
|
|
4838
|
+
if (!subscription)
|
|
4839
|
+
return { op: "noop", result: { status: "missing" } };
|
|
4840
|
+
if (subscription.lastChargedPeriod >= periodIndex) {
|
|
4841
|
+
return {
|
|
4842
|
+
op: "noop",
|
|
4843
|
+
result: { status: "charged", subscription }
|
|
4844
|
+
};
|
|
4845
|
+
}
|
|
4846
|
+
if (subscription.inFlightPeriod !== void 0 && !isStaleRenewal(subscription, renewalTimeoutMs)) {
|
|
4847
|
+
return {
|
|
4848
|
+
op: "noop",
|
|
4849
|
+
result: { status: "inFlight", subscription }
|
|
4850
|
+
};
|
|
4851
|
+
}
|
|
4852
|
+
const next = {
|
|
4853
|
+
...subscription,
|
|
4854
|
+
inFlightAttempt: attempt,
|
|
4855
|
+
inFlightPeriod: periodIndex,
|
|
4856
|
+
inFlightReference,
|
|
4857
|
+
inFlightStartedAt: timestamp()
|
|
4858
|
+
};
|
|
4859
|
+
return {
|
|
4860
|
+
op: "set",
|
|
4861
|
+
value: next,
|
|
4862
|
+
result: { status: "started", subscription: next }
|
|
4863
|
+
};
|
|
4864
|
+
});
|
|
4865
|
+
if (started.status !== "started")
|
|
4866
|
+
return started;
|
|
4867
|
+
const active = await getByLookupKey(started.subscription.lookupKey);
|
|
4868
|
+
if (active?.subscriptionId !== subscriptionId) {
|
|
4869
|
+
await clearRenewalState(subscriptionId, periodIndex, attempt);
|
|
4870
|
+
return { status: "superseded", subscription: started.subscription };
|
|
4871
|
+
}
|
|
4872
|
+
const result = await renew({
|
|
4873
|
+
inFlightReference,
|
|
4874
|
+
periodIndex,
|
|
4875
|
+
subscription: started.subscription
|
|
4876
|
+
}).catch(async (error) => {
|
|
4877
|
+
await clearRenewalState(subscriptionId, periodIndex, attempt);
|
|
4878
|
+
throw error;
|
|
4879
|
+
});
|
|
4880
|
+
const activeAfterRenew = await getByLookupKey(result.subscription.lookupKey);
|
|
4881
|
+
if (activeAfterRenew?.subscriptionId !== subscriptionId) {
|
|
4882
|
+
await clearRenewalState(subscriptionId, periodIndex, attempt);
|
|
4883
|
+
return { status: "superseded", subscription: started.subscription };
|
|
4884
|
+
}
|
|
4885
|
+
const committed = await store.update(recordKey(subscriptionId), (current) => {
|
|
4886
|
+
const existing = current;
|
|
4887
|
+
if (!existing || existing.inFlightPeriod !== periodIndex || existing.inFlightAttempt !== attempt) {
|
|
4888
|
+
return { op: "noop", result: false };
|
|
4889
|
+
}
|
|
4890
|
+
const terminal = {
|
|
4891
|
+
...existing.canceledAt ? { canceledAt: existing.canceledAt } : {},
|
|
4892
|
+
...existing.revokedAt ? { revokedAt: existing.revokedAt } : {}
|
|
4893
|
+
};
|
|
4894
|
+
return {
|
|
4895
|
+
op: "set",
|
|
4896
|
+
value: clearRenewal({
|
|
4897
|
+
...result.subscription,
|
|
4898
|
+
...terminal,
|
|
4899
|
+
lastChargedPeriod: periodIndex,
|
|
4900
|
+
subscriptionId
|
|
4901
|
+
}),
|
|
4902
|
+
result: true
|
|
4903
|
+
};
|
|
4904
|
+
});
|
|
4905
|
+
if (!committed)
|
|
4906
|
+
return { status: "claimMismatch" };
|
|
4907
|
+
const ownsLookup = await store.update(lookupRecordKey(result.subscription.lookupKey), (current) => {
|
|
4908
|
+
if (current !== subscriptionId)
|
|
4909
|
+
return { op: "noop", result: false };
|
|
4910
|
+
return { op: "set", value: subscriptionId, result: true };
|
|
4911
|
+
});
|
|
4912
|
+
if (!ownsLookup)
|
|
4913
|
+
return { status: "superseded", subscription: started.subscription };
|
|
4914
|
+
return { status: "renewed", result };
|
|
4915
|
+
}
|
|
5511
4916
|
};
|
|
5512
|
-
|
|
5513
|
-
|
|
5514
|
-
|
|
5515
|
-
|
|
5516
|
-
|
|
5517
|
-
|
|
5518
|
-
|
|
5519
|
-
|
|
5520
|
-
|
|
5521
|
-
|
|
5522
|
-
|
|
5523
|
-
|
|
5524
|
-
|
|
5525
|
-
|
|
5526
|
-
|
|
5527
|
-
return new DvmError(
|
|
5528
|
-
"tempo_channel_not_found",
|
|
5529
|
-
message,
|
|
5530
|
-
`Run '${abandon}' to retire this unusable local record without broadcasting anything, then ${intentClause(intent)}.${remainingClause(blocking)}`,
|
|
5531
|
-
data
|
|
5532
|
-
);
|
|
5533
|
-
}
|
|
5534
|
-
function channelData(association, chain, depositMicro, blocking) {
|
|
4917
|
+
}
|
|
4918
|
+
function isStaleActivation(marker, timeoutMs) {
|
|
4919
|
+
if (!Number.isFinite(timeoutMs) || timeoutMs < 0)
|
|
4920
|
+
return false;
|
|
4921
|
+
if ("committingAt" in marker && marker.committingAt)
|
|
4922
|
+
return false;
|
|
4923
|
+
const startedAt = new Date(marker.startedAt ?? "").getTime();
|
|
4924
|
+
if (!Number.isFinite(startedAt))
|
|
4925
|
+
return true;
|
|
4926
|
+
return Date.now() - startedAt >= timeoutMs;
|
|
4927
|
+
}
|
|
4928
|
+
function isStaleRenewal(subscription, timeoutMs) {
|
|
4929
|
+
return isStaleActivation({ startedAt: subscription.inFlightStartedAt }, timeoutMs);
|
|
4930
|
+
}
|
|
4931
|
+
function clearRenewal(subscription) {
|
|
5535
4932
|
return {
|
|
5536
|
-
|
|
5537
|
-
|
|
5538
|
-
|
|
5539
|
-
|
|
5540
|
-
|
|
5541
|
-
chain_status: chain.status,
|
|
5542
|
-
deposit_micro: depositMicro,
|
|
5543
|
-
...chain.status === "unreadable" ? {} : { settled_micro: chain.settledMicro },
|
|
5544
|
-
// How many records are still in the way, so an agent knows whether clearing
|
|
5545
|
-
// the one named above is the whole job.
|
|
5546
|
-
blocking_channels: blocking
|
|
4933
|
+
...subscription,
|
|
4934
|
+
inFlightAttempt: void 0,
|
|
4935
|
+
inFlightPeriod: void 0,
|
|
4936
|
+
inFlightReference: void 0,
|
|
4937
|
+
inFlightStartedAt: void 0
|
|
5547
4938
|
};
|
|
5548
4939
|
}
|
|
5549
|
-
function
|
|
5550
|
-
return
|
|
4940
|
+
function timestamp() {
|
|
4941
|
+
return (/* @__PURE__ */ new Date()).toISOString();
|
|
5551
4942
|
}
|
|
5552
|
-
function
|
|
5553
|
-
return
|
|
4943
|
+
function createAttemptToken() {
|
|
4944
|
+
return globalThis.crypto.randomUUID();
|
|
5554
4945
|
}
|
|
5555
4946
|
|
|
5556
4947
|
export {
|
|
4948
|
+
Proof_exports,
|
|
5557
4949
|
session_exports,
|
|
5558
|
-
|
|
5559
|
-
|
|
5560
|
-
loadIdentities,
|
|
5561
|
-
saveIdentities,
|
|
5562
|
-
withIdentitiesLock,
|
|
5563
|
-
generateIdentity,
|
|
5564
|
-
deriveIdentityFromPrivkey,
|
|
5565
|
-
resolveSigningIdentity,
|
|
5566
|
-
findSigningIdentityByPubkey,
|
|
5567
|
-
shellQuoteArg,
|
|
5568
|
-
TEMPO_CHARGE_PENDING_STALE_MS,
|
|
5569
|
-
withTempoChannelLock,
|
|
5570
|
-
listTempoChannelAssociations,
|
|
5571
|
-
loadTempoChannelAssociation,
|
|
5572
|
-
loadTempoChannelEntry,
|
|
5573
|
-
loadTempoChannelController,
|
|
5574
|
-
tempoChannelControlledBy,
|
|
5575
|
-
tempoChargeCredentialSettleable,
|
|
5576
|
-
recordPendingTempoChargeFunding,
|
|
5577
|
-
loadResumableTempoChargeFunding,
|
|
5578
|
-
listResumableTempoChargeFundings,
|
|
5579
|
-
clearPendingTempoChargeFunding,
|
|
5580
|
-
isPaymentRailKey,
|
|
5581
|
-
fundingRailLabel,
|
|
5582
|
-
paymentRailLabel,
|
|
5583
|
-
probeRailLabel,
|
|
5584
|
-
railLabelAtSentenceStart,
|
|
5585
|
-
rpcEndpointSuffix,
|
|
5586
|
-
rpcEndpointLine,
|
|
5587
|
-
unreachableRailDisplay,
|
|
5588
|
-
nwcRejectionDisplay,
|
|
5589
|
-
unreachableRailHint,
|
|
5590
|
-
tempoKeyImportRoutes,
|
|
5591
|
-
TEMPO_EXIT_KEY_MISSING_HINT,
|
|
5592
|
-
offersTempoCreditSession,
|
|
5593
|
-
offersTempoCreditCharge,
|
|
5594
|
-
withholdsTempoCreditSession,
|
|
5595
|
-
offersTempoCreditFunding,
|
|
5596
|
-
createTempoCreditSession,
|
|
5597
|
-
createTempoSessionPaymentFetch,
|
|
5598
|
-
tempoSessionChallengeChannelScope,
|
|
5599
|
-
tempoSessionCredentialChannelScope,
|
|
5600
|
-
tempoSessionAssociationByKey,
|
|
5601
|
-
tempoSessionPriorCumulativeMicro,
|
|
5602
|
-
tempoSessionCumulativeCapMicro,
|
|
5603
|
-
assertTempoSessionDepositWithinCap,
|
|
5604
|
-
assertTempoSessionChallengeWithinAsk,
|
|
5605
|
-
tempoSessionCredentialCumulativeMicro,
|
|
5606
|
-
assertTempoSessionVoucherWithinAsk,
|
|
5607
|
-
persistTempoOpenCredential,
|
|
5608
|
-
tempoSessionChallenge,
|
|
5609
|
-
tempoSessionChallengeMicro,
|
|
5610
|
-
createTempoCloseCredential,
|
|
5611
|
-
advanceTempoChannelExit,
|
|
5612
|
-
reconcileTempoChannelOnChain,
|
|
5613
|
-
assertTempoWalletIdle
|
|
4950
|
+
legacy_exports,
|
|
4951
|
+
subscription_exports
|
|
5614
4952
|
};
|