@lucid-agents/taskmarket 1.44.0 → 1.46.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.
Files changed (25) hide show
  1. package/dist/agent-compatibility.json +1 -1
  2. package/dist/{api-QATTK6I6.js → api-56KWZFR4.js} +2 -2
  3. package/dist/{channels-AH2WHLMC.js → channels-YKCZU2Q7.js} +4 -4
  4. package/dist/{chunk-3HR7XRLE.js → chunk-3MITXF2F.js} +3 -3
  5. package/dist/{chunk-3NPMVKNZ.js → chunk-64NUUQBC.js} +1 -1
  6. package/dist/{chunk-YENJWEM7.js → chunk-66HELSIU.js} +3 -3
  7. package/dist/{chunk-NLHDU4CH.js → chunk-7KZOHF7R.js} +1 -1
  8. package/dist/{chunk-CH3GXKIO.js → chunk-AS3N5L25.js} +2 -2
  9. package/dist/{chunk-ZPQLJAG4.js → chunk-DPJIDICA.js} +31 -13
  10. package/dist/{chunk-LETSESYQ.js → chunk-E3J2J3PZ.js} +8 -8
  11. package/dist/{chunk-IVCJPX7J.js → chunk-HFG7TSVD.js} +4661 -3748
  12. package/dist/{chunk-XBPINLPI.js → chunk-MMODVSSS.js} +1 -1
  13. package/dist/{chunk-AZMCG2LI.js → chunk-MUFEOBRQ.js} +1 -1
  14. package/dist/{chunk-J2TAHVUS.js → chunk-O5C2CWWL.js} +5 -5
  15. package/dist/{chunk-FUHULPDT.js → chunk-Y3B7POF2.js} +631 -40
  16. package/dist/{doctor-WW54ZCQR.js → doctor-TA3AZMPJ.js} +8 -8
  17. package/dist/index.js +640 -197
  18. package/dist/{launch-FQFOZYIN.js → launch-2RINYQTU.js} +11 -11
  19. package/dist/pi-extensions/xgate.cjs +32 -1
  20. package/dist/{read-auth-B7NFDF6U.js → read-auth-FFCZKAFN.js} +3 -3
  21. package/dist/{reconcile-KHSXUVR3.js → reconcile-O6LVP2Z3.js} +4 -4
  22. package/dist/{status-IMWQR4AR.js → status-FRMTSDIG.js} +8 -8
  23. package/dist/{sync-pull-EN7CFU3J.js → sync-pull-OUXRL6A2.js} +4 -4
  24. package/dist/{task-access-grants-IBD3JFGD.js → task-access-grants-WV3HVN5V.js} +2 -2
  25. package/package.json +1 -1
@@ -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-IVCJPX7J.js";
14
+ } from "./chunk-HFG7TSVD.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) {
@@ -4054,6 +4236,13 @@ function shortReason(value) {
4054
4236
  return void 0;
4055
4237
  return reason.length > FAILURE_REASON_MAX_LENGTH ? `${reason.slice(0, FAILURE_REASON_MAX_LENGTH)}...` : reason;
4056
4238
  }
