@ocap/tx-protocols 1.31.1 → 1.31.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (161) hide show
  1. package/esm/bridge-release-crypto.d.mts +39 -0
  2. package/esm/bridge-release-crypto.mjs +88 -0
  3. package/esm/bridge-release-window.d.mts +47 -0
  4. package/esm/bridge-release-window.mjs +62 -0
  5. package/esm/bridge-reserve.d.mts +24 -0
  6. package/esm/bridge-reserve.mjs +41 -0
  7. package/esm/execute.d.mts +1 -1
  8. package/esm/execute.mjs +58 -5
  9. package/esm/gas-security-guard.d.mts +6 -2
  10. package/esm/gas-security-guard.mjs +16 -9
  11. package/esm/index.d.mts +37 -18
  12. package/esm/index.mjs +6 -2
  13. package/esm/pipes/ensure-cost.mjs +7 -1
  14. package/esm/pipes/write-ledger.d.mts +2 -2
  15. package/esm/pipes/write-ledger.mjs +6 -3
  16. package/esm/protocols/account/delegate.mjs +6 -4
  17. package/esm/protocols/account/migrate.mjs +5 -3
  18. package/esm/protocols/account/revoke-delegate.mjs +5 -3
  19. package/esm/protocols/asset/acquire-v2.mjs +3 -1
  20. package/esm/protocols/asset/acquire-v3.mjs +4 -2
  21. package/esm/protocols/asset/consume.mjs +3 -1
  22. package/esm/protocols/asset/create.mjs +4 -2
  23. package/esm/protocols/asset/mint.mjs +4 -2
  24. package/esm/protocols/asset/pipes/exec-mint-hook.mjs +1 -1
  25. package/esm/protocols/asset/pipes/verify-itx-address.mjs +1 -1
  26. package/esm/protocols/asset/pipes/verify-itx-assets.mjs +1 -1
  27. package/esm/protocols/asset/update.mjs +4 -2
  28. package/esm/protocols/bridge/release.d.mts +34 -0
  29. package/esm/protocols/bridge/release.mjs +385 -0
  30. package/esm/protocols/factory/create.mjs +4 -2
  31. package/esm/protocols/governance/claim-stake.mjs +4 -2
  32. package/esm/protocols/governance/return-stake.mjs +4 -2
  33. package/esm/protocols/governance/revoke-ledger.mjs +1 -1
  34. package/esm/protocols/governance/revoke-stake.d.mts +7 -2
  35. package/esm/protocols/governance/revoke-stake.mjs +49 -28
  36. package/esm/protocols/governance/slash-stake.mjs +5 -3
  37. package/esm/protocols/governance/stake.mjs +6 -4
  38. package/esm/protocols/rollup/bridge-create.d.mts +13 -0
  39. package/esm/protocols/rollup/bridge-create.mjs +206 -0
  40. package/esm/protocols/rollup/bridge-membership.d.mts +10 -0
  41. package/esm/protocols/rollup/bridge-membership.mjs +154 -0
  42. package/esm/protocols/rollup/bridge-migrate.d.mts +10 -0
  43. package/esm/protocols/rollup/bridge-migrate.mjs +208 -0
  44. package/esm/protocols/rollup/bridge-v2.d.mts +113 -0
  45. package/esm/protocols/rollup/bridge-v2.mjs +219 -0
  46. package/esm/protocols/rollup/claim-reward.mjs +4 -2
  47. package/esm/protocols/rollup/close.d.mts +2 -1
  48. package/esm/protocols/rollup/close.mjs +59 -6
  49. package/esm/protocols/rollup/create-block.mjs +4 -2
  50. package/esm/protocols/rollup/create.d.mts +3 -0
  51. package/esm/protocols/rollup/create.mjs +45 -6
  52. package/esm/protocols/rollup/join.d.mts +2 -1
  53. package/esm/protocols/rollup/join.mjs +31 -23
  54. package/esm/protocols/rollup/leave.d.mts +2 -1
  55. package/esm/protocols/rollup/leave.mjs +32 -24
  56. package/esm/protocols/rollup/migrate.d.mts +2 -1
  57. package/esm/protocols/rollup/migrate.mjs +19 -10
  58. package/esm/protocols/rollup/pause.d.mts +4 -1
  59. package/esm/protocols/rollup/pause.mjs +50 -6
  60. package/esm/protocols/rollup/pipes/verify-evidence.mjs +2 -2
  61. package/esm/protocols/rollup/resume.d.mts +2 -1
  62. package/esm/protocols/rollup/resume.mjs +26 -6
  63. package/esm/protocols/rollup/update.d.mts +5 -1
  64. package/esm/protocols/rollup/update.mjs +56 -9
  65. package/esm/protocols/token/create.mjs +4 -2
  66. package/esm/protocols/token/deposit-v2.mjs +5 -3
  67. package/esm/protocols/token/withdraw-v2.mjs +5 -3
  68. package/esm/protocols/token-factory/burn.mjs +4 -2
  69. package/esm/protocols/token-factory/create.mjs +8 -4
  70. package/esm/protocols/token-factory/mint.mjs +4 -2
  71. package/esm/protocols/token-factory/update.mjs +20 -5
  72. package/esm/protocols/trade/exchange-v2.d.mts +5 -1
  73. package/esm/protocols/trade/exchange-v2.mjs +89 -4
  74. package/esm/protocols/trade/transfer-v2.mjs +15 -4
  75. package/esm/protocols/trade/transfer-v3.mjs +5 -3
  76. package/esm/stateless-prefix.d.mts +16 -0
  77. package/esm/stateless-prefix.mjs +82 -0
  78. package/esm/tx-timer.d.mts +1 -1
  79. package/esm/tx-timer.mjs +1 -1
  80. package/esm/util.mjs +2 -2
  81. package/lib/bridge-release-crypto.cjs +93 -0
  82. package/lib/bridge-release-crypto.d.cts +39 -0
  83. package/lib/bridge-release-window.cjs +69 -0
  84. package/lib/bridge-release-window.d.cts +47 -0
  85. package/lib/bridge-reserve.cjs +45 -0
  86. package/lib/bridge-reserve.d.cts +24 -0
  87. package/lib/execute.cjs +58 -5
  88. package/lib/gas-security-guard.cjs +16 -9
  89. package/lib/gas-security-guard.d.cts +6 -2
  90. package/lib/index.cjs +8 -1
  91. package/lib/index.d.cts +36 -17
  92. package/lib/pipes/ensure-cost.cjs +7 -1
  93. package/lib/pipes/write-ledger.cjs +6 -3
  94. package/lib/pipes/write-ledger.d.cts +2 -2
  95. package/lib/protocols/account/delegate.cjs +6 -4
  96. package/lib/protocols/account/migrate.cjs +5 -3
  97. package/lib/protocols/account/revoke-delegate.cjs +5 -3
  98. package/lib/protocols/asset/acquire-v2.cjs +3 -1
  99. package/lib/protocols/asset/acquire-v3.cjs +4 -2
  100. package/lib/protocols/asset/consume.cjs +3 -1
  101. package/lib/protocols/asset/create.cjs +4 -2
  102. package/lib/protocols/asset/mint.cjs +4 -2
  103. package/lib/protocols/asset/pipes/exec-mint-hook.cjs +1 -1
  104. package/lib/protocols/asset/pipes/verify-itx-address.cjs +1 -1
  105. package/lib/protocols/asset/pipes/verify-itx-assets.cjs +1 -1
  106. package/lib/protocols/asset/update.cjs +4 -2
  107. package/lib/protocols/bridge/release.cjs +390 -0
  108. package/lib/protocols/bridge/release.d.cts +34 -0
  109. package/lib/protocols/factory/create.cjs +4 -2
  110. package/lib/protocols/governance/claim-stake.cjs +4 -2
  111. package/lib/protocols/governance/return-stake.cjs +4 -2
  112. package/lib/protocols/governance/revoke-ledger.cjs +1 -1
  113. package/lib/protocols/governance/revoke-stake.cjs +49 -28
  114. package/lib/protocols/governance/revoke-stake.d.cts +7 -2
  115. package/lib/protocols/governance/slash-stake.cjs +5 -3
  116. package/lib/protocols/governance/stake.cjs +6 -4
  117. package/lib/protocols/rollup/bridge-create.cjs +209 -0
  118. package/lib/protocols/rollup/bridge-create.d.cts +13 -0
  119. package/lib/protocols/rollup/bridge-membership.cjs +157 -0
  120. package/lib/protocols/rollup/bridge-membership.d.cts +10 -0
  121. package/lib/protocols/rollup/bridge-migrate.cjs +212 -0
  122. package/lib/protocols/rollup/bridge-migrate.d.cts +10 -0
  123. package/lib/protocols/rollup/bridge-v2.cjs +244 -0
  124. package/lib/protocols/rollup/bridge-v2.d.cts +113 -0
  125. package/lib/protocols/rollup/claim-reward.cjs +4 -2
  126. package/lib/protocols/rollup/close.cjs +59 -6
  127. package/lib/protocols/rollup/close.d.cts +2 -1
  128. package/lib/protocols/rollup/create-block.cjs +4 -2
  129. package/lib/protocols/rollup/create.cjs +45 -6
  130. package/lib/protocols/rollup/create.d.cts +3 -0
  131. package/lib/protocols/rollup/join.cjs +31 -23
  132. package/lib/protocols/rollup/join.d.cts +2 -1
  133. package/lib/protocols/rollup/leave.cjs +32 -24
  134. package/lib/protocols/rollup/leave.d.cts +2 -1
  135. package/lib/protocols/rollup/migrate.cjs +19 -10
  136. package/lib/protocols/rollup/migrate.d.cts +2 -1
  137. package/lib/protocols/rollup/pause.cjs +50 -6
  138. package/lib/protocols/rollup/pause.d.cts +4 -1
  139. package/lib/protocols/rollup/pipes/verify-evidence.cjs +2 -2
  140. package/lib/protocols/rollup/resume.cjs +26 -6
  141. package/lib/protocols/rollup/resume.d.cts +2 -1
  142. package/lib/protocols/rollup/update.cjs +56 -9
  143. package/lib/protocols/rollup/update.d.cts +5 -1
  144. package/lib/protocols/token/create.cjs +4 -2
  145. package/lib/protocols/token/deposit-v2.cjs +5 -3
  146. package/lib/protocols/token/withdraw-v2.cjs +5 -3
  147. package/lib/protocols/token-factory/burn.cjs +4 -2
  148. package/lib/protocols/token-factory/create.cjs +8 -4
  149. package/lib/protocols/token-factory/mint.cjs +4 -2
  150. package/lib/protocols/token-factory/update.cjs +20 -5
  151. package/lib/protocols/trade/exchange-v2.cjs +90 -3
  152. package/lib/protocols/trade/exchange-v2.d.cts +5 -1
  153. package/lib/protocols/trade/transfer-v2.cjs +15 -4
  154. package/lib/protocols/trade/transfer-v3.cjs +5 -3
  155. package/lib/stateless-prefix.cjs +88 -0
  156. package/lib/stateless-prefix.d.cts +16 -0
  157. package/lib/tx-timer.cjs +1 -1
  158. package/lib/tx-timer.d.cts +1 -1
  159. package/lib/util.cjs +2 -2
  160. package/package.json +16 -16
  161. package/tools/fixtures.ts +9 -4
