@ocap/tx-pipeline 1.30.26 → 1.31.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (149) hide show
  1. package/esm/appchain-sovereign-hub.d.mts +160 -0
  2. package/esm/appchain-sovereign-hub.mjs +348 -0
  3. package/esm/arcvault-external-adapter.d.mts +166 -0
  4. package/esm/arcvault-external-adapter.mjs +376 -0
  5. package/esm/encrypted-nft-envelope.d.mts +172 -0
  6. package/esm/encrypted-nft-envelope.mjs +458 -0
  7. package/esm/evm-simplified-bridge.d.mts +1370 -0
  8. package/esm/evm-simplified-bridge.mjs +3875 -0
  9. package/esm/give-to-mint-karma.d.mts +472 -0
  10. package/esm/give-to-mint-karma.mjs +1057 -0
  11. package/esm/helpers/replay-guard.d.mts +15 -0
  12. package/esm/helpers/replay-guard.mjs +23 -0
  13. package/esm/index.d.mts +10 -5
  14. package/esm/index.mjs +14 -10
  15. package/esm/legacy-protocol-sunset.d.mts +251 -0
  16. package/esm/legacy-protocol-sunset.mjs +1519 -0
  17. package/esm/library.d.mts +16 -0
  18. package/esm/library.mjs +17 -0
  19. package/esm/native-abt-exchange.d.mts +2055 -0
  20. package/esm/native-abt-exchange.mjs +7250 -0
  21. package/esm/ofac-screening.d.mts +17 -0
  22. package/esm/ofac-screening.mjs +39 -0
  23. package/esm/pipes/anti-land-attack.mjs +1 -1
  24. package/esm/pipes/decode-itx.mjs +46 -4
  25. package/esm/pipes/decode-tx.d.mts +2 -3
  26. package/esm/pipes/decode-tx.mjs +56 -115
  27. package/esm/pipes/extract-signer.mjs +2 -2
  28. package/esm/pipes/extract-state.mjs +14 -3
  29. package/esm/pipes/post-execution-invariant-gate.d.mts +61 -0
  30. package/esm/pipes/post-execution-invariant-gate.mjs +789 -0
  31. package/esm/pipes/pre-flight-waf.d.mts +73 -0
  32. package/esm/pipes/pre-flight-waf.mjs +756 -0
  33. package/esm/pipes/take-state-snapshot.mjs +3 -2
  34. package/esm/pipes/update-owner.mjs +39 -4
  35. package/esm/pipes/verify-account-migration.mjs +14 -4
  36. package/esm/pipes/verify-blocked.mjs +1 -1
  37. package/esm/pipes/verify-delegation.d.mts +22 -3
  38. package/esm/pipes/verify-delegation.mjs +259 -36
  39. package/esm/pipes/verify-list-size.mjs +1 -1
  40. package/esm/pipes/verify-multisig-v2.mjs +15 -7
  41. package/esm/pipes/verify-multisig.mjs +15 -7
  42. package/esm/pipes/verify-sender.mjs +1 -1
  43. package/esm/pipes/verify-signature.mjs +35 -6
  44. package/esm/pipes/verify-signer.mjs +2 -2
  45. package/esm/pipes/verify-state-diff.mjs +3 -3
  46. package/esm/pipes/verify-token-access.mjs +1 -1
  47. package/esm/pipes/verify-token-balance.mjs +13 -5
  48. package/esm/pipes/verify-transferrable.d.mts +8 -1
  49. package/esm/pipes/verify-transferrable.mjs +3 -3
  50. package/esm/pipes/verify-tx-input.mjs +2 -2
  51. package/esm/pipes/verify-tx-size.mjs +46 -2
  52. package/esm/pipes/verify-tx.mjs +5 -7
  53. package/esm/pipes/verify-updater.mjs +1 -1
  54. package/esm/social-economy-factories.d.mts +346 -0
  55. package/esm/social-economy-factories.mjs +845 -0
  56. package/esm/super-suites-foundation.d.mts +513 -0
  57. package/esm/super-suites-foundation.mjs +1241 -0
  58. package/esm/transaction-block.d.mts +471 -0
  59. package/esm/transaction-block.mjs +1906 -0
  60. package/esm/uniswap-erc7683-solver.d.mts +201 -0
  61. package/esm/uniswap-erc7683-solver.mjs +321 -0
  62. package/esm/uniswap-lp-copilot.d.mts +113 -0
  63. package/esm/uniswap-lp-copilot.mjs +320 -0
  64. package/esm/uniswap-router.d.mts +335 -0
  65. package/esm/uniswap-router.mjs +578 -0
  66. package/esm/uniswap-token-factory-graduation.d.mts +187 -0
  67. package/esm/uniswap-token-factory-graduation.mjs +426 -0
  68. package/esm/uniswap-v4-hook.d.mts +173 -0
  69. package/esm/uniswap-v4-hook.mjs +517 -0
  70. package/lib/appchain-sovereign-hub.cjs +352 -0
  71. package/lib/appchain-sovereign-hub.d.cts +160 -0
  72. package/lib/arcvault-external-adapter.cjs +383 -0
  73. package/lib/arcvault-external-adapter.d.cts +166 -0
  74. package/lib/encrypted-nft-envelope.cjs +477 -0
  75. package/lib/encrypted-nft-envelope.d.cts +172 -0
  76. package/lib/evm-simplified-bridge.cjs +3943 -0
  77. package/lib/evm-simplified-bridge.d.cts +1370 -0
  78. package/lib/give-to-mint-karma.cjs +1084 -0
  79. package/lib/give-to-mint-karma.d.cts +472 -0
  80. package/lib/helpers/replay-guard.cjs +27 -0
  81. package/lib/helpers/replay-guard.d.cts +15 -0
  82. package/lib/index.cjs +49 -16
  83. package/lib/index.d.cts +10 -5
  84. package/lib/legacy-protocol-sunset.cjs +1543 -0
  85. package/lib/legacy-protocol-sunset.d.cts +251 -0
  86. package/lib/library.cjs +303 -0
  87. package/lib/library.d.cts +16 -0
  88. package/lib/native-abt-exchange.cjs +7322 -0
  89. package/lib/native-abt-exchange.d.cts +2055 -0
  90. package/lib/ofac-screening.cjs +42 -0
  91. package/lib/ofac-screening.d.cts +17 -0
  92. package/lib/pipes/anti-land-attack.cjs +2 -2
  93. package/lib/pipes/decode-itx.cjs +46 -4
  94. package/lib/pipes/decode-itx.d.cts +1 -1
  95. package/lib/pipes/decode-tx.cjs +55 -116
  96. package/lib/pipes/decode-tx.d.cts +3 -4
  97. package/lib/pipes/extract-signer.cjs +2 -2
  98. package/lib/pipes/extract-state.cjs +14 -3
  99. package/lib/pipes/post-execution-invariant-gate.cjs +800 -0
  100. package/lib/pipes/post-execution-invariant-gate.d.cts +61 -0
  101. package/lib/pipes/pre-flight-waf.cjs +772 -0
  102. package/lib/pipes/pre-flight-waf.d.cts +73 -0
  103. package/lib/pipes/take-state-snapshot.cjs +3 -2
  104. package/lib/pipes/update-owner.cjs +40 -5
  105. package/lib/pipes/update-owner.d.cts +1 -1
  106. package/lib/pipes/verify-account-migration.cjs +14 -4
  107. package/lib/pipes/verify-blocked.cjs +1 -1
  108. package/lib/pipes/verify-delegation.cjs +259 -36
  109. package/lib/pipes/verify-delegation.d.cts +22 -3
  110. package/lib/pipes/verify-list-size.cjs +1 -1
  111. package/lib/pipes/verify-multisig-v2.cjs +15 -7
  112. package/lib/pipes/verify-multisig.cjs +15 -7
  113. package/lib/pipes/verify-sender.cjs +1 -1
  114. package/lib/pipes/verify-service-fee.d.cts +1 -1
  115. package/lib/pipes/verify-signature.cjs +35 -6
  116. package/lib/pipes/verify-signature.d.cts +1 -1
  117. package/lib/pipes/verify-signer.cjs +2 -2
  118. package/lib/pipes/verify-state-diff.cjs +4 -4
  119. package/lib/pipes/verify-token-access.cjs +2 -2
  120. package/lib/pipes/verify-token-balance.cjs +13 -5
  121. package/lib/pipes/verify-transferrable.cjs +3 -3
  122. package/lib/pipes/verify-transferrable.d.cts +8 -1
  123. package/lib/pipes/verify-tx-input.cjs +3 -3
  124. package/lib/pipes/verify-tx-size.cjs +46 -2
  125. package/lib/pipes/verify-tx-size.d.cts +1 -1
  126. package/lib/pipes/verify-tx.cjs +6 -8
  127. package/lib/pipes/verify-tx.d.cts +1 -1
  128. package/lib/pipes/verify-updater.cjs +1 -1
  129. package/lib/social-economy-factories.cjs +852 -0
  130. package/lib/social-economy-factories.d.cts +346 -0
  131. package/lib/super-suites-foundation.cjs +1257 -0
  132. package/lib/super-suites-foundation.d.cts +513 -0
  133. package/lib/transaction-block.cjs +1941 -0
  134. package/lib/transaction-block.d.cts +471 -0
  135. package/lib/uniswap-erc7683-solver.cjs +327 -0
  136. package/lib/uniswap-erc7683-solver.d.cts +201 -0
  137. package/lib/uniswap-lp-copilot.cjs +328 -0
  138. package/lib/uniswap-lp-copilot.d.cts +113 -0
  139. package/lib/uniswap-router.cjs +593 -0
  140. package/lib/uniswap-router.d.cts +335 -0
  141. package/lib/uniswap-token-factory-graduation.cjs +431 -0
  142. package/lib/uniswap-token-factory-graduation.d.cts +187 -0
  143. package/lib/uniswap-v4-hook.cjs +527 -0
  144. package/lib/uniswap-v4-hook.d.cts +173 -0
  145. package/package.json +11 -10
  146. package/esm/helpers/dedup-height.d.mts +0 -16
  147. package/esm/helpers/dedup-height.mjs +0 -61
  148. package/lib/helpers/dedup-height.cjs +0 -72
  149. package/lib/helpers/dedup-height.d.cts +0 -16
