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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -13,7 +13,7 @@ import {
13
13
  parseErrorPayload,
14
14
  stricterPaymentState,
15
15
  toErrorFields
16
- } from "./chunk-XQA5ISYE.js";
16
+ } from "./chunk-BCI3TKYX.js";
17
17
 
18
18
  // src/mcp.ts
19
19
  async function buildMcpPaymentPayload(paymentRequired, signer) {
@@ -339,7 +339,7 @@ function readIntent(body) {
339
339
  // ../sdk/dist/buyer/verify-owner-transaction.js
340
340
  import { TransactionDataBuilder } from "@mysten/sui/transactions";
341
341
  import { bcs } from "@mysten/sui/bcs";
342
- import { fromBase64, normalizeStructTag as normalizeStructTag2, normalizeSuiAddress } from "@mysten/sui/utils";
342
+ import { fromBase64, normalizeStructTag as normalizeStructTag4, normalizeSuiAddress } from "@mysten/sui/utils";
343
343
 
344
344
  // ../core/dist/assets/testnet.js
345
345
  import { normalizeStructTag } from "@mysten/sui/utils";
@@ -384,6 +384,68 @@ function tryNormalizeStructTag(coinType) {
384
384
  }
385
385
  }
386
386
 
387
+ // ../core/dist/assets/localnet.js
388
+ import { normalizeStructTag as normalizeStructTag2 } from "@mysten/sui/utils";
389
+ var LOCALNET_SUI_COIN_TYPE = TESTNET_SUI_COIN_TYPE;
390
+ var LOCALNET_SUI_DECIMALS = TESTNET_SUI_DECIMALS;
391
+ var LOCALNET_USDC_DECIMALS = 6;
392
+ function localnetAssets(usdcCoinType) {
393
+ const assets = [
394
+ {
395
+ id: "sui",
396
+ symbol: "SUI",
397
+ coinType: LOCALNET_SUI_COIN_TYPE,
398
+ decimals: LOCALNET_SUI_DECIMALS,
399
+ network: "sui:localnet"
400
+ }
401
+ ];
402
+ const usdc = usdcCoinType?.trim();
403
+ if (usdc) {
404
+ try {
405
+ normalizeStructTag2(usdc);
406
+ } catch {
407
+ throw new Error(`localnet USDC coin type is not a valid coin type: ${usdc} (check SUIPAY_COIN_TYPE)`);
408
+ }
409
+ assets.push({
410
+ id: "usdc",
411
+ symbol: "USDC",
412
+ coinType: usdc,
413
+ decimals: LOCALNET_USDC_DECIMALS,
414
+ network: "sui:localnet"
415
+ });
416
+ }
417
+ return assets;
418
+ }
419
+
420
+ // ../core/dist/assets/index.js
421
+ import { normalizeStructTag as normalizeStructTag3 } from "@mysten/sui/utils";
422
+ function normalizeNetwork(network) {
423
+ const n = (network ?? "").trim();
424
+ return n === "sui:localnet" || n === "localnet" ? "sui:localnet" : "sui:testnet";
425
+ }
426
+ function assetsForNetwork(network, options) {
427
+ return normalizeNetwork(network) === "sui:localnet" ? localnetAssets(options?.usdcCoinType) : TESTNET_ASSETS;
428
+ }
429
+ function supportedAssetByCoinTypeForNetwork(coinType, network, options) {
430
+ if (normalizeNetwork(network) === "sui:testnet") {
431
+ return supportedAssetByCoinType(coinType);
432
+ }
433
+ const trimmed = coinType.trim();
434
+ if (!trimmed)
435
+ return null;
436
+ let target;
437
+ try {
438
+ target = normalizeStructTag3(trimmed);
439
+ } catch {
440
+ return null;
441
+ }
442
+ for (const asset of localnetAssets(options?.usdcCoinType)) {
443
+ if (normalizeStructTag3(asset.coinType) === target)
444
+ return asset;
445
+ }
446
+ return null;
447
+ }
448
+
387
449
  // ../sdk/dist/sponsor/kind-gas-coin.js
388
450
  function kindTouchesGasCoin(commands) {
389
451
  return commands.some(namesGasCoin);
@@ -422,7 +484,7 @@ function safeNormalizeAddress(address) {
422
484
  }
423
485
  function safeNormalizeStructTag(tag) {
424
486
  try {
425
- return normalizeStructTag2(tag);
487
+ return normalizeStructTag4(tag);
426
488
  } catch {
427
489
  }
428
490
  return null;
@@ -518,9 +580,12 @@ function verifyOwnerTransaction(input) {
518
580
  throw new TransactionVerificationError("unsupportedOperation");
519
581
  }
520
582
  }
583
+ const networkAssets = assetsForNetwork(input.assetNetwork, {
584
+ usdcCoinType: input.localnetUsdcCoinType
585
+ });
521
586
  const knownCoinPackages = /* @__PURE__ */ new Set([
522
587
  FRAMEWORK_PACKAGE_ID,
523
- ...TESTNET_ASSETS.map((a) => safeNormalizeAddress(a.coinType.split("::")[0]))
588
+ ...networkAssets.map((a) => safeNormalizeAddress(a.coinType.split("::")[0]))
524
589
  ]);
525
590
  for (const cmd of commands) {
526
591
  if (cmd.$kind === "MoveCall") {
@@ -673,7 +738,9 @@ function verifyOwnerTransaction(input) {
673
738
  switch (op.kind) {
674
739
  case "create_pool":
675
740
  case "top_up": {
676
- if (!supportedAssetByCoinType(normCoinType)) {
741
+ if (!supportedAssetByCoinTypeForNetwork(normCoinType, input.assetNetwork, {
742
+ usdcCoinType: input.localnetUsdcCoinType
743
+ })) {
677
744
  throw new TransactionVerificationError("coinType");
678
745
  }
679
746
  let expectedAmt;
@@ -1647,6 +1714,25 @@ async function executeSignedDigest(transport, input) {
1647
1714
  return ok({ digest: confirmed });
1648
1715
  }
1649
1716
 
1717
+ // ../sdk/dist/buyer/owner-anchors.js
1718
+ var SCOPED_GRANT_FN = "create_policy_grant";
1719
+ var OPEN_GRANT_FN = "create_open_recipient_grant";
1720
+ function declaredAsset(asset, assets = TESTNET_ASSETS) {
1721
+ if (typeof asset !== "string")
1722
+ return null;
1723
+ const trimmed = asset.trim();
1724
+ const byLabel = assets.find((a) => a.id === trimmed.toLowerCase());
1725
+ if (byLabel)
1726
+ return byLabel;
1727
+ const byCoin = supportedAssetByCoinType(trimmed);
1728
+ return byCoin && assets.some((a) => a.id === byCoin.id) ? byCoin : null;
1729
+ }
1730
+ function assertMoveFunction(target, expected) {
1731
+ const fn = typeof target === "string" ? target.split("::").at(-1) : void 0;
1732
+ if (fn !== expected)
1733
+ throw new TransactionVerificationError("target");
1734
+ }
1735
+
1650
1736
  // ../sdk/dist/buyer/v1/delegated-signers.js
1651
1737
  function createAgentsApi(transport) {
1652
1738
  async function list() {
@@ -1753,25 +1839,39 @@ function createAgentsApi(transport) {
1753
1839
  finalized.push(fin.value);
1754
1840
  }
1755
1841
  for (const grant of created.value.grants) {
1756
- const scope = input.assetScopes.find((s) => s.asset.toLowerCase() === grant.asset.toLowerCase() || supportedAssetByCoinType(s.asset)?.id === grant.asset.toLowerCase());
1757
- const coinType = TESTNET_ASSETS.find((a) => a.id === grant.asset.toLowerCase() || a.symbol.toLowerCase() === grant.asset.toLowerCase())?.coinType ?? scope?.asset ?? grant.asset;
1758
- const isTargetOpen = grant.moveTarget.endsWith("::create_open_recipient_grant");
1759
- const operation = isTargetOpen ? {
1760
- kind: "create_grant_open",
1761
- coinType,
1762
- delegate: { address: input.agentAddress, source: "independent" },
1763
- sessionCap: scope?.totalBudgetAtomic != null ? BigInt(scope.totalBudgetAtomic) : null,
1764
- maxPerPayment: scope?.maxPerPaymentAtomic != null ? BigInt(scope.maxPerPaymentAtomic) : null,
1765
- expiresAtMs: scope?.expiresAt != null ? String(scope.expiresAt) : "0"
1766
- } : {
1767
- kind: "create_grant_scoped",
1768
- coinType,
1769
- delegate: { address: input.agentAddress, source: "independent" },
1770
- sessionCap: scope?.totalBudgetAtomic ?? null,
1771
- maxPerPayment: scope?.maxPerPaymentAtomic ?? null,
1772
- expiresAtMs: scope?.expiresAt != null ? String(scope.expiresAt) : "0",
1773
- ...input.policyIds !== void 0 ? { policyIdCount: input.policyIds.length } : {}
1774
- };
1842
+ const open = input.accessMode === "open";
1843
+ assertMoveFunction(grant.moveTarget, open ? OPEN_GRANT_FN : SCOPED_GRANT_FN);
1844
+ const grantAsset = declaredAsset(grant.coinType) ?? declaredAsset(grant.asset);
1845
+ const scope = grantAsset ? input.assetScopes.find((s) => declaredAsset(s.asset)?.id === grantAsset.id) : void 0;
1846
+ if (!grantAsset || !scope)
1847
+ throw new TransactionVerificationError("coinType");
1848
+ const coinType = grantAsset.coinType;
1849
+ const delegate = { address: input.agentAddress, source: "independent" };
1850
+ const expiresAtMs = scope.expiresAt != null ? String(scope.expiresAt) : "0";
1851
+ let operation;
1852
+ if (open) {
1853
+ if (scope.totalBudgetAtomic == null || scope.maxPerPaymentAtomic == null) {
1854
+ throw new TransactionVerificationError("caps");
1855
+ }
1856
+ operation = {
1857
+ kind: "create_grant_open",
1858
+ coinType,
1859
+ delegate,
1860
+ sessionCap: BigInt(scope.totalBudgetAtomic),
1861
+ maxPerPayment: BigInt(scope.maxPerPaymentAtomic),
1862
+ expiresAtMs
1863
+ };
1864
+ } else {
1865
+ operation = {
1866
+ kind: "create_grant_scoped",
1867
+ coinType,
1868
+ delegate,
1869
+ sessionCap: scope.totalBudgetAtomic,
1870
+ maxPerPayment: scope.maxPerPaymentAtomic,
1871
+ expiresAtMs,
1872
+ ...input.policyIds !== void 0 ? { policyIdCount: input.policyIds.length } : {}
1873
+ };
1874
+ }
1775
1875
  const signed = await sponsorAndSignKind(transport, {
1776
1876
  kindBytes: grant.txKindBytes,
1777
1877
  sender: signerRes.value.address,
@@ -1989,41 +2089,97 @@ function createPoliciesApi(transport, intents) {
1989
2089
  return fail(response);
1990
2090
  return ok(parsed.intent);
1991
2091
  }
1992
- async function getPoolObjectId(asset, coinType) {
2092
+ async function getPoolObjectId(assetId, coinType) {
1993
2093
  const response = await transport.request("/v1/buyer/pools");
1994
2094
  if (response.status !== 200 || !isRecord(response.body) || !Array.isArray(response.body.pools)) {
1995
2095
  return null;
1996
2096
  }
1997
2097
  const pools = asDto(response.body.pools);
1998
- const found = pools.find((p) => p.asset.toLowerCase() === asset.toLowerCase() || p.coinType.toLowerCase() === coinType.toLowerCase() || supportedAssetByCoinType(p.coinType)?.id === asset.toLowerCase());
2098
+ const found = pools.find((p) => declaredAsset(p.coinType)?.coinType === coinType || declaredAsset(p.asset)?.id === assetId);
1999
2099
  return found?.objectId ?? null;
2000
2100
  }
2001
- async function activate(id, signer) {
2101
+ function readExpectation(options) {
2102
+ if (!isRecord(options) || !isRecord(options.expected))
2103
+ return null;
2104
+ const e = options.expected;
2105
+ const asset = declaredAsset(e.asset);
2106
+ if (!asset)
2107
+ return null;
2108
+ const positive = (v) => typeof v === "string" && /^[1-9][0-9]*$/.test(v);
2109
+ if (!positive(e.totalCap) || !positive(e.maxPerPayment))
2110
+ return null;
2111
+ if (!Number.isInteger(e.targetCount) || e.targetCount < 1)
2112
+ return null;
2113
+ const exp = e.expiresAt;
2114
+ if (exp != null && typeof exp !== "string" && typeof exp !== "number")
2115
+ return null;
2116
+ return {
2117
+ asset,
2118
+ terms: {
2119
+ asset: e.asset,
2120
+ totalCap: e.totalCap,
2121
+ maxPerPayment: e.maxPerPayment,
2122
+ expiresAt: exp,
2123
+ targetCount: e.targetCount
2124
+ }
2125
+ };
2126
+ }
2127
+ async function activate(id, options) {
2128
+ const read = readExpectation(options);
2129
+ if (!read) {
2130
+ return failLocal(400, "request.invalid", "not_charged", {
2131
+ message: "policies.activate needs options.expected: the asset, totalCap, maxPerPayment, expiresAt and targetCount the policy was created with"
2132
+ });
2133
+ }
2134
+ const { terms: expected, asset } = read;
2002
2135
  const policyRes = await get(id);
2003
2136
  if (!policyRes.ok)
2004
2137
  return policyRes;
2005
2138
  const policy = policyRes.value;
2006
- const poolObjectId = await getPoolObjectId(policy.asset, policy.coinType);
2139
+ const rowAsset = declaredAsset(policy.asset) ?? declaredAsset(policy.coinType);
2140
+ if (rowAsset?.id !== asset.id) {
2141
+ return failLocal(400, "request.invalid", "not_charged", {
2142
+ message: `Policy ${id} is for ${policy.asset}, not the expected asset ${asset.id}`
2143
+ });
2144
+ }
2145
+ const poolObjectId = await getPoolObjectId(asset.id, asset.coinType);
2007
2146
  if (!poolObjectId) {
2008
2147
  return failLocal(400, "request.invalid", "not_charged", {
2009
- message: `No active spend account pool found for asset ${policy.asset}`
2148
+ message: `No active spend account pool found for asset ${asset.id}`
2010
2149
  });
2011
2150
  }
2012
- const assetMatch = TESTNET_ASSETS.find((a) => a.id === policy.asset.toLowerCase() || a.symbol.toLowerCase() === policy.asset.toLowerCase() || a.coinType.toLowerCase() === policy.asset.toLowerCase()) ?? supportedAssetByCoinType(policy.coinType);
2013
- const coinType = assetMatch?.coinType ?? policy.coinType;
2014
2151
  const operation = {
2015
2152
  kind: "create_policy",
2016
- coinType,
2153
+ coinType: asset.coinType,
2017
2154
  poolObjectId,
2018
- totalCap: policy.totalCap,
2019
- maxPerPayment: policy.maxPerPayment,
2020
- expiresAtMs: policy.expiresAt ? Date.parse(policy.expiresAt) : "0",
2021
- targetCount: policy.targets?.length ?? 0
2155
+ totalCap: expected.totalCap,
2156
+ maxPerPayment: expected.maxPerPayment,
2157
+ expiresAtMs: expected.expiresAt ?? "0",
2158
+ targetCount: expected.targetCount
2022
2159
  };
2023
2160
  const prepared = await prepareAction(id, "/prepare");
2024
2161
  if (!prepared.ok)
2025
2162
  return prepared;
2026
- return intents.execute(prepared.value, operation, signer);
2163
+ return intents.execute(prepared.value, operation, options.signer);
2164
+ }
2165
+ async function createAndActivate(input, signer) {
2166
+ const created = await create(input);
2167
+ if (!created.ok)
2168
+ return created;
2169
+ const serviceIds = new Set(input.serviceIds.map((s) => s.trim()).filter(Boolean));
2170
+ const activated = await activate(created.value.id, {
2171
+ expected: {
2172
+ asset: input.asset,
2173
+ totalCap: input.totalCap,
2174
+ maxPerPayment: input.maxPerPayment,
2175
+ expiresAt: input.expiresAt ?? null,
2176
+ targetCount: serviceIds.size
2177
+ },
2178
+ ...signer ? { signer } : {}
2179
+ });
2180
+ if (!activated.ok)
2181
+ return activated;
2182
+ return ok({ ...activated.value, policy: created.value }, activated.status);
2027
2183
  }
2028
2184
  async function runLifecycle(id, action, suffix, signer) {
2029
2185
  const policyRes = await get(id);
@@ -2035,18 +2191,22 @@ function createPoliciesApi(transport, intents) {
2035
2191
  message: `Policy ${id} is not active on-chain (missing onChainPolicyId)`
2036
2192
  });
2037
2193
  }
2038
- const poolObjectId = await getPoolObjectId(policy.asset, policy.coinType);
2194
+ const asset = declaredAsset(policy.asset) ?? declaredAsset(policy.coinType);
2195
+ if (!asset) {
2196
+ return failLocal(400, "request.invalid", "not_charged", {
2197
+ message: `Unsupported asset ${policy.asset} for policy ${id}`
2198
+ });
2199
+ }
2200
+ const poolObjectId = await getPoolObjectId(asset.id, asset.coinType);
2039
2201
  if (!poolObjectId) {
2040
2202
  return failLocal(400, "request.invalid", "not_charged", {
2041
- message: `No active spend account pool found for asset ${policy.asset}`
2203
+ message: `No active spend account pool found for asset ${asset.id}`
2042
2204
  });
2043
2205
  }
2044
- const assetMatch = TESTNET_ASSETS.find((a) => a.id === policy.asset.toLowerCase() || a.symbol.toLowerCase() === policy.asset.toLowerCase() || a.coinType.toLowerCase() === policy.asset.toLowerCase()) ?? supportedAssetByCoinType(policy.coinType);
2045
- const coinType = assetMatch?.coinType ?? policy.coinType;
2046
2206
  const operation = {
2047
2207
  kind: "policy_lifecycle",
2048
2208
  action,
2049
- coinType,
2209
+ coinType: asset.coinType,
2050
2210
  poolObjectId,
2051
2211
  onChainPolicyId: policy.onChainPolicyId
2052
2212
  };
@@ -2064,6 +2224,7 @@ function createPoliciesApi(transport, intents) {
2064
2224
  prepareResume: (id) => prepareAction(id, "/resume/prepare"),
2065
2225
  prepareRevoke: (id) => prepareAction(id, "/revoke/prepare"),
2066
2226
  activate,
2227
+ createAndActivate,
2067
2228
  pause: (id, signer) => runLifecycle(id, "pause", "/pause/prepare", signer),
2068
2229
  resume: (id, signer) => runLifecycle(id, "resume", "/resume/prepare", signer),
2069
2230
  revoke: (id, signer) => runLifecycle(id, "revoke", "/revoke/prepare", signer)
@@ -2184,16 +2345,16 @@ function createSessionsApi(transport, intents) {
2184
2345
  message: "No delegate address provided or found in connection listing"
2185
2346
  });
2186
2347
  }
2187
- const declaredAsset = input.asset ?? conn?.asset;
2188
- if (!declaredAsset) {
2348
+ const declaredAsset2 = input.asset ?? conn?.asset;
2349
+ if (!declaredAsset2) {
2189
2350
  return failLocal(400, "request.invalid", "not_charged", {
2190
2351
  message: "No declared asset provided for grant"
2191
2352
  });
2192
2353
  }
2193
- const assetMatch = TESTNET_ASSETS.find((a) => a.id === declaredAsset.toLowerCase() || a.symbol.toLowerCase() === declaredAsset.toLowerCase() || a.coinType.toLowerCase() === declaredAsset.toLowerCase());
2354
+ const assetMatch = TESTNET_ASSETS.find((a) => a.id === declaredAsset2.toLowerCase() || a.symbol.toLowerCase() === declaredAsset2.toLowerCase() || a.coinType.toLowerCase() === declaredAsset2.toLowerCase());
2194
2355
  if (!assetMatch) {
2195
2356
  return failLocal(400, "request.invalid", "not_charged", {
2196
- message: `Unsupported asset ${declaredAsset} for grant`
2357
+ message: `Unsupported asset ${declaredAsset2} for grant`
2197
2358
  });
2198
2359
  }
2199
2360
  const coinType = assetMatch.coinType;
@@ -2485,7 +2646,7 @@ function wrapFailover(clients, options = {}) {
2485
2646
 
2486
2647
  // ../sdk/dist/buyer-control/chain.js
2487
2648
  import { Transaction as Transaction2, coinWithBalance } from "@mysten/sui/transactions";
2488
- import { fromBase64 as fromBase643, normalizeStructTag as normalizeStructTag4, normalizeSuiAddress as normalizeSuiAddress3, toBase64 } from "@mysten/sui/utils";
2649
+ import { fromBase64 as fromBase643, normalizeStructTag as normalizeStructTag6, normalizeSuiAddress as normalizeSuiAddress3, toBase64 } from "@mysten/sui/utils";
2489
2650
 
2490
2651
  // ../core/dist/chain/address.js
2491
2652
  function hexOf(address) {
@@ -2529,7 +2690,7 @@ function objectTypeFromGetObject(object) {
2529
2690
 
2530
2691
  // ../core/dist/policy/target.js
2531
2692
  import { createHash } from "crypto";
2532
- import { normalizeStructTag as normalizeStructTag3 } from "@mysten/sui/utils";
2693
+ import { normalizeStructTag as normalizeStructTag5 } from "@mysten/sui/utils";
2533
2694
 
2534
2695
  // ../core/dist/service-state/index.js
2535
2696
  var STATE_DIMENSIONS = Object.freeze([
@@ -2923,7 +3084,7 @@ var MODULE = "spend_account";
2923
3084
  var SUI_COIN_TYPE = "0x2::sui::SUI";
2924
3085
  function isSuiCoinType(coinType) {
2925
3086
  try {
2926
- return normalizeStructTag4(coinType) === normalizeStructTag4(SUI_COIN_TYPE);
3087
+ return normalizeStructTag6(coinType) === normalizeStructTag6(SUI_COIN_TYPE);
2927
3088
  } catch {
2928
3089
  return /::sui::SUI$/i.test(coinType);
2929
3090
  }
@@ -3556,6 +3717,24 @@ function createSpendAccountChain(options) {
3556
3717
  return null;
3557
3718
  }
3558
3719
  },
3720
+ async readGrantLastChange(grantObjectId) {
3721
+ try {
3722
+ const { object } = await client.core.getObject({
3723
+ objectId: grantObjectId,
3724
+ include: { json: true, previousTransaction: true }
3725
+ });
3726
+ const json = object?.json;
3727
+ if (!json || typeof json.revoked !== "boolean")
3728
+ return null;
3729
+ const previous = object?.previousTransaction;
3730
+ return {
3731
+ revoked: json.revoked,
3732
+ previousTransaction: typeof previous === "string" && previous.trim() ? previous.trim() : null
3733
+ };
3734
+ } catch {
3735
+ return null;
3736
+ }
3737
+ },
3559
3738
  async readPolicyBudget({ poolObjectId, onChainPolicyId }) {
3560
3739
  try {
3561
3740
  const response = await client.core.getDynamicField({
@@ -3680,13 +3859,18 @@ var GUARDED_DELEGATE_ARG_LAYOUT = {
3680
3859
  recipient: null,
3681
3860
  amount: 6,
3682
3861
  paymentIdHash: 7,
3683
- expiresAtMs: 9
3862
+ expiresAtMs: 9,
3863
+ // After clock (10): chain id, refund config, decide window, refund window.
3864
+ decideWindowMs: 13,
3865
+ refundWindowMs: 14
3684
3866
  },
3685
3867
  settle_any_recipient_to_refund_vault: {
3686
3868
  recipient: 4,
3687
3869
  amount: 5,
3688
3870
  paymentIdHash: 6,
3689
- expiresAtMs: 9
3871
+ expiresAtMs: 9,
3872
+ decideWindowMs: 13,
3873
+ refundWindowMs: 14
3690
3874
  }
3691
3875
  };
3692
3876
  function pureBytesOf(data, arg) {
@@ -3766,11 +3950,48 @@ function recoverGuardedDelegateCalls(finalized) {
3766
3950
  paymentIdHash: readPureVectorU8Hex(data, args[layout.paymentIdHash]),
3767
3951
  amount: readPureU64(data, args[layout.amount]),
3768
3952
  recipient: layout.recipient === null ? null : readPureAddress(data, args[layout.recipient]),
3769
- expiresAtMs: readPureU64(data, args[layout.expiresAtMs])
3953
+ expiresAtMs: readPureU64(data, args[layout.expiresAtMs]),
3954
+ ..."decideWindowMs" in layout ? {
3955
+ decideWindowMs: readPureU64(data, args[layout.decideWindowMs]),
3956
+ refundWindowMs: readPureU64(data, args[layout.refundWindowMs])
3957
+ } : {}
3770
3958
  });
3771
3959
  }
3772
3960
  return calls;
3773
3961
  }
3962
+ var VAULT_SETTLEMENT_TS_TIMEOUT_MS = 1e4;
3963
+ function withTimeout(work, ms, label) {
3964
+ return new Promise((resolve, reject2) => {
3965
+ const timer = setTimeout(() => reject2(new Error(`${label} timed out after ${ms}ms`)), ms);
3966
+ Promise.resolve(work).then((value) => {
3967
+ clearTimeout(timer);
3968
+ resolve(value);
3969
+ }, (err) => {
3970
+ clearTimeout(timer);
3971
+ reject2(err);
3972
+ });
3973
+ });
3974
+ }
3975
+ async function readVaultSettlementMs(client, digest) {
3976
+ const ledger = client.ledgerService;
3977
+ if (!ledger?.getTransaction)
3978
+ return void 0;
3979
+ try {
3980
+ const call = await withTimeout(ledger.getTransaction({
3981
+ digest,
3982
+ readMask: { paths: ["timestamp"] }
3983
+ }), VAULT_SETTLEMENT_TS_TIMEOUT_MS, "vault settlement timestamp read");
3984
+ const ts = call.response.transaction?.timestamp;
3985
+ if (!ts || ts.seconds === void 0)
3986
+ return void 0;
3987
+ const seconds = Number(ts.seconds);
3988
+ if (!Number.isFinite(seconds))
3989
+ return void 0;
3990
+ return seconds * 1e3 + Math.floor((ts.nanos ?? 0) / 1e6);
3991
+ } catch {
3992
+ return void 0;
3993
+ }
3994
+ }
3774
3995
  function createSpendAccountSettledTxReader(options) {
3775
3996
  const network = toGrpcNetwork(options.network);
3776
3997
  const client = options.client ?? createFailoverGrpcClient({
@@ -3825,6 +4046,7 @@ function createSpendAccountSettledTxReader(options) {
3825
4046
  kind: e.eventType.split("::").pop() ?? e.eventType
3826
4047
  }));
3827
4048
  const guardedDelegateCalls = recoverGuardedDelegateCalls(finalized);
4049
+ const timestampMs = events.some((event) => event.kind === "VaultOpened") ? await readVaultSettlementMs(client, digest) : void 0;
3828
4050
  return {
3829
4051
  status: "success",
3830
4052
  txDigest: digest,
@@ -3832,7 +4054,8 @@ function createSpendAccountSettledTxReader(options) {
3832
4054
  moveCalls,
3833
4055
  objectIds,
3834
4056
  events,
3835
- guardedDelegateCalls
4057
+ guardedDelegateCalls,
4058
+ ...timestampMs !== void 0 ? { timestampMs } : {}
3836
4059
  };
3837
4060
  }
3838
4061
  };
@@ -4225,7 +4448,7 @@ var sha256 = /* @__PURE__ */ createHasher(
4225
4448
  );
4226
4449
 
4227
4450
  // ../sdk/dist/protocol/offer-exclusion.js
4228
- import { normalizeStructTag as normalizeStructTag5, normalizeSuiAddress as normalizeSuiAddress4 } from "@mysten/sui/utils";
4451
+ import { normalizeStructTag as normalizeStructTag7, normalizeSuiAddress as normalizeSuiAddress4 } from "@mysten/sui/utils";
4229
4452
 
4230
4453
  // ../sdk/dist/protocol/terms.js
4231
4454
  function paymentIdHash(challengeId) {
@@ -4300,7 +4523,7 @@ function addr32(address) {
4300
4523
  return hexToBytes(normalized.slice(2));
4301
4524
  }
4302
4525
  function canonicalCoinTypeBytes(coinType) {
4303
- const normalized = normalizeStructTag5(coinType.trim());
4526
+ const normalized = normalizeStructTag7(coinType.trim());
4304
4527
  const canonical = normalized.replace(/0x([0-9a-f]{64})/g, "$1");
4305
4528
  if (!/^[0-9a-f]{64}::/.test(canonical)) {
4306
4529
  throw new Error(`coin type must resolve to a numeric package address: ${coinType}`);
@@ -4500,7 +4723,7 @@ function createGrpcExclusionRegistryReader(client) {
4500
4723
  // ../sdk/dist/delegated-signer/payer.js
4501
4724
  import { bcs as bcs7 } from "@mysten/sui/bcs";
4502
4725
  import { Transaction as Transaction4 } from "@mysten/sui/transactions";
4503
- import { fromBase64 as fromBase647, normalizeStructTag as normalizeStructTag8, normalizeSuiAddress as normalizeSuiAddress9, toBase64 as toBase645 } from "@mysten/sui/utils";
4726
+ import { fromBase64 as fromBase647, normalizeStructTag as normalizeStructTag10, normalizeSuiAddress as normalizeSuiAddress9, toBase64 as toBase645 } from "@mysten/sui/utils";
4504
4727
  import { Ed25519Keypair } from "@mysten/sui/keypairs/ed25519";
4505
4728
 
4506
4729
  // ../sdk/dist/delegated-signer/finality-poll.js
@@ -4526,7 +4749,7 @@ async function pollFinality(input) {
4526
4749
  }
4527
4750
 
4528
4751
  // ../sdk/dist/pay-operation/operation.js
4529
- import { normalizeStructTag as normalizeStructTag7, normalizeSuiAddress as normalizeSuiAddress6 } from "@mysten/sui/utils";
4752
+ import { normalizeStructTag as normalizeStructTag9, normalizeSuiAddress as normalizeSuiAddress6 } from "@mysten/sui/utils";
4530
4753
 
4531
4754
  // ../core/dist/policy/grant-target.js
4532
4755
  function normalizeHash(hex) {
@@ -4614,12 +4837,6 @@ import { fromBase64 as fromBase645, toBase64 as toBase643 } from "@mysten/sui/ut
4614
4837
 
4615
4838
  // ../sdk/dist/protocol/auth-params.js
4616
4839
  var TOKEN = /^[A-Za-z0-9!#$%&'*+\-.^_`|~]+$/;
4617
- function formatAuthParams(params) {
4618
- return Object.entries(params).map(([k, v]) => `${k}=${TOKEN.test(v) ? v : quote(v)}`).join(", ");
4619
- }
4620
- function quote(value) {
4621
- return `"${value.replace(/\\/g, "\\\\").replace(/"/g, '\\"')}"`;
4622
- }
4623
4840
  function parseAuthHeader(header) {
4624
4841
  const trimmed = header.trim();
4625
4842
  const firstSpace = trimmed.indexOf(" ");
@@ -4698,6 +4915,19 @@ function bytesToBase64Url(bytes) {
4698
4915
  const base64 = typeof globalThis.btoa === "function" ? globalThis.btoa(binary) : Buffer.from(bytes).toString("base64");
4699
4916
  return base64.replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/g, "");
4700
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
+ }
4701
4931
 
4702
4932
  // ../sdk/dist/protocol/challenge.js
4703
4933
  import { Ed25519PublicKey } from "@mysten/sui/keypairs/ed25519";
@@ -5042,9 +5272,220 @@ function offerToBase64Url(offer) {
5042
5272
  }
5043
5273
  var MPP_SCHEME = "Payment";
5044
5274
  var MPP_METHOD = "sui.charge";
5275
+ var MPP_SUI_METHOD = "sui";
5276
+ var MPP_CHARGE_INTENT = "charge";
5277
+ var MPP_RECEIPT_STATUS = "success";
5278
+ var LEGACY_RECEIPT_STATUS = "settled";
5045
5279
  var MPP_CHALLENGE_HEADER = "WWW-Authenticate";
5046
5280
  var MPP_CREDENTIAL_HEADER = "Authorization";
5047
5281
  var MPP_RECEIPT_HEADER = "Payment-Receipt";
5282
+ var HEADER_TEXT_REPLACEMENTS = {
5283
+ "\u2264": "<=",
5284
+ // ≤ less-than-or-equal
5285
+ "\u2265": ">=",
5286
+ // ≥ greater-than-or-equal
5287
+ "\u2014": "-",
5288
+ // — em dash
5289
+ "\u2013": "-",
5290
+ // – en dash
5291
+ "\u2018": "'",
5292
+ // ' left single quote
5293
+ "\u2019": "'",
5294
+ // ' right single quote
5295
+ "\u201C": '"',
5296
+ // " left double quote
5297
+ "\u201D": '"'
5298
+ // " right double quote
5299
+ };
5300
+ function latin1HeaderText(value) {
5301
+ let out = "";
5302
+ for (const ch of value) {
5303
+ const mapped = HEADER_TEXT_REPLACEMENTS[ch];
5304
+ if (mapped !== void 0)
5305
+ out += mapped;
5306
+ else if (ch.codePointAt(0) > 255)
5307
+ out += "?";
5308
+ else
5309
+ out += ch;
5310
+ }
5311
+ return out;
5312
+ }
5313
+ var DAY_MS = 864e5;
5314
+ function billingPeriod(periodMs) {
5315
+ if (!Number.isInteger(periodMs) || periodMs < DAY_MS || periodMs % DAY_MS !== 0)
5316
+ return null;
5317
+ const days = periodMs / DAY_MS;
5318
+ if (days % 7 === 0)
5319
+ return { periodCount: String(days / 7), periodUnit: "week" };
5320
+ return { periodCount: String(days), periodUnit: "day" };
5321
+ }
5322
+ function billingPeriodMs(unit, count) {
5323
+ if (!Number.isInteger(count) || count <= 0)
5324
+ return null;
5325
+ if (unit === "day")
5326
+ return count * DAY_MS;
5327
+ if (unit === "week")
5328
+ return count * 7 * DAY_MS;
5329
+ return null;
5330
+ }
5331
+ function expiresWire(offer) {
5332
+ if (typeof offer.expiresAt !== "number" || !Number.isFinite(offer.expiresAt))
5333
+ return void 0;
5334
+ return new Date(offer.expiresAt).toISOString();
5335
+ }
5336
+ function flatParams(offer) {
5337
+ const params = {
5338
+ amount: offer.amount,
5339
+ asset: offer.asset,
5340
+ network: offer.network,
5341
+ recipient: offer.payTo,
5342
+ package: offer.packageId,
5343
+ resource: offer.resource,
5344
+ digest: offer.digest
5345
+ };
5346
+ if (typeof offer.decimals === "number")
5347
+ params.decimals = String(offer.decimals);
5348
+ if (typeof offer.description === "string") {
5349
+ params.description = latin1HeaderText(offer.description);
5350
+ }
5351
+ if (typeof offer.issuedAt === "number" && Number.isFinite(offer.issuedAt)) {
5352
+ params.issued = new Date(offer.issuedAt).toISOString();
5353
+ }
5354
+ if (typeof offer.expiresAt === "number" && Number.isFinite(offer.expiresAt)) {
5355
+ params.expires = new Date(offer.expiresAt).toISOString();
5356
+ }
5357
+ if (offer.netAmount !== void 0)
5358
+ params.net_amount = offer.netAmount;
5359
+ if (offer.platformFee !== void 0)
5360
+ params.platform_fee = offer.platformFee;
5361
+ if (offer.digestVersion !== void 0)
5362
+ params.digest_version = String(offer.digestVersion);
5363
+ if (offer.settlementRail !== void 0)
5364
+ params.settlement_rail = offer.settlementRail;
5365
+ if (offer.serviceId !== void 0)
5366
+ params.service_id = offer.serviceId;
5367
+ if (offer.serviceRevision !== void 0) {
5368
+ params.service_revision = String(offer.serviceRevision);
5369
+ }
5370
+ if (offer.targetHash !== void 0)
5371
+ params.target_hash = offer.targetHash;
5372
+ if (offer.authorizationEpoch !== void 0) {
5373
+ params.authorization_epoch = String(offer.authorizationEpoch);
5374
+ }
5375
+ if (offer.method !== void 0)
5376
+ params.http_method = offer.method;
5377
+ if (offer.path !== void 0)
5378
+ params.http_path = offer.path;
5379
+ if (offer.bodyHash !== void 0)
5380
+ params.body_hash = offer.bodyHash;
5381
+ if (offer.contentType !== void 0)
5382
+ params.content_type = offer.contentType;
5383
+ if (offer.intent !== void 0)
5384
+ params.intent = offer.intent;
5385
+ if (offer.periodMs !== void 0)
5386
+ params.period_ms = String(offer.periodMs);
5387
+ if (offer.periodCount !== void 0)
5388
+ params.period_count = String(offer.periodCount);
5389
+ if (offer.refundable !== void 0)
5390
+ params.refundable = offer.refundable ? "true" : "false";
5391
+ if (offer.refundWindowMs !== void 0) {
5392
+ params.refund_window_ms = String(offer.refundWindowMs);
5393
+ }
5394
+ if (offer.decideWindowMs !== void 0) {
5395
+ params.decide_window_ms = String(offer.decideWindowMs);
5396
+ }
5397
+ if (offer.chainId !== void 0)
5398
+ params.chain_id = String(offer.chainId);
5399
+ if (offer.paymentSalt !== void 0)
5400
+ params.payment_salt = offer.paymentSalt;
5401
+ if (offer.refundConfigId !== void 0)
5402
+ params.refund_config_id = offer.refundConfigId;
5403
+ if (offer.refundTo !== void 0)
5404
+ params.refund_to = offer.refundTo;
5405
+ if (offer.sponsorGasOwner !== void 0) {
5406
+ params.sponsor_gas_owner = offer.sponsorGasOwner;
5407
+ }
5408
+ if (offer.sponsorGasBudget !== void 0) {
5409
+ params.sponsor_gas_budget = offer.sponsorGasBudget;
5410
+ }
5411
+ if (offer.sponsorGasPrice !== void 0) {
5412
+ params.sponsor_gas_price = offer.sponsorGasPrice;
5413
+ }
5414
+ if (offer.sponsorGasPayment !== void 0) {
5415
+ params.sponsor_gas_payment = offer.sponsorGasPayment;
5416
+ }
5417
+ if (offer.acceptedRails !== void 0) {
5418
+ params.accepted_rails = offer.acceptedRails.join(",");
5419
+ }
5420
+ if (offer.exclusionProtocolVersion !== void 0) {
5421
+ params.exclusion_protocol_version = String(offer.exclusionProtocolVersion);
5422
+ }
5423
+ if (offer.registryIdentity !== void 0) {
5424
+ params.registry_identity = offer.registryIdentity;
5425
+ }
5426
+ if (offer.sig !== void 0)
5427
+ params.sig = offer.sig;
5428
+ if (offer.sigKid !== void 0)
5429
+ params.sig_kid = offer.sigKid;
5430
+ return params;
5431
+ }
5432
+ function legacyRequestBlob(offer, copies = false) {
5433
+ const params = flatParams(offer);
5434
+ if (copies) {
5435
+ params.method = MPP_SUI_METHOD;
5436
+ params.realm = "suipay";
5437
+ params.challenge = offer.challengeId;
5438
+ if (typeof offer.mimeType === "string")
5439
+ params.type = offer.mimeType;
5440
+ }
5441
+ return bytesToBase64Url(new TextEncoder().encode(canonicalJson(params)));
5442
+ }
5443
+ function requestBlob(offer) {
5444
+ const flat = flatParams(offer);
5445
+ const details = { ...flat };
5446
+ delete details.amount;
5447
+ delete details.asset;
5448
+ delete details.recipient;
5449
+ delete details.description;
5450
+ delete details.expires;
5451
+ const body = {
5452
+ amount: flat.amount,
5453
+ currency: flat.asset,
5454
+ methodDetails: details
5455
+ };
5456
+ if (flat.recipient !== void 0)
5457
+ body.recipient = flat.recipient;
5458
+ if (flat.description !== void 0)
5459
+ body.description = flat.description;
5460
+ if (wireIntent(offer) === "subscription") {
5461
+ delete details.period_ms;
5462
+ const periodMs = offer.periodMs;
5463
+ const billing = typeof periodMs === "number" ? billingPeriod(periodMs) : null;
5464
+ if (!billing) {
5465
+ throw new Error("subscription periodMs is not an exact number of days");
5466
+ }
5467
+ body.periodCount = billing.periodCount;
5468
+ body.periodUnit = billing.periodUnit;
5469
+ const periodCount = offer.periodCount;
5470
+ const issuedAt = offer.issuedAt;
5471
+ if (typeof periodMs === "number" && typeof periodCount === "number" && typeof issuedAt === "number" && Number.isSafeInteger(periodMs) && Number.isSafeInteger(periodCount) && Number.isSafeInteger(issuedAt) && Number.isSafeInteger(periodMs * periodCount)) {
5472
+ const end = issuedAt + periodMs * periodCount;
5473
+ if (Number.isSafeInteger(end))
5474
+ body.subscriptionExpires = new Date(end).toISOString();
5475
+ }
5476
+ }
5477
+ return bytesToBase64Url(new TextEncoder().encode(canonicalJsonValue(body)));
5478
+ }
5479
+ function issuedRequestBlob(offer) {
5480
+ return requestBlob(offer);
5481
+ }
5482
+ function echoedRequestBlob(offer) {
5483
+ try {
5484
+ return issuedRequestBlob(offer);
5485
+ } catch {
5486
+ return legacyRequestBlob(offer);
5487
+ }
5488
+ }
5048
5489
  function splitChallenges(header) {
5049
5490
  const scheme = `${MPP_SCHEME} `;
5050
5491
  const value = header.trim();
@@ -5104,11 +5545,120 @@ function decodeChallenge(header, opts) {
5104
5545
  }
5105
5546
  return null;
5106
5547
  }
5548
+ function canonicalJson(fields) {
5549
+ const keys = Object.keys(fields).sort();
5550
+ return `{${keys.map((key) => `${JSON.stringify(key)}:${JSON.stringify(fields[key])}`).join(",")}}`;
5551
+ }
5552
+ function canonicalJsonValue(value) {
5553
+ if (value === null || typeof value !== "object")
5554
+ return JSON.stringify(value);
5555
+ if (Array.isArray(value))
5556
+ return `[${value.map(canonicalJsonValue).join(",")}]`;
5557
+ const fields = value;
5558
+ const keys = Object.keys(fields).sort();
5559
+ return `{${keys.map((key) => `${JSON.stringify(key)}:${canonicalJsonValue(fields[key])}`).join(",")}}`;
5560
+ }
5561
+ function wireIntent(offer) {
5562
+ return offer.intent === "subscription" ? "subscription" : MPP_CHARGE_INTENT;
5563
+ }
5564
+ var REQUEST_TOP_LEVEL = /* @__PURE__ */ new Set([
5565
+ "amount",
5566
+ "asset",
5567
+ "currency",
5568
+ "description",
5569
+ "externalId",
5570
+ "recipient",
5571
+ "subscriptionExpires"
5572
+ ]);
5573
+ function takeStrings(source, into) {
5574
+ for (const [key, value] of Object.entries(source)) {
5575
+ if (typeof value !== "string")
5576
+ return false;
5577
+ into[key] = value;
5578
+ }
5579
+ return true;
5580
+ }
5581
+ function officialParams(params) {
5582
+ if (params.method !== MPP_SUI_METHOD || !params.request)
5583
+ return null;
5584
+ if (params.intent !== MPP_CHARGE_INTENT && params.intent !== "subscription")
5585
+ return null;
5586
+ let body;
5587
+ try {
5588
+ body = JSON.parse(new TextDecoder().decode(bytesFromBase64Url(params.request)));
5589
+ } catch {
5590
+ return null;
5591
+ }
5592
+ if (!body || typeof body !== "object" || Array.isArray(body))
5593
+ return null;
5594
+ const record = body;
5595
+ const fields = {};
5596
+ const details = record.methodDetails;
5597
+ if (details !== void 0) {
5598
+ if (!details || typeof details !== "object" || Array.isArray(details))
5599
+ return null;
5600
+ if (!takeStrings(details, fields))
5601
+ return null;
5602
+ for (const [key, value] of Object.entries(record)) {
5603
+ if (key === "methodDetails" || key === "periodCount" || key === "periodUnit")
5604
+ continue;
5605
+ if (typeof value !== "string" || !REQUEST_TOP_LEVEL.has(key))
5606
+ return null;
5607
+ if (fields[key] !== void 0 && fields[key] !== value)
5608
+ return null;
5609
+ fields[key] = value;
5610
+ }
5611
+ const periodCount = record.periodCount;
5612
+ const periodUnit = record.periodUnit;
5613
+ if (periodCount !== void 0 || periodUnit !== void 0) {
5614
+ if (typeof periodCount !== "string" || typeof periodUnit !== "string")
5615
+ return null;
5616
+ if (!/^[1-9]\d*$/.test(periodCount))
5617
+ return null;
5618
+ const ms = billingPeriodMs(periodUnit, Number(periodCount));
5619
+ if (ms === null)
5620
+ return null;
5621
+ if (fields.period_ms !== void 0 && fields.period_ms !== String(ms))
5622
+ return null;
5623
+ fields.period_ms = String(ms);
5624
+ }
5625
+ if (params.intent === "subscription" && fields.period_ms === void 0)
5626
+ return null;
5627
+ } else if (!takeStrings(record, fields)) {
5628
+ return null;
5629
+ }
5630
+ if (fields.currency !== void 0) {
5631
+ if (fields.asset !== void 0 && fields.asset !== fields.currency)
5632
+ return null;
5633
+ fields.asset = fields.currency;
5634
+ }
5635
+ if (params.expires !== void 0) {
5636
+ if (fields.expires !== void 0 && fields.expires !== params.expires)
5637
+ return null;
5638
+ if (fields.expires === void 0)
5639
+ fields.expires = params.expires;
5640
+ }
5641
+ if (!fields.challenge && params.id)
5642
+ fields.challenge = params.id;
5643
+ if (fields.method === void 0)
5644
+ fields.method = MPP_SUI_METHOD;
5645
+ if (fields.method !== MPP_METHOD && fields.method !== MPP_SUI_METHOD)
5646
+ return null;
5647
+ if (fields.intent !== void 0 && fields.intent !== params.intent)
5648
+ return null;
5649
+ if (fields.intent === void 0 && params.intent === "subscription")
5650
+ return null;
5651
+ fields.method = MPP_METHOD;
5652
+ return fields;
5653
+ }
5107
5654
  function decodeSingleChallenge(header) {
5108
5655
  const parsed = parseAuthHeader(header);
5109
5656
  if (!parsed || parsed.scheme !== MPP_SCHEME)
5110
5657
  return null;
5111
- const p = parsed.params;
5658
+ const pinned = officialParams(parsed.params);
5659
+ const p = { ...pinned ?? parsed.params };
5660
+ if (p.method === MPP_SUI_METHOD)
5661
+ p.method = MPP_METHOD;
5112
5662
  if (p.method !== MPP_METHOD)
5113
5663
  return null;
5114
5664
  const required = [
@@ -5193,13 +5743,15 @@ function decodeSingleChallenge(header) {
5193
5743
  offer.intent = p.intent;
5194
5744
  if (p.period_ms !== void 0) {
5195
5745
  const ms = Number(p.period_ms);
5196
- if (Number.isFinite(ms))
5197
- offer.periodMs = ms;
5746
+ if (!Number.isSafeInteger(ms) || ms <= 0)
5747
+ return null;
5748
+ offer.periodMs = ms;
5198
5749
  }
5199
5750
  if (p.period_count !== void 0) {
5200
5751
  const count = Number(p.period_count);
5201
- if (Number.isFinite(count))
5202
- offer.periodCount = count;
5752
+ if (!Number.isSafeInteger(count) || count <= 0)
5753
+ return null;
5754
+ offer.periodCount = count;
5203
5755
  }
5204
5756
  if (p.refundable === "true")
5205
5757
  offer.refundable = true;
@@ -5259,25 +5811,46 @@ function decodeSingleChallenge(header) {
5259
5811
  offer.sigKid = p.sig_kid;
5260
5812
  return offer;
5261
5813
  }
5814
+ function echoedChallenge(offer, challengeId) {
5815
+ const challenge = {
5816
+ id: challengeId,
5817
+ realm: "suipay",
5818
+ method: MPP_SUI_METHOD,
5819
+ intent: wireIntent(offer),
5820
+ // Section 5.2 echoes the original challenge, including its request.
5821
+ request: echoedRequestBlob(offer)
5822
+ };
5823
+ const expires = expiresWire(offer);
5824
+ if (expires !== void 0)
5825
+ challenge.expires = expires;
5826
+ return challenge;
5827
+ }
5828
+ function encodeOfficialMessage(body) {
5829
+ return `${MPP_SCHEME} ${bytesToBase64Url(new TextEncoder().encode(canonicalJsonValue(body)))}`;
5830
+ }
5262
5831
  function encodeProof(proof) {
5263
- return `${MPP_SCHEME} ${formatAuthParams({
5264
- method: MPP_METHOD,
5265
- challenge: proof.challengeId,
5266
- payer: proof.payer,
5267
- offer: offerToBase64Url(proof.offer),
5268
- digest: proof.txDigest
5269
- })}`;
5832
+ return encodeOfficialMessage({
5833
+ challenge: echoedChallenge(proof.offer, proof.challengeId),
5834
+ payload: {
5835
+ payer: proof.payer,
5836
+ offer: offerToBase64Url(proof.offer),
5837
+ digest: proof.txDigest
5838
+ }
5839
+ });
5270
5840
  }
5271
- function decodeReceipt(header) {
5272
- const parsed = parseAuthHeader(`X ${header}`);
5273
- if (!parsed)
5841
+ function receiptFromParams(p) {
5842
+ if (p.method !== MPP_METHOD && p.method !== MPP_SUI_METHOD)
5843
+ return null;
5844
+ if (p.status !== MPP_RECEIPT_STATUS && p.status !== LEGACY_RECEIPT_STATUS)
5274
5845
  return null;
5275
- const p = parsed.params;
5276
- if (!p.challenge || !p.tx_digest || !p.payer || !p.amount || !p.asset || !p.network)
5846
+ if (p.tx_digest && p.reference && p.tx_digest !== p.reference)
5847
+ return null;
5848
+ const txDigest = p.tx_digest || p.reference;
5849
+ if (!p.challenge || !txDigest || !p.payer || !p.amount || !p.asset || !p.network)
5277
5850
  return null;
5278
5851
  const receipt = {
5279
5852
  challengeId: p.challenge,
5280
- txDigest: p.tx_digest,
5853
+ txDigest,
5281
5854
  network: p.network,
5282
5855
  payer: p.payer,
5283
5856
  amount: p.amount,
@@ -5298,6 +5871,34 @@ function decodeReceipt(header) {
5298
5871
  receipt.periodIndex = p.period_index;
5299
5872
  return receipt;
5300
5873
  }
5874
+ function decodeOfficialReceipt(header) {
5875
+ const token = header.trim();
5876
+ if (!/^[A-Za-z0-9_-]+$/.test(token))
5877
+ return null;
5878
+ let body;
5879
+ try {
5880
+ body = JSON.parse(new TextDecoder().decode(bytesFromBase64Url(token)));
5881
+ } catch {
5882
+ return null;
5883
+ }
5884
+ if (!body || typeof body !== "object" || Array.isArray(body))
5885
+ return null;
5886
+ const fields = {};
5887
+ for (const [key, value] of Object.entries(body)) {
5888
+ if (typeof value !== "string")
5889
+ return null;
5890
+ fields[key] = value;
5891
+ }
5892
+ return receiptFromParams(fields);
5893
+ }
5894
+ function decodeReceipt(header) {
5895
+ if (/^[A-Za-z0-9_-]+$/.test(header.trim()))
5896
+ return decodeOfficialReceipt(header);
5897
+ const parsed = parseAuthHeader(`X ${header}`);
5898
+ if (!parsed)
5899
+ return null;
5900
+ return receiptFromParams(parsed.params);
5901
+ }
5301
5902
 
5302
5903
  // ../sdk/dist/protocol/x402.js
5303
5904
  import { fromBase64 as fromBase644, toBase64 as toBase642 } from "@mysten/sui/utils";
@@ -5755,7 +6356,7 @@ import { fromHex } from "@mysten/sui/utils";
5755
6356
 
5756
6357
  // ../sdk/dist/protocol/coin-type-hash.js
5757
6358
  import { createHash as createHash2 } from "crypto";
5758
- import { normalizeStructTag as normalizeStructTag6 } from "@mysten/sui/utils";
6359
+ import { normalizeStructTag as normalizeStructTag8 } from "@mysten/sui/utils";
5759
6360
 
5760
6361
  // ../sdk/dist/protocol/refund-vault.js
5761
6362
  function isRefundableOffer(offer) {
@@ -6420,8 +7021,8 @@ function resolveAuthority(authority, offer) {
6420
7021
  };
6421
7022
  }
6422
7023
  function validateAmount(offer, resolved) {
6423
- const offerCoinType = normalizeStructTag7(offer.asset);
6424
- const grantCoinType = normalizeStructTag7(resolved.coinType);
7024
+ const offerCoinType = normalizeStructTag9(offer.asset);
7025
+ const grantCoinType = normalizeStructTag9(resolved.coinType);
6425
7026
  if (offerCoinType !== grantCoinType) {
6426
7027
  return {
6427
7028
  code: PAY_OPERATION_ERROR_CODES.COIN_TYPE_MISMATCH,
@@ -7492,7 +8093,7 @@ function atomicAmount(value) {
7492
8093
  }
7493
8094
  function sameStructTag(a, b) {
7494
8095
  try {
7495
- return normalizeStructTag8(a) === normalizeStructTag8(b);
8096
+ return normalizeStructTag10(a) === normalizeStructTag10(b);
7496
8097
  } catch {
7497
8098
  return false;
7498
8099
  }
@@ -8250,7 +8851,7 @@ async function payDelegatedSpendAccount(args) {
8250
8851
  refuseOffer("POLICY_NO_TARGET");
8251
8852
  }
8252
8853
  try {
8253
- normalizeStructTag8(offer2.asset);
8854
+ normalizeStructTag10(offer2.asset);
8254
8855
  } catch {
8255
8856
  refuseOffer("POLICY_BAD_ASSET");
8256
8857
  }
@@ -8314,7 +8915,7 @@ async function payDelegatedSpendAccount(args) {
8314
8915
  return buildSpendAccountPayKind(kindInput);
8315
8916
  };
8316
8917
  try {
8317
- normalizeStructTag8(snapshot.coinType);
8918
+ normalizeStructTag10(snapshot.coinType);
8318
8919
  } catch {
8319
8920
  return failed("POLICY_REJECTED", PUBLIC_DETAIL.POLICY_REJECTED);
8320
8921
  }
@@ -9913,7 +10514,9 @@ async function resolvePayerSession(options) {
9913
10514
  ok: false,
9914
10515
  // The gateway's stable code, never a raw body — the read client already
9915
10516
  // sanitized it, and an operator needs to tell 429 from 401.
9916
- error: manifestError(MANIFEST_ERROR_CODES.MALFORMED_MANIFEST, `bootstrap was refused (${bootstrap.error}${bootstrap.code ? `: ${bootstrap.code}` : ""})`)
10517
+ // A 429 is the gateway's rate limit, not a manifest the agent can fix, so
10518
+ // it keeps the retryable code instead of the manifest default.
10519
+ error: manifestError(MANIFEST_ERROR_CODES.MALFORMED_MANIFEST, `bootstrap was refused (${bootstrap.error}${bootstrap.code ? `: ${bootstrap.code}` : ""})`, bootstrap.status === 429 ? "limit.rate_limited" : void 0)
9917
10520
  };
9918
10521
  }
9919
10522
  const whole = manifestToSession({
@@ -10171,8 +10774,44 @@ async function createPayer(options) {
10171
10774
  value: { address, deployment, grant: binding, session, pay, verifySettlement }
10172
10775
  };
10173
10776
  }
10777
+
10778
+ // ../sdk/dist/oauth/delegate-proof.js
10779
+ import { normalizeSuiAddress as normalizeSuiAddress12 } from "@mysten/sui/utils";
10780
+ import { verifyPersonalMessageSignature as verifyPersonalMessageSignature3 } from "@mysten/sui/verify";
10781
+ var OAUTH_DELEGATE_PROOF_TTL_MS = 15 * 6e4;
10782
+ function encodeOAuthDelegateProof(binding, expiresAtMs, ownerAddress) {
10783
+ if (!binding.delegateAddress || !Number.isSafeInteger(expiresAtMs) || expiresAtMs <= 0) {
10784
+ throw new Error("Invalid delegate proof binding.");
10785
+ }
10786
+ return new TextEncoder().encode(JSON.stringify([
10787
+ "suipay:oauth-delegate:v1",
10788
+ binding.clientId,
10789
+ binding.redirectUri,
10790
+ binding.resource,
10791
+ binding.scope,
10792
+ binding.codeChallenge,
10793
+ normalizeSuiAddress12(binding.delegateAddress),
10794
+ normalizeSuiAddress12(ownerAddress),
10795
+ expiresAtMs
10796
+ ]));
10797
+ }
10798
+ async function verifyOAuthDelegateProof(binding, proof, nowMs = Date.now(), expectedOwner) {
10799
+ try {
10800
+ const p = proof;
10801
+ const message = encodeOAuthDelegateProof(binding, p.expiresAtMs, p.ownerAddress);
10802
+ if (typeof p.signature !== "string" || p.signature.length > 8192 || p.expiresAtMs <= nowMs || p.expiresAtMs > nowMs + OAUTH_DELEGATE_PROOF_TTL_MS)
10803
+ return false;
10804
+ if (expectedOwner && normalizeSuiAddress12(p.ownerAddress) !== normalizeSuiAddress12(expectedOwner))
10805
+ return false;
10806
+ const publicKey = await verifyPersonalMessageSignature3(message, p.signature);
10807
+ return publicKey.toSuiAddress() === normalizeSuiAddress12(binding.delegateAddress);
10808
+ } catch {
10809
+ return false;
10810
+ }
10811
+ }
10174
10812
  export {
10175
10813
  NativeTransferError,
10814
+ OAUTH_DELEGATE_PROOF_TTL_MS,
10176
10815
  SuiPayError,
10177
10816
  buildMcpPaymentPayload,
10178
10817
  buildNativeTransferBytes,
@@ -10183,10 +10822,12 @@ export {
10183
10822
  createPayer,
10184
10823
  createReader,
10185
10824
  dashboardManifestToAgentManifest,
10825
+ encodeOAuthDelegateProof,
10186
10826
  inspectNativeTransfer,
10187
10827
  manifestToSession,
10188
10828
  parseAgentManifest,
10189
10829
  personalMessageSigner,
10190
10830
  toErrorFields,
10831
+ verifyOAuthDelegateProof,
10191
10832
  verifyPreparedPayment
10192
10833
  };