@@ -1,13 +1,14 @@
1
1
  import { decodeAnySafe } from "../../util.mjs";
2
2
  import ensure_cost_default from "../../pipes/ensure-cost.mjs";
3
3
  import ensure_gas_default from "../../pipes/ensure-gas.mjs";
4
+ import { VerifyBridgeAuthority, bridgeUpdates, ifV1, loadBridge, peekBridge, readItxData, rejectRollupV1IfDisabled } from "./bridge-v2.mjs";
4
5
  import ensure_validator_default from "./pipes/ensure-validator.mjs";
5
6
  import verify_signers_default from "./pipes/verify-signers.mjs";
6
7
  import verify_status_default from "./pipes/verify-status.mjs";
7
- import { account, rollup } from "@ocap/state";
8
8
  import { Runner, pipes } from "@ocap/tx-pipeline";
9
- import { BN } from "@ocap/util";
10
9
  import { CustomError } from "@ocap/util/lib/error";
10
+ import { account, rollup } from "@ocap/state";
11
+ import { BN } from "@ocap/util";
11
12
  import Debug from "debug";
12
13
  import { v, vBN, vBNGreater, vBNPositive, vDID, vStripUnknown, vValidate } from "@arcblock/validator";
13
14
 
@@ -40,29 +41,64 @@ const schema = v.pipe(v.object({
40
41
  maxWithdrawFee: vBN(vBNPositive()),
41
42
  data: v.optional(v.nullable(v.any()))
42
43
  }), v.forward(v.check((input) => new BN(input.maxStakeAmount).gt(new BN(input.minStakeAmount)), "maxStakeAmount must be > minStakeAmount"), ["maxStakeAmount"]), v.forward(v.check((input) => input.maxSignerCount > input.minSignerCount, "maxSignerCount must be > minSignerCount"), ["maxSignerCount"]), v.forward(v.check((input) => input.maxBlockSize > input.minBlockSize, "maxBlockSize must be > minBlockSize"), ["maxBlockSize"]), v.forward(v.check((input) => new BN(input.maxDepositAmount).gt(new BN(input.minDepositAmount)), "maxDepositAmount must be > minDepositAmount"), ["maxDepositAmount"]), v.forward(v.check((input) => new BN(input.maxWithdrawAmount).gt(new BN(input.minWithdrawAmount)), "maxWithdrawAmount must be > minWithdrawAmount"), ["maxWithdrawAmount"]), v.forward(v.check((input) => new BN(input.maxDepositFee).gt(new BN(input.minDepositFee)), "maxDepositFee must be > minDepositFee"), ["maxDepositFee"]), v.forward(v.check((input) => new BN(input.maxWithdrawFee).gt(new BN(input.minWithdrawFee)), "maxWithdrawFee must be > minWithdrawFee"), ["maxWithdrawFee"]), vStripUnknown());