@@ -0,0 +1,73 @@
1
+ import { CustomError } from "@ocap/util/lib/error";
2
+ import { IBaseContext, IChainConfig, IDecodedContext, IDecodedTransaction } from "@ocap/types";
3
+
4
+ //#region src/pipes/pre-flight-waf.d.ts
5
+ declare const MAX_PREFLIGHT_JSON_DEPTH = 16;
6
+ declare const MAX_PREFLIGHT_JSON_KEYS = 512;
7
+ declare const MAX_PREFLIGHT_STRING_FIELD_BYTES: number;
8
+ declare const MAX_PREFLIGHT_WIRE_BYTES_FALLBACK: number;
9
+ declare const MAX_ROLLUP_TXS_LIST_SIZE = 512;
10
+ declare const MAX_DELEGATE_TYPE_URLS_LIST_SIZE = 128;
11
+ /**
12
+ * Fast O(1) wire-size and base64 character validation before allocating buffers or decoding.
13
+ */
14
+ declare function assertRawWireEnvelope(txBase64: string, config?: IChainConfig): void;
15
+ /**
16
+ * Reject unknown / alien fields in raw or CBOR `tx.itx` payloads that would otherwise be silently
17
+ * stripped by `createMessage()` or `vStripUnknown()`.
18
+ */
19
+ declare function assertKnownItxFields(typeUrl: string, rawInner: Record<string, unknown>): void;
20
+ /**
21
+ * Deep structural & anomaly scanner over decoded `itx` and raw `tx.itx`.
22
+ */
23
+ declare function scanItxPayloadAnomalies(itx: unknown, txType: string | undefined, config?: IChainConfig, rawTxItx?: unknown, txSignatures?: unknown): void;
24
+ /**
25
+ * Pipeline pipe that runs the Pre-Flight WAF structural & anomaly checks.
26
+ */
27
+ declare function PreFlightWaf(context: IDecodedContext, next: (err?: CustomError) => void): void;
28
+ declare namespace PreFlightWaf {
29
+ var SNAPSHOT_SYMBOL: typeof PREFLIGHT_VERIFIED_SNAPSHOT_SYMBOL;
30
+ var tryApplyVerifiedSnapshot: typeof tryApplyPreFlightVerifiedSnapshot;
31
+ }
32
+ declare const PREFLIGHT_VERIFIED_SNAPSHOT_SYMBOL: unique symbol;
33
+ interface IPreFlightVerifiedSnapshot {
34
+ txBase64: string;
35
+ configRef: IChainConfig | undefined;
36
+ chainId: unknown;
37
+ tokenDecimal: unknown;
38
+ txFeeForType: unknown;
39
+ maxTxSizeForType: unknown;
40
+ maxExtraSize: unknown;
41
+ maxMultisig: unknown;
42
+ maxListSize: unknown;
43
+ maxAssetSize: unknown;
44
+ isSupportedTx: boolean;
45
+ isMultiSignV2Tx: boolean;
46
+ txExtraSerialized: string;
47
+ gasStakeHeadersSerialized: string;
48
+ coSignatureSerialized: string;
49
+ tx: IDecodedTransaction;
50
+ txEncoding: 'cbor' | 'protobuf';
51
+ txSize: number;
52
+ baseTxSize: number;
53
+ extraSizeCounted: boolean;
54
+ txHash: string;
55
+ unsignedTxHash: string;
56
+ txBaseGas: boolean;
57
+ itx: Record<string, unknown>;
58
+ txType: string;
59
+ rawTxItxBeforeNormalize: unknown;
60
+ }
61
+ /**
62
+ * Apply the verified pre-flight snapshot onto `context` if and only if all verified inputs
63
+ * (`txBase64`, `config` invariants, and `extra.{txExtra,gasStakeHeaders,coSignature}`) are
64
+ * unchanged since `inspectTransactionPreFlight(context)` succeeded.
65
+ */
66
+ declare function tryApplyPreFlightVerifiedSnapshot(context: IBaseContext): boolean;
67
+ /**
68
+ * Stateless, zero-DB-I/O Pre-Flight inspection runner for `OCAPResolver.sendTx`
69
+ * BEFORE enqueuing into the single-writer queue (`this.queue`) or acquiring the SQLite write lock.
70
+ */
71
+ declare function inspectTransactionPreFlight(context: IBaseContext): Promise<IDecodedContext>;
72
+ //#endregion
73
+ export { IPreFlightVerifiedSnapshot, MAX_DELEGATE_TYPE_URLS_LIST_SIZE, MAX_PREFLIGHT_JSON_DEPTH, MAX_PREFLIGHT_JSON_KEYS, MAX_PREFLIGHT_STRING_FIELD_BYTES, MAX_PREFLIGHT_WIRE_BYTES_FALLBACK, MAX_ROLLUP_TXS_LIST_SIZE, PREFLIGHT_VERIFIED_SNAPSHOT_SYMBOL, assertKnownItxFields, assertRawWireEnvelope, PreFlightWaf as default, inspectTransactionPreFlight, scanItxPayloadAnomalies, tryApplyPreFlightVerifiedSnapshot };
@@ -18,8 +18,9 @@ function CreateTakeStateSnapshotPipe({ key = "stateSnapshot" } = {}) {
18
18
  const ctx = context;
19
19
  if (ctx.tx?.from && ctx.senderState?.address && ctx.senderState.address !== ctx.tx.from && !(0, _ocap_util.isSameDid)(ctx.senderState.address, ctx.tx.from)) return next(new _ocap_util_lib_error.CustomError("ACCOUNT_MIGRATED", "Cannot send tx from migrated account"));
20
20
  if (ctx.tx && !context.txType?.startsWith("fg:x:")) {
21
- if (ctx.tx.delegator && !ctx.delegationState && !ctx.isImplicitDelegation) return next(new _ocap_util_lib_error.CustomError("INVALID_DELEGATION", "Delegation is not supported for this transaction"));
22
- if ((0, _ocap_util_lib_get_list_field.getListField)(ctx.tx, "signatures").some((s) => Boolean(s?.delegator)) && !ctx.delegationStates && !Array.isArray(ctx.delegationState)) return next(new _ocap_util_lib_error.CustomError("INVALID_DELEGATION", "Multisig delegation is not supported for this transaction"));
21
+ const isSelfDelegationProtocol = context.txType === "fg:t:delegate" || context.txType === "fg:t:revoke_delegate";
22
+ if (ctx.tx.delegator && (isSelfDelegationProtocol || !ctx.isDelegationVerified && !ctx.delegationState && !ctx.isImplicitDelegation)) return next(new _ocap_util_lib_error.CustomError("INVALID_DELEGATION", "Delegation is not supported for this transaction"));
23
+ if ((0, _ocap_util_lib_get_list_field.getListField)(ctx.tx, "signatures").some((s) => Boolean(s?.delegator)) && (isSelfDelegationProtocol || !ctx.isMultiSigDelegationVerified && !ctx.delegationStates && !Array.isArray(ctx.delegationState))) return next(new _ocap_util_lib_error.CustomError("INVALID_DELEGATION", "Multisig delegation is not supported for this transaction"));
23
24
  }
24
25
  const [feeVaultState, gasVaultState] = await Promise.all([context.feeVault && !ctx.feeVaultState ? statedb.account.get(context.feeVault, context) : null, context.gasVault && !ctx.gasVaultState ? statedb.account.get(context.gasVault, context) : null]);
25
26
  if (feeVaultState) ctx.feeVaultState = feeVaultState;
@@ -1,11 +1,11 @@
1
1
  Object.defineProperty(exports, '__esModule', { value: true });
2
2
  const require_rolldown_runtime = require('../_virtual/rolldown_runtime.cjs');
3
3
  const require_package = require('../package.cjs');
4
- let lodash_get = require("lodash/get");
5
- lodash_get = require_rolldown_runtime.__toESM(lodash_get);
4
+ let _ocap_mcrypto = require("@ocap/mcrypto");
6
5
  let _ocap_util = require("@ocap/util");
7
6
  let _ocap_util_lib_error = require("@ocap/util/lib/error");
8
- let _ocap_mcrypto = require("@ocap/mcrypto");
7
+ let lodash_get = require("lodash/get");
8
+ lodash_get = require_rolldown_runtime.__toESM(lodash_get);
9
9
  let debug = require("debug");
10
10
  debug = require_rolldown_runtime.__toESM(debug);
11
11
  let lodash_set = require("lodash/set");
@@ -51,14 +51,49 @@ function CreateUpdateOwnerPipe({ assets, owner }) {
51
51
  });
