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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -198,6 +198,14 @@ the policy's terms as `expected` (and the signer as `options.signer`), or use
198
198
  `policies.createAndActivate`. `expected.asset` fixes the coin type: a policy
199
199
  the gateway reports for another asset is refused before anything is signed.
200
200
 
201
+ `buildMcpPaymentPayload(paymentRequired, signer, intent)`,
202
+ `createNativeTransferSigner({ client, sender, sign, intent })`, and
203
+ `buildNativeTransferBytes({ client, sender, accept, intent })` require a buyer
204
+ payment intent. Set `network`, `asset`, and `maxAmount` in base units from your
205
+ payment policy. Set `recipient` to pin the payee. Choose these values before
206
+ reading the server's offer. Native transfer helpers also check the intent
207
+ against the client's network.
208
+
201
209
  `createAndActivate` and the pool / policy / grant action helpers run the
202
210
  prepare → sponsor → sign → execute → finalize round-trip. After execute
203
211
  is sent, a lost confirmation is `chain.tx_unconfirmed` (money state
@@ -1,6 +1,6 @@
1
1
  // src/native-transfer.ts
2
2
  import { Transaction } from "@mysten/sui/transactions";
3
- import { fromBase64, normalizeStructTag, normalizeSuiAddress, toBase64 } from "@mysten/sui/utils";
3
+ import { fromBase64, normalizeStructTag as normalizeStructTag2, normalizeSuiAddress as normalizeSuiAddress2, toBase64 } from "@mysten/sui/utils";
4
4
 
5
5
  // ../core/dist/errors/types.js
6
6
  var PAYMENT_STATES = ["not_charged", "charged", "unknown"];
@@ -55,6 +55,19 @@ var ACCOUNT_CODES = {
55
55
  message: "This deposit would put your vault over the Mainnet Beta cap. Deposit less, or withdraw first."
56
56
  }
57
57
  },
