@mysten-incubation/suipay-buyer 0.4.0-dev.1 → 0.4.0-dev.11

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.
@@ -43,6 +43,18 @@ var ACCOUNT_CODES = {
43
43
  nextAction: "fix_request",
44
44
  user: { title: "Agent address not valid", message: "Enter a valid agent address and try again." }
45
45
  },
46
+ "account.deposit_cap_exceeded": {
47
+ surfaces: ["gateway", "sdk", "browser"],
48
+ status: 403,
49
+ title: "Deposit would exceed the vault beta cap",
50
+ paymentState: "not_charged",
51
+ retry: "never",
52
+ nextAction: "fix_request",
53
+ user: {
54
+ title: "Over the beta vault limit",
55
+ message: "This deposit would put your vault over the Mainnet Beta cap. Deposit less, or withdraw first."
56
+ }
57
+ },
46
58
  "account.finalize_mismatch": {
47
59
  surfaces: ["gateway"],
48
60
  status: 409,
@@ -869,7 +881,7 @@ var DELIVERY_CODES = {
869
881
  user: { title: "Something went wrong", message: "No result came back from the service." }
870
882
  },
871
883
  "delivery.seller_timeout": {
872
- surfaces: ["gateway"],
884
+ surfaces: ["gateway", "sdk", "mcp_local", "mcp_hosted"],
873
885
  status: 504,
874
886
  title: "Seller timed out after payment",
875
887
  paymentState: "charged",
@@ -1110,6 +1122,16 @@ var INDEXER_CODES = {
1110
1122
  nextAction: "contact_support",
1111
1123
  user: null,
1112
1124
  logOnly: true
1125
+ },
1126
+ "indexer.unsettled_delivery": {
1127
+ surfaces: ["indexer"],
1128
+ status: null,
1129
+ title: "Delivered call has no matching on-chain settlement",
1130
+ paymentState: "not_charged",
1131
+ retry: "never",
1132
+ nextAction: "contact_support",
1133
+ user: null,
1134
+ logOnly: true
1113
1135
  }
1114
1136
  };
1115
1137
 
@@ -2112,6 +2134,16 @@ var SERVICE_CODES = {
2112
2134
  nextAction: "retry_later",
2113
2135
  user: { title: "Temporarily unavailable", message: "This isn't available right now. Try again in a moment." }
2114
2136
  },
2137
+ "service.halted": {
2138
+ surfaces: ["gateway", "seller", "console_server", "mcp_hosted", "browser"],
2139
+ status: 503,
2140
+ title: "Services halted temporarily",
2141
+ paymentState: "not_charged",
2142
+ retry: "after_delay",
2143
+ retryAfterSeconds: 5,
2144
+ nextAction: "retry_later",
2145
+ user: { title: "Services halted temporarily", message: "Try again in a moment." }
2146
+ },
2115
2147
  "service.not_ready": {
2116
2148
  surfaces: ["gateway", "seller", "console_server"],
2117
2149
  status: 503,
@@ -2395,8 +2427,7 @@ var VALUE_PATTERNS = [
2395
2427
  /-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?(?:-----END [A-Z ]*PRIVATE KEY-----|$)/g,
2396
2428
  // Sui bech32 private keys.
2397
2429
  /suiprivkey1[0-9a-z]{20,}/gi,
2398
- // JSON Web Tokens (delivery proofs, OAuth tokens).
2399
- /\beyJ[A-Za-z0-9_-]{5,}\.[A-Za-z0-9_-]{5,}\.[A-Za-z0-9_-]{5,}/g,
2430
+ // JSON Web Tokens are matched by `redactJwts`, not a regex here.
2400
2431
  // Bearer and Payment authorization values.
2401
2432
  /\b(Bearer|Payment|Basic)\s+[A-Za-z0-9\-._~+/=,:]{8,}(?:\s*,\s*[a-z]+="[^"]*")*/g,
2402
2433
  // `sk-…`-style vendor keys.
@@ -2406,6 +2437,44 @@ var VALUE_PATTERNS = [
2406
2437
  // Google API keys.
2407
2438
  /\bAIza[0-9A-Za-z_-]{30,}/g
2408
2439
  ];
2440
+ var JWT_POSITION = 2;
2441
+ var WORD_CHAR = /[A-Za-z0-9_]/;
2442
+ var JWT_CHAR = /[A-Za-z0-9_-]/;
2443
+ function redactJwts(text) {
2444
+ if (!text.includes("eyJ"))
2445
+ return text;
2446
+ const stop = new Int32Array(text.length + 1);
2447
+ stop[text.length] = text.length;
2448
+ for (let p = text.length - 1; p >= 0; p -= 1) {
2449
+ stop[p] = JWT_CHAR.test(text[p]) ? stop[p + 1] : p;
2450
+ }
2451
+ const segment = (from) => from <= text.length ? stop[from] : -1;
2452
+ let out = "";
2453
+ let last = 0;
2454
+ let i = text.indexOf("eyJ");
2455
+ while (i !== -1) {
2456
+ let end = -1;
2457
+ if (i === 0 || !WORD_CHAR.test(text[i - 1])) {
2458
+ const first = segment(i + 3);
2459
+ if (first - (i + 3) >= 5 && text[first] === ".") {
2460
+ const second = segment(first + 1);
2461
+ if (second - (first + 1) >= 5 && text[second] === ".") {
2462
+ const third = segment(second + 1);
2463
+ if (third - (second + 1) >= 5)
2464
+ end = third;
2465
+ }
2466
+ }
2467
+ }
2468
+ if (end === -1) {
2469
+ i = text.indexOf("eyJ", i + 1);
2470
+ continue;
2471
+ }
2472
+ out += text.slice(last, i) + REDACTED;
2473
+ last = end;
2474
+ i = text.indexOf("eyJ", end);
2475
+ }
2476
+ return out + text.slice(last);
2477
+ }
2409
2478
  var JSON_SECRET_KEY_COLON = new RegExp(String.raw`(\\?)(["'])([\w.-]{0,64}${SECRET_KEY_SOURCE}[\w.-]{0,64}|key)(\\\2|\2)(\s*:\s*)`, "gi");
2410
2479
  var KEY_VALUE_PATTERN = new RegExp(String.raw`((?:(?<![\w.-])[\w.-]{0,64}${SECRET_KEY_SOURCE}[\w.-]{0,64}|(?<![\w.-])key)\s*[:=]\s*)("(?:\\.|[^"\\])*"?|'(?:\\.|[^'\\])*'?|(?![[{])[^\s"',;&}]+)`, "gi");
2411
2480
  var INSPECT_SECRET_KEY = new RegExp(String.raw`(?:(?<![\w.-])[\w.-]{0,64}${SECRET_KEY_SOURCE}[\w.-]{0,64}|(?<![\w.-])key)\s*[:=]\s*`, "gi");
@@ -2443,8 +2512,11 @@ function redactSecrets(text) {
2443
2512
  const head = dropSplitToken(text.slice(0, REDACT_MAX_LENGTH));
2444
2513
  out = `${head} \u2026[truncated ${text.length - head.length} chars]`;
2445
2514
  }
2446
- for (const pattern of VALUE_PATTERNS)
2515
+ for (const [index, pattern] of VALUE_PATTERNS.entries()) {
2516
+ if (index === JWT_POSITION)
2517
+ out = redactJwts(out);
2447
2518
  out = out.replace(pattern, REDACTED);
2519
+ }
2448
2520
  out = out.replace(URL_PATTERN, (_match, scheme, userinfo, host, path, query) => `${scheme}://${userinfo ? `${REDACTED}@` : ""}${host}${path}${query ? `?${REDACTED}` : ""}`);
2449
2521
  out = out.replace(RELATIVE_URL_QUERY, (_m, prefix, path) => `${prefix}${path}?${REDACTED}`);
2450
2522
  out = redactJsonSecretValues(out);
@@ -2770,6 +2842,15 @@ function parseErrorPayload(input) {
2770
2842
  }
2771
2843
  return null;
2772
2844
  }
2845
+ var DEFINITE_PRE_BROADCAST_REFUSALS = /* @__PURE__ */ new Set([
2846
+ "auth.spend_not_whitelisted"
2847
+ ]);
2848
+ function isValidatedProblemRefusal(parsed, allowedCodes) {
2849
+ return parsed !== null && parsed.source === "problem" && parsed.paymentState === "not_charged" && isErrorCode(parsed.code) && allowedCodes.has(parsed.code) && definitionOf(parsed.code).status === parsed.status;
2850
+ }
2851
+ function isDefinitePreBroadcastRefusal(parsed) {
2852
+ return isValidatedProblemRefusal(parsed, DEFINITE_PRE_BROADCAST_REFUSALS);
2853
+ }
2773
2854
  function readX402Failure(headers) {
2774
2855
  for (const name of X402_RESPONSE_HEADERS) {
2775
2856
  const raw = readHeader(headers, name);
@@ -3059,9 +3140,11 @@ var CONTEXT_ALLOWLIST = /* @__PURE__ */ new Set([
3059
3140
  "ownerDailyMist",
3060
3141
  "ownerHourlyMist",
3061
3142
  "ownerIdentityDailyMist",
3143
+ "ownerIdentityHourlyMist",
3062
3144
  "delegateDailyMist",
3063
3145
  "delegateHourlyMist",
3064
3146
  "delegateIdentityDailyMist",
3147
+ "delegateIdentityHourlyMist",
3065
3148
  "consecutiveFailures",
3066
3149
  "failuresInARow",
3067
3150
  "epochReadFailures",
@@ -3538,6 +3621,9 @@ export {
3538
3621
  deriveNextAction,
3539
3622
  stricterPaymentState,
3540
3623
  parseErrorPayload,
3624
+ DEFINITE_PRE_BROADCAST_REFUSALS,
3625
+ isValidatedProblemRefusal,
3626
+ isDefinitePreBroadcastRefusal,
3541
3627
  logError,
3542
3628
  SuiPayError,
3543
3629
  toErrorFields,
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { E as ErrorCode, P as PaymentState, N as NextAction, R as Receipt, C as CodeFor, D as DelegationScope, O as Offer } from './native-transfer-DspFvMQc.js';
2
- export { B as BuildNativeTransferInput, M as McpPaymentSigner, a as NativeTransferAccept, b as NativeTransferBuild, c as NativeTransferError, d as NativeTransferGas, e as NativeTransferSignerInput, S as SuiPayError, f as SuiPayErrorFields, g as buildMcpPaymentPayload, h as buildNativeTransferBytes, i as createNativeTransferSigner, j as inspectNativeTransfer, t as toErrorFields } from './native-transfer-DspFvMQc.js';
1
+ import { E as ErrorCode, P as PaymentState, N as NextAction, R as Receipt, C as CodeFor, D as DelegationScope, O as Offer } from './native-transfer-B9FlBiJZ.js';
2
+ export { B as BuildNativeTransferInput, M as McpPaymentSigner, a as NativeTransferAccept, b as NativeTransferBuild, c as NativeTransferError, d as NativeTransferGas, e as NativeTransferSignerInput, S as SuiPayError, f as SuiPayErrorFields, g as buildMcpPaymentPayload, h as buildNativeTransferBytes, i as createNativeTransferSigner, j as inspectNativeTransfer, t as toErrorFields } from './native-transfer-B9FlBiJZ.js';
3
3
  import { SuiGrpcClient } from '@mysten/sui/grpc';
4
4
  import { Ed25519Keypair } from '@mysten/sui/keypairs/ed25519';
5
5
  import { KeyObject } from 'node:crypto';
package/dist/index.js CHANGED
@@ -1,4 +1,5 @@
1
1
  import {
2
+ DEFINITE_PRE_BROADCAST_REFUSALS,
2
3
  ERROR_CODE_HEADER,
3
4
  NativeTransferError,
4
5
  SuiPayError,
@@ -8,12 +9,14 @@ import {
8
9
  deriveNextAction,
9
10
  deriveRetryable,
10
11
  inspectNativeTransfer,
12
+ isDefinitePreBroadcastRefusal,
11
13
  isErrorCode,
14
+ isValidatedProblemRefusal,
12
15
  logError,
13
16
  parseErrorPayload,
14
17
  stricterPaymentState,
15
18
  toErrorFields
16
- } from "./chunk-BCI3TKYX.js";
19
+ } from "./chunk-QY52OWHD.js";
17
20
 
18
21
  // src/mcp.ts
19
22
  async function buildMcpPaymentPayload(paymentRequired, signer) {
@@ -43,6 +46,7 @@ var LEGACY_CONTROL_PLANE_CODES = {
43
46
  CAP_EXCEEDED: "account.limit_exceeded",
44
47
  CONFLICT: "request.conflict",
45
48
  CROSS_ASSET_FORBIDDEN: "account.asset_unsupported",
49
+ DEPOSIT_CAP_EXCEEDED: "account.deposit_cap_exceeded",
46
50
  EXPIRED: "request.expired",
47
51
  FINALIZE_MISMATCH: "account.finalize_mismatch",
48
52
  FINALIZE_UNVERIFIED: "chain.tx_unverified",
@@ -765,23 +769,35 @@ function verifyOwnerTransaction(input) {
765
769
  throw new TransactionVerificationError("target");
766
770
  }
767
771
  const bCall = lastCmd.MoveCall;
768
- const expectedFn = op.kind === "create_pool" ? "create_account" : "fund_account";
769
- if (bCall.module !== "spend_account" || bCall.function !== expectedFn) {
772
+ const limitedFn = op.kind === "create_pool" ? "create_account_limited" : "fund_account_limited";
773
+ const legacyFn = op.kind === "create_pool" ? "create_account" : "fund_account";
774
+ if (bCall.module !== "spend_account" || bCall.function !== limitedFn && bCall.function !== legacyFn) {
770
775
  throw new TransactionVerificationError("target");
771
776
  }
777
+ const useLimited = bCall.function === limitedFn;
772
778
  const bTypeArgs = bCall.typeArguments;
773
779
  if (bTypeArgs.length !== 1 || safeNormalizeStructTag(bTypeArgs[0]) !== normCoinType) {
774
780
  throw new TransactionVerificationError("coinType");
775
781
  }
776
782
  const bArgs = bCall.arguments;
777
- const bExpectedArgCount = op.kind === "create_pool" ? 1 : 2;
783
+ const bExpectedArgCount = useLimited ? op.kind === "create_pool" ? 2 : 3 : op.kind === "create_pool" ? 1 : 2;
778
784
  if (bArgs.length !== bExpectedArgCount) {
779
785
  throw new TransactionVerificationError("target");
780
786
  }
781
- if (op.kind === "top_up") {
787
+ if (useLimited) {
788
+ const dirIdx = markInput(bArgs[0]);
789
+ const dirInput = data.inputs[dirIdx];
790
+ const dirObj = dirInput?.Object;
791
+ if (!dirObj?.SharedObject) {
792
+ throw new TransactionVerificationError("target");
793
+ }
794
+ if (op.kind === "top_up") {
795
+ assertPoolInput(bArgs[1], expectedPool);
796
+ }
797
+ } else if (op.kind === "top_up") {
782
798
  assertPoolInput(bArgs[0], expectedPool);
783
799
  }
784
- const coinArg = op.kind === "create_pool" ? bArgs[0] : bArgs[1];
800
+ const coinArg = useLimited ? op.kind === "create_pool" ? bArgs[1] : bArgs[2] : op.kind === "create_pool" ? bArgs[0] : bArgs[1];
785
801
  const splitCmdIdx = commands.findIndex((c) => c.$kind === "SplitCoins");
786
802
  if (splitCmdIdx === -1) {
787
803
  throw new TransactionVerificationError("funding");
@@ -2411,6 +2427,7 @@ function createSessionsApi(transport, intents) {
2411
2427
  }
2412
2428
 
2413
2429
  // ../sdk/dist/buyer/v1/discovery.js
2430
+ var MAX_SERVICE_PAGES = 20;
2414
2431
  function createCatalogApi(transport) {
2415
2432
  return {
2416
2433
  async services() {
@@ -2426,12 +2443,31 @@ function createCatalogApi(transport) {
2426
2443
  function createRegistryApi(transport) {
2427
2444
  return {
2428
2445
  async list() {
2429
- const response = await transport.request("/v1/services");
2430
- const { status, body } = response;
2431
- if (status !== 200 || !isRecord(body) || !Array.isArray(body.services)) {
2432
- return fail(response);
2446
+ const services = [];
2447
+ let cursor = null;
2448
+ const seen = /* @__PURE__ */ new Set();
2449
+ for (let page = 0; page < MAX_SERVICE_PAGES; page++) {
2450
+ const path = cursor ? `/v1/services?cursor=${encodeURIComponent(cursor)}` : "/v1/services";
2451
+ const response = await transport.request(path);
2452
+ const { status, body } = response;
2453
+ if (status !== 200 || !isRecord(body) || !Array.isArray(body.services)) {
2454
+ return fail(response);
2455
+ }
2456
+ services.push(...asDto(body.services));
2457
+ const next = body.nextCursor;
2458
+ if (typeof next !== "string" || next === "")
2459
+ return ok(services);
2460
+ if (seen.has(next) || page + 1 >= MAX_SERVICE_PAGES) {
2461
+ return failLocal(502, "client.unexpected", "not_charged", {
2462
+ message: "the gateway catalog was truncated"
2463
+ });
2464
+ }
2465
+ seen.add(next);
2466
+ cursor = next;
2433
2467
  }
2434
- return ok(asDto(body.services));
2468
+ return failLocal(502, "client.unexpected", "not_charged", {
2469
+ message: "the gateway catalog was truncated"
2470
+ });
2435
2471
  },
2436
2472
  async get(id) {
2437
2473
  const response = await transport.request(`/v1/services/${encodeURIComponent(id)}`);
@@ -2968,6 +3004,25 @@ var SERVICE_STATE_TRANSITIONS = Object.freeze([
2968
3004
  to: "none",
2969
3005
  actors: ["system"],
2970
3006
  requires: ["reason_code"]
3007
+ },
3008
+ // System listing moves for permissionless services: auto-list after
3009
+ // proof-of-settle (never lifts an operator delist) and reset to unlisted
3010
+ // when a revision changes the published seller URL.
3011
+ {
3012
+ id: "T26",
3013
+ dimension: "listing",
3014
+ from: ["unlisted"],
3015
+ to: "listed",
3016
+ actors: ["system"],
3017
+ requires: ["admission_admitted"]
3018
+ },
3019
+ {
3020
+ id: "T27",
3021
+ dimension: "listing",
3022
+ from: ["listed"],
3023
+ to: "unlisted",
3024
+ actors: ["system"],
3025
+ requires: ["reason_code"]
2971
3026
  }
2972
3027
  ]);
2973
3028
 
@@ -3180,6 +3235,38 @@ function createSpendAccountChain(options) {
3180
3235
  });
3181
3236
  const packageId = normalizeSuiAddress3(options.packageId);
3182
3237
  const target = (fn) => `${packageId}::${MODULE}::${fn}`;
3238
+ let grantRevokePackageId = null;
3239
+ async function readGrantRevokePackageId() {
3240
+ if (grantRevokePackageId)
3241
+ return grantRevokePackageId;
3242
+ try {
3243
+ const answer = await client.movePackageService.getDatatype({
3244
+ packageId,
3245
+ moduleName: MODULE,
3246
+ name: "GrantRevoked"
3247
+ });
3248
+ const definingId = answer.response?.datatype?.definingId;
3249
+ if (!definingId?.trim()) {
3250
+ logError({
3251
+ scope: "sdk.buyer-control",
3252
+ code: "chain.unavailable",
3253
+ level: "warn",
3254
+ msg: "Grant revoke datatype origin lookup returned no defining id"
3255
+ });
3256
+ return null;
3257
+ }
3258
+ grantRevokePackageId = normalizeSuiAddress3(definingId);
3259
+ return grantRevokePackageId;
3260
+ } catch (err) {
3261
+ logError({
3262
+ scope: "sdk.buyer-control",
3263
+ code: "chain.unavailable",
3264
+ level: "warn",
3265
+ msg: "Grant revoke datatype origin lookup failed"
3266
+ }, err);
3267
+ return null;
3268
+ }
3269
+ }
3183
3270
  async function kindBytes(tx) {
3184
3271
  return {
3185
3272
  kindBytes: toBase64(await tx.build({ client, onlyTransactionKind: true }))
@@ -3287,22 +3374,38 @@ function createSpendAccountChain(options) {
3287
3374
  const tx = new Transaction2();
3288
3375
  tx.setSender(input.owner);
3289
3376
  const funding = await fundingCoin(tx, input.owner, input.coinType, BigInt(input.funding));
3290
- tx.moveCall({
3291
- target: target("create_account"),
3292
- typeArguments: [input.coinType],
3293
- arguments: [funding]
3294
- });
3377
+ if (input.exclusionDirectoryId) {
3378
+ tx.moveCall({
3379
+ target: target("create_account_limited"),
3380
+ typeArguments: [input.coinType],
3381
+ arguments: [tx.object(input.exclusionDirectoryId), funding]
3382
+ });
3383
+ } else {
3384
+ tx.moveCall({
3385
+ target: target("create_account"),
3386
+ typeArguments: [input.coinType],
3387
+ arguments: [funding]
3388
+ });
3389
+ }
3295
3390
  return kindBytes(tx);
3296
3391
  },
3297
3392
  async buildTopUpKind(input) {
3298
3393
  const tx = new Transaction2();
3299
3394
  tx.setSender(input.owner);
3300
3395
  const funding = await fundingCoin(tx, input.owner, input.coinType, BigInt(input.amount));
3301
- tx.moveCall({
3302
- target: target("fund_account"),
3303
- typeArguments: [input.coinType],
3304
- arguments: [tx.object(input.poolObjectId), funding]
3305
- });
3396
+ if (input.exclusionDirectoryId) {
3397
+ tx.moveCall({
3398
+ target: target("fund_account_limited"),
3399
+ typeArguments: [input.coinType],
3400
+ arguments: [tx.object(input.exclusionDirectoryId), tx.object(input.poolObjectId), funding]
3401
+ });
3402
+ } else {
3403
+ tx.moveCall({
3404
+ target: target("fund_account"),
3405
+ typeArguments: [input.coinType],
3406
+ arguments: [tx.object(input.poolObjectId), funding]
3407
+ });
3408
+ }
3306
3409
  return kindBytes(tx);
3307
3410
  },
3308
3411
  async buildWithdrawKind(input) {
@@ -3788,6 +3891,44 @@ function createSpendAccountChain(options) {
3788
3891
  return null;
3789
3892
  }
3790
3893
  },
3894
+ readGrantRevokePackageId,
3895
+ async findGrantRevokeTransaction({ ownerAddress, grantObjectId }) {
3896
+ try {
3897
+ const owner = normalizeSuiAddress3(ownerAddress);
3898
+ const grant = normalizeSuiAddress3(grantObjectId);
3899
+ const definingId = await readGrantRevokePackageId();
3900
+ if (!definingId)
3901
+ return null;
3902
+ const eventType = `${definingId}::${MODULE}::GrantRevoked`;
3903
+ let before = null;
3904
+ let inspected = 0;
3905
+ for (let page = 0; page < 8 && inspected < 200; page++) {
3906
+ const result = await client.core.listEvents({
3907
+ filter: { sender: owner },
3908
+ order: "descending",
3909
+ limit: Math.min(50, 200 - inspected),
3910
+ before
3911
+ });
3912
+ for (const event of result.events.slice(0, 200 - inspected)) {
3913
+ inspected++;
3914
+ if (event.eventType !== eventType)
3915
+ continue;
3916
+ const json = event.json;
3917
+ if (typeof json?.grant !== "string" || normalizeSuiAddress3(json.grant) !== grant)
3918
+ continue;
3919
+ const digest = event.transactionDigest.trim();
3920
+ if (digest)
3921
+ return digest;
3922
+ }
3923
+ if (!result.hasNextPage || !result.endCursor || result.endCursor === before)
3924
+ return null;
3925
+ before = result.endCursor;
3926
+ }
3927
+ return null;
3928
+ } catch {
3929
+ return null;
3930
+ }
3931
+ },
3791
3932
  async readPolicyBudget({ poolObjectId, onChainPolicyId }) {
3792
3933
  try {
3793
3934
  const response = await client.core.getDynamicField({
@@ -6595,8 +6736,35 @@ function assertPaidMethod(method) {
6595
6736
  return upper;
6596
6737
  throw new PaidRequestError("method", `paid request method must be GET or POST, got ${method}`);
6597
6738
  }
6739
+ var MAX_RAW_CONTENT_TYPE_LENGTH = 1024;
6740
+ var WHITESPACE = /\s/;
6741
+ function collapseAround(value, mark, replacement) {
6742
+ let out = "";
6743
+ let pending = "";
6744
+ let afterMark = false;
6745
+ for (const ch of value) {
6746
+ if (WHITESPACE.test(ch)) {
6747
+ if (!afterMark)
6748
+ pending += ch;
6749
+ continue;
6750
+ }
6751
+ if (ch === mark) {
6752
+ out += replacement;
6753
+ pending = "";
6754
+ afterMark = true;
6755
+ continue;
6756
+ }
6757
+ out += pending + ch;
6758
+ pending = "";
6759
+ afterMark = false;
6760
+ }
6761
+ return afterMark ? out : out + pending;
6762
+ }
6598
6763
  function normalizeContentType(value) {
6599
- const normalized = value.trim().toLowerCase().replace(/\s*;\s*/g, "; ").replace(/\s*=\s*/g, "=");
6764
+ if (value.length > MAX_RAW_CONTENT_TYPE_LENGTH) {
6765
+ throw new PaidRequestError("invalid", `paid request content type is ${value.length} characters; max is ${MAX_RAW_CONTENT_TYPE_LENGTH}`);
6766
+ }
6767
+ const normalized = collapseAround(collapseAround(value.trim().toLowerCase(), ";", "; "), "=", "=");
6600
6768
  if (!isOfferContentType(normalized)) {
6601
6769
  throw new PaidRequestError("invalid", `paid request content type is malformed: ${value}`);
6602
6770
  }
@@ -7914,6 +8082,12 @@ async function readPublicSessionState(getObjectJson, grantObjectId) {
7914
8082
  revoked: asBool(g.revoked)
7915
8083
  };
7916
8084
  }
8085
+ function isRevokedBootstrap(data) {
8086
+ if (!data || typeof data !== "object")
8087
+ return false;
8088
+ const dto = data;
8089
+ return Array.isArray(dto.grants) && dto.grants.length === 0 && dto.grantStatus === "revoked";
8090
+ }
7917
8091
  async function bootstrapPayerSessions(options) {
7918
8092
  const fetchImpl = options.fetchImpl ?? fetch;
7919
8093
  const basePath = options.basePath ?? "/v1/delegate";
@@ -8041,6 +8215,8 @@ var DELEGATED_PAY_ERROR_CODE_SET = new Set(Object.values(DELEGATED_PAY_ERROR_COD
8041
8215
  function isDelegatedPayErrorCode(value) {
8042
8216
  return typeof value === "string" && DELEGATED_PAY_ERROR_CODE_SET.has(value);
8043
8217
  }
8218
+ var DELIVERY_SELLER_TIMEOUT_DETAIL = "Gateway timed out waiting for the paid service to deliver.";
8219
+ var EXECUTE_TIMEOUT_DETAIL = "Gateway timed out before confirming whether payment settled; check status before retrying.";
8044
8220
  var PUBLIC_DETAIL = {
8045
8221
  OFFER_SECRET_REQUIRED: "offer verification material is unavailable",
8046
8222
  CHALLENGE_TAMPERED: "offer digest does not verify",
@@ -8207,14 +8383,15 @@ function withReconcileKeys(error, extras) {
8207
8383
  };
8208
8384
  }
8209
8385
  async function gatewayDeliveryFailure(response, log, local) {
8386
+ const timedOut = response.status === 504;
8210
8387
  const result = gatewayFailure(await readGatewayAnswer(response), {
8211
- code: DELEGATED_PAY_CODES[local.code],
8388
+ code: timedOut ? "delivery.seller_timeout" : DELEGATED_PAY_CODES[local.code],
8212
8389
  paymentState: "charged",
8213
- detail: PUBLIC_DETAIL[local.code]
8390
+ detail: timedOut ? DELIVERY_SELLER_TIMEOUT_DETAIL : PUBLIC_DETAIL[local.code]
8214
8391
  }, { paymentId: local.paymentId, txDigest: local.txDigest, settlement: local.settlement });
8215
8392
  logInternal(log, {
8216
- code: "delivery.proof_rejected",
8217
- msg: "gateway did not deliver after settlement",
8393
+ code: timedOut ? "delivery.seller_timeout" : "delivery.proof_rejected",
8394
+ msg: timedOut ? "gateway timed out delivering after settlement" : "gateway did not deliver after settlement",
8218
8395
  context: {
8219
8396
  status: response.status,
8220
8397
  header: response.headers.get(ERROR_CODE_HEADER),
@@ -8232,14 +8409,13 @@ function gatewayFailure(answer, local, extras) {
8232
8409
  txDigest: error.txDigest ?? extras.txDigest
8233
8410
  });
8234
8411
  }
8235
- var SPEND_NOT_WHITELISTED = "auth.spend_not_whitelisted";
8236
- var REFUSED_BEFORE_BROADCAST = {
8237
- [SPEND_NOT_WHITELISTED]: 403,
8238
- "limit.rate_limited": 429
8239
- };
8240
- async function spendWhitelistRefusal(response, paymentId) {
8412
+ var PRE_SIGN_SPONSOR_CREATE_REFUSALS = /* @__PURE__ */ new Set([
8413
+ ...DEFINITE_PRE_BROADCAST_REFUSALS,
8414
+ "limit.rate_limited"
8415
+ ]);
8416
+ async function sponsorProblemRefusal(response, paymentId, admit) {
8241
8417
  const parsed = parseErrorPayload(await readGatewayAnswer(response));
8242
- if (parsed?.source !== "problem" || parsed.paymentState !== "not_charged" || REFUSED_BEFORE_BROADCAST[parsed.code] !== parsed.status) {
8418
+ if (!admit(parsed)) {
8243
8419
  return null;
8244
8420
  }
8245
8421
  const detail = parsed.detail?.trim();
@@ -9409,7 +9585,7 @@ async function payDelegatedSpendAccount(args) {
9409
9585
  })
9410
9586
  });
9411
9587
  if (!createRes.ok) {
9412
- const refused = await spendWhitelistRefusal(createRes, paymentId);
9588
+ const refused = await sponsorProblemRefusal(createRes, paymentId, (parsed) => isValidatedProblemRefusal(parsed, PRE_SIGN_SPONSOR_CREATE_REFUSALS));
9413
9589
  if (refused) {
9414
9590
  await releaseReservation(ledger, ownedPaymentId, log);
9415
9591
  return refused;
@@ -9506,7 +9682,7 @@ async function payDelegatedSpendAccount(args) {
9506
9682
  })
9507
9683
  });
9508
9684
  if (!execRes.ok) {
9509
- const refused = await spendWhitelistRefusal(execRes, paymentId);
9685
+ const refused = await sponsorProblemRefusal(execRes, paymentId, isDefinitePreBroadcastRefusal);
9510
9686
  if (refused) {
9511
9687
  await releaseReservation(ledger, ownedPaymentId, log);
9512
9688
  return refused;
@@ -9878,22 +10054,23 @@ async function recordX402Answer(ctx, answer) {
9878
10054
  if (answer.kind === "undelivered") {
9879
10055
  const stated = parseErrorPayload(answer.answer)?.paymentState;
9880
10056
  const charged = answer.receipt !== null || stated === "charged";
10057
+ const timedOut = answer.answer.status === 504;
9881
10058
  const settlement2 = answer.receipt ? { ...ctx.settlement, txDigest: answer.receipt.txDigest } : void 0;
9882
10059
  const result = gatewayFailure(answer.answer, charged ? {
9883
- code: DELEGATED_PAY_CODES.GATEWAY_REFUSED,
10060
+ code: timedOut ? "delivery.seller_timeout" : DELEGATED_PAY_CODES.GATEWAY_REFUSED,
9884
10061
  paymentState: "charged",
9885
- detail: PUBLIC_DETAIL.GATEWAY_REFUSED
10062
+ detail: timedOut ? DELIVERY_SELLER_TIMEOUT_DETAIL : PUBLIC_DETAIL.GATEWAY_REFUSED
9886
10063
  } : {
9887
10064
  code: DELEGATED_PAY_CODES.EXECUTE_AMBIGUOUS,
9888
10065
  paymentState: "unknown",
9889
- detail: PUBLIC_DETAIL.EXECUTE_AMBIGUOUS
10066
+ detail: timedOut ? EXECUTE_TIMEOUT_DETAIL : PUBLIC_DETAIL.EXECUTE_AMBIGUOUS
9890
10067
  }, {
9891
10068
  paymentId,
9892
10069
  ...settlement2 ? { txDigest: settlement2.txDigest, settlement: settlement2 } : answer.txDigest ? { txDigest: answer.txDigest } : {}
9893
10070
  });
9894
10071
  logInternal(log, {
9895
- code: "delivery.proof_rejected",
9896
- msg: "gateway did not deliver against an x402 credential",
10072
+ code: charged && timedOut ? "delivery.seller_timeout" : "delivery.proof_rejected",
10073
+ msg: charged && timedOut ? "gateway timed out delivering against an x402 credential" : "gateway did not deliver against an x402 credential",
9897
10074
  context: { status: answer.answer.status, code: result.code }
9898
10075
  });
9899
10076
  return completeAttempt(ledger, paymentId, result, log);
@@ -10746,6 +10923,15 @@ async function resolvePayerSession(options) {
10746
10923
  });
10747
10924
  if (whole.ok)
10748
10925
  return { ok: true, value: { ...whole.value, deployment } };
10926
+ if (whole.error.reason === MANIFEST_ERROR_CODES.NO_GRANTS) {
10927
+ if (isRevokedBootstrap(bootstrap.data)) {
10928
+ return {
10929
+ ok: false,
10930
+ error: manifestError(MANIFEST_ERROR_CODES.NO_GRANTS, "this delegate key has been revoked", "account.grant_revoked")
10931
+ };
10932
+ }
10933
+ return whole;
10934
+ }
10749
10935
  const data = bootstrap.data;
10750
10936
  const rawGrants = Array.isArray(data.grants) ? data.grants : [];
10751
10937
  const usable = [];
@@ -10778,7 +10964,9 @@ async function resolvePayerSession(options) {
10778
10964
  if (usable.length === 0) {
10779
10965
  const scoped = blocked.find((b) => b.error.reason === MANIFEST_ERROR_CODES.MISSING_POLICY_BINDING);
10780
10966
  const pick2 = scoped ?? blocked[0];
10781
- return pick2 ? { ok: false, error: explainBlockedGrant(pick2.raw, pick2.error) } : whole;
10967
+ if (pick2)
10968
+ return { ok: false, error: explainBlockedGrant(pick2.raw, pick2.error) };
10969
+ return whole;
10782
10970
  }
10783
10971
  const resolved = manifestToSession({
10784
10972
  manifest: { ...data, grants: usable },
@@ -10842,10 +11030,16 @@ async function verifyGrantOnChain(input) {
10842
11030
  return notVerified(`grant ${input.grantObjectId} draws on a different pool than the one resolved`);
10843
11031
  }
10844
11032
  if (state.revoked === true) {
10845
- return notVerified(`grant ${input.grantObjectId} is revoked on chain`);
11033
+ return {
11034
+ ok: false,
11035
+ error: manifestError(MANIFEST_ERROR_CODES.GRANT_NOT_VERIFIED, `grant ${input.grantObjectId} is revoked on chain`, "account.grant_revoked")
11036
+ };
10846
11037
  }
10847
11038
  if (state.paused === true) {
10848
- return notVerified(`grant ${input.grantObjectId} is paused on chain`);
11039
+ return {
11040
+ ok: false,
11041
+ error: manifestError(MANIFEST_ERROR_CODES.GRANT_NOT_VERIFIED, `grant ${input.grantObjectId} is paused on chain`, "account.grant_paused")
11042
+ };
10849
11043
  }
10850
11044
  return { ok: true, value: null };
10851
11045
  }
@@ -160,6 +160,16 @@ declare const ERRORS: {
160
160
  readonly user: null;
161
161
  readonly logOnly: true;
162
162
  };
163
+ readonly 'indexer.unsettled_delivery': {
164
+ readonly surfaces: readonly ["indexer"];
165
+ readonly status: null;
166
+ readonly title: "Delivered call has no matching on-chain settlement";
167
+ readonly paymentState: "not_charged";
168
+ readonly retry: "never";
169
+ readonly nextAction: "contact_support";
170
+ readonly user: null;
171
+ readonly logOnly: true;
172
+ };
163
173
  readonly 'client.agent_handoff_failed': {
164
174
  readonly surfaces: readonly ["browser", "mcp_local"];
165
175
  readonly status: null;
@@ -439,6 +449,19 @@ declare const ERRORS: {
439
449
  readonly message: "This isn't available right now. Try again in a moment.";
440
450
  };
441
451
  };
452
+ readonly 'service.halted': {
453
+ readonly surfaces: readonly ["gateway", "seller", "console_server", "mcp_hosted", "browser"];
454
+ readonly status: 503;
455
+ readonly title: "Services halted temporarily";
456
+ readonly paymentState: "not_charged";
457
+ readonly retry: "after_delay";
458
+ readonly retryAfterSeconds: 5;
459
+ readonly nextAction: "retry_later";
460
+ readonly user: {
461
+ readonly title: "Services halted temporarily";
462
+ readonly message: "Try again in a moment.";
463
+ };
464
+ };
442
465
  readonly 'service.not_ready': {
443
466
  readonly surfaces: readonly ["gateway", "seller", "console_server"];
444
467
  readonly status: 503;
@@ -1252,7 +1275,7 @@ declare const ERRORS: {
1252
1275
  };
1253
1276
  };
1254
1277
  readonly 'delivery.seller_timeout': {
1255
- readonly surfaces: readonly ["gateway"];
1278
+ readonly surfaces: readonly ["gateway", "sdk", "mcp_local", "mcp_hosted"];
1256
1279
  readonly status: 504;
1257
1280
  readonly title: "Seller timed out after payment";
1258
1281
  readonly paymentState: "charged";
@@ -1683,6 +1706,18 @@ declare const ERRORS: {
1683
1706
  readonly message: "Enter a valid agent address and try again.";
1684
1707
  };
1685
1708
  };
1709
+ readonly 'account.deposit_cap_exceeded': {
1710
+ readonly surfaces: readonly ["gateway", "sdk", "browser"];
1711
+ readonly status: 403;
1712
+ readonly title: "Deposit would exceed the vault beta cap";
1713
+ readonly paymentState: "not_charged";
1714
+ readonly retry: "never";
1715
+ readonly nextAction: "fix_request";
1716
+ readonly user: {
1717
+ readonly title: "Over the beta vault limit";
1718
+ readonly message: "This deposit would put your vault over the Mainnet Beta cap. Deposit less, or withdraw first.";
1719
+ };
1720
+ };
1686
1721
  readonly 'account.finalize_mismatch': {
1687
1722
  readonly surfaces: readonly ["gateway"];
1688
1723
  readonly status: 409;
@@ -1,2 +1,2 @@
1
1
  import '@mysten/sui/client';
2
- export { B as BuildNativeTransferInput, a as NativeTransferAccept, b as NativeTransferBuild, c as NativeTransferError, k as NativeTransferErrorCode, d as NativeTransferGas, e as NativeTransferSignerInput, h as buildNativeTransferBytes, i as createNativeTransferSigner, j as inspectNativeTransfer } from './native-transfer-DspFvMQc.js';
2
+ export { B as BuildNativeTransferInput, a as NativeTransferAccept, b as NativeTransferBuild, c as NativeTransferError, k as NativeTransferErrorCode, d as NativeTransferGas, e as NativeTransferSignerInput, h as buildNativeTransferBytes, i as createNativeTransferSigner, j as inspectNativeTransfer } from './native-transfer-B9FlBiJZ.js';
@@ -3,7 +3,7 @@ import {
3
3
  buildNativeTransferBytes,
4
4
  createNativeTransferSigner,
5
5
  inspectNativeTransfer
6
- } from "./chunk-BCI3TKYX.js";
6
+ } from "./chunk-QY52OWHD.js";
7
7
  export {
8
8
  NativeTransferError,
9
9
  buildNativeTransferBytes,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mysten-incubation/suipay-buyer",
3
- "version": "0.4.0-dev.1",
3
+ "version": "0.4.0-dev.11",
4
4
  "type": "module",
5
5
  "description": "SuiPay buyer SDK — delegated spend-account pay plus a typed /v1 control-plane client.",
6
6
  "license": "MIT",