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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -13,7 +13,7 @@ import {
13
13
  parseErrorPayload,
14
14
  stricterPaymentState,
15
15
  toErrorFields
16
- } from "./chunk-XSL5G2RU.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;
@@ -789,6 +856,9 @@ function verifyOwnerTransaction(input) {
789
856
  const cmd = commands[i];
790
857
  if (cmd.$kind === "MergeCoins") {
791
858
  const mc = cmd.MergeCoins;
859
+ if (JSON.stringify(mc.destination) !== JSON.stringify(splitCmd.SplitCoins.coin)) {
860
+ throw new TransactionVerificationError("funding");
861
+ }
792
862
  markInputOrResult(mc.destination);
793
863
  for (const s of mc.sources) {
794
864
  markInputOrResult(s);
@@ -958,87 +1028,253 @@ function verifyOwnerTransaction(input) {
958
1028
  allowedAssets.add(assetNorm);
959
1029
  const existing = assetGroups.get(assetNorm) ?? {
960
1030
  sumTotalCap: 0n,
961
- policyIds: []
1031
+ policyIds: [],
1032
+ policies: []
962
1033
  };
963
1034
  existing.sumTotalCap += capAmt;
964
1035
  existing.policyIds.push(p.id);
1036
+ existing.policies.push(p);
965
1037
  assetGroups.set(assetNorm, existing);
966
1038
  }
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");
1039
+ const isCombined = commands.length >= 5 && commands[0]?.$kind === "MoveCall" && commands[0].MoveCall?.module === "spend_account" && commands[0].MoveCall?.function === "new_policy_target";
1040
+ if (!isCombined) {
1041
+ const hasDraftPolicy = uniquePolicies.some((p) => p.status === "draft" || p.onChainPolicyId == null && p.targets && p.targets.length > 0);
1042
+ if (hasDraftPolicy) {
1043
+ throw new TransactionVerificationError("policyId");
1018
1044
  }
1019
- const txSessionCap = parseOptionU64(capBytes);
1020
- const maxInputIdx = markInput(args[3]);
1021
- const maxBytes = getPureBytes(data.inputs[maxInputIdx]);
1022
- if (!maxBytes) {
1045
+ const distinctAssetCount = assetGroups.size;
1046
+ const batchN = commands.length;
1047
+ if (batchN > distinctAssetCount) {
1023
1048
  throw new TransactionVerificationError("caps");
1024
1049
  }
1025
- const txMaxPerPayment = parseOptionU64(maxBytes);
1026
- if (txSessionCap === null || txMaxPerPayment !== txSessionCap) {
1027
- throw new TransactionVerificationError("caps");
1050
+ const seenCoins = /* @__PURE__ */ new Set();
1051
+ const seenPools = /* @__PURE__ */ new Set();
1052
+ for (let i = 0; i < batchN; i++) {
1053
+ const cmd = commands[i];
1054
+ if (cmd.$kind !== "MoveCall") {
1055
+ throw new TransactionVerificationError("unsupportedOperation");
1056
+ }
1057
+ const mc = cmd.MoveCall;
1058
+ if (mc.module !== "spend_account" || mc.function !== "create_policy_grant") {
1059
+ throw new TransactionVerificationError("target");
1060
+ }
1061
+ const mcTypes = mc.typeArguments;
1062
+ if (mcTypes.length !== 1) {
1063
+ throw new TransactionVerificationError("coinType");
1064
+ }
1065
+ const cmdCoinType2 = safeNormalizeStructTag(mcTypes[0]);
1066
+ if (!cmdCoinType2 || !allowedAssets.has(cmdCoinType2)) {
1067
+ throw new TransactionVerificationError("coinType");
1068
+ }
1069
+ if (seenCoins.has(cmdCoinType2)) {
1070
+ throw new TransactionVerificationError("coinType");
1071
+ }
1072
+ seenCoins.add(cmdCoinType2);
1073
+ const groupInfo2 = assetGroups.get(cmdCoinType2);
1074
+ const args = mc.arguments;
1075
+ if (args.length !== 6) {
1076
+ throw new TransactionVerificationError("target");
1077
+ }
1078
+ const poolInputIdx2 = markInput(args[0]);
1079
+ const poolId2 = getObjectIdFromInput(data.inputs[poolInputIdx2]);
1080
+ if (!poolId2) {
1081
+ throw new TransactionVerificationError("pool");
1082
+ }
1083
+ if (seenPools.has(poolId2)) {
1084
+ throw new TransactionVerificationError("pool");
1085
+ }
1086
+ seenPools.add(poolId2);
1087
+ const delInputIdx2 = markInput(args[1]);
1088
+ const delBytes2 = getPureBytes(data.inputs[delInputIdx2]);
1089
+ if (!delBytes2 || parseAddress(delBytes2) !== safeNormalizeAddress(op.delegate.address)) {
1090
+ throw new TransactionVerificationError("delegate");
1091
+ }
1092
+ const capInputIdx2 = markInput(args[2]);
1093
+ const capBytes2 = getPureBytes(data.inputs[capInputIdx2]);
1094
+ if (!capBytes2) {
1095
+ throw new TransactionVerificationError("caps");
1096
+ }
1097
+ const txSessionCap2 = parseOptionU64(capBytes2);
1098
+ const maxInputIdx2 = markInput(args[3]);
1099
+ const maxBytes2 = getPureBytes(data.inputs[maxInputIdx2]);
1100
+ if (!maxBytes2) {
1101
+ throw new TransactionVerificationError("caps");
1102
+ }
1103
+ const txMaxPerPayment2 = parseOptionU64(maxBytes2);
1104
+ if (txSessionCap2 === null || txMaxPerPayment2 !== txSessionCap2) {
1105
+ throw new TransactionVerificationError("caps");
1106
+ }
1107
+ if (txSessionCap2 > groupInfo2.sumTotalCap) {
1108
+ throw new TransactionVerificationError("caps");
1109
+ }
1110
+ assertPureU64(args[4], 0n, "expiry");
1111
+ const pIdsInputIdx = markInput(args[5]);
1112
+ const pIdsBytes = getPureBytes(data.inputs[pIdsInputIdx]);
1113
+ if (!pIdsBytes) {
1114
+ throw new TransactionVerificationError("policyId");
1115
+ }
1116
+ const parsedPids = bcs.vector(bcs.u64()).parse(pIdsBytes);
1117
+ const expectedOnChainIds = groupInfo2.policies.map((p) => p.onChainPolicyId != null ? String(p.onChainPolicyId) : null).filter((id) => id != null);
1118
+ if (expectedOnChainIds.length === 0 || expectedOnChainIds.length !== groupInfo2.policies.length || parsedPids.length !== expectedOnChainIds.length) {
1119
+ throw new TransactionVerificationError("policyId");
1120
+ }
1121
+ for (let idx = 0; idx < parsedPids.length; idx++) {
1122
+ if (String(parsedPids[idx]) !== expectedOnChainIds[idx]) {
1123
+ throw new TransactionVerificationError("policyId");
1124
+ }
1125
+ }
1028
1126
  }
1029
- if (txSessionCap > groupInfo.sumTotalCap) {
1030
- throw new TransactionVerificationError("caps");
1127
+ break;
1128
+ }
1129
+ if (uniquePolicies.length !== 1) {
1130
+ throw new TransactionVerificationError("targets");
1131
+ }
1132
+ const draftPolicy = uniquePolicies[0];
1133
+ let N = 0;
1134
+ while (N < commands.length && commands[N]?.$kind === "MoveCall" && commands[N].MoveCall?.module === "spend_account" && commands[N].MoveCall?.function === "new_policy_target") {
1135
+ N++;
1136
+ }
1137
+ if (!draftPolicy.targets || draftPolicy.targets.length !== N) {
1138
+ throw new TransactionVerificationError("targets");
1139
+ }
1140
+ if (commands.length !== N + 4) {
1141
+ throw new TransactionVerificationError("targets");
1142
+ }
1143
+ for (let i = 0; i < N; i++) {
1144
+ const c = commands[i];
1145
+ const mc = c.MoveCall;
1146
+ if (mc.arguments.length !== 3) {
1147
+ throw new TransactionVerificationError("target");
1031
1148
  }
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");
1149
+ const expectedTarget = draftPolicy.targets[i];
1150
+ const hashIdx = markInput(mc.arguments[0]);
1151
+ const hashBytes = getPureBytes(data.inputs[hashIdx]);
1152
+ const hash = hashBytes ? bcs.vector(bcs.u8()).parse(hashBytes) : null;
1153
+ const got = hash ? [...hash].map((byte) => byte.toString(16).padStart(2, "0")).join("") : "";
1154
+ const want = expectedTarget.targetHash.trim().toLowerCase().replace(/^0x/, "");
1155
+ if (!hash || got !== want)
1156
+ throw new TransactionVerificationError("target");
1157
+ const recipientIdx = markInput(mc.arguments[1]);
1158
+ const recipientBytes = getPureBytes(data.inputs[recipientIdx]);
1159
+ if (!recipientBytes || parseAddress(recipientBytes) !== safeNormalizeAddress(expectedTarget.recipient)) {
1160
+ throw new TransactionVerificationError("target");
1037
1161
  }
1038
- if (parseVectorU64Len(pIdsBytes) > groupInfo.policyIds.length) {
1039
- throw new TransactionVerificationError("policyId");
1162
+ assertPureU64(mc.arguments[2], BigInt(expectedTarget.maxPerPayment), "target");
1163
+ }
1164
+ const vecCmd = commands[N];
1165
+ if (vecCmd.$kind !== "MakeMoveVec") {
1166
+ throw new TransactionVerificationError("unsupportedOperation");
1167
+ }
1168
+ const targetElements = vecCmd.MakeMoveVec?.elements;
1169
+ if (!Array.isArray(targetElements) || targetElements.length !== N) {
1170
+ throw new TransactionVerificationError("targets");
1171
+ }
1172
+ for (let i = 0; i < N; i++) {
1173
+ const el = markResult(targetElements[i], "targets");
1174
+ if (el.cmdIndex !== i || el.resIndex !== 0) {
1175
+ throw new TransactionVerificationError("targets");
1040
1176
  }
1041
1177
  }
1178
+ const createPolicyCmd = commands[N + 1];
1179
+ if (createPolicyCmd.$kind !== "MoveCall" || createPolicyCmd.MoveCall?.module !== "spend_account" || createPolicyCmd.MoveCall?.function !== "create_spend_policy") {
1180
+ throw new TransactionVerificationError("target");
1181
+ }
1182
+ const policyTypes = createPolicyCmd.MoveCall.typeArguments;
1183
+ if (!policyTypes || policyTypes.length !== 1) {
1184
+ throw new TransactionVerificationError("coinType");
1185
+ }
1186
+ const cmdCoinType = safeNormalizeStructTag(policyTypes[0]);
1187
+ if (!cmdCoinType || !allowedAssets.has(cmdCoinType)) {
1188
+ throw new TransactionVerificationError("coinType");
1189
+ }
1190
+ const groupInfo = assetGroups.get(cmdCoinType);
1191
+ const policyArgs = createPolicyCmd.MoveCall.arguments;
1192
+ if (!policyArgs || policyArgs.length !== 5) {
1193
+ throw new TransactionVerificationError("target");
1194
+ }
1195
+ const poolInputIdx = markInput(policyArgs[0]);
1196
+ const poolId = getObjectIdFromInput(data.inputs[poolInputIdx]);
1197
+ if (!poolId) {
1198
+ throw new TransactionVerificationError("pool");
1199
+ }
1200
+ const targetsRes = markResult(policyArgs[1], "unsupportedOperation");
1201
+ if (targetsRes.cmdIndex !== N || targetsRes.resIndex !== 0) {
1202
+ throw new TransactionVerificationError("unsupportedOperation");
1203
+ }
1204
+ const totalCapInputIdx = markInput(policyArgs[2]);
1205
+ const totalCapBytes = getPureBytes(data.inputs[totalCapInputIdx]);
1206
+ if (!totalCapBytes)
1207
+ throw new TransactionVerificationError("caps");
1208
+ const policyTotalCap = parseU64(totalCapBytes);
1209
+ if (policyTotalCap <= 0n || policyTotalCap > groupInfo.sumTotalCap || policyTotalCap !== BigInt(draftPolicy.totalCap)) {
1210
+ throw new TransactionVerificationError("caps");
1211
+ }
1212
+ const maxPerPaymentInputIdx = markInput(policyArgs[3]);
1213
+ const maxPerPaymentBytes = getPureBytes(data.inputs[maxPerPaymentInputIdx]);
1214
+ if (!maxPerPaymentBytes)
1215
+ throw new TransactionVerificationError("caps");
1216
+ const policyMaxPerPayment = parseU64(maxPerPaymentBytes);
1217
+ if (policyMaxPerPayment <= 0n || policyMaxPerPayment > policyTotalCap || draftPolicy.maxPerPayment == null || policyMaxPerPayment !== BigInt(draftPolicy.maxPerPayment)) {
1218
+ throw new TransactionVerificationError("caps");
1219
+ }
1220
+ assertPureU64(policyArgs[4], callerExpiryU64(draftPolicy.expiresAtMs), "expiry");
1221
+ const idVecCmd = commands[N + 2];
1222
+ if (idVecCmd.$kind !== "MakeMoveVec" || !Array.isArray(idVecCmd.MakeMoveVec?.elements) || idVecCmd.MakeMoveVec.elements.length !== 1) {
1223
+ throw new TransactionVerificationError("policyId");
1224
+ }
1225
+ const policyRes = markResult(idVecCmd.MakeMoveVec.elements[0], "policyId");
1226
+ if (policyRes.cmdIndex !== N + 1 || policyRes.resIndex !== 0) {
1227
+ throw new TransactionVerificationError("policyId");
1228
+ }
1229
+ const grantCmd = commands[N + 3];
1230
+ if (grantCmd.$kind !== "MoveCall" || grantCmd.MoveCall?.module !== "spend_account" || grantCmd.MoveCall?.function !== "create_policy_grant") {
1231
+ throw new TransactionVerificationError("target");
1232
+ }
1233
+ const grantTypes = grantCmd.MoveCall.typeArguments;
1234
+ if (!grantTypes || grantTypes.length !== 1) {
1235
+ throw new TransactionVerificationError("coinType");
1236
+ }
1237
+ const grantCoinType = safeNormalizeStructTag(grantTypes[0]);
1238
+ if (grantCoinType !== cmdCoinType) {
1239
+ throw new TransactionVerificationError("coinType");
1240
+ }
1241
+ const grantArgs = grantCmd.MoveCall.arguments;
1242
+ if (!grantArgs || grantArgs.length !== 6) {
1243
+ throw new TransactionVerificationError("target");
1244
+ }
1245
+ const grantPoolInputIdx = markInput(grantArgs[0]);
1246
+ const grantPoolId = getObjectIdFromInput(data.inputs[grantPoolInputIdx]);
1247
+ if (!grantPoolId || grantPoolId !== poolId) {
1248
+ throw new TransactionVerificationError("pool");
1249
+ }
1250
+ const delInputIdx = markInput(grantArgs[1]);
1251
+ const delBytes = getPureBytes(data.inputs[delInputIdx]);
1252
+ if (!delBytes || parseAddress(delBytes) !== safeNormalizeAddress(op.delegate.address)) {
1253
+ throw new TransactionVerificationError("delegate");
1254
+ }
1255
+ const capInputIdx = markInput(grantArgs[2]);
1256
+ const capBytes = getPureBytes(data.inputs[capInputIdx]);
1257
+ if (!capBytes) {
1258
+ throw new TransactionVerificationError("caps");
1259
+ }
1260
+ const txSessionCap = parseOptionU64(capBytes);
1261
+ const maxInputIdx = markInput(grantArgs[3]);
1262
+ const maxBytes = getPureBytes(data.inputs[maxInputIdx]);
1263
+ if (!maxBytes) {
1264
+ throw new TransactionVerificationError("caps");
1265
+ }
1266
+ const txMaxPerPayment = parseOptionU64(maxBytes);
1267
+ if (txSessionCap === null || txMaxPerPayment !== txSessionCap) {
1268
+ throw new TransactionVerificationError("caps");
1269
+ }
1270
+ if (txSessionCap > groupInfo.sumTotalCap) {
1271
+ throw new TransactionVerificationError("caps");
1272
+ }
1273
+ assertPureU64(grantArgs[4], 0n, "expiry");
1274
+ const grantVecRes = markResult(grantArgs[5], "policyId");
1275
+ if (grantVecRes.cmdIndex !== N + 2 || grantVecRes.resIndex !== 0) {
1276
+ throw new TransactionVerificationError("policyId");
1277
+ }
1042
1278
  break;
1043
1279
  }
1044
1280
  case "create_grant_open": {
@@ -1481,6 +1717,46 @@ async function executeSignedDigest(transport, input) {
1481
1717
  return ok({ digest: confirmed });
1482
1718
  }
1483
1719
 
1720
+ // ../sdk/dist/buyer/owner-anchors.js
1721
+ var SCOPED_GRANT_FN = "create_policy_grant";
1722
+ var OPEN_GRANT_FN = "create_open_recipient_grant";
1723
+ function declaredAsset(asset, assets = TESTNET_ASSETS) {
1724
+ if (typeof asset !== "string")
1725
+ return null;
1726
+ const trimmed = asset.trim();
1727
+ const byLabel = assets.find((a) => a.id === trimmed.toLowerCase());
1728
+ if (byLabel)
1729
+ return byLabel;
1730
+ const byCoin = supportedAssetByCoinType(trimmed);
1731
+ return byCoin && assets.some((a) => a.id === byCoin.id) ? byCoin : null;
1732
+ }
1733
+ function assertMoveFunction(target, expected) {
1734
+ const fn = typeof target === "string" ? target.split("::").at(-1) : void 0;
1735
+ if (fn !== expected)
1736
+ throw new TransactionVerificationError("target");
1737
+ }
1738
+ function assertPreparedGrantScopes(scopes, prepared, submitted = [], assets = TESTNET_ASSETS) {
1739
+ const declared = /* @__PURE__ */ new Set();
1740
+ for (const scope of scopes) {
1741
+ const asset = declaredAsset(scope.asset, assets);
1742
+ if (!asset || declared.has(asset.id))
1743
+ throw new TransactionVerificationError("coinType");
1744
+ declared.add(asset.id);
1745
+ }
1746
+ const seenAssets = /* @__PURE__ */ new Set();
1747
+ const seenIds = /* @__PURE__ */ new Set();
1748
+ for (const grant of [...prepared, ...submitted]) {
1749
+ const asset = "coinType" in grant && typeof grant.coinType === "string" && declaredAsset(grant.coinType, assets) || declaredAsset(grant.asset, assets);
1750
+ if (!asset || !declared.has(asset.id))
1751
+ throw new TransactionVerificationError("coinType");
1752
+ if (seenAssets.has(asset.id) || seenIds.has(grant.grantId)) {
1753
+ throw new TransactionVerificationError("grants");
1754
+ }
1755
+ seenAssets.add(asset.id);
1756
+ seenIds.add(grant.grantId);
1757
+ }
1758
+ }
1759
+
1484
1760
  // ../sdk/dist/buyer/v1/delegated-signers.js
1485
1761
  function createAgentsApi(transport) {
1486
1762
  async function list() {
@@ -1579,27 +1855,48 @@ function createAgentsApi(transport) {
1579
1855
  const created = await create(input);
1580
1856
  if (!created.ok)
1581
1857
  return created;
1858
+ assertPreparedGrantScopes(input.assetScopes, created.value.grants, created.value.submitted);
1582
1859
  const finalized = [];
1860
+ for (const submitted of created.value.submitted ?? []) {
1861
+ const fin = await finalizeGrant(created.value.delegatedSignerId, submitted.grantId, submitted.digest);
1862
+ if (!fin.ok)
1863
+ return fin;
1864
+ finalized.push(fin.value);
1865
+ }
1583
1866
  for (const grant of created.value.grants) {
1584
- const scope = input.assetScopes.find((s) => s.asset.toLowerCase() === grant.asset.toLowerCase() || supportedAssetByCoinType(s.asset)?.id === grant.asset.toLowerCase());
1585
- const coinType = TESTNET_ASSETS.find((a) => a.id === grant.asset.toLowerCase() || a.symbol.toLowerCase() === grant.asset.toLowerCase())?.coinType ?? scope?.asset ?? grant.asset;
1586
- const isTargetOpen = grant.moveTarget.endsWith("::create_open_recipient_grant");
1587
- const operation = isTargetOpen ? {
1588
- kind: "create_grant_open",
1589
- coinType,
1590
- delegate: { address: input.agentAddress, source: "independent" },
1591
- sessionCap: scope?.totalBudgetAtomic != null ? BigInt(scope.totalBudgetAtomic) : null,
1592
- maxPerPayment: scope?.maxPerPaymentAtomic != null ? BigInt(scope.maxPerPaymentAtomic) : null,
1593
- expiresAtMs: scope?.expiresAt != null ? String(scope.expiresAt) : "0"
1594
- } : {
1595
- kind: "create_grant_scoped",
1596
- coinType,
1597
- delegate: { address: input.agentAddress, source: "independent" },
1598
- sessionCap: scope?.totalBudgetAtomic ?? null,
1599
- maxPerPayment: scope?.maxPerPaymentAtomic ?? null,
1600
- expiresAtMs: scope?.expiresAt != null ? String(scope.expiresAt) : "0",
1601
- ...input.policyIds !== void 0 ? { policyIdCount: input.policyIds.length } : {}
1602
- };
1867
+ const open = input.accessMode === "open";
1868
+ assertMoveFunction(grant.moveTarget, open ? OPEN_GRANT_FN : SCOPED_GRANT_FN);
1869
+ const grantAsset = declaredAsset(grant.coinType) ?? declaredAsset(grant.asset);
1870
+ const scope = grantAsset ? input.assetScopes.find((s) => declaredAsset(s.asset)?.id === grantAsset.id) : void 0;
1871
+ if (!grantAsset || !scope)
1872
+ throw new TransactionVerificationError("coinType");
1873
+ const coinType = grantAsset.coinType;
1874
+ const delegate = { address: input.agentAddress, source: "independent" };
1875
+ const expiresAtMs = scope.expiresAt != null ? String(scope.expiresAt) : "0";
1876
+ let operation;
1877
+ if (open) {
1878
+ if (scope.totalBudgetAtomic == null || scope.maxPerPaymentAtomic == null) {
1879
+ throw new TransactionVerificationError("caps");
1880
+ }
1881
+ operation = {
1882
+ kind: "create_grant_open",
1883
+ coinType,
1884
+ delegate,
1885
+ sessionCap: BigInt(scope.totalBudgetAtomic),
1886
+ maxPerPayment: BigInt(scope.maxPerPaymentAtomic),
1887
+ expiresAtMs
1888
+ };
1889
+ } else {
1890
+ operation = {
1891
+ kind: "create_grant_scoped",
1892
+ coinType,
1893
+ delegate,
1894
+ sessionCap: scope.totalBudgetAtomic,
1895
+ maxPerPayment: scope.maxPerPaymentAtomic,
1896
+ expiresAtMs,
1897
+ ...input.policyIds !== void 0 ? { policyIdCount: input.policyIds.length } : {}
1898
+ };
1899
+ }
1603
1900
  const signed = await sponsorAndSignKind(transport, {
1604
1901
  kindBytes: grant.txKindBytes,
1605
1902
  sender: signerRes.value.address,
@@ -1817,41 +2114,97 @@ function createPoliciesApi(transport, intents) {
1817
2114
  return fail(response);
1818
2115
  return ok(parsed.intent);
1819
2116
  }
1820
- async function getPoolObjectId(asset, coinType) {
2117
+ async function getPoolObjectId(assetId, coinType) {
1821
2118
  const response = await transport.request("/v1/buyer/pools");
1822
2119
  if (response.status !== 200 || !isRecord(response.body) || !Array.isArray(response.body.pools)) {
1823
2120
  return null;
1824
2121
  }
1825
2122
  const pools = asDto(response.body.pools);
1826
- const found = pools.find((p) => p.asset.toLowerCase() === asset.toLowerCase() || p.coinType.toLowerCase() === coinType.toLowerCase() || supportedAssetByCoinType(p.coinType)?.id === asset.toLowerCase());
2123
+ const found = pools.find((p) => declaredAsset(p.coinType)?.coinType === coinType || declaredAsset(p.asset)?.id === assetId);
1827
2124
  return found?.objectId ?? null;
1828
2125
  }
1829
- async function activate(id, signer) {
2126
+ function readExpectation(options) {
2127
+ if (!isRecord(options) || !isRecord(options.expected))
2128
+ return null;
2129
+ const e = options.expected;
2130
+ const asset = declaredAsset(e.asset);
2131
+ if (!asset)
2132
+ return null;
2133
+ const positive = (v) => typeof v === "string" && /^[1-9][0-9]*$/.test(v);
2134
+ if (!positive(e.totalCap) || !positive(e.maxPerPayment))
2135
+ return null;
2136
+ if (!Number.isInteger(e.targetCount) || e.targetCount < 1)
2137
+ return null;
2138
+ const exp = e.expiresAt;
2139
+ if (exp != null && typeof exp !== "string" && typeof exp !== "number")
2140
+ return null;
2141
+ return {
2142
+ asset,
2143
+ terms: {
2144
+ asset: e.asset,
2145
+ totalCap: e.totalCap,
2146
+ maxPerPayment: e.maxPerPayment,
2147
+ expiresAt: exp,
2148
+ targetCount: e.targetCount
2149
+ }
2150
+ };
2151
+ }
2152
+ async function activate(id, options) {
2153
+ const read = readExpectation(options);
2154
+ if (!read) {
2155
+ return failLocal(400, "request.invalid", "not_charged", {
2156
+ message: "policies.activate needs options.expected: the asset, totalCap, maxPerPayment, expiresAt and targetCount the policy was created with"
2157
+ });
2158
+ }
2159
+ const { terms: expected, asset } = read;
1830
2160
  const policyRes = await get(id);
1831
2161
  if (!policyRes.ok)
1832
2162
  return policyRes;
1833
2163
  const policy = policyRes.value;
1834
- const poolObjectId = await getPoolObjectId(policy.asset, policy.coinType);
2164
+ const rowAsset = declaredAsset(policy.asset) ?? declaredAsset(policy.coinType);
2165
+ if (rowAsset?.id !== asset.id) {
2166
+ return failLocal(400, "request.invalid", "not_charged", {
2167
+ message: `Policy ${id} is for ${policy.asset}, not the expected asset ${asset.id}`
2168
+ });
2169
+ }
2170
+ const poolObjectId = await getPoolObjectId(asset.id, asset.coinType);
1835
2171
  if (!poolObjectId) {
1836
2172
  return failLocal(400, "request.invalid", "not_charged", {
1837
- message: `No active spend account pool found for asset ${policy.asset}`
2173
+ message: `No active spend account pool found for asset ${asset.id}`
1838
2174
  });
1839
2175
  }
1840
- 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);
1841
- const coinType = assetMatch?.coinType ?? policy.coinType;
1842
2176
  const operation = {
1843
2177
  kind: "create_policy",
1844
- coinType,
2178
+ coinType: asset.coinType,
1845
2179
  poolObjectId,
1846
- totalCap: policy.totalCap,
1847
- maxPerPayment: policy.maxPerPayment,
1848
- expiresAtMs: policy.expiresAt ? Date.parse(policy.expiresAt) : "0",
1849
- targetCount: policy.targets?.length ?? 0
2180
+ totalCap: expected.totalCap,
2181
+ maxPerPayment: expected.maxPerPayment,
2182
+ expiresAtMs: expected.expiresAt ?? "0",
2183
+ targetCount: expected.targetCount
1850
2184
  };
1851
2185
  const prepared = await prepareAction(id, "/prepare");
1852
2186
  if (!prepared.ok)
1853
2187
  return prepared;
1854
- return intents.execute(prepared.value, operation, signer);
2188
+ return intents.execute(prepared.value, operation, options.signer);
2189
+ }
2190
+ async function createAndActivate(input, signer) {
2191
+ const created = await create(input);
2192
+ if (!created.ok)
2193
+ return created;
2194
+ const serviceIds = new Set(input.serviceIds.map((s) => s.trim()).filter(Boolean));
2195
+ const activated = await activate(created.value.id, {
2196
+ expected: {
2197
+ asset: input.asset,
2198
+ totalCap: input.totalCap,
2199
+ maxPerPayment: input.maxPerPayment,
2200
+ expiresAt: input.expiresAt ?? null,
2201
+ targetCount: serviceIds.size
2202
+ },
2203
+ ...signer ? { signer } : {}
2204
+ });
2205
+ if (!activated.ok)
2206
+ return activated;
2207
+ return ok({ ...activated.value, policy: created.value }, activated.status);
1855
2208
  }
1856
2209
  async function runLifecycle(id, action, suffix, signer) {
1857
2210
  const policyRes = await get(id);
@@ -1863,18 +2216,22 @@ function createPoliciesApi(transport, intents) {
1863
2216
  message: `Policy ${id} is not active on-chain (missing onChainPolicyId)`
1864
2217
  });
1865
2218
  }
1866
- const poolObjectId = await getPoolObjectId(policy.asset, policy.coinType);
2219
+ const asset = declaredAsset(policy.asset) ?? declaredAsset(policy.coinType);
2220
+ if (!asset) {
2221
+ return failLocal(400, "request.invalid", "not_charged", {
2222
+ message: `Unsupported asset ${policy.asset} for policy ${id}`
2223
+ });
2224
+ }
2225
+ const poolObjectId = await getPoolObjectId(asset.id, asset.coinType);
1867
2226
  if (!poolObjectId) {
1868
2227
  return failLocal(400, "request.invalid", "not_charged", {
1869
- message: `No active spend account pool found for asset ${policy.asset}`
2228
+ message: `No active spend account pool found for asset ${asset.id}`
1870
2229
  });
1871
2230
  }
1872
- 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);
1873
- const coinType = assetMatch?.coinType ?? policy.coinType;
1874
2231
  const operation = {
1875
2232
  kind: "policy_lifecycle",
1876
2233
  action,
1877
- coinType,
2234
+ coinType: asset.coinType,
1878
2235
  poolObjectId,
1879
2236
  onChainPolicyId: policy.onChainPolicyId
1880
2237
  };
@@ -1892,6 +2249,7 @@ function createPoliciesApi(transport, intents) {
1892
2249
  prepareResume: (id) => prepareAction(id, "/resume/prepare"),
1893
2250
  prepareRevoke: (id) => prepareAction(id, "/revoke/prepare"),
1894
2251
  activate,
2252
+ createAndActivate,
1895
2253
  pause: (id, signer) => runLifecycle(id, "pause", "/pause/prepare", signer),
1896
2254
  resume: (id, signer) => runLifecycle(id, "resume", "/resume/prepare", signer),
1897
2255
  revoke: (id, signer) => runLifecycle(id, "revoke", "/revoke/prepare", signer)
@@ -2012,16 +2370,16 @@ function createSessionsApi(transport, intents) {
2012
2370
  message: "No delegate address provided or found in connection listing"
2013
2371
  });
2014
2372
  }
2015
- const declaredAsset = input.asset ?? conn?.asset;
2016
- if (!declaredAsset) {
2373
+ const declaredAsset2 = input.asset ?? conn?.asset;
2374
+ if (!declaredAsset2) {
2017
2375
  return failLocal(400, "request.invalid", "not_charged", {
2018
2376
  message: "No declared asset provided for grant"
2019
2377
  });
2020
2378
  }
2021
- const assetMatch = TESTNET_ASSETS.find((a) => a.id === declaredAsset.toLowerCase() || a.symbol.toLowerCase() === declaredAsset.toLowerCase() || a.coinType.toLowerCase() === declaredAsset.toLowerCase());
2379
+ const assetMatch = TESTNET_ASSETS.find((a) => a.id === declaredAsset2.toLowerCase() || a.symbol.toLowerCase() === declaredAsset2.toLowerCase() || a.coinType.toLowerCase() === declaredAsset2.toLowerCase());
2022
2380
  if (!assetMatch) {
2023
2381
  return failLocal(400, "request.invalid", "not_charged", {
2024
- message: `Unsupported asset ${declaredAsset} for grant`
2382
+ message: `Unsupported asset ${declaredAsset2} for grant`
2025
2383
  });
2026
2384
  }
2027
2385
  const coinType = assetMatch.coinType;
@@ -2180,7 +2538,7 @@ function createBuyerControlPlane(options) {
2180
2538
  var createBuyer = createBuyerControlPlane;
2181
2539
 
2182
2540
  // ../sdk/dist/agent-sdk/delegate-agent.js
2183
- import { normalizeSuiAddress as normalizeSuiAddress11 } from "@mysten/sui/utils";
2541
+ import { normalizeSuiAddress as normalizeSuiAddress12 } from "@mysten/sui/utils";
2184
2542
 
2185
2543
  // ../sdk/dist/buyer-control/chain.js
2186
2544
  import { bcs as bcs2 } from "@mysten/sui/bcs";
@@ -2247,7 +2605,30 @@ function createFailoverGrpcClient(options) {
2247
2605
  const clients = endpoints.map((baseUrl) => new SuiGrpcClient({ network: options.network, baseUrl }));
2248
2606
  return wrapFailover(clients, { sleep: endpointRetrySleep });
2249
2607
  }
2250
- var FAILOVER_SERVICES = ["core", "ledgerService"];
2608
+ var FAILOVER_SERVICES = ["core", "ledgerService", "movePackageService"];
2609
+ var UNARY_RESULT_PROPERTIES = ["headers", "response", "status", "trailers"];
2610
+ function isUnaryCall(value) {
2611
+ return "method" in value && "request" in value && "requestHeaders" in value && UNARY_RESULT_PROPERTIES.every((prop) => typeof value[prop]?.then === "function");
2612
+ }
2613
+ function unaryCallWithFailover(first, finished) {
2614
+ const then = finished.then.bind(finished);
2615
+ const properties = /* @__PURE__ */ new Map();
2616
+ return new Proxy(first, {
2617
+ get(target, prop) {
2618
+ if (prop === "then")
2619
+ return then;
2620
+ if (UNARY_RESULT_PROPERTIES.includes(prop)) {
2621
+ let value = properties.get(prop);
2622
+ if (!value) {
2623
+ value = finished.then((call) => call[prop]);
2624
+ properties.set(prop, value);
2625
+ }
2626
+ return value;
2627
+ }
2628
+ return Reflect.get(target, prop, target);
2629
+ }
2630
+ });
2631
+ }
2251
2632
  function wrapFailover(clients, options = {}) {
2252
2633
  const primary = clients[0];
2253
2634
  const attempts = Math.max(1, options.attempts ?? RPC_ATTEMPTS_PER_ENDPOINT);
@@ -2265,10 +2646,14 @@ function wrapFailover(clients, options = {}) {
2265
2646
  return (...args) => {
2266
2647
  const first = callOn(primary, prop, args);
2267
2648
  const attemptsFor = prop === "executeTransaction" ? 1 : attempts;
2268
- if (first == null || typeof first.then !== "function" || typeof first.catch !== "function") {
2649
+ if (first == null || typeof first.then !== "function") {
2269
2650
  return first;
2270
2651
  }
2271
- return (async () => {
2652
+ const promise = typeof first.catch === "function";
2653
+ const unary = !promise && typeof first === "object" && isUnaryCall(first);
2654
+ if (!promise && !unary)
2655
+ return first;
2656
+ const finished = (async () => {
2272
2657
  let last;
2273
2658
  for (let endpoint = 0; endpoint < clients.length; endpoint++) {
2274
2659
  for (let attempt = 0; attempt < attemptsFor; attempt++) {
@@ -2290,6 +2675,7 @@ function wrapFailover(clients, options = {}) {
2290
2675
  }
2291
2676
  throw last;
2292
2677
  })();
2678
+ return unary ? unaryCallWithFailover(first, finished) : finished;
2293
2679
  };
2294
2680
  }
2295
2681
  });
@@ -2313,7 +2699,7 @@ function wrapFailover(clients, options = {}) {
2313
2699
 
2314
2700
  // ../sdk/dist/buyer-control/chain.js
2315
2701
  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";
2702
+ import { fromBase64 as fromBase643, normalizeStructTag as normalizeStructTag6, normalizeSuiAddress as normalizeSuiAddress3, toBase64 } from "@mysten/sui/utils";
2317
2703
 
2318
2704
  // ../core/dist/chain/address.js
2319
2705
  function hexOf(address) {
@@ -2357,7 +2743,7 @@ function objectTypeFromGetObject(object) {
2357
2743
 
2358
2744
  // ../core/dist/policy/target.js
2359
2745
  import { createHash } from "crypto";
2360
- import { normalizeStructTag as normalizeStructTag3 } from "@mysten/sui/utils";
2746
+ import { normalizeStructTag as normalizeStructTag5 } from "@mysten/sui/utils";
2361
2747
 
2362
2748
  // ../core/dist/service-state/index.js
2363
2749
  var STATE_DIMENSIONS = Object.freeze([
@@ -2574,6 +2960,14 @@ var SERVICE_STATE_TRANSITIONS = Object.freeze([
2574
2960
  to: "payout_change",
2575
2961
  actors: ["system"],
2576
2962
  requires: ["reason_code"]
2963
+ },
2964
+ {
2965
+ id: "T25",
2966
+ dimension: "suspension",
2967
+ from: ["binding_changed"],
2968
+ to: "none",
2969
+ actors: ["system"],
2970
+ requires: ["reason_code"]
2577
2971
  }
2578
2972
  ]);
2579
2973
 
@@ -2743,7 +3137,7 @@ var MODULE = "spend_account";
2743
3137
  var SUI_COIN_TYPE = "0x2::sui::SUI";
2744
3138
  function isSuiCoinType(coinType) {
2745
3139
  try {
2746
- return normalizeStructTag4(coinType) === normalizeStructTag4(SUI_COIN_TYPE);
3140
+ return normalizeStructTag6(coinType) === normalizeStructTag6(SUI_COIN_TYPE);
2747
3141
  } catch {
2748
3142
  return /::sui::SUI$/i.test(coinType);
2749
3143
  }
@@ -2973,6 +3367,70 @@ function createSpendAccountChain(options) {
2973
3367
  });
2974
3368
  return kindBytes(tx);
2975
3369
  },
3370
+ async buildCreatePolicyAndGrantKind(input) {
3371
+ if (!input.policy.targets?.length) {
3372
+ throw new Error("create_spend_policy requires at least one target");
3373
+ }
3374
+ if (!input.policy.totalCap || BigInt(input.policy.totalCap) <= 0n) {
3375
+ throw new Error("create_spend_policy requires a non-zero total_cap");
3376
+ }
3377
+ if (!input.policy.maxPerPayment || BigInt(input.policy.maxPerPayment) <= 0n) {
3378
+ throw new Error("create_spend_policy requires a non-zero max_per_payment");
3379
+ }
3380
+ if (!input.grant.sessionCap || BigInt(input.grant.sessionCap) <= 0n) {
3381
+ throw new Error("create_grant requires a non-zero session_cap");
3382
+ }
3383
+ if (!input.grant.maxPerPayment || BigInt(input.grant.maxPerPayment) <= 0n) {
3384
+ throw new Error("create_grant requires a non-zero max_per_payment");
3385
+ }
3386
+ const tx = new Transaction2();
3387
+ tx.setSender(input.owner);
3388
+ const targetResults = input.policy.targets.map((t) => {
3389
+ const hash = targetHashBytes(t.targetHash);
3390
+ return tx.moveCall({
3391
+ target: target("new_policy_target"),
3392
+ arguments: [
3393
+ tx.pure.vector("u8", Array.from(hash)),
3394
+ tx.pure.address(t.recipient),
3395
+ tx.pure.u64(BigInt(t.maxPerPayment))
3396
+ ]
3397
+ });
3398
+ });
3399
+ const targetsVec = tx.makeMoveVec({
3400
+ type: `${packageId}::${MODULE}::PolicyTarget`,
3401
+ elements: targetResults
3402
+ });
3403
+ const policyExpires = input.policy.expiresAtMs === void 0 || input.policy.expiresAtMs === null ? 0n : BigInt(input.policy.expiresAtMs);
3404
+ const policyIdResult = tx.moveCall({
3405
+ target: target("create_spend_policy"),
3406
+ typeArguments: [input.coinType],
3407
+ arguments: [
3408
+ tx.object(input.poolObjectId),
3409
+ targetsVec,
3410
+ tx.pure.u64(BigInt(input.policy.totalCap)),
3411
+ tx.pure.u64(BigInt(input.policy.maxPerPayment)),
3412
+ tx.pure.u64(policyExpires)
3413
+ ]
3414
+ });
3415
+ const policyIdsVec = tx.makeMoveVec({
3416
+ type: "u64",
3417
+ elements: [policyIdResult]
3418
+ });
3419
+ const grantExpires = input.grant.expiresAtMs === void 0 || input.grant.expiresAtMs === null ? 0n : BigInt(input.grant.expiresAtMs);
3420
+ tx.moveCall({
3421
+ target: target("create_policy_grant"),
3422
+ typeArguments: [input.coinType],
3423
+ arguments: [
3424
+ tx.object(input.poolObjectId),
3425
+ tx.pure.address(input.delegate),
3426
+ tx.pure.option("u64", BigInt(input.grant.sessionCap)),
3427
+ tx.pure.option("u64", BigInt(input.grant.maxPerPayment)),
3428
+ tx.pure.u64(grantExpires),
3429
+ policyIdsVec
3430
+ ]
3431
+ });
3432
+ return kindBytes(tx);
3433
+ },
2976
3434
  async buildPausePolicyKind(input) {
2977
3435
  const tx = new Transaction2();
2978
3436
  tx.setSender(input.owner);
@@ -3312,12 +3770,30 @@ function createSpendAccountChain(options) {
3312
3770
  return null;
3313
3771
  }
3314
3772
  },
3315
- async readPolicyBudget({ poolObjectId, onChainPolicyId }) {
3773
+ async readGrantLastChange(grantObjectId) {
3316
3774
  try {
3317
- const response = await client.core.getDynamicField({
3318
- parentId: poolObjectId,
3319
- name: { type: "u64", bcs: bcs2.u64().serialize(onChainPolicyId).toBytes() }
3320
- });
3775
+ const { object } = await client.core.getObject({
3776
+ objectId: grantObjectId,
3777
+ include: { json: true, previousTransaction: true }
3778
+ });
3779
+ const json = object?.json;
3780
+ if (!json || typeof json.revoked !== "boolean")
3781
+ return null;
3782
+ const previous = object?.previousTransaction;
3783
+ return {
3784
+ revoked: json.revoked,
3785
+ previousTransaction: typeof previous === "string" && previous.trim() ? previous.trim() : null
3786
+ };
3787
+ } catch {
3788
+ return null;
3789
+ }
3790
+ },
3791
+ async readPolicyBudget({ poolObjectId, onChainPolicyId }) {
3792
+ try {
3793
+ const response = await client.core.getDynamicField({
3794
+ parentId: poolObjectId,
3795
+ name: { type: "u64", bcs: bcs2.u64().serialize(onChainPolicyId).toBytes() }
3796
+ });
3321
3797
  const value = response?.dynamicField?.value;
3322
3798
  const parsed = parseSpendPolicyBudget(value?.bcs);
3323
3799
  if (!parsed || parsed.id !== BigInt(onChainPolicyId))
@@ -3436,13 +3912,18 @@ var GUARDED_DELEGATE_ARG_LAYOUT = {
3436
3912
  recipient: null,
3437
3913
  amount: 6,
3438
3914
  paymentIdHash: 7,
3439
- expiresAtMs: 9
3915
+ expiresAtMs: 9,
3916
+ // After clock (10): chain id, refund config, decide window, refund window.
3917
+ decideWindowMs: 13,
3918
+ refundWindowMs: 14
3440
3919
  },
3441
3920
  settle_any_recipient_to_refund_vault: {
3442
3921
  recipient: 4,
3443
3922
  amount: 5,
3444
3923
  paymentIdHash: 6,
3445
- expiresAtMs: 9
3924
+ expiresAtMs: 9,
3925
+ decideWindowMs: 13,
3926
+ refundWindowMs: 14
3446
3927
  }
3447
3928
  };
3448
3929
  function pureBytesOf(data, arg) {
@@ -3522,11 +4003,48 @@ function recoverGuardedDelegateCalls(finalized) {
3522
4003
  paymentIdHash: readPureVectorU8Hex(data, args[layout.paymentIdHash]),
3523
4004
  amount: readPureU64(data, args[layout.amount]),
3524
4005
  recipient: layout.recipient === null ? null : readPureAddress(data, args[layout.recipient]),
3525
- expiresAtMs: readPureU64(data, args[layout.expiresAtMs])
4006
+ expiresAtMs: readPureU64(data, args[layout.expiresAtMs]),
4007
+ ..."decideWindowMs" in layout ? {
4008
+ decideWindowMs: readPureU64(data, args[layout.decideWindowMs]),
4009
+ refundWindowMs: readPureU64(data, args[layout.refundWindowMs])
4010
+ } : {}
3526
4011
  });
3527
4012
  }
3528
4013
  return calls;
3529
4014
  }
4015
+ var VAULT_SETTLEMENT_TS_TIMEOUT_MS = 1e4;
4016
+ function withTimeout(work, ms, label) {
4017
+ return new Promise((resolve, reject2) => {
4018
+ const timer = setTimeout(() => reject2(new Error(`${label} timed out after ${ms}ms`)), ms);
4019
+ Promise.resolve(work).then((value) => {
4020
+ clearTimeout(timer);
4021
+ resolve(value);
4022
+ }, (err) => {
4023
+ clearTimeout(timer);
4024
+ reject2(err);
4025
+ });
4026
+ });
4027
+ }
4028
+ async function readVaultSettlementMs(client, digest) {
4029
+ const ledger = client.ledgerService;
4030
+ if (!ledger?.getTransaction)
4031
+ return void 0;
4032
+ try {
4033
+ const call = await withTimeout(ledger.getTransaction({
4034
+ digest,
4035
+ readMask: { paths: ["timestamp"] }
4036
+ }), VAULT_SETTLEMENT_TS_TIMEOUT_MS, "vault settlement timestamp read");
4037
+ const ts = call.response.transaction?.timestamp;
4038
+ if (!ts || ts.seconds === void 0)
4039
+ return void 0;
4040
+ const seconds = Number(ts.seconds);
4041
+ if (!Number.isFinite(seconds))
4042
+ return void 0;
4043
+ return seconds * 1e3 + Math.floor((ts.nanos ?? 0) / 1e6);
4044
+ } catch {
4045
+ return void 0;
4046
+ }
4047
+ }
3530
4048
  function createSpendAccountSettledTxReader(options) {
3531
4049
  const network = toGrpcNetwork(options.network);
3532
4050
  const client = options.client ?? createFailoverGrpcClient({
@@ -3581,6 +4099,7 @@ function createSpendAccountSettledTxReader(options) {
3581
4099
  kind: e.eventType.split("::").pop() ?? e.eventType
3582
4100
  }));
3583
4101
  const guardedDelegateCalls = recoverGuardedDelegateCalls(finalized);
4102
+ const timestampMs = events.some((event) => event.kind === "VaultOpened") ? await readVaultSettlementMs(client, digest) : void 0;
3584
4103
  return {
3585
4104
  status: "success",
3586
4105
  txDigest: digest,
@@ -3588,7 +4107,8 @@ function createSpendAccountSettledTxReader(options) {
3588
4107
  moveCalls,
3589
4108
  objectIds,
3590
4109
  events,
3591
- guardedDelegateCalls
4110
+ guardedDelegateCalls,
4111
+ ...timestampMs !== void 0 ? { timestampMs } : {}
3592
4112
  };
3593
4113
  }
3594
4114
  };
@@ -3981,7 +4501,7 @@ var sha256 = /* @__PURE__ */ createHasher(
3981
4501
  );
3982
4502
 
3983
4503
  // ../sdk/dist/protocol/offer-exclusion.js
3984
- import { normalizeStructTag as normalizeStructTag5, normalizeSuiAddress as normalizeSuiAddress4 } from "@mysten/sui/utils";
4504
+ import { normalizeStructTag as normalizeStructTag7, normalizeSuiAddress as normalizeSuiAddress4 } from "@mysten/sui/utils";
3985
4505
 
3986
4506
  // ../sdk/dist/protocol/terms.js
3987
4507
  function paymentIdHash(challengeId) {
@@ -4056,7 +4576,7 @@ function addr32(address) {
4056
4576
  return hexToBytes(normalized.slice(2));
4057
4577
  }
4058
4578
  function canonicalCoinTypeBytes(coinType) {
4059
- const normalized = normalizeStructTag5(coinType.trim());
4579
+ const normalized = normalizeStructTag7(coinType.trim());
4060
4580
  const canonical = normalized.replace(/0x([0-9a-f]{64})/g, "$1");
4061
4581
  if (!/^[0-9a-f]{64}::/.test(canonical)) {
4062
4582
  throw new Error(`coin type must resolve to a numeric package address: ${coinType}`);
@@ -4255,8 +4775,8 @@ function createGrpcExclusionRegistryReader(client) {
4255
4775
 
4256
4776
  // ../sdk/dist/delegated-signer/payer.js
4257
4777
  import { bcs as bcs7 } from "@mysten/sui/bcs";
4258
- 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";
4778
+ import { Transaction as Transaction5 } from "@mysten/sui/transactions";
4779
+ import { fromBase64 as fromBase648, normalizeStructTag as normalizeStructTag10, normalizeSuiAddress as normalizeSuiAddress10, toBase64 as toBase645 } from "@mysten/sui/utils";
4260
4780
  import { Ed25519Keypair } from "@mysten/sui/keypairs/ed25519";
4261
4781
 
4262
4782
  // ../sdk/dist/delegated-signer/finality-poll.js
@@ -4281,179 +4801,9 @@ async function pollFinality(input) {
4281
4801
  return { status: "timeout" };
4282
4802
  }
4283
4803
 
4284
- // ../sdk/dist/pay-operation/operation.js
4285
- import { normalizeStructTag as normalizeStructTag7, normalizeSuiAddress as normalizeSuiAddress6 } from "@mysten/sui/utils";
4286
-
4287
- // ../core/dist/policy/grant-target.js
4288
- function normalizeHash(hex) {
4289
- return hex.replace(/^0x/i, "").toLowerCase();
4290
- }
4291
- function grantAuthorityUsable(snapshot) {
4292
- if (snapshot.status === "paused") {
4293
- return { ok: false, reason: "grant is paused" };
4294
- }
4295
- if (snapshot.status === "revoked") {
4296
- return { ok: false, reason: "grant is revoked" };
4297
- }
4298
- if (snapshot.status === "expired") {
4299
- return { ok: false, reason: "grant is expired" };
4300
- }
4301
- if (snapshot.status !== "active") {
4302
- return { ok: false, reason: `grant status is ${snapshot.status}` };
4303
- }
4304
- if (!snapshot.grantObjectId?.trim()) {
4305
- return { ok: false, reason: "grant is not finalized (missing grantObjectId)" };
4306
- }
4307
- if (!snapshot.poolObjectId?.trim()) {
4308
- return { ok: false, reason: "poolObjectId is required" };
4309
- }
4310
- return {
4311
- ok: true,
4312
- grantObjectId: snapshot.grantObjectId,
4313
- poolObjectId: snapshot.poolObjectId
4314
- };
4315
- }
4316
- function resolveGrantTarget(snapshot, offerTargetHash) {
4317
- if (!offerTargetHash?.trim()) {
4318
- return { ok: false, reason: "offer.targetHash is required" };
4319
- }
4320
- const wanted = normalizeHash(offerTargetHash);
4321
- if (!/^[0-9a-f]{64}$/.test(wanted)) {
4322
- return { ok: false, reason: "offer.targetHash must be 32-byte hex" };
4323
- }
4324
- const usable = grantAuthorityUsable(snapshot);
4325
- if (!usable.ok) {
4326
- return usable;
4327
- }
4328
- const hits = [];
4329
- for (const policy of snapshot.policies) {
4330
- if (policy.status !== "active")
4331
- continue;
4332
- for (const target of policy.targets) {
4333
- if (normalizeHash(target.targetHash) === wanted) {
4334
- hits.push({
4335
- policyId: policy.policyId,
4336
- onChainPolicyId: policy.onChainPolicyId,
4337
- maxPerPayment: target.maxPerPayment
4338
- });
4339
- }
4340
- }
4341
- }
4342
- if (hits.length > 1) {
4343
- return {
4344
- ok: false,
4345
- reason: `target hash resolves to ${hits.length} active policies (EPolicyConflict)`
4346
- };
4347
- }
4348
- if (hits.length === 1) {
4349
- const hit = hits[0];
4350
- return {
4351
- ok: true,
4352
- policyId: hit.policyId,
4353
- onChainPolicyId: hit.onChainPolicyId,
4354
- targetHash: wanted,
4355
- maxPerPayment: hit.maxPerPayment,
4356
- poolObjectId: usable.poolObjectId,
4357
- grantObjectId: usable.grantObjectId,
4358
- coinType: snapshot.coinType,
4359
- delegateAddress: snapshot.delegateAddress
4360
- };
4361
- }
4362
- return {
4363
- ok: false,
4364
- reason: "no active policy in grant snapshot matches offer.targetHash"
4365
- };
4366
- }
4367
-
4368
- // ../sdk/dist/protocol/carrier.js
4369
- import { fromBase64 as fromBase645, toBase64 as toBase643 } from "@mysten/sui/utils";
4370
-
4371
- // ../sdk/dist/protocol/auth-params.js
4372
- 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
- function parseAuthHeader(header) {
4380
- const trimmed = header.trim();
4381
- const firstSpace = trimmed.indexOf(" ");
4382
- if (firstSpace === -1)
4383
- return null;
4384
- const scheme = trimmed.slice(0, firstSpace);
4385
- if (!TOKEN.test(scheme))
4386
- return null;
4387
- const params = parseParams(trimmed.slice(firstSpace + 1));
4388
- return params === null ? null : { scheme, params };
4389
- }
4390
- function parseParams(input) {
4391
- const params = {};
4392
- let i = 0;
4393
- const skipSpace = () => {
4394
- while (i < input.length && (input[i] === " " || input[i] === " "))
4395
- i++;
4396
- };
4397
- skipSpace();
4398
- while (i < input.length) {
4399
- const keyStart = i;
4400
- while (i < input.length && input[i] !== "=")
4401
- i++;
4402
- if (i >= input.length)
4403
- return null;
4404
- const key = input.slice(keyStart, i).trim();
4405
- if (!TOKEN.test(key))
4406
- return null;
4407
- i++;
4408
- let value;
4409
- if (input[i] === '"') {
4410
- i++;
4411
- let out = "";
4412
- let closed = false;
4413
- while (i < input.length) {
4414
- const ch = input[i];
4415
- if (ch === "\\" && i + 1 < input.length) {
4416
- out += input[i + 1];
4417
- i += 2;
4418
- continue;
4419
- }
4420
- if (ch === '"') {
4421
- i++;
4422
- closed = true;
4423
- break;
4424
- }
4425
- out += ch;
4426
- i++;
4427
- }
4428
- if (!closed)
4429
- return null;
4430
- value = out;
4431
- } else {
4432
- const start = i;
4433
- while (i < input.length && input[i] !== ",")
4434
- i++;
4435
- value = input.slice(start, i).trim();
4436
- }
4437
- params[key] = value;
4438
- skipSpace();
4439
- if (i < input.length) {
4440
- if (input[i] !== ",")
4441
- return null;
4442
- i++;
4443
- skipSpace();
4444
- }
4445
- }
4446
- return params;
4447
- }
4448
-
4449
- // ../sdk/dist/protocol/base64url.js
4450
- function bytesToBase64Url(bytes) {
4451
- let binary = "";
4452
- for (const byte of bytes)
4453
- binary += String.fromCharCode(byte);
4454
- const base64 = typeof globalThis.btoa === "function" ? globalThis.btoa(binary) : Buffer.from(bytes).toString("base64");
4455
- return base64.replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/g, "");
4456
- }
4804
+ // ../sdk/dist/delegated-signer/pay-gas.js
4805
+ import { Transaction as Transaction3 } from "@mysten/sui/transactions";
4806
+ import { fromBase64 as fromBase644, normalizeSuiAddress as normalizeSuiAddress6 } from "@mysten/sui/utils";
4457
4807
 
4458
4808
  // ../sdk/dist/protocol/challenge.js
4459
4809
  import { Ed25519PublicKey } from "@mysten/sui/keypairs/ed25519";
@@ -4540,6 +4890,53 @@ var OMIT_WHEN_ABSENT = /* @__PURE__ */ new Set([
4540
4890
  ...V4_OMIT_WHEN_ABSENT
4541
4891
  ]);
4542
4892
  var BODY_HASH_RE = /^[A-Za-z0-9_-]{43}$/;
4893
+ var CONTROL_CHAR_RE = /[\x00-\x1f\x7f]/;
4894
+ var SIGNED_NUMBER_FIELDS = /* @__PURE__ */ new Set([
4895
+ "decimals",
4896
+ "issuedAt",
4897
+ "expiresAt",
4898
+ "digestVersion",
4899
+ "serviceRevision",
4900
+ "authorizationEpoch",
4901
+ "periodMs",
4902
+ "periodCount",
4903
+ "refundWindowMs",
4904
+ "decideWindowMs",
4905
+ "chainId",
4906
+ "exclusionProtocolVersion"
4907
+ ]);
4908
+ function hasValidSignedOfferFields(offer, requireComplete = true) {
4909
+ if (typeof offer !== "object" || offer === null || Array.isArray(offer))
4910
+ return false;
4911
+ const fields = offer;
4912
+ for (const key of SIGNED_FIELDS_V4) {
4913
+ const value = fields[key];
4914
+ if (value === void 0) {
4915
+ if (requireComplete && SIGNED_FIELDS_V1.includes(key))
4916
+ return false;
4917
+ continue;
4918
+ }
4919
+ if (SIGNED_NUMBER_FIELDS.has(key)) {
4920
+ if (typeof value !== "number" || !Number.isSafeInteger(value) || value < 0)
4921
+ return false;
4922
+ if (key === "digestVersion" && (value < 1 || value > 4))
4923
+ return false;
4924
+ } else if (key === "refundable") {
4925
+ if (typeof value !== "boolean")
4926
+ return false;
4927
+ } else if (key === "acceptedRails") {
4928
+ if (!Array.isArray(value))
4929
+ return false;
4930
+ for (const rail of value) {
4931
+ if (typeof rail !== "string" || CONTROL_CHAR_RE.test(rail) || rail.includes(","))
4932
+ return false;
4933
+ }
4934
+ } else if (typeof value !== "string" || CONTROL_CHAR_RE.test(value)) {
4935
+ return false;
4936
+ }
4937
+ }
4938
+ return true;
4939
+ }
4543
4940
  var CONTENT_TYPE_RE = /^[a-z0-9!#$%&'*+.^_`|~-]+\/[a-z0-9!#$%&'*+.^_`|~-]+(?:; ?[a-z0-9!#$%&'*+.^_`|~-]+=(?:[a-zA-Z0-9!#$%&'*+.^_`|~-]+|"[^"\n\r]*"))*$/;
4544
4941
  function isBodyHash(value) {
4545
4942
  return typeof value === "string" && BODY_HASH_RE.test(value);
@@ -4718,6 +5115,8 @@ function toRawEd25519PublicKey(key) {
4718
5115
  throw new Error("unsupported Ed25519 public key representation");
4719
5116
  }
4720
5117
  function verifyOfferSig(offer, publicKey) {
5118
+ if (!hasValidSignedOfferFields(offer, false))
5119
+ return Promise.resolve(false);
4721
5120
  if (!offer.sig || typeof offer.sig !== "string")
4722
5121
  return Promise.resolve(false);
4723
5122
  if (!offer.digest || typeof offer.digest !== "string" || !offer.digest.trim() || offer.digest !== offer.digest.trim()) {
@@ -4752,44 +5151,313 @@ function verifyOfferSig(offer, publicKey) {
4752
5151
  function isExpired(offer, now = Date.now()) {
4753
5152
  return now >= offer.expiresAt;
4754
5153
  }
4755
- function decodeSponsorGasPayment(encoded) {
4756
- if (typeof encoded !== "string" || !encoded.trim()) {
4757
- throw new Error("sponsorGasPayment is required");
4758
- }
4759
- return encoded.split(",").map((part) => {
4760
- const bits = part.split("@");
4761
- if (bits.length !== 3 || !bits[0] || !bits[1] || !bits[2]) {
4762
- throw new Error(`malformed sponsorGasPayment segment: ${part}`);
5154
+ function decodeSponsorGasPayment(encoded) {
5155
+ if (typeof encoded !== "string" || !encoded.trim()) {
5156
+ throw new Error("sponsorGasPayment is required");
5157
+ }
5158
+ return encoded.split(",").map((part) => {
5159
+ const bits = part.split("@");
5160
+ if (bits.length !== 3 || !bits[0] || !bits[1] || !bits[2]) {
5161
+ throw new Error(`malformed sponsorGasPayment segment: ${part}`);
5162
+ }
5163
+ return { objectId: bits[0], version: bits[1], digest: bits[2] };
5164
+ });
5165
+ }
5166
+ var SPONSOR_GAS_ADDRESS_BALANCE = "address-balance";
5167
+ function decodeSponsorGasPin(encoded) {
5168
+ if (encoded === SPONSOR_GAS_ADDRESS_BALANCE)
5169
+ return [];
5170
+ return decodeSponsorGasPayment(encoded);
5171
+ }
5172
+ var ADDRESS_BALANCE_VALIDITY_EPOCHS = 1n;
5173
+ function addressBalanceGasExpiration(input) {
5174
+ const chain = input.chainIdentifier.trim();
5175
+ if (!chain)
5176
+ throw new Error("address-balance gas needs a chain identifier");
5177
+ if (input.epoch < 0n)
5178
+ throw new Error("address-balance gas needs a non-negative epoch");
5179
+ if (!Number.isInteger(input.nonce) || input.nonce < 0 || input.nonce > 4294967295) {
5180
+ throw new Error("address-balance gas nonce must be a u32");
5181
+ }
5182
+ return {
5183
+ ValidDuring: {
5184
+ minEpoch: String(input.epoch),
5185
+ maxEpoch: String(input.epoch + ADDRESS_BALANCE_VALIDITY_EPOCHS),
5186
+ minTimestamp: null,
5187
+ maxTimestamp: null,
5188
+ chain,
5189
+ nonce: input.nonce
5190
+ }
5191
+ };
5192
+ }
5193
+
5194
+ // ../sdk/dist/delegated-signer/pay-gas.js
5195
+ var DEFAULT_GAS_BUDGET = 10000000n;
5196
+ var DEFAULT_GAS_PRICE = 1000n;
5197
+ var X402_EXPIRATION_EPOCHS = 32n;
5198
+ async function readChainBound(read) {
5199
+ try {
5200
+ return await read();
5201
+ } catch (cause) {
5202
+ if (cause instanceof SuiPayError)
5203
+ throw cause;
5204
+ throw SuiPayError.of("chain.unavailable", "not_charged", {
5205
+ detail: "the pre-sign chain read is unavailable; no signature was produced"
5206
+ }, { cause });
5207
+ }
5208
+ }
5209
+ async function readPayExpirationPolicy(txBytes, readers) {
5210
+ const expiration = Transaction3.from(fromBase644(txBytes)).getData().expiration;
5211
+ if (expiration.$kind === "None")
5212
+ return void 0;
5213
+ if (!readers.getCurrentEpoch)
5214
+ throw new Error("a trusted current epoch is required");
5215
+ if (expiration.$kind !== "ValidDuring") {
5216
+ return { currentEpoch: BigInt(await readChainBound(readers.getCurrentEpoch)) };
5217
+ }
5218
+ if (!readers.getChainIdentifier)
5219
+ throw new Error("a trusted chain identifier is required");
5220
+ const [currentEpoch, chainIdentifier] = await Promise.all([
5221
+ readChainBound(readers.getCurrentEpoch),
5222
+ readChainBound(readers.getChainIdentifier)
5223
+ ]);
5224
+ return { currentEpoch: BigInt(currentEpoch), chainIdentifier };
5225
+ }
5226
+ function assertPayGas(data, delegate, policy = {}) {
5227
+ const actual = data.gasData;
5228
+ const agent = normalizeSuiAddress6(delegate);
5229
+ if (!actual.owner)
5230
+ throw new Error("transaction gas owner is missing");
5231
+ const owner = normalizeSuiAddress6(actual.owner);
5232
+ const pinned = policy.gas;
5233
+ if (policy.mode !== void 0 && policy.mode !== "agent" && policy.mode !== "sponsored") {
5234
+ throw new Error("transaction gas policy mode is invalid");
5235
+ }
5236
+ if (policy.mode === "agent") {
5237
+ if (!pinned)
5238
+ throw new Error("agent gas requires caller-owned gas inputs");
5239
+ } else if (owner === agent) {
5240
+ throw new Error("sponsored transaction gas owner must not be the delegate");
5241
+ }
5242
+ if (pinned) {
5243
+ const expectedOwner = normalizeSuiAddress6(pinned.owner ?? delegate);
5244
+ const samePayment = actual.payment.length === pinned.payment.length && pinned.payment.every((ref, i) => {
5245
+ const got = actual.payment[i];
5246
+ return normalizeSuiAddress6(got.objectId) === normalizeSuiAddress6(ref.objectId) && got.version === String(ref.version) && got.digest === ref.digest;
5247
+ });
5248
+ if (owner !== expectedOwner || actual.budget !== String(pinned.budget ?? DEFAULT_GAS_BUDGET) || actual.price !== String(pinned.price ?? DEFAULT_GAS_PRICE) || !samePayment) {
5249
+ throw new Error("transaction gas does not match the caller gas inputs");
5250
+ }
5251
+ }
5252
+ const expiration = data.expiration;
5253
+ const validity = policy.expiration;
5254
+ if (expiration.$kind === "None") {
5255
+ if (!actual.payment.length || validity?.requireBounded) {
5256
+ throw new Error("transaction gas requires bounded expiration");
5257
+ }
5258
+ return;
5259
+ }
5260
+ if (!validity || validity.currentEpoch < 0n) {
5261
+ throw new Error("transaction expiration has no trusted epoch bound");
5262
+ }
5263
+ const now = validity.currentEpoch;
5264
+ if (expiration.$kind === "Epoch") {
5265
+ const epoch = BigInt(expiration.Epoch);
5266
+ if (!actual.payment.length || epoch < now || epoch > now + X402_EXPIRATION_EPOCHS) {
5267
+ throw new Error("transaction epoch expiration is outside the allowed window");
5268
+ }
5269
+ return;
5270
+ }
5271
+ const window = expiration.ValidDuring;
5272
+ if (!validity.chainIdentifier || window.chain !== validity.chainIdentifier || window.minEpoch === null || window.maxEpoch === null || window.minTimestamp !== null || window.maxTimestamp !== null) {
5273
+ throw new Error("transaction validity does not match the trusted chain window");
5274
+ }
5275
+ const min = BigInt(window.minEpoch);
5276
+ const max = BigInt(window.maxEpoch);
5277
+ if (min > now || max < now || max > now + ADDRESS_BALANCE_VALIDITY_EPOCHS || max - min > ADDRESS_BALANCE_VALIDITY_EPOCHS) {
5278
+ throw new Error("transaction validity is outside the allowed epoch window");
5279
+ }
5280
+ }
5281
+
5282
+ // ../sdk/dist/pay-operation/operation.js
5283
+ import { normalizeStructTag as normalizeStructTag9, normalizeSuiAddress as normalizeSuiAddress7 } from "@mysten/sui/utils";
5284
+
5285
+ // ../core/dist/policy/grant-target.js
5286
+ function normalizeHash(hex) {
5287
+ return hex.replace(/^0x/i, "").toLowerCase();
5288
+ }
5289
+ function grantAuthorityUsable(snapshot) {
5290
+ if (snapshot.status === "paused") {
5291
+ return { ok: false, reason: "grant is paused" };
5292
+ }
5293
+ if (snapshot.status === "revoked") {
5294
+ return { ok: false, reason: "grant is revoked" };
5295
+ }
5296
+ if (snapshot.status === "expired") {
5297
+ return { ok: false, reason: "grant is expired" };
5298
+ }
5299
+ if (snapshot.status !== "active") {
5300
+ return { ok: false, reason: `grant status is ${snapshot.status}` };
5301
+ }
5302
+ if (!snapshot.grantObjectId?.trim()) {
5303
+ return { ok: false, reason: "grant is not finalized (missing grantObjectId)" };
5304
+ }
5305
+ if (!snapshot.poolObjectId?.trim()) {
5306
+ return { ok: false, reason: "poolObjectId is required" };
5307
+ }
5308
+ return {
5309
+ ok: true,
5310
+ grantObjectId: snapshot.grantObjectId,
5311
+ poolObjectId: snapshot.poolObjectId
5312
+ };
5313
+ }
5314
+ function resolveGrantTarget(snapshot, offerTargetHash) {
5315
+ if (!offerTargetHash?.trim()) {
5316
+ return { ok: false, reason: "offer.targetHash is required" };
5317
+ }
5318
+ const wanted = normalizeHash(offerTargetHash);
5319
+ if (!/^[0-9a-f]{64}$/.test(wanted)) {
5320
+ return { ok: false, reason: "offer.targetHash must be 32-byte hex" };
5321
+ }
5322
+ const usable = grantAuthorityUsable(snapshot);
5323
+ if (!usable.ok) {
5324
+ return usable;
5325
+ }
5326
+ const hits = [];
5327
+ for (const policy of snapshot.policies) {
5328
+ if (policy.status !== "active")
5329
+ continue;
5330
+ for (const target of policy.targets) {
5331
+ if (normalizeHash(target.targetHash) === wanted) {
5332
+ hits.push({
5333
+ policyId: policy.policyId,
5334
+ onChainPolicyId: policy.onChainPolicyId,
5335
+ maxPerPayment: target.maxPerPayment
5336
+ });
5337
+ }
5338
+ }
5339
+ }
5340
+ if (hits.length > 1) {
5341
+ return {
5342
+ ok: false,
5343
+ reason: `target hash resolves to ${hits.length} active policies (EPolicyConflict)`
5344
+ };
5345
+ }
5346
+ if (hits.length === 1) {
5347
+ const hit = hits[0];
5348
+ return {
5349
+ ok: true,
5350
+ policyId: hit.policyId,
5351
+ onChainPolicyId: hit.onChainPolicyId,
5352
+ targetHash: wanted,
5353
+ maxPerPayment: hit.maxPerPayment,
5354
+ poolObjectId: usable.poolObjectId,
5355
+ grantObjectId: usable.grantObjectId,
5356
+ coinType: snapshot.coinType,
5357
+ delegateAddress: snapshot.delegateAddress
5358
+ };
5359
+ }
5360
+ return {
5361
+ ok: false,
5362
+ reason: "no active policy in grant snapshot matches offer.targetHash"
5363
+ };
5364
+ }
5365
+
5366
+ // ../sdk/dist/protocol/carrier.js
5367
+ import { fromBase64 as fromBase646, toBase64 as toBase643 } from "@mysten/sui/utils";
5368
+
5369
+ // ../sdk/dist/protocol/auth-params.js
5370
+ var TOKEN = /^[A-Za-z0-9!#$%&'*+\-.^_`|~]+$/;
5371
+ function parseAuthHeader(header) {
5372
+ const trimmed = header.trim();
5373
+ const firstSpace = trimmed.indexOf(" ");
5374
+ if (firstSpace === -1)
5375
+ return null;
5376
+ const scheme = trimmed.slice(0, firstSpace);
5377
+ if (!TOKEN.test(scheme))
5378
+ return null;
5379
+ const params = parseParams(trimmed.slice(firstSpace + 1));
5380
+ return params === null ? null : { scheme, params };
5381
+ }
5382
+ function parseParams(input) {
5383
+ const params = {};
5384
+ let i = 0;
5385
+ const skipSpace = () => {
5386
+ while (i < input.length && (input[i] === " " || input[i] === " "))
5387
+ i++;
5388
+ };
5389
+ skipSpace();
5390
+ while (i < input.length) {
5391
+ const keyStart = i;
5392
+ while (i < input.length && input[i] !== "=")
5393
+ i++;
5394
+ if (i >= input.length)
5395
+ return null;
5396
+ const key = input.slice(keyStart, i).trim();
5397
+ if (!TOKEN.test(key))
5398
+ return null;
5399
+ i++;
5400
+ let value;
5401
+ if (input[i] === '"') {
5402
+ i++;
5403
+ let out = "";
5404
+ let closed = false;
5405
+ while (i < input.length) {
5406
+ const ch = input[i];
5407
+ if (ch === "\\" && i + 1 < input.length) {
5408
+ out += input[i + 1];
5409
+ i += 2;
5410
+ continue;
5411
+ }
5412
+ if (ch === '"') {
5413
+ i++;
5414
+ closed = true;
5415
+ break;
5416
+ }
5417
+ out += ch;
5418
+ i++;
5419
+ }
5420
+ if (!closed)
5421
+ return null;
5422
+ value = out;
5423
+ } else {
5424
+ const start = i;
5425
+ while (i < input.length && input[i] !== ",")
5426
+ i++;
5427
+ value = input.slice(start, i).trim();
4763
5428
  }
4764
- return { objectId: bits[0], version: bits[1], digest: bits[2] };
4765
- });
5429
+ params[key] = value;
5430
+ skipSpace();
5431
+ if (i < input.length) {
5432
+ if (input[i] !== ",")
5433
+ return null;
5434
+ i++;
5435
+ skipSpace();
5436
+ }
5437
+ }
5438
+ return params;
4766
5439
  }
4767
- var SPONSOR_GAS_ADDRESS_BALANCE = "address-balance";
4768
- function decodeSponsorGasPin(encoded) {
4769
- if (encoded === SPONSOR_GAS_ADDRESS_BALANCE)
4770
- return [];
4771
- return decodeSponsorGasPayment(encoded);
5440
+
5441
+ // ../sdk/dist/protocol/base64url.js
5442
+ function bytesToBase64Url(bytes) {
5443
+ let binary = "";
5444
+ for (const byte of bytes)
5445
+ binary += String.fromCharCode(byte);
5446
+ const base64 = typeof globalThis.btoa === "function" ? globalThis.btoa(binary) : Buffer.from(bytes).toString("base64");
5447
+ return base64.replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/g, "");
4772
5448
  }
4773
- var ADDRESS_BALANCE_VALIDITY_EPOCHS = 1n;
4774
- function addressBalanceGasExpiration(input) {
4775
- const chain = input.chainIdentifier.trim();
4776
- if (!chain)
4777
- throw new Error("address-balance gas needs a chain identifier");
4778
- if (input.epoch < 0n)
4779
- throw new Error("address-balance gas needs a non-negative epoch");
4780
- if (!Number.isInteger(input.nonce) || input.nonce < 0 || input.nonce > 4294967295) {
4781
- throw new Error("address-balance gas nonce must be a u32");
5449
+ function bytesFromBase64Url(s) {
5450
+ const normalized = s.replace(/-/g, "+").replace(/_/g, "/");
5451
+ const pad = (4 - normalized.length % 4) % 4;
5452
+ const base64 = normalized + "=".repeat(pad);
5453
+ if (typeof globalThis.atob === "function") {
5454
+ const binary = globalThis.atob(base64);
5455
+ const out = new Uint8Array(binary.length);
5456
+ for (let i = 0; i < binary.length; i++)
5457
+ out[i] = binary.charCodeAt(i);
5458
+ return out;
4782
5459
  }
4783
- return {
4784
- ValidDuring: {
4785
- minEpoch: String(input.epoch),
4786
- maxEpoch: String(input.epoch + ADDRESS_BALANCE_VALIDITY_EPOCHS),
4787
- minTimestamp: null,
4788
- maxTimestamp: null,
4789
- chain,
4790
- nonce: input.nonce
4791
- }
4792
- };
5460
+ return Uint8Array.from(Buffer.from(base64, "base64"));
4793
5461
  }
4794
5462
 
4795
5463
  // ../sdk/dist/protocol/mpp.js
@@ -4798,9 +5466,220 @@ function offerToBase64Url(offer) {
4798
5466
  }
4799
5467
  var MPP_SCHEME = "Payment";
4800
5468
  var MPP_METHOD = "sui.charge";
5469
+ var MPP_SUI_METHOD = "sui";
5470
+ var MPP_CHARGE_INTENT = "charge";
5471
+ var MPP_RECEIPT_STATUS = "success";
5472
+ var LEGACY_RECEIPT_STATUS = "settled";
4801
5473
  var MPP_CHALLENGE_HEADER = "WWW-Authenticate";
4802
5474
  var MPP_CREDENTIAL_HEADER = "Authorization";
4803
5475
  var MPP_RECEIPT_HEADER = "Payment-Receipt";
5476
+ var HEADER_TEXT_REPLACEMENTS = {
5477
+ "\u2264": "<=",
5478
+ // ≤ less-than-or-equal
5479
+ "\u2265": ">=",
5480
+ // ≥ greater-than-or-equal
5481
+ "\u2014": "-",
5482
+ // — em dash
5483
+ "\u2013": "-",
5484
+ // – en dash
5485
+ "\u2018": "'",
5486
+ // ' left single quote
5487
+ "\u2019": "'",
5488
+ // ' right single quote
5489
+ "\u201C": '"',
5490
+ // " left double quote
5491
+ "\u201D": '"'
5492
+ // " right double quote
5493
+ };
5494
+ function latin1HeaderText(value) {
5495
+ let out = "";
5496
+ for (const ch of value) {
5497
+ const mapped = HEADER_TEXT_REPLACEMENTS[ch];
5498
+ if (mapped !== void 0)
5499
+ out += mapped;
5500
+ else if (ch.codePointAt(0) > 255)
5501
+ out += "?";
5502
+ else
5503
+ out += ch;
5504
+ }
5505
+ return out;
5506
+ }
5507
+ var DAY_MS = 864e5;
5508
+ function billingPeriod(periodMs) {
5509
+ if (!Number.isInteger(periodMs) || periodMs < DAY_MS || periodMs % DAY_MS !== 0)
5510
+ return null;
5511
+ const days = periodMs / DAY_MS;
5512
+ if (days % 7 === 0)
5513
+ return { periodCount: String(days / 7), periodUnit: "week" };
5514
+ return { periodCount: String(days), periodUnit: "day" };
5515
+ }
5516
+ function billingPeriodMs(unit, count) {
5517
+ if (!Number.isInteger(count) || count <= 0)
5518
+ return null;
5519
+ if (unit === "day")
5520
+ return count * DAY_MS;
5521
+ if (unit === "week")
5522
+ return count * 7 * DAY_MS;
5523
+ return null;
5524
+ }
5525
+ function expiresWire(offer) {
5526
+ if (typeof offer.expiresAt !== "number" || !Number.isFinite(offer.expiresAt))
5527
+ return void 0;
5528
+ return new Date(offer.expiresAt).toISOString();
5529
+ }
5530
+ function flatParams(offer) {
5531
+ const params = {
5532
+ amount: offer.amount,
5533
+ asset: offer.asset,
5534
+ network: offer.network,
5535
+ recipient: offer.payTo,
5536
+ package: offer.packageId,
5537
+ resource: offer.resource,
5538
+ digest: offer.digest
5539
+ };
5540
+ if (typeof offer.decimals === "number")
5541
+ params.decimals = String(offer.decimals);
5542
+ if (typeof offer.description === "string") {
5543
+ params.description = latin1HeaderText(offer.description);
5544
+ }
5545
+ if (typeof offer.issuedAt === "number" && Number.isFinite(offer.issuedAt)) {
5546
+ params.issued = new Date(offer.issuedAt).toISOString();
5547
+ }
5548
+ if (typeof offer.expiresAt === "number" && Number.isFinite(offer.expiresAt)) {
5549
+ params.expires = new Date(offer.expiresAt).toISOString();
5550
+ }
5551
+ if (offer.netAmount !== void 0)
5552
+ params.net_amount = offer.netAmount;
5553
+ if (offer.platformFee !== void 0)
5554
+ params.platform_fee = offer.platformFee;
5555
+ if (offer.digestVersion !== void 0)
5556
+ params.digest_version = String(offer.digestVersion);
5557
+ if (offer.settlementRail !== void 0)
5558
+ params.settlement_rail = offer.settlementRail;
5559
+ if (offer.serviceId !== void 0)
5560
+ params.service_id = offer.serviceId;
5561
+ if (offer.serviceRevision !== void 0) {
5562
+ params.service_revision = String(offer.serviceRevision);
5563
+ }
5564
+ if (offer.targetHash !== void 0)
5565
+ params.target_hash = offer.targetHash;
5566
+ if (offer.authorizationEpoch !== void 0) {
5567
+ params.authorization_epoch = String(offer.authorizationEpoch);
5568
+ }
5569
+ if (offer.method !== void 0)
5570
+ params.http_method = offer.method;
5571
+ if (offer.path !== void 0)
5572
+ params.http_path = offer.path;
5573
+ if (offer.bodyHash !== void 0)
5574
+ params.body_hash = offer.bodyHash;
5575
+ if (offer.contentType !== void 0)
5576
+ params.content_type = offer.contentType;
5577
+ if (offer.intent !== void 0)
5578
+ params.intent = offer.intent;
5579
+ if (offer.periodMs !== void 0)
5580
+ params.period_ms = String(offer.periodMs);
5581
+ if (offer.periodCount !== void 0)
5582
+ params.period_count = String(offer.periodCount);
5583
+ if (offer.refundable !== void 0)
5584
+ params.refundable = offer.refundable ? "true" : "false";
5585
+ if (offer.refundWindowMs !== void 0) {
5586
+ params.refund_window_ms = String(offer.refundWindowMs);
5587
+ }
5588
+ if (offer.decideWindowMs !== void 0) {
5589
+ params.decide_window_ms = String(offer.decideWindowMs);
5590
+ }
5591
+ if (offer.chainId !== void 0)
5592
+ params.chain_id = String(offer.chainId);
5593
+ if (offer.paymentSalt !== void 0)
5594
+ params.payment_salt = offer.paymentSalt;
5595
+ if (offer.refundConfigId !== void 0)
5596
+ params.refund_config_id = offer.refundConfigId;
5597
+ if (offer.refundTo !== void 0)
5598
+ params.refund_to = offer.refundTo;
5599
+ if (offer.sponsorGasOwner !== void 0) {
5600
+ params.sponsor_gas_owner = offer.sponsorGasOwner;
5601
+ }
5602
+ if (offer.sponsorGasBudget !== void 0) {
5603
+ params.sponsor_gas_budget = offer.sponsorGasBudget;
5604
+ }
5605
+ if (offer.sponsorGasPrice !== void 0) {
5606
+ params.sponsor_gas_price = offer.sponsorGasPrice;
5607
+ }
5608
+ if (offer.sponsorGasPayment !== void 0) {
5609
+ params.sponsor_gas_payment = offer.sponsorGasPayment;
5610
+ }
5611
+ if (offer.acceptedRails !== void 0) {
5612
+ params.accepted_rails = offer.acceptedRails.join(",");
5613
+ }
5614
+ if (offer.exclusionProtocolVersion !== void 0) {
5615
+ params.exclusion_protocol_version = String(offer.exclusionProtocolVersion);
5616
+ }
5617
+ if (offer.registryIdentity !== void 0) {
5618
+ params.registry_identity = offer.registryIdentity;
5619
+ }
5620
+ if (offer.sig !== void 0)
5621
+ params.sig = offer.sig;
5622
+ if (offer.sigKid !== void 0)
5623
+ params.sig_kid = offer.sigKid;
5624
+ return params;
5625
+ }
5626
+ function legacyRequestBlob(offer, copies = false) {
5627
+ const params = flatParams(offer);
5628
+ if (copies) {
5629
+ params.method = MPP_SUI_METHOD;
5630
+ params.realm = "suipay";
5631
+ params.challenge = offer.challengeId;
5632
+ if (typeof offer.mimeType === "string")
5633
+ params.type = offer.mimeType;
5634
+ }
5635
+ return bytesToBase64Url(new TextEncoder().encode(canonicalJson(params)));
5636
+ }
5637
+ function requestBlob(offer) {
5638
+ const flat = flatParams(offer);
5639
+ const details = { ...flat };
5640
+ delete details.amount;
5641
+ delete details.asset;
5642
+ delete details.recipient;
5643
+ delete details.description;
5644
+ delete details.expires;
5645
+ const body = {
5646
+ amount: flat.amount,
5647
+ currency: flat.asset,
5648
+ methodDetails: details
5649
+ };
5650
+ if (flat.recipient !== void 0)
5651
+ body.recipient = flat.recipient;
5652
+ if (flat.description !== void 0)
5653
+ body.description = flat.description;
5654
+ if (wireIntent(offer) === "subscription") {
5655
+ delete details.period_ms;
5656
+ const periodMs = offer.periodMs;
5657
+ const billing = typeof periodMs === "number" ? billingPeriod(periodMs) : null;
5658
+ if (!billing) {
5659
+ throw new Error("subscription periodMs is not an exact number of days");
5660
+ }
5661
+ body.periodCount = billing.periodCount;
5662
+ body.periodUnit = billing.periodUnit;
5663
+ const periodCount = offer.periodCount;
5664
+ const issuedAt = offer.issuedAt;
5665
+ if (typeof periodMs === "number" && typeof periodCount === "number" && typeof issuedAt === "number" && Number.isSafeInteger(periodMs) && Number.isSafeInteger(periodCount) && Number.isSafeInteger(issuedAt) && Number.isSafeInteger(periodMs * periodCount)) {
5666
+ const end = issuedAt + periodMs * periodCount;
5667
+ if (Number.isSafeInteger(end))
5668
+ body.subscriptionExpires = new Date(end).toISOString();
5669
+ }
5670
+ }
5671
+ return bytesToBase64Url(new TextEncoder().encode(canonicalJsonValue(body)));
5672
+ }
5673
+ function issuedRequestBlob(offer) {
5674
+ return requestBlob(offer);
5675
+ }
5676
+ function echoedRequestBlob(offer) {
5677
+ try {
5678
+ return issuedRequestBlob(offer);
5679
+ } catch {
5680
+ return legacyRequestBlob(offer);
5681
+ }
5682
+ }
4804
5683
  function splitChallenges(header) {
4805
5684
  const scheme = `${MPP_SCHEME} `;
4806
5685
  const value = header.trim();
@@ -4860,11 +5739,120 @@ function decodeChallenge(header, opts) {
4860
5739
  }
4861
5740
  return null;
4862
5741
  }
5742
+ function canonicalJson(fields) {
5743
+ const keys = Object.keys(fields).sort();
5744
+ return `{${keys.map((key) => `${JSON.stringify(key)}:${JSON.stringify(fields[key])}`).join(",")}}`;
5745
+ }
5746
+ function canonicalJsonValue(value) {
5747
+ if (value === null || typeof value !== "object")
5748
+ return JSON.stringify(value);
5749
+ if (Array.isArray(value))
5750
+ return `[${value.map(canonicalJsonValue).join(",")}]`;
5751
+ const fields = value;
5752
+ const keys = Object.keys(fields).sort();
5753
+ return `{${keys.map((key) => `${JSON.stringify(key)}:${canonicalJsonValue(fields[key])}`).join(",")}}`;
5754
+ }
5755
+ function wireIntent(offer) {
5756
+ return offer.intent === "subscription" ? "subscription" : MPP_CHARGE_INTENT;
5757
+ }
5758
+ var REQUEST_TOP_LEVEL = /* @__PURE__ */ new Set([
5759
+ "amount",
5760
+ "asset",
5761
+ "currency",
5762
+ "description",
5763
+ "externalId",
5764
+ "recipient",
5765
+ "subscriptionExpires"
5766
+ ]);
5767
+ function takeStrings(source, into) {
5768
+ for (const [key, value] of Object.entries(source)) {
5769
+ if (typeof value !== "string")
5770
+ return false;
5771
+ into[key] = value;
5772
+ }
5773
+ return true;
5774
+ }
5775
+ function officialParams(params) {
5776
+ if (params.method !== MPP_SUI_METHOD || !params.request)
5777
+ return null;
5778
+ if (params.intent !== MPP_CHARGE_INTENT && params.intent !== "subscription")
5779
+ return null;
5780
+ let body;
5781
+ try {
5782
+ body = JSON.parse(new TextDecoder().decode(bytesFromBase64Url(params.request)));
5783
+ } catch {
5784
+ return null;
5785
+ }
5786
+ if (!body || typeof body !== "object" || Array.isArray(body))
5787
+ return null;
5788
+ const record = body;
5789
+ const fields = {};
5790
+ const details = record.methodDetails;
5791
+ if (details !== void 0) {
5792
+ if (!details || typeof details !== "object" || Array.isArray(details))
5793
+ return null;
5794
+ if (!takeStrings(details, fields))
5795
+ return null;
5796
+ for (const [key, value] of Object.entries(record)) {
5797
+ if (key === "methodDetails" || key === "periodCount" || key === "periodUnit")
5798
+ continue;
5799
+ if (typeof value !== "string" || !REQUEST_TOP_LEVEL.has(key))
5800
+ return null;
5801
+ if (fields[key] !== void 0 && fields[key] !== value)
5802
+ return null;
5803
+ fields[key] = value;
5804
+ }
5805
+ const periodCount = record.periodCount;
5806
+ const periodUnit = record.periodUnit;
5807
+ if (periodCount !== void 0 || periodUnit !== void 0) {
5808
+ if (typeof periodCount !== "string" || typeof periodUnit !== "string")
5809
+ return null;
5810
+ if (!/^[1-9]\d*$/.test(periodCount))
5811
+ return null;
5812
+ const ms = billingPeriodMs(periodUnit, Number(periodCount));
5813
+ if (ms === null)
5814
+ return null;
5815
+ if (fields.period_ms !== void 0 && fields.period_ms !== String(ms))
5816
+ return null;
5817
+ fields.period_ms = String(ms);
5818
+ }
5819
+ if (params.intent === "subscription" && fields.period_ms === void 0)
5820
+ return null;
5821
+ } else if (!takeStrings(record, fields)) {
5822
+ return null;
5823
+ }
5824
+ if (fields.currency !== void 0) {
5825
+ if (fields.asset !== void 0 && fields.asset !== fields.currency)
5826
+ return null;
5827
+ fields.asset = fields.currency;
5828
+ }
5829
+ if (params.expires !== void 0) {
5830
+ if (fields.expires !== void 0 && fields.expires !== params.expires)
5831
+ return null;
5832
+ if (fields.expires === void 0)
5833
+ fields.expires = params.expires;
5834
+ }
5835
+ if (!fields.challenge && params.id)
5836
+ fields.challenge = params.id;
5837
+ if (fields.method === void 0)
5838
+ fields.method = MPP_SUI_METHOD;
5839
+ if (fields.method !== MPP_METHOD && fields.method !== MPP_SUI_METHOD)
5840
+ return null;
5841
+ if (fields.intent !== void 0 && fields.intent !== params.intent)
5842
+ return null;
5843
+ if (fields.intent === void 0 && params.intent === "subscription")
5844
+ return null;
5845
+ fields.method = MPP_METHOD;
5846
+ return fields;
5847
+ }
4863
5848
  function decodeSingleChallenge(header) {
4864
5849
  const parsed = parseAuthHeader(header);
4865
5850
  if (!parsed || parsed.scheme !== MPP_SCHEME)
4866
5851
  return null;
4867
- const p = parsed.params;
5852
+ const pinned = officialParams(parsed.params);
5853
+ const p = { ...pinned ?? parsed.params };
5854
+ if (p.method === MPP_SUI_METHOD)
5855
+ p.method = MPP_METHOD;
4868
5856
  if (p.method !== MPP_METHOD)
4869
5857
  return null;
4870
5858
  const required = [
@@ -4949,13 +5937,15 @@ function decodeSingleChallenge(header) {
4949
5937
  offer.intent = p.intent;
4950
5938
  if (p.period_ms !== void 0) {
4951
5939
  const ms = Number(p.period_ms);
4952
- if (Number.isFinite(ms))
4953
- offer.periodMs = ms;
5940
+ if (!Number.isSafeInteger(ms) || ms <= 0)
5941
+ return null;
5942
+ offer.periodMs = ms;
4954
5943
  }
4955
5944
  if (p.period_count !== void 0) {
4956
5945
  const count = Number(p.period_count);
4957
- if (Number.isFinite(count))
4958
- offer.periodCount = count;
5946
+ if (!Number.isSafeInteger(count) || count <= 0)
5947
+ return null;
5948
+ offer.periodCount = count;
4959
5949
  }
4960
5950
  if (p.refundable === "true")
4961
5951
  offer.refundable = true;
@@ -5015,25 +6005,46 @@ function decodeSingleChallenge(header) {
5015
6005
  offer.sigKid = p.sig_kid;
5016
6006
  return offer;
5017
6007
  }
6008
+ function echoedChallenge(offer, challengeId) {
6009
+ const challenge = {
6010
+ id: challengeId,
6011
+ realm: "suipay",
6012
+ method: MPP_SUI_METHOD,
6013
+ intent: wireIntent(offer),
6014
+ // Section 5.2 echoes the original challenge, including its request.
6015
+ request: echoedRequestBlob(offer)
6016
+ };
6017
+ const expires = expiresWire(offer);
6018
+ if (expires !== void 0)
6019
+ challenge.expires = expires;
6020
+ return challenge;
6021
+ }
6022
+ function encodeOfficialMessage(body) {
6023
+ return `${MPP_SCHEME} ${bytesToBase64Url(new TextEncoder().encode(canonicalJsonValue(body)))}`;
6024
+ }
5018
6025
  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
- })}`;
6026
+ return encodeOfficialMessage({
6027
+ challenge: echoedChallenge(proof.offer, proof.challengeId),
6028
+ payload: {
6029
+ payer: proof.payer,
6030
+ offer: offerToBase64Url(proof.offer),
6031
+ digest: proof.txDigest
6032
+ }
6033
+ });
5026
6034
  }
5027
- function decodeReceipt(header) {
5028
- const parsed = parseAuthHeader(`X ${header}`);
5029
- if (!parsed)
6035
+ function receiptFromParams(p) {
6036
+ if (p.method !== MPP_METHOD && p.method !== MPP_SUI_METHOD)
6037
+ return null;
6038
+ if (p.status !== MPP_RECEIPT_STATUS && p.status !== LEGACY_RECEIPT_STATUS)
5030
6039
  return null;
5031
- const p = parsed.params;
5032
- if (!p.challenge || !p.tx_digest || !p.payer || !p.amount || !p.asset || !p.network)
6040
+ if (p.tx_digest && p.reference && p.tx_digest !== p.reference)
6041
+ return null;
6042
+ const txDigest = p.tx_digest || p.reference;
6043
+ if (!p.challenge || !txDigest || !p.payer || !p.amount || !p.asset || !p.network)
5033
6044
  return null;
5034
6045
  const receipt = {
5035
6046
  challengeId: p.challenge,
5036
- txDigest: p.tx_digest,
6047
+ txDigest,
5037
6048
  network: p.network,
5038
6049
  payer: p.payer,
5039
6050
  amount: p.amount,
@@ -5054,14 +6065,42 @@ function decodeReceipt(header) {
5054
6065
  receipt.periodIndex = p.period_index;
5055
6066
  return receipt;
5056
6067
  }
6068
+ function decodeOfficialReceipt(header) {
6069
+ const token = header.trim();
6070
+ if (!/^[A-Za-z0-9_-]+$/.test(token))
6071
+ return null;
6072
+ let body;
6073
+ try {
6074
+ body = JSON.parse(new TextDecoder().decode(bytesFromBase64Url(token)));
6075
+ } catch {
6076
+ return null;
6077
+ }
6078
+ if (!body || typeof body !== "object" || Array.isArray(body))
6079
+ return null;
6080
+ const fields = {};
6081
+ for (const [key, value] of Object.entries(body)) {
6082
+ if (typeof value !== "string")
6083
+ return null;
6084
+ fields[key] = value;
6085
+ }
6086
+ return receiptFromParams(fields);
6087
+ }
6088
+ function decodeReceipt(header) {
6089
+ if (/^[A-Za-z0-9_-]+$/.test(header.trim()))
6090
+ return decodeOfficialReceipt(header);
6091
+ const parsed = parseAuthHeader(`X ${header}`);
6092
+ if (!parsed)
6093
+ return null;
6094
+ return receiptFromParams(parsed.params);
6095
+ }
5057
6096
 
5058
6097
  // ../sdk/dist/protocol/x402.js
5059
- import { fromBase64 as fromBase644, toBase64 as toBase642 } from "@mysten/sui/utils";
6098
+ import { fromBase64 as fromBase645, toBase64 as toBase642 } from "@mysten/sui/utils";
5060
6099
  function utf8ToBase64(text) {
5061
6100
  return toBase642(new TextEncoder().encode(text));
5062
6101
  }
5063
6102
  function base64ToUtf8(value) {
5064
- return new TextDecoder().decode(fromBase644(value));
6103
+ return new TextDecoder().decode(fromBase645(value));
5065
6104
  }
5066
6105
  var X402_VERSION = 2;
5067
6106
  var X402_SCHEME = "exact";
@@ -5392,7 +6431,7 @@ async function readChallenge(res, dialect, opts) {
5392
6431
  const headerVal = res.headers.get(X402_CHALLENGE_HEADER);
5393
6432
  if (headerVal) {
5394
6433
  try {
5395
- const parsed = JSON.parse(new TextDecoder().decode(fromBase645(headerVal)));
6434
+ const parsed = JSON.parse(new TextDecoder().decode(fromBase646(headerVal)));
5396
6435
  const offer = decodeChallenge2(parsed, opts);
5397
6436
  if (offer)
5398
6437
  return offer;
@@ -5511,7 +6550,7 @@ import { fromHex } from "@mysten/sui/utils";
5511
6550
 
5512
6551
  // ../sdk/dist/protocol/coin-type-hash.js
5513
6552
  import { createHash as createHash2 } from "crypto";
5514
- import { normalizeStructTag as normalizeStructTag6 } from "@mysten/sui/utils";
6553
+ import { normalizeStructTag as normalizeStructTag8 } from "@mysten/sui/utils";
5515
6554
 
5516
6555
  // ../sdk/dist/protocol/refund-vault.js
5517
6556
  function isRefundableOffer(offer) {
@@ -5981,7 +7020,7 @@ async function resolvePayment(input, deps) {
5981
7020
  }
5982
7021
  let packageMatches;
5983
7022
  try {
5984
- packageMatches = normalizeSuiAddress6(offer.packageId) === normalizeSuiAddress6(packageId);
7023
+ packageMatches = normalizeSuiAddress7(offer.packageId) === normalizeSuiAddress7(packageId);
5985
7024
  } catch {
5986
7025
  packageMatches = false;
5987
7026
  }
@@ -6028,7 +7067,7 @@ async function resolvePayment(input, deps) {
6028
7067
  if (!identity) {
6029
7068
  return failedWith(PAY_OPERATION_ERROR_CODES.BUILD_FAILED, "guarded offer carries no valid registry identity", challengeId);
6030
7069
  }
6031
- if (normalizeSuiAddress6(identity.packageId) !== normalizeSuiAddress6(offer.packageId)) {
7070
+ if (normalizeSuiAddress7(identity.packageId) !== normalizeSuiAddress7(offer.packageId)) {
6032
7071
  return failedWith(PAY_OPERATION_ERROR_CODES.BUILD_FAILED, `guarded registry identity package ${identity.packageId} does not match offer package ${offer.packageId}`, challengeId);
6033
7072
  }
6034
7073
  if (!resolveExclusionRegistry2) {
@@ -6176,8 +7215,8 @@ function resolveAuthority(authority, offer) {
6176
7215
  };
6177
7216
  }
6178
7217
  function validateAmount(offer, resolved) {
6179
- const offerCoinType = normalizeStructTag7(offer.asset);
6180
- const grantCoinType = normalizeStructTag7(resolved.coinType);
7218
+ const offerCoinType = normalizeStructTag9(offer.asset);
7219
+ const grantCoinType = normalizeStructTag9(resolved.coinType);
6181
7220
  if (offerCoinType !== grantCoinType) {
6182
7221
  return {
6183
7222
  code: PAY_OPERATION_ERROR_CODES.COIN_TYPE_MISMATCH,
@@ -6223,8 +7262,8 @@ function validateAmount(offer, resolved) {
6223
7262
  import { randomBytes } from "crypto";
6224
7263
  import { bcs as bcs5 } from "@mysten/sui/bcs";
6225
7264
  import { isValidPersonalMessageSignature, verifyPersonalMessageSignature } from "@mysten/sui/verify";
6226
- import { fromBase64 as fromBase646, normalizeSuiAddress as normalizeSuiAddress7, toBase64 as toBase644 } from "@mysten/sui/utils";
6227
- import { Transaction as Transaction3 } from "@mysten/sui/transactions";
7265
+ import { fromBase64 as fromBase647, normalizeSuiAddress as normalizeSuiAddress8, toBase64 as toBase644 } from "@mysten/sui/utils";
7266
+ import { Transaction as Transaction4 } from "@mysten/sui/transactions";
6228
7267
  var SPONSOR_PERSONAL_MESSAGE_DOMAIN = "suipay:sponsor-personal-message:v1";
6229
7268
  function encodeSponsorPersonalMessagePayload(payload) {
6230
7269
  if (payload.domain !== SPONSOR_PERSONAL_MESSAGE_DOMAIN) {
@@ -6247,17 +7286,17 @@ function encodeSponsorPersonalMessagePayload(payload) {
6247
7286
  push(bcs5.vector(bcs5.u8()).serialize([...Buffer.from(payload.domain, "utf8")]).toBytes());
6248
7287
  push(bcs5.vector(bcs5.u8()).serialize([...Buffer.from(payload.nonce, "utf8")]).toBytes());
6249
7288
  push(bcs5.u64().serialize(BigInt(payload.expiryMs)).toBytes());
6250
- push(bcs5.Address.serialize(normalizeSuiAddress7(payload.delegate)).toBytes());
6251
- push(bcs5.Address.serialize(normalizeSuiAddress7(payload.poolId)).toBytes());
6252
- push(bcs5.Address.serialize(normalizeSuiAddress7(payload.grantId)).toBytes());
7289
+ push(bcs5.Address.serialize(normalizeSuiAddress8(payload.delegate)).toBytes());
7290
+ push(bcs5.Address.serialize(normalizeSuiAddress8(payload.poolId)).toBytes());
7291
+ push(bcs5.Address.serialize(normalizeSuiAddress8(payload.grantId)).toBytes());
6253
7292
  push(bcs5.vector(bcs5.u8()).serialize([...Buffer.from(payload.network, "utf8")]).toBytes());
6254
- push(bcs5.Address.serialize(normalizeSuiAddress7(payload.packageId)).toBytes());
7293
+ push(bcs5.Address.serialize(normalizeSuiAddress8(payload.packageId)).toBytes());
6255
7294
  push(bcs5.vector(bcs5.u8()).serialize([...Buffer.from(payload.requestId, "utf8")]).toBytes());
6256
7295
  push(bcs5.vector(bcs5.u8()).serialize([...payload.txKindHash]).toBytes());
6257
7296
  return Buffer.concat(parts.map((p) => Buffer.from(p)));
6258
7297
  }
6259
7298
  function hashTransactionKindBytes(kindBytes) {
6260
- const raw = typeof kindBytes === "string" ? fromBase646(kindBytes) : kindBytes;
7299
+ const raw = typeof kindBytes === "string" ? fromBase647(kindBytes) : kindBytes;
6261
7300
  return sha256(raw);
6262
7301
  }
6263
7302
  function buildSponsorPersonalMessagePayload(input) {
@@ -6265,11 +7304,11 @@ function buildSponsorPersonalMessagePayload(input) {
6265
7304
  domain: SPONSOR_PERSONAL_MESSAGE_DOMAIN,
6266
7305
  nonce: input.nonce,
6267
7306
  expiryMs: input.expiryMs,
6268
- delegate: normalizeSuiAddress7(input.delegate),
6269
- poolId: normalizeSuiAddress7(input.poolId),
6270
- grantId: normalizeSuiAddress7(input.grantId),
7307
+ delegate: normalizeSuiAddress8(input.delegate),
7308
+ poolId: normalizeSuiAddress8(input.poolId),
7309
+ grantId: normalizeSuiAddress8(input.grantId),
6271
7310
  network: input.network,
6272
- packageId: normalizeSuiAddress7(input.packageId),
7311
+ packageId: normalizeSuiAddress8(input.packageId),
6273
7312
  requestId: input.requestId,
6274
7313
  txKindHash: hashTransactionKindBytes(input.transactionKindBytes)
6275
7314
  };
@@ -6427,7 +7466,7 @@ function createOfferKeyResolver(gatewayUrl, options = {}) {
6427
7466
  import { bcs as bcs6 } from "@mysten/sui/bcs";
6428
7467
  import { messageWithIntent } from "@mysten/sui/cryptography";
6429
7468
  import { isValidPersonalMessageSignature as isValidPersonalMessageSignature2, verifyPersonalMessageSignature as verifyPersonalMessageSignature2 } from "@mysten/sui/verify";
6430
- import { normalizeSuiAddress as normalizeSuiAddress8 } from "@mysten/sui/utils";
7469
+ import { normalizeSuiAddress as normalizeSuiAddress9 } from "@mysten/sui/utils";
6431
7470
  var SIGNED_REQUEST_DOMAIN = "suipay:signed-request:v1";
6432
7471
  var BOOTSTRAP_REQUEST_DOMAIN = "suipay:bootstrap-request:v1";
6433
7472
  var SIGNED_REQUEST_MAX_AGE_MS = 3e5;
@@ -6459,7 +7498,7 @@ function encodeBootstrapRequest(payload) {
6459
7498
  throw new Error(`domain must be ${BOOTSTRAP_REQUEST_DOMAIN}`);
6460
7499
  }
6461
7500
  const utf8Vec = (s) => bcs6.vector(bcs6.u8()).serialize([...Buffer.from(s, "utf8")]).toBytes();
6462
- const addr = (a) => bcs6.Address.serialize(normalizeSuiAddress8(a)).toBytes();
7501
+ const addr = (a) => bcs6.Address.serialize(normalizeSuiAddress9(a)).toBytes();
6463
7502
  const parts = [
6464
7503
  utf8Vec(payload.domain),
6465
7504
  utf8Vec(payload.network),
@@ -6479,7 +7518,7 @@ function encodeSignedRequest(payload) {
6479
7518
  throw new Error(`domain must be ${SIGNED_REQUEST_DOMAIN}`);
6480
7519
  }
6481
7520
  const utf8Vec = (s) => bcs6.vector(bcs6.u8()).serialize([...Buffer.from(s, "utf8")]).toBytes();
6482
- const addr = (a) => bcs6.Address.serialize(normalizeSuiAddress8(a)).toBytes();
7521
+ const addr = (a) => bcs6.Address.serialize(normalizeSuiAddress9(a)).toBytes();
6483
7522
  const parts = [
6484
7523
  utf8Vec(payload.domain),
6485
7524
  utf8Vec(payload.network),
@@ -6918,7 +7957,6 @@ var bootstrapPayerGrants = bootstrapPayerSessions;
6918
7957
  // ../sdk/dist/delegated-signer/payer.js
6919
7958
  var FINALIZATION_ATTEMPTS = 20;
6920
7959
  var FINALIZATION_DELAY_MS = 250;
6921
- var X402_EXPIRATION_EPOCHS = 32n;
6922
7960
  var X402_PRESENT_ATTEMPTS = 10;
6923
7961
  var X402_PRESENT_DELAY_MS = 1e3;
6924
7962
  function delay(ms) {
@@ -6929,8 +7967,6 @@ function delay(ms) {
6929
7967
  var SUI_CLOCK2 = "0x6";
6930
7968
  var SUI_CLOCK_INITIAL_SHARED_VERSION = "1";
6931
7969
  var BROADCAST_UNKNOWN = "broadcast-unknown";
6932
- var DEFAULT_GAS_BUDGET = 10000000n;
6933
- var DEFAULT_GAS_PRICE = 1000n;
6934
7970
  var DELEGATED_PAY_ERROR_CODES = {
6935
7971
  OFFER_SECRET_REQUIRED: "OFFER_SECRET_REQUIRED",
6936
7972
  CHALLENGE_TAMPERED: "CHALLENGE_TAMPERED",
@@ -7234,7 +8270,7 @@ function defaultLog(entry, error) {
7234
8270
  }
7235
8271
  function sameAddress2(a, b) {
7236
8272
  try {
7237
- return normalizeSuiAddress9(a) === normalizeSuiAddress9(b);
8273
+ return normalizeSuiAddress10(a) === normalizeSuiAddress10(b);
7238
8274
  } catch {
7239
8275
  return false;
7240
8276
  }
@@ -7248,7 +8284,7 @@ function atomicAmount(value) {
7248
8284
  }
7249
8285
  function sameStructTag(a, b) {
7250
8286
  try {
7251
- return normalizeStructTag8(a) === normalizeStructTag8(b);
8287
+ return normalizeStructTag10(a) === normalizeStructTag10(b);
7252
8288
  } catch {
7253
8289
  return false;
7254
8290
  }
@@ -7296,7 +8332,7 @@ async function resolveSigner(input) {
7296
8332
  return {
7297
8333
  address: kp.getPublicKey().toSuiAddress(),
7298
8334
  async signTransaction(txBytes) {
7299
- const { signature } = await kp.signTransaction(fromBase647(txBytes));
8335
+ const { signature } = await kp.signTransaction(fromBase648(txBytes));
7300
8336
  return signature;
7301
8337
  },
7302
8338
  async signPersonalMessage(message) {
@@ -7372,7 +8408,7 @@ async function buildSpendAccountPayKind(input) {
7372
8408
  }
7373
8409
  const target = payMoveCallTarget(input.packageId, "scoped", true, refundable);
7374
8410
  const clockVersion = input.clockInitialSharedVersion?.trim() || SUI_CLOCK_INITIAL_SHARED_VERSION;
7375
- const tx = new Transaction4();
8411
+ const tx = new Transaction5();
7376
8412
  tx.setSender(input.delegate);
7377
8413
  tx.moveCall({
7378
8414
  target,
@@ -7444,7 +8480,7 @@ async function buildSpendAccountSettleOpenRecipientKind(input) {
7444
8480
  const guarded = resolveGuardedSettleOfflineInputs(input);
7445
8481
  const target = payMoveCallTarget(input.packageId, "open");
7446
8482
  const clockVersion = input.clockInitialSharedVersion?.trim() || SUI_CLOCK_INITIAL_SHARED_VERSION;
7447
- const tx = new Transaction4();
8483
+ const tx = new Transaction5();
7448
8484
  tx.setSender(input.delegate);
7449
8485
  tx.moveCall({
7450
8486
  target,
@@ -7491,7 +8527,7 @@ async function buildSpendAccountPayTx(input) {
7491
8527
  throw new Error("agent gas payment objects are required for executable pay");
7492
8528
  }
7493
8529
  const { kindBytes } = await buildSpendAccountPayKind(input);
7494
- const tx = Transaction4.fromKind(fromBase647(kindBytes));
8530
+ const tx = Transaction5.fromKind(fromBase648(kindBytes));
7495
8531
  tx.setSender(input.delegate);
7496
8532
  tx.setGasOwner(input.gas.owner ?? input.delegate);
7497
8533
  tx.setGasBudget(BigInt(input.gas.budget ?? DEFAULT_GAS_BUDGET));
@@ -7509,7 +8545,7 @@ async function buildSpendAccountSettleOpenRecipientTx(input) {
7509
8545
  throw new Error("agent gas payment objects are required for executable pay");
7510
8546
  }
7511
8547
  const { kindBytes } = await buildSpendAccountSettleOpenRecipientKind(input);
7512
- const tx = Transaction4.fromKind(fromBase647(kindBytes));
8548
+ const tx = Transaction5.fromKind(fromBase648(kindBytes));
7513
8549
  tx.setSender(input.delegate);
7514
8550
  tx.setGasOwner(input.gas.owner ?? input.delegate);
7515
8551
  tx.setGasBudget(BigInt(input.gas.budget ?? DEFAULT_GAS_BUDGET));
@@ -7542,7 +8578,7 @@ function readX402GasPin(offer) {
7542
8578
  }
7543
8579
  async function buildSpendAccountX402PayTx(input) {
7544
8580
  const { kindBytes } = await buildSpendAccountPayKind(input);
7545
- const tx = Transaction4.fromKind(fromBase647(kindBytes));
8581
+ const tx = Transaction5.fromKind(fromBase648(kindBytes));
7546
8582
  tx.setSender(input.delegate);
7547
8583
  tx.setGasOwner(input.gas.owner);
7548
8584
  tx.setGasBudget(input.gas.budget);
@@ -7578,7 +8614,7 @@ function chainIdentifierReader(client) {
7578
8614
  function assertPayTransaction(txBytes, expected) {
7579
8615
  let data;
7580
8616
  try {
7581
- data = Transaction4.from(fromBase647(txBytes)).getData();
8617
+ data = Transaction5.from(fromBase648(txBytes)).getData();
7582
8618
  } catch {
7583
8619
  throw new Error("transaction is not valid Sui transaction bytes");
7584
8620
  }
@@ -7593,13 +8629,13 @@ function assertPayTransaction(txBytes, expected) {
7593
8629
  if (cmd.$kind !== "MoveCall" || !cmd.MoveCall) {
7594
8630
  throw new Error("transaction is not a MoveCall");
7595
8631
  }
7596
- const got = `${normalizeSuiAddress9(String(cmd.MoveCall.package))}::${cmd.MoveCall.module}::${cmd.MoveCall.function}`;
8632
+ const got = `${normalizeSuiAddress10(String(cmd.MoveCall.package))}::${cmd.MoveCall.module}::${cmd.MoveCall.function}`;
7597
8633
  if (got !== wanted) {
7598
8634
  throw new Error(`transaction does not reconstruct ${wanted}`);
7599
8635
  }
7600
8636
  let expectedKind;
7601
8637
  try {
7602
- expectedKind = Transaction4.fromKind(fromBase647(expected.kindBytes)).getData();
8638
+ expectedKind = Transaction5.fromKind(fromBase648(expected.kindBytes)).getData();
7603
8639
  } catch {
7604
8640
  throw new Error("intended pay kind baseline is invalid");
7605
8641
  }
@@ -7625,6 +8661,7 @@ function assertPayTransaction(txBytes, expected) {
7625
8661
  if (args && args.length !== expectedArgc) {
7626
8662
  throw new Error(`pay expects ${expectedArgc} arguments; got ${args.length}`);
7627
8663
  }
8664
+ assertPayGas(data, expected.delegate, expected.gas);
7628
8665
  }
7629
8666
  function asValidatedReceipt(value) {
7630
8667
  if (!value || typeof value !== "object")
@@ -8006,7 +9043,7 @@ async function payDelegatedSpendAccount(args) {
8006
9043
  refuseOffer("POLICY_NO_TARGET");
8007
9044
  }
8008
9045
  try {
8009
- normalizeStructTag8(offer2.asset);
9046
+ normalizeStructTag10(offer2.asset);
8010
9047
  } catch {
8011
9048
  refuseOffer("POLICY_BAD_ASSET");
8012
9049
  }
@@ -8070,7 +9107,7 @@ async function payDelegatedSpendAccount(args) {
8070
9107
  return buildSpendAccountPayKind(kindInput);
8071
9108
  };
8072
9109
  try {
8073
- normalizeStructTag8(snapshot.coinType);
9110
+ normalizeStructTag10(snapshot.coinType);
8074
9111
  } catch {
8075
9112
  return failed("POLICY_REJECTED", PUBLIC_DETAIL.POLICY_REJECTED);
8076
9113
  }
@@ -8420,8 +9457,19 @@ async function payDelegatedSpendAccount(args) {
8420
9457
  }
8421
9458
  }
8422
9459
  try {
8423
- assertPayTransaction(txBytes, expectedPay);
9460
+ assertPayTransaction(txBytes, {
9461
+ ...expectedPay,
9462
+ gas: {
9463
+ mode: gasMode,
9464
+ ...gasMode === "agent" ? { gas: deps.gas } : {},
9465
+ expiration: await readPayExpirationPolicy(txBytes, deps)
9466
+ }
9467
+ });
8424
9468
  } catch (err) {
9469
+ if (err instanceof SuiPayError && err.code === "chain.unavailable") {
9470
+ logInternal(log, { code: "chain.unavailable", msg: "pre-sign chain read failed" }, err);
9471
+ return abortBeforeSign("PREPARED_VERIFY_UNAVAILABLE", PUBLIC_DETAIL.PREPARED_VERIFY_UNAVAILABLE);
9472
+ }
8425
9473
  logInternal(log, { code: "client.tx_mismatch", msg: "pre-sign pay validation failed" }, err);
8426
9474
  return abortBeforeSign(gasMode === "sponsored" ? "SPONSORED_TX_MISMATCH" : "TX_MISMATCH", gasMode === "sponsored" ? PUBLIC_DETAIL.SPONSORED_TX_MISMATCH : PUBLIC_DETAIL.TX_MISMATCH);
8427
9475
  }
@@ -8688,7 +9736,18 @@ async function payX402Reserved(ctx) {
8688
9736
  return ctx.abort("BUILD_FAILED", PUBLIC_DETAIL.BUILD_FAILED);
8689
9737
  }
8690
9738
  try {
8691
- assertPayTransaction(txBytes, ctx.expected);
9739
+ assertPayTransaction(txBytes, {
9740
+ ...ctx.expected,
9741
+ gas: {
9742
+ mode: "sponsored",
9743
+ gas: ctx.buildInput.gas,
9744
+ expiration: {
9745
+ currentEpoch: ctx.buildInput.currentEpoch,
9746
+ chainIdentifier: ctx.buildInput.chainIdentifier,
9747
+ requireBounded: true
9748
+ }
9749
+ }
9750
+ });
8692
9751
  } catch (err) {
8693
9752
  logInternal(log, { code: "client.tx_mismatch", msg: "pre-sign x402 pay validation failed" }, err);
8694
9753
  return ctx.abort("TX_MISMATCH", PUBLIC_DETAIL.TX_MISMATCH);
@@ -8878,7 +9937,7 @@ function payMoveCallTarget(packageId, accessMode = "scoped", _guarded = false, r
8878
9937
  accessMode: accessMode === "open" ? "open" : "scoped",
8879
9938
  refundable
8880
9939
  });
8881
- return `${normalizeSuiAddress9(packageId)}::spend_account::${fn}`;
9940
+ return `${normalizeSuiAddress10(packageId)}::spend_account::${fn}`;
8882
9941
  }
8883
9942
  function resolveGuardedSettleOfflineInputs(input) {
8884
9943
  const core = [input.exclusionDirectoryId, input.recipientRegistryId, input.expiresAtMs];
@@ -8954,9 +10013,9 @@ function createMemoryLedger() {
8954
10013
  }
8955
10014
 
8956
10015
  // ../sdk/dist/agent-sdk/verify-prepared-settlement.js
8957
- import { normalizeSuiAddress as normalizeSuiAddress10 } from "@mysten/sui/utils";
8958
- import { Transaction as Transaction5 } from "@mysten/sui/transactions";
8959
- import { fromBase64 as fromBase648 } from "@mysten/sui/utils";
10016
+ import { normalizeSuiAddress as normalizeSuiAddress11 } from "@mysten/sui/utils";
10017
+ import { Transaction as Transaction6 } from "@mysten/sui/transactions";
10018
+ import { fromBase64 as fromBase649 } from "@mysten/sui/utils";
8960
10019
 
8961
10020
  // ../sdk/dist/protocol/prepared-settlement.js
8962
10021
  var PREPARED_SETTLEMENT_VERSION = 1;
@@ -9045,7 +10104,7 @@ function reject(field, message, cause) {
9045
10104
  }
9046
10105
  function sameAddress3(a, b) {
9047
10106
  try {
9048
- return normalizeSuiAddress10(a) === normalizeSuiAddress10(b);
10107
+ return normalizeSuiAddress11(a) === normalizeSuiAddress11(b);
9049
10108
  } catch {
9050
10109
  return false;
9051
10110
  }
@@ -9056,7 +10115,7 @@ function sameCoinType(a, b) {
9056
10115
  if (pkg === void 0 || rest.length !== 2)
9057
10116
  return value.trim();
9058
10117
  try {
9059
- return `${normalizeSuiAddress10(pkg)}::${rest.join("::")}`;
10118
+ return `${normalizeSuiAddress11(pkg)}::${rest.join("::")}`;
9060
10119
  } catch {
9061
10120
  return value.trim();
9062
10121
  }
@@ -9081,7 +10140,7 @@ async function verifyPreparedPayment(input) {
9081
10140
  }
9082
10141
  let data;
9083
10142
  try {
9084
- data = Transaction5.from(fromBase648(prepared.transactionBytes)).getData();
10143
+ data = Transaction6.from(fromBase649(prepared.transactionBytes)).getData();
9085
10144
  } catch {
9086
10145
  reject("transactionBytes", "prepared transaction bytes are not a Sui transaction");
9087
10146
  }
@@ -9196,9 +10255,15 @@ async function verifyPreparedPayment(input) {
9196
10255
  kindBytes: rebuilt,
9197
10256
  accessMode: prepared.accessMode,
9198
10257
  recipient: prepared.recipient,
9199
- refundable: offer.refundable === true
10258
+ refundable: offer.refundable === true,
10259
+ gas: {
10260
+ mode: "sponsored",
10261
+ expiration: await readPayExpirationPolicy(prepared.transactionBytes, input)
10262
+ }
9200
10263
  });
9201
10264
  } catch (err) {
10265
+ if (err instanceof SuiPayError && err.code === "chain.unavailable")
10266
+ throw err;
9202
10267
  reject("transactionBytes", "prepared transaction does not reconstruct the intended settlement", err);
9203
10268
  }
9204
10269
  return prepared;
@@ -9669,7 +10734,9 @@ async function resolvePayerSession(options) {
9669
10734
  ok: false,
9670
10735
  // The gateway's stable code, never a raw body — the read client already
9671
10736
  // 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}` : ""})`)
10737
+ // A 429 is the gateway's rate limit, not a manifest the agent can fix, so
10738
+ // it keeps the retryable code instead of the manifest default.
10739
+ 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
10740
  };
9674
10741
  }
9675
10742
  const whole = manifestToSession({
@@ -9768,10 +10835,10 @@ async function verifyGrantOnChain(input) {
9768
10835
  ok: false,
9769
10836
  error: manifestError(MANIFEST_ERROR_CODES.GRANT_NOT_VERIFIED, detail)
9770
10837
  });
9771
- if (!state.delegateAddress || normalizeSuiAddress11(state.delegateAddress) !== normalizeSuiAddress11(input.delegateAddress)) {
10838
+ if (!state.delegateAddress || normalizeSuiAddress12(state.delegateAddress) !== normalizeSuiAddress12(input.delegateAddress)) {
9772
10839
  return notVerified(`grant ${input.grantObjectId} does not name this delegate on chain`);
9773
10840
  }
9774
- if (!state.poolObjectId || normalizeSuiAddress11(state.poolObjectId) !== normalizeSuiAddress11(input.poolObjectId)) {
10841
+ if (!state.poolObjectId || normalizeSuiAddress12(state.poolObjectId) !== normalizeSuiAddress12(input.poolObjectId)) {
9775
10842
  return notVerified(`grant ${input.grantObjectId} draws on a different pool than the one resolved`);
9776
10843
  }
9777
10844
  if (state.revoked === true) {
@@ -9919,7 +10986,9 @@ async function createPayer(options) {
9919
10986
  offer,
9920
10987
  delegateAddress: address,
9921
10988
  expectedGrantObjectId: binding.grantObjectId,
9922
- expectedPoolObjectId: binding.poolObjectId
10989
+ expectedPoolObjectId: binding.poolObjectId,
10990
+ getCurrentEpoch: deps.getCurrentEpoch,
10991
+ getChainIdentifier: deps.getChainIdentifier
9923
10992
  });
9924
10993
  }
9925
10994
  return {
@@ -9927,8 +10996,44 @@ async function createPayer(options) {
9927
10996
  value: { address, deployment, grant: binding, session, pay, verifySettlement }
9928
10997
  };
9929
10998
  }
10999
+
11000
+ // ../sdk/dist/oauth/delegate-proof.js
11001
+ import { normalizeSuiAddress as normalizeSuiAddress13 } from "@mysten/sui/utils";
11002
+ import { verifyPersonalMessageSignature as verifyPersonalMessageSignature3 } from "@mysten/sui/verify";
11003
+ var OAUTH_DELEGATE_PROOF_TTL_MS = 15 * 6e4;
11004
+ function encodeOAuthDelegateProof(binding, expiresAtMs, ownerAddress) {
11005
+ if (!binding.delegateAddress || !Number.isSafeInteger(expiresAtMs) || expiresAtMs <= 0) {
11006
+ throw new Error("Invalid delegate proof binding.");
11007
+ }
11008
+ return new TextEncoder().encode(JSON.stringify([
11009
+ "suipay:oauth-delegate:v1",
11010
+ binding.clientId,
11011
+ binding.redirectUri,
11012
+ binding.resource,
11013
+ binding.scope,
11014
+ binding.codeChallenge,
11015
+ normalizeSuiAddress13(binding.delegateAddress),
11016
+ normalizeSuiAddress13(ownerAddress),
11017
+ expiresAtMs
11018
+ ]));
11019
+ }
11020
+ async function verifyOAuthDelegateProof(binding, proof, nowMs = Date.now(), expectedOwner) {
11021
+ try {
11022
+ const p = proof;
11023
+ const message = encodeOAuthDelegateProof(binding, p.expiresAtMs, p.ownerAddress);
11024
+ if (typeof p.signature !== "string" || p.signature.length > 8192 || p.expiresAtMs <= nowMs || p.expiresAtMs > nowMs + OAUTH_DELEGATE_PROOF_TTL_MS)
11025
+ return false;
11026
+ if (expectedOwner && normalizeSuiAddress13(p.ownerAddress) !== normalizeSuiAddress13(expectedOwner))
11027
+ return false;
11028
+ const publicKey = await verifyPersonalMessageSignature3(message, p.signature);
11029
+ return publicKey.toSuiAddress() === normalizeSuiAddress13(binding.delegateAddress);
11030
+ } catch {
11031
+ return false;
11032
+ }
11033
+ }
9930
11034
  export {
9931
11035
  NativeTransferError,
11036
+ OAUTH_DELEGATE_PROOF_TTL_MS,
9932
11037
  SuiPayError,
9933
11038
  buildMcpPaymentPayload,
9934
11039
  buildNativeTransferBytes,
@@ -9939,10 +11044,12 @@ export {
9939
11044
  createPayer,
9940
11045
  createReader,
9941
11046
  dashboardManifestToAgentManifest,
11047
+ encodeOAuthDelegateProof,
9942
11048
  inspectNativeTransfer,
9943
11049
  manifestToSession,
9944
11050
  parseAgentManifest,
9945
11051
  personalMessageSigner,
9946
11052
  toErrorFields,
11053
+ verifyOAuthDelegateProof,
9947
11054
  verifyPreparedPayment
9948
11055
  };