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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -990,7 +990,7 @@ declare function createReader(options: PayerReadClientOptions): PayerReadClient;
990
990
  * prior done result is never lost when capability is unavailable.
991
991
  * 5. Derive payment_id_hash / terms_hash.
992
992
  * 6. Build the full executable pay transaction (real shared-object versions).
993
- * 7. Validate-before-sign (built tx encodes exactly the intended pay; gas may differ).
993
+ * 7. Validate-before-sign (intended pay plus the caller's gas authority).
994
994
  * 8. Sign, 9. execute, 10. complete(ledger) with terminal ok/ambiguous, settle.
995
995
  * x402 refuses before 3 when its offer, gas pins or epoch are missing, skips
996
996
  * 4, builds 6 with the offer-pinned sponsor gas, and in place of 9-10
@@ -1825,6 +1825,9 @@ interface VerifyPreparedSettlementInput {
1825
1825
  */
1826
1826
  expectedGrantObjectId?: string;
1827
1827
  expectedPoolObjectId?: string;
1828
+ /** Independently read network bounds for Epoch / ValidDuring envelopes. */
1829
+ getCurrentEpoch?: () => Promise<bigint | number>;
1830
+ getChainIdentifier?: () => Promise<string>;
1828
1831
  }
1829
1832
  /**
1830
1833
  * Verify a prepared settlement and return it, or throw
package/dist/index.js CHANGED
@@ -856,6 +856,9 @@ function verifyOwnerTransaction(input) {
856
856
  const cmd = commands[i];
857
857
  if (cmd.$kind === "MergeCoins") {
858
858
  const mc = cmd.MergeCoins;
859
+ if (JSON.stringify(mc.destination) !== JSON.stringify(splitCmd.SplitCoins.coin)) {
860
+ throw new TransactionVerificationError("funding");
861
+ }
859
862
  markInputOrResult(mc.destination);
860
863
  for (const s of mc.sources) {
861
864
  markInputOrResult(s);
@@ -1732,6 +1735,27 @@ function assertMoveFunction(target, expected) {
1732
1735
  if (fn !== expected)
1733
1736
  throw new TransactionVerificationError("target");
1734
1737
  }
1738
+ function assertPreparedGrantScopes(scopes, prepared, submitted = [], assets = TESTNET_ASSETS) {
1739
+ const declared = /* @__PURE__ */ new Set();
1740
+ for (const scope of scopes) {
1741
+ const asset = declaredAsset(scope.asset, assets);
1742
+ if (!asset || declared.has(asset.id))
1743
+ throw new TransactionVerificationError("coinType");
1744
+ declared.add(asset.id);
1745
+ }
1746
+ const seenAssets = /* @__PURE__ */ new Set();
1747
+ const seenIds = /* @__PURE__ */ new Set();
1748
+ for (const grant of [...prepared, ...submitted]) {
1749
+ const asset = "coinType" in grant && typeof grant.coinType === "string" && declaredAsset(grant.coinType, assets) || declaredAsset(grant.asset, assets);
1750
+ if (!asset || !declared.has(asset.id))
1751
+ throw new TransactionVerificationError("coinType");
1752
+ if (seenAssets.has(asset.id) || seenIds.has(grant.grantId)) {
1753
+ throw new TransactionVerificationError("grants");
1754
+ }
1755
+ seenAssets.add(asset.id);
1756
+ seenIds.add(grant.grantId);
1757
+ }
1758
+ }
1735
1759
 
1736
1760
  // ../sdk/dist/buyer/v1/delegated-signers.js
