@ocap/tx-pipeline 1.31.1 → 1.31.2

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.
Files changed (105) hide show
  1. package/esm/bridge-release-keys.d.mts +33 -0
  2. package/esm/bridge-release-keys.mjs +81 -0
  3. package/esm/bridge-reserves.d.mts +107 -0
  4. package/esm/bridge-reserves.mjs +242 -0
  5. package/esm/helpers/bridge-withdraw.d.mts +86 -0
  6. package/esm/helpers/bridge-withdraw.mjs +123 -0
  7. package/esm/helpers/replay-guard.d.mts +19 -1
  8. package/esm/helpers/replay-guard.mjs +39 -1
  9. package/esm/index.d.mts +3 -1
  10. package/esm/index.mjs +8 -6
  11. package/esm/legacy-protocol-sunset.d.mts +2 -2
  12. package/esm/legacy-protocol-sunset.mjs +5 -5
  13. package/esm/legacy-rollup-archive.d.mts +67 -0
  14. package/esm/legacy-rollup-archive.mjs +199 -0
  15. package/esm/library.d.mts +4 -4
  16. package/esm/library.mjs +3 -3
  17. package/esm/native-abt-exchange.d.mts +3 -0
  18. package/esm/native-abt-exchange.mjs +93 -46
  19. package/esm/pipes/bridge-release-gate.d.mts +30 -0
  20. package/esm/pipes/bridge-release-gate.mjs +143 -0
  21. package/esm/pipes/bridge-reserve-v2-gate.d.mts +53 -0
  22. package/esm/pipes/bridge-reserve-v2-gate.mjs +264 -0
  23. package/esm/pipes/decode-tx.mjs +29 -4
  24. package/esm/pipes/extract-signer.mjs +1 -1
  25. package/esm/pipes/extract-state.mjs +2 -2
  26. package/esm/pipes/post-execution-invariant-gate.d.mts +19 -2
  27. package/esm/pipes/post-execution-invariant-gate.mjs +121 -6
  28. package/esm/pipes/pre-flight-waf.d.mts +18 -1
  29. package/esm/pipes/pre-flight-waf.mjs +48 -13
  30. package/esm/pipes/update-owner.mjs +1 -1
  31. package/esm/pipes/verify-account-migration.mjs +1 -1
  32. package/esm/pipes/verify-delegation.mjs +49 -25
  33. package/esm/pipes/verify-multisig-v2.mjs +5 -4
  34. package/esm/pipes/verify-multisig.mjs +5 -4
  35. package/esm/pipes/verify-signature.d.mts +7 -1
  36. package/esm/pipes/verify-signature.mjs +119 -16
  37. package/esm/pipes/verify-signer.mjs +2 -2
  38. package/esm/pipes/verify-token-access.mjs +1 -1
  39. package/esm/pipes/verify-token-balance.mjs +1 -1
  40. package/esm/pipes/verify-tx-input.mjs +1 -1
  41. package/esm/pipes/verify-tx-size.mjs +1 -1
  42. package/esm/pipes/verify-tx.mjs +12 -5
  43. package/esm/super-suites-foundation.mjs +6 -6
  44. package/esm/transaction-block.d.mts +6 -2
  45. package/esm/transaction-block.mjs +282 -40
  46. package/esm/uniswap-router.d.mts +247 -1
  47. package/esm/uniswap-router.mjs +573 -2
  48. package/lib/bridge-release-keys.cjs +88 -0
  49. package/lib/bridge-release-keys.d.cts +33 -0
  50. package/lib/bridge-reserves.cjs +257 -0
  51. package/lib/bridge-reserves.d.cts +107 -0
  52. package/lib/helpers/bridge-withdraw.cjs +136 -0
  53. package/lib/helpers/bridge-withdraw.d.cts +86 -0
  54. package/lib/helpers/replay-guard.cjs +39 -0
  55. package/lib/helpers/replay-guard.d.cts +20 -2
  56. package/lib/index.cjs +25 -5
  57. package/lib/index.d.cts +3 -1
  58. package/lib/legacy-protocol-sunset.cjs +7 -7
  59. package/lib/legacy-protocol-sunset.d.cts +2 -2
  60. package/lib/legacy-rollup-archive.cjs +208 -0
  61. package/lib/legacy-rollup-archive.d.cts +67 -0
  62. package/lib/library.cjs +14 -68
  63. package/lib/library.d.cts +4 -4
  64. package/lib/native-abt-exchange.cjs +93 -46
  65. package/lib/native-abt-exchange.d.cts +3 -0
  66. package/lib/pipes/bridge-release-gate.cjs +145 -0
  67. package/lib/pipes/bridge-release-gate.d.cts +30 -0
  68. package/lib/pipes/bridge-reserve-v2-gate.cjs +273 -0
  69. package/lib/pipes/bridge-reserve-v2-gate.d.cts +53 -0
  70. package/lib/pipes/decode-itx.d.cts +1 -1
  71. package/lib/pipes/decode-tx.cjs +28 -3
  72. package/lib/pipes/decode-tx.d.cts +1 -1
  73. package/lib/pipes/extract-signer.cjs +1 -1
  74. package/lib/pipes/extract-state.cjs +3 -3
  75. package/lib/pipes/post-execution-invariant-gate.cjs +121 -4
  76. package/lib/pipes/post-execution-invariant-gate.d.cts +19 -2
  77. package/lib/pipes/pre-flight-waf.cjs +51 -13
  78. package/lib/pipes/pre-flight-waf.d.cts +19 -2
  79. package/lib/pipes/update-owner.cjs +1 -1
  80. package/lib/pipes/update-owner.d.cts +1 -1
  81. package/lib/pipes/verify-account-migration.cjs +1 -1
  82. package/lib/pipes/verify-delegation.cjs +50 -26
  83. package/lib/pipes/verify-multisig-v2.cjs +5 -4
  84. package/lib/pipes/verify-multisig.cjs +5 -4
  85. package/lib/pipes/verify-service-fee.d.cts +1 -1
  86. package/lib/pipes/verify-signature.cjs +118 -14
  87. package/lib/pipes/verify-signature.d.cts +8 -2
  88. package/lib/pipes/verify-signer.cjs +2 -2
  89. package/lib/pipes/verify-token-access.cjs +1 -1
  90. package/lib/pipes/verify-token-balance.cjs +1 -1
  91. package/lib/pipes/verify-tx-input.cjs +1 -1
  92. package/lib/pipes/verify-tx-size.cjs +1 -1
  93. package/lib/pipes/verify-tx-size.d.cts +1 -1
  94. package/lib/pipes/verify-tx.cjs +11 -5
  95. package/lib/pipes/verify-tx.d.cts +1 -1
  96. package/lib/super-suites-foundation.cjs +6 -6
  97. package/lib/transaction-block.cjs +282 -40
  98. package/lib/transaction-block.d.cts +6 -2
  99. package/lib/uniswap-router.cjs +576 -1
  100. package/lib/uniswap-router.d.cts +247 -1
  101. package/package.json +10 -10
  102. package/esm/evm-simplified-bridge.d.mts +0 -1370
  103. package/esm/evm-simplified-bridge.mjs +0 -3875
  104. package/lib/evm-simplified-bridge.cjs +0 -3943
  105. package/lib/evm-simplified-bridge.d.cts +0 -1370
