@ocap/tx-pipeline 1.31.1 → 1.31.3

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