52
52
  const hierarchyError = await verifyAssetHierarchy(itemList.map((item) => item.address), ownerAddress, context);
53
53
  if (hierarchyError) return next(hierarchyError);
54
+ const isTargetAsset = Boolean(ownerAddress && (0, _arcblock_did.toTypeInfo)(ownerAddress).role === _ocap_mcrypto.types.RoleType.ROLE_ASSET);
55
+ if (isTargetAsset && itemList.some((item) => states.token?.isTokenCharterAsset?.(item))) return next(new _ocap_util_lib_error.CustomError("INVALID_OWNER", "Token Charter NFT cannot be owned by an asset", { persist: true }));
54
56
  try {
55
- const updated = await Promise.all(itemList.map(async (item) => {
57
+ const prepared = await Promise.all(itemList.map(async (item) => {
56
58
  const old = await statedb.asset.get(item.address, context);
59
+ if (isTargetAsset && states.token?.isTokenCharterAsset?.(old)) throw new _ocap_util_lib_error.CustomError("INVALID_OWNER", "Token Charter NFT cannot be owned by an asset", { persist: true });
57
60
  const updates = states.asset.update(old, { owner: ownerAddress }, context);
58
- return statedb.asset.update(item.address, updates, context);
61
+ let tokenAddress;
62
+ let updatedToken = null;
63
+ let existingFactory = null;
64
+ let updatedFactory = null;
65
+ if (ownerAddress && states.token?.isTokenCharterAsset?.(old)) {
66
+ tokenAddress = (old?.data)?.value?.tokenAddress;
67
+ if (tokenAddress && statedb.token?.get && statedb.token?.update && states.token?.update) {
68
+ const existingToken = await statedb.token.get(tokenAddress, context);
69
+ if (existingToken) {
70
+ const safeToken = states.token.normalizeLegacyTokenStateForUpdate ? states.token.normalizeLegacyTokenStateForUpdate(existingToken) : existingToken;
71
+ updatedToken = states.token.update(safeToken, { issuer: ownerAddress });
72
+ if (existingToken.tokenFactoryAddress && statedb.tokenFactory?.get && statedb.tokenFactory?.update && states.tokenFactory?.update) {
73
+ existingFactory = await statedb.tokenFactory.get(existingToken.tokenFactoryAddress, context);
74
+ if (existingFactory) updatedFactory = states.tokenFactory.update(existingFactory, { owner: ownerAddress }, context);
75
+ }
76
+ }
77
+ }
78
+ }
79
+ return {
80
+ item,
81
+ updates,
82
+ tokenAddress,
83
+ updatedToken,
84
+ existingFactory,
85
+ updatedFactory
86
+ };
87
+ }));
88
+ const updated = await Promise.all(prepared.map(async ({ item, updates, tokenAddress, updatedToken, existingFactory, updatedFactory }) => {
89
+ const updatedAsset = await statedb.asset.update(item.address, updates, context);
90
+ if (tokenAddress && updatedToken && statedb.token?.update) await statedb.token.update(tokenAddress, updatedToken, context);
91
+ if (existingFactory && updatedFactory && statedb.tokenFactory?.update) await statedb.tokenFactory.update(existingFactory.address, updatedFactory, context);
92
+ return updatedAsset;
59
93
  }));
60
94
  (0, lodash_set.default)(context, assets, isList ? updated : updated.shift());
61
95
  } catch (err) {
96
+ if (err?.code === "INVALID_OWNER") return next(err);
62
97
  return next(new _ocap_util_lib_error.CustomError("INTERNAL", err.message, { persist: true }));
63
98
  }
64
99
  next();
@@ -1,6 +1,6 @@
1
1
  import { PipeFunction } from "../runner.cjs";
2
- import { IBaseContext } from "@ocap/types";
3
2
  import { CustomError } from "@ocap/util/lib/error";
3
+ import { IBaseContext } from "@ocap/types";
4
4
 
5
5
  //#region src/pipes/update-owner.d.ts
6
6
  declare function verifyAssetHierarchy(assetAddresses: string[], newOwnerAddress: string | undefined, context: IBaseContext, pendingOwners?: Record<string, string>, pendingConsumed?: string[]): Promise<CustomError | null>;
@@ -1,9 +1,10 @@
1
1
  Object.defineProperty(exports, '__esModule', { value: true });
2
2
  const require_rolldown_runtime = require('../_virtual/rolldown_runtime.cjs');
3
+ let _ocap_util_lib_error = require("@ocap/util/lib/error");
3
4
  let lodash_get = require("lodash/get");
4
5
  lodash_get = require_rolldown_runtime.__toESM(lodash_get);
5
- let _ocap_util_lib_error = require("@ocap/util/lib/error");
6
6
  let _ocap_util_lib_get_list_field = require("@ocap/util/lib/get-list-field");
7
+ let _ocap_util_lib_get_related_addr = require("@ocap/util/lib/get-related-addr");
7
8
 
8
9
  //#region src/pipes/verify-account-migration.ts
9
10
  function CreateVerifyAccountMigrationPipe({ stateKey = "", addressKey = "", signerKey = "" }) {
@@ -14,11 +15,15 @@ function CreateVerifyAccountMigrationPipe({ stateKey = "", addressKey = "", sign
14
15
  if (rawAddressList && rawStateList) {
15
16
  const stateList = (Array.isArray(rawStateList) ? rawStateList : [rawStateList]).filter(Boolean);
16
17
  const addressList = (Array.isArray(rawAddressList) ? rawAddressList : [rawAddressList]).filter(Boolean);
17
- if (stateList.length !== addressList.length) return next(new _ocap_util_lib_error.CustomError("INVALID_TX", "state and address list size mismatch for account migration verify", { persist: false }));
18
+ if (stateList.length !== addressList.length) {
19
+ const migratedAddr = addressList.find((addr) => !stateList.some((s) => s.address === addr) && stateList.some((s) => (0, _ocap_util_lib_get_related_addr.getRelatedAddresses)(s).includes(addr)));
20
+ if (migratedAddr) return next(new _ocap_util_lib_error.CustomError("ACCOUNT_MIGRATED", `account ${migratedAddr} is migrated`, { persist: true }));
21
+ return next(new _ocap_util_lib_error.CustomError("INVALID_TX", "state and address list size mismatch for account migration verify", { persist: false }));
22
+ }
18
23
  for (let i = 0; i < stateList.length; i += 1) {
19
24
  const state = stateList[i];
20
25
  const address = addressList[i];
21
- if (state.address !== address) return next(new _ocap_util_lib_error.CustomError("ACCOUNT_MIGRATED", `account ${address} is migrated`, { persist: true }));
26
+ if (state.address !== address || Array.isArray(state.migratedTo) && state.migratedTo.length > 0) return next(new _ocap_util_lib_error.CustomError("ACCOUNT_MIGRATED", `account ${address} is migrated`, { persist: true }));
22
27
  }
23
28
  }
24
29
  }
@@ -28,8 +33,13 @@ function CreateVerifyAccountMigrationPipe({ stateKey = "", addressKey = "", sign
28
33
  const signatures = (0, _ocap_util_lib_get_list_field.getListField)(context.tx, "signatures");
29
34
  for (const signature of signatures) {
30
35
  const state = signers.find((x) => x.address === signature.signer);
31
- if (!state || state.address !== signature.signer) return next(new _ocap_util_lib_error.CustomError("ACCOUNT_MIGRATED", `Signer account ${signature.signer} is migrated`, { persist: true }));
36
+ if (!state || state.address !== signature.signer || Array.isArray(state.migratedTo) && state.migratedTo.length > 0) return next(new _ocap_util_lib_error.CustomError("ACCOUNT_MIGRATED", `Signer account ${signature.signer} is migrated`, { persist: true }));
32
37
  }
38
+ } else if (signers && typeof signers === "object" && !Array.isArray(signers)) {
39
+ const singleState = signers;
40
+ const signatures = (0, _ocap_util_lib_get_list_field.getListField)(context.tx, "signatures");
41
+ const expectedAddress = (addressKey ? (0, lodash_get.default)(context, addressKey) : void 0) || signatures[0]?.signer;
42
+ if (expectedAddress && singleState.address !== expectedAddress || Array.isArray(singleState.migratedTo) && singleState.migratedTo.length > 0) return next(new _ocap_util_lib_error.CustomError("ACCOUNT_MIGRATED", `Signer account ${expectedAddress || singleState.address} is migrated`, { persist: true }));
33
43
  }
34
44
  }
35
45
  next();
@@ -1,8 +1,8 @@
1
1
  Object.defineProperty(exports, '__esModule', { value: true });
2
2
  const require_rolldown_runtime = require('../_virtual/rolldown_runtime.cjs');
3
+ let _ocap_util_lib_error = require("@ocap/util/lib/error");
3
4
  let lodash_get = require("lodash/get");
4
5
  lodash_get = require_rolldown_runtime.__toESM(lodash_get);
5
- let _ocap_util_lib_error = require("@ocap/util/lib/error");
6
6
  let _ocap_util_lib_get_related_addr = require("@ocap/util/lib/get-related-addr");
7
7
 
8
8
  //#region src/pipes/verify-blocked.ts
@@ -1,10 +1,10 @@
1
1
  Object.defineProperty(exports, '__esModule', { value: true });
2
2
  const require_rolldown_runtime = require('../_virtual/rolldown_runtime.cjs');
3
- let lodash_get = require("lodash/get");
4
- lodash_get = require_rolldown_runtime.__toESM(lodash_get);
3
+ let _ocap_mcrypto = require("@ocap/mcrypto");
5
4
  let _ocap_util = require("@ocap/util");
6
5
  let _ocap_util_lib_error = require("@ocap/util/lib/error");
7
- let _ocap_mcrypto = require("@ocap/mcrypto");
6
+ let lodash_get = require("lodash/get");
7
+ lodash_get = require_rolldown_runtime.__toESM(lodash_get);
8
8
  let _ocap_util_lib_get_list_field = require("@ocap/util/lib/get-list-field");
9
9
  let lodash_set = require("lodash/set");
10
10
  lodash_set = require_rolldown_runtime.__toESM(lodash_set);
@@ -12,25 +12,102 @@ let _arcblock_did = require("@arcblock/did");
12
12
  let _ocap_util_lib_get_related_addr = require("@ocap/util/lib/get-related-addr");
13
13
  let lodash_isEmpty = require("lodash/isEmpty");
14
14
  lodash_isEmpty = require_rolldown_runtime.__toESM(lodash_isEmpty);
15
+ let _ocap_wallet = require("@ocap/wallet");
15
16
  let _arcblock_did_util = require("@arcblock/did-util");
16
17
 
17
18
  //#region src/pipes/verify-delegation.ts
18
19
  const ZERO = (0, _ocap_util.toBN)(0);
19
- const isDelegationSufficient = (requirements, limitation) => {
20
- if (!limitation || !limitation.tokens.length && !limitation.assets.length) return { sufficient: true };
21
- const now = Math.floor(Date.now() / 1e3);
20
+ const DECIMAL_UINT_RE = /^\d+$/;
21
+ const parseNonNegativeBN = (raw, defaultZero = true) => {
22
+ if (raw === void 0 || raw === null || raw === "") return defaultZero ? ZERO : null;
23
+ const str = String(raw).trim();
24
+ if (!DECIMAL_UINT_RE.test(str)) return null;
25
+ try {
26
+ const val = (0, _ocap_util.toBN)(str);
27
+ return val.gte(ZERO) ? val : null;
28
+ } catch {
29
+ return null;
30
+ }
31
+ };
32
+ const isDelegationSufficient = (requirements, limitation, options = {}) => {
33
+ const now = options.now !== void 0 && Number.isFinite(options.now) ? Math.floor(options.now) : Math.floor(Date.now() / 1e3);
34
+ const coSignedByOwner = Boolean(options.coSignedByOwner);
35
+ if (!requirements || requirements.length === 0) {
36
+ if (!limitation || !limitation.tokens?.length && !limitation.assets?.length) return { sufficient: true };
37
+ const zeroReqCountedLimits = /* @__PURE__ */ new Set();
38
+ for (const limit of limitation.tokens || []) {
39
+ if (limit.coSignRequired && !coSignedByOwner) return {
40
+ sufficient: false,
41
+ reason: "human co-signature required for tier-3 delegation"
42
+ };
43
+ if (limit.txCount > 0 && limit.txSent >= limit.txCount) return {
44
+ sufficient: false,
45
+ reason: "tx count exceeds threshold"
46
+ };
47
+ if (limit.validUntil > 0 && limit.validUntil < now) return {
48
+ sufficient: false,
49
+ reason: "delegation expired"
50
+ };
51
+ if (limit.rate && limit.lastTx && limit.rate.interval > 0) {
52
+ if (limit.lastTx + limit.rate.interval > now) return {
53
+ sufficient: false,
54
+ reason: "delegation rate limit exceeded"
55
+ };
56
+ }
57
+ zeroReqCountedLimits.add(limit);
58
+ }
59
+ for (const limit of limitation.assets || []) {
60
+ if (limit.txCount > 0 && limit.txSent >= limit.txCount) return {
61
+ sufficient: false,
62
+ reason: "tx count exceeds threshold"
63
+ };
64
+ if (limit.validUntil > 0 && limit.validUntil < now) return {
65
+ sufficient: false,
66
+ reason: "delegation expired"
67
+ };
68
+ if (limit.rate && limit.lastTx && limit.rate.interval > 0) {
69
+ if (limit.lastTx + limit.rate.interval > now) return {
70
+ sufficient: false,
71
+ reason: "delegation rate limit exceeded"
72
+ };
73
+ }
74
+ zeroReqCountedLimits.add(limit);
75
+ }
76
+ for (const limit of zeroReqCountedLimits) {
77
+ limit.txSent = (limit.txSent || 0) + 1;
78
+ limit.lastTx = now;
79
+ }
80
+ return { sufficient: true };
81
+ }
82
+ if (!limitation || !limitation.tokens?.length && !limitation.assets?.length) {
83
+ if (limitation?.unlimited === true) return { sufficient: true };
84
+ return {
85
+ sufficient: false,
86
+ reason: "delegation limit is empty"
87
+ };
88
+ }
22
89
  const countedLimits = /* @__PURE__ */ new Set();
23
90
  const txSpentByLimit = /* @__PURE__ */ new Map();
91
+ const baseSpentByLimit = /* @__PURE__ */ new Map();
92
+ const windowStateByLimit = /* @__PURE__ */ new Map();
24
93
  for (const requirement of requirements) {
25
94
  if (requirement.type === "token") {
26
95
  const limit = limitation.tokens.find((token) => (0, _ocap_util.isSameDid)(token.address, requirement.address));
27
96
  if (limit) {
28
97
  const requirementTo = [requirement.to].flat().filter(Boolean);
29
98
  const limitTo = [limit.to].flat().filter(Boolean);
99
+ if (limit.requirePinnedPayee && (!limitTo.length || !requirementTo.length)) return {
100
+ sufficient: false,
101
+ reason: "pinned payee address is required for subscription delegation"
102
+ };
30
103
  if (!(!requirementTo.length || !limitTo.length || requirementTo.some((x) => limitTo.some((y) => (0, _ocap_util.isSameDid)(x, y))))) return {
31
104
  sufficient: false,
32
105
  reason: "token receiver is not allowed"
33
106
  };
107
+ if (limit.coSignRequired && !coSignedByOwner) return {
108
+ sufficient: false,
109
+ reason: "human co-signature required for tier-3 delegation"
110
+ };
34
111
  const isFirstMatchInTx = !countedLimits.has(limit);
35
112
  if (isFirstMatchInTx) {
36
113
  if (limit.txCount > 0 && limit.txSent >= limit.txCount) return {
@@ -50,26 +127,94 @@ const isDelegationSufficient = (requirements, limitation) => {
50
127
  };
51
128
  }
52
129
  }
53
- const requirementValue = (0, _ocap_util.toBN)(requirement.value || "0");
130
+ const requirementValue = parseNonNegativeBN(requirement.value);
131
+ if (!requirementValue) return {
132
+ sufficient: false,
133
+ reason: "invalid token requirement value"
134
+ };
54
135
  const currentTxSpent = (txSpentByLimit.get(limit) || ZERO).add(requirementValue);
55
136
  txSpentByLimit.set(limit, currentTxSpent);
56
- const txAllowance = (0, _ocap_util.toBN)(limit.txAllowance || "0");
57
- if (txAllowance.gt(ZERO) && currentTxSpent.gt(txAllowance)) return {
137
+ const rawTxAllowance = parseNonNegativeBN(limit.txAllowance);
138
+ const rawMaxPerTx = parseNonNegativeBN(limit.maxPerTx);
139
+ const coSignAllowance = parseNonNegativeBN(limit.coSignAllowance);
140
+ if (!rawTxAllowance || !rawMaxPerTx || !coSignAllowance) return {
141
+ sufficient: false,
142
+ reason: "invalid delegation allowance configuration"
143
+ };
144
+ let txAllowance = ZERO;
145
+ if (rawTxAllowance.gt(ZERO) && rawMaxPerTx.gt(ZERO)) txAllowance = rawTxAllowance.lt(rawMaxPerTx) ? rawTxAllowance : rawMaxPerTx;
146
+ else if (rawTxAllowance.gt(ZERO)) txAllowance = rawTxAllowance;
147
+ else if (rawMaxPerTx.gt(ZERO)) txAllowance = rawMaxPerTx;
148
+ const hasCoSignStepUp = coSignAllowance.gt(ZERO);
149
+ const windowLimit = parseNonNegativeBN(limit.windowLimit);
150
+ if (!windowLimit) return {
151
+ sufficient: false,
152
+ reason: "invalid window allowance configuration"
153
+ };
154
+ if (hasCoSignStepUp && currentTxSpent.gt(coSignAllowance)) return {
155
+ sufficient: false,
156
+ reason: "token amount exceeds co-sign allowance"
157
+ };
158
+ if (hasCoSignStepUp && txAllowance.isZero() && windowLimit.isZero() && !coSignedByOwner && currentTxSpent.gt(ZERO)) return {
159
+ sufficient: false,
160
+ reason: "human co-signature required for over-budget spend"
161
+ };
162
+ if (txAllowance.gt(ZERO) && currentTxSpent.gt(txAllowance)) if (coSignedByOwner && hasCoSignStepUp && currentTxSpent.lte(coSignAllowance)) {} else if (!coSignedByOwner && hasCoSignStepUp && currentTxSpent.lte(coSignAllowance)) return {
163
+ sufficient: false,
164
+ reason: "human co-signature required for over-budget spend"
165
+ };
166
+ else return {
58
167
  sufficient: false,
59
168
  reason: "token amount exceeds tx allowance"
60
169
  };
61
- const totalAllowance = (0, _ocap_util.toBN)(limit.totalAllowance || "0");
62
- const spentAllowance = (0, _ocap_util.toBN)(limit.spentAllowance || "0");
63
- if (totalAllowance.gt(ZERO) && requirementValue.add(spentAllowance).gt(totalAllowance)) return {
170
+ const hasWindowSeconds = limit.windowSeconds !== void 0 && limit.windowSeconds !== null;
171
+ const windowSeconds = hasWindowSeconds ? Number(limit.windowSeconds) : 0;
172
+ if (windowLimit.gt(ZERO) && (!Number.isFinite(windowSeconds) || windowSeconds <= 0) || hasWindowSeconds && (!Number.isFinite(windowSeconds) || windowSeconds < 0 || windowSeconds > 0 && windowLimit.isZero())) return {
64
173
  sufficient: false,
65
- reason: "token amount exceeds total allowance"
174
+ reason: "invalid window allowance configuration"
66
175
  };
67
- if (isFirstMatchInTx) {
68
- countedLimits.add(limit);
69
- limit.txSent = (limit.txSent || 0) + 1;
70
- limit.lastTx = now;
176
+ if (windowLimit.gt(ZERO) && windowSeconds > 0) {
177
+ let winState = windowStateByLimit.get(limit);
178
+ if (!winState) {
179
+ const prevStart = Number(limit.windowStart || 0);
180
+ const isExpiredWindow = !prevStart || now >= prevStart + windowSeconds;
181
+ const prevWindowSpent = parseNonNegativeBN(limit.windowSpent);
182
+ if (!prevWindowSpent) return {
183
+ sufficient: false,
184
+ reason: "invalid window allowance configuration"
185
+ };
186
+ winState = {
187
+ spent: isExpiredWindow ? ZERO : prevWindowSpent,
188
+ start: isExpiredWindow ? now : prevStart
189
+ };
190
+ }
191
+ const nextWindowSpent = winState.spent.add(requirementValue);
192
+ if (nextWindowSpent.gt(windowLimit)) if (coSignedByOwner && hasCoSignStepUp && currentTxSpent.lte(coSignAllowance)) {} else if (!coSignedByOwner && hasCoSignStepUp && currentTxSpent.lte(coSignAllowance)) return {
193
+ sufficient: false,
194
+ reason: "human co-signature required for over-budget spend"
195
+ };
196
+ else return {
197
+ sufficient: false,
198
+ reason: "token amount exceeds window allowance"
199
+ };
200
+ winState.spent = nextWindowSpent;
201
+ windowStateByLimit.set(limit, winState);
202
+ }
203
+ const totalAllowance = parseNonNegativeBN(limit.totalAllowance);
204
+ let baseSpent = baseSpentByLimit.get(limit);
205
+ if (!baseSpent) {
206
+ baseSpent = parseNonNegativeBN(limit.spentAllowance) ?? void 0;
207
+ if (baseSpent) baseSpentByLimit.set(limit, baseSpent);
71
208
  }
72
- limit.spentAllowance = spentAllowance.add(requirementValue).toString();
209
+ if (!totalAllowance || !baseSpent) return {
210
+ sufficient: false,
211
+ reason: "invalid total allowance configuration"
212
+ };
213
+ if (totalAllowance.gt(ZERO) && currentTxSpent.add(baseSpent).gt(totalAllowance)) return {
214
+ sufficient: false,
215
+ reason: "token amount exceeds total allowance"
216
+ };
217
+ if (isFirstMatchInTx) countedLimits.add(limit);
73
218
  continue;
74
219
  }
75
220
  return {
@@ -104,8 +249,6 @@ const isDelegationSufficient = (requirements, limitation) => {
104
249
  };
105
250
  }
106
251
  countedLimits.add(limit);
107
- limit.txSent = (limit.txSent || 0) + 1;
108
- limit.lastTx = now;
109
252
  }
110
253
  continue;
111
254
  }
@@ -119,6 +262,18 @@ const isDelegationSufficient = (requirements, limitation) => {
119
262
  reason: "requirement type invalid"
120
263
  };
121
264
  }
265
+ for (const limit of countedLimits) {
266
+ limit.txSent = (limit.txSent || 0) + 1;
267
+ limit.lastTx = now;
268
+ }
269
+ for (const [limit, txSpent] of txSpentByLimit.entries()) {
270
+ limit.spentAllowance = (baseSpentByLimit.get(limit) || ZERO).add(txSpent).toString();
271
+ const updatedWin = windowStateByLimit.get(limit);
272
+ if (updatedWin) {
273
+ limit.windowSpent = updatedWin.spent.toString();
274
+ limit.windowStart = updatedWin.start;
275
+ }
276
+ }
122
277
  return { sufficient: true };
123
278
  };
124
279
  const verifyImplicitAssetOwnership = async (signerAddress, delegatorState, context, delegatorAddress) => {
@@ -153,19 +308,71 @@ const verifyImplicitAssetOwnership = async (signerAddress, delegatorState, conte
153
308
  function CreateVerifyDelegationPipe({ type = "signature", delegationKey = "delegationState", requirementsKey = "delegationRequirements", signerKey = "signerState", delegatorKey = "delegatorState", getRequirements }) {
154
309
  return async function VerifyDelegation(context, next) {
155
310
  const { tx, txType, statedb } = context;
156
- const getDelegationState = async (signerState, delegatorState) => {
311
+ const getDelegationState = async (signerState, delegatorState, existingPool = []) => {
157
312
  if (delegatorState) {
158
313
  const related = (0, _ocap_util_lib_get_related_addr.getRelatedAddresses)(delegatorState);
314
+ const topLevelDelegation = context.delegationState;
159
315
  return (await Promise.all(related.map(async (x) => {
160
- const delegation = await statedb.delegation.get((0, _arcblock_did_util.toDelegateAddress)(signerState.address, x), context);
316
+ const targetAddress = (0, _arcblock_did_util.toDelegateAddress)(signerState.address, x);
317
+ const cached = existingPool.find((d) => d && (0, _ocap_util.isSameDid)(d.address, targetAddress)) || (topLevelDelegation && (0, _ocap_util.isSameDid)(topLevelDelegation.address, targetAddress) ? topLevelDelegation : void 0);
318
+ if (cached) {
319
+ cached.to = x;
320
+ return cached;
321
+ }
322
+ const delegation = await statedb.delegation.get(targetAddress, context);
161
323
  if (delegation) delegation.to = x;
162
324
  return delegation;
163
325
  }))).find((x) => x);
164
326
  }
165
327
  return null;
166
328
  };
167
- const checkDelegation = (delegationState, requirements) => {
168
- const now = Math.floor(Date.now() / 1e3);
329
+ const verifyOwnerCoSignature = async (signerState, delegateePk) => {
330
+ if (!signerState?.address) return false;
331
+ if (Array.isArray(signerState.migratedTo) && signerState.migratedTo.length > 0) return false;
332
+ let rawCoSig = (0, lodash_get.default)(context, "extra.coSignature");
333
+ if (!rawCoSig) {
334
+ const rawTxExtra = (0, lodash_get.default)(context, "extra.txExtra");
335
+ if (typeof rawTxExtra === "string" && rawTxExtra.trim().startsWith("{")) try {
336
+ const parsed = JSON.parse(rawTxExtra);
337
+ if (parsed?.coSignature && typeof parsed.coSignature === "object") rawCoSig = parsed.coSignature;
338
+ } catch {}
339
+ else if (rawTxExtra && typeof rawTxExtra === "object") {
340
+ const maybeCoSig = rawTxExtra.coSignature;
341
+ if (maybeCoSig && typeof maybeCoSig === "object") rawCoSig = maybeCoSig;
342
+ }
343
+ }
344
+ if (!rawCoSig || typeof rawCoSig.pk !== "string" || typeof rawCoSig.signature !== "string") return false;
345
+ const candidatePayloads = [context.txHash, context.unsignedTxHash].filter((x) => typeof x === "string" && x.length > 0);
346
+ if (candidatePayloads.length === 0) return false;
347
+ const ownerAddr = signerState.address;
348
+ const forbiddenPk = delegateePk || tx.pk;
349
+ const coSigPkHex = (0, _arcblock_did.normalizePublicKeyHex)(rawCoSig.pk);
350
+ const forbiddenPkHex = forbiddenPk ? (0, _arcblock_did.normalizePublicKeyHex)(forbiddenPk) : "";
351
+ if (!coSigPkHex || forbiddenPkHex && coSigPkHex === forbiddenPkHex) return false;
352
+ if (!(0, _arcblock_did.isFromPublicKey)(ownerAddr, rawCoSig.pk)) return false;
353
+ try {
354
+ const wallet = (0, _ocap_wallet.fromPublicKey)(rawCoSig.pk, (0, _arcblock_did.toTypeInfo)(ownerAddr));
355
+ for (const payload of candidatePayloads) {
356
+ if (await wallet.verify(payload, rawCoSig.signature, false)) return true;
357
+ if (await wallet.verify(payload, rawCoSig.signature, true)) return true;
358
+ }
359
+ } catch {
360
+ return false;
361
+ }
362
+ return false;
363
+ };
364
+ const getTxTimestampSeconds = () => {
365
+ const txTime = context.txTime;
366
+ if (txTime !== void 0 && txTime !== null && txTime !== "") if (typeof txTime === "number") {
367
+ if (Number.isFinite(txTime) && txTime > 0) return txTime > 1e11 ? Math.floor(txTime / 1e3) : Math.floor(txTime);
368
+ } else {
369
+ const parsedMs = new Date(txTime).getTime();
370
+ if (Number.isFinite(parsedMs) && parsedMs > 0) return Math.floor(parsedMs / 1e3);
371
+ }
372
+ return Math.floor(Date.now() / 1e3);
373
+ };
374
+ const checkDelegation = (delegationState, requirements, coSignedByOwner = false) => {
375
+ const now = getTxTimestampSeconds();
169
376
  const validUntil = delegationState.validUntil || 0;
170
377
  if (validUntil > 0 && validUntil < now) return {
171
378
  valid: false,
@@ -200,7 +407,11 @@ function CreateVerifyDelegationPipe({ type = "signature", delegationKey = "deleg
200
407
  };
201
408
  const result = isDelegationSufficient(requirements, {
202
409
  tokens: rawLimit.tokens || [],
203
- assets: rawLimit.assets || []
410
+ assets: rawLimit.assets || [],
411
+ ...rawLimit.unlimited === true ? { unlimited: true } : {}
412
+ }, {
413
+ now,
414
+ coSignedByOwner
204
415
  });
205
416
  if (result.sufficient === false) return {
206
417
  valid: false,
@@ -216,16 +427,18 @@ function CreateVerifyDelegationPipe({ type = "signature", delegationKey = "deleg
216
427
  const signerState = (0, lodash_get.default)(context, signerKey);
217
428
  const delegatorState = (0, lodash_get.default)(context, delegatorKey);
218
429
  const signerAddress = signerState?.address || tx?.from;
430
+ if (delegatorState && (tx?.delegator && !(0, _ocap_util.isSameDid)(delegatorState.address, tx.delegator) || Array.isArray(delegatorState.migratedTo) && delegatorState.migratedTo.length > 0)) return next(new _ocap_util_lib_error.CustomError("ACCOUNT_MIGRATED", `Delegator account ${tx?.delegator} is migrated`, { persist: false }));
219
431
  if (signerAddress && (0, _arcblock_did.toTypeInfo)(signerAddress).role === _ocap_mcrypto.types.RoleType.ROLE_ASSET) {
220
432
  try {
221
433
  if (await verifyImplicitAssetOwnership(signerAddress, delegatorState || (tx?.delegator ? { address: tx.delegator } : null), context, tx?.delegator)) {
222
434
  (0, lodash_set.default)(context, "isImplicitDelegation", true);
435
+ (0, lodash_set.default)(context, "isDelegationVerified", true);
223
436
  return next();
224
437
  }
225
438
  } catch (err) {
226
439
  return next(err);
227
440
  }
228
- return next(new _ocap_util_lib_error.CustomError("INVALID_DELEGATION", `Account ${delegatorState?.address || tx?.delegator} is not the owner of asset ${signerAddress}`, { persist: true }));
441
+ return next(new _ocap_util_lib_error.CustomError("INVALID_DELEGATION", `Account ${delegatorState?.address || tx?.delegator} is not the owner of asset ${signerAddress}`, { persist: false }));
229
442
  }
230
443
  const delegationState = await getDelegationState(signerState, delegatorState ?? null);
231
444
  if (!delegationState) {
@@ -233,12 +446,15 @@ function CreateVerifyDelegationPipe({ type = "signature", delegationKey = "deleg
233
446
  signerAddress: signerState?.address,
234
447
  delegatorAddress: delegatorState?.address
235
448
  });
236
- return next(new _ocap_util_lib_error.CustomError("INVALID_DELEGATION", "No delegation found between sender and delegator", { persist: true }));
449
+ return next(new _ocap_util_lib_error.CustomError("INVALID_DELEGATION", "No delegation found between sender and delegator", { persist: false }));
237
450
  }
238
- const result = checkDelegation(delegationState, requirements);
239
- if (result.code) return next(new _ocap_util_lib_error.CustomError(result.code, `Delegation check failed: ${result.reason}`, { persist: true }));
451
+ const coSignedByOwner = await verifyOwnerCoSignature(signerState);
452
+ const result = checkDelegation(delegationState, requirements, coSignedByOwner);
453
+ if (result.code) return next(new _ocap_util_lib_error.CustomError(result.code, `Delegation check failed: ${result.reason}`, { persist: false }));
454
+ if (coSignedByOwner) (0, lodash_set.default)(context, "coSignedByOwner", true);
240
455
  (0, lodash_set.default)(context, delegationKey, delegationState);
241
456
  (0, lodash_set.default)(context, "isDelegationChanged", true);
457
+ (0, lodash_set.default)(context, "isDelegationVerified", true);
242
458
  return next();
243
459
  }
244
460
  if (type === "multisig") {
@@ -259,7 +475,7 @@ function CreateVerifyDelegationPipe({ type = "signature", delegationKey = "deleg
259
475
  allRequirements.push(...sigRequirements);
260
476
  const signerState = signerStates?.find((x) => signer && (0, _ocap_util.isSameDid)(x.address, signer));
261
477
  const delegatorState = delegatorStates?.find((x) => delegator && (0, _ocap_util_lib_get_related_addr.getRelatedAddresses)(x).some((addr) => (0, _ocap_util.isSameDid)(addr, delegator)));
262
- if (delegatorState && (delegator && !(0, _ocap_util.isSameDid)(delegatorState.address, delegator) || Array.isArray(delegatorState.migratedTo) && delegatorState.migratedTo.length > 0)) return next(new _ocap_util_lib_error.CustomError("ACCOUNT_MIGRATED", `Delegator account ${delegator} is migrated`, { persist: true }));
478
+ if (delegatorState && (delegator && !(0, _ocap_util.isSameDid)(delegatorState.address, delegator) || Array.isArray(delegatorState.migratedTo) && delegatorState.migratedTo.length > 0)) return next(new _ocap_util_lib_error.CustomError("ACCOUNT_MIGRATED", `Delegator account ${delegator} is migrated`, { persist: false }));
263
479
  const signerAddress = signerState?.address || signer;
264
480
  if (signerAddress && (0, _arcblock_did.toTypeInfo)(signerAddress).role === _ocap_mcrypto.types.RoleType.ROLE_ASSET) {
265
481
  try {
@@ -267,22 +483,29 @@ function CreateVerifyDelegationPipe({ type = "signature", delegationKey = "deleg
267
483
  } catch (err) {
268
484
  return next(err);
269
485
  }
270
- return next(new _ocap_util_lib_error.CustomError("INVALID_DELEGATION", `Account ${delegatorState?.address || delegator} is not the owner of asset ${signerAddress}`, { persist: true }));
486
+ return next(new _ocap_util_lib_error.CustomError("INVALID_DELEGATION", `Account ${delegatorState?.address || delegator} is not the owner of asset ${signerAddress}`, { persist: false }));
271
487
  }
272
- const delegationState = await getDelegationState(signerState, delegatorState ?? null);
488
+ const delegationState = await getDelegationState(signerState, delegatorState ?? null, delegationStates);
273
489
  if (!delegationState) {
274
490
  console.error("invalid_delegation", {
275
491
  signerAddress: signerState?.address,
276
492
  delegatorAddress: delegatorState?.address
277
493
  });
278
- return next(new _ocap_util_lib_error.CustomError("INVALID_DELEGATION", "No delegation found between signer and delegator", { persist: true }));
494
+ return next(new _ocap_util_lib_error.CustomError("INVALID_DELEGATION", "No delegation found between signer and delegator", { persist: false }));
495
+ }
496
+ const topLevelDelegation = context.delegationState;
497
+ const alreadyVerifiedInTx = delegationStates.some((d) => (0, _ocap_util.isSameDid)(d.address, delegationState.address)) || Boolean(topLevelDelegation && (0, _ocap_util.isSameDid)(topLevelDelegation.address, delegationState.address));
498
+ const coSignedByOwner = await verifyOwnerCoSignature(signerState, signature.pk);
499
+ if (!alreadyVerifiedInTx || sigRequirements.length > 0) {
500
+ const result = checkDelegation(delegationState, sigRequirements, coSignedByOwner);
501
+ if (result.code) return next(new _ocap_util_lib_error.CustomError(result.code, `Delegation check failed: ${result.reason}`, { persist: false }));
279
502
  }
280
- const result = checkDelegation(delegationState, sigRequirements);
281
- if (result.code) return next(new _ocap_util_lib_error.CustomError(result.code, `Delegation check failed: ${result.reason}`, { persist: true }));
282
- delegationStates.push(delegationState);
503
+ if (coSignedByOwner) (0, lodash_set.default)(context, "coSignedByOwner", true);
504
+ if (!delegationStates.some((d) => (0, _ocap_util.isSameDid)(d.address, delegationState.address))) delegationStates.push(delegationState);
283
505
  }
284
506
  (0, lodash_set.default)(context, requirementsKey, allRequirements);
285
507
  (0, lodash_set.default)(context, delegationKey, delegationStates);
508
+ (0, lodash_set.default)(context, "isMultiSigDelegationVerified", true);
286
509
  if (delegationStates.length > 0) (0, lodash_set.default)(context, "isDelegationChanged", true);
287
510
  return next();
288
511
  }