@@ -194,6 +194,18 @@ function buildAbtUtilityPassThroughPlan(input) {
194
194
  const sourceTxEvidenceHash = assertSafeIdentifier(input.sourceTxEvidenceHash, "sourceTxEvidenceHash");
195
195
  const targetAssetOrStakeAddress = input.targetAssetOrStakeAddress !== void 0 ? assertSafeIdentifier(input.targetAssetOrStakeAddress, "targetAssetOrStakeAddress") : void 0;
196
196
  if (!ALLOWED_SERVICE_TYPES.has(input.serviceType)) throw new CustomError("INVALID_ABT_PASSTHROUGH", `Unsupported serviceType: ${String(input.serviceType)}`);
197
+ if (input.selectedTreasuryTokenAddresses) {
198
+ const normalizeEvmOrNativeEth = (raw) => {
199
+ const stripped = raw.trim().replace(/^did:abt:/i, "").toLowerCase();
200
+ return stripped === "0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee" ? "native:eth" : stripped;
201
+ };
202
+ const normalizedPaymentToken = normalizeEvmOrNativeEth(assertEvmAddress(input.paymentTokenEvmAddress, "paymentTokenEvmAddress"));
203
+ const normalizedHops = Array.isArray(input.routePath) ? input.routePath.filter((h) => typeof h === "string").map(normalizeEvmOrNativeEth) : [];
204
+ for (const rawAllowed of input.selectedTreasuryTokenAddresses) if (typeof rawAllowed === "string") {
205
+ const canonicalAllowed = normalizeEvmOrNativeEth(rawAllowed);
206
+ if (canonicalAllowed === normalizedPaymentToken || normalizedHops.includes(canonicalAllowed)) throw new CustomError("SELECTED_CURRENCY_UNISWAP_SWAP_FORBIDDEN", `Selected treasury currency (${canonicalAllowed}) must be paid directly to Official External Treasury via buildDirectBuyTreasuryCashierPlan without swapping through Uniswap into ABT`);
207
+ }
208
+ }
197
209
  if (normalizeScreeningAddress(buyerOcapDid) === normalizeScreeningAddress(serviceRecipientDid) || normalizeScreeningAddress(buyerOcapDid) === normalizeScreeningAddress(relayerOcapDid)) throw new CustomError("SELF_DEALING_CONSUMPTIVE_BYPASS", "buyerOcapDid cannot be identical to serviceRecipientDid or relayerOcapDid in a 0-second consumptive pass-through");
198
210
  assertNotOfacSanctioned([
199
211
  input.senderEvmAddress,
@@ -529,7 +541,7 @@ function buildOutboundWithdrawAndSwapPlan(input) {
529
541
  });
530
542
  const ocapPostConditions = {
531
543
  signer: sellerOcapDid,
532
- maxTokenOutflow: { [abtOcapTokenAddress]: grossAbtBn.toString(10) },
544
+ maxTokenOutflow: { [sellerOcapDid]: { [abtOcapTokenAddress]: grossAbtBn.toString(10) } },
533
545
  strictZeroUnlistedOutflow: true
534
546
  };
535
547
  const fallbackToDirectAbt = input.fallbackToDirectAbtOnSwapFailure ?? true;
@@ -573,6 +585,565 @@ function buildOutboundWithdrawAndSwapPlan(input) {
573
585
  }
574
586
  };
575
587
  }