4239
+ var RAIL_SIGN_REFUSAL_CODES = /* @__PURE__ */ new Set([
4240
+ "challenge_invalid",
4241
+ "challenge_expired",
4242
+ "insufficient_balance",
4243
+ "payment_header_conflict",
4244
+ "request_failed"
4245
+ ]);
4057
4246
  function x402FailureReason(headers) {
4058
4247
  const settlementHeader = headers.get("payment-response") ?? headers.get("x-payment-response");
4059
4248
  if (settlementHeader) {
@@ -4298,11 +4487,41 @@ async function runX402Exchange(runtime, input, options, context) {
4298
4487
  status: 402,
4299
4488
  headers: Object.freeze(x402HeaderRecord(response.headers))
4300
4489
  };
4490
+ const protocol = input.protocol ?? "auto";
4301
4491
  let paymentRequired;
4302
- try {
4303
- paymentRequired = parseChallenge({ status: 402, headers: { ...challenge.headers }, body: challengeBody }, prepared.url, firstParty);
4304
- } catch {
4305
- throw fail("challenge_invalid", "Invalid x402 payment challenge", { status: 402 });
4492
+ if (firstParty || protocol !== "mpp") {
4493
+ try {
4494
+ paymentRequired = parseChallenge({ status: 402, headers: { ...challenge.headers }, body: challengeBody }, prepared.url, firstParty);
4495
+ } catch {
4496
+ paymentRequired = void 0;
4497
+ }
4498
+ if (paymentRequired?.accepts.some((option) => option.scheme === MPP_TEMPO_CHARGE_SCHEME)) {
4499
+ const accepts = paymentRequired.accepts.filter((option) => option.scheme !== MPP_TEMPO_CHARGE_SCHEME);
4500
+ paymentRequired = accepts.length > 0 ? { ...paymentRequired, accepts } : void 0;
4501
+ }
4502
+ }
4503
+ const mpp = !firstParty && protocol !== "x402" ? readMppChallenges(challenge.headers["www-authenticate"], runtime.now()) : void 0;
4504
+ if (paymentRequired && mpp && mpp.requirements.length > 0) {
4505
+ paymentRequired = {
4506
+ ...paymentRequired,
4507
+ accepts: [...paymentRequired.accepts, ...mpp.requirements]
4508
+ };
4509
+ } else if (!paymentRequired) {
4510
+ if (mpp && mpp.requirements.length > 0) {
4511
+ paymentRequired = {
4512
+ x402Version: 2,
4513
+ resource: { url: prepared.url.toString() },
4514
+ accepts: mpp.requirements
4515
+ };
4516
+ } else if (mpp?.failure) {
4517
+ throw fail(mpp.failure.code, mpp.failure.message, { status: 402 });
4518
+ } else if (mpp?.seen) {
4519
+ throw fail("no_supported_rail", "No advertised MPP payment option can be paid", {
4520
+ status: 402
4521
+ });
4522
+ } else {
4523
+ throw fail("challenge_invalid", protocol === "mpp" ? "The response carries no Payment challenge" : "Invalid x402 payment challenge", { status: 402 });
4524
+ }
4306
4525
  }
4307
4526
  const selection = selectX402Payment({
4308
4527
  rails,
@@ -4348,7 +4567,8 @@ async function runX402Exchange(runtime, input, options, context) {
4348
4567
  authorizedAmount: maxAmount,
4349
4568
  policyRuleId: selection.transient ? void 0 : authorization.rule.id,
4350
4569
  windowMaximum: authorization.payment.spendWindow.max,
4351
- unattended: false
4570
+ unattended: false,
4571
+ ...rail.feeTerms?.(requirement) ?? {}
4352
4572
  };
4353
4573
  let approved;
4354
4574
  try {
@@ -4476,7 +4696,8 @@ async function runX402Exchange(runtime, input, options, context) {
4476
4696
  url: prepared.url,
4477
4697
  method: prepared.method,
4478
4698
  requestFingerprint: prepared.requestHash,
4479
- firstParty
4699
+ firstParty,
4700
+ headers: Object.freeze({ ...unpaidHeaders })
4480
4701
  },
4481
4702
  paymentRequired,
4482
4703
  challenge,
@@ -4551,7 +4772,7 @@ async function runX402Exchange(runtime, input, options, context) {
4551
4772
  await release(errorMessage(error), takeStaged());
4552
4773
  if (signal.aborted)
4553
4774
  throw aborted();
4554
- throw fail("signer_unavailable", errorMessage(error), { cause: error });
4775
+ throw fail(error instanceof X402PayError && RAIL_SIGN_REFUSAL_CODES.has(error.code) ? error.code : "signer_unavailable", errorMessage(error), { cause: error });
4555
4776
  }
4556
4777
  try {
4557
4778
  await transition({
@@ -4902,6 +5123,11 @@ function createX402Payer(config) {
4902
5123
  headers: input.headers,
4903
5124
  body: input.body
4904
5125
  }, { firstPartyOrigin });
5126
+ if (input.protocol !== void 0 && !X402_PAY_PROTOCOLS.includes(input.protocol)) {
5127
+ throw new X402PayError("x402 protocol must be auto, x402 or mpp", {
5128
+ code: "invalid_request"
5129
+ });
5130
+ }
4905
5131
  if (input.policyRuleId !== void 0 && typeof input.policyRuleId !== "string") {
4906
5132
  throw new X402PayError("x402 policyRuleId must be a string", { code: "invalid_request" });
4907
5133
  }
@@ -5098,7 +5324,7 @@ function createX402Payer(config) {
5098
5324
  }
5099
5325
 
5100
5326
  // ../../packages/x402-payer/dist/base-channel/runtime.js
5101
- import { z as z3 } from "zod";
5327
+ import { z as z4 } from "zod";
5102
5328
 
5103
5329
  // ../../packages/x402-payer/dist/base-channel/store.js
5104
5330
  import { createHash as createHash3, randomUUID as randomUUID6 } from "crypto";
@@ -5386,9 +5612,9 @@ function channelStatusFailure(status, body) {
5386
5612
  function explainedByUnresolved(routerCharged, baseline, ceiling, unresolved) {
5387
5613
  return routerCharged > baseline && routerCharged <= ceiling && unresolved.some((u) => BigInt(u.chargedBefore) === baseline && routerCharged <= baseline + BigInt(u.maximum));
5388
5614
  }
5389
- var purchaseStatusSchema = z3.object({
5390
- purchase_id: z3.string(),
5391
- payment: z3.enum([
5615
+ var purchaseStatusSchema = z4.object({
5616
+ purchase_id: z4.string(),
5617
+ payment: z4.enum([
5392
5618
  "awaiting_payment",
5393
5619
  "pending",
5394
5620
  "verified",
@@ -5396,7 +5622,7 @@ var purchaseStatusSchema = z3.object({
5396
5622
  "collection_failed",
5397
5623
  "unresolved"
5398
5624
  ]),
5399
- inference: z3.enum([
5625
+ inference: z4.enum([
5400
5626
  "awaiting_payment",
5401
5627
  "admitted",
5402
5628
  "dispatch_claimed",
@@ -5405,8 +5631,8 @@ var purchaseStatusSchema = z3.object({
5405
5631
  "zero_charge",
5406
5632
  "unresolved"
5407
5633
  ]),
5408
- delivery: z3.string(),
5409
- result_replay_available: z3.literal(false)
5634
+ delivery: z4.string(),
5635
+ result_replay_available: z4.literal(false)
5410
5636
  }).strict();
5411
5637
  function createChannelRuntime(config) {
5412
5638
  const identity = channelIdentity(config.channel);
@@ -5451,7 +5677,7 @@ function createChannelRuntime(config) {
5451
5677
  }
5452
5678
  }
5453
5679
  }
5454
- async function http4(requestUrl, init, signal) {
5680
+ async function http5(requestUrl, init, signal) {
5455
5681
  if (requestUrl.origin !== url.origin)
5456
5682
  throw invalidRequest("channel request left the pinned origin");
5457
5683
  const policy = await config.loadPolicy({ allowMissing: false });
@@ -5547,7 +5773,7 @@ function createChannelRuntime(config) {
5547
5773
  statusUrl.searchParams.set("network", identity.network);
5548
5774
  if (!headers["x-channel-signature"] || !headers["x-channel-issued-at"])
5549
5775
  throw outcomeUncertain("channel status request could not be signed");
5550
- const response = await http4(statusUrl, { method: sync ? "POST" : "GET", headers }, signal);
5776
+ const response = await http5(statusUrl, { method: sync ? "POST" : "GET", headers }, signal);
5551
5777
  if (response.status !== 200)
5552
5778
  throw channelStatusFailure(response.status, response.body);
5553
5779
  const parsed = statusSchema.safeParse(response.body);
@@ -5706,7 +5932,7 @@ function createChannelRuntime(config) {
5706
5932
  funding,
5707
5933
  account,
5708
5934
  validateAllocation,
5709
- http: http4,
5935
+ http: http5,
5710
5936
  syncReturns,
5711
5937
  synchronize,
5712
5938
  routerView,
@@ -5745,22 +5971,22 @@ function confirmationWait(config) {
5745
5971
  sleep: input.sleep ?? abortableSleep
5746
5972
  };
5747
5973
  }
5748
- var depositDataSchema = z3.object({
5974
+ var depositDataSchema = z4.object({
5749
5975
  nonce: hex32,
5750
- amount: z3.string(),
5751
- validBefore: z3.number(),
5752
- afterBlock: z3.string().optional()
5976
+ amount: z4.string(),
5977
+ validBefore: z4.number(),
5978
+ afterBlock: z4.string().optional()
5753
5979
  });
5754
- var paymentDataSchema = z3.object({
5755
- purchaseId: z3.string(),
5756
- statusToken: z3.string(),
5757
- chargedBefore: z3.string(),
5758
- maximum: z3.string(),
5759
- sequence: z3.number(),
5760
- refused: z3.boolean(),
5980
+ var paymentDataSchema = z4.object({
5981
+ purchaseId: z4.string(),
5982
+ statusToken: z4.string(),
5983
+ chargedBefore: z4.string(),
5984
+ maximum: z4.string(),
5985
+ sequence: z4.number(),
5986
+ refused: z4.boolean(),
5761
5987
  deposit: depositDataSchema.nullable(),
5762
5988
  /** Payer clock (unix seconds) when the voucher was signed; absent on older records. */
5763
- signedAt: z3.number().optional()
5989
+ signedAt: z4.number().optional()
5764
5990
  });
5765
5991
  function depositProof(data) {
5766
5992
  return data.deposit ? { ...data.deposit, nonce: data.deposit.nonce } : void 0;
@@ -7148,7 +7374,7 @@ function createBaseChannelPayer(inputConfig) {
7148
7374
 
7149
7375
  // ../../packages/x402-payer/dist/taskmarket-fee-rail.js
7150
7376
  import { randomBytes } from "crypto";
7151
- import { getAddress as getAddress5, toHex } from "viem";
7377
+ import { getAddress as getAddress6, toHex } from "viem";
7152
7378
  var TASKMARKET_FEE_RAIL_ID = "taskmarket-fee";
7153
7379
  var TRANSFER_WITH_AUTHORIZATION = [
7154
7380
  { name: "from", type: "address" },
@@ -7295,7 +7521,7 @@ function createTaskmarketFeeRail() {
7295
7521
  resource: paymentRequired.resource,
7296
7522
  requirement,
7297
7523
  typedData,
7298
- from: getAddress5(account.address),
7524
+ from: getAddress6(account.address),
7299
7525
  signTypedData: (data) => account.signTypedData(data)
7300
7526
  });
7301
7527
  return {
@@ -7331,11 +7557,16 @@ function createTaskmarketFeeRail() {
7331
7557
  };
7332
7558
  }
7333
7559
 
7560
+ // ../../packages/x402-payer/dist/mpp-tempo-rail.js
7561
+ import { randomBytes as randomBytes3 } from "crypto";
7562
+ import { createPublicClient as createPublicClient4, defineChain as defineChain3, getAddress as getAddress8, http as http4, isAddressEqual as isAddressEqual2, keccak256 as keccak2562, parseAbiItem as parseAbiItem2 } from "viem";
7563
+ import { z as z5 } from "zod";
7564
+
7334
7565
  // ../../packages/x402-payer/dist/mpp-tempo.js
7335
7566
  import { randomBytes as randomBytes2 } from "crypto";
7336
7567
  import { Signature } from "ox";
7337
7568
  import { SignatureEnvelope, TxEnvelopeTempo } from "ox/tempo";
7338
- import { encodeFunctionData as encodeFunctionData3, getAddress as getAddress6, isAddressEqual, maxUint256 } from "viem";
7569
+ import { encodeFunctionData as encodeFunctionData3, getAddress as getAddress7, isAddressEqual, maxUint256 } from "viem";
7339
7570
  var MPP_TEMPO_DEFAULT_FEES = {
7340
7571
  gas: 500000n,
7341
7572
  maxFeePerGas: 20000000000n,
@@ -7368,7 +7599,7 @@ var TIP20_TRANSFER_ABI = [
7368
7599
  ];
7369
7600
  async function signSponsoredTempoTransfer(input) {
7370
7601
  const fees = { ...MPP_TEMPO_DEFAULT_FEES, ...input.fees };
7371
- const to = getAddress6(input.to);
7602
+ const to = getAddress7(input.to);
7372
7603
  const data = input.memo === void 0 ? encodeFunctionData3({
7373
7604
  abi: TIP20_TRANSFER_ABI,
7374
7605
  functionName: "transfer",
@@ -7380,15 +7611,17 @@ async function signSponsoredTempoTransfer(input) {
7380
7611
  });
7381
7612
  const envelope = TxEnvelopeTempo.from({
7382
7613
  chainId: input.chainId,
7383
- calls: [{ to: getAddress6(input.token), data }],
7614
+ calls: [{ to: getAddress7(input.token), data }],
7384
7615
  gas: fees.gas,
7385
7616
  maxFeePerGas: fees.maxFeePerGas,
7386
7617
  maxPriorityFeePerGas: fees.maxPriorityFeePerGas,
7387
7618
  nonceKey: EXPIRING_NONCE_KEY,
7388
7619
  nonce: 0n,
7389
7620
  validBefore: input.validBefore,
7390
- // The sponsorship marker: the sender signs without committing to a fee payer or fee token.
7391
- feePayerSignature: null
7621
+ ...input.feeToken === void 0 ? (
7622
+ // The sponsorship marker: the sender signs without committing to a fee payer or fee token.
7623
+ { feePayerSignature: null }
7624
+ ) : { feeToken: getAddress7(input.feeToken) }
7392
7625
  });
7393
7626
  let signature2;
7394
7627
  try {
@@ -7400,12 +7633,12 @@ async function signSponsoredTempoTransfer(input) {
7400
7633
  });
7401
7634
  }
7402
7635
  const envelopeSignature = SignatureEnvelope.from(Signature.from(signature2));
7403
- if (input.format === "sender")
7636
+ if (input.format === "sender" || input.feeToken !== void 0)
7404
7637
  return TxEnvelopeTempo.serialize(envelope, { signature: envelopeSignature });
7405
7638
  return TxEnvelopeTempo.serialize(envelope, {
7406
7639
  signature: envelopeSignature,
7407
7640
  format: "feePayer",
7408
- sender: getAddress6(input.signer.address)
7641
+ sender: getAddress7(input.signer.address)
7409
7642
  });
7410
7643
  }
7411
7644
  function challengeRefused(message) {
@@ -7461,12 +7694,367 @@ async function createMppTempoCredential(input) {
7461
7694
  });
7462
7695
  const authorization = formatMppCredential({
7463
7696
  challenge,
7464
- source: `did:pkh:eip155:${chainId}:${getAddress6(signer.address)}`,
7697
+ source: `did:pkh:eip155:${chainId}:${getAddress7(signer.address)}`,
7465
7698
  payload: { type: "transaction", signature: transaction }
7466
7699
  });
7467
7700
  return { authorization, request, transaction, memo, validBefore };
7468
7701
  }
7469
7702
 
7703
+ // ../../packages/x402-payer/dist/mpp-tempo-rail.js
7704
+ var MPP_TEMPO_CHARGE_RAIL_ID = "mpp-tempo-charge";
7705
+ var MPP_TEMPO_CHARGE_FEES = {
7706
+ ...MPP_TEMPO_DEFAULT_FEES,
7707
+ gas: 400000n
7708
+ };
7709
+ var FEE_UNITS_PER_BASE_UNIT = 10n ** 12n;
7710
+ var SPONSORED_MIN_REMAINING_SECONDS = 15;
7711
+ var VALIDITY_SECONDS = 25;
7712
+ var MAX_LOG_RANGE = 100000n;
7713
+ var MAX_LOG_RANGES = 16;
7714
+ var AUTHORIZATION_KIND = "tempo-transfer-with-memo";
7715
+ var TRANSFER_WITH_MEMO = parseAbiItem2("event TransferWithMemo(address indexed from, address indexed to, uint256 amount, bytes32 indexed memo)");
7716
+ var BALANCE_OF = parseAbiItem2("function balanceOf(address account) view returns (uint256)");
7717
+ function viemReader(network, policy) {
7718
+ const rpcUrl = rpcUrlForNetwork(policy, network);
7719
+ const client = createPublicClient4({
7720
+ chain: defineChain3({
7721
+ id: evmChainIdOf(network),
7722
+ name: network,
7723
+ nativeCurrency: { name: "USD", symbol: "USD", decimals: 6 },
7724
+ rpcUrls: { default: { http: [rpcUrl] } }
7725
+ }),
7726
+ transport: http4(rpcUrl)
7727
+ });
7728
+ return {
7729
+ chainId: () => client.getChainId(),
7730
+ tokenBalance: (token, owner) => client.readContract({
7731
+ address: token,
7732
+ abi: [BALANCE_OF],
7733
+ functionName: "balanceOf",
7734
+ args: [owner]
7735
+ }),
7736
+ latestBlock: async () => {
7737
+ const block = await client.getBlock();
7738
+ return { number: block.number, timestamp: Number(block.timestamp) };
7739
+ },
7740
+ blockTimestamp: async (blockNumber) => Number((await client.getBlock({ blockNumber })).timestamp),
7741
+ transactionReceipt: async (hash) => {
7742
+ try {
7743
+ const receipt = await client.getTransactionReceipt({ hash });
7744
+ const attodollars = receipt.gasUsed * receipt.effectiveGasPrice;
7745
+ return {
7746
+ status: receipt.status === "success" ? "success" : "reverted",
7747
+ feeUnits: (attodollars + FEE_UNITS_PER_BASE_UNIT - 1n) / FEE_UNITS_PER_BASE_UNIT
7748
+ };
7749
+ } catch (error) {
7750
+ if (error instanceof Error && error.name === "TransactionReceiptNotFoundError")
7751
+ return void 0;
7752
+ throw error;
7753
+ }
7754
+ },
7755
+ transfersWithMemo: async ({ token, from, to, memo, fromBlock, toBlock }) => (await client.getLogs({
7756
+ address: token,
7757
+ event: TRANSFER_WITH_MEMO,
7758
+ args: { from, to, memo },
7759
+ fromBlock,
7760
+ toBlock
7761
+ })).map((log) => ({ amount: log.args.amount, transactionHash: log.transactionHash }))
7762
+ };
7763
+ }
7764
+ var ECHOED_PARAMS = [
7765
+ "id",
7766
+ "realm",
7767
+ "method",
7768
+ "intent",
7769
+ "request",
7770
+ "expires",
7771
+ "digest",
7772
+ "opaque",
7773
+ "description"
7774
+ ];
7775
+ function refused(message) {
7776
+ return new X402PayError(message, { code: "challenge_invalid" });
7777
+ }
7778
+ function readCharge(requirement) {
7779
+ if (requirement.scheme !== MPP_TEMPO_CHARGE_SCHEME || !EVM_NETWORK_PATTERN.test(requirement.network))
7780
+ throw refused("Not an MPP tempo charge requirement");
7781
+ const chainId = evmChainIdOf(requirement.network);
7782
+ if (!MPP_TEMPO_CHAIN_IDS.includes(chainId))
7783
+ throw refused(`Chain ${chainId} is not a Tempo chain`);
7784
+ const mpp = requirement.extra?.["mpp"];
7785
+ if (!mpp || typeof mpp !== "object" || !mpp.challenge || typeof mpp.challenge !== "object")
7786
+ throw refused("The MPP challenge data is missing");
7787
+ const parsed = ThirdPartyMppTempoChargeRequestSchema.safeParse(mpp.request);
7788
+ if (!parsed.success)
7789
+ throw refused("The MPP charge request is malformed");
7790
+ const request = parsed.data;
7791
+ const details = request.methodDetails;
7792
+ const params = mpp.challenge;
7793
+ if (details?.chainId !== chainId || details.splits !== void 0 || details.memo !== void 0 || details.supportedModes !== void 0 && !details.supportedModes.includes("pull"))
7794
+ throw refused("The MPP charge is not a payable pull-mode charge on this chain");
7795
+ const amount = BigInt(request.amount);
7796
+ if (amount === 0n || requirement.amount !== amount.toString() || !isAddressEqual2(requirement.asset, request.currency) || !isAddressEqual2(requirement.payTo, request.recipient))
7797
+ throw refused("The MPP requirement does not match its charge request");
7798
+ if (Object.values(params).some((value) => typeof value !== "string") || !params["id"] || !params["realm"] || !params["request"] || params["method"]?.toLowerCase() !== "tempo" || params["intent"]?.toLowerCase() !== "charge")
7799
+ throw refused("The MPP challenge is malformed");
7800
+ let echoed;
7801
+ try {
7802
+ echoed = decodeMppJson(ThirdPartyMppTempoChargeRequestSchema, params["request"]);
7803
+ } catch {
7804
+ throw refused("The echoed Payment challenge request is malformed");
7805
+ }
7806
+ if (canonicalJson(echoed) !== canonicalJson(request))
7807
+ throw refused("The Payment challenge request differs from the charge being signed");
7808
+ const echoedExpiry = params["expires"] === void 0 ? void 0 : Date.parse(params["expires"]);
7809
+ if (echoedExpiry === void 0 !== (typeof mpp.expiresAt !== "string") || echoedExpiry !== void 0 && new Date(echoedExpiry).toISOString() !== mpp.expiresAt)
7810
+ throw refused("The Payment challenge expiry differs from the charge being signed");
7811
+ if (params["digest"] !== void 0)
7812
+ throw refused("A Payment challenge with a digest is not supported");
7813
+ const named = params["header"]?.toLowerCase();
7814
+ if (named !== void 0 && named !== "payment-authorization")
7815
+ throw refused("The Payment challenge names a credential header that is not supported");
7816
+ return {
7817
+ chainId,
7818
+ token: getAddress8(request.currency.toLowerCase()),
7819
+ recipient: getAddress8(request.recipient.toLowerCase()),
7820
+ amount,
7821
+ sponsored: details.feePayer === true,
7822
+ ...typeof mpp.expiresAt === "string" ? { expiresAt: mpp.expiresAt } : {},
7823
+ header: named === "payment-authorization" ? "payment-authorization" : "authorization",
7824
+ challenge: params
7825
+ };
7826
+ }
7827
+ function worstCaseFee(fees) {
7828
+ const attodollars = fees.gas * fees.maxFeePerGas;
7829
+ return (attodollars + FEE_UNITS_PER_BASE_UNIT - 1n) / FEE_UNITS_PER_BASE_UNIT;
7830
+ }
7831
+ function chargeData(data) {
7832
+ 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"]))
7833
+ throw new Error("The MPP payment has no recorded memo, token, recipient and expiry");
7834
+ return data;
7835
+ }
7836
+ function createMppTempoChargeRail(options = {}) {
7837
+ const fees = { ...MPP_TEMPO_CHARGE_FEES, ...options.fees };
7838
+ const now = options.now ?? Date.now;
7839
+ const readerFor = options.reader ?? viemReader;
7840
+ const feeUnits = worstCaseFee(fees);
7841
+ async function reader(network, policy) {
7842
+ const chain = readerFor(network, policy);
7843
+ const rpcChainId = await chain.chainId();
7844
+ if (rpcChainId !== evmChainIdOf(network))
7845
+ throw new Error(`RPC chain id ${rpcChainId} does not match ${network}`);
7846
+ return chain;
7847
+ }
7848
+ return {
7849
+ id: MPP_TEMPO_CHARGE_RAIL_ID,
7850
+ kind: "per-request",
7851
+ supports(requirement) {
7852
+ return requirement.scheme === MPP_TEMPO_CHARGE_SCHEME && typeof requirement.network === "string" && EVM_NETWORK_PATTERN.test(requirement.network);
7853
+ },
7854
+ select(requirement) {
7855
+ const charge = readCharge(requirement);
7856
+ return { maxAmount: (charge.amount + (charge.sponsored ? 0n : feeUnits)).toString() };
7857
+ },
7858
+ feeTerms(requirement) {
7859
+ const charge = readCharge(requirement);
7860
+ return {
7861
+ feeSponsored: charge.sponsored,
7862
+ chargeAmount: charge.amount.toString(),
7863
+ maxFee: (charge.sponsored ? 0n : feeUnits).toString()
7864
+ };
7865
+ },
7866
+ async sign(context) {
7867
+ throwIfAborted(context.signal);
7868
+ const charge = readCharge(context.requirement);
7869
+ const { account } = context;
7870
+ if (context.request.headers?.[charge.header] !== void 0)
7871
+ throw new X402PayError(`The request already sets the ${charge.header} header the Payment challenge needs for its credential`, { code: "payment_header_conflict" });
7872
+ const nowSeconds = Math.floor(now() / 1e3);
7873
+ let remaining = VALIDITY_SECONDS;
7874
+ if (charge.expiresAt !== void 0) {
7875
+ const left = Math.floor(Date.parse(charge.expiresAt) / 1e3) - nowSeconds;
7876
+ if (!(left > 0) || charge.sponsored && left < SPONSORED_MIN_REMAINING_SECONDS)
7877
+ throw new X402PayError("The Payment challenge has expired", {
7878
+ code: "challenge_expired"
7879
+ });
7880
+ remaining = Math.min(remaining, left);
7881
+ }
7882
+ const validBefore = nowSeconds + remaining;
7883
+ const required = charge.amount + (charge.sponsored ? 0n : feeUnits);
7884
+ let balance;
7885
+ let head;
7886
+ try {
7887
+ const chain = await reader(context.requirement.network, context.policy);
7888
+ balance = await chain.tokenBalance(charge.token, getAddress8(account.address));
7889
+ head = await chain.latestBlock();
7890
+ } catch (error) {
7891
+ throw new X402PayError(`Could not read the wallet balance of token ${charge.token}`, {
7892
+ code: "request_failed",
7893
+ cause: error
7894
+ });
7895
+ }
7896
+ if (balance < required)
7897
+ 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" });
7898
+ throwIfAborted(context.signal);
7899
+ if (typeof account.sign !== "function")
7900
+ throw new X402PayError("The wallet cannot sign a Tempo transfer", {
7901
+ code: "signer_unavailable"
7902
+ });
7903
+ const sign = account.sign.bind(account);
7904
+ const memo = mppAttributionMemo({
7905
+ realm: charge.challenge["realm"],
7906
+ challengeId: charge.challenge["id"],
7907
+ // Random, so that the memo is unique per payment and reconcile can find exactly this one.
7908
+ client: randomBytes3(10).toString("hex")
7909
+ });
7910
+ const transaction = await signSponsoredTempoTransfer({
7911
+ signer: { address: account.address, sign },
7912
+ chainId: charge.chainId,
7913
+ token: charge.token,
7914
+ to: charge.recipient,
7915
+ amount: charge.amount,
7916
+ memo,
7917
+ validBefore,
7918
+ fees,
7919
+ ...charge.sponsored ? {} : { feeToken: charge.token }
7920
+ });
7921
+ const txHash = charge.sponsored ? void 0 : keccak2562(transaction);
7922
+ const echoed = {};
7923
+ for (const name of ECHOED_PARAMS) {
7924
+ const value = charge.challenge[name];
7925
+ if (value !== void 0)
7926
+ echoed[name] = value;
7927
+ }
7928
+ const credential = encodeMppJson({
7929
+ challenge: echoed,
7930
+ source: `did:pkh:eip155:${charge.chainId}:${getAddress8(account.address)}`,
7931
+ payload: { type: "transaction", signature: transaction }
7932
+ });
7933
+ return {
7934
+ headers: { [charge.header]: `Payment ${credential}` },
7935
+ nonce: memo,
7936
+ authorizationKind: AUTHORIZATION_KIND,
7937
+ authorizationExpiresAt: new Date(validBefore * 1e3).toISOString(),
7938
+ // A wallet-paid transaction goes to the chain as signed, so its hash is known now and
7939
+ // tells a failed broadcast (fee burned, no memo log) from one that never landed.
7940
+ ...charge.sponsored ? {} : { commitment: txHash },
7941
+ data: {
7942
+ txHash: txHash ?? null,
7943
+ sponsored: charge.sponsored,
7944
+ headNumber: Number(head.number),
7945
+ headTimestamp: head.timestamp,
7946
+ memo,
7947
+ validBefore,
7948
+ signedAt: nowSeconds,
7949
+ token: charge.token,
7950
+ recipient: charge.recipient,
7951
+ amount: charge.amount.toString()
7952
+ }
7953
+ };
7954
+ },
7955
+ async settle(context) {
7956
+ const { status, headers } = context.response;
7957
+ const encoded = headers.get("payment-receipt");
7958
+ if (status < 200 || status >= 300)
7959
+ return { outcome: "unknown", reason: `Paid request returned HTTP ${status}` };
7960
+ if (!encoded)
7961
+ return { outcome: "unknown", reason: "Paid request returned no settlement evidence" };
7962
+ let json;
7963
+ try {
7964
+ json = decodeMppJson(z5.unknown(), encoded);
7965
+ } catch {
7966
+ return {
7967
+ outcome: "unknown",
7968
+ reason: "Paid request returned malformed settlement evidence"
7969
+ };
7970
+ }
7971
+ const parsed = MppReceiptSchema.safeParse(json);
7972
+ if (!parsed.success)
7973
+ return { outcome: "rejected", reason: "receipt_invalid" };
7974
+ const receipt = parsed.data;
7975
+ return {
7976
+ outcome: "settled",
7977
+ amount: context.payment.record.authorizedAmount,
7978
+ transaction: receipt.reference
7979
+ };
7980
+ },
7981
+ async reconcile({ record, policy, signal }) {
7982
+ const data = chargeData(record.rail?.data);
7983
+ const token = getAddress8(data.token);
7984
+ const charged = BigInt(record.authorizedAmount);
7985
+ const worstFee = charged - BigInt(data.amount);
7986
+ try {
7987
+ const chain = await reader(record.network, policy);
7988
+ if (data.txHash !== null) {
7989
+ const receipt = await chain.transactionReceipt(data.txHash);
7990
+ if (receipt?.status === "success")
7991
+ return {
7992
+ outcome: "settled",
7993
+ amount: record.authorizedAmount,
7994
+ transaction: data.txHash
7995
+ };
7996
+ if (receipt) {
7997
+ const fee = receipt.feeUnits !== void 0 && receipt.feeUnits > 0n ? receipt.feeUnits : worstFee;
7998
+ return {
7999
+ outcome: "settled",
8000
+ amount: (fee < worstFee ? fee : worstFee).toString(),
8001
+ transaction: data.txHash
8002
+ };
8003
+ }
8004
+ }
8005
+ const latest = await chain.latestBlock();
8006
+ const start = BigInt(data.headNumber);
8007
+ if (start > latest.number)
8008
+ return { outcome: "pending" };
8009
+ const past = latest.timestamp > data.validBefore;
8010
+ let end = latest.number;
8011
+ if (past) {
8012
+ let low = start;
8013
+ let high = latest.number;
8014
+ while (low < high) {
8015
+ throwIfAborted(signal);
8016
+ const middle = (low + high) / 2n;
8017
+ if (await chain.blockTimestamp(middle) > data.validBefore)
8018
+ high = middle;
8019
+ else
8020
+ low = middle + 1n;
8021
+ }
8022
+ end = low;
8023
+ }
8024
+ let from = start;
8025
+ for (let range = 0; from <= end; range += 1) {
8026
+ if (range === MAX_LOG_RANGES)
8027
+ return { outcome: "pending" };
8028
+ throwIfAborted(signal);
8029
+ const to = from + MAX_LOG_RANGE - 1n < end ? from + MAX_LOG_RANGE - 1n : end;
8030
+ const logs = await chain.transfersWithMemo({
8031
+ token,
8032
+ from: getAddress8(record.payer),
8033
+ to: getAddress8(data.recipient),
8034
+ memo: data.memo,
8035
+ fromBlock: from,
8036
+ toBlock: to
8037
+ });
8038
+ if (logs.some((log) => log.amount === BigInt(data.amount)))
8039
+ return {
8040
+ outcome: "settled",
8041
+ amount: record.authorizedAmount,
8042
+ transaction: logs.find((log) => log.amount === BigInt(data.amount)).transactionHash
8043
+ };
8044
+ from = to + 1n;
8045
+ }
8046
+ if (!past || !data.sponsored && data.txHash === null)
8047
+ return { outcome: "pending" };
8048
+ return { outcome: "unspent" };
8049
+ } catch (error) {
8050
+ if (signal?.aborted)
8051
+ throw error;
8052
+ return { outcome: "pending" };
8053
+ }
8054
+ }
8055
+ };
8056
+ }
8057
+
7470
8058
  // src/lib/x402-paths.ts
7471
8059
  import path5 from "path";
7472
8060
  function getX402JournalPath() {
@@ -7478,6 +8066,7 @@ function getX402PolicyPath() {
7478
8066
 
7479
8067
  export {
7480
8068
  X402_INVOCATION_ID_PATTERN,
8069
+ X402_PAY_PROTOCOLS,
7481
8070
  X402PayError,
7482
8071
  withX402FileLock,
7483
8072
  x402SpendWindowAvailability,
@@ -7496,6 +8085,7 @@ export {
7496
8085
  createEvmPerRequestRail,
7497
8086
  assertX402HeaderName,
7498
8087
  assertX402HeaderValue,
8088
+ MPP_TEMPO_CHARGE_SCHEME,
7499
8089
  reconcileX402Payment,
7500
8090
  createX402Payer,
7501
8091
  createX402Allocations,
@@ -7510,6 +8100,7 @@ export {
7510
8100
  signSponsoredTempoTransfer,
7511
8101
  readMppTempoChallenge,
7512
8102
  createMppTempoCredential,
8103
+ createMppTempoChargeRail,
7513
8104
  getX402JournalPath,
7514
8105
  getX402PolicyPath
7515
8106
  };