58
+ "account.deposits_paused": {
59
+ surfaces: ["gateway", "sdk", "browser"],
60
+ status: 403,
61
+ title: "Deposits are paused",
62
+ paymentState: "not_charged",
63
+ retry: "after_delay",
64
+ retryAfterSeconds: 30,
65
+ nextAction: "retry_later",
66
+ user: {
67
+ title: "Deposits paused",
68
+ message: "New deposits are paused right now. Withdrawals and spending still work. Try again after deposits resume."
69
+ }
70
+ },
58
71
  "account.finalize_mismatch": {
59
72
  surfaces: ["gateway"],
60
73
  status: 409,
@@ -2125,7 +2138,7 @@ var SERVICE_CODES = {
2125
2138
  // Also `browser`: a directory page that only got a pass/fail boolean off
2126
2139
  // a server-side fetch restates this exact condition locally — the user
2127
2140
  // copy is equally true regardless of which layer noticed.
2128
- surfaces: ["gateway", "console_server", "mcp_hosted", "browser"],
2141
+ surfaces: ["gateway", "seller", "console_server", "mcp_hosted", "browser"],
2129
2142
  status: 503,
2130
2143
  title: "Service temporarily unavailable",
2131
2144
  paymentState: "not_charged",
@@ -2843,7 +2856,14 @@ function parseErrorPayload(input) {
2843
2856
  return null;
2844
2857
  }
2845
2858
  var DEFINITE_PRE_BROADCAST_REFUSALS = /* @__PURE__ */ new Set([
2846
- "auth.spend_not_whitelisted"
2859
+ "auth.spend_not_whitelisted",
2860
+ // Confirmed operator spend pause: gateway refuses before broadcast after
2861
+ // first-use bind or a chain_failed + ESpendPaused abort. Generic
2862
+ // `service.unavailable` stays out — session-revocation and other pre-check
2863
+ // paths can emit it after a lost execute may already have broadcast.
2864
+ "service.halted",
2865
+ // Confirmed operator deposit pause on dry-run / chain_failed + EDepositPaused.
2866
+ "account.deposits_paused"
2847
2867
  ]);
2848
2868
  function isValidatedProblemRefusal(parsed, allowedCodes) {
2849
2869
  return parsed !== null && parsed.source === "problem" && parsed.paymentState === "not_charged" && isErrorCode(parsed.code) && allowedCodes.has(parsed.code) && definitionOf(parsed.code).status === parsed.status;
@@ -3054,6 +3074,8 @@ var CONTEXT_ALLOWLIST = /* @__PURE__ */ new Set([
3054
3074
  "sessionDecision",
3055
3075
  "settleCode",
3056
3076
  "signedRequest",
3077
+ // ADR-0103: v1/v2 dual-accept drain counter on verified delegate/bootstrap lines.
3078
+ "protocolVersion",
3057
3079
  "signerCode",
3058
3080
  "consentCode",
3059
3081
  "publicReason",
@@ -3378,13 +3400,146 @@ function toErrorFields(value) {
3378
3400
  return { code: "service.internal", paymentState: "unknown", retryable: false, nextAction: "contact_support" };
3379
3401
  }
3380
3402
 
3403
+ // src/mcp.ts
3404
+ import { isValidSuiAddress, normalizeStructTag, normalizeSuiAddress } from "@mysten/sui/utils";
3405
+ var SUI_ADDRESS_WIRE = /^0x[0-9a-fA-F]{1,64}$/;
3406
+ var BURN_ADDRESS = normalizeSuiAddress("0x0");
3407
+ function parseStrictSuiAddress(raw) {
3408
+ if (typeof raw !== "string" || !SUI_ADDRESS_WIRE.test(raw)) return null;
3409
+ const normalized = normalizeSuiAddress(raw);
3410
+ if (!isValidSuiAddress(normalized) || normalized === BURN_ADDRESS) return null;
3411
+ return normalized;
3412
+ }
3413
+ var INTENT_REFUSAL_CODES = {
3414
+ invalid: "client.config_invalid",
3415
+ mismatch: "payment.method_unsupported",
3416
+ limit: "account.limit_exceeded"
3417
+ };
3418
+ function intentRefusalToError(refusal) {
3419
+ return SuiPayError.of(INTENT_REFUSAL_CODES[refusal.kind], "not_charged", { detail: refusal.detail });
3420
+ }
3421
+ function invalid(detail) {
3422
+ return { ok: false, refusal: { kind: "invalid", detail } };
3423
+ }
3424
+ function resolveBuyerIntent(intent) {
3425
+ if (typeof intent !== "object" || intent === null) {
3426
+ return invalid("a buyer payment intent (network, maxAmount, asset) is required");
3427
+ }
3428
+ const raw = intent;
3429
+ if (typeof raw.network !== "string" || !raw.network.startsWith("sui:") || raw.network.length <= 4) {
3430
+ return invalid("intent.network must be a sui:* network");
3431
+ }
3432
+ let maxAmount;
3433
+ if (typeof raw.maxAmount === "bigint") {
3434
+ maxAmount = raw.maxAmount;
3435
+ } else if (typeof raw.maxAmount === "string" && /^[0-9]+$/.test(raw.maxAmount)) {
3436
+ maxAmount = BigInt(raw.maxAmount);
3437
+ } else {
3438
+ return invalid("intent.maxAmount must be a bigint or an integer string");
3439
+ }
3440
+ if (maxAmount <= 0n) return invalid("intent.maxAmount must be positive");
3441
+ if (typeof raw.asset !== "string") return invalid("intent.asset must be a coin type");
3442
+ let asset;
3443
+ try {
3444
+ asset = normalizeStructTag(raw.asset);
3445
+ } catch {
3446
+ return invalid("intent.asset must be a coin type");
3447
+ }
3448
+ let recipient;
3449
+ if (raw.recipient !== void 0) {
3450
+ const parsed = parseStrictSuiAddress(raw.recipient);
3451
+ if (!parsed) return invalid("intent.recipient must be a Sui address");
3452
+ recipient = parsed;
3453
+ }
3454
+ return {
3455
+ ok: true,
3456
+ intent: { network: raw.network, maxAmount, asset, ...recipient ? { recipient } : {} }
3457
+ };
3458
+ }
3459
+ function checkAcceptAgainstIntent(accept, intent) {
3460
+ if (accept.scheme !== "exact") {
3461
+ return { kind: "mismatch", detail: `accept scheme ${accept.scheme} is not exact` };
3462
+ }
3463
+ if (accept.network !== intent.network) {
3464
+ return { kind: "mismatch", detail: `accept network ${accept.network} is not the intended ${intent.network}` };
3465
+ }
3466
+ let asset;
3467
+ try {
3468
+ asset = normalizeStructTag(accept.asset);
3469
+ } catch {
3470
+ return { kind: "mismatch", detail: `accept asset ${accept.asset} is not a coin type` };
3471
+ }
3472
+ if (asset !== intent.asset) {
3473
+ return { kind: "mismatch", detail: `accept asset ${asset} is not the intended ${intent.asset}` };
3474
+ }
3475
+ if (typeof accept.amount !== "string" || !/^[0-9]+$/.test(accept.amount)) {
3476
+ return { kind: "mismatch", detail: "accept amount is not an integer string" };
3477
+ }
3478
+ const amount = BigInt(accept.amount);
3479
+ if (amount <= 0n) {
3480
+ return { kind: "mismatch", detail: "accept amount must be positive" };
3481
+ }
3482
+ if (amount > intent.maxAmount) {
3483
+ return {
3484
+ kind: "limit",
3485
+ detail: `accept amount ${accept.amount} exceeds the intended maximum ${intent.maxAmount}`
3486
+ };
3487
+ }
3488
+ const payTo = parseStrictSuiAddress(accept.payTo);
3489
+ if (!payTo) {
3490
+ return { kind: "mismatch", detail: "accept payTo must be a Sui address" };
3491
+ }
3492
+ if (intent.recipient !== void 0 && payTo !== intent.recipient) {
3493
+ return { kind: "mismatch", detail: `accept payTo ${accept.payTo} is not the intended recipient` };
3494
+ }
3495
+ return null;
3496
+ }
3497
+ async function buildMcpPaymentPayload(paymentRequired, signer, intent) {
3498
+ const resolved = resolveBuyerIntent(intent);
3499
+ if (!resolved.ok) throw intentRefusalToError(resolved.refusal);
3500
+ const candidates = paymentRequired.accepts.filter(
3501
+ (a) => a.scheme === "exact" && a.network === resolved.intent.network
3502
+ );
3503
+ let firstRefusal = null;
3504
+ let accept;
3505
+ for (const candidate of candidates) {
3506
+ const refusal = checkAcceptAgainstIntent(candidate, resolved.intent);
3507
+ if (!refusal) {
3508
+ accept = candidate;
3509
+ break;
3510
+ }
3511
+ firstRefusal ??= refusal;
3512
+ }
3513
+ if (!accept) {
3514
+ if (firstRefusal) throw intentRefusalToError(firstRefusal);
3515
+ throw SuiPayError.of("payment.method_unsupported", "not_charged", {
3516
+ detail: `no exact accept on ${resolved.intent.network} in PaymentRequired`
3517
+ });
3518
+ }
3519
+ const signed = await signer.buildNativeTransfer(accept);
3520
+ const payload = {
3521
+ x402Version: 2,
3522
+ resource: paymentRequired.resource,
3523
+ accepted: accept,
3524
+ payload: {
3525
+ transaction: signed.transaction,
3526
+ signature: signed.signature
3527
+ }
3528
+ };
3529
+ return { payload, meta: { "x402/payment": payload } };
3530
+ }
3531
+
3381
3532
  // src/native-transfer.ts
3382
- var SUI_COIN_TYPE = normalizeStructTag("0x2::sui::SUI");
3533
+ var DEFAULT_NATIVE_MAX_GAS_BUDGET = 10000000n;
3534
+ var SUI_COIN_TYPE = normalizeStructTag2("0x2::sui::SUI");
3383
3535
  var NATIVE_COMMAND_KINDS = /* @__PURE__ */ new Set(["SplitCoins", "MergeCoins", "TransferObjects"]);
3384
3536
  var MAX_PAYMENT_COINS = 200;
3385
3537
  var COIN_PAGE_LIMIT = 50;
3386
3538
  var NATIVE_TRANSFER_CODES = {
3387
3539
  UNSUPPORTED_ACCEPT: "payment.method_unsupported",
3540
+ INTENT_INVALID: INTENT_REFUSAL_CODES.invalid,
3541
+ INTENT_MISMATCH: INTENT_REFUSAL_CODES.mismatch,
3542
+ INTENT_LIMIT_EXCEEDED: INTENT_REFUSAL_CODES.limit,
3388
3543
  INSUFFICIENT_BALANCE: "account.funds_insufficient",
3389
3544
  TOO_MANY_COINS: "account.too_many_coins",
3390
3545
  BUILD_FAILED: "client.build_failed",
@@ -3414,6 +3569,29 @@ var NativeTransferError = class extends SuiPayError {
3414
3569
  this.reason = reason;
3415
3570
  }
3416
3571
  };
3572
+ var INTENT_REASONS = {
3573
+ invalid: "INTENT_INVALID",
3574
+ mismatch: "INTENT_MISMATCH",
3575
+ limit: "INTENT_LIMIT_EXCEEDED"
3576
+ };
3577
+ function refuse(refusal) {
3578
+ throw new NativeTransferError(INTENT_REASONS[refusal.kind], refusal.detail);
3579
+ }
3580
+ function resolveIntentFor(client, intent) {
3581
+ const resolved = resolveBuyerIntent(intent);
3582
+ if (!resolved.ok) return refuse(resolved.refusal);
3583
+ const clientNetwork = client?.network;
3584
+ if (typeof clientNetwork !== "string" || clientNetwork.length === 0) {
3585
+ return refuse({ kind: "invalid", detail: "the client does not expose a network to pin the intent to" });
3586
+ }
3587
+ if (`sui:${clientNetwork}` !== resolved.intent.network) {
3588
+ return refuse({
3589
+ kind: "mismatch",
3590
+ detail: `client network sui:${clientNetwork} is not the intended ${resolved.intent.network}`
3591
+ });
3592
+ }
3593
+ return resolved.intent;
3594
+ }
3417
3595
  function parseAmount(raw) {
3418
3596
  if (!/^[0-9]+$/.test(raw)) {
3419
3597
  throw new NativeTransferError("UNSUPPORTED_ACCEPT", `amount ${raw} is not an integer string`);
@@ -3426,7 +3604,7 @@ function parseAmount(raw) {
3426
3604
  }
3427
3605
  function normalizeAsset(asset) {
3428
3606
  try {
3429
- return normalizeStructTag(asset);
3607
+ return normalizeStructTag2(asset);
3430
3608
  } catch {
3431
3609
  throw new NativeTransferError("UNSUPPORTED_ACCEPT", `asset ${asset} is not a coin type`);
3432
3610
  }
@@ -3488,7 +3666,7 @@ function readAddress(arg, inputs) {
3488
3666
  if (raw?.length !== 32) return void 0;
3489
3667
  let hex = "";
3490
3668
  for (const b of raw) hex += b.toString(16).padStart(2, "0");
3491
- return normalizeSuiAddress(`0x${hex}`);
3669
+ return normalizeSuiAddress2(`0x${hex}`);
3492
3670
  }
3493
3671
  function readU64(arg, inputs) {
3494
3672
  const raw = pureBytes(arg, inputs);
@@ -3505,12 +3683,31 @@ function splitIndexOf(arg) {
3505
3683
  return void 0;
3506
3684
  }
3507
3685
  function inspectNativeTransfer(bytes, expected) {
3686
+ const sender = parseStrictSuiAddress(expected.sender);
3687
+ if (!sender) return "expected sender is not a Sui address";
3688
+ const payTo = parseStrictSuiAddress(expected.payTo);
3689
+ if (!payTo) return "expected payTo is not a Sui address";
3690
+ if (expected.maxGasBudget !== void 0 && (typeof expected.maxGasBudget !== "bigint" || expected.maxGasBudget <= 0n)) {
3691
+ return "maxGasBudget must be a positive bigint";
3692
+ }
3508
3693
  const data = Transaction.from(bytes).getData();
3509
3694
  const commands = data.commands;
3510
3695
  const inputs = data.inputs;
3511
- if (!data.sender || normalizeSuiAddress(data.sender) !== expected.sender) {
3696
+ if (!data.sender || normalizeSuiAddress2(data.sender) !== sender) {
3512
3697
  return "transaction sender is not the payer";
3513
3698
  }
3699
+ const gasOwner = data.gasData?.owner;
3700
+ if (!gasOwner || normalizeSuiAddress2(gasOwner) !== sender) {
3701
+ return "gas is not paid by the payer";
3702
+ }
3703
+ const budget = data.gasData?.budget;
3704
+ if (budget === null || budget === void 0 || !/^[0-9]+$/.test(String(budget)) || BigInt(budget) <= 0n) {
3705
+ return "transaction gas budget is missing or not a positive integer";
3706
+ }
3707
+ const maxGasBudget = expected.maxGasBudget ?? DEFAULT_NATIVE_MAX_GAS_BUDGET;
3708
+ if (BigInt(budget) > maxGasBudget) {
3709
+ return `gas budget ${budget} exceeds the allowed ${maxGasBudget}`;
3710
+ }
3514
3711
  for (const command of commands) {
3515
3712
  if (!NATIVE_COMMAND_KINDS.has(command.$kind)) {
3516
3713
  return `command ${command.$kind} is not a native transfer`;
@@ -3518,15 +3715,15 @@ function inspectNativeTransfer(bytes, expected) {
3518
3715
  }
3519
3716
  const external = commands.filter((c) => {
3520
3717
  if (c.$kind !== "TransferObjects" || !c.TransferObjects) return false;
3521
- return readAddress(c.TransferObjects.address, inputs) !== expected.sender;
3718
+ return readAddress(c.TransferObjects.address, inputs) !== sender;
3522
3719
  });
3523
3720
  if (external.length !== 1) {
3524
3721
  return `transaction has ${external.length} external recipients; exactly one is allowed`;
3525
3722
  }
3526
3723
  const transfer = external[0].TransferObjects;
3527
3724
  const recipient = readAddress(transfer.address, inputs);
3528
- if (recipient !== expected.payTo) {
3529
- return `transaction pays ${recipient ?? "an unreadable address"}, not ${expected.payTo}`;
3725
+ if (recipient !== payTo) {
3726
+ return `transaction pays ${recipient ?? "an unreadable address"}, not ${payTo}`;
3530
3727
  }
3531
3728
  if (transfer.objects.length !== 1) {
3532
3729
  return "the payment transfer must move exactly one coin";
@@ -3545,18 +3742,55 @@ function inspectNativeTransfer(bytes, expected) {
3545
3742
  }
3546
3743
  return null;
3547
3744
  }
3745
+ function requirePositiveBigint(value, label) {
3746
+ if (typeof value !== "bigint" || value <= 0n) {
3747
+ throw new NativeTransferError("INTENT_INVALID", `${label} must be a positive bigint`);
3748
+ }
3749
+ return value;
3750
+ }
3751
+ function parseGasInteger(raw, label) {
3752
+ try {
3753
+ const value = typeof raw === "bigint" ? raw : BigInt(raw);
3754
+ if (value <= 0n) {
3755
+ throw new NativeTransferError("INTENT_INVALID", `${label} must be a positive integer`);
3756
+ }
3757
+ return value;
3758
+ } catch (err) {
3759
+ if (err instanceof NativeTransferError) throw err;
3760
+ throw new NativeTransferError("INTENT_INVALID", `${label} must be an integer`, { cause: err });
3761
+ }
3762
+ }
3763
+ function resolveMaxGasBudget(input, pinnedBudget) {
3764
+ const explicit = input.maxGasBudget !== void 0 ? requirePositiveBigint(input.maxGasBudget, "maxGasBudget") : void 0;
3765
+ if (pinnedBudget !== void 0 && explicit !== void 0) {
3766
+ return pinnedBudget < explicit ? pinnedBudget : explicit;
3767
+ }
3768
+ return explicit ?? pinnedBudget ?? DEFAULT_NATIVE_MAX_GAS_BUDGET;
3769
+ }
3548
3770
  async function buildNativeTransferBytes(input) {
3549
3771
  const { accept, client } = input;
3772
+ const intent = resolveIntentFor(client, input.intent);
3773
+ const outside = checkAcceptAgainstIntent(accept, intent);
3774
+ if (outside) return refuse(outside);
3550
3775
  if (accept.scheme !== "exact" || !accept.network.startsWith("sui:")) {
3551
3776
  throw new NativeTransferError(
3552
3777
  "UNSUPPORTED_ACCEPT",
3553
3778
  `accept is ${accept.scheme} on ${accept.network}; only exact on sui:* is supported`
3554
3779
  );
3555
3780
  }
3556
- const sender = normalizeSuiAddress(input.sender);
3557
- const payTo = normalizeSuiAddress(accept.payTo);
3781
+ const sender = parseStrictSuiAddress(input.sender);
3782
+ if (!sender) {
3783
+ throw new NativeTransferError("INTENT_INVALID", "sender must be a Sui address");
3784
+ }
3785
+ const payTo = parseStrictSuiAddress(accept.payTo);
3786
+ if (!payTo) {
3787
+ throw new NativeTransferError("UNSUPPORTED_ACCEPT", "accept payTo must be a Sui address");
3788
+ }
3558
3789
  const amount = parseAmount(accept.amount);
3559
3790
  const asset = normalizeAsset(accept.asset);
3791
+ const pinnedBudget = input.gas ? parseGasInteger(input.gas.budget, "gas budget") : void 0;
3792
+ const pinnedPrice = input.gas ? parseGasInteger(input.gas.price, "gas price") : void 0;
3793
+ const maxGasBudget = resolveMaxGasBudget(input, pinnedBudget);
3560
3794
  const tx = new Transaction();
3561
3795
  tx.setSender(sender);
3562
3796
  if (asset === SUI_COIN_TYPE) {
@@ -3578,8 +3812,8 @@ async function buildNativeTransferBytes(input) {
3578
3812
  }
3579
3813
  if (input.gas) {
3580
3814
  tx.setGasPayment(input.gas.payment);
3581
- tx.setGasPrice(BigInt(input.gas.price));
3582
- tx.setGasBudget(BigInt(input.gas.budget));
3815
+ tx.setGasPrice(pinnedPrice);
3816
+ tx.setGasBudget(pinnedBudget);
3583
3817
  }
3584
3818
  let bytes;
3585
3819
  try {
@@ -3587,7 +3821,12 @@ async function buildNativeTransferBytes(input) {
3587
3821
  } catch (err) {
3588
3822
  throw new NativeTransferError("BUILD_FAILED", "could not build the transfer", { cause: err });
3589
3823
  }
3590
- const problem = inspectNativeTransfer(bytes, { sender, payTo, amount });
3824
+ const problem = inspectNativeTransfer(bytes, {
3825
+ sender,
3826
+ payTo,
3827
+ amount,
3828
+ maxGasBudget
3829
+ });
3591
3830
  if (problem) throw new NativeTransferError("NOT_NATIVE", problem);
3592
3831
  return {
3593
3832
  transaction: toBase64(bytes),
@@ -3599,13 +3838,23 @@ async function buildNativeTransferBytes(input) {
3599
3838
  };
3600
3839
  }
3601
3840
  function createNativeTransferSigner(input) {
3841
+ resolveIntentFor(input.client, input.intent);
3842
+ const sender = parseStrictSuiAddress(input.sender);
3843
+ if (!sender) {
3844
+ throw new NativeTransferError("INTENT_INVALID", "sender must be a Sui address");
3845
+ }
3846
+ if (input.maxGasBudget !== void 0) {
3847
+ requirePositiveBigint(input.maxGasBudget, "maxGasBudget");
3848
+ }
3602
3849
  return {
3603
3850
  async buildNativeTransfer(accept) {
3604
3851
  const built = await buildNativeTransferBytes({
3605
3852
  client: input.client,
3606
- sender: input.sender,
3853
+ sender,
3607
3854
  accept,
3608
- ...input.gas ? { gas: input.gas } : {}
3855
+ intent: input.intent,
3856
+ ...input.gas ? { gas: input.gas } : {},
3857
+ ...input.maxGasBudget !== void 0 ? { maxGasBudget: input.maxGasBudget } : {}
3609
3858
  });
3610
3859
  const signature = await input.sign(built.bytes);
3611
3860
  return { transaction: built.transaction, signature };
@@ -3627,6 +3876,8 @@ export {
3627
3876
  logError,
3628
3877
  SuiPayError,
3629
3878
  toErrorFields,
3879
+ buildMcpPaymentPayload,
3880
+ DEFAULT_NATIVE_MAX_GAS_BUDGET,
3630
3881
  NativeTransferError,
3631
3882
  inspectNativeTransfer,
3632
3883
  buildNativeTransferBytes,
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-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';
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-D0UoteMk.js';
2
+ export { B as BuildNativeTransferInput, a as BuyerPaymentIntent, M as McpPaymentSigner, b as NativeTransferAccept, c as NativeTransferBuild, d as NativeTransferError, e as NativeTransferGas, f as NativeTransferSignerInput, S as SuiPayError, g as SuiPayErrorFields, h as buildMcpPaymentPayload, i as buildNativeTransferBytes, j as createNativeTransferSigner, k as inspectNativeTransfer, t as toErrorFields } from './native-transfer-D0UoteMk.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';
@@ -834,7 +834,7 @@ interface DelegatePoliciesDTO {
834
834
  * Agent signing helper — emit the four `x-suipay-*` signed-request headers.
835
835
  *
836
836
  * A delegate agent proves identity on every private, grant-scoped request by
837
- * signing the canonical `SignedRequestV1` payload with a Sui personal-message
837
+ * signing the canonical `SignedRequestV2` payload with a Sui personal-message
838
838
  * signature. This helper is the client-side counterpart to the gateway verifier:
839
839
  * it canonicalizes the path/query and hashes the body EXACTLY as the verifier
840
840
  * will (reusing the P0 codec's `canonicalizePath` / `canonicalizeQuery` /
@@ -846,24 +846,30 @@ interface DelegatePoliciesDTO {
846
846
  * bound via {@link personalMessageSigner}). Money never moves on this signature;
847
847
  * it authorizes only the grant-scoped reads the epic defines.
848
848
  *
849
- * Byte-for-byte parity with P0 is locked by the golden vector in
850
- * `tests/agent-sdk-signed-headers.test.ts`, which reproduces the exact
851
- * signature the cross-language vector (`tests/parity/signed-request-golden.test.ts`)
852
- * pins.
849
+ * The signed bytes are pinned by the v2 vector in
850
+ * `tests/agent-sdk-signed-headers.test.ts`, built from the same field values
851
+ * as the v1 cross-language vector (`tests/parity/signed-request-golden.test.ts`).
853
852
  */
854
853
 
855
854
  /** Sui personal-message signer: returns the serialized signature (base64). */
856
855
  type SignPersonalMessage = (message: Uint8Array) => Promise<string>;
857
856
  /**
858
- * The deployment + grant identity every signed request binds. `network` and
859
- * `packageId` MUST equal the gateway's server-authoritative config; `delegate`
860
- * MUST equal the grant's registered on-chain delegate (the signer's address).
857
+ * The deployment + grant identity every signed request binds. `network`,
858
+ * `packageId`, and `origin` MUST equal the gateway's server-authoritative
859
+ * config; `delegate` MUST equal the grant's registered on-chain delegate (the
860
+ * signer's address).
861
861
  */
862
862
  interface SessionSignerContext {
863
863
  /** e.g. `sui:testnet` — must equal the gateway config. */
864
864
  network: string;
865
865
  /** Deployed package id — must equal the gateway config. */
866
866
  packageId: string;
867
+ /**
868
+ * The gateway the request is sent to — any http(s) URL on it; only its
869
+ * {@link canonicalOrigin} is signed. Must equal the gateway's configured base
870
+ * URL origin, so the signature cannot be replayed at another gateway.
871
+ */
872
+ origin: string;
867
873
  /** On-chain grant object id — the authorization scope. */
868
874
  grantObjectId: string;
869
875
  /** Registered delegate Sui address (the signer). */
@@ -939,8 +945,11 @@ type PayerReadResult<T> = {
939
945
  interface PayerReadClientOptions {
940
946
  /** Gateway origin, e.g. `https://gateway.suipay.dev` (no trailing slash needed). */
941
947
  gatewayUrl: string;
942
- /** Deployment + grant identity every signed read binds. */
943
- context: SessionSignerContext;
948
+ /**
949
+ * Deployment + grant identity every signed read binds. The signed origin is
950
+ * always `gatewayUrl`'s: a read binds the gateway it is sent to.
951
+ */
952
+ context: Omit<SessionSignerContext, 'origin'>;
944
953
  /** Local personal-message signer; the key never leaves it. */
945
954
  signPersonalMessage: SignPersonalMessage;
946
955
  /** Injectable fetch (tests / custom transports). Defaults to global `fetch`. */
package/dist/index.js CHANGED
@@ -3,6 +3,7 @@ import {
3
3
  ERROR_CODE_HEADER,
4
4
  NativeTransferError,
5
5
  SuiPayError,
6
+ buildMcpPaymentPayload,
6
7
  buildNativeTransferBytes,
7
8
  createNativeTransferSigner,
8
9
  definitionOf,
@@ -16,30 +17,7 @@ import {
16
17
  parseErrorPayload,
17
18
  stricterPaymentState,
18
19
  toErrorFields
19
- } from "./chunk-QY52OWHD.js";
20
-
21
- // src/mcp.ts
22
- async function buildMcpPaymentPayload(paymentRequired, signer) {
23
- const accept = paymentRequired.accepts.find(
24
- (a) => a.scheme === "exact" && a.network.startsWith("sui:")
25
- );
26
- if (!accept) {
27
- throw SuiPayError.of("payment.method_unsupported", "not_charged", {
28
- detail: "no sui:* exact accept in PaymentRequired"
29
- });
30
- }
31
- const signed = await signer.buildNativeTransfer(accept);
32
- const payload = {
33
- x402Version: 2,
34
- resource: paymentRequired.resource,
35
- accepted: accept,
36
- payload: {
37
- transaction: signed.transaction,
38
- signature: signed.signature
39
- }
40
- };
41
- return { payload, meta: { "x402/payment": payload } };
42
- }
20
+ } from "./chunk-FWLPQH4N.js";
43
21
 
44
22
  // ../sdk/dist/buyer/legacy-control-codes.js
45
23
  var LEGACY_CONTROL_PLANE_CODES = {
@@ -47,6 +25,7 @@ var LEGACY_CONTROL_PLANE_CODES = {
47
25
  CONFLICT: "request.conflict",
48
26
  CROSS_ASSET_FORBIDDEN: "account.asset_unsupported",
49
27
  DEPOSIT_CAP_EXCEEDED: "account.deposit_cap_exceeded",
28
+ DEPOSITS_PAUSED: "account.deposits_paused",
50
29
  EXPIRED: "request.expired",
51
30
  FINALIZE_MISMATCH: "account.finalize_mismatch",
52
31
  FINALIZE_UNVERIFIED: "chain.tx_unverified",
@@ -72,6 +51,12 @@ var LEGACY_CONTROL_PLANE_CODES = {
72
51
  UNVERIFIED: "chain.tx_unverified"
73
52
  };
74
53
 
54
+ // ../sdk/dist/protocol/redirect.js
55
+ var NO_REDIRECT = { redirect: "manual" };
56
+ function isRedirectResponse(res) {
57
+ return res.type === "opaqueredirect" || res.status >= 300 && res.status < 400;
58
+ }
59
+
75
60
  // ../sdk/dist/buyer/transport.js
76
61
  var FORBIDDEN_SECRET_KEYS = [
77
62
  "privateKey",
@@ -282,8 +267,18 @@ function createTransport(options) {
282
267
  const response = await fetchImpl(joinUrl(options.baseUrl, path), {
283
268
  method: init.method ?? (init.body !== void 0 ? "POST" : "GET"),
284
269
  headers,
285
- body: init.body === void 0 ? void 0 : typeof init.body === "string" ? init.body : JSON.stringify(init.body)
270
+ body: init.body === void 0 ? void 0 : typeof init.body === "string" ? init.body : JSON.stringify(init.body),
271
+ ...NO_REDIRECT
286
272
  });
273
+ if (isRedirectResponse(response)) {
274
+ return {
275
+ status: 0,
276
+ body: localErrorBody(localClientError("request.redirect_refused", "not_charged", {
277
+ message: "SuiPay answered with a redirect, which is refused."
278
+ })),
279
+ headers: new Headers()
280
+ };
281
+ }
287
282
  const body = await response.json().catch(() => null);
288
283
  return { status: response.status, body, headers: response.headers };
289
284
  } catch {
@@ -5335,6 +5330,8 @@ function addressBalanceGasExpiration(input) {
5335
5330
  // ../sdk/dist/delegated-signer/pay-gas.js
5336
5331
  var DEFAULT_GAS_BUDGET = 10000000n;
5337
5332
  var DEFAULT_GAS_PRICE = 1000n;
5333
+ var MAX_SPONSOR_GAS_BUDGET = 50000000n;
5334
+ var MAX_SPONSOR_GAS_PRICE = 10000n;
5338
5335
  var X402_EXPIRATION_EPOCHS = 32n;
5339
5336
  async function readChainBound(read) {
5340
5337
  try {
@@ -5377,8 +5374,16 @@ function assertPayGas(data, delegate, policy = {}) {
5377
5374
  if (policy.mode === "agent") {
5378
5375
  if (!pinned)
5379
5376
  throw new Error("agent gas requires caller-owned gas inputs");
5380
- } else if (owner === agent) {
5381
- throw new Error("sponsored transaction gas owner must not be the delegate");
5377
+ } else {
5378
+ if (owner === agent) {
5379
+ throw new Error("sponsored transaction gas owner must not be the delegate");
5380
+ }
5381
+ if (actual.budget == null || actual.price == null) {
5382
+ throw new Error("sponsored transaction gas budget and price must be pinned");
5383
+ }
5384
+ if (BigInt(actual.budget) > MAX_SPONSOR_GAS_BUDGET || BigInt(actual.price) > MAX_SPONSOR_GAS_PRICE) {
5385
+ throw new Error("sponsored transaction gas budget or price exceeds the cap");
5386
+ }
5382
5387
  }
5383
5388
  if (pinned) {
5384
5389
  const expectedOwner = normalizeSuiAddress6(pinned.owner ?? delegate);
@@ -6261,6 +6266,8 @@ var X402_ERROR_REASON = {
6261
6266
  INSUFFICIENT_FUNDS: "insufficient_funds",
6262
6267
  PAYER_MISMATCH: "invalid_payload",
6263
6268
  SETTLEMENT_REJECTED: "invalid_transaction_state",
6269
+ SPEND_PAUSED: "unexpected_settle_error",
6270
+ SPEND_PAUSE_UNAVAILABLE: "unexpected_settle_error",
6264
6271
  SETTLEMENT_MISMATCH: "unexpected_settle_error",
6265
6272
  AMBIGUOUS: "settlement_pending",
6266
6273
  VERSION_UNSUPPORTED: "invalid_x402_version",
@@ -7534,10 +7541,13 @@ async function fetchGatewayOfferKeys(gatewayUrl, options = {}) {
7534
7541
  const targetUrl = `${normalizedBase}${SUIPAY_OFFER_KEYS_PATH}`;
7535
7542
  let response;
7536
7543
  try {
7537
- response = await fetchImpl(targetUrl);
7544
+ response = await fetchImpl(targetUrl, NO_REDIRECT);
7538
7545
  } catch (err) {
7539
7546
  throw new OfferKeysFetchError(`failed to fetch gateway offer keys: ${err instanceof Error ? err.message : String(err)}`);
7540
7547
  }
7548
+ if (isRedirectResponse(response)) {
7549
+ throw new OfferKeysFetchError("failed to fetch gateway offer keys: redirect refused", response.status);
7550
+ }
7541
7551
  if (response.status === 404) {
7542
7552
  throw new OfferKeysGatewayUnavailableError();
7543
7553
  }
@@ -7637,6 +7647,29 @@ import { isValidPersonalMessageSignature as isValidPersonalMessageSignature2, ve
7637
7647
  import { normalizeSuiAddress as normalizeSuiAddress9 } from "@mysten/sui/utils";
7638
7648
  var SIGNED_REQUEST_DOMAIN = "suipay:signed-request:v1";
7639
7649
  var BOOTSTRAP_REQUEST_DOMAIN = "suipay:bootstrap-request:v1";
7650
+ var SIGNED_REQUEST_DOMAIN_V2 = "suipay:signed-request:v2";
7651
+ var BOOTSTRAP_REQUEST_DOMAIN_V2 = "suipay:bootstrap-request:v2";
7652
+ function canonicalOrigin(urlOrOrigin) {
7653
+ if (typeof urlOrOrigin !== "string" || urlOrOrigin.trim() === "") {
7654
+ throw new Error("origin must be a non-empty http(s) URL");
7655
+ }
7656
+ let url;
7657
+ try {
7658
+ url = new URL(urlOrOrigin.trim());
7659
+ } catch {
7660
+ throw new Error("origin must be an absolute http(s) URL");
7661
+ }
7662
+ if (url.protocol !== "https:" && url.protocol !== "http:") {
7663
+ throw new Error("origin must use http or https");
7664
+ }
7665
+ if (url.username !== "" || url.password !== "") {
7666
+ throw new Error("origin must not carry userinfo");
7667
+ }
7668
+ if (url.hostname === "" || url.origin === "null") {
7669
+ throw new Error("origin must name a host");
7670
+ }
7671
+ return url.origin;
7672
+ }
7640
7673
  var SIGNED_REQUEST_MAX_AGE_MS = 3e5;
7641
7674
  var SIGNED_REQUEST_MAX_FUTURE_SKEW_MS = 3e4;
7642
7675
  var SIGNED_REQUEST_NONCE_TTL_MS = SIGNED_REQUEST_MAX_AGE_MS + 2 * SIGNED_REQUEST_MAX_FUTURE_SKEW_MS;
@@ -7661,6 +7694,61 @@ function hexToBytes32(hex) {
7661
7694
  }
7662
7695
  return Uint8Array.from(Buffer.from(h, "hex"));
7663
7696
  }
7697
+ var utf8VecBytes = (s) => bcs6.vector(bcs6.u8()).serialize([...Buffer.from(s, "utf8")]).toBytes();
7698
+ var addressBytes = (a) => bcs6.Address.serialize(normalizeSuiAddress9(a)).toBytes();
7699
+ function assertCanonicalOrigin(origin) {
7700
+ if (typeof origin !== "string" || canonicalOrigin(origin) !== origin) {
7701
+ throw new Error("origin must be a canonical http(s) origin");
7702
+ }
7703
+ return origin;
7704
+ }
7705
+ function encodeSignedRequestV2(payload) {
7706
+ if (payload.domain !== SIGNED_REQUEST_DOMAIN_V2) {
7707
+ throw new Error(`domain must be ${SIGNED_REQUEST_DOMAIN_V2}`);
7708
+ }
7709
+ const origin = assertCanonicalOrigin(payload.origin);
7710
+ const parts = [
7711
+ utf8VecBytes(payload.domain),
7712
+ utf8VecBytes(payload.network),
7713
+ addressBytes(payload.packageId),
7714
+ utf8VecBytes(origin),
7715
+ addressBytes(payload.grantObjectId),
7716
+ addressBytes(payload.delegate),
7717
+ utf8VecBytes(payload.method),
7718
+ utf8VecBytes(payload.path),
7719
+ utf8VecBytes(payload.query),
7720
+ bcs6.vector(bcs6.u8()).serialize([...hexToBytes32(payload.bodyHash)]).toBytes(),
7721
+ bcs6.u64().serialize(BigInt(payload.timestampMs)).toBytes(),
7722
+ utf8VecBytes(payload.nonce)
7723
+ ];
7724
+ return Buffer.concat(parts.map((p) => Buffer.from(p)));
7725
+ }
7726
+ function encodeBootstrapRequestV2(payload) {
7727
+ if (payload.domain !== BOOTSTRAP_REQUEST_DOMAIN_V2) {
7728
+ throw new Error(`domain must be ${BOOTSTRAP_REQUEST_DOMAIN_V2}`);
7729
+ }
7730
+ const origin = assertCanonicalOrigin(payload.origin);
7731
+ const parts = [
7732
+ utf8VecBytes(payload.domain),
7733
+ utf8VecBytes(payload.network),
7734
+ addressBytes(payload.packageId),
7735
+ utf8VecBytes(origin),
7736
+ addressBytes(payload.delegate),
7737
+ utf8VecBytes(payload.method),
7738
+ utf8VecBytes(payload.path),
7739
+ utf8VecBytes(payload.query),
7740
+ bcs6.vector(bcs6.u8()).serialize([...hexToBytes32(payload.bodyHash)]).toBytes(),
7741
+ bcs6.u64().serialize(BigInt(payload.timestampMs)).toBytes(),
7742
+ utf8VecBytes(payload.nonce)
7743
+ ];
7744
+ return Buffer.concat(parts.map((p) => Buffer.from(p)));
7745
+ }
7746
+ function encodeAnySignedRequest(payload) {
7747
+ return payload.domain === SIGNED_REQUEST_DOMAIN_V2 ? encodeSignedRequestV2(payload) : encodeSignedRequest(payload);
7748
+ }
7749
+ function encodeAnyBootstrapRequest(payload) {
7750
+ return payload.domain === BOOTSTRAP_REQUEST_DOMAIN_V2 ? encodeBootstrapRequestV2(payload) : encodeBootstrapRequest(payload);
7751
+ }
7664
7752
  function encodeBootstrapRequest(payload) {
7665
7753
  if (payload.domain !== BOOTSTRAP_REQUEST_DOMAIN) {
7666
7754
  throw new Error(`domain must be ${BOOTSTRAP_REQUEST_DOMAIN}`);
@@ -7793,10 +7881,10 @@ function validateNonceFormat(nonce) {
7793
7881
  return bytes >= SIGNED_REQUEST_NONCE_MIN_ENTROPY_BYTES;
7794
7882
  }
7795
7883
  async function signSignedRequest(input) {
7796
- return input.signPersonalMessage(encodeSignedRequest(input.payload));
7884
+ return input.signPersonalMessage(encodeAnySignedRequest(input.payload));
7797
7885
  }
7798
7886
  async function signBootstrapRequest(input) {
7799
- return input.signPersonalMessage(encodeBootstrapRequest(input.payload));
7887
+ return input.signPersonalMessage(encodeAnyBootstrapRequest(input.payload));
7800
7888
  }
7801
7889
 
7802
7890
  // ../sdk/dist/agent-sdk/signed-headers.js
@@ -7822,6 +7910,17 @@ function splitPathAndQuery(target) {
7822
7910
  return { path: noFragment.slice(0, q), query: noFragment.slice(q + 1) };
7823
7911
  }
7824
7912
  }
7913
+ function assertTargetOrigin(url, signedOrigin) {
7914
+ let target;
7915
+ try {
7916
+ target = new URL(url);
7917
+ } catch {
7918
+ return;
7919
+ }
7920
+ if (canonicalOrigin(target.href) !== canonicalOrigin(signedOrigin)) {
7921
+ throw new Error("request URL origin does not match the signed origin");
7922
+ }
7923
+ }
7825
7924
  function buildSignedRequestPayload(context, request, fields) {
7826
7925
  if (!validateNonceFormat(fields.nonce)) {
7827
7926
  throw new Error("nonce must be base64url with at least 128 bits of entropy");
@@ -7830,9 +7929,10 @@ function buildSignedRequestPayload(context, request, fields) {
7830
7929
  throw new Error("timestampMs must be a positive integer (epoch ms)");
7831
7930
  }
7832
7931
  return {
7833
- domain: SIGNED_REQUEST_DOMAIN,
7932
+ domain: SIGNED_REQUEST_DOMAIN_V2,
7834
7933
  network: context.network,
7835
7934
  packageId: context.packageId,
7935
+ origin: canonicalOrigin(context.origin),
7836
7936
  grantObjectId: context.grantObjectId,
7837
7937
  delegate: context.delegateAddress,
7838
7938
  method: request.method.toUpperCase(),
@@ -7869,6 +7969,7 @@ async function signSessionRequest(input) {
7869
7969
  };
7870
7970
  }
7871
7971
  async function signSessionRequestForUrl(input) {
7972
+ assertTargetOrigin(input.url, input.context.origin);
7872
7973
  const { path, query } = splitPathAndQuery(input.url);
7873
7974
  return signSessionRequest({
7874
7975
  context: input.context,
@@ -7893,9 +7994,10 @@ function buildBootstrapRequestPayload(context, request, fields) {
7893
7994
  throw new Error("timestampMs must be a positive integer (epoch ms)");
7894
7995
  }
7895
7996
  return {
7896
- domain: BOOTSTRAP_REQUEST_DOMAIN,
7997
+ domain: BOOTSTRAP_REQUEST_DOMAIN_V2,
7897
7998
  network: context.network,
7898
7999
  packageId: context.packageId,
8000
+ origin: canonicalOrigin(context.origin),
7899
8001
  delegate: context.delegateAddress,
7900
8002
  method: request.method.toUpperCase(),
7901
8003
  path: canonicalizePath(request.path),
@@ -7931,6 +8033,7 @@ async function signBootstrapSessionRequest(input) {
7931
8033
  };
7932
8034
  }
7933
8035
  async function signBootstrapSessionRequestForUrl(input) {
8036
+ assertTargetOrigin(input.url, input.context.origin);
7934
8037
  const { path, query } = splitPathAndQuery(input.url);
7935
8038
  return signBootstrapSessionRequest({
7936
8039
  context: input.context,
@@ -7949,6 +8052,9 @@ async function signBootstrapSessionRequestForUrl(input) {
7949
8052
  function classifyReadFailure(status) {
7950
8053
  return status >= 500 ? "unavailable" : "rejected";
7951
8054
  }
8055
+ function redirectRefused() {
8056
+ return { ok: false, status: 0, error: "unavailable", code: "request.redirect_refused" };
8057
+ }
7952
8058
  function joinUrl2(gatewayUrl, basePath, suffix) {
7953
8059
  const origin = gatewayUrl.replace(/\/$/, "");
7954
8060
  let base = basePath.replace(/\/$/, "");
@@ -7983,7 +8089,7 @@ function createReader(options) {
7983
8089
  let signed;
7984
8090
  try {
7985
8091
  signed = await signSessionRequestForUrl({
7986
- context: options.context,
8092
+ context: { ...options.context, origin: canonicalOrigin(options.gatewayUrl) },
7987
8093
  method: "GET",
7988
8094
  url,
7989
8095
  signPersonalMessage: options.signPersonalMessage,
@@ -7996,11 +8102,14 @@ function createReader(options) {
7996
8102
  try {
7997
8103
  res = await fetchImpl(url, {
7998
8104
  method: "GET",
7999
- headers: { ...signed.headers, accept: "application/json" }
8105
+ headers: { ...signed.headers, accept: "application/json" },
8106
+ ...NO_REDIRECT
8000
8107
  });
8001
8108
  } catch {
8002
8109
  return { ok: false, status: 0, error: "unavailable" };
8003
8110
  }
8111
+ if (isRedirectResponse(res))
8112
+ return redirectRefused();
8004
8113
  const body = await readJsonBody(res);
8005
8114
  if (res.status >= 200 && res.status < 300) {
8006
8115
  return { ok: true, status: res.status, data: body };
@@ -8095,7 +8204,7 @@ async function bootstrapPayerSessions(options) {
8095
8204
  let signed;
8096
8205
  try {
8097
8206
  signed = await signBootstrapSessionRequestForUrl({
8098
- context: options.context,
8207
+ context: { ...options.context, origin: canonicalOrigin(options.gatewayUrl) },
8099
8208
  method: "GET",
8100
8209
  url,
8101
8210
  signPersonalMessage: options.signPersonalMessage,
@@ -8108,11 +8217,14 @@ async function bootstrapPayerSessions(options) {
8108
8217
  try {
8109
8218
  res = await fetchImpl(url, {
8110
8219
  method: "GET",
8111
- headers: { ...signed.headers, accept: "application/json" }
8220
+ headers: { ...signed.headers, accept: "application/json" },
8221
+ ...NO_REDIRECT
8112
8222
  });
8113
8223
  } catch {
8114
8224
  return { ok: false, status: 0, error: "unavailable" };
8115
8225
  }
8226
+ if (isRedirectResponse(res))
8227
+ return redirectRefused();
8116
8228
  const body = await readJsonBody(res);
8117
8229
  if (res.status >= 200 && res.status < 300) {
8118
8230
  return { ok: true, status: res.status, data: body };
@@ -8409,9 +8521,29 @@ function gatewayFailure(answer, local, extras) {
8409
8521
  txDigest: error.txDigest ?? extras.txDigest
8410
8522
  });
8411
8523
  }
8412
- var PRE_SIGN_SPONSOR_CREATE_REFUSALS = /* @__PURE__ */ new Set([
8524
+ var PRE_SIGN_SPONSOR_REFUSALS = /* @__PURE__ */ new Set([
8413
8525
  ...DEFINITE_PRE_BROADCAST_REFUSALS,
8414
- "limit.rate_limited"
8526
+ "auth.spend_daily_limit_reached",
8527
+ // Unreadable pause / other pre-sign unavailability: safe on challenge and
8528
+ // sponsor create only. Execute keeps this ambiguous (see DEFINITE set).
8529
+ "service.unavailable",
8530
+ "limit.rate_limited",
8531
+ "limit.gas_quota_exceeded",
8532
+ "sponsor.would_abort",
8533
+ "sponsor.kind_rejected",
8534
+ "sponsor.target_not_allowed",
8535
+ "account.grant_revoked",
8536
+ "account.grant_paused",
8537
+ "account.grant_expired",
8538
+ "account.grant_not_active"
8539
+ ]);
8540
+ function isPreSignSponsorRefusal(parsed) {
8541
+ return isValidatedProblemRefusal(parsed, PRE_SIGN_SPONSOR_REFUSALS);
8542
+ }
8543
+ var BYO_SPONSOR_EXECUTE_PRE_BROADCAST_REFUSALS = /* @__PURE__ */ new Set([
8544
+ "auth.spend_daily_limit_reached",
8545
+ "sponsor.sponsorship_not_found",
8546
+ "sponsor.unavailable"
8415
8547
  ]);
8416
8548
  async function sponsorProblemRefusal(response, paymentId, admit) {
8417
8549
  const parsed = parseErrorPayload(await readGatewayAnswer(response));
@@ -9073,6 +9205,11 @@ async function payDelegatedSpendAccount(args) {
9073
9205
  detail: "the gateway could not be reached; nothing was signed"
9074
9206
  });
9075
9207
  }
9208
+ if (isRedirectResponse(first)) {
9209
+ return resultError("request.redirect_refused", "not_charged", {
9210
+ detail: "the gateway answered with a redirect; nothing was signed"
9211
+ });
9212
+ }
9076
9213
  if (first.status !== 402) {
9077
9214
  let body2;
9078
9215
  try {
@@ -9512,9 +9649,18 @@ async function payDelegatedSpendAccount(args) {
9512
9649
  grantId: resolved.grantObjectId,
9513
9650
  network: session.network,
9514
9651
  packageId: session.packageId
9515
- })
9652
+ }),
9653
+ ...NO_REDIRECT
9516
9654
  });
9655
+ if (isRedirectResponse(challengeRes)) {
9656
+ return abortBeforeSign("SPONSOR_UNAVAILABLE", PUBLIC_DETAIL.SPONSOR_UNAVAILABLE);
9657
+ }
9517
9658
  if (!challengeRes.ok) {
9659
+ const refused = await sponsorProblemRefusal(challengeRes, paymentId, isPreSignSponsorRefusal);
9660
+ if (refused) {
9661
+ await releaseReservation(ledger, ownedPaymentId, log);
9662
+ return refused;
9663
+ }
9518
9664
  return abortBeforeSign("SPONSOR_UNAVAILABLE", PUBLIC_DETAIL.SPONSOR_UNAVAILABLE);
9519
9665
  }
9520
9666
  const body2 = await challengeRes.json();
@@ -9582,10 +9728,14 @@ async function payDelegatedSpendAccount(args) {
9582
9728
  packageId: challenge.packageId,
9583
9729
  requestId: paymentId
9584
9730
  }
9585
- })
9731
+ }),
9732
+ ...NO_REDIRECT
9586
9733
  });
9734
+ if (isRedirectResponse(createRes)) {
9735
+ return abortBeforeSign("SPONSOR_UNAVAILABLE", PUBLIC_DETAIL.SPONSOR_UNAVAILABLE);
9736
+ }
9587
9737
  if (!createRes.ok) {
9588
- const refused = await sponsorProblemRefusal(createRes, paymentId, (parsed) => isValidatedProblemRefusal(parsed, PRE_SIGN_SPONSOR_CREATE_REFUSALS));
9738
+ const refused = await sponsorProblemRefusal(createRes, paymentId, isPreSignSponsorRefusal);
9589
9739
  if (refused) {
9590
9740
  await releaseReservation(ledger, ownedPaymentId, log);
9591
9741
  return refused;
@@ -9679,10 +9829,11 @@ async function payDelegatedSpendAccount(args) {
9679
9829
  signature,
9680
9830
  executeToken: sponsoredExecuteToken,
9681
9831
  ...sponsoredBackendToken ? { sponsorBackendToken: sponsoredBackendToken } : {}
9682
- })
9832
+ }),
9833
+ ...NO_REDIRECT
9683
9834
  });
9684
9835
  if (!execRes.ok) {
9685
- const refused = await sponsorProblemRefusal(execRes, paymentId, isDefinitePreBroadcastRefusal);
9836
+ const refused = isRedirectResponse(execRes) ? null : await sponsorProblemRefusal(execRes, paymentId, (parsed) => isDefinitePreBroadcastRefusal(parsed) || isValidatedProblemRefusal(parsed, BYO_SPONSOR_EXECUTE_PRE_BROADCAST_REFUSALS));
9686
9837
  if (refused) {
9687
9838
  await releaseReservation(ledger, ownedPaymentId, log);
9688
9839
  return refused;
@@ -9791,6 +9942,8 @@ async function payDelegatedSpendAccount(args) {
9791
9942
  let second;
9792
9943
  try {
9793
9944
  second = await fetchImpl(resourceUrl, paidRequestInit(request, { [MPP_CREDENTIAL_HEADER]: proof }));
9945
+ if (isRedirectResponse(second))
9946
+ throw new Error("proof presentation refused a redirect");
9794
9947
  } catch (err) {
9795
9948
  logInternal(log, { code: "client.gateway_unreachable", msg: "proof presentation failed" }, err);
9796
9949
  return completeAttempt(ledger, paymentId, ambiguous("PROOF_PRESENTATION_FAILED", PUBLIC_DETAIL.PROOF_PRESENTATION_FAILED, {
@@ -9972,6 +10125,9 @@ async function presentX402Credential(ctx, header) {
9972
10125
  let response;
9973
10126
  try {
9974
10127
  response = await ctx.fetchImpl(ctx.resourceUrl, paidRequestInit(ctx.request, { [X402_PAYMENT_HEADER]: header }));
10128
+ if (isRedirectResponse(response)) {
10129
+ throw new Error("x402 credential presentation refused a redirect");
10130
+ }
9975
10131
  } catch (err) {
9976
10132
  logInternal(ctx.deps.log, { code: "client.gateway_unreachable", msg: "x402 credential presentation failed" }, err);
9977
10133
  return { kind: "unresolved", txDigest };
@@ -9998,7 +10154,8 @@ async function presentX402Credential(ctx, header) {
9998
10154
  const settledReceipt = receipt && receipt.challengeId === ctx.offer.challengeId ? receipt : null;
9999
10155
  const pending = decoded !== null && isX402Failure(decoded) && decoded.errorReason === "settlement_pending";
10000
10156
  const answer = await readGatewayAnswer(response);
10001
- const stated = parseErrorPayload(answer)?.paymentState;
10157
+ const parsed = parseErrorPayload(answer);
10158
+ const stated = parsed?.paymentState;
10002
10159
  if (settledReceipt || pending || stated === "charged" || stated === "unknown") {
10003
10160
  return {
10004
10161
  kind: "undelivered",
@@ -10007,6 +10164,12 @@ async function presentX402Credential(ctx, header) {
10007
10164
  txDigest: settledReceipt?.txDigest ?? txDigest
10008
10165
  };
10009
10166
  }
10167
+ if (parsed?.source === "problem" && (parsed.code === "service.halted" || parsed.code === "service.unavailable") && answer.body.paymentState === "not_charged" && decoded && isX402Failure(decoded) && decoded.errorReason === "unexpected_settle_error") {
10168
+ txDigest = parsed.txDigest ?? txDigest;
10169
+ if (attempt === 1 && !txDigest)
10170
+ return { kind: "refused", answer };
10171
+ return { kind: "unresolved", txDigest };
10172
+ }
10010
10173
  if (attempt < attempts)
10011
10174
  await sleep(X402_PRESENT_DELAY_MS);
10012
10175
  }
@@ -10782,7 +10945,8 @@ async function fetchGatewayDeployment(options) {
10782
10945
  try {
10783
10946
  res = await fetchImpl(`${origin}${base}/deployment`, {
10784
10947
  method: "GET",
10785
- headers: { accept: "application/json" }
10948
+ headers: { accept: "application/json" },
10949
+ ...NO_REDIRECT
10786
10950
  });
10787
10951
  } catch {
10788
10952
  return {
@@ -10790,6 +10954,12 @@ async function fetchGatewayDeployment(options) {
10790
10954
  error: manifestError(MANIFEST_ERROR_CODES.MALFORMED_MANIFEST, "gateway deployment identity could not be reached", "client.gateway_unreachable")
10791
10955
  };
10792
10956
  }
10957
+ if (isRedirectResponse(res)) {
10958
+ return {
10959
+ ok: false,
10960
+ error: manifestError(MANIFEST_ERROR_CODES.MALFORMED_MANIFEST, "gateway deployment identity refused a redirect", "request.redirect_refused")
10961
+ };
10962
+ }
10793
10963
  if (res.status < 200 || res.status >= 300) {
10794
10964
  return {
10795
10965
  ok: false,
@@ -437,7 +437,7 @@ declare const ERRORS: {
437
437
  };
438
438
  };
439
439
  readonly 'service.unavailable': {
440
- readonly surfaces: readonly ["gateway", "console_server", "mcp_hosted", "browser"];
440
+ readonly surfaces: readonly ["gateway", "seller", "console_server", "mcp_hosted", "browser"];
441
441
  readonly status: 503;
442
442
  readonly title: "Service temporarily unavailable";
443
443
  readonly paymentState: "not_charged";
@@ -1718,6 +1718,19 @@ declare const ERRORS: {
1718
1718
  readonly message: "This deposit would put your vault over the Mainnet Beta cap. Deposit less, or withdraw first.";
1719
1719
  };
1720
1720
  };
1721
+ readonly 'account.deposits_paused': {
1722
+ readonly surfaces: readonly ["gateway", "sdk", "browser"];
1723
+ readonly status: 403;
1724
+ readonly title: "Deposits are paused";
1725
+ readonly paymentState: "not_charged";
1726
+ readonly retry: "after_delay";
1727
+ readonly retryAfterSeconds: 30;
1728
+ readonly nextAction: "retry_later";
1729
+ readonly user: {
1730
+ readonly title: "Deposits paused";
1731
+ readonly message: "New deposits are paused right now. Withdrawals and spending still work. Try again after deposits resume.";
1732
+ };
1733
+ };
1721
1734
  readonly 'account.finalize_mismatch': {
1722
1735
  readonly surfaces: readonly ["gateway"];
1723
1736
  readonly status: 409;
@@ -3383,13 +3396,35 @@ interface X402PaymentPayload {
3383
3396
  };
3384
3397
  }
3385
3398
 
3399
+ /**
3400
+ * Buyer helper: pick the sui:* exact accept the buyer's own intent allows,
3401
+ * return a PaymentPayload plus the `_meta` object to attach. Does not
3402
+ * implement an MCP client.
3403
+ *
3404
+ * The PaymentRequired comes from a server the buyer does not trust, so nothing
3405
+ * in it chooses what gets paid: the buyer states the network, asset, ceiling and
3406
+ * (optionally) recipient up front, and an accept outside that intent is never
3407
+ * handed to a signer.
3408
+ */
3409
+
3410
+ /** What the buyer is willing to pay, decided before any server response is read. */
3411
+ interface BuyerPaymentIntent {
3412
+ /** CAIP-2 network the payment must settle on, e.g. `sui:testnet`. */
3413
+ network: string;
3414
+ /** Largest amount, in the asset's base units, the buyer will pay. */
3415
+ maxAmount: bigint | string;
3416
+ /** Coin type the payment must be made in. Compared in canonical form. */
3417
+ asset: string;
3418
+ /** When set, the accept's `payTo` must be this address. */
3419
+ recipient?: string;
3420
+ }
3386
3421
  interface McpPaymentSigner {
3387
3422
  buildNativeTransfer(accept: X402Accept): Promise<{
3388
3423
  transaction: string;
3389
3424
  signature: string;
3390
3425
  }>;
3391
3426
  }
3392
- declare function buildMcpPaymentPayload(paymentRequired: X402PaymentRequired, signer: McpPaymentSigner): Promise<{
3427
+ declare function buildMcpPaymentPayload(paymentRequired: X402PaymentRequired, signer: McpPaymentSigner, intent: BuyerPaymentIntent): Promise<{
3393
3428
  payload: X402PaymentPayload;
3394
3429
  meta: {
3395
3430
  'x402/payment': X402PaymentPayload;
@@ -3412,13 +3447,15 @@ declare function buildMcpPaymentPayload(paymentRequired: X402PaymentRequired, si
3412
3447
  * withdrawal), which the gateway would classify as not native.
3413
3448
  */
3414
3449
 
3450
+ /** Default ceiling on auto-estimated gas when the caller does not pin `gas`. */
3451
+ declare const DEFAULT_NATIVE_MAX_GAS_BUDGET = 10000000n;
3415
3452
  /**
3416
3453
  * Fields the native builder actually reads. `extra.suipay` Move-call dressing
3417
3454
  * (module/function) is not an input: this PTB is MoveCall-free by construction.
3418
3455
  */
3419
3456
  type NativeTransferAccept = Pick<X402Accept, 'scheme' | 'network' | 'amount' | 'asset' | 'payTo'>;
3420
3457
  /** Why a native transfer was refused. Internal; callers branch on the registry `code`. */
3421
- type NativeTransferErrorCode = 'UNSUPPORTED_ACCEPT' | 'INSUFFICIENT_BALANCE' | 'TOO_MANY_COINS' | 'BUILD_FAILED' | 'NOT_NATIVE';
3458
+ type NativeTransferErrorCode = 'UNSUPPORTED_ACCEPT' | 'INTENT_INVALID' | 'INTENT_MISMATCH' | 'INTENT_LIMIT_EXCEEDED' | 'INSUFFICIENT_BALANCE' | 'TOO_MANY_COINS' | 'BUILD_FAILED' | 'NOT_NATIVE';
3422
3459
  /**
3423
3460
  * A native transfer that was not built. Nothing was signed, so the money state
3424
3461
  * is always `not_charged`. `reason` names the internal refusal for logs.
@@ -3441,8 +3478,20 @@ interface BuildNativeTransferInput {
3441
3478
  client: ClientWithCoreApi;
3442
3479
  sender: string;
3443
3480
  accept: NativeTransferAccept;
3481
+ /**
3482
+ * What the buyer decided to pay before reading the server's accept. The
3483
+ * accept must sit inside it and `client.network` must match it, or nothing
3484
+ * is built.
3485
+ */
3486
+ intent: BuyerPaymentIntent;
3444
3487
  /** Pin gas instead of letting the client resolve it. */
3445
3488
  gas?: NativeTransferGas;
3489
+ /**
3490
+ * Ceiling on the built transaction's gas budget. Defaults to
3491
+ * {@link DEFAULT_NATIVE_MAX_GAS_BUDGET}; when `gas` is pinned, that budget is
3492
+ * the ceiling unless this is set lower.
3493
+ */
3494
+ maxGasBudget?: bigint;
3446
3495
  }
3447
3496
  interface NativeTransferBuild {
3448
3497
  /** Base64 BCS TransactionData, ready for a wallet to sign as-is. */
@@ -3461,6 +3510,7 @@ declare function inspectNativeTransfer(bytes: Uint8Array, expected: {
3461
3510
  sender: string;
3462
3511
  payTo: string;
3463
3512
  amount: bigint;
3513
+ maxGasBudget?: bigint;
3464
3514
  }): string | null;
3465
3515
  /** Build and self-check the native transfer. Throws {@link NativeTransferError}; never returns bytes that fail. */
3466
3516
  declare function buildNativeTransferBytes(input: BuildNativeTransferInput): Promise<NativeTransferBuild>;
@@ -3469,9 +3519,13 @@ interface NativeTransferSignerInput {
3469
3519
  sender: string;
3470
3520
  /** Sign the exact transaction bytes; return the serialized signature. */
3471
3521
  sign: (bytes: Uint8Array) => Promise<string>;
3522
+ /** The buyer's bounds; checked against every accept and against `client.network`. */
3523
+ intent: BuyerPaymentIntent;
3472
3524
  gas?: NativeTransferGas;
3525
+ /** Ceiling on auto-estimated or pinned gas; see {@link BuildNativeTransferInput.maxGasBudget}. */
3526
+ maxGasBudget?: bigint;
3473
3527
  }
3474
3528
  /** An {@link McpPaymentSigner} backed by {@link buildNativeTransferBytes}. */
3475
3529
  declare function createNativeTransferSigner(input: NativeTransferSignerInput): McpPaymentSigner;
3476
3530
 
3477
- export { type BuildNativeTransferInput as B, type CodeFor as C, type DelegationScope as D, type ErrorCode as E, type McpPaymentSigner as M, type NextAction as N, type Offer as O, type PaymentState as P, type Receipt as R, SuiPayError as S, type NativeTransferAccept as a, type NativeTransferBuild as b, NativeTransferError as c, type NativeTransferGas as d, type NativeTransferSignerInput as e, type SuiPayErrorFields as f, buildMcpPaymentPayload as g, buildNativeTransferBytes as h, createNativeTransferSigner as i, inspectNativeTransfer as j, type NativeTransferErrorCode as k, toErrorFields as t };
3531
+ export { type BuildNativeTransferInput as B, type CodeFor as C, type DelegationScope as D, type ErrorCode as E, type McpPaymentSigner as M, type NextAction as N, type Offer as O, type PaymentState as P, type Receipt as R, SuiPayError as S, type BuyerPaymentIntent as a, type NativeTransferAccept as b, type NativeTransferBuild as c, NativeTransferError as d, type NativeTransferGas as e, type NativeTransferSignerInput as f, type SuiPayErrorFields as g, buildMcpPaymentPayload as h, buildNativeTransferBytes as i, createNativeTransferSigner as j, inspectNativeTransfer as k, DEFAULT_NATIVE_MAX_GAS_BUDGET as l, type NativeTransferErrorCode as m, toErrorFields as t };
@@ -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-B9FlBiJZ.js';
2
+ export { B as BuildNativeTransferInput, a as BuyerPaymentIntent, l as DEFAULT_NATIVE_MAX_GAS_BUDGET, b as NativeTransferAccept, c as NativeTransferBuild, d as NativeTransferError, m as NativeTransferErrorCode, e as NativeTransferGas, f as NativeTransferSignerInput, i as buildNativeTransferBytes, j as createNativeTransferSigner, k as inspectNativeTransfer } from './native-transfer-D0UoteMk.js';
@@ -1,10 +1,12 @@
1
1
  import {
2
+ DEFAULT_NATIVE_MAX_GAS_BUDGET,
2
3
  NativeTransferError,
3
4
  buildNativeTransferBytes,
4
5
  createNativeTransferSigner,
5
6
  inspectNativeTransfer
6
- } from "./chunk-QY52OWHD.js";
7
+ } from "./chunk-FWLPQH4N.js";
7
8
  export {
9
+ DEFAULT_NATIVE_MAX_GAS_BUDGET,
8
10
  NativeTransferError,
9
11
  buildNativeTransferBytes,
10
12
  createNativeTransferSigner,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mysten-incubation/suipay-buyer",
3
- "version": "0.4.0-dev.11",
3
+ "version": "0.4.0-dev.12",
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",