1737
1761
  function createAgentsApi(transport) {
@@ -1831,6 +1855,7 @@ function createAgentsApi(transport) {
1831
1855
  const created = await create(input);
1832
1856
  if (!created.ok)
1833
1857
  return created;
1858
+ assertPreparedGrantScopes(input.assetScopes, created.value.grants, created.value.submitted);
1834
1859
  const finalized = [];
1835
1860
  for (const submitted of created.value.submitted ?? []) {
1836
1861
  const fin = await finalizeGrant(created.value.delegatedSignerId, submitted.grantId, submitted.digest);
@@ -2513,7 +2538,7 @@ function createBuyerControlPlane(options) {
2513
2538
  var createBuyer = createBuyerControlPlane;
2514
2539
 
2515
2540
  // ../sdk/dist/agent-sdk/delegate-agent.js
2516
- import { normalizeSuiAddress as normalizeSuiAddress11 } from "@mysten/sui/utils";
2541
+ import { normalizeSuiAddress as normalizeSuiAddress12 } from "@mysten/sui/utils";
2517
2542
 
2518
2543
  // ../sdk/dist/buyer-control/chain.js
2519
2544
  import { bcs as bcs2 } from "@mysten/sui/bcs";
@@ -2580,7 +2605,30 @@ function createFailoverGrpcClient(options) {
2580
2605
  const clients = endpoints.map((baseUrl) => new SuiGrpcClient({ network: options.network, baseUrl }));
2581
2606
  return wrapFailover(clients, { sleep: endpointRetrySleep });
2582
2607
  }
2583
- var FAILOVER_SERVICES = ["core", "ledgerService"];
2608
+ var FAILOVER_SERVICES = ["core", "ledgerService", "movePackageService"];
2609
+ var UNARY_RESULT_PROPERTIES = ["headers", "response", "status", "trailers"];
2610
+ function isUnaryCall(value) {
2611
+ return "method" in value && "request" in value && "requestHeaders" in value && UNARY_RESULT_PROPERTIES.every((prop) => typeof value[prop]?.then === "function");
2612
+ }
2613
+ function unaryCallWithFailover(first, finished) {
2614
+ const then = finished.then.bind(finished);
2615
+ const properties = /* @__PURE__ */ new Map();
2616
+ return new Proxy(first, {
2617
+ get(target, prop) {
2618
+ if (prop === "then")
2619
+ return then;
2620
+ if (UNARY_RESULT_PROPERTIES.includes(prop)) {
2621
+ let value = properties.get(prop);
2622
+ if (!value) {
2623
+ value = finished.then((call) => call[prop]);
2624
+ properties.set(prop, value);
2625
+ }
2626
+ return value;
2627
+ }
2628
+ return Reflect.get(target, prop, target);
2629
+ }
2630
+ });
2631
+ }
2584
2632
  function wrapFailover(clients, options = {}) {
2585
2633
  const primary = clients[0];
2586
2634
  const attempts = Math.max(1, options.attempts ?? RPC_ATTEMPTS_PER_ENDPOINT);
@@ -2598,10 +2646,14 @@ function wrapFailover(clients, options = {}) {
2598
2646
  return (...args) => {
2599
2647
  const first = callOn(primary, prop, args);
2600
2648
  const attemptsFor = prop === "executeTransaction" ? 1 : attempts;
2601
- if (first == null || typeof first.then !== "function" || typeof first.catch !== "function") {
2649
+ if (first == null || typeof first.then !== "function") {
2602
2650
  return first;
2603
2651
  }
2604
- return (async () => {
2652
+ const promise = typeof first.catch === "function";
2653
+ const unary = !promise && typeof first === "object" && isUnaryCall(first);
2654
+ if (!promise && !unary)
2655
+ return first;
2656
+ const finished = (async () => {
2605
2657
  let last;
2606
2658
  for (let endpoint = 0; endpoint < clients.length; endpoint++) {
2607
2659
  for (let attempt = 0; attempt < attemptsFor; attempt++) {
@@ -2623,6 +2675,7 @@ function wrapFailover(clients, options = {}) {
2623
2675
  }
2624
2676
  throw last;
2625
2677
  })();
2678
+ return unary ? unaryCallWithFailover(first, finished) : finished;
2626
2679
  };
2627
2680
  }
2628
2681
  });
@@ -4722,8 +4775,8 @@ function createGrpcExclusionRegistryReader(client) {
4722
4775
 
4723
4776
  // ../sdk/dist/delegated-signer/payer.js
4724
4777
  import { bcs as bcs7 } from "@mysten/sui/bcs";
4725
- import { Transaction as Transaction4 } from "@mysten/sui/transactions";
4726
- import { fromBase64 as fromBase647, normalizeStructTag as normalizeStructTag10, normalizeSuiAddress as normalizeSuiAddress9, toBase64 as toBase645 } from "@mysten/sui/utils";
4778
+ import { Transaction as Transaction5 } from "@mysten/sui/transactions";
4779
+ import { fromBase64 as fromBase648, normalizeStructTag as normalizeStructTag10, normalizeSuiAddress as normalizeSuiAddress10, toBase64 as toBase645 } from "@mysten/sui/utils";
4727
4780
  import { Ed25519Keypair } from "@mysten/sui/keypairs/ed25519";
4728
4781
 
4729
4782
  // ../sdk/dist/delegated-signer/finality-poll.js
@@ -4748,186 +4801,9 @@ async function pollFinality(input) {
4748
4801
  return { status: "timeout" };
4749
4802
  }
4750
4803
 
4751
- // ../sdk/dist/pay-operation/operation.js
4752
- import { normalizeStructTag as normalizeStructTag9, normalizeSuiAddress as normalizeSuiAddress6 } from "@mysten/sui/utils";
4753
-
4754
- // ../core/dist/policy/grant-target.js
4755
- function normalizeHash(hex) {
4756
- return hex.replace(/^0x/i, "").toLowerCase();
4757
- }
4758
- function grantAuthorityUsable(snapshot) {
4759
- if (snapshot.status === "paused") {
4760
- return { ok: false, reason: "grant is paused" };
4761
- }
4762
- if (snapshot.status === "revoked") {
4763
- return { ok: false, reason: "grant is revoked" };
4764
- }
4765
- if (snapshot.status === "expired") {
4766
- return { ok: false, reason: "grant is expired" };
4767
- }
4768
- if (snapshot.status !== "active") {
4769
- return { ok: false, reason: `grant status is ${snapshot.status}` };
4770
- }
4771
- if (!snapshot.grantObjectId?.trim()) {
4772
- return { ok: false, reason: "grant is not finalized (missing grantObjectId)" };
4773
- }
4774
- if (!snapshot.poolObjectId?.trim()) {
4775
- return { ok: false, reason: "poolObjectId is required" };
4776
- }
4777
- return {
4778
- ok: true,
4779
- grantObjectId: snapshot.grantObjectId,
4780
- poolObjectId: snapshot.poolObjectId
4781
- };
4782
- }
4783
- function resolveGrantTarget(snapshot, offerTargetHash) {
4784
- if (!offerTargetHash?.trim()) {
4785
- return { ok: false, reason: "offer.targetHash is required" };
4786
- }
4787
- const wanted = normalizeHash(offerTargetHash);
4788
- if (!/^[0-9a-f]{64}$/.test(wanted)) {
4789
- return { ok: false, reason: "offer.targetHash must be 32-byte hex" };
4790
- }
4791
- const usable = grantAuthorityUsable(snapshot);
4792
- if (!usable.ok) {
4793
- return usable;
4794
- }
4795
- const hits = [];
4796
- for (const policy of snapshot.policies) {
4797
- if (policy.status !== "active")
4798
- continue;
4799
- for (const target of policy.targets) {
4800
- if (normalizeHash(target.targetHash) === wanted) {
4801
- hits.push({
4802
- policyId: policy.policyId,
4803
- onChainPolicyId: policy.onChainPolicyId,
4804
- maxPerPayment: target.maxPerPayment
4805
- });
4806
- }
4807
- }
4808
- }
4809
- if (hits.length > 1) {
4810
- return {
4811
- ok: false,
4812
- reason: `target hash resolves to ${hits.length} active policies (EPolicyConflict)`
4813
- };
4814
- }
4815
- if (hits.length === 1) {
4816
- const hit = hits[0];
4817
- return {
4818
- ok: true,
4819
- policyId: hit.policyId,
4820
- onChainPolicyId: hit.onChainPolicyId,
4821
- targetHash: wanted,
4822
- maxPerPayment: hit.maxPerPayment,
4823
- poolObjectId: usable.poolObjectId,
4824
- grantObjectId: usable.grantObjectId,
4825
- coinType: snapshot.coinType,
4826
- delegateAddress: snapshot.delegateAddress
4827
- };
4828
- }
4829
- return {
4830
- ok: false,
4831
- reason: "no active policy in grant snapshot matches offer.targetHash"
4832
- };
4833
- }
4834
-
4835
- // ../sdk/dist/protocol/carrier.js
4836
- import { fromBase64 as fromBase645, toBase64 as toBase643 } from "@mysten/sui/utils";
4837
-
4838
- // ../sdk/dist/protocol/auth-params.js
4839
- var TOKEN = /^[A-Za-z0-9!#$%&'*+\-.^_`|~]+$/;
4840
- function parseAuthHeader(header) {
4841
- const trimmed = header.trim();
4842
- const firstSpace = trimmed.indexOf(" ");
4843
- if (firstSpace === -1)
4844
- return null;
4845
- const scheme = trimmed.slice(0, firstSpace);
4846
- if (!TOKEN.test(scheme))
4847
- return null;
4848
- const params = parseParams(trimmed.slice(firstSpace + 1));
4849
- return params === null ? null : { scheme, params };
4850
- }
4851
- function parseParams(input) {
4852
- const params = {};
4853
- let i = 0;
4854
- const skipSpace = () => {
4855
- while (i < input.length && (input[i] === " " || input[i] === " "))
4856
- i++;
4857
- };
4858
- skipSpace();
4859
- while (i < input.length) {
4860
- const keyStart = i;
4861
- while (i < input.length && input[i] !== "=")
4862
- i++;
4863
- if (i >= input.length)
4864
- return null;
4865
- const key = input.slice(keyStart, i).trim();
4866
- if (!TOKEN.test(key))
4867
- return null;
4868
- i++;
4869
- let value;
4870
- if (input[i] === '"') {
4871
- i++;
4872
- let out = "";
4873
- let closed = false;
4874
- while (i < input.length) {
4875
- const ch = input[i];
4876
- if (ch === "\\" && i + 1 < input.length) {
4877
- out += input[i + 1];
4878
- i += 2;
4879
- continue;
4880
- }
4881
- if (ch === '"') {
4882
- i++;
4883
- closed = true;
4884
- break;
4885
- }
4886
- out += ch;
4887
- i++;
4888
- }
4889
- if (!closed)
4890
- return null;
4891
- value = out;
4892
- } else {
4893
- const start = i;
4894
- while (i < input.length && input[i] !== ",")
4895
- i++;
4896
- value = input.slice(start, i).trim();
4897
- }
4898
- params[key] = value;
4899
- skipSpace();
4900
- if (i < input.length) {
4901
- if (input[i] !== ",")
4902
- return null;
4903
- i++;
4904
- skipSpace();
4905
- }
4906
- }
4907
- return params;
4908
- }
4909
-
4910
- // ../sdk/dist/protocol/base64url.js
4911
- function bytesToBase64Url(bytes) {
4912
- let binary = "";
4913
- for (const byte of bytes)
4914
- binary += String.fromCharCode(byte);
4915
- const base64 = typeof globalThis.btoa === "function" ? globalThis.btoa(binary) : Buffer.from(bytes).toString("base64");
4916
- return base64.replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/g, "");
4917
- }
4918
- function bytesFromBase64Url(s) {
4919
- const normalized = s.replace(/-/g, "+").replace(/_/g, "/");
4920
- const pad = (4 - normalized.length % 4) % 4;
4921
- const base64 = normalized + "=".repeat(pad);
4922
- if (typeof globalThis.atob === "function") {
4923
- const binary = globalThis.atob(base64);
4924
- const out = new Uint8Array(binary.length);
4925
- for (let i = 0; i < binary.length; i++)
4926
- out[i] = binary.charCodeAt(i);
4927
- return out;
4928
- }
4929
- return Uint8Array.from(Buffer.from(base64, "base64"));
4930
- }
4804
+ // ../sdk/dist/delegated-signer/pay-gas.js
4805
+ import { Transaction as Transaction3 } from "@mysten/sui/transactions";
4806
+ import { fromBase64 as fromBase644, normalizeSuiAddress as normalizeSuiAddress6 } from "@mysten/sui/utils";
4931
4807
 
4932
4808
  // ../sdk/dist/protocol/challenge.js
4933
4809
  import { Ed25519PublicKey } from "@mysten/sui/keypairs/ed25519";
@@ -5014,6 +4890,53 @@ var OMIT_WHEN_ABSENT = /* @__PURE__ */ new Set([
5014
4890
  ...V4_OMIT_WHEN_ABSENT
5015
4891
  ]);
5016
4892
  var BODY_HASH_RE = /^[A-Za-z0-9_-]{43}$/;
4893
+ var CONTROL_CHAR_RE = /[\x00-\x1f\x7f]/;
4894
+ var SIGNED_NUMBER_FIELDS = /* @__PURE__ */ new Set([
4895
+ "decimals",
4896
+ "issuedAt",
4897
+ "expiresAt",
4898
+ "digestVersion",
4899
+ "serviceRevision",
4900
+ "authorizationEpoch",
4901
+ "periodMs",
4902
+ "periodCount",
4903
+ "refundWindowMs",
4904
+ "decideWindowMs",
4905
+ "chainId",
4906
+ "exclusionProtocolVersion"
4907
+ ]);
4908
+ function hasValidSignedOfferFields(offer, requireComplete = true) {
4909
+ if (typeof offer !== "object" || offer === null || Array.isArray(offer))
4910
+ return false;
4911
+ const fields = offer;
4912
+ for (const key of SIGNED_FIELDS_V4) {
4913
+ const value = fields[key];
4914
+ if (value === void 0) {
4915
+ if (requireComplete && SIGNED_FIELDS_V1.includes(key))
4916
+ return false;
4917
+ continue;
4918
+ }
4919
+ if (SIGNED_NUMBER_FIELDS.has(key)) {
4920
+ if (typeof value !== "number" || !Number.isSafeInteger(value) || value < 0)
4921
+ return false;
4922
+ if (key === "digestVersion" && (value < 1 || value > 4))
4923
+ return false;
4924
+ } else if (key === "refundable") {
4925
+ if (typeof value !== "boolean")
4926
+ return false;
4927
+ } else if (key === "acceptedRails") {
4928
+ if (!Array.isArray(value))
4929
+ return false;
4930
+ for (const rail of value) {
4931
+ if (typeof rail !== "string" || CONTROL_CHAR_RE.test(rail) || rail.includes(","))
4932
+ return false;
4933
+ }
4934
+ } else if (typeof value !== "string" || CONTROL_CHAR_RE.test(value)) {
4935
+ return false;
4936
+ }
4937
+ }
4938
+ return true;
4939
+ }
5017
4940
  var CONTENT_TYPE_RE = /^[a-z0-9!#$%&'*+.^_`|~-]+\/[a-z0-9!#$%&'*+.^_`|~-]+(?:; ?[a-z0-9!#$%&'*+.^_`|~-]+=(?:[a-zA-Z0-9!#$%&'*+.^_`|~-]+|"[^"\n\r]*"))*$/;
5018
4941
  function isBodyHash(value) {
5019
4942
  return typeof value === "string" && BODY_HASH_RE.test(value);
@@ -5192,6 +5115,8 @@ function toRawEd25519PublicKey(key) {
5192
5115
  throw new Error("unsupported Ed25519 public key representation");
5193
5116
  }
5194
5117
  function verifyOfferSig(offer, publicKey) {
5118
+ if (!hasValidSignedOfferFields(offer, false))
5119
+ return Promise.resolve(false);
5195
5120
  if (!offer.sig || typeof offer.sig !== "string")
5196
5121
  return Promise.resolve(false);
5197
5122
  if (!offer.digest || typeof offer.digest !== "string" || !offer.digest.trim() || offer.digest !== offer.digest.trim()) {
@@ -5266,6 +5191,275 @@ function addressBalanceGasExpiration(input) {
5266
5191
  };
5267
5192
  }
5268
5193
 
5194
+ // ../sdk/dist/delegated-signer/pay-gas.js
5195
+ var DEFAULT_GAS_BUDGET = 10000000n;
5196
+ var DEFAULT_GAS_PRICE = 1000n;
5197
+ var X402_EXPIRATION_EPOCHS = 32n;
5198
+ async function readChainBound(read) {
5199
+ try {
5200
+ return await read();
5201
+ } catch (cause) {
5202
+ if (cause instanceof SuiPayError)
5203
+ throw cause;
5204
+ throw SuiPayError.of("chain.unavailable", "not_charged", {
5205
+ detail: "the pre-sign chain read is unavailable; no signature was produced"
5206
+ }, { cause });
5207
+ }
5208
+ }
5209
+ async function readPayExpirationPolicy(txBytes, readers) {
5210
+ const expiration = Transaction3.from(fromBase644(txBytes)).getData().expiration;
5211
+ if (expiration.$kind === "None")
5212
+ return void 0;
5213
+ if (!readers.getCurrentEpoch)
5214
+ throw new Error("a trusted current epoch is required");
5215
+ if (expiration.$kind !== "ValidDuring") {
5216
+ return { currentEpoch: BigInt(await readChainBound(readers.getCurrentEpoch)) };
5217
+ }
5218
+ if (!readers.getChainIdentifier)
5219
+ throw new Error("a trusted chain identifier is required");
5220
+ const [currentEpoch, chainIdentifier] = await Promise.all([
5221
+ readChainBound(readers.getCurrentEpoch),
5222
+ readChainBound(readers.getChainIdentifier)
5223
+ ]);
5224
+ return { currentEpoch: BigInt(currentEpoch), chainIdentifier };
5225
+ }
5226
+ function assertPayGas(data, delegate, policy = {}) {
5227
+ const actual = data.gasData;
5228
+ const agent = normalizeSuiAddress6(delegate);
5229
+ if (!actual.owner)
5230
+ throw new Error("transaction gas owner is missing");
5231
+ const owner = normalizeSuiAddress6(actual.owner);
5232
+ const pinned = policy.gas;
5233
+ if (policy.mode !== void 0 && policy.mode !== "agent" && policy.mode !== "sponsored") {
5234
+ throw new Error("transaction gas policy mode is invalid");
5235
+ }
5236
+ if (policy.mode === "agent") {
5237
+ if (!pinned)
5238
+ throw new Error("agent gas requires caller-owned gas inputs");
5239
+ } else if (owner === agent) {
5240
+ throw new Error("sponsored transaction gas owner must not be the delegate");
5241
+ }
5242
+ if (pinned) {
5243
+ const expectedOwner = normalizeSuiAddress6(pinned.owner ?? delegate);
5244
+ const samePayment = actual.payment.length === pinned.payment.length && pinned.payment.every((ref, i) => {
5245
+ const got = actual.payment[i];
5246
+ return normalizeSuiAddress6(got.objectId) === normalizeSuiAddress6(ref.objectId) && got.version === String(ref.version) && got.digest === ref.digest;
5247
+ });
5248
+ if (owner !== expectedOwner || actual.budget !== String(pinned.budget ?? DEFAULT_GAS_BUDGET) || actual.price !== String(pinned.price ?? DEFAULT_GAS_PRICE) || !samePayment) {
5249
+ throw new Error("transaction gas does not match the caller gas inputs");
5250
+ }
5251
+ }
5252
+ const expiration = data.expiration;
5253
+ const validity = policy.expiration;
5254
+ if (expiration.$kind === "None") {
5255
+ if (!actual.payment.length || validity?.requireBounded) {
5256
+ throw new Error("transaction gas requires bounded expiration");
5257
+ }
5258
+ return;
5259
+ }
5260
+ if (!validity || validity.currentEpoch < 0n) {
5261
+ throw new Error("transaction expiration has no trusted epoch bound");
5262
+ }
5263
+ const now = validity.currentEpoch;
5264
+ if (expiration.$kind === "Epoch") {
5265
+ const epoch = BigInt(expiration.Epoch);
5266
+ if (!actual.payment.length || epoch < now || epoch > now + X402_EXPIRATION_EPOCHS) {
5267
+ throw new Error("transaction epoch expiration is outside the allowed window");
5268
+ }
5269
+ return;
5270
+ }
5271
+ const window = expiration.ValidDuring;
5272
+ if (!validity.chainIdentifier || window.chain !== validity.chainIdentifier || window.minEpoch === null || window.maxEpoch === null || window.minTimestamp !== null || window.maxTimestamp !== null) {
5273
+ throw new Error("transaction validity does not match the trusted chain window");
5274
+ }
5275
+ const min = BigInt(window.minEpoch);
5276
+ const max = BigInt(window.maxEpoch);
5277
+ if (min > now || max < now || max > now + ADDRESS_BALANCE_VALIDITY_EPOCHS || max - min > ADDRESS_BALANCE_VALIDITY_EPOCHS) {
5278
+ throw new Error("transaction validity is outside the allowed epoch window");
5279
+ }
5280
+ }
5281
+
5282
+ // ../sdk/dist/pay-operation/operation.js
5283
+ import { normalizeStructTag as normalizeStructTag9, normalizeSuiAddress as normalizeSuiAddress7 } from "@mysten/sui/utils";
5284
+
5285
+ // ../core/dist/policy/grant-target.js
5286
+ function normalizeHash(hex) {
5287
+ return hex.replace(/^0x/i, "").toLowerCase();
5288
+ }
5289
+ function grantAuthorityUsable(snapshot) {
5290
+ if (snapshot.status === "paused") {
5291
+ return { ok: false, reason: "grant is paused" };
5292
+ }
5293
+ if (snapshot.status === "revoked") {
5294
+ return { ok: false, reason: "grant is revoked" };
5295
+ }
5296
+ if (snapshot.status === "expired") {
5297
+ return { ok: false, reason: "grant is expired" };
5298
+ }
5299
+ if (snapshot.status !== "active") {
5300
+ return { ok: false, reason: `grant status is ${snapshot.status}` };
5301
+ }
5302
+ if (!snapshot.grantObjectId?.trim()) {
5303
+ return { ok: false, reason: "grant is not finalized (missing grantObjectId)" };
5304
+ }
5305
+ if (!snapshot.poolObjectId?.trim()) {
5306
+ return { ok: false, reason: "poolObjectId is required" };
5307
+ }
5308
+ return {
5309
+ ok: true,
5310
+ grantObjectId: snapshot.grantObjectId,
5311
+ poolObjectId: snapshot.poolObjectId
5312
+ };
5313
+ }
5314
+ function resolveGrantTarget(snapshot, offerTargetHash) {
5315
+ if (!offerTargetHash?.trim()) {
5316
+ return { ok: false, reason: "offer.targetHash is required" };
5317
+ }
5318
+ const wanted = normalizeHash(offerTargetHash);
5319
+ if (!/^[0-9a-f]{64}$/.test(wanted)) {
5320
+ return { ok: false, reason: "offer.targetHash must be 32-byte hex" };
5321
+ }
5322
+ const usable = grantAuthorityUsable(snapshot);
5323
+ if (!usable.ok) {
5324
+ return usable;
5325
+ }
5326
+ const hits = [];
5327
+ for (const policy of snapshot.policies) {
5328
+ if (policy.status !== "active")
5329
+ continue;
5330
+ for (const target of policy.targets) {
5331
+ if (normalizeHash(target.targetHash) === wanted) {
5332
+ hits.push({
5333
+ policyId: policy.policyId,
5334
+ onChainPolicyId: policy.onChainPolicyId,
5335
+ maxPerPayment: target.maxPerPayment
5336
+ });
5337
+ }
5338
+ }
5339
+ }
5340
+ if (hits.length > 1) {
5341
+ return {
5342
+ ok: false,
5343
+ reason: `target hash resolves to ${hits.length} active policies (EPolicyConflict)`
5344
+ };
5345
+ }
5346
+ if (hits.length === 1) {
5347
+ const hit = hits[0];
5348
+ return {
5349
+ ok: true,
5350
+ policyId: hit.policyId,
5351
+ onChainPolicyId: hit.onChainPolicyId,
5352
+ targetHash: wanted,
5353
+ maxPerPayment: hit.maxPerPayment,
5354
+ poolObjectId: usable.poolObjectId,
5355
+ grantObjectId: usable.grantObjectId,
5356
+ coinType: snapshot.coinType,
5357
+ delegateAddress: snapshot.delegateAddress
5358
+ };
5359
+ }
5360
+ return {
5361
+ ok: false,
5362
+ reason: "no active policy in grant snapshot matches offer.targetHash"
5363
+ };
5364
+ }
5365
+
5366
+ // ../sdk/dist/protocol/carrier.js
5367
+ import { fromBase64 as fromBase646, toBase64 as toBase643 } from "@mysten/sui/utils";
5368
+
5369
+ // ../sdk/dist/protocol/auth-params.js
5370
+ var TOKEN = /^[A-Za-z0-9!#$%&'*+\-.^_`|~]+$/;
5371
+ function parseAuthHeader(header) {
5372
+ const trimmed = header.trim();
5373
+ const firstSpace = trimmed.indexOf(" ");
5374
+ if (firstSpace === -1)
5375
+ return null;
5376
+ const scheme = trimmed.slice(0, firstSpace);
5377
+ if (!TOKEN.test(scheme))
5378
+ return null;
5379
+ const params = parseParams(trimmed.slice(firstSpace + 1));
5380
+ return params === null ? null : { scheme, params };
5381
+ }
5382
+ function parseParams(input) {
5383
+ const params = {};
5384
+ let i = 0;
5385
+ const skipSpace = () => {
5386
+ while (i < input.length && (input[i] === " " || input[i] === " "))
5387
+ i++;
5388
+ };
5389
+ skipSpace();
5390
+ while (i < input.length) {
5391
+ const keyStart = i;
5392
+ while (i < input.length && input[i] !== "=")
5393
+ i++;
5394
+ if (i >= input.length)
5395
+ return null;
5396
+ const key = input.slice(keyStart, i).trim();
5397
+ if (!TOKEN.test(key))
5398
+ return null;
5399
+ i++;
5400
+ let value;
5401
+ if (input[i] === '"') {
5402
+ i++;
5403
+ let out = "";
5404
+ let closed = false;
5405
+ while (i < input.length) {
5406
+ const ch = input[i];
5407
+ if (ch === "\\" && i + 1 < input.length) {
5408
+ out += input[i + 1];
5409
+ i += 2;
5410
+ continue;
5411
+ }
5412
+ if (ch === '"') {
5413
+ i++;
5414
+ closed = true;
5415
+ break;
5416
+ }
5417
+ out += ch;
5418
+ i++;
5419
+ }
5420
+ if (!closed)
5421
+ return null;
5422
+ value = out;
5423
+ } else {
5424
+ const start = i;
5425
+ while (i < input.length && input[i] !== ",")
5426
+ i++;
5427
+ value = input.slice(start, i).trim();
5428
+ }
5429
+ params[key] = value;
5430
+ skipSpace();
5431
+ if (i < input.length) {
5432
+ if (input[i] !== ",")
5433
+ return null;
5434
+ i++;
5435
+ skipSpace();
5436
+ }
5437
+ }
5438
+ return params;
5439
+ }
5440
+
5441
+ // ../sdk/dist/protocol/base64url.js
5442
+ function bytesToBase64Url(bytes) {
5443
+ let binary = "";
5444
+ for (const byte of bytes)
5445
+ binary += String.fromCharCode(byte);
5446
+ const base64 = typeof globalThis.btoa === "function" ? globalThis.btoa(binary) : Buffer.from(bytes).toString("base64");
5447
+ return base64.replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/g, "");
5448
+ }
5449
+ function bytesFromBase64Url(s) {
5450
+ const normalized = s.replace(/-/g, "+").replace(/_/g, "/");
5451
+ const pad = (4 - normalized.length % 4) % 4;
5452
+ const base64 = normalized + "=".repeat(pad);
5453
+ if (typeof globalThis.atob === "function") {
5454
+ const binary = globalThis.atob(base64);
5455
+ const out = new Uint8Array(binary.length);
5456
+ for (let i = 0; i < binary.length; i++)
5457
+ out[i] = binary.charCodeAt(i);
5458
+ return out;
5459
+ }
5460
+ return Uint8Array.from(Buffer.from(base64, "base64"));
5461
+ }
5462
+
5269
5463
  // ../sdk/dist/protocol/mpp.js
5270
5464
  function offerToBase64Url(offer) {
5271
5465
  return bytesToBase64Url(new TextEncoder().encode(JSON.stringify(offer)));
@@ -5901,12 +6095,12 @@ function decodeReceipt(header) {
5901
6095
  }
5902
6096
 
5903
6097
  // ../sdk/dist/protocol/x402.js
5904
- import { fromBase64 as fromBase644, toBase64 as toBase642 } from "@mysten/sui/utils";
6098
+ import { fromBase64 as fromBase645, toBase64 as toBase642 } from "@mysten/sui/utils";
5905
6099
  function utf8ToBase64(text) {
5906
6100
  return toBase642(new TextEncoder().encode(text));
5907
6101
  }
5908
6102
  function base64ToUtf8(value) {
5909
- return new TextDecoder().decode(fromBase644(value));
6103
+ return new TextDecoder().decode(fromBase645(value));
5910
6104
  }
5911
6105
  var X402_VERSION = 2;
5912
6106
  var X402_SCHEME = "exact";
@@ -6237,7 +6431,7 @@ async function readChallenge(res, dialect, opts) {
6237
6431
  const headerVal = res.headers.get(X402_CHALLENGE_HEADER);
6238
6432
  if (headerVal) {
6239
6433
  try {
6240
- const parsed = JSON.parse(new TextDecoder().decode(fromBase645(headerVal)));
6434
+ const parsed = JSON.parse(new TextDecoder().decode(fromBase646(headerVal)));
6241
6435
  const offer = decodeChallenge2(parsed, opts);
6242
6436
  if (offer)
6243
6437
  return offer;
@@ -6826,7 +7020,7 @@ async function resolvePayment(input, deps) {
6826
7020
  }
6827
7021
  let packageMatches;
6828
7022
  try {
6829
- packageMatches = normalizeSuiAddress6(offer.packageId) === normalizeSuiAddress6(packageId);
7023
+ packageMatches = normalizeSuiAddress7(offer.packageId) === normalizeSuiAddress7(packageId);
6830
7024
  } catch {
6831
7025
  packageMatches = false;
6832
7026
  }
@@ -6873,7 +7067,7 @@ async function resolvePayment(input, deps) {
6873
7067
  if (!identity) {
6874
7068
  return failedWith(PAY_OPERATION_ERROR_CODES.BUILD_FAILED, "guarded offer carries no valid registry identity", challengeId);
6875
7069
  }
6876
- if (normalizeSuiAddress6(identity.packageId) !== normalizeSuiAddress6(offer.packageId)) {
7070
+ if (normalizeSuiAddress7(identity.packageId) !== normalizeSuiAddress7(offer.packageId)) {
6877
7071
  return failedWith(PAY_OPERATION_ERROR_CODES.BUILD_FAILED, `guarded registry identity package ${identity.packageId} does not match offer package ${offer.packageId}`, challengeId);
6878
7072
  }
6879
7073
  if (!resolveExclusionRegistry2) {
@@ -7068,8 +7262,8 @@ function validateAmount(offer, resolved) {
7068
7262
  import { randomBytes } from "crypto";
7069
7263
  import { bcs as bcs5 } from "@mysten/sui/bcs";
7070
7264
  import { isValidPersonalMessageSignature, verifyPersonalMessageSignature } from "@mysten/sui/verify";
7071
- import { fromBase64 as fromBase646, normalizeSuiAddress as normalizeSuiAddress7, toBase64 as toBase644 } from "@mysten/sui/utils";
7072
- import { Transaction as Transaction3 } from "@mysten/sui/transactions";
7265
+ import { fromBase64 as fromBase647, normalizeSuiAddress as normalizeSuiAddress8, toBase64 as toBase644 } from "@mysten/sui/utils";
7266
+ import { Transaction as Transaction4 } from "@mysten/sui/transactions";
7073
7267
  var SPONSOR_PERSONAL_MESSAGE_DOMAIN = "suipay:sponsor-personal-message:v1";
7074
7268
  function encodeSponsorPersonalMessagePayload(payload) {
7075
7269
  if (payload.domain !== SPONSOR_PERSONAL_MESSAGE_DOMAIN) {
@@ -7092,17 +7286,17 @@ function encodeSponsorPersonalMessagePayload(payload) {
7092
7286
  push(bcs5.vector(bcs5.u8()).serialize([...Buffer.from(payload.domain, "utf8")]).toBytes());
7093
7287
  push(bcs5.vector(bcs5.u8()).serialize([...Buffer.from(payload.nonce, "utf8")]).toBytes());
7094
7288
  push(bcs5.u64().serialize(BigInt(payload.expiryMs)).toBytes());
7095
- push(bcs5.Address.serialize(normalizeSuiAddress7(payload.delegate)).toBytes());
7096
- push(bcs5.Address.serialize(normalizeSuiAddress7(payload.poolId)).toBytes());
7097
- push(bcs5.Address.serialize(normalizeSuiAddress7(payload.grantId)).toBytes());
7289
+ push(bcs5.Address.serialize(normalizeSuiAddress8(payload.delegate)).toBytes());
7290
+ push(bcs5.Address.serialize(normalizeSuiAddress8(payload.poolId)).toBytes());
7291
+ push(bcs5.Address.serialize(normalizeSuiAddress8(payload.grantId)).toBytes());
7098
7292
  push(bcs5.vector(bcs5.u8()).serialize([...Buffer.from(payload.network, "utf8")]).toBytes());
7099
- push(bcs5.Address.serialize(normalizeSuiAddress7(payload.packageId)).toBytes());
7293
+ push(bcs5.Address.serialize(normalizeSuiAddress8(payload.packageId)).toBytes());
7100
7294
  push(bcs5.vector(bcs5.u8()).serialize([...Buffer.from(payload.requestId, "utf8")]).toBytes());
7101
7295
  push(bcs5.vector(bcs5.u8()).serialize([...payload.txKindHash]).toBytes());
7102
7296
  return Buffer.concat(parts.map((p) => Buffer.from(p)));
7103
7297
  }
7104
7298
  function hashTransactionKindBytes(kindBytes) {
7105
- const raw = typeof kindBytes === "string" ? fromBase646(kindBytes) : kindBytes;
7299
+ const raw = typeof kindBytes === "string" ? fromBase647(kindBytes) : kindBytes;
7106
7300
  return sha256(raw);
7107
7301
  }
7108
7302
  function buildSponsorPersonalMessagePayload(input) {
@@ -7110,11 +7304,11 @@ function buildSponsorPersonalMessagePayload(input) {
7110
7304
  domain: SPONSOR_PERSONAL_MESSAGE_DOMAIN,
7111
7305
  nonce: input.nonce,
7112
7306
  expiryMs: input.expiryMs,
7113
- delegate: normalizeSuiAddress7(input.delegate),
7114
- poolId: normalizeSuiAddress7(input.poolId),
7115
- grantId: normalizeSuiAddress7(input.grantId),
7307
+ delegate: normalizeSuiAddress8(input.delegate),
7308
+ poolId: normalizeSuiAddress8(input.poolId),
7309
+ grantId: normalizeSuiAddress8(input.grantId),
7116
7310
  network: input.network,
7117
- packageId: normalizeSuiAddress7(input.packageId),
7311
+ packageId: normalizeSuiAddress8(input.packageId),
7118
7312
  requestId: input.requestId,
7119
7313
  txKindHash: hashTransactionKindBytes(input.transactionKindBytes)
7120
7314
  };
@@ -7272,7 +7466,7 @@ function createOfferKeyResolver(gatewayUrl, options = {}) {
7272
7466
  import { bcs as bcs6 } from "@mysten/sui/bcs";
7273
7467
  import { messageWithIntent } from "@mysten/sui/cryptography";
7274
7468
  import { isValidPersonalMessageSignature as isValidPersonalMessageSignature2, verifyPersonalMessageSignature as verifyPersonalMessageSignature2 } from "@mysten/sui/verify";
7275
- import { normalizeSuiAddress as normalizeSuiAddress8 } from "@mysten/sui/utils";
7469
+ import { normalizeSuiAddress as normalizeSuiAddress9 } from "@mysten/sui/utils";
7276
7470
  var SIGNED_REQUEST_DOMAIN = "suipay:signed-request:v1";
7277
7471
  var BOOTSTRAP_REQUEST_DOMAIN = "suipay:bootstrap-request:v1";
7278
7472
  var SIGNED_REQUEST_MAX_AGE_MS = 3e5;
@@ -7304,7 +7498,7 @@ function encodeBootstrapRequest(payload) {
7304
7498
  throw new Error(`domain must be ${BOOTSTRAP_REQUEST_DOMAIN}`);
7305
7499
  }
7306
7500
  const utf8Vec = (s) => bcs6.vector(bcs6.u8()).serialize([...Buffer.from(s, "utf8")]).toBytes();
7307
- const addr = (a) => bcs6.Address.serialize(normalizeSuiAddress8(a)).toBytes();
7501
+ const addr = (a) => bcs6.Address.serialize(normalizeSuiAddress9(a)).toBytes();
7308
7502
  const parts = [
7309
7503
  utf8Vec(payload.domain),
7310
7504
  utf8Vec(payload.network),
@@ -7324,7 +7518,7 @@ function encodeSignedRequest(payload) {
7324
7518
  throw new Error(`domain must be ${SIGNED_REQUEST_DOMAIN}`);
7325
7519
  }
7326
7520
  const utf8Vec = (s) => bcs6.vector(bcs6.u8()).serialize([...Buffer.from(s, "utf8")]).toBytes();
7327
- const addr = (a) => bcs6.Address.serialize(normalizeSuiAddress8(a)).toBytes();
7521
+ const addr = (a) => bcs6.Address.serialize(normalizeSuiAddress9(a)).toBytes();
7328
7522
  const parts = [
7329
7523
  utf8Vec(payload.domain),
7330
7524
  utf8Vec(payload.network),
@@ -7763,7 +7957,6 @@ var bootstrapPayerGrants = bootstrapPayerSessions;
7763
7957
  // ../sdk/dist/delegated-signer/payer.js
7764
7958
  var FINALIZATION_ATTEMPTS = 20;
7765
7959
  var FINALIZATION_DELAY_MS = 250;
7766
- var X402_EXPIRATION_EPOCHS = 32n;
7767
7960
  var X402_PRESENT_ATTEMPTS = 10;
7768
7961
  var X402_PRESENT_DELAY_MS = 1e3;
7769
7962
  function delay(ms) {
@@ -7774,8 +7967,6 @@ function delay(ms) {
7774
7967
  var SUI_CLOCK2 = "0x6";
7775
7968
  var SUI_CLOCK_INITIAL_SHARED_VERSION = "1";
7776
7969
  var BROADCAST_UNKNOWN = "broadcast-unknown";
7777
- var DEFAULT_GAS_BUDGET = 10000000n;
7778
- var DEFAULT_GAS_PRICE = 1000n;
7779
7970
  var DELEGATED_PAY_ERROR_CODES = {
7780
7971
  OFFER_SECRET_REQUIRED: "OFFER_SECRET_REQUIRED",
7781
7972
  CHALLENGE_TAMPERED: "CHALLENGE_TAMPERED",
@@ -8079,7 +8270,7 @@ function defaultLog(entry, error) {
8079
8270
  }
8080
8271
  function sameAddress2(a, b) {
8081
8272
  try {
8082
- return normalizeSuiAddress9(a) === normalizeSuiAddress9(b);
8273
+ return normalizeSuiAddress10(a) === normalizeSuiAddress10(b);
8083
8274
  } catch {
8084
8275
  return false;
8085
8276
  }
@@ -8141,7 +8332,7 @@ async function resolveSigner(input) {
8141
8332
  return {
8142
8333
  address: kp.getPublicKey().toSuiAddress(),
8143
8334
  async signTransaction(txBytes) {
8144
- const { signature } = await kp.signTransaction(fromBase647(txBytes));
8335
+ const { signature } = await kp.signTransaction(fromBase648(txBytes));
8145
8336
  return signature;
8146
8337
  },
8147
8338
  async signPersonalMessage(message) {
@@ -8217,7 +8408,7 @@ async function buildSpendAccountPayKind(input) {
8217
8408
  }
8218
8409
  const target = payMoveCallTarget(input.packageId, "scoped", true, refundable);
8219
8410
  const clockVersion = input.clockInitialSharedVersion?.trim() || SUI_CLOCK_INITIAL_SHARED_VERSION;
8220
- const tx = new Transaction4();
8411
+ const tx = new Transaction5();
8221
8412
  tx.setSender(input.delegate);
8222
8413
  tx.moveCall({
8223
8414
  target,
@@ -8289,7 +8480,7 @@ async function buildSpendAccountSettleOpenRecipientKind(input) {
8289
8480
  const guarded = resolveGuardedSettleOfflineInputs(input);
8290
8481
  const target = payMoveCallTarget(input.packageId, "open");
8291
8482
  const clockVersion = input.clockInitialSharedVersion?.trim() || SUI_CLOCK_INITIAL_SHARED_VERSION;
8292
- const tx = new Transaction4();
8483
+ const tx = new Transaction5();
8293
8484
  tx.setSender(input.delegate);
8294
8485
  tx.moveCall({
8295
8486
  target,
@@ -8336,7 +8527,7 @@ async function buildSpendAccountPayTx(input) {
8336
8527
  throw new Error("agent gas payment objects are required for executable pay");
8337
8528
  }
8338
8529
  const { kindBytes } = await buildSpendAccountPayKind(input);
8339
- const tx = Transaction4.fromKind(fromBase647(kindBytes));
8530
+ const tx = Transaction5.fromKind(fromBase648(kindBytes));
8340
8531
  tx.setSender(input.delegate);
8341
8532
  tx.setGasOwner(input.gas.owner ?? input.delegate);
8342
8533
  tx.setGasBudget(BigInt(input.gas.budget ?? DEFAULT_GAS_BUDGET));
@@ -8354,7 +8545,7 @@ async function buildSpendAccountSettleOpenRecipientTx(input) {
8354
8545
  throw new Error("agent gas payment objects are required for executable pay");
8355
8546
  }
8356
8547
  const { kindBytes } = await buildSpendAccountSettleOpenRecipientKind(input);
8357
- const tx = Transaction4.fromKind(fromBase647(kindBytes));
8548
+ const tx = Transaction5.fromKind(fromBase648(kindBytes));
8358
8549
  tx.setSender(input.delegate);
8359
8550
  tx.setGasOwner(input.gas.owner ?? input.delegate);
8360
8551
  tx.setGasBudget(BigInt(input.gas.budget ?? DEFAULT_GAS_BUDGET));
@@ -8387,7 +8578,7 @@ function readX402GasPin(offer) {
8387
8578
  }
8388
8579
  async function buildSpendAccountX402PayTx(input) {
8389
8580
  const { kindBytes } = await buildSpendAccountPayKind(input);
8390
- const tx = Transaction4.fromKind(fromBase647(kindBytes));
8581
+ const tx = Transaction5.fromKind(fromBase648(kindBytes));
8391
8582
  tx.setSender(input.delegate);
8392
8583
  tx.setGasOwner(input.gas.owner);
8393
8584
  tx.setGasBudget(input.gas.budget);
@@ -8423,7 +8614,7 @@ function chainIdentifierReader(client) {
8423
8614
  function assertPayTransaction(txBytes, expected) {
8424
8615
  let data;
8425
8616
  try {
8426
- data = Transaction4.from(fromBase647(txBytes)).getData();
8617
+ data = Transaction5.from(fromBase648(txBytes)).getData();
8427
8618
  } catch {
8428
8619
  throw new Error("transaction is not valid Sui transaction bytes");
8429
8620
  }
@@ -8438,13 +8629,13 @@ function assertPayTransaction(txBytes, expected) {
8438
8629
  if (cmd.$kind !== "MoveCall" || !cmd.MoveCall) {
8439
8630
  throw new Error("transaction is not a MoveCall");
8440
8631
  }
8441
- const got = `${normalizeSuiAddress9(String(cmd.MoveCall.package))}::${cmd.MoveCall.module}::${cmd.MoveCall.function}`;
8632
+ const got = `${normalizeSuiAddress10(String(cmd.MoveCall.package))}::${cmd.MoveCall.module}::${cmd.MoveCall.function}`;
8442
8633
  if (got !== wanted) {
8443
8634
  throw new Error(`transaction does not reconstruct ${wanted}`);
8444
8635
  }
8445
8636
  let expectedKind;
8446
8637
  try {
8447
- expectedKind = Transaction4.fromKind(fromBase647(expected.kindBytes)).getData();
8638
+ expectedKind = Transaction5.fromKind(fromBase648(expected.kindBytes)).getData();
8448
8639
  } catch {
8449
8640
  throw new Error("intended pay kind baseline is invalid");
8450
8641
  }
@@ -8470,6 +8661,7 @@ function assertPayTransaction(txBytes, expected) {
8470
8661
  if (args && args.length !== expectedArgc) {
8471
8662
  throw new Error(`pay expects ${expectedArgc} arguments; got ${args.length}`);
8472
8663
  }
8664
+ assertPayGas(data, expected.delegate, expected.gas);
8473
8665
  }
8474
8666
  function asValidatedReceipt(value) {
8475
8667
  if (!value || typeof value !== "object")
@@ -9265,8 +9457,19 @@ async function payDelegatedSpendAccount(args) {
9265
9457
  }
9266
9458
  }
9267
9459
  try {
9268
- assertPayTransaction(txBytes, expectedPay);
9460
+ assertPayTransaction(txBytes, {
9461
+ ...expectedPay,
9462
+ gas: {
9463
+ mode: gasMode,
9464
+ ...gasMode === "agent" ? { gas: deps.gas } : {},
9465
+ expiration: await readPayExpirationPolicy(txBytes, deps)
9466
+ }
9467
+ });
9269
9468
  } catch (err) {
9469
+ if (err instanceof SuiPayError && err.code === "chain.unavailable") {
9470
+ logInternal(log, { code: "chain.unavailable", msg: "pre-sign chain read failed" }, err);
9471
+ return abortBeforeSign("PREPARED_VERIFY_UNAVAILABLE", PUBLIC_DETAIL.PREPARED_VERIFY_UNAVAILABLE);
9472
+ }
9270
9473
  logInternal(log, { code: "client.tx_mismatch", msg: "pre-sign pay validation failed" }, err);
9271
9474
  return abortBeforeSign(gasMode === "sponsored" ? "SPONSORED_TX_MISMATCH" : "TX_MISMATCH", gasMode === "sponsored" ? PUBLIC_DETAIL.SPONSORED_TX_MISMATCH : PUBLIC_DETAIL.TX_MISMATCH);
9272
9475
  }
@@ -9533,7 +9736,18 @@ async function payX402Reserved(ctx) {
9533
9736
  return ctx.abort("BUILD_FAILED", PUBLIC_DETAIL.BUILD_FAILED);
9534
9737
  }
9535
9738
  try {
9536
- assertPayTransaction(txBytes, ctx.expected);
9739
+ assertPayTransaction(txBytes, {
9740
+ ...ctx.expected,
9741
+ gas: {
9742
+ mode: "sponsored",
9743
+ gas: ctx.buildInput.gas,
9744
+ expiration: {
9745
+ currentEpoch: ctx.buildInput.currentEpoch,
9746
+ chainIdentifier: ctx.buildInput.chainIdentifier,
9747
+ requireBounded: true
9748
+ }
9749
+ }
9750
+ });
9537
9751
  } catch (err) {
9538
9752
  logInternal(log, { code: "client.tx_mismatch", msg: "pre-sign x402 pay validation failed" }, err);
9539
9753
  return ctx.abort("TX_MISMATCH", PUBLIC_DETAIL.TX_MISMATCH);
@@ -9723,7 +9937,7 @@ function payMoveCallTarget(packageId, accessMode = "scoped", _guarded = false, r
9723
9937
  accessMode: accessMode === "open" ? "open" : "scoped",
9724
9938
  refundable
9725
9939
  });
9726
- return `${normalizeSuiAddress9(packageId)}::spend_account::${fn}`;
9940
+ return `${normalizeSuiAddress10(packageId)}::spend_account::${fn}`;
9727
9941
  }
9728
9942
  function resolveGuardedSettleOfflineInputs(input) {
9729
9943
  const core = [input.exclusionDirectoryId, input.recipientRegistryId, input.expiresAtMs];
@@ -9799,9 +10013,9 @@ function createMemoryLedger() {
9799
10013
  }
9800
10014
 
9801
10015
  // ../sdk/dist/agent-sdk/verify-prepared-settlement.js
9802
- import { normalizeSuiAddress as normalizeSuiAddress10 } from "@mysten/sui/utils";
9803
- import { Transaction as Transaction5 } from "@mysten/sui/transactions";
9804
- import { fromBase64 as fromBase648 } from "@mysten/sui/utils";
10016
+ import { normalizeSuiAddress as normalizeSuiAddress11 } from "@mysten/sui/utils";
10017
+ import { Transaction as Transaction6 } from "@mysten/sui/transactions";
10018
+ import { fromBase64 as fromBase649 } from "@mysten/sui/utils";
9805
10019
 
9806
10020
  // ../sdk/dist/protocol/prepared-settlement.js
9807
10021
  var PREPARED_SETTLEMENT_VERSION = 1;
@@ -9890,7 +10104,7 @@ function reject(field, message, cause) {
9890
10104
  }
9891
10105
  function sameAddress3(a, b) {
9892
10106
  try {
9893
- return normalizeSuiAddress10(a) === normalizeSuiAddress10(b);
10107
+ return normalizeSuiAddress11(a) === normalizeSuiAddress11(b);
9894
10108
  } catch {
9895
10109
  return false;
9896
10110
  }
@@ -9901,7 +10115,7 @@ function sameCoinType(a, b) {
9901
10115
  if (pkg === void 0 || rest.length !== 2)
9902
10116
  return value.trim();
9903
10117
  try {
9904
- return `${normalizeSuiAddress10(pkg)}::${rest.join("::")}`;
10118
+ return `${normalizeSuiAddress11(pkg)}::${rest.join("::")}`;
9905
10119
  } catch {
9906
10120
  return value.trim();
9907
10121
  }
@@ -9926,7 +10140,7 @@ async function verifyPreparedPayment(input) {
9926
10140
  }
9927
10141
  let data;
9928
10142
  try {
9929
- data = Transaction5.from(fromBase648(prepared.transactionBytes)).getData();
10143
+ data = Transaction6.from(fromBase649(prepared.transactionBytes)).getData();
9930
10144
  } catch {
9931
10145
  reject("transactionBytes", "prepared transaction bytes are not a Sui transaction");
9932
10146
  }
@@ -10041,9 +10255,15 @@ async function verifyPreparedPayment(input) {
10041
10255
  kindBytes: rebuilt,
10042
10256
  accessMode: prepared.accessMode,
10043
10257
  recipient: prepared.recipient,
10044
- refundable: offer.refundable === true
10258
+ refundable: offer.refundable === true,
10259
+ gas: {
10260
+ mode: "sponsored",
10261
+ expiration: await readPayExpirationPolicy(prepared.transactionBytes, input)
10262
+ }
10045
10263
  });
10046
10264
  } catch (err) {
10265
+ if (err instanceof SuiPayError && err.code === "chain.unavailable")
10266
+ throw err;
10047
10267
  reject("transactionBytes", "prepared transaction does not reconstruct the intended settlement", err);
10048
10268
  }
10049
10269
  return prepared;
@@ -10615,10 +10835,10 @@ async function verifyGrantOnChain(input) {
10615
10835
  ok: false,
10616
10836
  error: manifestError(MANIFEST_ERROR_CODES.GRANT_NOT_VERIFIED, detail)
10617
10837
  });
10618
- if (!state.delegateAddress || normalizeSuiAddress11(state.delegateAddress) !== normalizeSuiAddress11(input.delegateAddress)) {
10838
+ if (!state.delegateAddress || normalizeSuiAddress12(state.delegateAddress) !== normalizeSuiAddress12(input.delegateAddress)) {
10619
10839
  return notVerified(`grant ${input.grantObjectId} does not name this delegate on chain`);
10620
10840
  }
10621
- if (!state.poolObjectId || normalizeSuiAddress11(state.poolObjectId) !== normalizeSuiAddress11(input.poolObjectId)) {
10841
+ if (!state.poolObjectId || normalizeSuiAddress12(state.poolObjectId) !== normalizeSuiAddress12(input.poolObjectId)) {
10622
10842
  return notVerified(`grant ${input.grantObjectId} draws on a different pool than the one resolved`);
10623
10843
  }
10624
10844
  if (state.revoked === true) {
@@ -10766,7 +10986,9 @@ async function createPayer(options) {
10766
10986
  offer,
10767
10987
  delegateAddress: address,
10768
10988
  expectedGrantObjectId: binding.grantObjectId,
10769
- expectedPoolObjectId: binding.poolObjectId
10989
+ expectedPoolObjectId: binding.poolObjectId,
10990
+ getCurrentEpoch: deps.getCurrentEpoch,
10991
+ getChainIdentifier: deps.getChainIdentifier
10770
10992
  });
10771
10993
  }
10772
10994
  return {
@@ -10776,7 +10998,7 @@ async function createPayer(options) {
10776
10998
  }
10777
10999
 
10778
11000
  // ../sdk/dist/oauth/delegate-proof.js
10779
- import { normalizeSuiAddress as normalizeSuiAddress12 } from "@mysten/sui/utils";
11001
+ import { normalizeSuiAddress as normalizeSuiAddress13 } from "@mysten/sui/utils";
10780
11002
  import { verifyPersonalMessageSignature as verifyPersonalMessageSignature3 } from "@mysten/sui/verify";
10781
11003
  var OAUTH_DELEGATE_PROOF_TTL_MS = 15 * 6e4;
10782
11004
  function encodeOAuthDelegateProof(binding, expiresAtMs, ownerAddress) {
@@ -10790,8 +11012,8 @@ function encodeOAuthDelegateProof(binding, expiresAtMs, ownerAddress) {
10790
11012
  binding.resource,
10791
11013
  binding.scope,
10792
11014
  binding.codeChallenge,
10793
- normalizeSuiAddress12(binding.delegateAddress),
10794
- normalizeSuiAddress12(ownerAddress),
11015
+ normalizeSuiAddress13(binding.delegateAddress),
11016
+ normalizeSuiAddress13(ownerAddress),
10795
11017
  expiresAtMs
10796
11018
  ]));
10797
11019
  }
@@ -10801,10 +11023,10 @@ async function verifyOAuthDelegateProof(binding, proof, nowMs = Date.now(), expe
10801
11023
  const message = encodeOAuthDelegateProof(binding, p.expiresAtMs, p.ownerAddress);
10802
11024
  if (typeof p.signature !== "string" || p.signature.length > 8192 || p.expiresAtMs <= nowMs || p.expiresAtMs > nowMs + OAUTH_DELEGATE_PROOF_TTL_MS)
10803
11025
  return false;
10804
- if (expectedOwner && normalizeSuiAddress12(p.ownerAddress) !== normalizeSuiAddress12(expectedOwner))
11026
+ if (expectedOwner && normalizeSuiAddress13(p.ownerAddress) !== normalizeSuiAddress13(expectedOwner))
10805
11027
  return false;
10806
11028
  const publicKey = await verifyPersonalMessageSignature3(message, p.signature);
10807
- return publicKey.toSuiAddress() === normalizeSuiAddress12(binding.delegateAddress);
11029
+ return publicKey.toSuiAddress() === normalizeSuiAddress13(binding.delegateAddress);
10808
11030
  } catch {
10809
11031
  return false;
10810
11032
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mysten-incubation/suipay-buyer",
3
- "version": "0.4.0-dev.0",
3
+ "version": "0.4.0-dev.1",
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",