588
+ /**
589
+ * Issue #1408 (`#blockchain seq: 830, 831, 833, 834`):
590
+ * Default Selected Valuable External Currencies that our Official External Treasury directly accepts and holds,
591
+ * treated identically to Credit Card (Stripe) checkout — NEVER swapped into ABT on Uniswap.
592
+ */
593
+ const DEFAULT_SELECTED_TREASURY_CURRENCY_SYMBOLS = [
594
+ "ETH",
595
+ "WETH",
596
+ "USDC",
597
+ "USDT",
598
+ "SOL"
599
+ ];
600
+ /**
601
+ * Maximum number of consumed external payment evidences retained in `DirectBuyTreasuryCashier` memory
602
+ * to enforce bounded hardware I/O envelope.
603
+ */
604
+ const MAX_TRACKED_DIRECT_BUY_EVIDENCES = 1e4;
605
+ const SOLANA_ADDRESS_OR_NATIVE_REGEX = /^(?:native:sol|[1-9A-HJ-NP-Za-km-z]{32,44})$/;
606
+ const EXTERNAL_TX_HASH_REGEX = /^(?:0x[0-9a-fA-F]{64}|[1-9A-HJ-NP-Za-km-z]{43,88})$/;
607
+ const COLON_FREE_SAFE_ID_REGEX = /^[a-zA-Z0-9._-]{1,64}$/;
608
+ const NATIVE_ETH_EVM_PSEUDO_ADDRESS = "0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee";
609
+ const MAX_DIRECT_BUY_RELAYER_FEE_BPS = 1e3;
610
+ function assertColonFreeIdentifier(value, fieldName) {
611
+ const trimmed = assertSafeIdentifier(value, fieldName);
612
+ if (!COLON_FREE_SAFE_ID_REGEX.test(trimmed)) throw new CustomError("INVALID_DIRECT_BUY_CASHIER", `${fieldName} must match /^[a-zA-Z0-9._-]{1,64}$/ (colons and whitespace are forbidden): ${trimmed}`);
613
+ return trimmed;
614
+ }
615
+ function normalizeOcapDidIdentifier(value, fieldName) {
616
+ const trimmed = assertSafeIdentifier(value, fieldName).replace(/^did:abt:/i, "");
617
+ if (!trimmed || FORBIDDEN_KEYS.has(trimmed) || !COLON_FREE_SAFE_ID_REGEX.test(trimmed)) throw new CustomError("INVALID_DIRECT_BUY_CASHIER", `Invalid OCAP identifier for ${fieldName}: ${String(value)}`);
618
+ return trimmed;
619
+ }
620
+ function normalizeExternalChainAddress(address, chainFamily, fieldName, allowNativePseudoAddress = false) {
621
+ if (typeof address !== "string") throw new CustomError("INVALID_DIRECT_BUY_CASHIER", `${fieldName} must be a non-empty string`);
622
+ const trimmed = address.trim().replace(/^did:abt:/i, "");
623
+ if (chainFamily === "EVM") {
624
+ const lower = trimmed.toLowerCase();
625
+ if (lower === "native:eth" || lower === NATIVE_ETH_EVM_PSEUDO_ADDRESS) {
626
+ if (!allowNativePseudoAddress) throw new CustomError("INVALID_DIRECT_BUY_CASHIER", `${fieldName} cannot be native ETH pseudo-address (${trimmed})`);
627
+ return "native:eth";
628
+ }
629
+ if (!EVM_HEX_ADDRESS_REGEX.test(trimmed)) throw new CustomError("INVALID_DIRECT_BUY_CASHIER", `${fieldName} must be a valid 20-byte 0x EVM address${allowNativePseudoAddress ? " or 'native:eth'" : ""}`);
630
+ return lower;
631
+ }
632
+ if (chainFamily === "SOLANA") {
633
+ if (allowNativePseudoAddress && trimmed.toLowerCase() === "native:sol") return "native:sol";
634
+ if (!SOLANA_ADDRESS_OR_NATIVE_REGEX.test(trimmed) || !allowNativePseudoAddress && trimmed.toLowerCase() === "native:sol") throw new CustomError("INVALID_DIRECT_BUY_CASHIER", `${fieldName} must be a valid Solana Base58 address${allowNativePseudoAddress ? " or 'native:sol'" : ""}`);
635
+ return trimmed;
636
+ }
637
+ throw new CustomError("INVALID_DIRECT_BUY_CASHIER", `Unsupported chainFamily: ${String(chainFamily)}`);
638
+ }
639
+ function findSelectedTreasuryCurrency(currencies, chainFamily, chainId, normalizedTokenAddress) {
640
+ for (const spec of currencies) {
641
+ if (!spec || typeof spec !== "object") continue;
642
+ if (spec.chainFamily !== chainFamily || spec.chainId.trim() !== chainId) continue;
643
+ const specToken = normalizeExternalChainAddress(spec.tokenAddress, spec.chainFamily, "selectedTreasuryCurrencies.tokenAddress", true);
644
+ if (specToken === normalizedTokenAddress) return {
645
+ ...spec,
646
+ chainId: spec.chainId.trim(),
647
+ tokenAddress: specToken
648
+ };
649
+ }
650
+ }
651
+ function validateSelectedTreasuryCurrencySpec(spec) {
652
+ if (!spec || typeof spec !== "object") throw new CustomError("INVALID_DIRECT_BUY_CASHIER", "Invalid selectedTreasuryCurrencies entry");
653
+ if (!DEFAULT_SELECTED_TREASURY_CURRENCY_SYMBOLS.includes(spec.symbol) || typeof spec.decimals !== "number" || !Number.isSafeInteger(spec.decimals) || spec.decimals < 1 || spec.decimals > 24) throw new CustomError("INVALID_DIRECT_BUY_CASHIER", `Selected treasury currency symbol must be one of ${DEFAULT_SELECTED_TREASURY_CURRENCY_SYMBOLS.join(", ")} with decimals in 1..24`);
654
+ const chainId = assertColonFreeIdentifier(spec.chainId, "selectedTreasuryCurrencies.chainId");
655
+ const tokenAddress = normalizeExternalChainAddress(spec.tokenAddress, spec.chainFamily, "selectedTreasuryCurrencies.tokenAddress", true);
656
+ if (spec.symbol === "ETH" || tokenAddress === "native:eth") {
657
+ if (spec.chainFamily !== "EVM" || spec.symbol !== "ETH" || tokenAddress !== "native:eth" || spec.decimals !== 18) throw new CustomError("INVALID_DIRECT_BUY_CASHIER", "Native ETH selectedTreasuryCurrencies entry must have chainFamily=\"EVM\", symbol=\"ETH\", tokenAddress=\"native:eth\", and decimals=18");
658
+ }
659
+ if (spec.symbol === "WETH") {
660
+ if (spec.chainFamily !== "EVM" || tokenAddress === "native:eth" || spec.decimals !== 18) throw new CustomError("INVALID_DIRECT_BUY_CASHIER", "WETH selectedTreasuryCurrencies entry must have chainFamily=\"EVM\", a 20-byte ERC-20 address, and decimals=18");
661
+ }
662
+ if (spec.symbol === "SOL" || tokenAddress === "native:sol") {
663
+ if (spec.chainFamily !== "SOLANA" || spec.symbol !== "SOL" || tokenAddress !== "native:sol" || spec.decimals !== 9) throw new CustomError("INVALID_DIRECT_BUY_CASHIER", "Native SOL selectedTreasuryCurrencies entry must have chainFamily=\"SOLANA\", symbol=\"SOL\", tokenAddress=\"native:sol\", and decimals=9");
664
+ }
665
+ const officialUsdPriceMicroPerUnit = parsePositiveUint(spec.officialUsdPriceMicroPerUnit, "selectedTreasuryCurrencies.officialUsdPriceMicroPerUnit").toString(10);
666
+ return {
667
+ symbol: spec.symbol,
668
+ chainFamily: spec.chainFamily,
669
+ chainId,
670
+ tokenAddress,
671
+ decimals: spec.decimals,
672
+ officialUsdPriceMicroPerUnit
673
+ };
674
+ }
675
+ function validateSelectedTreasuryCurrencyList(specs) {
676
+ if (!Array.isArray(specs) || specs.length === 0) throw new CustomError("INVALID_DIRECT_BUY_CASHIER", "selectedTreasuryCurrencies must be a non-empty whitelist of accepted treasury reserve currencies");
677
+ const validated = [];
678
+ const seenTokenKeys = /* @__PURE__ */ new Set();
679
+ const seenSymbolKeys = /* @__PURE__ */ new Set();
680
+ for (const raw of specs) {
681
+ const item = validateSelectedTreasuryCurrencySpec(raw);
682
+ const tokenKey = `${item.chainFamily}:${item.chainId}:${item.tokenAddress}`;
683
+ const symbolKey = `${item.chainFamily}:${item.chainId}:${item.symbol}`;
684
+ if (seenTokenKeys.has(tokenKey) || seenSymbolKeys.has(symbolKey)) throw new CustomError("INVALID_DIRECT_BUY_CASHIER", `Duplicate selectedTreasuryCurrencies definition for ${tokenKey} (${item.symbol})`);
685
+ seenTokenKeys.add(tokenKey);
686
+ seenSymbolKeys.add(symbolKey);
687
+ validated.push(item);
688
+ }
689
+ return validated;
690
+ }
691
+ /**
692
+ * Issue #1408 (`#blockchain seq: 830, 831, 833, 834`):
693
+ * Builds a Bridge-Decoupled, Stripe-Equivalent Direct Buy Treasury Cashier Plan:
694
+ *
695
+ * 1. **Selected Valuable External Currencies (`ETH`, `WETH`, `USDC`, `USDT`, `SOL`) = Credit Card (Stripe) Equivalent**:
696
+ * - **Zero Uniswap Swap**: Never routed through Uniswap to buy `ABT` (rejects `unlistedTokenSwap` on selected currencies).
697
+ * - **Zero Bridge Coupling**: Paid directly to our controlled `officialExternalTreasuryAddress` (never to `ArcEvmBridgeGateway` / `MultiSigVault`).
698
+ * - **Two OCAP Fulfillment Modes**:
699
+ * - `FIRST_PARTY_DIRECT_PAYMENT`: For our own first-party services, OCAP directly delivers the service/credit/asset/VC without any `ABT` conversion.
700
+ * - `OFFICIAL_TREASURY_ABT_RELEASE`: When the target OCAP protocol/merchant requires `ABT`, our `officialOcapTreasuryDid` directly releases existing `ABT` on OCAP using `CATALOG_FIXED_PRICE` or `OFFICIAL_PRICING_RATE` (0 `deposit_token_v2`).
701
+ *
702
+ * 2. **Unlisted / Unrecognized External Tokens (Anti-Scam-Token Gate)**:
703
+ * - Our Official External Treasury Wallet **never accepts or holds unlisted tokens directly** (`UNLISTED_TOKEN_DIRECT_TREASURY_PAYMENT_FORBIDDEN`).
704
+ * - User must swap the unlisted token on the external chain via Uniswap **into a Selected Treasury Currency (`USDC`, `USDT`, `WETH`)** swept to `officialExternalTreasuryAddress`, after which OCAP fulfillment proceeds via the same Bridge-free cashier flow.
705
+ */
706
+ function buildDirectBuyTreasuryCashierPlan(input) {
707
+ if (!input || typeof input !== "object") throw new CustomError("INVALID_DIRECT_BUY_CASHIER", "Missing Direct Buy Treasury Cashier input");
708
+ const orderId = assertColonFreeIdentifier(input.orderId, "orderId");
709
+ const serviceId = assertColonFreeIdentifier(input.serviceId, "serviceId");
710
+ const chainId = assertColonFreeIdentifier(input.chainId, "chainId");
711
+ const buyerOcapDid = normalizeOcapDidIdentifier(input.buyerOcapDid, "buyerOcapDid");
712
+ const serviceRecipientDid = normalizeOcapDidIdentifier(input.serviceRecipientDid, "serviceRecipientDid");
713
+ const targetAssetOrStakeAddress = input.targetAssetOrStakeAddress !== void 0 ? normalizeOcapDidIdentifier(input.targetAssetOrStakeAddress, "targetAssetOrStakeAddress") : void 0;
714
+ if (!ALLOWED_SERVICE_TYPES.has(input.serviceType)) throw new CustomError("INVALID_DIRECT_BUY_CASHIER", `Unsupported serviceType: ${String(input.serviceType)}`);
715
+ if (input.ocapFulfillmentMode !== "FIRST_PARTY_DIRECT_PAYMENT" && input.ocapFulfillmentMode !== "OFFICIAL_TREASURY_ABT_RELEASE") throw new CustomError("INVALID_DIRECT_BUY_CASHIER", `Unsupported ocapFulfillmentMode: ${String(input.ocapFulfillmentMode)}`);
716
+ if (input.pricingPolicyMode !== "CATALOG_FIXED_PRICE" && input.pricingPolicyMode !== "OFFICIAL_PRICING_RATE") throw new CustomError("INVALID_DIRECT_BUY_CASHIER", `Unsupported pricingPolicyMode: ${String(input.pricingPolicyMode)}`);
717
+ const validatedCurrencies = validateSelectedTreasuryCurrencyList(input.selectedTreasuryCurrencies);
718
+ const senderExternalAddress = normalizeExternalChainAddress(input.senderExternalAddress, input.chainFamily, "senderExternalAddress", false);
719
+ const officialExternalTreasuryAddress = normalizeExternalChainAddress(input.officialExternalTreasuryAddress, input.chainFamily, "officialExternalTreasuryAddress", false);
720
+ const paymentTokenAddress = normalizeExternalChainAddress(input.paymentTokenAddress, input.chainFamily, "paymentTokenAddress", true);
721
+ if (senderExternalAddress === officialExternalTreasuryAddress) throw new CustomError("INVALID_DIRECT_BUY_CASHIER", "senderExternalAddress must be distinct from officialExternalTreasuryAddress");
722
+ let normalizedBridgeAddr;
723
+ if (input.bridgeContractAddress !== void 0) {
724
+ normalizedBridgeAddr = normalizeExternalChainAddress(input.bridgeContractAddress, input.chainFamily, "bridgeContractAddress", false);
725
+ if (normalizedBridgeAddr === officialExternalTreasuryAddress) throw new CustomError("DIRECT_BUY_BRIDGE_COUPLING_FORBIDDEN", "officialExternalTreasuryAddress must be 100% decoupled from bridgeContractAddress (Direct Buy never deposits into the ABT Bridge)");
726
+ }
727
+ const normalizedAbtExternalToken = input.abtExternalTokenAddress !== void 0 ? normalizeExternalChainAddress(input.abtExternalTokenAddress, input.chainFamily, "abtExternalTokenAddress", false) : void 0;
728
+ if (normalizedAbtExternalToken && paymentTokenAddress === normalizedAbtExternalToken) throw new CustomError("DIRECT_BUY_ABT_DEX_SWAP_FORBIDDEN", "Direct Buy Cashier is for non-ABT external currencies (ETH/USDC/USDT/SOL or unlisted tokens swapped into them); ERC-20 ABT uses the 1:1 ABT Bridge");
729
+ if (typeof input.externalPaymentTxHash !== "string" || !EXTERNAL_TX_HASH_REGEX.test(input.externalPaymentTxHash.trim())) throw new CustomError("INVALID_DIRECT_BUY_CASHIER", "externalPaymentTxHash must be a valid 32-byte 0x EVM tx hash or Solana Base58 signature");
730
+ const externalPaymentTxHash = input.chainFamily === "EVM" ? input.externalPaymentTxHash.trim().toLowerCase() : input.externalPaymentTxHash.trim();
731
+ const externalLogIndex = input.externalLogIndex ?? 0;
732
+ if (typeof externalLogIndex !== "number" || !Number.isSafeInteger(externalLogIndex) || externalLogIndex < 0) throw new CustomError("INVALID_DIRECT_BUY_CASHIER", "externalLogIndex must be a non-negative safe integer");
733
+ if ((paymentTokenAddress === "native:eth" || paymentTokenAddress === "native:sol") && externalLogIndex !== 0) throw new CustomError("INVALID_DIRECT_BUY_CASHIER", "externalLogIndex must be 0 for native ETH / native SOL transfers");
734
+ const minConfirmations = input.minConfirmations ?? 12;
735
+ if (typeof minConfirmations !== "number" || !Number.isSafeInteger(minConfirmations) || minConfirmations < 1) throw new CustomError("INVALID_DIRECT_BUY_CASHIER", "minConfirmations must be a positive safe integer");
736
+ if (input.reorged === true) throw new CustomError("REORGED_EXTERNAL_PAYMENT", `External payment transaction ${externalPaymentTxHash} was marked reorged and cannot be fulfilled`);
737
+ if (typeof input.confirmations !== "number" || !Number.isSafeInteger(input.confirmations) || input.confirmations < minConfirmations) throw new CustomError("INSUFFICIENT_EXTERNAL_CONFIRMATIONS", `External payment confirmations (${String(input.confirmations)}) is below minConfirmations (${minConfirmations})`);
738
+ if (normalizeScreeningAddress(buyerOcapDid) === normalizeScreeningAddress(serviceRecipientDid) || targetAssetOrStakeAddress !== void 0 && normalizeScreeningAddress(buyerOcapDid) === normalizeScreeningAddress(targetAssetOrStakeAddress)) throw new CustomError("SELF_DEALING_DIRECT_BUY_BYPASS", "buyerOcapDid cannot be identical to serviceRecipientDid or targetAssetOrStakeAddress in Direct Buy Cashier");
739
+ const paymentAmountInBn = parsePositiveUint(input.paymentAmountIn, "paymentAmountIn");
740
+ const catalogUsdPriceMicroBn = parsePositiveUint(input.catalogUsdPriceMicro, "catalogUsdPriceMicro");
741
+ const directSelectedSpec = findSelectedTreasuryCurrency(validatedCurrencies, input.chainFamily, chainId, paymentTokenAddress);
742
+ let externalSettlementMode;
743
+ let settledCurrencySpec;
744
+ let settledTreasuryAmountBn;
745
+ let unlistedTokenSwapPayload;
746
+ if (directSelectedSpec) {
747
+ if (input.unlistedTokenSwap !== void 0) throw new CustomError("SELECTED_CURRENCY_UNISWAP_SWAP_FORBIDDEN", `Selected treasury currency ${directSelectedSpec.symbol} (${paymentTokenAddress}) is treated identically to Credit Card (Stripe) and MUST NOT be swapped through Uniswap`);
748
+ externalSettlementMode = "SELECTED_TREASURY_CURRENCY_DIRECT_TRANSFER";
749
+ settledCurrencySpec = directSelectedSpec;
750
+ settledTreasuryAmountBn = paymentAmountInBn;
751
+ } else {
752
+ if (paymentTokenAddress === "native:eth" || paymentTokenAddress === "native:sol") throw new CustomError("SELECTED_CURRENCY_UNISWAP_SWAP_FORBIDDEN", `Native ${paymentTokenAddress === "native:eth" ? "ETH" : "SOL"} is a Selected Treasury Currency and must be paid directly to officialExternalTreasuryAddress without Uniswap swap`);
753
+ if (!input.unlistedTokenSwap) throw new CustomError("UNLISTED_TOKEN_DIRECT_TREASURY_PAYMENT_FORBIDDEN", `Unlisted external token (${paymentTokenAddress}) cannot be paid directly to Official External Treasury; user must swap it on external Uniswap into a Selected Treasury Currency (${DEFAULT_SELECTED_TREASURY_CURRENCY_SYMBOLS.join("/")}) first`);
754
+ if (input.chainFamily !== "EVM") throw new CustomError("INVALID_DIRECT_BUY_CASHIER", "unlistedTokenSwap via Uniswap Universal Router is only supported on EVM chains");
755
+ const targetTreasuryTokenAddr = normalizeExternalChainAddress(input.unlistedTokenSwap.settledTreasuryTokenAddress, "EVM", "unlistedTokenSwap.settledTreasuryTokenAddress", false);
756
+ if (normalizedAbtExternalToken) {
757
+ const normalizedSwapHops = Array.isArray(input.unlistedTokenSwap.routePath) ? input.unlistedTokenSwap.routePath.map((hop, idx) => normalizeExternalChainAddress(hop, "EVM", `unlistedTokenSwap.routePath[${idx}]`, false)) : [];
758
+ if (targetTreasuryTokenAddr === normalizedAbtExternalToken || normalizedSwapHops.includes(normalizedAbtExternalToken)) throw new CustomError("DIRECT_BUY_ABT_DEX_SWAP_FORBIDDEN", "Unlisted external tokens in Direct Buy must swap into a Selected Treasury Currency (USDC/USDT/WETH) delivered to officialExternalTreasuryAddress, never into or through ERC-20 ABT");
759
+ }
760
+ const targetSelectedSpec = findSelectedTreasuryCurrency(validatedCurrencies, "EVM", chainId, targetTreasuryTokenAddr);
761
+ if (!targetSelectedSpec) throw new CustomError("UNLISTED_SWAP_OUTPUT_NOT_SELECTED_CURRENCY", `unlistedTokenSwap.settledTreasuryTokenAddress (${targetTreasuryTokenAddr}) must be a whitelisted Selected Treasury Currency on chain ${chainId}`);
762
+ unlistedTokenSwapPayload = buildUniversalRouterCrossChainPayload({
763
+ chainId,
764
+ senderEvmAddress: senderExternalAddress,
765
+ buyerOcapDid,
766
+ universalRouterAddress: input.unlistedTokenSwap.universalRouterAddress,
767
+ ocapVaultAddress: officialExternalTreasuryAddress,
768
+ tokenIn: paymentTokenAddress,
769
+ tokenOut: targetTreasuryTokenAddr,
770
+ routePath: input.unlistedTokenSwap.routePath,
771
+ poolVersion: input.unlistedTokenSwap.poolVersion ?? "v4",
772
+ amountIn: paymentAmountInBn.toString(10),
773
+ expectedAmountOut: input.unlistedTokenSwap.expectedSettledTreasuryAmountOut,
774
+ maxSlippageBps: input.unlistedTokenSwap.maxSlippageBps,
775
+ deadline: input.unlistedTokenSwap.deadline,
776
+ currentTimestamp: input.unlistedTokenSwap.currentTimestamp,
777
+ permit2: input.unlistedTokenSwap.permit2,
778
+ integratorId: input.unlistedTokenSwap.integratorId,
779
+ brokerageFeeBps: 0,
780
+ ofacBlocklist: input.ofacBlocklist
781
+ });
782
+ externalSettlementMode = "UNLISTED_TOKEN_EXTERNAL_UNISWAP_TO_TREASURY_CURRENCY";
783
+ settledCurrencySpec = targetSelectedSpec;
784
+ settledTreasuryAmountBn = new BN(unlistedTokenSwapPayload.amountOutMinimum, 10);
785
+ }
786
+ const unitScaleBn = new BN(10).pow(new BN(settledCurrencySpec.decimals));
787
+ const usdPricePerUnitBn = new BN(settledCurrencySpec.officialUsdPriceMicroPerUnit, 10);
788
+ const settledTreasuryValueUsdMicroBn = settledTreasuryAmountBn.mul(usdPricePerUnitBn).div(unitScaleBn);
789
+ if (settledTreasuryValueUsdMicroBn.lt(catalogUsdPriceMicroBn)) throw new CustomError("INSUFFICIENT_TREASURY_PAYMENT_FOR_CATALOG_PRICE", `Settled treasury value (${settledTreasuryValueUsdMicroBn.toString(10)} micro-USD in ${settledCurrencySpec.symbol}) is less than catalogUsdPriceMicro (${catalogUsdPriceMicroBn.toString(10)} micro-USD)`);
790
+ assertNotOfacSanctioned([
791
+ senderExternalAddress,
792
+ officialExternalTreasuryAddress,
793
+ normalizedBridgeAddr,
794
+ normalizedAbtExternalToken,
795
+ paymentTokenAddress,
796
+ settledCurrencySpec.tokenAddress,
797
+ buyerOcapDid,
798
+ serviceRecipientDid,
799
+ targetAssetOrStakeAddress,
800
+ input.officialOcapTreasuryDid,
801
+ input.relayerOcapDid,
802
+ input.abtOcapTokenAddress
803
+ ], input.ofacBlocklist);
804
+ const statements = [];
805
+ let treasuryPostConditions;
806
+ let buyerPostConditions;
807
+ let abtServicePriceWeiStr = "0";
808
+ let abtRelayerFeeWeiStr = "0";
809
+ let totalAbtReleasedStr = "0";
810
+ let officialOcapTreasuryDid;
811
+ let abtOcapTokenAddress;
812
+ let relayerOcapDid;
813
+ if (input.ocapFulfillmentMode === "FIRST_PARTY_DIRECT_PAYMENT") {
814
+ statements.push({
815
+ type: "transfer_v3",
816
+ typeUrl: "fg:t:transfer_v3",
817
+ from: serviceRecipientDid,
818
+ itx: {
819
+ to: buyerOcapDid,
820
+ tokens: [],
821
+ data: {
822
+ type: "json",
823
+ value: JSON.stringify({
824
+ directBuyFulfillment: "FIRST_PARTY_DIRECT_PAYMENT",
825
+ stripeEquivalent: true,
826
+ orderId,
827
+ serviceId,
828
+ serviceType: input.serviceType,
829
+ target: targetAssetOrStakeAddress || serviceRecipientDid,
830
+ externalChainFamily: input.chainFamily,
831
+ externalChainId: chainId,
832
+ externalPaymentTxHash,
833
+ externalLogIndex,
834
+ settledCurrencySymbol: settledCurrencySpec.symbol,
835
+ settledTreasuryCurrencyAmount: settledTreasuryAmountBn.toString(10),
836
+ catalogUsdPriceMicro: catalogUsdPriceMicroBn.toString(10)
837
+ })
838
+ }
839
+ }
840
+ });
841
+ buyerPostConditions = {
842
+ signer: buyerOcapDid,
843
+ maxTokenOutflow: { [buyerOcapDid]: {} },
844
+ strictZeroUnlistedOutflow: true
845
+ };
846
+ } else {
847
+ officialOcapTreasuryDid = normalizeOcapDidIdentifier(input.officialOcapTreasuryDid ?? "", "officialOcapTreasuryDid");
848
+ abtOcapTokenAddress = normalizeOcapDidIdentifier(input.abtOcapTokenAddress ?? "", "abtOcapTokenAddress");
849
+ relayerOcapDid = input.relayerOcapDid !== void 0 ? normalizeOcapDidIdentifier(input.relayerOcapDid, "relayerOcapDid") : void 0;
850
+ const abtRelayerFeeBn = input.abtRelayerFeeWei !== void 0 ? parseNonNegativeUint(input.abtRelayerFeeWei, "abtRelayerFeeWei") : new BN(0);
851
+ if (normalizeScreeningAddress(officialOcapTreasuryDid) === normalizeScreeningAddress(buyerOcapDid) || normalizeScreeningAddress(officialOcapTreasuryDid) === normalizeScreeningAddress(serviceRecipientDid) || targetAssetOrStakeAddress !== void 0 && normalizeScreeningAddress(officialOcapTreasuryDid) === normalizeScreeningAddress(targetAssetOrStakeAddress)) throw new CustomError("INVALID_DIRECT_BUY_CASHIER", "officialOcapTreasuryDid must be distinct from buyerOcapDid, serviceRecipientDid, and targetAssetOrStakeAddress");
852
+ if (abtRelayerFeeBn.gt(new BN(0)) && !relayerOcapDid) throw new CustomError("INVALID_DIRECT_BUY_CASHIER", "relayerOcapDid is required when abtRelayerFeeWei is greater than 0");
853
+ if (relayerOcapDid !== void 0 && (normalizeScreeningAddress(relayerOcapDid) === normalizeScreeningAddress(buyerOcapDid) || normalizeScreeningAddress(relayerOcapDid) === normalizeScreeningAddress(serviceRecipientDid) || normalizeScreeningAddress(relayerOcapDid) === normalizeScreeningAddress(officialOcapTreasuryDid))) throw new CustomError("SELF_DEALING_DIRECT_BUY_BYPASS", "relayerOcapDid must be distinct from buyerOcapDid, serviceRecipientDid, and officialOcapTreasuryDid");
854
+ const abtScaleBn = new BN(ABT_DECIMALS_SCALE, 10);
855
+ const officialAbtPriceMicroUsdBn = input.officialAbtPriceMicroUsd !== void 0 ? parsePositiveUint(input.officialAbtPriceMicroUsd, "officialAbtPriceMicroUsd") : void 0;
856
+ let abtServicePriceBn;
857
+ if (input.pricingPolicyMode === "CATALOG_FIXED_PRICE") abtServicePriceBn = parsePositiveUint(input.abtCatalogPriceWei ?? "", "abtCatalogPriceWei");
858
+ else {
859
+ if (!officialAbtPriceMicroUsdBn) throw new CustomError("INVALID_DIRECT_BUY_CASHIER", "officialAbtPriceMicroUsd is required when pricingPolicyMode is OFFICIAL_PRICING_RATE");
860
+ abtServicePriceBn = catalogUsdPriceMicroBn.mul(abtScaleBn).add(officialAbtPriceMicroUsdBn.sub(new BN(1))).div(officialAbtPriceMicroUsdBn);
861
+ }
862
+ const maxAllowedRelayerFeeBn = abtServicePriceBn.mul(new BN(MAX_DIRECT_BUY_RELAYER_FEE_BPS)).div(new BN(1e4));
863
+ if (abtRelayerFeeBn.gt(maxAllowedRelayerFeeBn)) throw new CustomError("EXCESSIVE_DIRECT_BUY_RELAYER_FEE", `abtRelayerFeeWei (${abtRelayerFeeBn.toString(10)}) exceeds maximum allowed ${MAX_DIRECT_BUY_RELAYER_FEE_BPS} bps (10%) of abtServicePriceWei (${abtServicePriceBn.toString(10)})`);
864
+ const totalAbtReleasedBn = abtServicePriceBn.add(abtRelayerFeeBn);
865
+ const proportionalRelayerUsdMicroBn = catalogUsdPriceMicroBn.mul(abtRelayerFeeBn).add(abtServicePriceBn.sub(new BN(1))).div(abtServicePriceBn);
866
+ let requiredTotalUsdMicroBn = catalogUsdPriceMicroBn.add(proportionalRelayerUsdMicroBn);
867
+ if (officialAbtPriceMicroUsdBn) {
868
+ const releasedAbtUsdMicroBn = totalAbtReleasedBn.mul(officialAbtPriceMicroUsdBn).div(abtScaleBn);
869
+ if (releasedAbtUsdMicroBn.gt(requiredTotalUsdMicroBn)) requiredTotalUsdMicroBn = releasedAbtUsdMicroBn;
870
+ }
871
+ if (settledTreasuryValueUsdMicroBn.lt(requiredTotalUsdMicroBn)) throw new CustomError("INSUFFICIENT_TREASURY_PAYMENT_FOR_ABT_RELEASE", `Settled treasury value (${settledTreasuryValueUsdMicroBn.toString(10)} micro-USD) is less than required backing (${requiredTotalUsdMicroBn.toString(10)} micro-USD) for releasing ${totalAbtReleasedBn.toString(10)} wei ABT`);
872
+ abtServicePriceWeiStr = abtServicePriceBn.toString(10);
873
+ abtRelayerFeeWeiStr = abtRelayerFeeBn.toString(10);
874
+ totalAbtReleasedStr = totalAbtReleasedBn.toString(10);
875
+ statements.push({
876
+ type: "transfer_v3",
877
+ typeUrl: "fg:t:transfer_v3",
878
+ from: officialOcapTreasuryDid,
879
+ itx: {
880
+ to: buyerOcapDid,
881
+ tokens: [{
882
+ address: abtOcapTokenAddress,
883
+ value: abtServicePriceWeiStr
884
+ }],
885
+ data: {
886
+ type: "json",
887
+ value: JSON.stringify({
888
+ directBuyFulfillment: "OFFICIAL_TREASURY_ABT_RELEASE",
889
+ pricingPolicyMode: input.pricingPolicyMode,
890
+ bridgeDecoupled: true,
891
+ orderId,
892
+ serviceId,
893
+ externalChainFamily: input.chainFamily,
894
+ externalChainId: chainId,
895
+ externalPaymentTxHash,
896
+ externalLogIndex,
897
+ settledCurrencySymbol: settledCurrencySpec.symbol,
898
+ settledTreasuryCurrencyAmount: settledTreasuryAmountBn.toString(10)
899
+ })
900
+ }
901
+ }
902
+ });
903
+ if (abtRelayerFeeBn.gt(new BN(0)) && relayerOcapDid) statements.push({
904
+ type: "transfer_v3",
905
+ typeUrl: "fg:t:transfer_v3",
906
+ from: officialOcapTreasuryDid,
907
+ itx: {
908
+ to: relayerOcapDid,
909
+ tokens: [{
910
+ address: abtOcapTokenAddress,
911
+ value: abtRelayerFeeWeiStr
912
+ }],
913
+ data: {
914
+ type: "json",
915
+ value: JSON.stringify({
916
+ directBuyFulfillment: "OFFICIAL_TREASURY_RELAYER_FEE",
917
+ orderId,
918
+ externalPaymentTxHash
919
+ })
920
+ }
921
+ }
922
+ });
923
+ const consumeStatement = input.serviceType === "nft_purchase" ? {
924
+ type: "acquire_asset_v3",
925
+ typeUrl: "fg:t:acquire_asset_v3",
926
+ from: buyerOcapDid,
927
+ itx: {
928
+ to: serviceRecipientDid,
929
+ factory: targetAssetOrStakeAddress || serviceRecipientDid,
930
+ token: {
931
+ address: abtOcapTokenAddress,
932
+ value: abtServicePriceWeiStr
933
+ }
934
+ }
935
+ } : input.serviceType === "utility_stake" ? {
936
+ type: "stake",
937
+ typeUrl: "fg:t:stake",
938
+ from: buyerOcapDid,
939
+ itx: {
940
+ address: targetAssetOrStakeAddress || serviceRecipientDid,
941
+ receiver: serviceRecipientDid,
942
+ tokens: [{
943
+ address: abtOcapTokenAddress,
944
+ value: abtServicePriceWeiStr
945
+ }]
946
+ }
947
+ } : {
948
+ type: "transfer_v3",
949
+ typeUrl: "fg:t:transfer_v3",
950
+ from: buyerOcapDid,
951
+ itx: {
952
+ to: serviceRecipientDid,
953
+ tokens: [{
954
+ address: abtOcapTokenAddress,
955
+ value: abtServicePriceWeiStr
956
+ }],
957
+ data: {
958
+ type: "json",
959
+ value: JSON.stringify({
960
+ consumptiveUse: true,
961
+ orderId,
962
+ serviceId,
963
+ serviceType: input.serviceType,
964
+ target: targetAssetOrStakeAddress || serviceRecipientDid
965
+ })
966
+ }
967
+ }
968
+ };
969
+ statements.push(consumeStatement);
970
+ treasuryPostConditions = {
971
+ signer: officialOcapTreasuryDid,
972
+ maxTokenOutflow: { [officialOcapTreasuryDid]: { [abtOcapTokenAddress]: totalAbtReleasedStr } },
973
+ strictZeroUnlistedOutflow: true
974
+ };
975
+ buyerPostConditions = {
976
+ signer: buyerOcapDid,
977
+ maxTokenOutflow: { [buyerOcapDid]: { [abtOcapTokenAddress]: "0" } },
978
+ strictZeroUnlistedOutflow: true
979
+ };
980
+ }
981
+ const evidenceKey = `${input.chainFamily}:${chainId}:${externalPaymentTxHash}:${externalLogIndex}`;
982
+ const canonicalDigestPreimage = JSON.stringify({
983
+ domain: "OCAP_DIRECT_BUY_TREASURY_CASHIER_V1",
984
+ orderId,
985
+ serviceId,
986
+ serviceType: input.serviceType,
987
+ externalSettlementMode,
988
+ ocapFulfillmentMode: input.ocapFulfillmentMode,
989
+ pricingPolicyMode: input.pricingPolicyMode,
990
+ evidenceKey,
991
+ senderExternalAddress,
992
+ officialExternalTreasuryAddress,
993
+ userPaymentTokenAddress: paymentTokenAddress,
994
+ userPaymentAmountIn: paymentAmountInBn.toString(10),
995
+ settledCurrencySymbol: settledCurrencySpec.symbol,
996
+ settledTreasuryTokenAddress: settledCurrencySpec.tokenAddress,
997
+ settledTreasuryAmount: settledTreasuryAmountBn.toString(10),
998
+ settledTreasuryValueUsdMicro: settledTreasuryValueUsdMicroBn.toString(10),
999
+ catalogUsdPriceMicro: catalogUsdPriceMicroBn.toString(10),
1000
+ unlistedTokenSwapCalldataDigest: unlistedTokenSwapPayload?.calldataDigest ?? null,
1001
+ buyerOcapDid,
1002
+ serviceRecipientDid,
1003
+ targetAssetOrStakeAddress: targetAssetOrStakeAddress ?? null,
1004
+ officialOcapTreasuryDid: officialOcapTreasuryDid ?? null,
1005
+ abtOcapTokenAddress: abtOcapTokenAddress ?? null,
1006
+ relayerOcapDid: relayerOcapDid ?? null,
1007
+ abtServicePriceWei: abtServicePriceWeiStr,
1008
+ abtRelayerFeeWei: abtRelayerFeeWeiStr
1009
+ });
1010
+ const planDigest = `0x${Hasher.SHA3.hash256(Buffer.from(canonicalDigestPreimage, "utf8")).replace(/^0x/i, "").toLowerCase()}`;
1011
+ const actions = externalSettlementMode === "SELECTED_TREASURY_CURRENCY_DIRECT_TRANSFER" ? [`Direct transfer ${settledTreasuryAmountBn.toString(10)} ${settledCurrencySpec.symbol} to Official External Treasury (${officialExternalTreasuryAddress}) — 0 Uniswap Swap, 0 Bridge`] : [`Swap unlisted token (${paymentTokenAddress}) -> ${settledCurrencySpec.symbol} (${settledCurrencySpec.tokenAddress}) on external Uniswap and sweep to Official External Treasury (${officialExternalTreasuryAddress}) — 0 Bridge`];
1012
+ if (input.ocapFulfillmentMode === "FIRST_PARTY_DIRECT_PAYMENT") actions.push(`Stripe-equivalent direct OCAP fulfillment of ${serviceId} (${input.serviceType}) from ${serviceRecipientDid} to ${buyerOcapDid} (0 ABT conversion required)`);
1013
+ else actions.push(`Official OCAP Treasury (${officialOcapTreasuryDid}) releases ${abtServicePriceWeiStr} ABT (${input.pricingPolicyMode}) directly on OCAP`, `Buyer (${buyerOcapDid}) atomically consumes ${abtServicePriceWeiStr} ABT at ${serviceRecipientDid} (${input.serviceType})`);
1014
+ return {
1015
+ orderId,
1016
+ serviceId,
1017
+ serviceType: input.serviceType,
1018
+ externalSettlementMode,
1019
+ ocapFulfillmentMode: input.ocapFulfillmentMode,
1020
+ pricingPolicyMode: input.pricingPolicyMode,
1021
+ bridgeDecoupled: true,
1022
+ usesBridgeDepositProtocol: false,
1023
+ selectedCurrencySwappedOnUniswap: false,
1024
+ externalSettlementSpec: {
1025
+ chainFamily: input.chainFamily,
1026
+ chainId,
1027
+ senderExternalAddress,
1028
+ officialExternalTreasuryAddress,
1029
+ userPaymentTokenAddress: paymentTokenAddress,
1030
+ userPaymentAmountIn: paymentAmountInBn.toString(10),
1031
+ settledTreasuryCurrencySymbol: settledCurrencySpec.symbol,
1032
+ settledTreasuryTokenAddress: settledCurrencySpec.tokenAddress,
1033
+ settledTreasuryCurrencyAmount: settledTreasuryAmountBn.toString(10),
1034
+ settledTreasuryValueUsdMicro: settledTreasuryValueUsdMicroBn.toString(10),
1035
+ externalPaymentTxHash,
1036
+ externalLogIndex,
1037
+ confirmations: input.confirmations,
1038
+ unlistedTokenSwapPayload
1039
+ },
1040
+ ocapExecutionSpec: {
1041
+ buyerOcapDid,
1042
+ serviceRecipientDid,
1043
+ officialOcapTreasuryDid,
1044
+ abtOcapTokenAddress,
1045
+ abtReleasedFromTreasuryWei: totalAbtReleasedStr,
1046
+ abtServicePriceWei: abtServicePriceWeiStr,
1047
+ abtRelayerFeeWei: abtRelayerFeeWeiStr,
1048
+ statements,
1049
+ treasuryPostConditions,
1050
+ buyerPostConditions
1051
+ },
1052
+ economics: {
1053
+ stripeEquivalentDirectTreasuryCollection: true,
1054
+ uniswapSwapUsedForSelectedCurrency: false,
1055
+ bridgeRollupUsed: false,
1056
+ netBuyerSpeculativeAbtRetained: "0",
1057
+ holdingPeriodSeconds: 0,
1058
+ catalogUsdPriceMicro: catalogUsdPriceMicroBn.toString(10),
1059
+ settledTreasuryValueUsdMicro: settledTreasuryValueUsdMicroBn.toString(10),
1060
+ abtServicePriceWei: abtServicePriceWeiStr,
1061
+ abtRelayerFeeWei: abtRelayerFeeWeiStr,
1062
+ totalAbtReleasedFromOcapTreasuryWei: totalAbtReleasedStr
1063
+ },
1064
+ clearSigningSummary: {
1065
+ youPayExternal: externalSettlementMode === "SELECTED_TREASURY_CURRENCY_DIRECT_TRANSFER" ? `${paymentAmountInBn.toString(10)} ${settledCurrencySpec.symbol} (Direct to Official Treasury ${officialExternalTreasuryAddress})` : `${paymentAmountInBn.toString(10)} (${paymentTokenAddress}) -> min ${settledTreasuryAmountBn.toString(10)} ${settledCurrencySpec.symbol} (Swept to Official Treasury ${officialExternalTreasuryAddress})`,
1066
+ externalSettlement: externalSettlementMode,
1067
+ ocapFulfillmentMode: input.ocapFulfillmentMode,
1068
+ actions,
1069
+ youReceiveOnOcap: `Service ${serviceId} (${input.serviceType}) delivered to ${buyerOcapDid}`
1070
+ },
1071
+ evidenceKey,
1072
+ planDigest
1073
+ };
1074
+ }
1075
+ /**
1076
+ * Stateful, replay-protected Direct Buy Treasury Cashier coordinator (#1408).
1077
+ * Enforces:
1078
+ * - Zero Bridge coupling (never emits `deposit_token_v2` or touches `ArcEvmBridgeGateway` / `MultiSigVault`)
1079
+ * - Zero Uniswap swap for Selected Treasury Currencies (`ETH`, `WETH`, `USDC`, `USDT`, `SOL`)
1080
+ * - Anti-Scam-Token gate for Unlisted Tokens (must swap on external Uniswap into a Selected Treasury Currency first)
1081
+ * - Triple replay protection on `evidenceKey` (`chainFamily:chainId:txHash:logIndex`), `txKey` (`chainFamily:chainId:txHash`), and `orderId`
1082
+ */
1083
+ var DirectBuyTreasuryCashier = class {
1084
+ constructor(config) {
1085
+ this.consumedEvidenceKeys = /* @__PURE__ */ new Set();
1086
+ this.consumedTxKeys = /* @__PURE__ */ new Set();
1087
+ this.consumedOrderIds = /* @__PURE__ */ new Set();
1088
+ if (!config || typeof config !== "object") throw new CustomError("INVALID_DIRECT_BUY_CASHIER", "Missing DirectBuyTreasuryCashierConfig");
1089
+ this.selectedTreasuryCurrencies = validateSelectedTreasuryCurrencyList(config.selectedTreasuryCurrencies);
1090
+ this.officialOcapTreasuryDid = normalizeOcapDidIdentifier(config.officialOcapTreasuryDid, "officialOcapTreasuryDid");
1091
+ this.abtOcapTokenAddress = normalizeOcapDidIdentifier(config.abtOcapTokenAddress, "abtOcapTokenAddress");
1092
+ this.officialAbtPriceMicroUsd = parsePositiveUint(config.officialAbtPriceMicroUsd, "officialAbtPriceMicroUsd").toString(10);
1093
+ this.minConfirmationsByChainFamily = {
1094
+ EVM: config.minConfirmationsByChainFamily?.EVM ?? 12,
1095
+ SOLANA: config.minConfirmationsByChainFamily?.SOLANA ?? 32
1096
+ };
1097
+ const maxTracked = config.maxTrackedEvidences ?? MAX_TRACKED_DIRECT_BUY_EVIDENCES;
1098
+ if (typeof maxTracked !== "number" || !Number.isSafeInteger(maxTracked) || maxTracked < 1 || maxTracked > MAX_TRACKED_DIRECT_BUY_EVIDENCES) throw new CustomError("INVALID_DIRECT_BUY_CASHIER", `maxTrackedEvidences must be an integer between 1 and ${MAX_TRACKED_DIRECT_BUY_EVIDENCES}`);
1099
+ this.maxTrackedEvidences = maxTracked;
1100
+ this.defaultOfacBlocklist = config.ofacBlocklist ? Array.from(config.ofacBlocklist) : [];
1101
+ assertNotOfacSanctioned([this.officialOcapTreasuryDid, this.abtOcapTokenAddress], this.defaultOfacBlocklist);
1102
+ }
1103
+ updateOfficialAbtPriceMicroUsd(newPriceMicroUsd) {
1104
+ this.officialAbtPriceMicroUsd = parsePositiveUint(newPriceMicroUsd, "newPriceMicroUsd").toString(10);
1105
+ }
1106
+ isEvidenceConsumed(evidenceKey) {
1107
+ if (typeof evidenceKey !== "string") return false;
1108
+ return this.consumedEvidenceKeys.has(evidenceKey.trim());
1109
+ }
1110
+ isOrderConsumed(orderId) {
1111
+ if (typeof orderId !== "string") return false;
1112
+ return this.consumedOrderIds.has(orderId.trim());
1113
+ }
1114
+ processExternalDirectBuyOrder(input) {
1115
+ const minConfirmations = input.minConfirmations ?? this.minConfirmationsByChainFamily[input.chainFamily] ?? 12;
1116
+ const mergedOfacBlocklist = input.ofacBlocklist ? [...this.defaultOfacBlocklist, ...Array.from(input.ofacBlocklist)] : this.defaultOfacBlocklist;
1117
+ const plan = buildDirectBuyTreasuryCashierPlan({
1118
+ ...input,
1119
+ minConfirmations,
1120
+ selectedTreasuryCurrencies: this.selectedTreasuryCurrencies,
1121
+ officialOcapTreasuryDid: this.officialOcapTreasuryDid,
1122
+ abtOcapTokenAddress: this.abtOcapTokenAddress,
1123
+ officialAbtPriceMicroUsd: input.officialAbtPriceMicroUsd ?? this.officialAbtPriceMicroUsd,
1124
+ ofacBlocklist: mergedOfacBlocklist
1125
+ });
1126
+ const txKey = `${plan.externalSettlementSpec.chainFamily}:${plan.externalSettlementSpec.chainId}:${plan.externalSettlementSpec.externalPaymentTxHash}`;
1127
+ if (this.consumedEvidenceKeys.has(plan.evidenceKey) || this.consumedTxKeys.has(txKey)) throw new CustomError("REPLAYED_DIRECT_BUY_EVIDENCE", `External payment evidence ${plan.evidenceKey} (tx ${txKey}) has already been consumed`);
1128
+ if (this.consumedOrderIds.has(plan.orderId)) throw new CustomError("REPLAYED_DIRECT_BUY_ORDER", `Direct buy order ${plan.orderId} has already been consumed`);
1129
+ if (this.consumedEvidenceKeys.size >= this.maxTrackedEvidences) {
1130
+ const oldestEvidence = this.consumedEvidenceKeys.values().next().value;
1131
+ if (oldestEvidence !== void 0) this.consumedEvidenceKeys.delete(oldestEvidence);
1132
+ }
1133
+ if (this.consumedTxKeys.size >= this.maxTrackedEvidences) {
1134
+ const oldestTx = this.consumedTxKeys.values().next().value;
1135
+ if (oldestTx !== void 0) this.consumedTxKeys.delete(oldestTx);
1136
+ }
1137
+ if (this.consumedOrderIds.size >= this.maxTrackedEvidences) {
1138
+ const oldestOrder = this.consumedOrderIds.values().next().value;
1139
+ if (oldestOrder !== void 0) this.consumedOrderIds.delete(oldestOrder);
1140
+ }
1141
+ this.consumedEvidenceKeys.add(plan.evidenceKey);
1142
+ this.consumedTxKeys.add(txKey);
1143
+ this.consumedOrderIds.add(plan.orderId);
1144
+ return plan;
1145
+ }
1146
+ };
576
1147
 