43
- runner.use(({ itx }, next) => {
44
+ runner.use(peekBridge("itx.rollup", { rejectV1IfDisabled: "update_rollup" }));
45
+ runner.use(ifV1(({ itx }, next) => {
44
46
  const { error } = vValidate(schema, itx);
45
47
  return next(error ? new CustomError("INVALID_TX", `Invalid itx: ${error.message}`) : void 0);
46
- });
47
- runner.use(pipes.VerifyInfo([{
48
+ }));
49
+ runner.use(ifV1(pipes.VerifyInfo([{
48
50
  error: "INVALID_TX",
49
51
  message: "Sum of itx.proposerFeeShare and itx.publisherFeeShare must be less than 10000",
50
52
  fn: (ctx) => {
51
53
  const context = ctx;
52
54
  return context.itx.proposerFeeShare + context.itx.publisherFeeShare < 1e4;
53
55
  }
54
- }]));
56
+ }])));
55
57
  runner.use(pipes.ExtractState({
56
58
  from: "itx.rollup",
57
59
  to: "rollupState",
58
60
  status: "INVALID_ROLLUP",
59
61
  table: "rollup"
60
62
  }));
61
- runner.use(ensure_validator_default(true));
62
- runner.use(verify_status_default({ paused: false }));
63
- runner.use(verify_signers_default({
63
+ runner.use(loadBridge);
64
+ runner.use(rejectRollupV1IfDisabled("update_rollup"));
65
+ runner.use(ifV1(ensure_validator_default(true)));
66
+ runner.use(ifV1(verify_status_default({ paused: false })));
67
+ runner.use((context, next) => {
68
+ if (!context.isBridgeV2) return next();
69
+ try {
70
+ rollup.assertV1FieldsUnused(context.itx, "INVALID_ROLLUP_UPDATE");
71
+ context.bridgePlan = rollup.planBridgePatch(context.bridgeBody, readItxData(context.itx), context.txSec);
72
+ } catch (err) {
73
+ return next(new CustomError("INVALID_TX", err.message));
74
+ }
75
+ return next();
76
+ });
77
+ runner.use(async (context, next) => {
78
+ const plan = context.bridgePlan;
79
+ if (!context.isBridgeV2 || plan?.kind !== "propose-owner") return next();
80
+ const candidate = plan.body.pendingOwner?.address;
81
+ if (!await context.statedb.account.get(candidate, context)) return next(new CustomError("INVALID_TX", "The proposed owner has no account on this chain"));
82
+ return next();
83
+ });
84
+ runner.use(ifV1(verify_signers_default({
64
85
  signersKey: "tx.signaturesList",
65
86
  allowSender: true
87
+ })));
88
+ runner.use(VerifyBridgeAuthority((context) => {
89
+ const kind = context.bridgePlan?.kind;
90
+ if (kind === "propose-owner") return {
91
+ owner: "none",
92
+ quorum: "twoThirds"
93
+ };
94
+ if (kind === "cancel-owner-proposal") return {
95
+ owner: "alone",
96
+ quorum: "none"
97
+ };
98
+ return {
99
+ owner: "required",
100
+ quorum: "threshold"
101
+ };
66
102
  }));
67
103
  runner.use(pipes.VerifyMultiSigV2({ signersKey: "signers" }));
68
104
  runner.use(pipes.ExtractState({
@@ -91,6 +127,17 @@ runner.use(ensure_cost_default({ attachSenderChanges: true }));
91
127
  runner.use(pipes.TakeStateSnapshot());
92
128
  runner.use(async (context, next) => {
93
129
  const { tx: tx$1, itx, rollupState, statedb, senderState, senderUpdates, updateVaults } = context;
130
+ if (context.isBridgeV2) {
131
+ const updates = bridgeUpdates(context, context.bridgePlan.body);
132
+ const [newSenderState$1, newRollupState$1] = await Promise.all([statedb.account.update(senderState.address, account.update(senderState, {
133
+ nonce: tx$1.nonce,
134
+ ...senderUpdates
135
+ }, context), context), statedb.rollup.update(itx.rollup, rollup.updateBridge(context.rollupStateOrig, updates, context), context)]);
136
+ if (updateVaults) await updateVaults();
137
+ context.senderState = newSenderState$1;
138
+ context.rollupState = newRollupState$1;
139
+ return next();
140
+ }
94
141
  const data = decodeAnySafe(itx.data ?? null);
95
142
  const sanitizedItx = { ...itx };
96
143
  delete sanitizedItx.reserves;
@@ -1,11 +1,12 @@
1
1
  import { decodeAnySafe, getDelegationRequirements } from "../../util.mjs";
2
2
  import ensure_cost_default from "../../pipes/ensure-cost.mjs";
3
3
  import ensure_gas_default from "../../pipes/ensure-gas.mjs";
4
+ import { markStatelessPrefix } from "../../stateless-prefix.mjs";
5
+ import { Runner, pipes } from "@ocap/tx-pipeline";
6
+ import { CustomError } from "@ocap/util/lib/error";
4
7
  import { toTokenAddress } from "@arcblock/did-util";
5
8
  import { account, delegation, token } from "@ocap/state";
6
- import { Runner, pipes } from "@ocap/tx-pipeline";
7
9
  import { BN, fromTokenToUnit } from "@ocap/util";
8
- import { CustomError } from "@ocap/util/lib/error";
9
10
  import cloneDeep from "lodash/cloneDeep.js";
10
11
  import Debug from "debug";
11
12
  import { schemas, v, vBN, vBNGreater, vBNMax, vDID, vForbidden, vStripUnknown, vValidate } from "@arcblock/validator";
@@ -65,6 +66,7 @@ runner.use(pipes.VerifyInfo([{
65
66
  return toTokenAddress(itx, context.txEncoding) === context.itx.address;
66
67
  }
67
68
  }]));
69
+ markStatelessPrefix(runner);
68
70
  runner.use(pipes.ExtractState({
69
71
  from: "tx.from",
70
72
  to: "senderState",
@@ -1,14 +1,15 @@
1
1
  import { applyTokenChange, applyTokenUpdates, getBNSum, getRewardLocker, getTxFee } from "../../util.mjs";
2
2
  import ensure_cost_default from "../../pipes/ensure-cost.mjs";
3
3
  import ensure_gas_default from "../../pipes/ensure-gas.mjs";
4
+ import { rejectBridgeV2 } from "../rollup/bridge-v2.mjs";
4
5
  import verify_signers_default from "../rollup/pipes/verify-signers.mjs";
5
6
  import verify_status_default from "../rollup/pipes/verify-status.mjs";
6
- import { toStakeAddress } from "@arcblock/did-util";
7
- import { account, evidence, rollup, stake } from "@ocap/state";
8
7
  import { Runner, pipes } from "@ocap/tx-pipeline";
9
- import { BN, fromUnitToToken } from "@ocap/util";
10
8
  import { CustomError } from "@ocap/util/lib/error";
11
9
  import { getListField } from "@ocap/util/lib/get-list-field";
10
+ import { toStakeAddress } from "@arcblock/did-util";
11
+ import { account, evidence, rollup, stake } from "@ocap/state";
12
+ import { BN, fromUnitToToken } from "@ocap/util";
12
13
  import Debug from "debug";
13
14
  import { patterns, schemas, v, vBN, vBNMin, vDID, vStripUnknown, vValidate } from "@arcblock/validator";
14
15
 
@@ -38,6 +39,7 @@ runner.use(pipes.ExtractState({
38
39
  status: "INVALID_ROLLUP",
39
40
  table: "rollup"
40
41
  }));
42
+ runner.use(rejectBridgeV2("deposit_token_v2"));
41
43
  runner.use((context, next) => {
42
44
  const { tx: tx$1, itx, rollupState } = context;
43
45
  if (rollup.getRollupTargetType(rollupState) === "EVM") {
@@ -1,13 +1,14 @@
1
1
  import { applyTokenChange, applyTokenUpdates, getBNSum, getRewardLocker, getTxFee } from "../../util.mjs";
2
2
  import ensure_cost_default from "../../pipes/ensure-cost.mjs";
3
3
  import ensure_gas_default from "../../pipes/ensure-gas.mjs";
4
+ import { rejectBridgeV2 } from "../rollup/bridge-v2.mjs";
4
5
  import verify_status_default from "../rollup/pipes/verify-status.mjs";
5
- import { toStakeAddress } from "@arcblock/did-util";
6
- import { account, rollup, stake } from "@ocap/state";
7
6
  import { Runner, pipes } from "@ocap/tx-pipeline";
8
- import { BN, fromUnitToToken } from "@ocap/util";
9
7
  import { CustomError } from "@ocap/util/lib/error";
10
8
  import { getListField } from "@ocap/util/lib/get-list-field";
9
+ import { toStakeAddress } from "@arcblock/did-util";
10
+ import { account, rollup, stake } from "@ocap/state";
11
+ import { BN, fromUnitToToken } from "@ocap/util";
11
12
  import Debug from "debug";
12
13
  import { schemas, v, vBN, vBNMin, vDID, vStripUnknown, vValidate } from "@arcblock/validator";
13
14
 
@@ -38,6 +39,7 @@ runner.use(pipes.ExtractState({
38
39
  status: "INVALID_ROLLUP",
39
40
  table: "rollup"
40
41
  }));
42
+ runner.use(rejectBridgeV2("withdraw_token_v2"));
41
43
  runner.use((context, next) => {
42
44
  const { tx: tx$1, itx, rollupState } = context;
43
45
  if (rollup.getRollupTargetType(rollupState) === "EVM") {
@@ -1,12 +1,13 @@
1
1
  import { applyTokenChange, applyTokenUpdates } from "../../util.mjs";
2
2
  import ensure_cost_default from "../../pipes/ensure-cost.mjs";
3
3
  import ensure_gas_default from "../../pipes/ensure-gas.mjs";
4
+ import { markStatelessPrefix } from "../../stateless-prefix.mjs";
4
5
  import calc_reserve_default from "./pipes/calc-reserve.mjs";
5
- import { account, token, tokenFactory } from "@ocap/state";
6
6
  import { Runner, pipes } from "@ocap/tx-pipeline";
7
- import { BN, fromUnitToToken, isSameDid, toAddress } from "@ocap/util";
8
7
  import { CustomError } from "@ocap/util/lib/error";
9
8
  import { getListField } from "@ocap/util/lib/get-list-field";
9
+ import { account, token, tokenFactory } from "@ocap/state";
10
+ import { BN, fromUnitToToken, isSameDid, toAddress } from "@ocap/util";
10
11
  import { getRelatedAddresses } from "@ocap/util/lib/get-related-addr";
11
12
  import pick from "lodash/pick.js";
12
13
  import { schemas, v, vBN, vBNGreater, vDID, vStripUnknown, vValidate } from "@arcblock/validator";
@@ -29,6 +30,7 @@ runner.use(({ itx }, next) => {
29
30
  if (error) return next(new CustomError("INVALID_TX", `Invalid itx: ${error.message}`));
30
31
  return next();
31
32
  });
33
+ markStatelessPrefix(runner);
32
34
  runner.use(pipes.ExtractState({
33
35
  from: "itx.tokenFactory",
34
36
  to: "tokenFactoryState",
@@ -1,16 +1,17 @@
1
1
  import { applyTokenChange, decodeAnySafe, getDelegationRequirements, isHttpUrl, isHttpsUrl } from "../../util.mjs";
2
2
  import ensure_cost_default from "../../pipes/ensure-cost.mjs";
3
3
  import ensure_gas_default from "../../pipes/ensure-gas.mjs";
4
+ import { markStatelessPrefix } from "../../stateless-prefix.mjs";
4
5
  import verify_ownership_default from "./pipes/verify-ownership.mjs";
5
6
  import verify_url_default from "./pipes/verify-url.mjs";
6
7
  import { any, array, check, literal, maxLength, maxValue, minLength, minValue, nullable, number, object, optional, picklist, pipe, safeParse, string, toLowerCase, toUpperCase, union } from "../../node_modules/valibot/dist/index.mjs";
7
8
  import verify_icon_default from "./pipes/verify-icon.mjs";
8
- import { toStakeAddress, toTokenAddress, toTokenFactoryAddress } from "@arcblock/did-util";
9
- import { account, delegation, stake, token, tokenFactory } from "@ocap/state";
10
9
  import { Runner, pipes } from "@ocap/tx-pipeline";
11
- import { BN, fromTokenToUnit, fromUnitToToken } from "@ocap/util";
12
10
  import { CustomError } from "@ocap/util/lib/error";
13
11
  import { getListField } from "@ocap/util/lib/get-list-field";
12
+ import { toStakeAddress, toTokenAddress, toTokenFactoryAddress } from "@arcblock/did-util";
13
+ import { account, delegation, stake, token, tokenFactory } from "@ocap/state";
14
+ import { BN, fromTokenToUnit, fromUnitToToken } from "@ocap/util";
14
15
  import cloneDeep from "lodash/cloneDeep.js";
15
16
  import Debug from "debug";
16
17
  import { vBN, vBNGreater, vDID, vStripUnknown, vValidate } from "@arcblock/validator";
@@ -60,7 +61,9 @@ runner.use((context, next) => {
60
61
  if (context.itx.curve == null) return next(new CustomError("INVALID_TX", "Invalid itx: curve is required for non-CreditToken"));
61
62
  const curveResult = safeParse(tokenFactory.vCurveSchema, context.itx.curve);
62
63
  if (!curveResult.success) return next(new CustomError("INVALID_TX", `Invalid itx: ${curveResult.issues.map((i) => i.message).join("; ")}`));
63
- context.itx.curve = curveResult.output;
64
+ const curveOutput = curveResult.output;
65
+ if (curveOutput.type === "quadratic" && !Number.isSafeInteger(curveOutput.constant)) return next(new CustomError("INVALID_TX", "Invalid itx: quadratic curve constant must be a safe integer"));
66
+ context.itx.curve = curveOutput;
64
67
  }
65
68
  const itxToken = context.itx.token;
66
69
  if (itxToken.metadata) {
@@ -117,6 +120,7 @@ runner.use(pipes.VerifyInfo([
117
120
  }
118
121
  }
119
122
  ]));
123
+ markStatelessPrefix(runner);
120
124
  runner.use(verify_icon_default());
121
125
  runner.use(verify_url_default({ urlKeys: ["itx.token.website", "itx.token.metadata.value.communityUrl"] }));
122
126
  runner.use(verify_ownership_default({ tokenKey: "itx.token" }));
@@ -1,13 +1,14 @@
1
1
  import { applyTokenChange, applyTokenUpdates } from "../../util.mjs";
2
2
  import ensure_cost_default from "../../pipes/ensure-cost.mjs";
3
3
  import ensure_gas_default from "../../pipes/ensure-gas.mjs";
4
+ import { markStatelessPrefix } from "../../stateless-prefix.mjs";
4
5
  import { any, nullable, object, optional, pipe } from "../../node_modules/valibot/dist/index.mjs";
5
6
  import calc_reserve_default from "./pipes/calc-reserve.mjs";
6
- import { account, token, tokenFactory } from "@ocap/state";
7
7
  import { Runner, pipes } from "@ocap/tx-pipeline";
8
- import { BN, fromUnitToToken, isSameDid, toAddress } from "@ocap/util";
9
8
  import { CustomError } from "@ocap/util/lib/error";
10
9
  import { getListField } from "@ocap/util/lib/get-list-field";
10
+ import { account, token, tokenFactory } from "@ocap/state";
11
+ import { BN, fromUnitToToken, isSameDid, toAddress } from "@ocap/util";
11
12
  import { getRelatedAddresses } from "@ocap/util/lib/get-related-addr";
12
13
  import pick from "lodash/pick.js";
13
14
  import { schemas, vBN, vBNGreater, vDID, vStripUnknown, vValidate } from "@arcblock/validator";
@@ -29,6 +30,7 @@ runner.use(({ itx }, next) => {
29
30
  if (error) return next(new CustomError("INVALID_TX", `Invalid itx: ${error.message}`));
30
31
  return next();
31
32
  });
33
+ markStatelessPrefix(runner);
32
34
  runner.use(pipes.ExtractState({
33
35
  from: "itx.tokenFactory",
34
36
  to: "tokenFactoryState",
@@ -1,19 +1,29 @@
1
1
  import { applyTokenChange, decodeAnySafe, getDelegationRequirements, isHttpUrl, isHttpsUrl } from "../../util.mjs";
2
2
  import ensure_cost_default from "../../pipes/ensure-cost.mjs";
3
3
  import ensure_gas_default from "../../pipes/ensure-gas.mjs";
4
+ import { markStatelessPrefix } from "../../stateless-prefix.mjs";
4
5
  import verify_ownership_default from "./pipes/verify-ownership.mjs";
5
6
  import verify_url_default from "./pipes/verify-url.mjs";
6
7
  import verify_icon_default from "./pipes/verify-icon.mjs";
7
- import { account, delegation, token, tokenFactory } from "@ocap/state";
8
8
  import { Runner, pipes } from "@ocap/tx-pipeline";
9
- import { isSameDid } from "@ocap/util";
10
9
  import { CustomError } from "@ocap/util/lib/error";
10
+ import { account, delegation, token, tokenFactory } from "@ocap/state";
11
+ import { isSameDid } from "@ocap/util";
11
12
  import { getRelatedAddresses } from "@ocap/util/lib/get-related-addr";
12
13
  import Debug from "debug";
13
14
  import { v, vDID, vStripUnknown, vValidate } from "@arcblock/validator";
14
15
 
15
16
  //#region src/protocols/token-factory/update.ts
16
17
  const debug = Debug("@ocap/tx-protocols:update-token-factory");
18
+ /**
19
+ * Whether this tx changes the fee rate. `fee_rate` is a proto3 scalar, so an omitted value decodes to 0: a zero is
20
+ * only treated as "set the fee to 0" when it was explicit or when the tx carries nothing else to update.
21
+ */
22
+ const shouldUpdateFeeRate = ({ tx: tx$1, itx }) => {
23
+ const rawItx = tx$1?.itx || {};
24
+ const hasExplicitFeeRate = typeof rawItx.feeRate === "number" || rawItx.value && typeof rawItx.value === "object" && typeof rawItx.value.feeRate === "number" || !rawItx.typeUrl && !rawItx.type && typeof itx.feeRate === "number";
25
+ return Boolean(itx.feeRate) || itx.feeRate === 0 && (hasExplicitFeeRate || !itx.token && !itx.data);
26
+ };
17
27
  const runner = new Runner("update_token_factory");
18
28
  const isTest = process.env.NODE_ENV === "development" || process.env.NODE_ENV === "test" || process.env.CI;
19
29
  runner.use(pipes.VerifyMultiSig(0));
@@ -49,6 +59,7 @@ runner.use((context, next) => {
49
59
  }
50
60
  return next();
51
61
  });
62
+ markStatelessPrefix(runner);
52
63
  runner.use(verify_icon_default({ iconKey: "itx.token.icon" }));
53
64
  runner.use(verify_url_default({ urlKeys: ["itx.token.website", "itx.token.metadata.value.communityUrl"] }));
54
65
  runner.use(pipes.ExtractState({
@@ -106,6 +117,12 @@ runner.use((context, next) => {
106
117
  if (!(delegatorState ? getRelatedAddresses(delegatorState) : tx$1.delegator ? [tx$1.delegator] : getRelatedAddresses(senderState)).some((addr) => isSameDid(addr, tokenFactoryState.owner))) return next(new CustomError("FORBIDDEN", "Token factory can only be updated by owner"));
107
118
  return next();
108
119
  });
120
+ runner.use((context, next) => {
121
+ const { itx, tokenFactoryState } = context;
122
+ const currentFeeRate = tokenFactoryState.feeRate;
123
+ if (shouldUpdateFeeRate(context) && itx.feeRate > currentFeeRate) return next(new CustomError("INVALID_TX", `Token factory fee rate can only be decreased after creation: current ${currentFeeRate}, requested ${itx.feeRate}`));
124
+ return next();
125
+ });
109
126
  runner.use(ensure_gas_default((context) => {
110
127
  const result = {
111
128
  create: 0,
@@ -124,9 +141,7 @@ runner.use(async (context, next) => {
124
141
  const tokenStateValue = tokenState;
125
142
  const { tokens: senderTokens = {} } = senderStateValue;
126
143
  const senderUpdates = senderChange ? applyTokenChange({ tokens: senderTokens }, senderChange) : { tokens: senderTokens };
127
- const rawItx = tx$1?.itx || {};
128
- const hasExplicitFeeRate = typeof rawItx.feeRate === "number" || rawItx.value && typeof rawItx.value === "object" && typeof rawItx.value.feeRate === "number" || !rawItx.typeUrl && !rawItx.type && typeof itx.feeRate === "number";
129
- const factoryUpdates = Boolean(itx.feeRate) || itx.feeRate === 0 && (hasExplicitFeeRate || !itx.token && !itx.data) ? { feeRate: itx.feeRate } : {};
144
+ const factoryUpdates = shouldUpdateFeeRate(context) ? { feeRate: itx.feeRate } : {};
130
145
  const tokenUpdates = itx.token ? {
131
146
  icon: itx.token.icon || tokenStateValue.icon,
132
147
  website: itx.token.website || tokenStateValue.website,
@@ -50,5 +50,9 @@ type Context = IReadyContext<TExchangeV2Tx> & IWithSender & IWithReceiver & Part
50
50
  };
51
51
  };
52
52
  declare const runner: Runner<Context>;
53
+ /** Default implicit lifetime (30 days) for `exchange_v2` orders that omit `itx.expiredAt` (#1421). */
54
+ declare const DEFAULT_EXCHANGE_V2_TTL_SECONDS: number;
55
+ /** Hard upper bound (10 years) on `transaction.exchangeV2.defaultTtlSeconds` to keep millisecond arithmetic safe. */
56
+ declare const MAX_EXCHANGE_V2_TTL_SECONDS = 315360000;
53
57
  //#endregion
54
- export { TokenInput, runner as default };
58
+ export { DEFAULT_EXCHANGE_V2_TTL_SECONDS, MAX_EXCHANGE_V2_TTL_SECONDS, TokenInput, runner as default };
@@ -1,13 +1,13 @@
1
1
  import { applyTokenChange } from "../../util.mjs";
2
2
  import ensure_cost_default from "../../pipes/ensure-cost.mjs";
3
3
  import ensure_gas_default from "../../pipes/ensure-gas.mjs";
4
- import { toTypeInfo } from "@arcblock/did";
5
4
  import { types } from "@ocap/mcrypto";
6
- import { account, delegation, token } from "@ocap/state";
7
5
  import { Runner, pipes, verifyAssetHierarchy } from "@ocap/tx-pipeline";
8
- import { BN, isSameDid } from "@ocap/util";
9
6
  import { CustomError } from "@ocap/util/lib/error";
10
7
  import { getListField } from "@ocap/util/lib/get-list-field";
8
+ import { toTypeInfo } from "@arcblock/did";
9
+ import { account, delegation, token } from "@ocap/state";
10
+ import { BN, isSameDid } from "@ocap/util";
11
11
  import { getRelatedAddresses } from "@ocap/util/lib/get-related-addr";
12
12
  import Debug from "debug";
13
13
  import { decodeBigInt } from "@ocap/message";
@@ -18,6 +18,72 @@ import isEmpty from "lodash/isEmpty.js";
18
18
  //#region src/protocols/trade/exchange-v2.ts
19
19
  const debug = Debug("@ocap/tx-protocols:exchange-v2");
20
20
  const runner = new Runner("exchange_v2");
21
+ /** Default implicit lifetime (30 days) for `exchange_v2` orders that omit `itx.expiredAt` (#1421). */
22
+ const DEFAULT_EXCHANGE_V2_TTL_SECONDS = 720 * 60 * 60;
23
+ /** Hard upper bound (10 years) on `transaction.exchangeV2.defaultTtlSeconds` to keep millisecond arithmetic safe. */
24
+ const MAX_EXCHANGE_V2_TTL_SECONDS = 31536e4;
25
+ function parseExchangeExpiredAtMs(rawExpiredAt) {
26
+ if (rawExpiredAt === void 0 || rawExpiredAt === null || rawExpiredAt === "") return {
27
+ isSet: false,
28
+ valid: true,
29
+ expiredAtMs: 0
30
+ };
31
+ if (typeof rawExpiredAt === "string") {
32
+ const ms = Date.parse(rawExpiredAt);
33
+ if (!Number.isFinite(ms)) return {
34
+ isSet: true,
35
+ valid: false,
36
+ expiredAtMs: NaN
37
+ };
38
+ return {
39
+ isSet: true,
40
+ valid: true,
41
+ expiredAtMs: ms
42
+ };
43
+ }
44
+ if (rawExpiredAt instanceof Date) {
45
+ const ms = rawExpiredAt.getTime();
46
+ return {
47
+ isSet: true,
48
+ valid: Number.isFinite(ms),
49
+ expiredAtMs: ms
50
+ };
51
+ }
52
+ if (typeof rawExpiredAt === "object" && !Array.isArray(rawExpiredAt)) {
53
+ const record = rawExpiredAt;
54
+ const keys = Object.keys(record);
55
+ if (keys.length === 0) return {
56
+ isSet: false,
57
+ valid: true,
58
+ expiredAtMs: 0
59
+ };
60
+ if (keys.some((k) => k !== "seconds" && k !== "nanos")) return {
61
+ isSet: true,
62
+ valid: false,
63
+ expiredAtMs: NaN
64
+ };
65
+ const rawSec = record.seconds;
66
+ const rawNanos = record.nanos;
67
+ const sec = rawSec === void 0 ? 0 : typeof rawSec === "number" ? rawSec : typeof rawSec === "string" && /^-?\d+$/.test(rawSec) ? Number(rawSec) : NaN;
68
+ const nanos = rawNanos === void 0 ? 0 : typeof rawNanos === "number" ? rawNanos : typeof rawNanos === "string" && /^-?\d+$/.test(rawNanos) ? Number(rawNanos) : NaN;
69
+ if (!Number.isFinite(sec) || !Number.isFinite(nanos)) return {
70
+ isSet: true,
71
+ valid: false,
72
+ expiredAtMs: NaN
73
+ };
74
+ const ms = sec * 1e3 + Math.trunc(nanos / 1e6);
75
+ return {
76
+ isSet: true,
77
+ valid: Number.isFinite(ms),
78
+ expiredAtMs: ms
79
+ };
80
+ }
81
+ return {
82
+ isSet: true,
83
+ valid: false,
84
+ expiredAtMs: NaN
85
+ };
86
+ }
21
87
  const exchangeInfoSchema = v.object({
22
88
  value: v.optional(v.nullable(v.any())),
23
89
  tokensList: v.optional(v.array(schemas.tokenInput), []),
@@ -30,6 +96,7 @@ const schema = v.pipe(v.object({
30
96
  to: schemas.tokenHolder,
31
97
  sender: exchangeInfoSchema,
32
98
  receiver: exchangeInfoSchema,
99
+ expiredAt: v.optional(v.nullable(v.any())),
33
100
  data: v.optional(v.nullable(v.any()))
34
101
  }), vStripUnknown());
35
102
  runner.use(({ itx }, next) => {
@@ -103,6 +170,24 @@ runner.use(pipes.VerifyInfo([{
103
170
  return true;
104
171
  }
105
172
  }]));
173
+ runner.use((context, next) => {
174
+ const txTimeMs = context.txTime ? new Date(context.txTime).getTime() : NaN;
175
+ const nowMs = Number.isFinite(txTimeMs) ? txTimeMs : Date.now();
176
+ const nonceBn = account.parseNonceBn(context.tx?.nonce);
177
+ const maxNonce = nowMs + account.DELEGATED_NONCE_MAX_FUTURE_MS;
178
+ if (!nonceBn || nonceBn.lte(new BN(0)) || nonceBn.gt(new BN(String(maxNonce), 10))) return next(new CustomError("INVALID_NONCE", `tx.nonce of a exchange_v2 tx should not exceed the tx time in milliseconds plus 24 hours (max ${maxNonce}, got ${nonceBn ? nonceBn.toString(10) : String(context.tx?.nonce)})`));
179
+ const parsedExpiry = parseExchangeExpiredAtMs(context.itx?.expiredAt);
180
+ if (!parsedExpiry.valid) return next(new CustomError("INVALID_TX", "Invalid itx.expiredAt"));
181
+ if (parsedExpiry.isSet) {
182
+ if (parsedExpiry.expiredAtMs < nowMs) return next(new CustomError("EXPIRED_TX", `exchange_v2 transaction expired at ${new Date(parsedExpiry.expiredAtMs).toISOString()} (txTime: ${new Date(nowMs).toISOString()})`));
183
+ } else {
184
+ const configuredTtlSeconds = context.config?.transaction?.exchangeV2?.defaultTtlSeconds;
185
+ const ttlSeconds = typeof configuredTtlSeconds === "number" && Number.isFinite(configuredTtlSeconds) && configuredTtlSeconds >= 1 ? Math.min(Math.floor(configuredTtlSeconds), MAX_EXCHANGE_V2_TTL_SECONDS) : DEFAULT_EXCHANGE_V2_TTL_SECONDS;
186
+ const minImplicitNonce = Math.max(1, Math.trunc(nowMs - ttlSeconds * 1e3));
187
+ if (nonceBn.lt(new BN(String(minImplicitNonce), 10))) return next(new CustomError("EXPIRED_TX", `exchange_v2 transaction without itx.expiredAt exceeded default TTL of ${ttlSeconds}s (min nonce ${minImplicitNonce}, got ${nonceBn.toString(10)}, txTime: ${new Date(nowMs).toISOString()})`));
188
+ }
189
+ return next();
190
+ });
106
191
  runner.use(pipes.VerifySigner({ signer: "itx.to" }));
107
192
  runner.use(pipes.VerifyListSize({ listKey: ["senderAssets", "receiverAssets"] }));
108
193
  runner.use(pipes.VerifyListSize({ listKey: ["senderTokens", "receiverTokens"] }));
@@ -350,4 +435,4 @@ runner.use(pipes.VerifyStateDiff());
350
435
  var exchange_v2_default = runner;
351
436
 
352
437
  //#endregion
353
- export { exchange_v2_default as default };
438
+ export { DEFAULT_EXCHANGE_V2_TTL_SECONDS, MAX_EXCHANGE_V2_TTL_SECONDS, exchange_v2_default as default };
@@ -1,18 +1,20 @@
1
1
  import { applyTokenChange } from "../../util.mjs";
2
2
  import ensure_cost_default from "../../pipes/ensure-cost.mjs";
3
3
  import ensure_gas_default from "../../pipes/ensure-gas.mjs";
4
+ import { markStatelessPrefix } from "../../stateless-prefix.mjs";
5
+ import { types } from "@ocap/mcrypto";
6
+ import { Runner, isBridgeReserveRole, pipes, resolveBridgeForReserve, verifyAssetHierarchy } from "@ocap/tx-pipeline";
7
+ import { CustomError } from "@ocap/util/lib/error";
8
+ import { getListField } from "@ocap/util/lib/get-list-field";
4
9
  import { toTypeInfo } from "@arcblock/did";
5
10
  import { toStakeAddress } from "@arcblock/did-util";
6
- import { types } from "@ocap/mcrypto";
7
11
  import { account, delegation, token } from "@ocap/state";
8
- import { Runner, pipes, verifyAssetHierarchy } from "@ocap/tx-pipeline";
9
12
  import { BN, isSameDid } from "@ocap/util";
10
- import { CustomError } from "@ocap/util/lib/error";
11
- import { getListField } from "@ocap/util/lib/get-list-field";
12
13
  import { getRelatedAddresses } from "@ocap/util/lib/get-related-addr";
13
14
  import { decodeBigInt } from "@ocap/message";
14
15
  import { schemas, v, vDID, vStripUnknown, vValidate } from "@arcblock/validator";
15
16
  import isEmpty from "lodash/isEmpty.js";
17
+ import { checkBridgeWithdraw, isBridgeWithdrawFailure } from "@ocap/tx-pipeline/lib/helpers/bridge-withdraw";
16
18
 
17
19
  //#region src/protocols/trade/transfer-v2.ts
18
20
  const runner = new Runner("transfer_v2");
@@ -85,6 +87,7 @@ runner.use(pipes.VerifyInfo([
85
87
  }
86
88
  ]));
87
89
  runner.use(pipes.VerifyListSize({ listKey: ["assets", "tokens"] }));
90
+ markStatelessPrefix(runner);
88
91
  runner.use((context, next) => {
89
92
  if (context.itx.value) {
90
93
  const amount = new BN(decodeBigInt(context.itx.value));
@@ -104,6 +107,14 @@ runner.use((context, next) => {
104
107
  }
105
108
  next();
106
109
  });
110
+ runner.use(async (context, next) => {
111
+ if (!isBridgeReserveRole(context.itx.to)) return next();
112
+ const bridge = await resolveBridgeForReserve(context, context.itx.to);
113
+ if (!bridge) return next(new CustomError("BRIDGE_WITHDRAW_RESERVE", `${context.itx.to} has the bridge reserve role but is not the reserve of any bridge`));
114
+ const result = checkBridgeWithdraw(context, bridge);
115
+ if (isBridgeWithdrawFailure(result)) return next(new CustomError(result.code, result.message));
116
+ return next();
117
+ });
107
118
  runner.use(ensure_gas_default((context) => {
108
119
  const result = {
109
120
  create: 0,
@@ -1,13 +1,14 @@
1
1
  import { applyTokenChange, applyTokenUpdates } from "../../util.mjs";
2
2
  import ensure_cost_default from "../../pipes/ensure-cost.mjs";
3
3
  import ensure_gas_default from "../../pipes/ensure-gas.mjs";
4
- import { toTypeInfo } from "@arcblock/did";
4
+ import { markStatelessPrefix } from "../../stateless-prefix.mjs";
5
5
  import { types } from "@ocap/mcrypto";
6
- import { account, asset, delegation, token } from "@ocap/state";
7
6
  import { Runner, pipes, verifyAssetHierarchy } from "@ocap/tx-pipeline";
8
- import { BN, isSameDid } from "@ocap/util";
9
7
  import { CustomError } from "@ocap/util/lib/error";
10
8
  import { getListField } from "@ocap/util/lib/get-list-field";
9
+ import { toTypeInfo } from "@arcblock/did";
10
+ import { account, asset, delegation, token } from "@ocap/state";
11
+ import { BN, isSameDid } from "@ocap/util";
11
12
  import { getRelatedAddresses } from "@ocap/util/lib/get-related-addr";
12
13
  import Debug from "debug";
13
14
  import { schemas, v, vStripUnknown, vValidate } from "@arcblock/validator";
@@ -106,6 +107,7 @@ runner.use(pipes.VerifyInfo([
106
107
  }
107
108
  }
108
109
  ]));
110
+ markStatelessPrefix(runner);
109
111
  runner.use(pipes.ExtractState({
110
112
  from: "inputTokens",
111
113
  to: "tokenStates",
@@ -0,0 +1,16 @@
1
+ //#region src/stateless-prefix.d.ts
2
+ type StatelessProtocolsMap = Record<string, unknown>;
3
+ /** Declare that every pipe added to `runner` so far is stateless (see the rules above). */
4
+ declare function markStatelessPrefix(runner: unknown): void;
5
+ /** Number of leading pipes of `runner` that were declared stateless (0 when the protocol did not opt in). */
6
+ declare function getStatelessPrefixLength(runner: unknown): number;
7
+ /** Registered once by `index.ts` with the protocol map every executor uses. */
8
+ declare function setDefaultStatelessProtocols(protocols: StatelessProtocolsMap): void;
9
+ /**
10
+ * Run the stateless prefix of the protocol that handles `context.txType`.
11
+ * Resolves when the tx passes (or when there is nothing to check), rejects with the protocol's own error.
12
+ * Needs a decoded context (`tx`, `itx`, `txType`); never touches state and never mutates `context`.
13
+ */
14
+ declare function assertStatelessTxRules(context: unknown, protocols?: StatelessProtocolsMap): Promise<void>;
15
+ //#endregion
16
+ export { StatelessProtocolsMap, assertStatelessTxRules, getStatelessPrefixLength, markStatelessPrefix, setDefaultStatelessProtocols };
@@ -0,0 +1,82 @@
1
+ import { Runner } from "@ocap/tx-pipeline";
2
+ import camelCase from "lodash/camelCase.js";
3
+ import cloneDeep from "lodash/cloneDeep.js";
4
+
5
+ //#region src/stateless-prefix.ts
6
+ /**
7
+ * Early rejection of statelessly-invalid txs (follow-up to #1419).
8
+ *
9
+ * Every protocol runner starts with pipes that only look at the decoded tx and the chain config: the itx schema,
10
+ * `VerifyInfo` conditions, list-size limits. A tx they reject can never become valid, whatever the chain state is,
11
+ * yet without this module it is only rejected after it went through the single-writer queue and the executor's
12
+ * state lookups (duplicate / nonce / delegation checks).
13
+ *
14
+ * A protocol opts in by calling `markStatelessPrefix(runner)` right after its last leading stateless pipe.
15
+ * `assertStatelessTxRules` then runs exactly those pipes, the same function objects the protocol runs later, so:
16
+ * - error code, message and `props.persist` are the ones the protocol produces today;
17
+ * - nothing that the protocol accepts can be rejected here (no second copy of a rule that could drift);
18
+ * - the in-protocol check stays where it is: this is an optimisation, never the only gate.
19
+ * A rejection from here never counts as a security strike (see the end of `assertStatelessTxRules`).
20
+ *
21
+ * Rules for a pipe placed before the mark: it may read `tx`, `itx`, `txType`, `txEncoding`, `extra` and `config`
22
+ * only. No statedb / indexdb / ledger access, no network or DNS, no clock, no process-local state, and no
23
+ * signature verification that the protocol does not repeat anyway. Those handles are removed from the context the
24
+ * prefix runs on, and a prefix that crashes instead of rejecting is ignored (the in-protocol run decides).
25
+ */
26
+ const prefixLengths = /* @__PURE__ */ new WeakMap();
27
+ const toProtocolName = (typeUrl) => camelCase(typeUrl.split(":").pop() ?? "");
28
+ /** Declare that every pipe added to `runner` so far is stateless (see the rules above). */
29
+ function markStatelessPrefix(runner) {
30
+ const target = runner;
31
+ prefixLengths.set(target, target.pipes.length);
32
+ }
33
+ /** Number of leading pipes of `runner` that were declared stateless (0 when the protocol did not opt in). */
34
+ function getStatelessPrefixLength(runner) {
35
+ if (!runner || typeof runner !== "object") return 0;
36
+ return prefixLengths.get(runner) ?? 0;
37
+ }
38
+ const isProtocolRejection = (err) => {
39
+ const e = err;
40
+ return Boolean(e) && typeof e?.code === "string" && typeof e?.props === "object" && e?.props !== null;
41
+ };
42
+ let defaultProtocols = {};
43
+ /** Registered once by `index.ts` with the protocol map every executor uses. */
44
+ function setDefaultStatelessProtocols(protocols) {
45
+ defaultProtocols = protocols;
46
+ }
47
+ /**
48
+ * Run the stateless prefix of the protocol that handles `context.txType`.
49
+ * Resolves when the tx passes (or when there is nothing to check), rejects with the protocol's own error.
50
+ * Needs a decoded context (`tx`, `itx`, `txType`); never touches state and never mutates `context`.
51
+ */
52
+ async function assertStatelessTxRules(context, protocols = defaultProtocols) {
53
+ const ctx = context;
54
+ if (!ctx || typeof ctx.txType !== "string" || !ctx.tx || !ctx.itx) return;
55
+ const protocol = protocols[toProtocolName(ctx.txType)];
56
+ const length = getStatelessPrefixLength(protocol);
57
+ if (!protocol || length <= 0) return;
58
+ const prefix = new Runner(`${protocol.name || "protocol"}:stateless`);
59
+ prefix.pipes = protocol.pipes.slice(0, length);
60
+ const isolated = {
61
+ ...ctx,
62
+ tx: cloneDeep(ctx.tx),
63
+ itx: cloneDeep(ctx.itx),
64
+ statedb: void 0,
65
+ indexdb: void 0,
66
+ ledger: void 0,
67
+ txn: void 0,
68
+ timer: void 0,
69
+ logger: void 0,
70
+ filter: void 0
71
+ };
72
+ const err = await new Promise((resolve) => {
73
+ prefix.run(isolated, (e) => resolve(e));
74
+ });
75
+ if (isProtocolRejection(err)) {
76
+ err._strikeRecorded = true;
77
+ throw err;
78
+ }
79
+ }
80
+
81
+ //#endregion
82
+ export { assertStatelessTxRules, getStatelessPrefixLength, markStatelessPrefix, setDefaultStatelessProtocols };