@lucid-agents/taskmarket 1.45.0 → 1.47.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/dist/agent-compatibility.json +1 -1
- package/dist/{api-PZVGK3VQ.js → api-ENHCGR7K.js} +2 -2
- package/dist/{channels-LDMZ3OEM.js → channels-LX2DTMKZ.js} +4 -4
- package/dist/{chunk-PRYNO5S7.js → chunk-4MAQWPJ2.js} +1 -1
- package/dist/{chunk-QYXBVFVX.js → chunk-54J54BK7.js} +5 -5
- package/dist/{chunk-THIC75V5.js → chunk-AMT2L4BR.js} +3 -3
- package/dist/{chunk-5NILW5UT.js → chunk-AS6EFS2V.js} +2 -1
- package/dist/{chunk-6YFLKQ4Q.js → chunk-O53R76N3.js} +121 -18
- package/dist/{chunk-QUY6764O.js → chunk-PDVDVVVF.js} +2 -2
- package/dist/{chunk-JPVBWX3Q.js → chunk-PPJNXEWM.js} +3 -3
- package/dist/{chunk-XLJRCGOJ.js → chunk-RO5AHGHC.js} +1 -1
- package/dist/{chunk-KY4JM6NG.js → chunk-TUP4MTW6.js} +31 -13
- package/dist/{chunk-TPCXOWSC.js → chunk-V2BCPGOB.js} +8 -8
- package/dist/{chunk-FHDTYW6C.js → chunk-WOPSQ2GZ.js} +1 -1
- package/dist/{chunk-GIVPCMJ3.js → chunk-XRM455ZG.js} +670 -43
- package/dist/{doctor-HV5QQDGU.js → doctor-PEAKIDKS.js} +8 -8
- package/dist/index.js +345 -62
- package/dist/{launch-56RHQCWT.js → launch-CEJWCOQA.js} +11 -11
- package/dist/pi-extensions/xgate.cjs +7 -1
- package/dist/{read-auth-ZJBQQVGO.js → read-auth-524RVF3G.js} +3 -3
- package/dist/{reconcile-PQXSATCK.js → reconcile-GMYKLZTG.js} +4 -4
- package/dist/{status-EBMZGDFS.js → status-Y6JAL4DR.js} +8 -8
- package/dist/{sync-pull-423LBSPO.js → sync-pull-YFIWHI4H.js} +4 -4
- package/dist/{task-access-grants-KWTKM3NP.js → task-access-grants-GXJ6WOQK.js} +2 -2
- package/package.json +4 -4
|
@@ -1,14 +1,17 @@
|
|
|
1
1
|
import { createRequire as __tmCreateRequire } from 'node:module'; import { fileURLToPath as __tmFileURLToPath } from 'node:url'; import { dirname as __tmDirname } from 'node:path'; const require = __tmCreateRequire(import.meta.url); const __tmFilename = __tmFileURLToPath(import.meta.url); const __tmDirnameValue = __tmDirname(__tmFilename);
|
|
2
2
|
import {
|
|
3
|
+
MppReceiptSchema,
|
|
3
4
|
MppTempoChargeRequestSchema,
|
|
4
5
|
TEMPO_MAX_VALIDITY_WINDOW_SECONDS,
|
|
6
|
+
canonicalJson,
|
|
5
7
|
clampValidityWindowSeconds,
|
|
6
8
|
decodeMppJson,
|
|
9
|
+
encodeMppJson,
|
|
7
10
|
formatMppCredential,
|
|
8
11
|
getTaskmarketHome,
|
|
9
12
|
mppAttributionMemo,
|
|
10
13
|
parseMppChallenge
|
|
11
|
-
} from "./chunk-
|
|
14
|
+
} from "./chunk-O53R76N3.js";
|
|
12
15
|
|
|
13
16
|
// ../../packages/x402-payer/dist/api.js
|
|
14
17
|
var X402_PAYER_API_VERSION = 1;
|
|
@@ -18,6 +21,7 @@ var DEFAULT_X402_PAYER_LIMITS = Object.freeze({
|
|
|
18
21
|
maxResponseBodyBytes: 4194304,
|
|
19
22
|
maxChallengeBodyBytes: 65536
|
|
20
23
|
});
|
|
24
|
+
var X402_PAY_PROTOCOLS = ["auto", "x402", "mpp"];
|
|
21
25
|
|
|
22
26
|
// ../../packages/x402-payer/dist/payment-journal.js
|
|
23
27
|
import { randomUUID as randomUUID2 } from "crypto";
|
|
@@ -3832,6 +3836,184 @@ async function journaled(fn, details = {}) {
|
|
|
3832
3836
|
}
|
|
3833
3837
|
}
|
|
3834
3838
|
|
|
3839
|
+
// ../../packages/x402-payer/dist/mpp-challenge.js
|
|
3840
|
+
import { getAddress as getAddress5 } from "viem";
|
|
3841
|
+
import { z as z3 } from "zod";
|
|
3842
|
+
var MPP_TEMPO_CHARGE_SCHEME = "mpp-tempo-charge";
|
|
3843
|
+
var MPP_TEMPO_CHARGE_VALIDITY_SECONDS = 25;
|
|
3844
|
+
var MPP_CHALLENGE_MAX_HEADER_LENGTH = 16384;
|
|
3845
|
+
var MPP_CHALLENGE_MAX_COUNT = 16;
|
|
3846
|
+
var MAX_PARAM_LENGTH = 4096;
|
|
3847
|
+
var MPP_TEMPO_CHAIN_IDS = Object.freeze([4217, 42431]);
|
|
3848
|
+
var UINT256_MAX = 2n ** 256n - 1n;
|
|
3849
|
+
var ThirdPartyMppTempoChargeRequestSchema = z3.object({
|
|
3850
|
+
amount: z3.string().regex(/^(0|[1-9]\d{0,77})$/),
|
|
3851
|
+
currency: z3.string().regex(/^0x[0-9a-fA-F]{40}$/),
|
|
3852
|
+
recipient: z3.string().regex(/^0x[0-9a-fA-F]{40}$/),
|
|
3853
|
+
methodDetails: z3.object({
|
|
3854
|
+
chainId: z3.number().int().positive().optional(),
|
|
3855
|
+
feePayer: z3.boolean().optional(),
|
|
3856
|
+
supportedModes: z3.array(z3.string()).optional(),
|
|
3857
|
+
memo: z3.string().optional(),
|
|
3858
|
+
splits: z3.unknown().optional()
|
|
3859
|
+
}).passthrough().optional()
|
|
3860
|
+
}).passthrough();
|
|
3861
|
+
var TOKEN = /[!#$%&'*+.^_`|~0-9A-Za-z-]+/y;
|
|
3862
|
+
function splitChallenges(header) {
|
|
3863
|
+
const challenges = [];
|
|
3864
|
+
let current;
|
|
3865
|
+
let start = 0;
|
|
3866
|
+
const close = (end) => {
|
|
3867
|
+
if (current)
|
|
3868
|
+
current.raw = header.slice(start, end).replace(/[\s,]+$/, "");
|
|
3869
|
+
};
|
|
3870
|
+
let i = 0;
|
|
3871
|
+
while (i < header.length) {
|
|
3872
|
+
if (/[\s,]/.test(header[i])) {
|
|
3873
|
+
i++;
|
|
3874
|
+
continue;
|
|
3875
|
+
}
|
|
3876
|
+
const tokenStart = i;
|
|
3877
|
+
TOKEN.lastIndex = i;
|
|
3878
|
+
const token = TOKEN.exec(header);
|
|
3879
|
+
if (!token) {
|
|
3880
|
+
if (current)
|
|
3881
|
+
current.malformed = true;
|
|
3882
|
+
i++;
|
|
3883
|
+
continue;
|
|
3884
|
+
}
|
|
3885
|
+
i = TOKEN.lastIndex;
|
|
3886
|
+
while (header[i] === " " || header[i] === " ")
|
|
3887
|
+
i++;
|
|
3888
|
+
if (header[i] !== "=") {
|
|
3889
|
+
close(tokenStart);
|
|
3890
|
+
current = { scheme: token[0], params: {}, raw: "", malformed: false };
|
|
3891
|
+
start = tokenStart;
|
|
3892
|
+
challenges.push(current);
|
|
3893
|
+
continue;
|
|
3894
|
+
}
|
|
3895
|
+
i++;
|
|
3896
|
+
while (header[i] === " " || header[i] === " ")
|
|
3897
|
+
i++;
|
|
3898
|
+
let value;
|
|
3899
|
+
if (header[i] === '"') {
|
|
3900
|
+
let end = i + 1;
|
|
3901
|
+
let out = "";
|
|
3902
|
+
while (end < header.length && header[end] !== '"') {
|
|
3903
|
+
if (header[end] === "\\")
|
|
3904
|
+
end++;
|
|
3905
|
+
if (end < header.length)
|
|
3906
|
+
out += header[end];
|
|
3907
|
+
end++;
|
|
3908
|
+
}
|
|
3909
|
+
if (header[end] !== '"') {
|
|
3910
|
+
if (current)
|
|
3911
|
+
current.malformed = true;
|
|
3912
|
+
i = header.length;
|
|
3913
|
+
break;
|
|
3914
|
+
}
|
|
3915
|
+
value = out;
|
|
3916
|
+
i = end + 1;
|
|
3917
|
+
} else {
|
|
3918
|
+
const bare = /^[^\s,"]*/.exec(header.slice(i))[0];
|
|
3919
|
+
value = bare;
|
|
3920
|
+
i += bare.length;
|
|
3921
|
+
}
|
|
3922
|
+
if (!current || current.scheme.toLowerCase() !== "payment")
|
|
3923
|
+
continue;
|
|
3924
|
+
const name = token[0].toLowerCase();
|
|
3925
|
+
if (Object.hasOwn(current.params, name) || value.length > MAX_PARAM_LENGTH)
|
|
3926
|
+
current.malformed = true;
|
|
3927
|
+
else
|
|
3928
|
+
current.params[name] = value;
|
|
3929
|
+
}
|
|
3930
|
+
close(i);
|
|
3931
|
+
return challenges;
|
|
3932
|
+
}
|
|
3933
|
+
var RFC3339_INSTANT = /^\d{4}-\d{2}-\d{2}[Tt]\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:[Zz]|[+-]\d{2}:\d{2})$/;
|
|
3934
|
+
function readMppChallenges(header, now) {
|
|
3935
|
+
const none = { requirements: [], seen: false };
|
|
3936
|
+
if (!header || !/\bpayment\s/i.test(header))
|
|
3937
|
+
return none;
|
|
3938
|
+
const invalid3 = (message) => ({
|
|
3939
|
+
requirements: [],
|
|
3940
|
+
seen: true,
|
|
3941
|
+
failure: { code: "challenge_invalid", message }
|
|
3942
|
+
});
|
|
3943
|
+
if (header.length > MPP_CHALLENGE_MAX_HEADER_LENGTH)
|
|
3944
|
+
return invalid3(`The Payment challenge header exceeds ${MPP_CHALLENGE_MAX_HEADER_LENGTH} characters`);
|
|
3945
|
+
const payment = splitChallenges(header).filter((entry) => entry.scheme.toLowerCase() === "payment");
|
|
3946
|
+
if (payment.length === 0)
|
|
3947
|
+
return none;
|
|
3948
|
+
if (payment.length > MPP_CHALLENGE_MAX_COUNT)
|
|
3949
|
+
return invalid3(`The server sent more than ${MPP_CHALLENGE_MAX_COUNT} Payment challenges`);
|
|
3950
|
+
const requirements = [];
|
|
3951
|
+
let expired = 0;
|
|
3952
|
+
let malformed;
|
|
3953
|
+
for (const { params, raw, malformed: broken } of payment) {
|
|
3954
|
+
if (params["method"]?.toLowerCase() !== "tempo" || params["intent"]?.toLowerCase() !== "charge")
|
|
3955
|
+
continue;
|
|
3956
|
+
const { id, realm, request: encoded, expires } = params;
|
|
3957
|
+
if (broken || !id || !realm || !encoded) {
|
|
3958
|
+
malformed ??= "The server sent a malformed Payment challenge";
|
|
3959
|
+
continue;
|
|
3960
|
+
}
|
|
3961
|
+
let request;
|
|
3962
|
+
try {
|
|
3963
|
+
request = decodeMppJson(ThirdPartyMppTempoChargeRequestSchema, encoded);
|
|
3964
|
+
} catch {
|
|
3965
|
+
malformed ??= "The Payment challenge request is malformed";
|
|
3966
|
+
continue;
|
|
3967
|
+
}
|
|
3968
|
+
let expiresAt;
|
|
3969
|
+
if (expires !== void 0) {
|
|
3970
|
+
const expiresMs = RFC3339_INSTANT.test(expires) ? Date.parse(expires) : NaN;
|
|
3971
|
+
if (!Number.isFinite(expiresMs)) {
|
|
3972
|
+
malformed ??= "The Payment challenge expiry is malformed";
|
|
3973
|
+
continue;
|
|
3974
|
+
}
|
|
3975
|
+
if (expiresMs <= now.getTime()) {
|
|
3976
|
+
expired++;
|
|
3977
|
+
continue;
|
|
3978
|
+
}
|
|
3979
|
+
expiresAt = new Date(expiresMs).toISOString();
|
|
3980
|
+
}
|
|
3981
|
+
const details = request.methodDetails;
|
|
3982
|
+
const amount = BigInt(request.amount);
|
|
3983
|
+
if (details?.chainId === void 0 || !MPP_TEMPO_CHAIN_IDS.includes(details.chainId) || amount === 0n || amount > UINT256_MAX || details.supportedModes !== void 0 && !details.supportedModes.includes("pull") || details.splits !== void 0 || details.memo !== void 0)
|
|
3984
|
+
continue;
|
|
3985
|
+
const remaining = expiresAt === void 0 ? MPP_TEMPO_CHARGE_VALIDITY_SECONDS : Math.floor((Date.parse(expiresAt) - now.getTime()) / 1e3);
|
|
3986
|
+
const data = {
|
|
3987
|
+
challenge: params,
|
|
3988
|
+
raw,
|
|
3989
|
+
request,
|
|
3990
|
+
sponsored: details.feePayer === true,
|
|
3991
|
+
...expiresAt !== void 0 ? { expiresAt } : {}
|
|
3992
|
+
};
|
|
3993
|
+
requirements.push({
|
|
3994
|
+
scheme: MPP_TEMPO_CHARGE_SCHEME,
|
|
3995
|
+
network: `eip155:${details.chainId}`,
|
|
3996
|
+
// Normalized for policy matching only; sign from `extra.mpp` (see `MppRequirementData`).
|
|
3997
|
+
asset: getAddress5(request.currency.toLowerCase()),
|
|
3998
|
+
payTo: getAddress5(request.recipient.toLowerCase()),
|
|
3999
|
+
amount: amount.toString(),
|
|
4000
|
+
maxTimeoutSeconds: Math.max(1, Math.min(MPP_TEMPO_CHARGE_VALIDITY_SECONDS, remaining)),
|
|
4001
|
+
extra: { mpp: data }
|
|
4002
|
+
});
|
|
4003
|
+
}
|
|
4004
|
+
if (requirements.length > 0)
|
|
4005
|
+
return { requirements, seen: true };
|
|
4006
|
+
if (malformed)
|
|
4007
|
+
return invalid3(malformed);
|
|
4008
|
+
if (expired > 0)
|
|
4009
|
+
return {
|
|
4010
|
+
requirements,
|
|
4011
|
+
seen: true,
|
|
4012
|
+
failure: { code: "challenge_expired", message: "The Payment challenge has expired" }
|
|
4013
|
+
};
|
|
4014
|
+
return { requirements, seen: true };
|
|
4015
|
+
}
|
|
4016
|
+
|
|
3835
4017
|
// ../../packages/x402-payer/dist/selection.js
|
|
3836
4018
|
import { randomUUID as randomUUID5 } from "crypto";
|
|
3837
4019
|
function x402PrivateNetworkAllowed(input) {
|
|
@@ -3931,7 +4113,7 @@ function firstPartyAuthorization(input) {
|
|
|
3931
4113
|
windowStartedAt: new Date(now.getTime() - spendWindow.seconds * 1e3).toISOString()
|
|
3932
4114
|
};
|
|
3933
4115
|
}
|
|
3934
|
-
function selectX402Payment(input) {
|
|
4116
|
+
async function selectX402Payment(input) {
|
|
3935
4117
|
const offered = input.firstParty ? [
|
|
3936
4118
|
...input.rails.filter((rail) => rail.firstPartyOnly === true),
|
|
3937
4119
|
...input.rails.filter((rail) => rail.firstPartyOnly !== true)
|
|
@@ -4018,7 +4200,20 @@ function selectX402Payment(input) {
|
|
|
4018
4200
|
continue;
|
|
4019
4201
|
}
|
|
4020
4202
|
}
|
|
4021
|
-
authorized.
|
|
4203
|
+
const bestPriority = authorized.reduce((best, option) => Math.max(best, option.authorization.rule.priority), Number.NEGATIVE_INFINITY);
|
|
4204
|
+
const top = authorized.filter((option) => option.authorization.rule.priority === bestPriority);
|
|
4205
|
+
const affordable = /* @__PURE__ */ new Map();
|
|
4206
|
+
if (top.length > 1 && input.canAfford) {
|
|
4207
|
+
for (const option of top) {
|
|
4208
|
+
affordable.set(option, option.rail.canAfford ? await input.canAfford(option).catch(() => true) : true);
|
|
4209
|
+
}
|
|
4210
|
+
}
|
|
4211
|
+
const funded = (option) => affordable.get(option) === false ? 1 : 0;
|
|
4212
|
+
top.sort((left, right) => {
|
|
4213
|
+
const cost = BigInt(left.maxAmount) - BigInt(right.maxAmount);
|
|
4214
|
+
return funded(left) - funded(right) || (cost < 0n ? -1 : cost > 0n ? 1 : 0) || left.paymentIndex - right.paymentIndex || left.index - right.index;
|
|
4215
|
+
});
|
|
4216
|
+
authorized.splice(0, authorized.length, ...top);
|
|
4022
4217
|
if (authorized[0])
|
|
4023
4218
|
return authorized[0];
|
|
4024
4219
|
const denied = new X402PayError("No advertised x402 payment option is authorized by policy", {
|
|
@@ -4054,6 +4249,13 @@ function shortReason(value) {
|
|
|
4054
4249
|
return void 0;
|
|
4055
4250
|
return reason.length > FAILURE_REASON_MAX_LENGTH ? `${reason.slice(0, FAILURE_REASON_MAX_LENGTH)}...` : reason;
|
|
4056
4251
|
}
|
|
4252
|
+
var RAIL_SIGN_REFUSAL_CODES = /* @__PURE__ */ new Set([
|
|
4253
|
+
"challenge_invalid",
|
|
4254
|
+
"challenge_expired",
|
|
4255
|
+
"insufficient_balance",
|
|
4256
|
+
"payment_header_conflict",
|
|
4257
|
+
"request_failed"
|
|
4258
|
+
]);
|
|
4057
4259
|
function x402FailureReason(headers) {
|
|
4058
4260
|
const settlementHeader = headers.get("payment-response") ?? headers.get("x-payment-response");
|
|
4059
4261
|
if (settlementHeader) {
|
|
@@ -4298,13 +4500,44 @@ async function runX402Exchange(runtime, input, options, context) {
|
|
|
4298
4500
|
status: 402,
|
|
4299
4501
|
headers: Object.freeze(x402HeaderRecord(response.headers))
|
|
4300
4502
|
};
|
|
4503
|
+
const protocol = input.protocol ?? "auto";
|
|
4301
4504
|
let paymentRequired;
|
|
4302
|
-
|
|
4303
|
-
|
|
4304
|
-
|
|
4305
|
-
|
|
4505
|
+
if (firstParty || protocol !== "mpp") {
|
|
4506
|
+
try {
|
|
4507
|
+
paymentRequired = parseChallenge({ status: 402, headers: { ...challenge.headers }, body: challengeBody }, prepared.url, firstParty);
|
|
4508
|
+
} catch {
|
|
4509
|
+
paymentRequired = void 0;
|
|
4510
|
+
}
|
|
4511
|
+
if (paymentRequired?.accepts.some((option) => option.scheme === MPP_TEMPO_CHARGE_SCHEME)) {
|
|
4512
|
+
const accepts = paymentRequired.accepts.filter((option) => option.scheme !== MPP_TEMPO_CHARGE_SCHEME);
|
|
4513
|
+
paymentRequired = accepts.length > 0 ? { ...paymentRequired, accepts } : void 0;
|
|
4514
|
+
}
|
|
4306
4515
|
}
|
|
4307
|
-
const
|
|
4516
|
+
const mpp = !firstParty && protocol !== "x402" ? readMppChallenges(challenge.headers["www-authenticate"], runtime.now()) : void 0;
|
|
4517
|
+
if (paymentRequired && mpp && mpp.requirements.length > 0) {
|
|
4518
|
+
paymentRequired = {
|
|
4519
|
+
...paymentRequired,
|
|
4520
|
+
accepts: [...paymentRequired.accepts, ...mpp.requirements]
|
|
4521
|
+
};
|
|
4522
|
+
} else if (!paymentRequired) {
|
|
4523
|
+
if (mpp && mpp.requirements.length > 0) {
|
|
4524
|
+
paymentRequired = {
|
|
4525
|
+
x402Version: 2,
|
|
4526
|
+
resource: { url: prepared.url.toString() },
|
|
4527
|
+
accepts: mpp.requirements
|
|
4528
|
+
};
|
|
4529
|
+
} else if (mpp?.failure) {
|
|
4530
|
+
throw fail(mpp.failure.code, mpp.failure.message, { status: 402 });
|
|
4531
|
+
} else if (mpp?.seen) {
|
|
4532
|
+
throw fail("no_supported_rail", "No advertised MPP payment option can be paid", {
|
|
4533
|
+
status: 402
|
|
4534
|
+
});
|
|
4535
|
+
} else {
|
|
4536
|
+
throw fail("challenge_invalid", protocol === "mpp" ? "The response carries no Payment challenge" : "Invalid x402 payment challenge", { status: 402 });
|
|
4537
|
+
}
|
|
4538
|
+
}
|
|
4539
|
+
let payerAddress;
|
|
4540
|
+
const selection = await selectX402Payment({
|
|
4308
4541
|
rails,
|
|
4309
4542
|
paymentRequired,
|
|
4310
4543
|
policy,
|
|
@@ -4314,6 +4547,11 @@ async function runX402Exchange(runtime, input, options, context) {
|
|
|
4314
4547
|
invocationId,
|
|
4315
4548
|
now: runtime.now(),
|
|
4316
4549
|
firstParty,
|
|
4550
|
+
// The wallet is asked only when the policy leaves several options of equal standing.
|
|
4551
|
+
canAfford: async ({ requirement: requirement2, rail: rail2 }) => {
|
|
4552
|
+
payerAddress ??= getAccount().then((account2) => account2.address);
|
|
4553
|
+
return await rail2.canAfford?.({ requirement: requirement2, payer: await payerAddress, policy, signal }) ?? true;
|
|
4554
|
+
},
|
|
4317
4555
|
...allocation ? {
|
|
4318
4556
|
allocation: {
|
|
4319
4557
|
allocationId: allocation.id,
|
|
@@ -4348,7 +4586,8 @@ async function runX402Exchange(runtime, input, options, context) {
|
|
|
4348
4586
|
authorizedAmount: maxAmount,
|
|
4349
4587
|
policyRuleId: selection.transient ? void 0 : authorization.rule.id,
|
|
4350
4588
|
windowMaximum: authorization.payment.spendWindow.max,
|
|
4351
|
-
unattended: false
|
|
4589
|
+
unattended: false,
|
|
4590
|
+
...rail.feeTerms?.(requirement) ?? {}
|
|
4352
4591
|
};
|
|
4353
4592
|
let approved;
|
|
4354
4593
|
try {
|
|
@@ -4476,7 +4715,8 @@ async function runX402Exchange(runtime, input, options, context) {
|
|
|
4476
4715
|
url: prepared.url,
|
|
4477
4716
|
method: prepared.method,
|
|
4478
4717
|
requestFingerprint: prepared.requestHash,
|
|
4479
|
-
firstParty
|
|
4718
|
+
firstParty,
|
|
4719
|
+
headers: Object.freeze({ ...unpaidHeaders })
|
|
4480
4720
|
},
|
|
4481
4721
|
paymentRequired,
|
|
4482
4722
|
challenge,
|
|
@@ -4551,7 +4791,7 @@ async function runX402Exchange(runtime, input, options, context) {
|
|
|
4551
4791
|
await release(errorMessage(error), takeStaged());
|
|
4552
4792
|
if (signal.aborted)
|
|
4553
4793
|
throw aborted();
|
|
4554
|
-
throw fail("signer_unavailable", errorMessage(error), { cause: error });
|
|
4794
|
+
throw fail(error instanceof X402PayError && RAIL_SIGN_REFUSAL_CODES.has(error.code) ? error.code : "signer_unavailable", errorMessage(error), { cause: error });
|
|
4555
4795
|
}
|
|
4556
4796
|
try {
|
|
4557
4797
|
await transition({
|
|
@@ -4902,6 +5142,11 @@ function createX402Payer(config) {
|
|
|
4902
5142
|
headers: input.headers,
|
|
4903
5143
|
body: input.body
|
|
4904
5144
|
}, { firstPartyOrigin });
|
|
5145
|
+
if (input.protocol !== void 0 && !X402_PAY_PROTOCOLS.includes(input.protocol)) {
|
|
5146
|
+
throw new X402PayError("x402 protocol must be auto, x402 or mpp", {
|
|
5147
|
+
code: "invalid_request"
|
|
5148
|
+
});
|
|
5149
|
+
}
|
|
4905
5150
|
if (input.policyRuleId !== void 0 && typeof input.policyRuleId !== "string") {
|
|
4906
5151
|
throw new X402PayError("x402 policyRuleId must be a string", { code: "invalid_request" });
|
|
4907
5152
|
}
|
|
@@ -5098,7 +5343,7 @@ function createX402Payer(config) {
|
|
|
5098
5343
|
}
|
|
5099
5344
|
|
|
5100
5345
|
// ../../packages/x402-payer/dist/base-channel/runtime.js
|
|
5101
|
-
import { z as
|
|
5346
|
+
import { z as z4 } from "zod";
|
|
5102
5347
|
|
|
5103
5348
|
// ../../packages/x402-payer/dist/base-channel/store.js
|
|
5104
5349
|
import { createHash as createHash3, randomUUID as randomUUID6 } from "crypto";
|
|
@@ -5386,9 +5631,9 @@ function channelStatusFailure(status, body) {
|
|
|
5386
5631
|
function explainedByUnresolved(routerCharged, baseline, ceiling, unresolved) {
|
|
5387
5632
|
return routerCharged > baseline && routerCharged <= ceiling && unresolved.some((u) => BigInt(u.chargedBefore) === baseline && routerCharged <= baseline + BigInt(u.maximum));
|
|
5388
5633
|
}
|
|
5389
|
-
var purchaseStatusSchema =
|
|
5390
|
-
purchase_id:
|
|
5391
|
-
payment:
|
|
5634
|
+
var purchaseStatusSchema = z4.object({
|
|
5635
|
+
purchase_id: z4.string(),
|
|
5636
|
+
payment: z4.enum([
|
|
5392
5637
|
"awaiting_payment",
|
|
5393
5638
|
"pending",
|
|
5394
5639
|
"verified",
|
|
@@ -5396,7 +5641,7 @@ var purchaseStatusSchema = z3.object({
|
|
|
5396
5641
|
"collection_failed",
|
|
5397
5642
|
"unresolved"
|
|
5398
5643
|
]),
|
|
5399
|
-
inference:
|
|
5644
|
+
inference: z4.enum([
|
|
5400
5645
|
"awaiting_payment",
|
|
5401
5646
|
"admitted",
|
|
5402
5647
|
"dispatch_claimed",
|
|
@@ -5405,8 +5650,8 @@ var purchaseStatusSchema = z3.object({
|
|
|
5405
5650
|
"zero_charge",
|
|
5406
5651
|
"unresolved"
|
|
5407
5652
|
]),
|
|
5408
|
-
delivery:
|
|
5409
|
-
result_replay_available:
|
|
5653
|
+
delivery: z4.string(),
|
|
5654
|
+
result_replay_available: z4.literal(false)
|
|
5410
5655
|
}).strict();
|
|
5411
5656
|
function createChannelRuntime(config) {
|
|
5412
5657
|
const identity = channelIdentity(config.channel);
|
|
@@ -5451,7 +5696,7 @@ function createChannelRuntime(config) {
|
|
|
5451
5696
|
}
|
|
5452
5697
|
}
|
|
5453
5698
|
}
|
|
5454
|
-
async function
|
|
5699
|
+
async function http5(requestUrl, init, signal) {
|
|
5455
5700
|
if (requestUrl.origin !== url.origin)
|
|
5456
5701
|
throw invalidRequest("channel request left the pinned origin");
|
|
5457
5702
|
const policy = await config.loadPolicy({ allowMissing: false });
|
|
@@ -5547,7 +5792,7 @@ function createChannelRuntime(config) {
|
|
|
5547
5792
|
statusUrl.searchParams.set("network", identity.network);
|
|
5548
5793
|
if (!headers["x-channel-signature"] || !headers["x-channel-issued-at"])
|
|
5549
5794
|
throw outcomeUncertain("channel status request could not be signed");
|
|
5550
|
-
const response = await
|
|
5795
|
+
const response = await http5(statusUrl, { method: sync ? "POST" : "GET", headers }, signal);
|
|
5551
5796
|
if (response.status !== 200)
|
|
5552
5797
|
throw channelStatusFailure(response.status, response.body);
|
|
5553
5798
|
const parsed = statusSchema.safeParse(response.body);
|
|
@@ -5706,7 +5951,7 @@ function createChannelRuntime(config) {
|
|
|
5706
5951
|
funding,
|
|
5707
5952
|
account,
|
|
5708
5953
|
validateAllocation,
|
|
5709
|
-
http:
|
|
5954
|
+
http: http5,
|
|
5710
5955
|
syncReturns,
|
|
5711
5956
|
synchronize,
|
|
5712
5957
|
routerView,
|
|
@@ -5745,22 +5990,22 @@ function confirmationWait(config) {
|
|
|
5745
5990
|
sleep: input.sleep ?? abortableSleep
|
|
5746
5991
|
};
|
|
5747
5992
|
}
|
|
5748
|
-
var depositDataSchema =
|
|
5993
|
+
var depositDataSchema = z4.object({
|
|
5749
5994
|
nonce: hex32,
|
|
5750
|
-
amount:
|
|
5751
|
-
validBefore:
|
|
5752
|
-
afterBlock:
|
|
5995
|
+
amount: z4.string(),
|
|
5996
|
+
validBefore: z4.number(),
|
|
5997
|
+
afterBlock: z4.string().optional()
|
|
5753
5998
|
});
|
|
5754
|
-
var paymentDataSchema =
|
|
5755
|
-
purchaseId:
|
|
5756
|
-
statusToken:
|
|
5757
|
-
chargedBefore:
|
|
5758
|
-
maximum:
|
|
5759
|
-
sequence:
|
|
5760
|
-
refused:
|
|
5999
|
+
var paymentDataSchema = z4.object({
|
|
6000
|
+
purchaseId: z4.string(),
|
|
6001
|
+
statusToken: z4.string(),
|
|
6002
|
+
chargedBefore: z4.string(),
|
|
6003
|
+
maximum: z4.string(),
|
|
6004
|
+
sequence: z4.number(),
|
|
6005
|
+
refused: z4.boolean(),
|
|
5761
6006
|
deposit: depositDataSchema.nullable(),
|
|
5762
6007
|
/** Payer clock (unix seconds) when the voucher was signed; absent on older records. */
|
|
5763
|
-
signedAt:
|
|
6008
|
+
signedAt: z4.number().optional()
|
|
5764
6009
|
});
|
|
5765
6010
|
function depositProof(data) {
|
|
5766
6011
|
return data.deposit ? { ...data.deposit, nonce: data.deposit.nonce } : void 0;
|
|
@@ -7148,7 +7393,7 @@ function createBaseChannelPayer(inputConfig) {
|
|
|
7148
7393
|
|
|
7149
7394
|
// ../../packages/x402-payer/dist/taskmarket-fee-rail.js
|
|
7150
7395
|
import { randomBytes } from "crypto";
|
|
7151
|
-
import { getAddress as
|
|
7396
|
+
import { getAddress as getAddress6, toHex } from "viem";
|
|
7152
7397
|
var TASKMARKET_FEE_RAIL_ID = "taskmarket-fee";
|
|
7153
7398
|
var TRANSFER_WITH_AUTHORIZATION = [
|
|
7154
7399
|
{ name: "from", type: "address" },
|
|
@@ -7295,7 +7540,7 @@ function createTaskmarketFeeRail() {
|
|
|
7295
7540
|
resource: paymentRequired.resource,
|
|
7296
7541
|
requirement,
|
|
7297
7542
|
typedData,
|
|
7298
|
-
from:
|
|
7543
|
+
from: getAddress6(account.address),
|
|
7299
7544
|
signTypedData: (data) => account.signTypedData(data)
|
|
7300
7545
|
});
|
|
7301
7546
|
return {
|
|
@@ -7331,11 +7576,16 @@ function createTaskmarketFeeRail() {
|
|
|
7331
7576
|
};
|
|
7332
7577
|
}
|
|
7333
7578
|
|
|
7579
|
+
// ../../packages/x402-payer/dist/mpp-tempo-rail.js
|
|
7580
|
+
import { randomBytes as randomBytes3 } from "crypto";
|
|
7581
|
+
import { createPublicClient as createPublicClient4, defineChain as defineChain3, getAddress as getAddress8, http as http4, isAddressEqual as isAddressEqual2, keccak256 as keccak2562, parseAbiItem as parseAbiItem2 } from "viem";
|
|
7582
|
+
import { z as z5 } from "zod";
|
|
7583
|
+
|
|
7334
7584
|
// ../../packages/x402-payer/dist/mpp-tempo.js
|
|
7335
7585
|
import { randomBytes as randomBytes2 } from "crypto";
|
|
7336
7586
|
import { Signature } from "ox";
|
|
7337
7587
|
import { SignatureEnvelope, TxEnvelopeTempo } from "ox/tempo";
|
|
7338
|
-
import { encodeFunctionData as encodeFunctionData3, getAddress as
|
|
7588
|
+
import { encodeFunctionData as encodeFunctionData3, getAddress as getAddress7, isAddressEqual, maxUint256 } from "viem";
|
|
7339
7589
|
var MPP_TEMPO_DEFAULT_FEES = {
|
|
7340
7590
|
gas: 500000n,
|
|
7341
7591
|
maxFeePerGas: 20000000000n,
|
|
@@ -7368,7 +7618,7 @@ var TIP20_TRANSFER_ABI = [
|
|
|
7368
7618
|
];
|
|
7369
7619
|
async function signSponsoredTempoTransfer(input) {
|
|
7370
7620
|
const fees = { ...MPP_TEMPO_DEFAULT_FEES, ...input.fees };
|
|
7371
|
-
const to =
|
|
7621
|
+
const to = getAddress7(input.to);
|
|
7372
7622
|
const data = input.memo === void 0 ? encodeFunctionData3({
|
|
7373
7623
|
abi: TIP20_TRANSFER_ABI,
|
|
7374
7624
|
functionName: "transfer",
|
|
@@ -7380,15 +7630,17 @@ async function signSponsoredTempoTransfer(input) {
|
|
|
7380
7630
|
});
|
|
7381
7631
|
const envelope = TxEnvelopeTempo.from({
|
|
7382
7632
|
chainId: input.chainId,
|
|
7383
|
-
calls: [{ to:
|
|
7633
|
+
calls: [{ to: getAddress7(input.token), data }],
|
|
7384
7634
|
gas: fees.gas,
|
|
7385
7635
|
maxFeePerGas: fees.maxFeePerGas,
|
|
7386
7636
|
maxPriorityFeePerGas: fees.maxPriorityFeePerGas,
|
|
7387
7637
|
nonceKey: EXPIRING_NONCE_KEY,
|
|
7388
7638
|
nonce: 0n,
|
|
7389
7639
|
validBefore: input.validBefore,
|
|
7390
|
-
|
|
7391
|
-
|
|
7640
|
+
...input.feeToken === void 0 ? (
|
|
7641
|
+
// The sponsorship marker: the sender signs without committing to a fee payer or fee token.
|
|
7642
|
+
{ feePayerSignature: null }
|
|
7643
|
+
) : { feeToken: getAddress7(input.feeToken) }
|
|
7392
7644
|
});
|
|
7393
7645
|
let signature2;
|
|
7394
7646
|
try {
|
|
@@ -7400,12 +7652,12 @@ async function signSponsoredTempoTransfer(input) {
|
|
|
7400
7652
|
});
|
|
7401
7653
|
}
|
|
7402
7654
|
const envelopeSignature = SignatureEnvelope.from(Signature.from(signature2));
|
|
7403
|
-
if (input.format === "sender")
|
|
7655
|
+
if (input.format === "sender" || input.feeToken !== void 0)
|
|
7404
7656
|
return TxEnvelopeTempo.serialize(envelope, { signature: envelopeSignature });
|
|
7405
7657
|
return TxEnvelopeTempo.serialize(envelope, {
|
|
7406
7658
|
signature: envelopeSignature,
|
|
7407
7659
|
format: "feePayer",
|
|
7408
|
-
sender:
|
|
7660
|
+
sender: getAddress7(input.signer.address)
|
|
7409
7661
|
});
|
|
7410
7662
|
}
|
|
7411
7663
|
function challengeRefused(message) {
|
|
@@ -7461,12 +7713,384 @@ async function createMppTempoCredential(input) {
|
|
|
7461
7713
|
});
|
|
7462
7714
|
const authorization = formatMppCredential({
|
|
7463
7715
|
challenge,
|
|
7464
|
-
source: `did:pkh:eip155:${chainId}:${
|
|
7716
|
+
source: `did:pkh:eip155:${chainId}:${getAddress7(signer.address)}`,
|
|
7465
7717
|
payload: { type: "transaction", signature: transaction }
|
|
7466
7718
|
});
|
|
7467
7719
|
return { authorization, request, transaction, memo, validBefore };
|
|
7468
7720
|
}
|
|
7469
7721
|
|
|
7722
|
+
// ../../packages/x402-payer/dist/mpp-tempo-rail.js
|
|
7723
|
+
var MPP_TEMPO_CHARGE_RAIL_ID = "mpp-tempo-charge";
|
|
7724
|
+
var MPP_TEMPO_CHARGE_FEES = {
|
|
7725
|
+
...MPP_TEMPO_DEFAULT_FEES,
|
|
7726
|
+
gas: 400000n
|
|
7727
|
+
};
|
|
7728
|
+
var FEE_UNITS_PER_BASE_UNIT = 10n ** 12n;
|
|
7729
|
+
var SPONSORED_MIN_REMAINING_SECONDS = 15;
|
|
7730
|
+
var VALIDITY_SECONDS = 25;
|
|
7731
|
+
var MAX_LOG_RANGE = 100000n;
|
|
7732
|
+
var UNSPENT_CONFIRMATION_BLOCKS = 30n;
|
|
7733
|
+
var MAX_LOG_RANGES = 16;
|
|
7734
|
+
var AUTHORIZATION_KIND = "tempo-transfer-with-memo";
|
|
7735
|
+
var TRANSFER_WITH_MEMO = parseAbiItem2("event TransferWithMemo(address indexed from, address indexed to, uint256 amount, bytes32 indexed memo)");
|
|
7736
|
+
var BALANCE_OF = parseAbiItem2("function balanceOf(address account) view returns (uint256)");
|
|
7737
|
+
function viemReader(network, policy) {
|
|
7738
|
+
const rpcUrl = rpcUrlForNetwork(policy, network);
|
|
7739
|
+
const client = createPublicClient4({
|
|
7740
|
+
chain: defineChain3({
|
|
7741
|
+
id: evmChainIdOf(network),
|
|
7742
|
+
name: network,
|
|
7743
|
+
nativeCurrency: { name: "USD", symbol: "USD", decimals: 6 },
|
|
7744
|
+
rpcUrls: { default: { http: [rpcUrl] } }
|
|
7745
|
+
}),
|
|
7746
|
+
transport: http4(rpcUrl)
|
|
7747
|
+
});
|
|
7748
|
+
return {
|
|
7749
|
+
chainId: () => client.getChainId(),
|
|
7750
|
+
tokenBalance: (token, owner) => client.readContract({
|
|
7751
|
+
address: token,
|
|
7752
|
+
abi: [BALANCE_OF],
|
|
7753
|
+
functionName: "balanceOf",
|
|
7754
|
+
args: [owner]
|
|
7755
|
+
}),
|
|
7756
|
+
latestBlock: async () => {
|
|
7757
|
+
const block = await client.getBlock();
|
|
7758
|
+
return { number: block.number, timestamp: Number(block.timestamp) };
|
|
7759
|
+
},
|
|
7760
|
+
blockTimestamp: async (blockNumber) => Number((await client.getBlock({ blockNumber })).timestamp),
|
|
7761
|
+
transactionReceipt: async (hash) => {
|
|
7762
|
+
try {
|
|
7763
|
+
const receipt = await client.getTransactionReceipt({ hash });
|
|
7764
|
+
const attodollars = receipt.gasUsed * receipt.effectiveGasPrice;
|
|
7765
|
+
return {
|
|
7766
|
+
status: receipt.status === "success" ? "success" : "reverted",
|
|
7767
|
+
feeUnits: (attodollars + FEE_UNITS_PER_BASE_UNIT - 1n) / FEE_UNITS_PER_BASE_UNIT
|
|
7768
|
+
};
|
|
7769
|
+
} catch (error) {
|
|
7770
|
+
if (error instanceof Error && error.name === "TransactionReceiptNotFoundError")
|
|
7771
|
+
return void 0;
|
|
7772
|
+
throw error;
|
|
7773
|
+
}
|
|
7774
|
+
},
|
|
7775
|
+
transfersWithMemo: async ({ token, from, to, memo, fromBlock, toBlock }) => (await client.getLogs({
|
|
7776
|
+
address: token,
|
|
7777
|
+
event: TRANSFER_WITH_MEMO,
|
|
7778
|
+
args: { from, to, memo },
|
|
7779
|
+
fromBlock,
|
|
7780
|
+
toBlock
|
|
7781
|
+
})).map((log) => ({ amount: log.args.amount, transactionHash: log.transactionHash }))
|
|
7782
|
+
};
|
|
7783
|
+
}
|
|
7784
|
+
var ECHOED_PARAMS = [
|
|
7785
|
+
"id",
|
|
7786
|
+
"realm",
|
|
7787
|
+
"method",
|
|
7788
|
+
"intent",
|
|
7789
|
+
"request",
|
|
7790
|
+
"expires",
|
|
7791
|
+
"digest",
|
|
7792
|
+
"opaque",
|
|
7793
|
+
"description"
|
|
7794
|
+
];
|
|
7795
|
+
function refused(message) {
|
|
7796
|
+
return new X402PayError(message, { code: "challenge_invalid" });
|
|
7797
|
+
}
|
|
7798
|
+
function readCharge(requirement) {
|
|
7799
|
+
if (requirement.scheme !== MPP_TEMPO_CHARGE_SCHEME || !EVM_NETWORK_PATTERN.test(requirement.network))
|
|
7800
|
+
throw refused("Not an MPP tempo charge requirement");
|
|
7801
|
+
const chainId = evmChainIdOf(requirement.network);
|
|
7802
|
+
if (!MPP_TEMPO_CHAIN_IDS.includes(chainId))
|
|
7803
|
+
throw refused(`Chain ${chainId} is not a Tempo chain`);
|
|
7804
|
+
const mpp = requirement.extra?.["mpp"];
|
|
7805
|
+
if (!mpp || typeof mpp !== "object" || !mpp.challenge || typeof mpp.challenge !== "object")
|
|
7806
|
+
throw refused("The MPP challenge data is missing");
|
|
7807
|
+
const parsed = ThirdPartyMppTempoChargeRequestSchema.safeParse(mpp.request);
|
|
7808
|
+
if (!parsed.success)
|
|
7809
|
+
throw refused("The MPP charge request is malformed");
|
|
7810
|
+
const request = parsed.data;
|
|
7811
|
+
const details = request.methodDetails;
|
|
7812
|
+
const params = mpp.challenge;
|
|
7813
|
+
if (details?.chainId !== chainId || details.splits !== void 0 || details.memo !== void 0 || details.supportedModes !== void 0 && !details.supportedModes.includes("pull"))
|
|
7814
|
+
throw refused("The MPP charge is not a payable pull-mode charge on this chain");
|
|
7815
|
+
const amount = BigInt(request.amount);
|
|
7816
|
+
if (amount === 0n || requirement.amount !== amount.toString() || !isAddressEqual2(requirement.asset, request.currency) || !isAddressEqual2(requirement.payTo, request.recipient))
|
|
7817
|
+
throw refused("The MPP requirement does not match its charge request");
|
|
7818
|
+
if (Object.values(params).some((value) => typeof value !== "string") || !params["id"] || !params["realm"] || !params["request"] || params["method"]?.toLowerCase() !== "tempo" || params["intent"]?.toLowerCase() !== "charge")
|
|
7819
|
+
throw refused("The MPP challenge is malformed");
|
|
7820
|
+
let echoed;
|
|
7821
|
+
try {
|
|
7822
|
+
echoed = decodeMppJson(ThirdPartyMppTempoChargeRequestSchema, params["request"]);
|
|
7823
|
+
} catch {
|
|
7824
|
+
throw refused("The echoed Payment challenge request is malformed");
|
|
7825
|
+
}
|
|
7826
|
+
if (canonicalJson(echoed) !== canonicalJson(request))
|
|
7827
|
+
throw refused("The Payment challenge request differs from the charge being signed");
|
|
7828
|
+
const echoedExpiry = params["expires"] === void 0 ? void 0 : Date.parse(params["expires"]);
|
|
7829
|
+
if (echoedExpiry === void 0 !== (typeof mpp.expiresAt !== "string") || echoedExpiry !== void 0 && new Date(echoedExpiry).toISOString() !== mpp.expiresAt)
|
|
7830
|
+
throw refused("The Payment challenge expiry differs from the charge being signed");
|
|
7831
|
+
if (params["digest"] !== void 0)
|
|
7832
|
+
throw refused("A Payment challenge with a digest is not supported");
|
|
7833
|
+
const named = params["header"]?.toLowerCase();
|
|
7834
|
+
if (named !== void 0 && named !== "payment-authorization")
|
|
7835
|
+
throw refused("The Payment challenge names a credential header that is not supported");
|
|
7836
|
+
return {
|
|
7837
|
+
chainId,
|
|
7838
|
+
token: getAddress8(request.currency.toLowerCase()),
|
|
7839
|
+
recipient: getAddress8(request.recipient.toLowerCase()),
|
|
7840
|
+
amount,
|
|
7841
|
+
sponsored: details.feePayer === true,
|
|
7842
|
+
...typeof mpp.expiresAt === "string" ? { expiresAt: mpp.expiresAt } : {},
|
|
7843
|
+
header: named === "payment-authorization" ? "payment-authorization" : "authorization",
|
|
7844
|
+
challenge: params
|
|
7845
|
+
};
|
|
7846
|
+
}
|
|
7847
|
+
function worstCaseFee(fees) {
|
|
7848
|
+
const attodollars = fees.gas * fees.maxFeePerGas;
|
|
7849
|
+
return (attodollars + FEE_UNITS_PER_BASE_UNIT - 1n) / FEE_UNITS_PER_BASE_UNIT;
|
|
7850
|
+
}
|
|
7851
|
+
function chargeData(data) {
|
|
7852
|
+
if (!data || typeof data["memo"] !== "string" || !BYTES32_PATTERN.test(data["memo"]) || typeof data["validBefore"] !== "number" || typeof data["signedAt"] !== "number" || typeof data["headNumber"] !== "number" || typeof data["headTimestamp"] !== "number" || typeof data["sponsored"] !== "boolean" || data["txHash"] !== null && (typeof data["txHash"] !== "string" || !BYTES32_PATTERN.test(data["txHash"])) || typeof data["token"] !== "string" || typeof data["recipient"] !== "string" || typeof data["amount"] !== "string" || !/^\d+$/.test(data["amount"]))
|
|
7853
|
+
throw new Error("The MPP payment has no recorded memo, token, recipient and expiry");
|
|
7854
|
+
return data;
|
|
7855
|
+
}
|
|
7856
|
+
function createMppTempoChargeRail(options = {}) {
|
|
7857
|
+
const fees = { ...MPP_TEMPO_CHARGE_FEES, ...options.fees };
|
|
7858
|
+
const now = options.now ?? Date.now;
|
|
7859
|
+
const readerFor = options.reader ?? viemReader;
|
|
7860
|
+
const feeUnits = worstCaseFee(fees);
|
|
7861
|
+
async function reader(network, policy) {
|
|
7862
|
+
const chain = readerFor(network, policy);
|
|
7863
|
+
const rpcChainId = await chain.chainId();
|
|
7864
|
+
if (rpcChainId !== evmChainIdOf(network))
|
|
7865
|
+
throw new Error(`RPC chain id ${rpcChainId} does not match ${network}`);
|
|
7866
|
+
return chain;
|
|
7867
|
+
}
|
|
7868
|
+
return {
|
|
7869
|
+
id: MPP_TEMPO_CHARGE_RAIL_ID,
|
|
7870
|
+
kind: "per-request",
|
|
7871
|
+
supports(requirement) {
|
|
7872
|
+
return requirement.scheme === MPP_TEMPO_CHARGE_SCHEME && typeof requirement.network === "string" && EVM_NETWORK_PATTERN.test(requirement.network);
|
|
7873
|
+
},
|
|
7874
|
+
select(requirement) {
|
|
7875
|
+
const charge = readCharge(requirement);
|
|
7876
|
+
return { maxAmount: (charge.amount + (charge.sponsored ? 0n : feeUnits)).toString() };
|
|
7877
|
+
},
|
|
7878
|
+
async canAfford({ requirement, payer, policy }) {
|
|
7879
|
+
const charge = readCharge(requirement);
|
|
7880
|
+
try {
|
|
7881
|
+
const chain = await reader(requirement.network, policy);
|
|
7882
|
+
const balance = await chain.tokenBalance(charge.token, getAddress8(payer));
|
|
7883
|
+
return balance >= charge.amount + (charge.sponsored ? 0n : feeUnits);
|
|
7884
|
+
} catch {
|
|
7885
|
+
return true;
|
|
7886
|
+
}
|
|
7887
|
+
},
|
|
7888
|
+
feeTerms(requirement) {
|
|
7889
|
+
const charge = readCharge(requirement);
|
|
7890
|
+
return {
|
|
7891
|
+
feeSponsored: charge.sponsored,
|
|
7892
|
+
chargeAmount: charge.amount.toString(),
|
|
7893
|
+
maxFee: (charge.sponsored ? 0n : feeUnits).toString()
|
|
7894
|
+
};
|
|
7895
|
+
},
|
|
7896
|
+
async sign(context) {
|
|
7897
|
+
throwIfAborted(context.signal);
|
|
7898
|
+
const charge = readCharge(context.requirement);
|
|
7899
|
+
const { account } = context;
|
|
7900
|
+
if (context.request.headers?.[charge.header] !== void 0)
|
|
7901
|
+
throw new X402PayError(`The request already sets the ${charge.header} header the Payment challenge needs for its credential`, { code: "payment_header_conflict" });
|
|
7902
|
+
const nowSeconds = Math.floor(now() / 1e3);
|
|
7903
|
+
let remaining = VALIDITY_SECONDS;
|
|
7904
|
+
if (charge.expiresAt !== void 0) {
|
|
7905
|
+
const left = Math.floor(Date.parse(charge.expiresAt) / 1e3) - nowSeconds;
|
|
7906
|
+
if (!(left > 0) || charge.sponsored && left < SPONSORED_MIN_REMAINING_SECONDS)
|
|
7907
|
+
throw new X402PayError("The Payment challenge has expired", {
|
|
7908
|
+
code: "challenge_expired"
|
|
7909
|
+
});
|
|
7910
|
+
remaining = Math.min(remaining, left);
|
|
7911
|
+
}
|
|
7912
|
+
const validBefore = nowSeconds + remaining;
|
|
7913
|
+
const required = charge.amount + (charge.sponsored ? 0n : feeUnits);
|
|
7914
|
+
let balance;
|
|
7915
|
+
let head;
|
|
7916
|
+
try {
|
|
7917
|
+
const chain = await reader(context.requirement.network, context.policy);
|
|
7918
|
+
balance = await chain.tokenBalance(charge.token, getAddress8(account.address));
|
|
7919
|
+
head = await chain.latestBlock();
|
|
7920
|
+
} catch (error) {
|
|
7921
|
+
throw new X402PayError(`Could not read the wallet balance of token ${charge.token}`, {
|
|
7922
|
+
code: "request_failed",
|
|
7923
|
+
cause: error
|
|
7924
|
+
});
|
|
7925
|
+
}
|
|
7926
|
+
if (balance < required)
|
|
7927
|
+
throw new X402PayError(`The wallet holds ${balance} of token ${charge.token} and the payment needs ${required}${charge.sponsored ? "" : " including the network fee"}`, { code: "insufficient_balance" });
|
|
7928
|
+
throwIfAborted(context.signal);
|
|
7929
|
+
if (typeof account.sign !== "function")
|
|
7930
|
+
throw new X402PayError("The wallet cannot sign a Tempo transfer", {
|
|
7931
|
+
code: "signer_unavailable"
|
|
7932
|
+
});
|
|
7933
|
+
const sign = account.sign.bind(account);
|
|
7934
|
+
const memo = mppAttributionMemo({
|
|
7935
|
+
realm: charge.challenge["realm"],
|
|
7936
|
+
challengeId: charge.challenge["id"],
|
|
7937
|
+
// Random, so that the memo is unique per payment and reconcile can find exactly this one.
|
|
7938
|
+
client: randomBytes3(10).toString("hex")
|
|
7939
|
+
});
|
|
7940
|
+
const transaction = await signSponsoredTempoTransfer({
|
|
7941
|
+
signer: { address: account.address, sign },
|
|
7942
|
+
chainId: charge.chainId,
|
|
7943
|
+
token: charge.token,
|
|
7944
|
+
to: charge.recipient,
|
|
7945
|
+
amount: charge.amount,
|
|
7946
|
+
memo,
|
|
7947
|
+
validBefore,
|
|
7948
|
+
fees,
|
|
7949
|
+
...charge.sponsored ? {} : { feeToken: charge.token }
|
|
7950
|
+
});
|
|
7951
|
+
const txHash = charge.sponsored ? void 0 : keccak2562(transaction);
|
|
7952
|
+
const echoed = {};
|
|
7953
|
+
for (const name of ECHOED_PARAMS) {
|
|
7954
|
+
const value = charge.challenge[name];
|
|
7955
|
+
if (value !== void 0)
|
|
7956
|
+
echoed[name] = value;
|
|
7957
|
+
}
|
|
7958
|
+
const credential = encodeMppJson({
|
|
7959
|
+
challenge: echoed,
|
|
7960
|
+
source: `did:pkh:eip155:${charge.chainId}:${getAddress8(account.address)}`,
|
|
7961
|
+
payload: { type: "transaction", signature: transaction }
|
|
7962
|
+
});
|
|
7963
|
+
return {
|
|
7964
|
+
headers: { [charge.header]: `Payment ${credential}` },
|
|
7965
|
+
nonce: memo,
|
|
7966
|
+
authorizationKind: AUTHORIZATION_KIND,
|
|
7967
|
+
authorizationExpiresAt: new Date(validBefore * 1e3).toISOString(),
|
|
7968
|
+
// A wallet-paid transaction goes to the chain as signed, so its hash is known now and
|
|
7969
|
+
// tells a failed broadcast (fee burned, no memo log) from one that never landed.
|
|
7970
|
+
...charge.sponsored ? {} : { commitment: txHash },
|
|
7971
|
+
data: {
|
|
7972
|
+
txHash: txHash ?? null,
|
|
7973
|
+
sponsored: charge.sponsored,
|
|
7974
|
+
headNumber: Number(head.number),
|
|
7975
|
+
headTimestamp: head.timestamp,
|
|
7976
|
+
memo,
|
|
7977
|
+
validBefore,
|
|
7978
|
+
signedAt: nowSeconds,
|
|
7979
|
+
token: charge.token,
|
|
7980
|
+
recipient: charge.recipient,
|
|
7981
|
+
amount: charge.amount.toString()
|
|
7982
|
+
}
|
|
7983
|
+
};
|
|
7984
|
+
},
|
|
7985
|
+
async settle(context) {
|
|
7986
|
+
const { status, headers } = context.response;
|
|
7987
|
+
const encoded = headers.get("payment-receipt");
|
|
7988
|
+
if (status < 200 || status >= 300)
|
|
7989
|
+
return { outcome: "unknown", reason: `Paid request returned HTTP ${status}` };
|
|
7990
|
+
if (!encoded)
|
|
7991
|
+
return { outcome: "unknown", reason: "Paid request returned no settlement evidence" };
|
|
7992
|
+
let json;
|
|
7993
|
+
try {
|
|
7994
|
+
json = decodeMppJson(z5.unknown(), encoded);
|
|
7995
|
+
} catch {
|
|
7996
|
+
return {
|
|
7997
|
+
outcome: "unknown",
|
|
7998
|
+
reason: "Paid request returned malformed settlement evidence"
|
|
7999
|
+
};
|
|
8000
|
+
}
|
|
8001
|
+
const parsed = MppReceiptSchema.safeParse(json);
|
|
8002
|
+
if (!parsed.success)
|
|
8003
|
+
return { outcome: "rejected", reason: "receipt_invalid" };
|
|
8004
|
+
const receipt = parsed.data;
|
|
8005
|
+
return {
|
|
8006
|
+
outcome: "settled",
|
|
8007
|
+
amount: context.payment.record.authorizedAmount,
|
|
8008
|
+
transaction: receipt.reference
|
|
8009
|
+
};
|
|
8010
|
+
},
|
|
8011
|
+
async reconcile({ record, policy, signal }) {
|
|
8012
|
+
const data = chargeData(record.rail?.data);
|
|
8013
|
+
const token = getAddress8(data.token);
|
|
8014
|
+
const charged = BigInt(record.authorizedAmount);
|
|
8015
|
+
const worstFee = charged - BigInt(data.amount);
|
|
8016
|
+
try {
|
|
8017
|
+
const chain = await reader(record.network, policy);
|
|
8018
|
+
if (data.txHash !== null) {
|
|
8019
|
+
const receipt = await chain.transactionReceipt(data.txHash);
|
|
8020
|
+
if (receipt?.status === "success")
|
|
8021
|
+
return {
|
|
8022
|
+
outcome: "settled",
|
|
8023
|
+
amount: record.authorizedAmount,
|
|
8024
|
+
transaction: data.txHash
|
|
8025
|
+
};
|
|
8026
|
+
if (receipt) {
|
|
8027
|
+
const fee = receipt.feeUnits !== void 0 && receipt.feeUnits > 0n ? receipt.feeUnits : worstFee;
|
|
8028
|
+
return {
|
|
8029
|
+
outcome: "settled",
|
|
8030
|
+
amount: (fee < worstFee ? fee : worstFee).toString(),
|
|
8031
|
+
transaction: data.txHash
|
|
8032
|
+
};
|
|
8033
|
+
}
|
|
8034
|
+
}
|
|
8035
|
+
const latest = await chain.latestBlock();
|
|
8036
|
+
const start = BigInt(data.headNumber);
|
|
8037
|
+
if (start > latest.number)
|
|
8038
|
+
return { outcome: "pending" };
|
|
8039
|
+
const past = latest.timestamp > data.validBefore;
|
|
8040
|
+
let end = latest.number;
|
|
8041
|
+
if (past) {
|
|
8042
|
+
let low = start;
|
|
8043
|
+
let high = latest.number;
|
|
8044
|
+
while (low < high) {
|
|
8045
|
+
throwIfAborted(signal);
|
|
8046
|
+
const middle = (low + high) / 2n;
|
|
8047
|
+
if (await chain.blockTimestamp(middle) > data.validBefore)
|
|
8048
|
+
high = middle;
|
|
8049
|
+
else
|
|
8050
|
+
low = middle + 1n;
|
|
8051
|
+
}
|
|
8052
|
+
end = low;
|
|
8053
|
+
}
|
|
8054
|
+
const confirmed = end + UNSPENT_CONFIRMATION_BLOCKS;
|
|
8055
|
+
if (past)
|
|
8056
|
+
end = confirmed < latest.number ? confirmed : latest.number;
|
|
8057
|
+
let from = start;
|
|
8058
|
+
for (let range = 0; from <= end; range += 1) {
|
|
8059
|
+
if (range === MAX_LOG_RANGES)
|
|
8060
|
+
return { outcome: "pending" };
|
|
8061
|
+
throwIfAborted(signal);
|
|
8062
|
+
const to = from + MAX_LOG_RANGE - 1n < end ? from + MAX_LOG_RANGE - 1n : end;
|
|
8063
|
+
const logs = await chain.transfersWithMemo({
|
|
8064
|
+
token,
|
|
8065
|
+
from: getAddress8(record.payer),
|
|
8066
|
+
to: getAddress8(data.recipient),
|
|
8067
|
+
memo: data.memo,
|
|
8068
|
+
fromBlock: from,
|
|
8069
|
+
toBlock: to
|
|
8070
|
+
});
|
|
8071
|
+
if (logs.some((log) => log.amount === BigInt(data.amount)))
|
|
8072
|
+
return {
|
|
8073
|
+
outcome: "settled",
|
|
8074
|
+
amount: record.authorizedAmount,
|
|
8075
|
+
transaction: logs.find((log) => log.amount === BigInt(data.amount)).transactionHash
|
|
8076
|
+
};
|
|
8077
|
+
from = to + 1n;
|
|
8078
|
+
}
|
|
8079
|
+
if (!past || !data.sponsored && data.txHash === null || end < confirmed)
|
|
8080
|
+
return { outcome: "pending" };
|
|
8081
|
+
const after = await chain.latestBlock();
|
|
8082
|
+
if (after.number < end || after.number < latest.number || after.timestamp <= data.validBefore)
|
|
8083
|
+
return { outcome: "pending" };
|
|
8084
|
+
return { outcome: "unspent" };
|
|
8085
|
+
} catch (error) {
|
|
8086
|
+
if (signal?.aborted)
|
|
8087
|
+
throw error;
|
|
8088
|
+
return { outcome: "pending" };
|
|
8089
|
+
}
|
|
8090
|
+
}
|
|
8091
|
+
};
|
|
8092
|
+
}
|
|
8093
|
+
|
|
7470
8094
|
// src/lib/x402-paths.ts
|
|
7471
8095
|
import path5 from "path";
|
|
7472
8096
|
function getX402JournalPath() {
|
|
@@ -7478,6 +8102,7 @@ function getX402PolicyPath() {
|
|
|
7478
8102
|
|
|
7479
8103
|
export {
|
|
7480
8104
|
X402_INVOCATION_ID_PATTERN,
|
|
8105
|
+
X402_PAY_PROTOCOLS,
|
|
7481
8106
|
X402PayError,
|
|
7482
8107
|
withX402FileLock,
|
|
7483
8108
|
x402SpendWindowAvailability,
|
|
@@ -7496,6 +8121,7 @@ export {
|
|
|
7496
8121
|
createEvmPerRequestRail,
|
|
7497
8122
|
assertX402HeaderName,
|
|
7498
8123
|
assertX402HeaderValue,
|
|
8124
|
+
MPP_TEMPO_CHARGE_SCHEME,
|
|
7499
8125
|
reconcileX402Payment,
|
|
7500
8126
|
createX402Payer,
|
|
7501
8127
|
createX402Allocations,
|
|
@@ -7510,6 +8136,7 @@ export {
|
|
|
7510
8136
|
signSponsoredTempoTransfer,
|
|
7511
8137
|
readMppTempoChallenge,
|
|
7512
8138
|
createMppTempoCredential,
|
|
8139
|
+
createMppTempoChargeRail,
|
|
7513
8140
|
getX402JournalPath,
|
|
7514
8141
|
getX402PolicyPath
|
|
7515
8142
|
};
|