@mysten-incubation/suipay-buyer 0.3.0-dev.2 → 0.3.0-dev.20

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-XHHXRSY3.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;
@@ -514,13 +576,16 @@ function verifyOwnerTransaction(input) {
514
576
  if (k === "TransferObjects" || k === "Publish" || k === "Upgrade") {
515
577
  throw new TransactionVerificationError("unsupportedOperation");
516
578
  }
517
- if (k === "MakeMoveVec" && input.operation.kind !== "create_policy" && input.operation.kind !== "replace_grant") {
579
+ if (k === "MakeMoveVec" && input.operation.kind !== "create_policy" && input.operation.kind !== "replace_grant" && input.operation.kind !== "create_grant_consent_batch") {
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;
@@ -958,87 +1025,253 @@ function verifyOwnerTransaction(input) {
958
1025
  allowedAssets.add(assetNorm);
959
1026
  const existing = assetGroups.get(assetNorm) ?? {
960
1027
  sumTotalCap: 0n,
961
- policyIds: []
1028
+ policyIds: [],
1029
+ policies: []
962
1030
  };
963
1031
  existing.sumTotalCap += capAmt;
964
1032
  existing.policyIds.push(p.id);
1033
+ existing.policies.push(p);
965
1034
  assetGroups.set(assetNorm, existing);
966
1035
  }
967
- const distinctAssetCount = assetGroups.size;
968
- const batchN = commands.length;
969
- if (batchN > distinctAssetCount) {
970
- throw new TransactionVerificationError("caps");
971
- }
972
- const seenCoins = /* @__PURE__ */ new Set();
973
- const seenPools = /* @__PURE__ */ new Set();
974
- for (let i = 0; i < batchN; i++) {
975
- const cmd = commands[i];
976
- if (cmd.$kind !== "MoveCall") {
977
- throw new TransactionVerificationError("unsupportedOperation");
978
- }
979
- const mc = cmd.MoveCall;
980
- if (mc.module !== "spend_account" || mc.function !== "create_policy_grant") {
981
- throw new TransactionVerificationError("target");
982
- }
983
- const mcTypes = mc.typeArguments;
984
- if (mcTypes.length !== 1) {
985
- throw new TransactionVerificationError("coinType");
986
- }
987
- const cmdCoinType = safeNormalizeStructTag(mcTypes[0]);
988
- if (!cmdCoinType || !allowedAssets.has(cmdCoinType)) {
989
- throw new TransactionVerificationError("coinType");
990
- }
991
- if (seenCoins.has(cmdCoinType)) {
992
- throw new TransactionVerificationError("coinType");
993
- }
994
- seenCoins.add(cmdCoinType);
995
- const groupInfo = assetGroups.get(cmdCoinType);
996
- const args = mc.arguments;
997
- if (args.length !== 6) {
998
- throw new TransactionVerificationError("target");
999
- }
1000
- const poolInputIdx = markInput(args[0]);
1001
- const poolId = getObjectIdFromInput(data.inputs[poolInputIdx]);
1002
- if (!poolId) {
1003
- throw new TransactionVerificationError("pool");
1004
- }
1005
- if (seenPools.has(poolId)) {
1006
- throw new TransactionVerificationError("pool");
1007
- }
1008
- seenPools.add(poolId);
1009
- const delInputIdx = markInput(args[1]);
1010
- const delBytes = getPureBytes(data.inputs[delInputIdx]);
1011
- if (!delBytes || parseAddress(delBytes) !== safeNormalizeAddress(op.delegate.address)) {
1012
- throw new TransactionVerificationError("delegate");
1013
- }
1014
- const capInputIdx = markInput(args[2]);
1015
- const capBytes = getPureBytes(data.inputs[capInputIdx]);
1016
- if (!capBytes) {
1017
- throw new TransactionVerificationError("caps");
1036
+ const isCombined = commands.length >= 5 && commands[0]?.$kind === "MoveCall" && commands[0].MoveCall?.module === "spend_account" && commands[0].MoveCall?.function === "new_policy_target";
1037
+ if (!isCombined) {
1038
+ const hasDraftPolicy = uniquePolicies.some((p) => p.status === "draft" || p.onChainPolicyId == null && p.targets && p.targets.length > 0);
1039
+ if (hasDraftPolicy) {
1040
+ throw new TransactionVerificationError("policyId");
1018
1041
  }
1019
- const txSessionCap = parseOptionU64(capBytes);
1020
- const maxInputIdx = markInput(args[3]);
1021
- const maxBytes = getPureBytes(data.inputs[maxInputIdx]);
1022
- if (!maxBytes) {
1042
+ const distinctAssetCount = assetGroups.size;
1043
+ const batchN = commands.length;
1044
+ if (batchN > distinctAssetCount) {
1023
1045
  throw new TransactionVerificationError("caps");
1024
1046
  }
1025
- const txMaxPerPayment = parseOptionU64(maxBytes);
1026
- if (txSessionCap === null || txMaxPerPayment !== txSessionCap) {
1027
- throw new TransactionVerificationError("caps");
1047
+ const seenCoins = /* @__PURE__ */ new Set();
1048
+ const seenPools = /* @__PURE__ */ new Set();
1049
+ for (let i = 0; i < batchN; i++) {
1050
+ const cmd = commands[i];
1051
+ if (cmd.$kind !== "MoveCall") {
1052
+ throw new TransactionVerificationError("unsupportedOperation");
1053
+ }
1054
+ const mc = cmd.MoveCall;
1055
+ if (mc.module !== "spend_account" || mc.function !== "create_policy_grant") {
1056
+ throw new TransactionVerificationError("target");
1057
+ }
1058
+ const mcTypes = mc.typeArguments;
1059
+ if (mcTypes.length !== 1) {
1060
+ throw new TransactionVerificationError("coinType");
1061
+ }
1062
+ const cmdCoinType2 = safeNormalizeStructTag(mcTypes[0]);
1063
+ if (!cmdCoinType2 || !allowedAssets.has(cmdCoinType2)) {
1064
+ throw new TransactionVerificationError("coinType");
1065
+ }
1066
+ if (seenCoins.has(cmdCoinType2)) {
1067
+ throw new TransactionVerificationError("coinType");
1068
+ }
1069
+ seenCoins.add(cmdCoinType2);
1070
+ const groupInfo2 = assetGroups.get(cmdCoinType2);
1071
+ const args = mc.arguments;
1072
+ if (args.length !== 6) {
1073
+ throw new TransactionVerificationError("target");
1074
+ }
1075
+ const poolInputIdx2 = markInput(args[0]);
1076
+ const poolId2 = getObjectIdFromInput(data.inputs[poolInputIdx2]);
1077
+ if (!poolId2) {
1078
+ throw new TransactionVerificationError("pool");
1079
+ }
1080
+ if (seenPools.has(poolId2)) {
1081
+ throw new TransactionVerificationError("pool");
1082
+ }
1083
+ seenPools.add(poolId2);
1084
+ const delInputIdx2 = markInput(args[1]);
1085
+ const delBytes2 = getPureBytes(data.inputs[delInputIdx2]);
1086
+ if (!delBytes2 || parseAddress(delBytes2) !== safeNormalizeAddress(op.delegate.address)) {
1087
+ throw new TransactionVerificationError("delegate");
1088
+ }
1089
+ const capInputIdx2 = markInput(args[2]);
1090
+ const capBytes2 = getPureBytes(data.inputs[capInputIdx2]);
1091
+ if (!capBytes2) {
1092
+ throw new TransactionVerificationError("caps");
1093
+ }
1094
+ const txSessionCap2 = parseOptionU64(capBytes2);
1095
+ const maxInputIdx2 = markInput(args[3]);
1096
+ const maxBytes2 = getPureBytes(data.inputs[maxInputIdx2]);
1097
+ if (!maxBytes2) {
1098
+ throw new TransactionVerificationError("caps");
1099
+ }
1100
+ const txMaxPerPayment2 = parseOptionU64(maxBytes2);
1101
+ if (txSessionCap2 === null || txMaxPerPayment2 !== txSessionCap2) {
1102
+ throw new TransactionVerificationError("caps");
1103
+ }
1104
+ if (txSessionCap2 > groupInfo2.sumTotalCap) {
1105
+ throw new TransactionVerificationError("caps");
1106
+ }
1107
+ assertPureU64(args[4], 0n, "expiry");
1108
+ const pIdsInputIdx = markInput(args[5]);
1109
+ const pIdsBytes = getPureBytes(data.inputs[pIdsInputIdx]);
1110
+ if (!pIdsBytes) {
1111
+ throw new TransactionVerificationError("policyId");
1112
+ }
1113
+ const parsedPids = bcs.vector(bcs.u64()).parse(pIdsBytes);
1114
+ const expectedOnChainIds = groupInfo2.policies.map((p) => p.onChainPolicyId != null ? String(p.onChainPolicyId) : null).filter((id) => id != null);
1115
+ if (expectedOnChainIds.length === 0 || expectedOnChainIds.length !== groupInfo2.policies.length || parsedPids.length !== expectedOnChainIds.length) {
1116
+ throw new TransactionVerificationError("policyId");
1117
+ }
1118
+ for (let idx = 0; idx < parsedPids.length; idx++) {
1119
+ if (String(parsedPids[idx]) !== expectedOnChainIds[idx]) {
1120
+ throw new TransactionVerificationError("policyId");
1121
+ }
1122
+ }
1028
1123
  }
1029
- if (txSessionCap > groupInfo.sumTotalCap) {
1030
- throw new TransactionVerificationError("caps");
1124
+ break;
1125
+ }
1126
+ if (uniquePolicies.length !== 1) {
1127
+ throw new TransactionVerificationError("targets");
1128
+ }
1129
+ const draftPolicy = uniquePolicies[0];
1130
+ let N = 0;
1131
+ while (N < commands.length && commands[N]?.$kind === "MoveCall" && commands[N].MoveCall?.module === "spend_account" && commands[N].MoveCall?.function === "new_policy_target") {
1132
+ N++;
1133
+ }
1134
+ if (!draftPolicy.targets || draftPolicy.targets.length !== N) {
1135
+ throw new TransactionVerificationError("targets");
1136
+ }
1137
+ if (commands.length !== N + 4) {
1138
+ throw new TransactionVerificationError("targets");
1139
+ }
1140
+ for (let i = 0; i < N; i++) {
1141
+ const c = commands[i];
1142
+ const mc = c.MoveCall;
1143
+ if (mc.arguments.length !== 3) {
1144
+ throw new TransactionVerificationError("target");
1031
1145
  }
1032
- assertPureU64(args[4], 0n, "expiry");
1033
- const pIdsInputIdx = markInput(args[5]);
1034
- const pIdsBytes = getPureBytes(data.inputs[pIdsInputIdx]);
1035
- if (!pIdsBytes) {
1036
- throw new TransactionVerificationError("policyId");
1146
+ const expectedTarget = draftPolicy.targets[i];
1147
+ const hashIdx = markInput(mc.arguments[0]);
1148
+ const hashBytes = getPureBytes(data.inputs[hashIdx]);
1149
+ const hash = hashBytes ? bcs.vector(bcs.u8()).parse(hashBytes) : null;
1150
+ const got = hash ? [...hash].map((byte) => byte.toString(16).padStart(2, "0")).join("") : "";
1151
+ const want = expectedTarget.targetHash.trim().toLowerCase().replace(/^0x/, "");
1152
+ if (!hash || got !== want)
1153
+ throw new TransactionVerificationError("target");
1154
+ const recipientIdx = markInput(mc.arguments[1]);
1155
+ const recipientBytes = getPureBytes(data.inputs[recipientIdx]);
1156
+ if (!recipientBytes || parseAddress(recipientBytes) !== safeNormalizeAddress(expectedTarget.recipient)) {
1157
+ throw new TransactionVerificationError("target");
1037
1158
  }
1038
- if (parseVectorU64Len(pIdsBytes) > groupInfo.policyIds.length) {
1039
- throw new TransactionVerificationError("policyId");
1159
+ assertPureU64(mc.arguments[2], BigInt(expectedTarget.maxPerPayment), "target");
1160
+ }
1161
+ const vecCmd = commands[N];
1162
+ if (vecCmd.$kind !== "MakeMoveVec") {
1163
+ throw new TransactionVerificationError("unsupportedOperation");
1164
+ }
1165
+ const targetElements = vecCmd.MakeMoveVec?.elements;
1166
+ if (!Array.isArray(targetElements) || targetElements.length !== N) {
1167
+ throw new TransactionVerificationError("targets");
1168
+ }
1169
+ for (let i = 0; i < N; i++) {
1170
+ const el = markResult(targetElements[i], "targets");
1171
+ if (el.cmdIndex !== i || el.resIndex !== 0) {
1172
+ throw new TransactionVerificationError("targets");
1040
1173
  }
1041
1174
  }
1175
+ const createPolicyCmd = commands[N + 1];
1176
+ if (createPolicyCmd.$kind !== "MoveCall" || createPolicyCmd.MoveCall?.module !== "spend_account" || createPolicyCmd.MoveCall?.function !== "create_spend_policy") {
1177
+ throw new TransactionVerificationError("target");
1178
+ }
1179
+ const policyTypes = createPolicyCmd.MoveCall.typeArguments;
1180
+ if (!policyTypes || policyTypes.length !== 1) {
1181
+ throw new TransactionVerificationError("coinType");
1182
+ }
1183
+ const cmdCoinType = safeNormalizeStructTag(policyTypes[0]);
1184
+ if (!cmdCoinType || !allowedAssets.has(cmdCoinType)) {
1185
+ throw new TransactionVerificationError("coinType");
1186
+ }
1187
+ const groupInfo = assetGroups.get(cmdCoinType);
1188
+ const policyArgs = createPolicyCmd.MoveCall.arguments;
1189
+ if (!policyArgs || policyArgs.length !== 5) {
1190
+ throw new TransactionVerificationError("target");
1191
+ }
1192
+ const poolInputIdx = markInput(policyArgs[0]);
1193
+ const poolId = getObjectIdFromInput(data.inputs[poolInputIdx]);
1194
+ if (!poolId) {
1195
+ throw new TransactionVerificationError("pool");
1196
+ }
1197
+ const targetsRes = markResult(policyArgs[1], "unsupportedOperation");
1198
+ if (targetsRes.cmdIndex !== N || targetsRes.resIndex !== 0) {
1199
+ throw new TransactionVerificationError("unsupportedOperation");
1200
+ }
1201
+ const totalCapInputIdx = markInput(policyArgs[2]);
1202
+ const totalCapBytes = getPureBytes(data.inputs[totalCapInputIdx]);
1203
+ if (!totalCapBytes)
1204
+ throw new TransactionVerificationError("caps");
1205
+ const policyTotalCap = parseU64(totalCapBytes);
1206
+ if (policyTotalCap <= 0n || policyTotalCap > groupInfo.sumTotalCap || policyTotalCap !== BigInt(draftPolicy.totalCap)) {
1207
+ throw new TransactionVerificationError("caps");
1208
+ }
1209
+ const maxPerPaymentInputIdx = markInput(policyArgs[3]);
1210
+ const maxPerPaymentBytes = getPureBytes(data.inputs[maxPerPaymentInputIdx]);
1211
+ if (!maxPerPaymentBytes)
1212
+ throw new TransactionVerificationError("caps");
1213
+ const policyMaxPerPayment = parseU64(maxPerPaymentBytes);
1214
+ if (policyMaxPerPayment <= 0n || policyMaxPerPayment > policyTotalCap || draftPolicy.maxPerPayment == null || policyMaxPerPayment !== BigInt(draftPolicy.maxPerPayment)) {
1215
+ throw new TransactionVerificationError("caps");
1216
+ }
1217
+ assertPureU64(policyArgs[4], callerExpiryU64(draftPolicy.expiresAtMs), "expiry");
1218
+ const idVecCmd = commands[N + 2];
1219
+ if (idVecCmd.$kind !== "MakeMoveVec" || !Array.isArray(idVecCmd.MakeMoveVec?.elements) || idVecCmd.MakeMoveVec.elements.length !== 1) {
1220
+ throw new TransactionVerificationError("policyId");
1221
+ }
1222
+ const policyRes = markResult(idVecCmd.MakeMoveVec.elements[0], "policyId");
1223
+ if (policyRes.cmdIndex !== N + 1 || policyRes.resIndex !== 0) {
1224
+ throw new TransactionVerificationError("policyId");
1225
+ }
1226
+ const grantCmd = commands[N + 3];
1227
+ if (grantCmd.$kind !== "MoveCall" || grantCmd.MoveCall?.module !== "spend_account" || grantCmd.MoveCall?.function !== "create_policy_grant") {
1228
+ throw new TransactionVerificationError("target");
1229
+ }
1230
+ const grantTypes = grantCmd.MoveCall.typeArguments;
1231
+ if (!grantTypes || grantTypes.length !== 1) {
1232
+ throw new TransactionVerificationError("coinType");
1233
+ }
1234
+ const grantCoinType = safeNormalizeStructTag(grantTypes[0]);
1235
+ if (grantCoinType !== cmdCoinType) {
1236
+ throw new TransactionVerificationError("coinType");
1237
+ }
1238
+ const grantArgs = grantCmd.MoveCall.arguments;
1239
+ if (!grantArgs || grantArgs.length !== 6) {
1240
+ throw new TransactionVerificationError("target");
1241
+ }
1242
+ const grantPoolInputIdx = markInput(grantArgs[0]);
1243
+ const grantPoolId = getObjectIdFromInput(data.inputs[grantPoolInputIdx]);
1244
+ if (!grantPoolId || grantPoolId !== poolId) {
1245
+ throw new TransactionVerificationError("pool");
1246
+ }
1247
+ const delInputIdx = markInput(grantArgs[1]);
1248
+ const delBytes = getPureBytes(data.inputs[delInputIdx]);
1249
+ if (!delBytes || parseAddress(delBytes) !== safeNormalizeAddress(op.delegate.address)) {
1250
+ throw new TransactionVerificationError("delegate");
1251
+ }
1252
+ const capInputIdx = markInput(grantArgs[2]);
1253
+ const capBytes = getPureBytes(data.inputs[capInputIdx]);
1254
+ if (!capBytes) {
1255
+ throw new TransactionVerificationError("caps");
1256
+ }
1257
+ const txSessionCap = parseOptionU64(capBytes);
1258
+ const maxInputIdx = markInput(grantArgs[3]);
1259
+ const maxBytes = getPureBytes(data.inputs[maxInputIdx]);
1260
+ if (!maxBytes) {
1261
+ throw new TransactionVerificationError("caps");
1262
+ }
1263
+ const txMaxPerPayment = parseOptionU64(maxBytes);
1264
+ if (txSessionCap === null || txMaxPerPayment !== txSessionCap) {
1265
+ throw new TransactionVerificationError("caps");
1266
+ }
1267
+ if (txSessionCap > groupInfo.sumTotalCap) {
1268
+ throw new TransactionVerificationError("caps");
1269
+ }
1270
+ assertPureU64(grantArgs[4], 0n, "expiry");
1271
+ const grantVecRes = markResult(grantArgs[5], "policyId");
1272
+ if (grantVecRes.cmdIndex !== N + 2 || grantVecRes.resIndex !== 0) {
1273
+ throw new TransactionVerificationError("policyId");
1274
+ }
1042
1275
  break;
1043
1276
  }
1044
1277
  case "create_grant_open": {
@@ -1580,6 +1813,12 @@ function createAgentsApi(transport) {
1580
1813
  if (!created.ok)
1581
1814
  return created;
1582
1815
  const finalized = [];
1816
+ for (const submitted of created.value.submitted ?? []) {
1817
+ const fin = await finalizeGrant(created.value.delegatedSignerId, submitted.grantId, submitted.digest);
1818
+ if (!fin.ok)
1819
+ return fin;
1820
+ finalized.push(fin.value);
1821
+ }
1583
1822
  for (const grant of created.value.grants) {
1584
1823
  const scope = input.assetScopes.find((s) => s.asset.toLowerCase() === grant.asset.toLowerCase() || supportedAssetByCoinType(s.asset)?.id === grant.asset.toLowerCase());
1585
1824
  const coinType = TESTNET_ASSETS.find((a) => a.id === grant.asset.toLowerCase() || a.symbol.toLowerCase() === grant.asset.toLowerCase())?.coinType ?? scope?.asset ?? grant.asset;
@@ -2313,7 +2552,7 @@ function wrapFailover(clients, options = {}) {
2313
2552
 
2314
2553
  // ../sdk/dist/buyer-control/chain.js
2315
2554
  import { Transaction as Transaction2, coinWithBalance } from "@mysten/sui/transactions";
2316
- import { fromBase64 as fromBase643, normalizeStructTag as normalizeStructTag4, normalizeSuiAddress as normalizeSuiAddress3, toBase64 } from "@mysten/sui/utils";
2555
+ import { fromBase64 as fromBase643, normalizeStructTag as normalizeStructTag6, normalizeSuiAddress as normalizeSuiAddress3, toBase64 } from "@mysten/sui/utils";
2317
2556
 
2318
2557
  // ../core/dist/chain/address.js
2319
2558
  function hexOf(address) {
@@ -2357,7 +2596,7 @@ function objectTypeFromGetObject(object) {
2357
2596
 
2358
2597
  // ../core/dist/policy/target.js
2359
2598
  import { createHash } from "crypto";
2360
- import { normalizeStructTag as normalizeStructTag3 } from "@mysten/sui/utils";
2599
+ import { normalizeStructTag as normalizeStructTag5 } from "@mysten/sui/utils";
2361
2600
 
2362
2601
  // ../core/dist/service-state/index.js
2363
2602
  var STATE_DIMENSIONS = Object.freeze([
@@ -2574,6 +2813,14 @@ var SERVICE_STATE_TRANSITIONS = Object.freeze([
2574
2813
  to: "payout_change",
2575
2814
  actors: ["system"],
2576
2815
  requires: ["reason_code"]
2816
+ },
2817
+ {
2818
+ id: "T25",
2819
+ dimension: "suspension",
2820
+ from: ["binding_changed"],
2821
+ to: "none",
2822
+ actors: ["system"],
2823
+ requires: ["reason_code"]
2577
2824
  }
2578
2825
  ]);
2579
2826
 
@@ -2743,7 +2990,7 @@ var MODULE = "spend_account";
2743
2990
  var SUI_COIN_TYPE = "0x2::sui::SUI";
2744
2991
  function isSuiCoinType(coinType) {
2745
2992
  try {
2746
- return normalizeStructTag4(coinType) === normalizeStructTag4(SUI_COIN_TYPE);
2993
+ return normalizeStructTag6(coinType) === normalizeStructTag6(SUI_COIN_TYPE);
2747
2994
  } catch {
2748
2995
  return /::sui::SUI$/i.test(coinType);
2749
2996
  }
@@ -2973,6 +3220,70 @@ function createSpendAccountChain(options) {
2973
3220
  });
2974
3221
  return kindBytes(tx);
2975
3222
  },
3223
+ async buildCreatePolicyAndGrantKind(input) {
3224
+ if (!input.policy.targets?.length) {
3225
+ throw new Error("create_spend_policy requires at least one target");
3226
+ }
3227
+ if (!input.policy.totalCap || BigInt(input.policy.totalCap) <= 0n) {
3228
+ throw new Error("create_spend_policy requires a non-zero total_cap");
3229
+ }
3230
+ if (!input.policy.maxPerPayment || BigInt(input.policy.maxPerPayment) <= 0n) {
3231
+ throw new Error("create_spend_policy requires a non-zero max_per_payment");
3232
+ }
3233
+ if (!input.grant.sessionCap || BigInt(input.grant.sessionCap) <= 0n) {
3234
+ throw new Error("create_grant requires a non-zero session_cap");
3235
+ }
3236
+ if (!input.grant.maxPerPayment || BigInt(input.grant.maxPerPayment) <= 0n) {
3237
+ throw new Error("create_grant requires a non-zero max_per_payment");
3238
+ }
3239
+ const tx = new Transaction2();
3240
+ tx.setSender(input.owner);
3241
+ const targetResults = input.policy.targets.map((t) => {
3242
+ const hash = targetHashBytes(t.targetHash);
3243
+ return tx.moveCall({
3244
+ target: target("new_policy_target"),
3245
+ arguments: [
3246
+ tx.pure.vector("u8", Array.from(hash)),
3247
+ tx.pure.address(t.recipient),
3248
+ tx.pure.u64(BigInt(t.maxPerPayment))
3249
+ ]
3250
+ });
3251
+ });
3252
+ const targetsVec = tx.makeMoveVec({
3253
+ type: `${packageId}::${MODULE}::PolicyTarget`,
3254
+ elements: targetResults
3255
+ });
3256
+ const policyExpires = input.policy.expiresAtMs === void 0 || input.policy.expiresAtMs === null ? 0n : BigInt(input.policy.expiresAtMs);
3257
+ const policyIdResult = tx.moveCall({
3258
+ target: target("create_spend_policy"),
3259
+ typeArguments: [input.coinType],
3260
+ arguments: [
3261
+ tx.object(input.poolObjectId),
3262
+ targetsVec,
3263
+ tx.pure.u64(BigInt(input.policy.totalCap)),
3264
+ tx.pure.u64(BigInt(input.policy.maxPerPayment)),
3265
+ tx.pure.u64(policyExpires)
3266
+ ]
3267
+ });
3268
+ const policyIdsVec = tx.makeMoveVec({
3269
+ type: "u64",
3270
+ elements: [policyIdResult]
3271
+ });
3272
+ const grantExpires = input.grant.expiresAtMs === void 0 || input.grant.expiresAtMs === null ? 0n : BigInt(input.grant.expiresAtMs);
3273
+ tx.moveCall({
3274
+ target: target("create_policy_grant"),
3275
+ typeArguments: [input.coinType],
3276
+ arguments: [
3277
+ tx.object(input.poolObjectId),
3278
+ tx.pure.address(input.delegate),
3279
+ tx.pure.option("u64", BigInt(input.grant.sessionCap)),
3280
+ tx.pure.option("u64", BigInt(input.grant.maxPerPayment)),
3281
+ tx.pure.u64(grantExpires),
3282
+ policyIdsVec
3283
+ ]
3284
+ });
3285
+ return kindBytes(tx);
3286
+ },
2976
3287
  async buildPausePolicyKind(input) {
2977
3288
  const tx = new Transaction2();
2978
3289
  tx.setSender(input.owner);
@@ -3981,7 +4292,7 @@ var sha256 = /* @__PURE__ */ createHasher(
3981
4292
  );
3982
4293
 
3983
4294
  // ../sdk/dist/protocol/offer-exclusion.js
3984
- import { normalizeStructTag as normalizeStructTag5, normalizeSuiAddress as normalizeSuiAddress4 } from "@mysten/sui/utils";
4295
+ import { normalizeStructTag as normalizeStructTag7, normalizeSuiAddress as normalizeSuiAddress4 } from "@mysten/sui/utils";
3985
4296
 
3986
4297
  // ../sdk/dist/protocol/terms.js
3987
4298
  function paymentIdHash(challengeId) {
@@ -4056,7 +4367,7 @@ function addr32(address) {
4056
4367
  return hexToBytes(normalized.slice(2));
4057
4368
  }
4058
4369
  function canonicalCoinTypeBytes(coinType) {
4059
- const normalized = normalizeStructTag5(coinType.trim());
4370
+ const normalized = normalizeStructTag7(coinType.trim());
4060
4371
  const canonical = normalized.replace(/0x([0-9a-f]{64})/g, "$1");
4061
4372
  if (!/^[0-9a-f]{64}::/.test(canonical)) {
4062
4373
  throw new Error(`coin type must resolve to a numeric package address: ${coinType}`);
@@ -4256,7 +4567,7 @@ function createGrpcExclusionRegistryReader(client) {
4256
4567
  // ../sdk/dist/delegated-signer/payer.js
4257
4568
  import { bcs as bcs7 } from "@mysten/sui/bcs";
4258
4569
  import { Transaction as Transaction4 } from "@mysten/sui/transactions";
4259
- import { fromBase64 as fromBase647, normalizeStructTag as normalizeStructTag8, normalizeSuiAddress as normalizeSuiAddress9, toBase64 as toBase645 } from "@mysten/sui/utils";
4570
+ import { fromBase64 as fromBase647, normalizeStructTag as normalizeStructTag10, normalizeSuiAddress as normalizeSuiAddress9, toBase64 as toBase645 } from "@mysten/sui/utils";
4260
4571
  import { Ed25519Keypair } from "@mysten/sui/keypairs/ed25519";
4261
4572
 
4262
4573
  // ../sdk/dist/delegated-signer/finality-poll.js
@@ -4282,7 +4593,7 @@ async function pollFinality(input) {
4282
4593
  }
4283
4594
 
4284
4595
  // ../sdk/dist/pay-operation/operation.js
4285
- import { normalizeStructTag as normalizeStructTag7, normalizeSuiAddress as normalizeSuiAddress6 } from "@mysten/sui/utils";
4596
+ import { normalizeStructTag as normalizeStructTag9, normalizeSuiAddress as normalizeSuiAddress6 } from "@mysten/sui/utils";
4286
4597
 
4287
4598
  // ../core/dist/policy/grant-target.js
4288
4599
  function normalizeHash(hex) {
@@ -4370,12 +4681,6 @@ import { fromBase64 as fromBase645, toBase64 as toBase643 } from "@mysten/sui/ut
4370
4681
 
4371
4682
  // ../sdk/dist/protocol/auth-params.js
4372
4683
  var TOKEN = /^[A-Za-z0-9!#$%&'*+\-.^_`|~]+$/;
4373
- function formatAuthParams(params) {
4374
- return Object.entries(params).map(([k, v]) => `${k}=${TOKEN.test(v) ? v : quote(v)}`).join(", ");
4375
- }
4376
- function quote(value) {
4377
- return `"${value.replace(/\\/g, "\\\\").replace(/"/g, '\\"')}"`;
4378
- }
4379
4684
  function parseAuthHeader(header) {
4380
4685
  const trimmed = header.trim();
4381
4686
  const firstSpace = trimmed.indexOf(" ");
@@ -4454,6 +4759,19 @@ function bytesToBase64Url(bytes) {
4454
4759
  const base64 = typeof globalThis.btoa === "function" ? globalThis.btoa(binary) : Buffer.from(bytes).toString("base64");
4455
4760
  return base64.replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/g, "");
4456
4761
  }
4762
+ function bytesFromBase64Url(s) {
4763
+ const normalized = s.replace(/-/g, "+").replace(/_/g, "/");
4764
+ const pad = (4 - normalized.length % 4) % 4;
4765
+ const base64 = normalized + "=".repeat(pad);
4766
+ if (typeof globalThis.atob === "function") {
4767
+ const binary = globalThis.atob(base64);
4768
+ const out = new Uint8Array(binary.length);
4769
+ for (let i = 0; i < binary.length; i++)
4770
+ out[i] = binary.charCodeAt(i);
4771
+ return out;
4772
+ }
4773
+ return Uint8Array.from(Buffer.from(base64, "base64"));
4774
+ }
4457
4775
 
4458
4776
  // ../sdk/dist/protocol/challenge.js
4459
4777
  import { Ed25519PublicKey } from "@mysten/sui/keypairs/ed25519";
@@ -4798,9 +5116,220 @@ function offerToBase64Url(offer) {
4798
5116
  }
4799
5117
  var MPP_SCHEME = "Payment";
4800
5118
  var MPP_METHOD = "sui.charge";
5119
+ var MPP_SUI_METHOD = "sui";
5120
+ var MPP_CHARGE_INTENT = "charge";
5121
+ var MPP_RECEIPT_STATUS = "success";
5122
+ var LEGACY_RECEIPT_STATUS = "settled";
4801
5123
  var MPP_CHALLENGE_HEADER = "WWW-Authenticate";
4802
5124
  var MPP_CREDENTIAL_HEADER = "Authorization";
4803
5125
  var MPP_RECEIPT_HEADER = "Payment-Receipt";
5126
+ var HEADER_TEXT_REPLACEMENTS = {
5127
+ "\u2264": "<=",
5128
+ // ≤ less-than-or-equal
5129
+ "\u2265": ">=",
5130
+ // ≥ greater-than-or-equal
5131
+ "\u2014": "-",
5132
+ // — em dash
5133
+ "\u2013": "-",
5134
+ // – en dash
5135
+ "\u2018": "'",
5136
+ // ' left single quote
5137
+ "\u2019": "'",
5138
+ // ' right single quote
5139
+ "\u201C": '"',
5140
+ // " left double quote
5141
+ "\u201D": '"'
5142
+ // " right double quote
5143
+ };
5144
+ function latin1HeaderText(value) {
5145
+ let out = "";
5146
+ for (const ch of value) {
5147
+ const mapped = HEADER_TEXT_REPLACEMENTS[ch];
5148
+ if (mapped !== void 0)
5149
+ out += mapped;
5150
+ else if (ch.codePointAt(0) > 255)
5151
+ out += "?";
5152
+ else
5153
+ out += ch;
5154
+ }
5155
+ return out;
5156
+ }
5157
+ var DAY_MS = 864e5;
5158
+ function billingPeriod(periodMs) {
5159
+ if (!Number.isInteger(periodMs) || periodMs < DAY_MS || periodMs % DAY_MS !== 0)
5160
+ return null;
5161
+ const days = periodMs / DAY_MS;
5162
+ if (days % 7 === 0)
5163
+ return { periodCount: String(days / 7), periodUnit: "week" };
5164
+ return { periodCount: String(days), periodUnit: "day" };
5165
+ }
5166
+ function billingPeriodMs(unit, count) {
5167
+ if (!Number.isInteger(count) || count <= 0)
5168
+ return null;
5169
+ if (unit === "day")
5170
+ return count * DAY_MS;
5171
+ if (unit === "week")
5172
+ return count * 7 * DAY_MS;
5173
+ return null;
5174
+ }
5175
+ function expiresWire(offer) {
5176
+ if (typeof offer.expiresAt !== "number" || !Number.isFinite(offer.expiresAt))
5177
+ return void 0;
5178
+ return new Date(offer.expiresAt).toISOString();
5179
+ }
5180
+ function flatParams(offer) {
5181
+ const params = {
5182
+ amount: offer.amount,
5183
+ asset: offer.asset,
5184
+ network: offer.network,
5185
+ recipient: offer.payTo,
5186
+ package: offer.packageId,
5187
+ resource: offer.resource,
5188
+ digest: offer.digest
5189
+ };
5190
+ if (typeof offer.decimals === "number")
5191
+ params.decimals = String(offer.decimals);
5192
+ if (typeof offer.description === "string") {
5193
+ params.description = latin1HeaderText(offer.description);
5194
+ }
5195
+ if (typeof offer.issuedAt === "number" && Number.isFinite(offer.issuedAt)) {
5196
+ params.issued = new Date(offer.issuedAt).toISOString();
5197
+ }
5198
+ if (typeof offer.expiresAt === "number" && Number.isFinite(offer.expiresAt)) {
5199
+ params.expires = new Date(offer.expiresAt).toISOString();
5200
+ }
5201
+ if (offer.netAmount !== void 0)
5202
+ params.net_amount = offer.netAmount;
5203
+ if (offer.platformFee !== void 0)
5204
+ params.platform_fee = offer.platformFee;
5205
+ if (offer.digestVersion !== void 0)
5206
+ params.digest_version = String(offer.digestVersion);
5207
+ if (offer.settlementRail !== void 0)
5208
+ params.settlement_rail = offer.settlementRail;
5209
+ if (offer.serviceId !== void 0)
5210
+ params.service_id = offer.serviceId;
5211
+ if (offer.serviceRevision !== void 0) {
5212
+ params.service_revision = String(offer.serviceRevision);
5213
+ }
5214
+ if (offer.targetHash !== void 0)
5215
+ params.target_hash = offer.targetHash;
5216
+ if (offer.authorizationEpoch !== void 0) {
5217
+ params.authorization_epoch = String(offer.authorizationEpoch);
5218
+ }
5219
+ if (offer.method !== void 0)
5220
+ params.http_method = offer.method;
5221
+ if (offer.path !== void 0)
5222
+ params.http_path = offer.path;
5223
+ if (offer.bodyHash !== void 0)
5224
+ params.body_hash = offer.bodyHash;
5225
+ if (offer.contentType !== void 0)
5226
+ params.content_type = offer.contentType;
5227
+ if (offer.intent !== void 0)
5228
+ params.intent = offer.intent;
5229
+ if (offer.periodMs !== void 0)
5230
+ params.period_ms = String(offer.periodMs);
5231
+ if (offer.periodCount !== void 0)
5232
+ params.period_count = String(offer.periodCount);
5233
+ if (offer.refundable !== void 0)
5234
+ params.refundable = offer.refundable ? "true" : "false";
5235
+ if (offer.refundWindowMs !== void 0) {
5236
+ params.refund_window_ms = String(offer.refundWindowMs);
5237
+ }
5238
+ if (offer.decideWindowMs !== void 0) {
5239
+ params.decide_window_ms = String(offer.decideWindowMs);
5240
+ }
5241
+ if (offer.chainId !== void 0)
5242
+ params.chain_id = String(offer.chainId);
5243
+ if (offer.paymentSalt !== void 0)
5244
+ params.payment_salt = offer.paymentSalt;
5245
+ if (offer.refundConfigId !== void 0)
5246
+ params.refund_config_id = offer.refundConfigId;
5247
+ if (offer.refundTo !== void 0)
5248
+ params.refund_to = offer.refundTo;
5249
+ if (offer.sponsorGasOwner !== void 0) {
5250
+ params.sponsor_gas_owner = offer.sponsorGasOwner;
5251
+ }
5252
+ if (offer.sponsorGasBudget !== void 0) {
5253
+ params.sponsor_gas_budget = offer.sponsorGasBudget;
5254
+ }
5255
+ if (offer.sponsorGasPrice !== void 0) {
5256
+ params.sponsor_gas_price = offer.sponsorGasPrice;
5257
+ }
5258
+ if (offer.sponsorGasPayment !== void 0) {
5259
+ params.sponsor_gas_payment = offer.sponsorGasPayment;
5260
+ }
5261
+ if (offer.acceptedRails !== void 0) {
5262
+ params.accepted_rails = offer.acceptedRails.join(",");
5263
+ }
5264
+ if (offer.exclusionProtocolVersion !== void 0) {
5265
+ params.exclusion_protocol_version = String(offer.exclusionProtocolVersion);
5266
+ }
5267
+ if (offer.registryIdentity !== void 0) {
5268
+ params.registry_identity = offer.registryIdentity;
5269
+ }
5270
+ if (offer.sig !== void 0)
5271
+ params.sig = offer.sig;
5272
+ if (offer.sigKid !== void 0)
5273
+ params.sig_kid = offer.sigKid;
5274
+ return params;
5275
+ }
5276
+ function legacyRequestBlob(offer, copies = false) {
5277
+ const params = flatParams(offer);
5278
+ if (copies) {
5279
+ params.method = MPP_SUI_METHOD;
5280
+ params.realm = "suipay";
5281
+ params.challenge = offer.challengeId;
5282
+ if (typeof offer.mimeType === "string")
5283
+ params.type = offer.mimeType;
5284
+ }
5285
+ return bytesToBase64Url(new TextEncoder().encode(canonicalJson(params)));
5286
+ }
5287
+ function requestBlob(offer) {
5288
+ const flat = flatParams(offer);
5289
+ const details = { ...flat };
5290
+ delete details.amount;
5291
+ delete details.asset;
5292
+ delete details.recipient;
5293
+ delete details.description;
5294
+ delete details.expires;
5295
+ const body = {
5296
+ amount: flat.amount,
5297
+ currency: flat.asset,
5298
+ methodDetails: details
5299
+ };
5300
+ if (flat.recipient !== void 0)
5301
+ body.recipient = flat.recipient;
5302
+ if (flat.description !== void 0)
5303
+ body.description = flat.description;
5304
+ if (wireIntent(offer) === "subscription") {
5305
+ delete details.period_ms;
5306
+ const periodMs = offer.periodMs;
5307
+ const billing = typeof periodMs === "number" ? billingPeriod(periodMs) : null;
5308
+ if (!billing) {
5309
+ throw new Error("subscription periodMs is not an exact number of days");
5310
+ }
5311
+ body.periodCount = billing.periodCount;
5312
+ body.periodUnit = billing.periodUnit;
5313
+ const periodCount = offer.periodCount;
5314
+ const issuedAt = offer.issuedAt;
5315
+ if (typeof periodMs === "number" && typeof periodCount === "number" && typeof issuedAt === "number" && Number.isSafeInteger(periodMs) && Number.isSafeInteger(periodCount) && Number.isSafeInteger(issuedAt) && Number.isSafeInteger(periodMs * periodCount)) {
5316
+ const end = issuedAt + periodMs * periodCount;
5317
+ if (Number.isSafeInteger(end))
5318
+ body.subscriptionExpires = new Date(end).toISOString();
5319
+ }
5320
+ }
5321
+ return bytesToBase64Url(new TextEncoder().encode(canonicalJsonValue(body)));
5322
+ }
5323
+ function issuedRequestBlob(offer) {
5324
+ return requestBlob(offer);
5325
+ }
5326
+ function echoedRequestBlob(offer) {
5327
+ try {
5328
+ return issuedRequestBlob(offer);
5329
+ } catch {
5330
+ return legacyRequestBlob(offer);
5331
+ }
5332
+ }
4804
5333
  function splitChallenges(header) {
4805
5334
  const scheme = `${MPP_SCHEME} `;
4806
5335
  const value = header.trim();
@@ -4860,11 +5389,120 @@ function decodeChallenge(header, opts) {
4860
5389
  }
4861
5390
  return null;
4862
5391
  }
5392
+ function canonicalJson(fields) {
5393
+ const keys = Object.keys(fields).sort();
5394
+ return `{${keys.map((key) => `${JSON.stringify(key)}:${JSON.stringify(fields[key])}`).join(",")}}`;
5395
+ }
5396
+ function canonicalJsonValue(value) {
5397
+ if (value === null || typeof value !== "object")
5398
+ return JSON.stringify(value);
5399
+ if (Array.isArray(value))
5400
+ return `[${value.map(canonicalJsonValue).join(",")}]`;
5401
+ const fields = value;
5402
+ const keys = Object.keys(fields).sort();
5403
+ return `{${keys.map((key) => `${JSON.stringify(key)}:${canonicalJsonValue(fields[key])}`).join(",")}}`;
5404
+ }
5405
+ function wireIntent(offer) {
5406
+ return offer.intent === "subscription" ? "subscription" : MPP_CHARGE_INTENT;
5407
+ }
5408
+ var REQUEST_TOP_LEVEL = /* @__PURE__ */ new Set([
5409
+ "amount",
5410
+ "asset",
5411
+ "currency",
5412
+ "description",
5413
+ "externalId",
5414
+ "recipient",
5415
+ "subscriptionExpires"
5416
+ ]);
5417
+ function takeStrings(source, into) {
5418
+ for (const [key, value] of Object.entries(source)) {
5419
+ if (typeof value !== "string")
5420
+ return false;
5421
+ into[key] = value;
5422
+ }
5423
+ return true;
5424
+ }
5425
+ function officialParams(params) {
5426
+ if (params.method !== MPP_SUI_METHOD || !params.request)
5427
+ return null;
5428
+ if (params.intent !== MPP_CHARGE_INTENT && params.intent !== "subscription")
5429
+ return null;
5430
+ let body;
5431
+ try {
5432
+ body = JSON.parse(new TextDecoder().decode(bytesFromBase64Url(params.request)));
5433
+ } catch {
5434
+ return null;
5435
+ }
5436
+ if (!body || typeof body !== "object" || Array.isArray(body))
5437
+ return null;
5438
+ const record = body;
5439
+ const fields = {};
5440
+ const details = record.methodDetails;
5441
+ if (details !== void 0) {
5442
+ if (!details || typeof details !== "object" || Array.isArray(details))
5443
+ return null;
5444
+ if (!takeStrings(details, fields))
5445
+ return null;
5446
+ for (const [key, value] of Object.entries(record)) {
5447
+ if (key === "methodDetails" || key === "periodCount" || key === "periodUnit")
5448
+ continue;
5449
+ if (typeof value !== "string" || !REQUEST_TOP_LEVEL.has(key))
5450
+ return null;
5451
+ if (fields[key] !== void 0 && fields[key] !== value)
5452
+ return null;
5453
+ fields[key] = value;
5454
+ }
5455
+ const periodCount = record.periodCount;
5456
+ const periodUnit = record.periodUnit;
5457
+ if (periodCount !== void 0 || periodUnit !== void 0) {
5458
+ if (typeof periodCount !== "string" || typeof periodUnit !== "string")
5459
+ return null;
5460
+ if (!/^[1-9]\d*$/.test(periodCount))
5461
+ return null;
5462
+ const ms = billingPeriodMs(periodUnit, Number(periodCount));
5463
+ if (ms === null)
5464
+ return null;
5465
+ if (fields.period_ms !== void 0 && fields.period_ms !== String(ms))
5466
+ return null;
5467
+ fields.period_ms = String(ms);
5468
+ }
5469
+ if (params.intent === "subscription" && fields.period_ms === void 0)
5470
+ return null;
5471
+ } else if (!takeStrings(record, fields)) {
5472
+ return null;
5473
+ }
5474
+ if (fields.currency !== void 0) {
5475
+ if (fields.asset !== void 0 && fields.asset !== fields.currency)
5476
+ return null;
5477
+ fields.asset = fields.currency;
5478
+ }
5479
+ if (params.expires !== void 0) {
5480
+ if (fields.expires !== void 0 && fields.expires !== params.expires)
5481
+ return null;
5482
+ if (fields.expires === void 0)
5483
+ fields.expires = params.expires;
5484
+ }
5485
+ if (!fields.challenge && params.id)
5486
+ fields.challenge = params.id;
5487
+ if (fields.method === void 0)
5488
+ fields.method = MPP_SUI_METHOD;
5489
+ if (fields.method !== MPP_METHOD && fields.method !== MPP_SUI_METHOD)
5490
+ return null;
5491
+ if (fields.intent !== void 0 && fields.intent !== params.intent)
5492
+ return null;
5493
+ if (fields.intent === void 0 && params.intent === "subscription")
5494
+ return null;
5495
+ fields.method = MPP_METHOD;
5496
+ return fields;
5497
+ }
4863
5498
  function decodeSingleChallenge(header) {
4864
5499
  const parsed = parseAuthHeader(header);
4865
5500
  if (!parsed || parsed.scheme !== MPP_SCHEME)
4866
5501
  return null;
4867
- const p = parsed.params;
5502
+ const pinned = officialParams(parsed.params);
5503
+ const p = { ...pinned ?? parsed.params };
5504
+ if (p.method === MPP_SUI_METHOD)
5505
+ p.method = MPP_METHOD;
4868
5506
  if (p.method !== MPP_METHOD)
4869
5507
  return null;
4870
5508
  const required = [
@@ -4949,13 +5587,15 @@ function decodeSingleChallenge(header) {
4949
5587
  offer.intent = p.intent;
4950
5588
  if (p.period_ms !== void 0) {
4951
5589
  const ms = Number(p.period_ms);
4952
- if (Number.isFinite(ms))
4953
- offer.periodMs = ms;
5590
+ if (!Number.isSafeInteger(ms) || ms <= 0)
5591
+ return null;
5592
+ offer.periodMs = ms;
4954
5593
  }
4955
5594
  if (p.period_count !== void 0) {
4956
5595
  const count = Number(p.period_count);
4957
- if (Number.isFinite(count))
4958
- offer.periodCount = count;
5596
+ if (!Number.isSafeInteger(count) || count <= 0)
5597
+ return null;
5598
+ offer.periodCount = count;
4959
5599
  }
4960
5600
  if (p.refundable === "true")
4961
5601
  offer.refundable = true;
@@ -5015,25 +5655,46 @@ function decodeSingleChallenge(header) {
5015
5655
  offer.sigKid = p.sig_kid;
5016
5656
  return offer;
5017
5657
  }
5658
+ function echoedChallenge(offer, challengeId) {
5659
+ const challenge = {
5660
+ id: challengeId,
5661
+ realm: "suipay",
5662
+ method: MPP_SUI_METHOD,
5663
+ intent: wireIntent(offer),
5664
+ // Section 5.2 echoes the original challenge, including its request.
5665
+ request: echoedRequestBlob(offer)
5666
+ };
5667
+ const expires = expiresWire(offer);
5668
+ if (expires !== void 0)
5669
+ challenge.expires = expires;
5670
+ return challenge;
5671
+ }
5672
+ function encodeOfficialMessage(body) {
5673
+ return `${MPP_SCHEME} ${bytesToBase64Url(new TextEncoder().encode(canonicalJsonValue(body)))}`;
5674
+ }
5018
5675
  function encodeProof(proof) {
5019
- return `${MPP_SCHEME} ${formatAuthParams({
5020
- method: MPP_METHOD,
5021
- challenge: proof.challengeId,
5022
- payer: proof.payer,
5023
- offer: offerToBase64Url(proof.offer),
5024
- digest: proof.txDigest
5025
- })}`;
5676
+ return encodeOfficialMessage({
5677
+ challenge: echoedChallenge(proof.offer, proof.challengeId),
5678
+ payload: {
5679
+ payer: proof.payer,
5680
+ offer: offerToBase64Url(proof.offer),
5681
+ digest: proof.txDigest
5682
+ }
5683
+ });
5026
5684
  }
5027
- function decodeReceipt(header) {
5028
- const parsed = parseAuthHeader(`X ${header}`);
5029
- if (!parsed)
5685
+ function receiptFromParams(p) {
5686
+ if (p.method !== MPP_METHOD && p.method !== MPP_SUI_METHOD)
5687
+ return null;
5688
+ if (p.status !== MPP_RECEIPT_STATUS && p.status !== LEGACY_RECEIPT_STATUS)
5030
5689
  return null;
5031
- const p = parsed.params;
5032
- if (!p.challenge || !p.tx_digest || !p.payer || !p.amount || !p.asset || !p.network)
5690
+ if (p.tx_digest && p.reference && p.tx_digest !== p.reference)
5691
+ return null;
5692
+ const txDigest = p.tx_digest || p.reference;
5693
+ if (!p.challenge || !txDigest || !p.payer || !p.amount || !p.asset || !p.network)
5033
5694
  return null;
5034
5695
  const receipt = {
5035
5696
  challengeId: p.challenge,
5036
- txDigest: p.tx_digest,
5697
+ txDigest,
5037
5698
  network: p.network,
5038
5699
  payer: p.payer,
5039
5700
  amount: p.amount,
@@ -5054,6 +5715,34 @@ function decodeReceipt(header) {
5054
5715
  receipt.periodIndex = p.period_index;
5055
5716
  return receipt;
5056
5717
  }
5718
+ function decodeOfficialReceipt(header) {
5719
+ const token = header.trim();
5720
+ if (!/^[A-Za-z0-9_-]+$/.test(token))
5721
+ return null;
5722
+ let body;
5723
+ try {
5724
+ body = JSON.parse(new TextDecoder().decode(bytesFromBase64Url(token)));
5725
+ } catch {
5726
+ return null;
5727
+ }
5728
+ if (!body || typeof body !== "object" || Array.isArray(body))
5729
+ return null;
5730
+ const fields = {};
5731
+ for (const [key, value] of Object.entries(body)) {
5732
+ if (typeof value !== "string")
5733
+ return null;
5734
+ fields[key] = value;
5735
+ }
5736
+ return receiptFromParams(fields);
5737
+ }
5738
+ function decodeReceipt(header) {
5739
+ if (/^[A-Za-z0-9_-]+$/.test(header.trim()))
5740
+ return decodeOfficialReceipt(header);
5741
+ const parsed = parseAuthHeader(`X ${header}`);
5742
+ if (!parsed)
5743
+ return null;
5744
+ return receiptFromParams(parsed.params);
5745
+ }
5057
5746
 
5058
5747
  // ../sdk/dist/protocol/x402.js
5059
5748
  import { fromBase64 as fromBase644, toBase64 as toBase642 } from "@mysten/sui/utils";
@@ -5511,7 +6200,7 @@ import { fromHex } from "@mysten/sui/utils";
5511
6200
 
5512
6201
  // ../sdk/dist/protocol/coin-type-hash.js
5513
6202
  import { createHash as createHash2 } from "crypto";
5514
- import { normalizeStructTag as normalizeStructTag6 } from "@mysten/sui/utils";
6203
+ import { normalizeStructTag as normalizeStructTag8 } from "@mysten/sui/utils";
5515
6204
 
5516
6205
  // ../sdk/dist/protocol/refund-vault.js
5517
6206
  function isRefundableOffer(offer) {
@@ -6176,8 +6865,8 @@ function resolveAuthority(authority, offer) {
6176
6865
  };
6177
6866
  }
6178
6867
  function validateAmount(offer, resolved) {
6179
- const offerCoinType = normalizeStructTag7(offer.asset);
6180
- const grantCoinType = normalizeStructTag7(resolved.coinType);
6868
+ const offerCoinType = normalizeStructTag9(offer.asset);
6869
+ const grantCoinType = normalizeStructTag9(resolved.coinType);
6181
6870
  if (offerCoinType !== grantCoinType) {
6182
6871
  return {
6183
6872
  code: PAY_OPERATION_ERROR_CODES.COIN_TYPE_MISMATCH,
@@ -7248,7 +7937,7 @@ function atomicAmount(value) {
7248
7937
  }
7249
7938
  function sameStructTag(a, b) {
7250
7939
  try {
7251
- return normalizeStructTag8(a) === normalizeStructTag8(b);
7940
+ return normalizeStructTag10(a) === normalizeStructTag10(b);
7252
7941
  } catch {
7253
7942
  return false;
7254
7943
  }
@@ -8006,7 +8695,7 @@ async function payDelegatedSpendAccount(args) {
8006
8695
  refuseOffer("POLICY_NO_TARGET");
8007
8696
  }
8008
8697
  try {
8009
- normalizeStructTag8(offer2.asset);
8698
+ normalizeStructTag10(offer2.asset);
8010
8699
  } catch {
8011
8700
  refuseOffer("POLICY_BAD_ASSET");
8012
8701
  }
@@ -8070,7 +8759,7 @@ async function payDelegatedSpendAccount(args) {
8070
8759
  return buildSpendAccountPayKind(kindInput);
8071
8760
  };
8072
8761
  try {
8073
- normalizeStructTag8(snapshot.coinType);
8762
+ normalizeStructTag10(snapshot.coinType);
8074
8763
  } catch {
8075
8764
  return failed("POLICY_REJECTED", PUBLIC_DETAIL.POLICY_REJECTED);
8076
8765
  }
@@ -9669,7 +10358,9 @@ async function resolvePayerSession(options) {
9669
10358
  ok: false,
9670
10359
  // The gateway's stable code, never a raw body — the read client already
9671
10360
  // sanitized it, and an operator needs to tell 429 from 401.
9672
- error: manifestError(MANIFEST_ERROR_CODES.MALFORMED_MANIFEST, `bootstrap was refused (${bootstrap.error}${bootstrap.code ? `: ${bootstrap.code}` : ""})`)
10361
+ // A 429 is the gateway's rate limit, not a manifest the agent can fix, so
10362
+ // it keeps the retryable code instead of the manifest default.
10363
+ error: manifestError(MANIFEST_ERROR_CODES.MALFORMED_MANIFEST, `bootstrap was refused (${bootstrap.error}${bootstrap.code ? `: ${bootstrap.code}` : ""})`, bootstrap.status === 429 ? "limit.rate_limited" : void 0)
9673
10364
  };
9674
10365
  }
9675
10366
  const whole = manifestToSession({