@mysten-incubation/suipay-buyer 0.4.0-dev.0 → 0.4.0-dev.10

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/index.js CHANGED
@@ -13,7 +13,7 @@ import {
13
13
  parseErrorPayload,
14
14
  stricterPaymentState,
15
15
  toErrorFields
16
- } from "./chunk-BCI3TKYX.js";
16
+ } from "./chunk-RWUAPD7K.js";
17
17
 
18
18
  // src/mcp.ts
19
19
  async function buildMcpPaymentPayload(paymentRequired, signer) {
@@ -856,6 +856,9 @@ function verifyOwnerTransaction(input) {
856
856
  const cmd = commands[i];
857
857
  if (cmd.$kind === "MergeCoins") {
858
858
  const mc = cmd.MergeCoins;
859
+ if (JSON.stringify(mc.destination) !== JSON.stringify(splitCmd.SplitCoins.coin)) {
860
+ throw new TransactionVerificationError("funding");
861
+ }
859
862
  markInputOrResult(mc.destination);
860
863
  for (const s of mc.sources) {
861
864
  markInputOrResult(s);
@@ -1732,6 +1735,27 @@ function assertMoveFunction(target, expected) {
1732
1735
  if (fn !== expected)
1733
1736
  throw new TransactionVerificationError("target");
1734
1737
  }
1738
+ function assertPreparedGrantScopes(scopes, prepared, submitted = [], assets = TESTNET_ASSETS) {
1739
+ const declared = /* @__PURE__ */ new Set();
1740
+ for (const scope of scopes) {
1741
+ const asset = declaredAsset(scope.asset, assets);
1742
+ if (!asset || declared.has(asset.id))
1743
+ throw new TransactionVerificationError("coinType");
1744
+ declared.add(asset.id);
1745
+ }
1746
+ const seenAssets = /* @__PURE__ */ new Set();
1747
+ const seenIds = /* @__PURE__ */ new Set();
1748
+ for (const grant of [...prepared, ...submitted]) {
1749
+ const asset = "coinType" in grant && typeof grant.coinType === "string" && declaredAsset(grant.coinType, assets) || declaredAsset(grant.asset, assets);
1750
+ if (!asset || !declared.has(asset.id))
1751
+ throw new TransactionVerificationError("coinType");
1752
+ if (seenAssets.has(asset.id) || seenIds.has(grant.grantId)) {
1753
+ throw new TransactionVerificationError("grants");
1754
+ }
1755
+ seenAssets.add(asset.id);
1756
+ seenIds.add(grant.grantId);
1757
+ }
1758
+ }
1735
1759
 
1736
1760
  // ../sdk/dist/buyer/v1/delegated-signers.js
1737
1761
  function createAgentsApi(transport) {
@@ -1831,6 +1855,7 @@ function createAgentsApi(transport) {
1831
1855
  const created = await create(input);
1832
1856
  if (!created.ok)
1833
1857
  return created;
1858
+ assertPreparedGrantScopes(input.assetScopes, created.value.grants, created.value.submitted);
1834
1859
  const finalized = [];
1835
1860
  for (const submitted of created.value.submitted ?? []) {
1836
1861
  const fin = await finalizeGrant(created.value.delegatedSignerId, submitted.grantId, submitted.digest);
@@ -2386,6 +2411,7 @@ function createSessionsApi(transport, intents) {
2386
2411
  }
2387
2412
 
2388
2413
  // ../sdk/dist/buyer/v1/discovery.js
2414
+ var MAX_SERVICE_PAGES = 20;
2389
2415
  function createCatalogApi(transport) {
2390
2416
  return {
2391
2417
  async services() {
@@ -2401,12 +2427,31 @@ function createCatalogApi(transport) {
2401
2427
  function createRegistryApi(transport) {
2402
2428
  return {
2403
2429
  async list() {
2404
- const response = await transport.request("/v1/services");
2405
- const { status, body } = response;
2406
- if (status !== 200 || !isRecord(body) || !Array.isArray(body.services)) {
2407
- return fail(response);
2430
+ const services = [];
2431
+ let cursor = null;
2432
+ const seen = /* @__PURE__ */ new Set();
2433
+ for (let page = 0; page < MAX_SERVICE_PAGES; page++) {
2434
+ const path = cursor ? `/v1/services?cursor=${encodeURIComponent(cursor)}` : "/v1/services";
2435
+ const response = await transport.request(path);
2436
+ const { status, body } = response;
2437
+ if (status !== 200 || !isRecord(body) || !Array.isArray(body.services)) {
2438
+ return fail(response);
2439
+ }
2440
+ services.push(...asDto(body.services));
2441
+ const next = body.nextCursor;
2442
+ if (typeof next !== "string" || next === "")
2443
+ return ok(services);
2444
+ if (seen.has(next) || page + 1 >= MAX_SERVICE_PAGES) {
2445
+ return failLocal(502, "client.unexpected", "not_charged", {
2446
+ message: "the gateway catalog was truncated"
2447
+ });
2448
+ }
2449
+ seen.add(next);
2450
+ cursor = next;
2408
2451
  }
2409
- return ok(asDto(body.services));
2452
+ return failLocal(502, "client.unexpected", "not_charged", {
2453
+ message: "the gateway catalog was truncated"
2454
+ });
2410
2455
  },
2411
2456
  async get(id) {
2412
2457
  const response = await transport.request(`/v1/services/${encodeURIComponent(id)}`);
@@ -2513,7 +2558,7 @@ function createBuyerControlPlane(options) {
2513
2558
  var createBuyer = createBuyerControlPlane;
2514
2559
 
2515
2560
  // ../sdk/dist/agent-sdk/delegate-agent.js
2516
- import { normalizeSuiAddress as normalizeSuiAddress11 } from "@mysten/sui/utils";
2561
+ import { normalizeSuiAddress as normalizeSuiAddress12 } from "@mysten/sui/utils";
2517
2562
 
2518
2563
  // ../sdk/dist/buyer-control/chain.js
2519
2564
  import { bcs as bcs2 } from "@mysten/sui/bcs";
@@ -2580,7 +2625,30 @@ function createFailoverGrpcClient(options) {
2580
2625
  const clients = endpoints.map((baseUrl) => new SuiGrpcClient({ network: options.network, baseUrl }));
2581
2626
  return wrapFailover(clients, { sleep: endpointRetrySleep });
2582
2627
  }
2583
- var FAILOVER_SERVICES = ["core", "ledgerService"];
2628
+ var FAILOVER_SERVICES = ["core", "ledgerService", "movePackageService"];
2629
+ var UNARY_RESULT_PROPERTIES = ["headers", "response", "status", "trailers"];
2630
+ function isUnaryCall(value) {
2631
+ return "method" in value && "request" in value && "requestHeaders" in value && UNARY_RESULT_PROPERTIES.every((prop) => typeof value[prop]?.then === "function");
2632
+ }
2633
+ function unaryCallWithFailover(first, finished) {
2634
+ const then = finished.then.bind(finished);
2635
+ const properties = /* @__PURE__ */ new Map();
2636
+ return new Proxy(first, {
2637
+ get(target, prop) {
2638
+ if (prop === "then")
2639
+ return then;
2640
+ if (UNARY_RESULT_PROPERTIES.includes(prop)) {
2641
+ let value = properties.get(prop);
2642
+ if (!value) {
2643
+ value = finished.then((call) => call[prop]);
2644
+ properties.set(prop, value);
2645
+ }
2646
+ return value;
2647
+ }
2648
+ return Reflect.get(target, prop, target);
2649
+ }
2650
+ });
2651
+ }
2584
2652
  function wrapFailover(clients, options = {}) {
2585
2653
  const primary = clients[0];
2586
2654
  const attempts = Math.max(1, options.attempts ?? RPC_ATTEMPTS_PER_ENDPOINT);
@@ -2598,10 +2666,14 @@ function wrapFailover(clients, options = {}) {
2598
2666
  return (...args) => {
2599
2667
  const first = callOn(primary, prop, args);
2600
2668
  const attemptsFor = prop === "executeTransaction" ? 1 : attempts;
2601
- if (first == null || typeof first.then !== "function" || typeof first.catch !== "function") {
2669
+ if (first == null || typeof first.then !== "function") {
2602
2670
  return first;
2603
2671
  }
2604
- return (async () => {
2672
+ const promise = typeof first.catch === "function";
2673
+ const unary = !promise && typeof first === "object" && isUnaryCall(first);
2674
+ if (!promise && !unary)
2675
+ return first;
2676
+ const finished = (async () => {
2605
2677
  let last;
2606
2678
  for (let endpoint = 0; endpoint < clients.length; endpoint++) {
2607
2679
  for (let attempt = 0; attempt < attemptsFor; attempt++) {
@@ -2623,6 +2695,7 @@ function wrapFailover(clients, options = {}) {
2623
2695
  }
2624
2696
  throw last;
2625
2697
  })();
2698
+ return unary ? unaryCallWithFailover(first, finished) : finished;
2626
2699
  };
2627
2700
  }
2628
2701
  });
@@ -2915,6 +2988,25 @@ var SERVICE_STATE_TRANSITIONS = Object.freeze([
2915
2988
  to: "none",
2916
2989
  actors: ["system"],
2917
2990
  requires: ["reason_code"]
2991
+ },
2992
+ // System listing moves for permissionless services: auto-list after
2993
+ // proof-of-settle (never lifts an operator delist) and reset to unlisted
2994
+ // when a revision changes the published seller URL.
2995
+ {
2996
+ id: "T26",
2997
+ dimension: "listing",
2998
+ from: ["unlisted"],
2999
+ to: "listed",
3000
+ actors: ["system"],
3001
+ requires: ["admission_admitted"]
3002
+ },
3003
+ {
3004
+ id: "T27",
3005
+ dimension: "listing",
3006
+ from: ["listed"],
3007
+ to: "unlisted",
3008
+ actors: ["system"],
3009
+ requires: ["reason_code"]
2918
3010
  }
2919
3011
  ]);
2920
3012
 
@@ -3127,6 +3219,38 @@ function createSpendAccountChain(options) {
3127
3219
  });
3128
3220
  const packageId = normalizeSuiAddress3(options.packageId);
3129
3221
  const target = (fn) => `${packageId}::${MODULE}::${fn}`;
3222
+ let grantRevokePackageId = null;
3223
+ async function readGrantRevokePackageId() {
3224
+ if (grantRevokePackageId)
3225
+ return grantRevokePackageId;
3226
+ try {
3227
+ const answer = await client.movePackageService.getDatatype({
3228
+ packageId,
3229
+ moduleName: MODULE,
3230
+ name: "GrantRevoked"
3231
+ });
3232
+ const definingId = answer.response?.datatype?.definingId;
3233
+ if (!definingId?.trim()) {
3234
+ logError({
3235
+ scope: "sdk.buyer-control",
3236
+ code: "chain.unavailable",
3237
+ level: "warn",
3238
+ msg: "Grant revoke datatype origin lookup returned no defining id"
3239
+ });
3240
+ return null;
3241
+ }
3242
+ grantRevokePackageId = normalizeSuiAddress3(definingId);
3243
+ return grantRevokePackageId;
3244
+ } catch (err) {
3245
+ logError({
3246
+ scope: "sdk.buyer-control",
3247
+ code: "chain.unavailable",
3248
+ level: "warn",
3249
+ msg: "Grant revoke datatype origin lookup failed"
3250
+ }, err);
3251
+ return null;
3252
+ }
3253
+ }
3130
3254
  async function kindBytes(tx) {
3131
3255
  return {
3132
3256
  kindBytes: toBase64(await tx.build({ client, onlyTransactionKind: true }))
@@ -3735,6 +3859,44 @@ function createSpendAccountChain(options) {
3735
3859
  return null;
3736
3860
  }
3737
3861
  },
3862
+ readGrantRevokePackageId,
3863
+ async findGrantRevokeTransaction({ ownerAddress, grantObjectId }) {
3864
+ try {
3865
+ const owner = normalizeSuiAddress3(ownerAddress);
3866
+ const grant = normalizeSuiAddress3(grantObjectId);
3867
+ const definingId = await readGrantRevokePackageId();
3868
+ if (!definingId)
3869
+ return null;
3870
+ const eventType = `${definingId}::${MODULE}::GrantRevoked`;
3871
+ let before = null;
3872
+ let inspected = 0;
3873
+ for (let page = 0; page < 8 && inspected < 200; page++) {
3874
+ const result = await client.core.listEvents({
3875
+ filter: { sender: owner },
3876
+ order: "descending",
3877
+ limit: Math.min(50, 200 - inspected),
3878
+ before
3879
+ });
3880
+ for (const event of result.events.slice(0, 200 - inspected)) {
3881
+ inspected++;
3882
+ if (event.eventType !== eventType)
3883
+ continue;
3884
+ const json = event.json;
3885
+ if (typeof json?.grant !== "string" || normalizeSuiAddress3(json.grant) !== grant)
3886
+ continue;
3887
+ const digest = event.transactionDigest.trim();
3888
+ if (digest)
3889
+ return digest;
3890
+ }
3891
+ if (!result.hasNextPage || !result.endCursor || result.endCursor === before)
3892
+ return null;
3893
+ before = result.endCursor;
3894
+ }
3895
+ return null;
3896
+ } catch {
3897
+ return null;
3898
+ }
3899
+ },
3738
3900
  async readPolicyBudget({ poolObjectId, onChainPolicyId }) {
3739
3901
  try {
3740
3902
  const response = await client.core.getDynamicField({
@@ -4722,8 +4884,8 @@ function createGrpcExclusionRegistryReader(client) {
4722
4884
 
4723
4885
  // ../sdk/dist/delegated-signer/payer.js
4724
4886
  import { bcs as bcs7 } from "@mysten/sui/bcs";
4725
- import { Transaction as Transaction4 } from "@mysten/sui/transactions";
4726
- import { fromBase64 as fromBase647, normalizeStructTag as normalizeStructTag10, normalizeSuiAddress as normalizeSuiAddress9, toBase64 as toBase645 } from "@mysten/sui/utils";
4887
+ import { Transaction as Transaction5 } from "@mysten/sui/transactions";
4888
+ import { fromBase64 as fromBase648, normalizeStructTag as normalizeStructTag10, normalizeSuiAddress as normalizeSuiAddress10, toBase64 as toBase645 } from "@mysten/sui/utils";
4727
4889
  import { Ed25519Keypair } from "@mysten/sui/keypairs/ed25519";
4728
4890
 
4729
4891
  // ../sdk/dist/delegated-signer/finality-poll.js
@@ -4748,186 +4910,9 @@ async function pollFinality(input) {
4748
4910
  return { status: "timeout" };
4749
4911
  }
4750
4912
 
4751
- // ../sdk/dist/pay-operation/operation.js
4752
- import { normalizeStructTag as normalizeStructTag9, normalizeSuiAddress as normalizeSuiAddress6 } from "@mysten/sui/utils";
4753
-
4754
- // ../core/dist/policy/grant-target.js
4755
- function normalizeHash(hex) {
4756
- return hex.replace(/^0x/i, "").toLowerCase();
4757
- }
4758
- function grantAuthorityUsable(snapshot) {
4759
- if (snapshot.status === "paused") {
4760
- return { ok: false, reason: "grant is paused" };
4761
- }
4762
- if (snapshot.status === "revoked") {
4763
- return { ok: false, reason: "grant is revoked" };
4764
- }
4765
- if (snapshot.status === "expired") {
4766
- return { ok: false, reason: "grant is expired" };
4767
- }
4768
- if (snapshot.status !== "active") {
4769
- return { ok: false, reason: `grant status is ${snapshot.status}` };
4770
- }
4771
- if (!snapshot.grantObjectId?.trim()) {
4772
- return { ok: false, reason: "grant is not finalized (missing grantObjectId)" };
4773
- }
4774
- if (!snapshot.poolObjectId?.trim()) {
4775
- return { ok: false, reason: "poolObjectId is required" };
4776
- }
4777
- return {
4778
- ok: true,
4779
- grantObjectId: snapshot.grantObjectId,
4780
- poolObjectId: snapshot.poolObjectId
4781
- };
4782
- }
4783
- function resolveGrantTarget(snapshot, offerTargetHash) {
4784
- if (!offerTargetHash?.trim()) {
4785
- return { ok: false, reason: "offer.targetHash is required" };
4786
- }
4787
- const wanted = normalizeHash(offerTargetHash);
4788
- if (!/^[0-9a-f]{64}$/.test(wanted)) {
4789
- return { ok: false, reason: "offer.targetHash must be 32-byte hex" };
4790
- }
4791
- const usable = grantAuthorityUsable(snapshot);
4792
- if (!usable.ok) {
4793
- return usable;
4794
- }
4795
- const hits = [];
4796
- for (const policy of snapshot.policies) {
4797
- if (policy.status !== "active")
4798
- continue;
4799
- for (const target of policy.targets) {
4800
- if (normalizeHash(target.targetHash) === wanted) {
4801
- hits.push({
4802
- policyId: policy.policyId,
4803
- onChainPolicyId: policy.onChainPolicyId,
4804
- maxPerPayment: target.maxPerPayment
4805
- });
4806
- }
4807
- }
4808
- }
4809
- if (hits.length > 1) {
4810
- return {
4811
- ok: false,
4812
- reason: `target hash resolves to ${hits.length} active policies (EPolicyConflict)`
4813
- };
4814
- }
4815
- if (hits.length === 1) {
4816
- const hit = hits[0];
4817
- return {
4818
- ok: true,
4819
- policyId: hit.policyId,
4820
- onChainPolicyId: hit.onChainPolicyId,
4821
- targetHash: wanted,
4822
- maxPerPayment: hit.maxPerPayment,
4823
- poolObjectId: usable.poolObjectId,
4824
- grantObjectId: usable.grantObjectId,
4825
- coinType: snapshot.coinType,
4826
- delegateAddress: snapshot.delegateAddress
4827
- };
4828
- }
4829
- return {
4830
- ok: false,
4831
- reason: "no active policy in grant snapshot matches offer.targetHash"
4832
- };
4833
- }
4834
-
4835
- // ../sdk/dist/protocol/carrier.js
4836
- import { fromBase64 as fromBase645, toBase64 as toBase643 } from "@mysten/sui/utils";
4837
-
4838
- // ../sdk/dist/protocol/auth-params.js
4839
- var TOKEN = /^[A-Za-z0-9!#$%&'*+\-.^_`|~]+$/;
4840
- function parseAuthHeader(header) {
4841
- const trimmed = header.trim();
4842
- const firstSpace = trimmed.indexOf(" ");
4843
- if (firstSpace === -1)
4844
- return null;
4845
- const scheme = trimmed.slice(0, firstSpace);
4846
- if (!TOKEN.test(scheme))
4847
- return null;
4848
- const params = parseParams(trimmed.slice(firstSpace + 1));
4849
- return params === null ? null : { scheme, params };
4850
- }
4851
- function parseParams(input) {
4852
- const params = {};
4853
- let i = 0;
4854
- const skipSpace = () => {
4855
- while (i < input.length && (input[i] === " " || input[i] === " "))
4856
- i++;
4857
- };
4858
- skipSpace();
4859
- while (i < input.length) {
4860
- const keyStart = i;
4861
- while (i < input.length && input[i] !== "=")
4862
- i++;
4863
- if (i >= input.length)
4864
- return null;
4865
- const key = input.slice(keyStart, i).trim();
4866
- if (!TOKEN.test(key))
4867
- return null;
4868
- i++;
4869
- let value;
4870
- if (input[i] === '"') {
4871
- i++;
4872
- let out = "";
4873
- let closed = false;
4874
- while (i < input.length) {
4875
- const ch = input[i];
4876
- if (ch === "\\" && i + 1 < input.length) {
4877
- out += input[i + 1];
4878
- i += 2;
4879
- continue;
4880
- }
4881
- if (ch === '"') {
4882
- i++;
4883
- closed = true;
4884
- break;
4885
- }
4886
- out += ch;
4887
- i++;
4888
- }
4889
- if (!closed)
4890
- return null;
4891
- value = out;
4892
- } else {
4893
- const start = i;
4894
- while (i < input.length && input[i] !== ",")
4895
- i++;
4896
- value = input.slice(start, i).trim();
4897
- }
4898
- params[key] = value;
4899
- skipSpace();
4900
- if (i < input.length) {
4901
- if (input[i] !== ",")
4902
- return null;
4903
- i++;
4904
- skipSpace();
4905
- }
4906
- }
4907
- return params;
4908
- }
4909
-
4910
- // ../sdk/dist/protocol/base64url.js
4911
- function bytesToBase64Url(bytes) {
4912
- let binary = "";
4913
- for (const byte of bytes)
4914
- binary += String.fromCharCode(byte);
4915
- const base64 = typeof globalThis.btoa === "function" ? globalThis.btoa(binary) : Buffer.from(bytes).toString("base64");
4916
- return base64.replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/g, "");
4917
- }
4918
- function bytesFromBase64Url(s) {
4919
- const normalized = s.replace(/-/g, "+").replace(/_/g, "/");
4920
- const pad = (4 - normalized.length % 4) % 4;
4921
- const base64 = normalized + "=".repeat(pad);
4922
- if (typeof globalThis.atob === "function") {
4923
- const binary = globalThis.atob(base64);
4924
- const out = new Uint8Array(binary.length);
4925
- for (let i = 0; i < binary.length; i++)
4926
- out[i] = binary.charCodeAt(i);
4927
- return out;
4928
- }
4929
- return Uint8Array.from(Buffer.from(base64, "base64"));
4930
- }
4913
+ // ../sdk/dist/delegated-signer/pay-gas.js
4914
+ import { Transaction as Transaction3 } from "@mysten/sui/transactions";
4915
+ import { fromBase64 as fromBase644, normalizeSuiAddress as normalizeSuiAddress6 } from "@mysten/sui/utils";
4931
4916
 
4932
4917
  // ../sdk/dist/protocol/challenge.js
4933
4918
  import { Ed25519PublicKey } from "@mysten/sui/keypairs/ed25519";
@@ -5014,6 +4999,53 @@ var OMIT_WHEN_ABSENT = /* @__PURE__ */ new Set([
5014
4999
  ...V4_OMIT_WHEN_ABSENT
5015
5000
  ]);
5016
5001
  var BODY_HASH_RE = /^[A-Za-z0-9_-]{43}$/;
5002
+ var CONTROL_CHAR_RE = /[\x00-\x1f\x7f]/;
5003
+ var SIGNED_NUMBER_FIELDS = /* @__PURE__ */ new Set([
5004
+ "decimals",
5005
+ "issuedAt",
5006
+ "expiresAt",
5007
+ "digestVersion",
5008
+ "serviceRevision",
5009
+ "authorizationEpoch",
5010
+ "periodMs",
5011
+ "periodCount",
5012
+ "refundWindowMs",
5013
+ "decideWindowMs",
5014
+ "chainId",
5015
+ "exclusionProtocolVersion"
5016
+ ]);
5017
+ function hasValidSignedOfferFields(offer, requireComplete = true) {
5018
+ if (typeof offer !== "object" || offer === null || Array.isArray(offer))
5019
+ return false;
5020
+ const fields = offer;
5021
+ for (const key of SIGNED_FIELDS_V4) {
5022
+ const value = fields[key];
5023
+ if (value === void 0) {
5024
+ if (requireComplete && SIGNED_FIELDS_V1.includes(key))
5025
+ return false;
5026
+ continue;
5027
+ }
5028
+ if (SIGNED_NUMBER_FIELDS.has(key)) {
5029
+ if (typeof value !== "number" || !Number.isSafeInteger(value) || value < 0)
5030
+ return false;
5031
+ if (key === "digestVersion" && (value < 1 || value > 4))
5032
+ return false;
5033
+ } else if (key === "refundable") {
5034
+ if (typeof value !== "boolean")
5035
+ return false;
5036
+ } else if (key === "acceptedRails") {
5037
+ if (!Array.isArray(value))
5038
+ return false;
5039
+ for (const rail of value) {
5040
+ if (typeof rail !== "string" || CONTROL_CHAR_RE.test(rail) || rail.includes(","))
5041
+ return false;
5042
+ }
5043
+ } else if (typeof value !== "string" || CONTROL_CHAR_RE.test(value)) {
5044
+ return false;
5045
+ }
5046
+ }
5047
+ return true;
5048
+ }
5017
5049
  var CONTENT_TYPE_RE = /^[a-z0-9!#$%&'*+.^_`|~-]+\/[a-z0-9!#$%&'*+.^_`|~-]+(?:; ?[a-z0-9!#$%&'*+.^_`|~-]+=(?:[a-zA-Z0-9!#$%&'*+.^_`|~-]+|"[^"\n\r]*"))*$/;
5018
5050
  function isBodyHash(value) {
5019
5051
  return typeof value === "string" && BODY_HASH_RE.test(value);
@@ -5192,6 +5224,8 @@ function toRawEd25519PublicKey(key) {
5192
5224
  throw new Error("unsupported Ed25519 public key representation");
5193
5225
  }
5194
5226
  function verifyOfferSig(offer, publicKey) {
5227
+ if (!hasValidSignedOfferFields(offer, false))
5228
+ return Promise.resolve(false);
5195
5229
  if (!offer.sig || typeof offer.sig !== "string")
5196
5230
  return Promise.resolve(false);
5197
5231
  if (!offer.digest || typeof offer.digest !== "string" || !offer.digest.trim() || offer.digest !== offer.digest.trim()) {
@@ -5266,6 +5300,275 @@ function addressBalanceGasExpiration(input) {
5266
5300
  };
5267
5301
  }
5268
5302
 
5303
+ // ../sdk/dist/delegated-signer/pay-gas.js
5304
+ var DEFAULT_GAS_BUDGET = 10000000n;
5305
+ var DEFAULT_GAS_PRICE = 1000n;
5306
+ var X402_EXPIRATION_EPOCHS = 32n;
5307
+ async function readChainBound(read) {
5308
+ try {
5309
+ return await read();
5310
+ } catch (cause) {
5311
+ if (cause instanceof SuiPayError)
5312
+ throw cause;
5313
+ throw SuiPayError.of("chain.unavailable", "not_charged", {
5314
+ detail: "the pre-sign chain read is unavailable; no signature was produced"
5315
+ }, { cause });
5316
+ }
5317
+ }
5318
+ async function readPayExpirationPolicy(txBytes, readers) {
5319
+ const expiration = Transaction3.from(fromBase644(txBytes)).getData().expiration;
5320
+ if (expiration.$kind === "None")
5321
+ return void 0;
5322
+ if (!readers.getCurrentEpoch)
5323
+ throw new Error("a trusted current epoch is required");
5324
+ if (expiration.$kind !== "ValidDuring") {
5325
+ return { currentEpoch: BigInt(await readChainBound(readers.getCurrentEpoch)) };
5326
+ }
5327
+ if (!readers.getChainIdentifier)
5328
+ throw new Error("a trusted chain identifier is required");
5329
+ const [currentEpoch, chainIdentifier] = await Promise.all([
5330
+ readChainBound(readers.getCurrentEpoch),
5331
+ readChainBound(readers.getChainIdentifier)
5332
+ ]);
5333
+ return { currentEpoch: BigInt(currentEpoch), chainIdentifier };
5334
+ }
5335
+ function assertPayGas(data, delegate, policy = {}) {
5336
+ const actual = data.gasData;
5337
+ const agent = normalizeSuiAddress6(delegate);
5338
+ if (!actual.owner)
5339
+ throw new Error("transaction gas owner is missing");
5340
+ const owner = normalizeSuiAddress6(actual.owner);
5341
+ const pinned = policy.gas;
5342
+ if (policy.mode !== void 0 && policy.mode !== "agent" && policy.mode !== "sponsored") {
5343
+ throw new Error("transaction gas policy mode is invalid");
5344
+ }
5345
+ if (policy.mode === "agent") {
5346
+ if (!pinned)
5347
+ throw new Error("agent gas requires caller-owned gas inputs");
5348
+ } else if (owner === agent) {
5349
+ throw new Error("sponsored transaction gas owner must not be the delegate");
5350
+ }
5351
+ if (pinned) {
5352
+ const expectedOwner = normalizeSuiAddress6(pinned.owner ?? delegate);
5353
+ const samePayment = actual.payment.length === pinned.payment.length && pinned.payment.every((ref, i) => {
5354
+ const got = actual.payment[i];
5355
+ return normalizeSuiAddress6(got.objectId) === normalizeSuiAddress6(ref.objectId) && got.version === String(ref.version) && got.digest === ref.digest;
5356
+ });
5357
+ if (owner !== expectedOwner || actual.budget !== String(pinned.budget ?? DEFAULT_GAS_BUDGET) || actual.price !== String(pinned.price ?? DEFAULT_GAS_PRICE) || !samePayment) {
5358
+ throw new Error("transaction gas does not match the caller gas inputs");
5359
+ }
5360
+ }
5361
+ const expiration = data.expiration;
5362
+ const validity = policy.expiration;
5363
+ if (expiration.$kind === "None") {
5364
+ if (!actual.payment.length || validity?.requireBounded) {
5365
+ throw new Error("transaction gas requires bounded expiration");
5366
+ }
5367
+ return;
5368
+ }
5369
+ if (!validity || validity.currentEpoch < 0n) {
5370
+ throw new Error("transaction expiration has no trusted epoch bound");
5371
+ }
5372
+ const now = validity.currentEpoch;
5373
+ if (expiration.$kind === "Epoch") {
5374
+ const epoch = BigInt(expiration.Epoch);
5375
+ if (!actual.payment.length || epoch < now || epoch > now + X402_EXPIRATION_EPOCHS) {
5376
+ throw new Error("transaction epoch expiration is outside the allowed window");
5377
+ }
5378
+ return;
5379
+ }
5380
+ const window = expiration.ValidDuring;
5381
+ if (!validity.chainIdentifier || window.chain !== validity.chainIdentifier || window.minEpoch === null || window.maxEpoch === null || window.minTimestamp !== null || window.maxTimestamp !== null) {
5382
+ throw new Error("transaction validity does not match the trusted chain window");
5383
+ }
5384
+ const min = BigInt(window.minEpoch);
5385
+ const max = BigInt(window.maxEpoch);
5386
+ if (min > now || max < now || max > now + ADDRESS_BALANCE_VALIDITY_EPOCHS || max - min > ADDRESS_BALANCE_VALIDITY_EPOCHS) {
5387
+ throw new Error("transaction validity is outside the allowed epoch window");
5388
+ }
5389
+ }
5390
+
5391
+ // ../sdk/dist/pay-operation/operation.js
5392
+ import { normalizeStructTag as normalizeStructTag9, normalizeSuiAddress as normalizeSuiAddress7 } from "@mysten/sui/utils";
5393
+
5394
+ // ../core/dist/policy/grant-target.js
5395
+ function normalizeHash(hex) {
5396
+ return hex.replace(/^0x/i, "").toLowerCase();
5397
+ }
5398
+ function grantAuthorityUsable(snapshot) {
5399
+ if (snapshot.status === "paused") {
5400
+ return { ok: false, reason: "grant is paused" };
5401
+ }
5402
+ if (snapshot.status === "revoked") {
5403
+ return { ok: false, reason: "grant is revoked" };
5404
+ }
5405
+ if (snapshot.status === "expired") {
5406
+ return { ok: false, reason: "grant is expired" };
5407
+ }
5408
+ if (snapshot.status !== "active") {
5409
+ return { ok: false, reason: `grant status is ${snapshot.status}` };
5410
+ }
5411
+ if (!snapshot.grantObjectId?.trim()) {
5412
+ return { ok: false, reason: "grant is not finalized (missing grantObjectId)" };
5413
+ }
5414
+ if (!snapshot.poolObjectId?.trim()) {
5415
+ return { ok: false, reason: "poolObjectId is required" };
5416
+ }
5417
+ return {
5418
+ ok: true,
5419
+ grantObjectId: snapshot.grantObjectId,
5420
+ poolObjectId: snapshot.poolObjectId
5421
+ };
5422
+ }
5423
+ function resolveGrantTarget(snapshot, offerTargetHash) {
5424
+ if (!offerTargetHash?.trim()) {
5425
+ return { ok: false, reason: "offer.targetHash is required" };
5426
+ }
5427
+ const wanted = normalizeHash(offerTargetHash);
5428
+ if (!/^[0-9a-f]{64}$/.test(wanted)) {
5429
+ return { ok: false, reason: "offer.targetHash must be 32-byte hex" };
5430
+ }
5431
+ const usable = grantAuthorityUsable(snapshot);
5432
+ if (!usable.ok) {
5433
+ return usable;
5434
+ }
5435
+ const hits = [];
5436
+ for (const policy of snapshot.policies) {
5437
+ if (policy.status !== "active")
5438
+ continue;
5439
+ for (const target of policy.targets) {
5440
+ if (normalizeHash(target.targetHash) === wanted) {
5441
+ hits.push({
5442
+ policyId: policy.policyId,
5443
+ onChainPolicyId: policy.onChainPolicyId,
5444
+ maxPerPayment: target.maxPerPayment
5445
+ });
5446
+ }
5447
+ }
5448
+ }
5449
+ if (hits.length > 1) {
5450
+ return {
5451
+ ok: false,
5452
+ reason: `target hash resolves to ${hits.length} active policies (EPolicyConflict)`
5453
+ };
5454
+ }
5455
+ if (hits.length === 1) {
5456
+ const hit = hits[0];
5457
+ return {
5458
+ ok: true,
5459
+ policyId: hit.policyId,
5460
+ onChainPolicyId: hit.onChainPolicyId,
5461
+ targetHash: wanted,
5462
+ maxPerPayment: hit.maxPerPayment,
5463
+ poolObjectId: usable.poolObjectId,
5464
+ grantObjectId: usable.grantObjectId,
5465
+ coinType: snapshot.coinType,
5466
+ delegateAddress: snapshot.delegateAddress
5467
+ };
5468
+ }
5469
+ return {
5470
+ ok: false,
5471
+ reason: "no active policy in grant snapshot matches offer.targetHash"
5472
+ };
5473
+ }
5474
+
5475
+ // ../sdk/dist/protocol/carrier.js
5476
+ import { fromBase64 as fromBase646, toBase64 as toBase643 } from "@mysten/sui/utils";
5477
+
5478
+ // ../sdk/dist/protocol/auth-params.js
5479
+ var TOKEN = /^[A-Za-z0-9!#$%&'*+\-.^_`|~]+$/;
5480
+ function parseAuthHeader(header) {
5481
+ const trimmed = header.trim();
5482
+ const firstSpace = trimmed.indexOf(" ");
5483
+ if (firstSpace === -1)
5484
+ return null;
5485
+ const scheme = trimmed.slice(0, firstSpace);
5486
+ if (!TOKEN.test(scheme))
5487
+ return null;
5488
+ const params = parseParams(trimmed.slice(firstSpace + 1));
5489
+ return params === null ? null : { scheme, params };
5490
+ }
5491
+ function parseParams(input) {
5492
+ const params = {};
5493
+ let i = 0;
5494
+ const skipSpace = () => {
5495
+ while (i < input.length && (input[i] === " " || input[i] === " "))
5496
+ i++;
5497
+ };
5498
+ skipSpace();
5499
+ while (i < input.length) {
5500
+ const keyStart = i;
5501
+ while (i < input.length && input[i] !== "=")
5502
+ i++;
5503
+ if (i >= input.length)
5504
+ return null;
5505
+ const key = input.slice(keyStart, i).trim();
5506
+ if (!TOKEN.test(key))
5507
+ return null;
5508
+ i++;
5509
+ let value;
5510
+ if (input[i] === '"') {
5511
+ i++;
5512
+ let out = "";
5513
+ let closed = false;
5514
+ while (i < input.length) {
5515
+ const ch = input[i];
5516
+ if (ch === "\\" && i + 1 < input.length) {
5517
+ out += input[i + 1];
5518
+ i += 2;
5519
+ continue;
5520
+ }
5521
+ if (ch === '"') {
5522
+ i++;
5523
+ closed = true;
5524
+ break;
5525
+ }
5526
+ out += ch;
5527
+ i++;
5528
+ }
5529
+ if (!closed)
5530
+ return null;
5531
+ value = out;
5532
+ } else {
5533
+ const start = i;
5534
+ while (i < input.length && input[i] !== ",")
5535
+ i++;
5536
+ value = input.slice(start, i).trim();
5537
+ }
5538
+ params[key] = value;
5539
+ skipSpace();
5540
+ if (i < input.length) {
5541
+ if (input[i] !== ",")
5542
+ return null;
5543
+ i++;
5544
+ skipSpace();
5545
+ }
5546
+ }
5547
+ return params;
5548
+ }
5549
+
5550
+ // ../sdk/dist/protocol/base64url.js
5551
+ function bytesToBase64Url(bytes) {
5552
+ let binary = "";
5553
+ for (const byte of bytes)
5554
+ binary += String.fromCharCode(byte);
5555
+ const base64 = typeof globalThis.btoa === "function" ? globalThis.btoa(binary) : Buffer.from(bytes).toString("base64");
5556
+ return base64.replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/g, "");
5557
+ }
5558
+ function bytesFromBase64Url(s) {
5559
+ const normalized = s.replace(/-/g, "+").replace(/_/g, "/");
5560
+ const pad = (4 - normalized.length % 4) % 4;
5561
+ const base64 = normalized + "=".repeat(pad);
5562
+ if (typeof globalThis.atob === "function") {
5563
+ const binary = globalThis.atob(base64);
5564
+ const out = new Uint8Array(binary.length);
5565
+ for (let i = 0; i < binary.length; i++)
5566
+ out[i] = binary.charCodeAt(i);
5567
+ return out;
5568
+ }
5569
+ return Uint8Array.from(Buffer.from(base64, "base64"));
5570
+ }
5571
+
5269
5572
  // ../sdk/dist/protocol/mpp.js
5270
5573
  function offerToBase64Url(offer) {
5271
5574
  return bytesToBase64Url(new TextEncoder().encode(JSON.stringify(offer)));
@@ -5901,12 +6204,12 @@ function decodeReceipt(header) {
5901
6204
  }
5902
6205
 
5903
6206
  // ../sdk/dist/protocol/x402.js
5904
- import { fromBase64 as fromBase644, toBase64 as toBase642 } from "@mysten/sui/utils";
6207
+ import { fromBase64 as fromBase645, toBase64 as toBase642 } from "@mysten/sui/utils";
5905
6208
  function utf8ToBase64(text) {
5906
6209
  return toBase642(new TextEncoder().encode(text));
5907
6210
  }
5908
6211
  function base64ToUtf8(value) {
5909
- return new TextDecoder().decode(fromBase644(value));
6212
+ return new TextDecoder().decode(fromBase645(value));
5910
6213
  }
5911
6214
  var X402_VERSION = 2;
5912
6215
  var X402_SCHEME = "exact";
@@ -6237,7 +6540,7 @@ async function readChallenge(res, dialect, opts) {
6237
6540
  const headerVal = res.headers.get(X402_CHALLENGE_HEADER);
6238
6541
  if (headerVal) {
6239
6542
  try {
6240
- const parsed = JSON.parse(new TextDecoder().decode(fromBase645(headerVal)));
6543
+ const parsed = JSON.parse(new TextDecoder().decode(fromBase646(headerVal)));
6241
6544
  const offer = decodeChallenge2(parsed, opts);
6242
6545
  if (offer)
6243
6546
  return offer;
@@ -6401,8 +6704,35 @@ function assertPaidMethod(method) {
6401
6704
  return upper;
6402
6705
  throw new PaidRequestError("method", `paid request method must be GET or POST, got ${method}`);
6403
6706
  }
6707
+ var MAX_RAW_CONTENT_TYPE_LENGTH = 1024;
6708
+ var WHITESPACE = /\s/;
6709
+ function collapseAround(value, mark, replacement) {
6710
+ let out = "";
6711
+ let pending = "";
6712
+ let afterMark = false;
6713
+ for (const ch of value) {
6714
+ if (WHITESPACE.test(ch)) {
6715
+ if (!afterMark)
6716
+ pending += ch;
6717
+ continue;
6718
+ }
6719
+ if (ch === mark) {
6720
+ out += replacement;
6721
+ pending = "";
6722
+ afterMark = true;
6723
+ continue;
6724
+ }
6725
+ out += pending + ch;
6726
+ pending = "";
6727
+ afterMark = false;
6728
+ }
6729
+ return afterMark ? out : out + pending;
6730
+ }
6404
6731
  function normalizeContentType(value) {
6405
- const normalized = value.trim().toLowerCase().replace(/\s*;\s*/g, "; ").replace(/\s*=\s*/g, "=");
6732
+ if (value.length > MAX_RAW_CONTENT_TYPE_LENGTH) {
6733
+ throw new PaidRequestError("invalid", `paid request content type is ${value.length} characters; max is ${MAX_RAW_CONTENT_TYPE_LENGTH}`);
6734
+ }
6735
+ const normalized = collapseAround(collapseAround(value.trim().toLowerCase(), ";", "; "), "=", "=");
6406
6736
  if (!isOfferContentType(normalized)) {
6407
6737
  throw new PaidRequestError("invalid", `paid request content type is malformed: ${value}`);
6408
6738
  }
@@ -6826,7 +7156,7 @@ async function resolvePayment(input, deps) {
6826
7156
  }
6827
7157
  let packageMatches;
6828
7158
  try {
6829
- packageMatches = normalizeSuiAddress6(offer.packageId) === normalizeSuiAddress6(packageId);
7159
+ packageMatches = normalizeSuiAddress7(offer.packageId) === normalizeSuiAddress7(packageId);
6830
7160
  } catch {
6831
7161
  packageMatches = false;
6832
7162
  }
@@ -6873,7 +7203,7 @@ async function resolvePayment(input, deps) {
6873
7203
  if (!identity) {
6874
7204
  return failedWith(PAY_OPERATION_ERROR_CODES.BUILD_FAILED, "guarded offer carries no valid registry identity", challengeId);
6875
7205
  }
6876
- if (normalizeSuiAddress6(identity.packageId) !== normalizeSuiAddress6(offer.packageId)) {
7206
+ if (normalizeSuiAddress7(identity.packageId) !== normalizeSuiAddress7(offer.packageId)) {
6877
7207
  return failedWith(PAY_OPERATION_ERROR_CODES.BUILD_FAILED, `guarded registry identity package ${identity.packageId} does not match offer package ${offer.packageId}`, challengeId);
6878
7208
  }
6879
7209
  if (!resolveExclusionRegistry2) {
@@ -7068,8 +7398,8 @@ function validateAmount(offer, resolved) {
7068
7398
  import { randomBytes } from "crypto";
7069
7399
  import { bcs as bcs5 } from "@mysten/sui/bcs";
7070
7400
  import { isValidPersonalMessageSignature, verifyPersonalMessageSignature } from "@mysten/sui/verify";
7071
- import { fromBase64 as fromBase646, normalizeSuiAddress as normalizeSuiAddress7, toBase64 as toBase644 } from "@mysten/sui/utils";
7072
- import { Transaction as Transaction3 } from "@mysten/sui/transactions";
7401
+ import { fromBase64 as fromBase647, normalizeSuiAddress as normalizeSuiAddress8, toBase64 as toBase644 } from "@mysten/sui/utils";
7402
+ import { Transaction as Transaction4 } from "@mysten/sui/transactions";
7073
7403
  var SPONSOR_PERSONAL_MESSAGE_DOMAIN = "suipay:sponsor-personal-message:v1";
7074
7404
  function encodeSponsorPersonalMessagePayload(payload) {
7075
7405
  if (payload.domain !== SPONSOR_PERSONAL_MESSAGE_DOMAIN) {
@@ -7092,17 +7422,17 @@ function encodeSponsorPersonalMessagePayload(payload) {
7092
7422
  push(bcs5.vector(bcs5.u8()).serialize([...Buffer.from(payload.domain, "utf8")]).toBytes());
7093
7423
  push(bcs5.vector(bcs5.u8()).serialize([...Buffer.from(payload.nonce, "utf8")]).toBytes());
7094
7424
  push(bcs5.u64().serialize(BigInt(payload.expiryMs)).toBytes());
7095
- push(bcs5.Address.serialize(normalizeSuiAddress7(payload.delegate)).toBytes());
7096
- push(bcs5.Address.serialize(normalizeSuiAddress7(payload.poolId)).toBytes());
7097
- push(bcs5.Address.serialize(normalizeSuiAddress7(payload.grantId)).toBytes());
7425
+ push(bcs5.Address.serialize(normalizeSuiAddress8(payload.delegate)).toBytes());
7426
+ push(bcs5.Address.serialize(normalizeSuiAddress8(payload.poolId)).toBytes());
7427
+ push(bcs5.Address.serialize(normalizeSuiAddress8(payload.grantId)).toBytes());
7098
7428
  push(bcs5.vector(bcs5.u8()).serialize([...Buffer.from(payload.network, "utf8")]).toBytes());
7099
- push(bcs5.Address.serialize(normalizeSuiAddress7(payload.packageId)).toBytes());
7429
+ push(bcs5.Address.serialize(normalizeSuiAddress8(payload.packageId)).toBytes());
7100
7430
  push(bcs5.vector(bcs5.u8()).serialize([...Buffer.from(payload.requestId, "utf8")]).toBytes());
7101
7431
  push(bcs5.vector(bcs5.u8()).serialize([...payload.txKindHash]).toBytes());
7102
7432
  return Buffer.concat(parts.map((p) => Buffer.from(p)));
7103
7433
  }
7104
7434
  function hashTransactionKindBytes(kindBytes) {
7105
- const raw = typeof kindBytes === "string" ? fromBase646(kindBytes) : kindBytes;
7435
+ const raw = typeof kindBytes === "string" ? fromBase647(kindBytes) : kindBytes;
7106
7436
  return sha256(raw);
7107
7437
  }
7108
7438
  function buildSponsorPersonalMessagePayload(input) {
@@ -7110,11 +7440,11 @@ function buildSponsorPersonalMessagePayload(input) {
7110
7440
  domain: SPONSOR_PERSONAL_MESSAGE_DOMAIN,
7111
7441
  nonce: input.nonce,
7112
7442
  expiryMs: input.expiryMs,
7113
- delegate: normalizeSuiAddress7(input.delegate),
7114
- poolId: normalizeSuiAddress7(input.poolId),
7115
- grantId: normalizeSuiAddress7(input.grantId),
7443
+ delegate: normalizeSuiAddress8(input.delegate),
7444
+ poolId: normalizeSuiAddress8(input.poolId),
7445
+ grantId: normalizeSuiAddress8(input.grantId),
7116
7446
  network: input.network,
7117
- packageId: normalizeSuiAddress7(input.packageId),
7447
+ packageId: normalizeSuiAddress8(input.packageId),
7118
7448
  requestId: input.requestId,
7119
7449
  txKindHash: hashTransactionKindBytes(input.transactionKindBytes)
7120
7450
  };
@@ -7272,7 +7602,7 @@ function createOfferKeyResolver(gatewayUrl, options = {}) {
7272
7602
  import { bcs as bcs6 } from "@mysten/sui/bcs";
7273
7603
  import { messageWithIntent } from "@mysten/sui/cryptography";
7274
7604
  import { isValidPersonalMessageSignature as isValidPersonalMessageSignature2, verifyPersonalMessageSignature as verifyPersonalMessageSignature2 } from "@mysten/sui/verify";
7275
- import { normalizeSuiAddress as normalizeSuiAddress8 } from "@mysten/sui/utils";
7605
+ import { normalizeSuiAddress as normalizeSuiAddress9 } from "@mysten/sui/utils";
7276
7606
  var SIGNED_REQUEST_DOMAIN = "suipay:signed-request:v1";
7277
7607
  var BOOTSTRAP_REQUEST_DOMAIN = "suipay:bootstrap-request:v1";
7278
7608
  var SIGNED_REQUEST_MAX_AGE_MS = 3e5;
@@ -7304,7 +7634,7 @@ function encodeBootstrapRequest(payload) {
7304
7634
  throw new Error(`domain must be ${BOOTSTRAP_REQUEST_DOMAIN}`);
7305
7635
  }
7306
7636
  const utf8Vec = (s) => bcs6.vector(bcs6.u8()).serialize([...Buffer.from(s, "utf8")]).toBytes();
7307
- const addr = (a) => bcs6.Address.serialize(normalizeSuiAddress8(a)).toBytes();
7637
+ const addr = (a) => bcs6.Address.serialize(normalizeSuiAddress9(a)).toBytes();
7308
7638
  const parts = [
7309
7639
  utf8Vec(payload.domain),
7310
7640
  utf8Vec(payload.network),
@@ -7324,7 +7654,7 @@ function encodeSignedRequest(payload) {
7324
7654
  throw new Error(`domain must be ${SIGNED_REQUEST_DOMAIN}`);
7325
7655
  }
7326
7656
  const utf8Vec = (s) => bcs6.vector(bcs6.u8()).serialize([...Buffer.from(s, "utf8")]).toBytes();
7327
- const addr = (a) => bcs6.Address.serialize(normalizeSuiAddress8(a)).toBytes();
7657
+ const addr = (a) => bcs6.Address.serialize(normalizeSuiAddress9(a)).toBytes();
7328
7658
  const parts = [
7329
7659
  utf8Vec(payload.domain),
7330
7660
  utf8Vec(payload.network),
@@ -7763,7 +8093,6 @@ var bootstrapPayerGrants = bootstrapPayerSessions;
7763
8093
  // ../sdk/dist/delegated-signer/payer.js
7764
8094
  var FINALIZATION_ATTEMPTS = 20;
7765
8095
  var FINALIZATION_DELAY_MS = 250;
7766
- var X402_EXPIRATION_EPOCHS = 32n;
7767
8096
  var X402_PRESENT_ATTEMPTS = 10;
7768
8097
  var X402_PRESENT_DELAY_MS = 1e3;
7769
8098
  function delay(ms) {
@@ -7774,8 +8103,6 @@ function delay(ms) {
7774
8103
  var SUI_CLOCK2 = "0x6";
7775
8104
  var SUI_CLOCK_INITIAL_SHARED_VERSION = "1";
7776
8105
  var BROADCAST_UNKNOWN = "broadcast-unknown";
7777
- var DEFAULT_GAS_BUDGET = 10000000n;
7778
- var DEFAULT_GAS_PRICE = 1000n;
7779
8106
  var DELEGATED_PAY_ERROR_CODES = {
7780
8107
  OFFER_SECRET_REQUIRED: "OFFER_SECRET_REQUIRED",
7781
8108
  CHALLENGE_TAMPERED: "CHALLENGE_TAMPERED",
@@ -7850,6 +8177,8 @@ var DELEGATED_PAY_ERROR_CODE_SET = new Set(Object.values(DELEGATED_PAY_ERROR_COD
7850
8177
  function isDelegatedPayErrorCode(value) {
7851
8178
  return typeof value === "string" && DELEGATED_PAY_ERROR_CODE_SET.has(value);
7852
8179
  }
8180
+ var DELIVERY_SELLER_TIMEOUT_DETAIL = "Gateway timed out waiting for the paid service to deliver.";
8181
+ var EXECUTE_TIMEOUT_DETAIL = "Gateway timed out before confirming whether payment settled; check status before retrying.";
7853
8182
  var PUBLIC_DETAIL = {
7854
8183
  OFFER_SECRET_REQUIRED: "offer verification material is unavailable",
7855
8184
  CHALLENGE_TAMPERED: "offer digest does not verify",
@@ -8016,14 +8345,15 @@ function withReconcileKeys(error, extras) {
8016
8345
  };
8017
8346
  }
8018
8347
  async function gatewayDeliveryFailure(response, log, local) {
8348
+ const timedOut = response.status === 504;
8019
8349
  const result = gatewayFailure(await readGatewayAnswer(response), {
8020
- code: DELEGATED_PAY_CODES[local.code],
8350
+ code: timedOut ? "delivery.seller_timeout" : DELEGATED_PAY_CODES[local.code],
8021
8351
  paymentState: "charged",
8022
- detail: PUBLIC_DETAIL[local.code]
8352
+ detail: timedOut ? DELIVERY_SELLER_TIMEOUT_DETAIL : PUBLIC_DETAIL[local.code]
8023
8353
  }, { paymentId: local.paymentId, txDigest: local.txDigest, settlement: local.settlement });
8024
8354
  logInternal(log, {
8025
- code: "delivery.proof_rejected",
8026
- msg: "gateway did not deliver after settlement",
8355
+ code: timedOut ? "delivery.seller_timeout" : "delivery.proof_rejected",
8356
+ msg: timedOut ? "gateway timed out delivering after settlement" : "gateway did not deliver after settlement",
8027
8357
  context: {
8028
8358
  status: response.status,
8029
8359
  header: response.headers.get(ERROR_CODE_HEADER),
@@ -8079,7 +8409,7 @@ function defaultLog(entry, error) {
8079
8409
  }
8080
8410
  function sameAddress2(a, b) {
8081
8411
  try {
8082
- return normalizeSuiAddress9(a) === normalizeSuiAddress9(b);
8412
+ return normalizeSuiAddress10(a) === normalizeSuiAddress10(b);
8083
8413
  } catch {
8084
8414
  return false;
8085
8415
  }
@@ -8141,7 +8471,7 @@ async function resolveSigner(input) {
8141
8471
  return {
8142
8472
  address: kp.getPublicKey().toSuiAddress(),
8143
8473
  async signTransaction(txBytes) {
8144
- const { signature } = await kp.signTransaction(fromBase647(txBytes));
8474
+ const { signature } = await kp.signTransaction(fromBase648(txBytes));
8145
8475
  return signature;
8146
8476
  },
8147
8477
  async signPersonalMessage(message) {
@@ -8217,7 +8547,7 @@ async function buildSpendAccountPayKind(input) {
8217
8547
  }
8218
8548
  const target = payMoveCallTarget(input.packageId, "scoped", true, refundable);
8219
8549
  const clockVersion = input.clockInitialSharedVersion?.trim() || SUI_CLOCK_INITIAL_SHARED_VERSION;
8220
- const tx = new Transaction4();
8550
+ const tx = new Transaction5();
8221
8551
  tx.setSender(input.delegate);
8222
8552
  tx.moveCall({
8223
8553
  target,
@@ -8289,7 +8619,7 @@ async function buildSpendAccountSettleOpenRecipientKind(input) {
8289
8619
  const guarded = resolveGuardedSettleOfflineInputs(input);
8290
8620
  const target = payMoveCallTarget(input.packageId, "open");
8291
8621
  const clockVersion = input.clockInitialSharedVersion?.trim() || SUI_CLOCK_INITIAL_SHARED_VERSION;
8292
- const tx = new Transaction4();
8622
+ const tx = new Transaction5();
8293
8623
  tx.setSender(input.delegate);
8294
8624
  tx.moveCall({
8295
8625
  target,
@@ -8336,7 +8666,7 @@ async function buildSpendAccountPayTx(input) {
8336
8666
  throw new Error("agent gas payment objects are required for executable pay");
8337
8667
  }
8338
8668
  const { kindBytes } = await buildSpendAccountPayKind(input);
8339
- const tx = Transaction4.fromKind(fromBase647(kindBytes));
8669
+ const tx = Transaction5.fromKind(fromBase648(kindBytes));
8340
8670
  tx.setSender(input.delegate);
8341
8671
  tx.setGasOwner(input.gas.owner ?? input.delegate);
8342
8672
  tx.setGasBudget(BigInt(input.gas.budget ?? DEFAULT_GAS_BUDGET));
@@ -8354,7 +8684,7 @@ async function buildSpendAccountSettleOpenRecipientTx(input) {
8354
8684
  throw new Error("agent gas payment objects are required for executable pay");
8355
8685
  }
8356
8686
  const { kindBytes } = await buildSpendAccountSettleOpenRecipientKind(input);
8357
- const tx = Transaction4.fromKind(fromBase647(kindBytes));
8687
+ const tx = Transaction5.fromKind(fromBase648(kindBytes));
8358
8688
  tx.setSender(input.delegate);
8359
8689
  tx.setGasOwner(input.gas.owner ?? input.delegate);
8360
8690
  tx.setGasBudget(BigInt(input.gas.budget ?? DEFAULT_GAS_BUDGET));
@@ -8387,7 +8717,7 @@ function readX402GasPin(offer) {
8387
8717
  }
8388
8718
  async function buildSpendAccountX402PayTx(input) {
8389
8719
  const { kindBytes } = await buildSpendAccountPayKind(input);
8390
- const tx = Transaction4.fromKind(fromBase647(kindBytes));
8720
+ const tx = Transaction5.fromKind(fromBase648(kindBytes));
8391
8721
  tx.setSender(input.delegate);
8392
8722
  tx.setGasOwner(input.gas.owner);
8393
8723
  tx.setGasBudget(input.gas.budget);
@@ -8423,7 +8753,7 @@ function chainIdentifierReader(client) {
8423
8753
  function assertPayTransaction(txBytes, expected) {
8424
8754
  let data;
8425
8755
  try {
8426
- data = Transaction4.from(fromBase647(txBytes)).getData();
8756
+ data = Transaction5.from(fromBase648(txBytes)).getData();
8427
8757
  } catch {
8428
8758
  throw new Error("transaction is not valid Sui transaction bytes");
8429
8759
  }
@@ -8438,13 +8768,13 @@ function assertPayTransaction(txBytes, expected) {
8438
8768
  if (cmd.$kind !== "MoveCall" || !cmd.MoveCall) {
8439
8769
  throw new Error("transaction is not a MoveCall");
8440
8770
  }
8441
- const got = `${normalizeSuiAddress9(String(cmd.MoveCall.package))}::${cmd.MoveCall.module}::${cmd.MoveCall.function}`;
8771
+ const got = `${normalizeSuiAddress10(String(cmd.MoveCall.package))}::${cmd.MoveCall.module}::${cmd.MoveCall.function}`;
8442
8772
  if (got !== wanted) {
8443
8773
  throw new Error(`transaction does not reconstruct ${wanted}`);
8444
8774
  }
8445
8775
  let expectedKind;
8446
8776
  try {
8447
- expectedKind = Transaction4.fromKind(fromBase647(expected.kindBytes)).getData();
8777
+ expectedKind = Transaction5.fromKind(fromBase648(expected.kindBytes)).getData();
8448
8778
  } catch {
8449
8779
  throw new Error("intended pay kind baseline is invalid");
8450
8780
  }
@@ -8470,6 +8800,7 @@ function assertPayTransaction(txBytes, expected) {
8470
8800
  if (args && args.length !== expectedArgc) {
8471
8801
  throw new Error(`pay expects ${expectedArgc} arguments; got ${args.length}`);
8472
8802
  }
8803
+ assertPayGas(data, expected.delegate, expected.gas);
8473
8804
  }
8474
8805
  function asValidatedReceipt(value) {
8475
8806
  if (!value || typeof value !== "object")
@@ -9265,8 +9596,19 @@ async function payDelegatedSpendAccount(args) {
9265
9596
  }
9266
9597
  }
9267
9598
  try {
9268
- assertPayTransaction(txBytes, expectedPay);
9599
+ assertPayTransaction(txBytes, {
9600
+ ...expectedPay,
9601
+ gas: {
9602
+ mode: gasMode,
9603
+ ...gasMode === "agent" ? { gas: deps.gas } : {},
9604
+ expiration: await readPayExpirationPolicy(txBytes, deps)
9605
+ }
9606
+ });
9269
9607
  } catch (err) {
9608
+ if (err instanceof SuiPayError && err.code === "chain.unavailable") {
9609
+ logInternal(log, { code: "chain.unavailable", msg: "pre-sign chain read failed" }, err);
9610
+ return abortBeforeSign("PREPARED_VERIFY_UNAVAILABLE", PUBLIC_DETAIL.PREPARED_VERIFY_UNAVAILABLE);
9611
+ }
9270
9612
  logInternal(log, { code: "client.tx_mismatch", msg: "pre-sign pay validation failed" }, err);
9271
9613
  return abortBeforeSign(gasMode === "sponsored" ? "SPONSORED_TX_MISMATCH" : "TX_MISMATCH", gasMode === "sponsored" ? PUBLIC_DETAIL.SPONSORED_TX_MISMATCH : PUBLIC_DETAIL.TX_MISMATCH);
9272
9614
  }
@@ -9533,7 +9875,18 @@ async function payX402Reserved(ctx) {
9533
9875
  return ctx.abort("BUILD_FAILED", PUBLIC_DETAIL.BUILD_FAILED);
9534
9876
  }
9535
9877
  try {
9536
- assertPayTransaction(txBytes, ctx.expected);
9878
+ assertPayTransaction(txBytes, {
9879
+ ...ctx.expected,
9880
+ gas: {
9881
+ mode: "sponsored",
9882
+ gas: ctx.buildInput.gas,
9883
+ expiration: {
9884
+ currentEpoch: ctx.buildInput.currentEpoch,
9885
+ chainIdentifier: ctx.buildInput.chainIdentifier,
9886
+ requireBounded: true
9887
+ }
9888
+ }
9889
+ });
9537
9890
  } catch (err) {
9538
9891
  logInternal(log, { code: "client.tx_mismatch", msg: "pre-sign x402 pay validation failed" }, err);
9539
9892
  return ctx.abort("TX_MISMATCH", PUBLIC_DETAIL.TX_MISMATCH);
@@ -9664,22 +10017,23 @@ async function recordX402Answer(ctx, answer) {
9664
10017
  if (answer.kind === "undelivered") {
9665
10018
  const stated = parseErrorPayload(answer.answer)?.paymentState;
9666
10019
  const charged = answer.receipt !== null || stated === "charged";
10020
+ const timedOut = answer.answer.status === 504;
9667
10021
  const settlement2 = answer.receipt ? { ...ctx.settlement, txDigest: answer.receipt.txDigest } : void 0;
9668
10022
  const result = gatewayFailure(answer.answer, charged ? {
9669
- code: DELEGATED_PAY_CODES.GATEWAY_REFUSED,
10023
+ code: timedOut ? "delivery.seller_timeout" : DELEGATED_PAY_CODES.GATEWAY_REFUSED,
9670
10024
  paymentState: "charged",
9671
- detail: PUBLIC_DETAIL.GATEWAY_REFUSED
10025
+ detail: timedOut ? DELIVERY_SELLER_TIMEOUT_DETAIL : PUBLIC_DETAIL.GATEWAY_REFUSED
9672
10026
  } : {
9673
10027
  code: DELEGATED_PAY_CODES.EXECUTE_AMBIGUOUS,
9674
10028
  paymentState: "unknown",
9675
- detail: PUBLIC_DETAIL.EXECUTE_AMBIGUOUS
10029
+ detail: timedOut ? EXECUTE_TIMEOUT_DETAIL : PUBLIC_DETAIL.EXECUTE_AMBIGUOUS
9676
10030
  }, {
9677
10031
  paymentId,
9678
10032
  ...settlement2 ? { txDigest: settlement2.txDigest, settlement: settlement2 } : answer.txDigest ? { txDigest: answer.txDigest } : {}
9679
10033
  });
9680
10034
  logInternal(log, {
9681
- code: "delivery.proof_rejected",
9682
- msg: "gateway did not deliver against an x402 credential",
10035
+ code: charged && timedOut ? "delivery.seller_timeout" : "delivery.proof_rejected",
10036
+ msg: charged && timedOut ? "gateway timed out delivering against an x402 credential" : "gateway did not deliver against an x402 credential",
9683
10037
  context: { status: answer.answer.status, code: result.code }
9684
10038
  });
9685
10039
  return completeAttempt(ledger, paymentId, result, log);
@@ -9723,7 +10077,7 @@ function payMoveCallTarget(packageId, accessMode = "scoped", _guarded = false, r
9723
10077
  accessMode: accessMode === "open" ? "open" : "scoped",
9724
10078
  refundable
9725
10079
  });
9726
- return `${normalizeSuiAddress9(packageId)}::spend_account::${fn}`;
10080
+ return `${normalizeSuiAddress10(packageId)}::spend_account::${fn}`;
9727
10081
  }
9728
10082
  function resolveGuardedSettleOfflineInputs(input) {
9729
10083
  const core = [input.exclusionDirectoryId, input.recipientRegistryId, input.expiresAtMs];
@@ -9799,9 +10153,9 @@ function createMemoryLedger() {
9799
10153
  }
9800
10154
 
9801
10155
  // ../sdk/dist/agent-sdk/verify-prepared-settlement.js
9802
- import { normalizeSuiAddress as normalizeSuiAddress10 } from "@mysten/sui/utils";
9803
- import { Transaction as Transaction5 } from "@mysten/sui/transactions";
9804
- import { fromBase64 as fromBase648 } from "@mysten/sui/utils";
10156
+ import { normalizeSuiAddress as normalizeSuiAddress11 } from "@mysten/sui/utils";
10157
+ import { Transaction as Transaction6 } from "@mysten/sui/transactions";
10158
+ import { fromBase64 as fromBase649 } from "@mysten/sui/utils";
9805
10159
 
9806
10160
  // ../sdk/dist/protocol/prepared-settlement.js
9807
10161
  var PREPARED_SETTLEMENT_VERSION = 1;
@@ -9890,7 +10244,7 @@ function reject(field, message, cause) {
9890
10244
  }
9891
10245
  function sameAddress3(a, b) {
9892
10246
  try {
9893
- return normalizeSuiAddress10(a) === normalizeSuiAddress10(b);
10247
+ return normalizeSuiAddress11(a) === normalizeSuiAddress11(b);
9894
10248
  } catch {
9895
10249
  return false;
9896
10250
  }
@@ -9901,7 +10255,7 @@ function sameCoinType(a, b) {
9901
10255
  if (pkg === void 0 || rest.length !== 2)
9902
10256
  return value.trim();
9903
10257
  try {
9904
- return `${normalizeSuiAddress10(pkg)}::${rest.join("::")}`;
10258
+ return `${normalizeSuiAddress11(pkg)}::${rest.join("::")}`;
9905
10259
  } catch {
9906
10260
  return value.trim();
9907
10261
  }
@@ -9926,7 +10280,7 @@ async function verifyPreparedPayment(input) {
9926
10280
  }
9927
10281
  let data;
9928
10282
  try {
9929
- data = Transaction5.from(fromBase648(prepared.transactionBytes)).getData();
10283
+ data = Transaction6.from(fromBase649(prepared.transactionBytes)).getData();
9930
10284
  } catch {
9931
10285
  reject("transactionBytes", "prepared transaction bytes are not a Sui transaction");
9932
10286
  }
@@ -10041,9 +10395,15 @@ async function verifyPreparedPayment(input) {
10041
10395
  kindBytes: rebuilt,
10042
10396
  accessMode: prepared.accessMode,
10043
10397
  recipient: prepared.recipient,
10044
- refundable: offer.refundable === true
10398
+ refundable: offer.refundable === true,
10399
+ gas: {
10400
+ mode: "sponsored",
10401
+ expiration: await readPayExpirationPolicy(prepared.transactionBytes, input)
10402
+ }
10045
10403
  });
10046
10404
  } catch (err) {
10405
+ if (err instanceof SuiPayError && err.code === "chain.unavailable")
10406
+ throw err;
10047
10407
  reject("transactionBytes", "prepared transaction does not reconstruct the intended settlement", err);
10048
10408
  }
10049
10409
  return prepared;
@@ -10615,10 +10975,10 @@ async function verifyGrantOnChain(input) {
10615
10975
  ok: false,
10616
10976
  error: manifestError(MANIFEST_ERROR_CODES.GRANT_NOT_VERIFIED, detail)
10617
10977
  });
10618
- if (!state.delegateAddress || normalizeSuiAddress11(state.delegateAddress) !== normalizeSuiAddress11(input.delegateAddress)) {
10978
+ if (!state.delegateAddress || normalizeSuiAddress12(state.delegateAddress) !== normalizeSuiAddress12(input.delegateAddress)) {
10619
10979
  return notVerified(`grant ${input.grantObjectId} does not name this delegate on chain`);
10620
10980
  }
10621
- if (!state.poolObjectId || normalizeSuiAddress11(state.poolObjectId) !== normalizeSuiAddress11(input.poolObjectId)) {
10981
+ if (!state.poolObjectId || normalizeSuiAddress12(state.poolObjectId) !== normalizeSuiAddress12(input.poolObjectId)) {
10622
10982
  return notVerified(`grant ${input.grantObjectId} draws on a different pool than the one resolved`);
10623
10983
  }
10624
10984
  if (state.revoked === true) {
@@ -10766,7 +11126,9 @@ async function createPayer(options) {
10766
11126
  offer,
10767
11127
  delegateAddress: address,
10768
11128
  expectedGrantObjectId: binding.grantObjectId,
10769
- expectedPoolObjectId: binding.poolObjectId
11129
+ expectedPoolObjectId: binding.poolObjectId,
11130
+ getCurrentEpoch: deps.getCurrentEpoch,
11131
+ getChainIdentifier: deps.getChainIdentifier
10770
11132
  });
10771
11133
  }
10772
11134
  return {
@@ -10776,7 +11138,7 @@ async function createPayer(options) {
10776
11138
  }
10777
11139
 
10778
11140
  // ../sdk/dist/oauth/delegate-proof.js
10779
- import { normalizeSuiAddress as normalizeSuiAddress12 } from "@mysten/sui/utils";
11141
+ import { normalizeSuiAddress as normalizeSuiAddress13 } from "@mysten/sui/utils";
10780
11142
  import { verifyPersonalMessageSignature as verifyPersonalMessageSignature3 } from "@mysten/sui/verify";
10781
11143
  var OAUTH_DELEGATE_PROOF_TTL_MS = 15 * 6e4;
10782
11144
  function encodeOAuthDelegateProof(binding, expiresAtMs, ownerAddress) {
@@ -10790,8 +11152,8 @@ function encodeOAuthDelegateProof(binding, expiresAtMs, ownerAddress) {
10790
11152
  binding.resource,
10791
11153
  binding.scope,
10792
11154
  binding.codeChallenge,
10793
- normalizeSuiAddress12(binding.delegateAddress),
10794
- normalizeSuiAddress12(ownerAddress),
11155
+ normalizeSuiAddress13(binding.delegateAddress),
11156
+ normalizeSuiAddress13(ownerAddress),
10795
11157
  expiresAtMs
10796
11158
  ]));
10797
11159
  }
@@ -10801,10 +11163,10 @@ async function verifyOAuthDelegateProof(binding, proof, nowMs = Date.now(), expe
10801
11163
  const message = encodeOAuthDelegateProof(binding, p.expiresAtMs, p.ownerAddress);
10802
11164
  if (typeof p.signature !== "string" || p.signature.length > 8192 || p.expiresAtMs <= nowMs || p.expiresAtMs > nowMs + OAUTH_DELEGATE_PROOF_TTL_MS)
10803
11165
  return false;
10804
- if (expectedOwner && normalizeSuiAddress12(p.ownerAddress) !== normalizeSuiAddress12(expectedOwner))
11166
+ if (expectedOwner && normalizeSuiAddress13(p.ownerAddress) !== normalizeSuiAddress13(expectedOwner))
10805
11167
  return false;
10806
11168
  const publicKey = await verifyPersonalMessageSignature3(message, p.signature);
10807
- return publicKey.toSuiAddress() === normalizeSuiAddress12(binding.delegateAddress);
11169
+ return publicKey.toSuiAddress() === normalizeSuiAddress13(binding.delegateAddress);
10808
11170
  } catch {
10809
11171
  return false;
10810
11172
  }