577
1148
  //#endregion
578
- export { ABT_DECIMALS_SCALE, CHAINALYSIS_OFAC_ORACLE_ADDRESS, DEFAULT_OCAP_INTEGRATOR_ID, DEFAULT_USD_QUOTE_TTL_SECONDS, MAX_ALLOWED_ZAP_SLIPPAGE_BPS, MAX_ROUTE_PATH_LENGTH, MAX_USD_QUOTE_TTL_SECONDS, UNIVERSAL_ROUTER_COMMANDS, assertNotOfacSanctioned, buildAbtUtilityPassThroughPlan, buildOutboundWithdrawAndSwapPlan, buildUniversalRouterCrossChainPayload, createUsdAnchoredAbtQuote, normalizeScreeningAddress, verifyUsdAnchoredAbtQuote };
1149
+ export { ABT_DECIMALS_SCALE, CHAINALYSIS_OFAC_ORACLE_ADDRESS, DEFAULT_OCAP_INTEGRATOR_ID, DEFAULT_SELECTED_TREASURY_CURRENCY_SYMBOLS, DEFAULT_USD_QUOTE_TTL_SECONDS, DirectBuyTreasuryCashier, MAX_ALLOWED_ZAP_SLIPPAGE_BPS, MAX_ROUTE_PATH_LENGTH, MAX_TRACKED_DIRECT_BUY_EVIDENCES, MAX_USD_QUOTE_TTL_SECONDS, UNIVERSAL_ROUTER_COMMANDS, assertNotOfacSanctioned, buildAbtUtilityPassThroughPlan, buildDirectBuyTreasuryCashierPlan, buildOutboundWithdrawAndSwapPlan, buildUniversalRouterCrossChainPayload, createUsdAnchoredAbtQuote, normalizeScreeningAddress, verifyUsdAnchoredAbtQuote };