@ocap/tx-protocols 1.31.0 → 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 (164) 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 +5 -3
  8. package/esm/execute.mjs +593 -21
  9. package/esm/gas-security-guard.d.mts +7 -2
  10. package/esm/gas-security-guard.mjs +25 -16
  11. package/esm/index.d.mts +38 -19
  12. package/esm/index.mjs +7 -3
  13. package/esm/pipes/ensure-cost.mjs +36 -10
  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 +35 -11
  32. package/esm/protocols/governance/return-stake.mjs +4 -2
  33. package/esm/protocols/governance/revoke-ledger.d.mts +34 -0
  34. package/esm/protocols/governance/revoke-ledger.mjs +179 -0
  35. package/esm/protocols/governance/revoke-stake.d.mts +7 -2
  36. package/esm/protocols/governance/revoke-stake.mjs +58 -29
  37. package/esm/protocols/governance/slash-stake.mjs +14 -4
  38. package/esm/protocols/governance/stake.mjs +6 -4
  39. package/esm/protocols/rollup/bridge-create.d.mts +13 -0
  40. package/esm/protocols/rollup/bridge-create.mjs +206 -0
  41. package/esm/protocols/rollup/bridge-membership.d.mts +10 -0
  42. package/esm/protocols/rollup/bridge-membership.mjs +154 -0
  43. package/esm/protocols/rollup/bridge-migrate.d.mts +10 -0
  44. package/esm/protocols/rollup/bridge-migrate.mjs +208 -0
  45. package/esm/protocols/rollup/bridge-v2.d.mts +113 -0
  46. package/esm/protocols/rollup/bridge-v2.mjs +219 -0
  47. package/esm/protocols/rollup/claim-reward.mjs +4 -2
  48. package/esm/protocols/rollup/close.d.mts +2 -1
  49. package/esm/protocols/rollup/close.mjs +59 -6
  50. package/esm/protocols/rollup/create-block.mjs +4 -2
  51. package/esm/protocols/rollup/create.d.mts +3 -0
  52. package/esm/protocols/rollup/create.mjs +45 -6
  53. package/esm/protocols/rollup/join.d.mts +2 -1
  54. package/esm/protocols/rollup/join.mjs +31 -23
  55. package/esm/protocols/rollup/leave.d.mts +2 -1
  56. package/esm/protocols/rollup/leave.mjs +32 -24
  57. package/esm/protocols/rollup/migrate.d.mts +2 -1
  58. package/esm/protocols/rollup/migrate.mjs +19 -10
  59. package/esm/protocols/rollup/pause.d.mts +4 -1
  60. package/esm/protocols/rollup/pause.mjs +50 -6
  61. package/esm/protocols/rollup/pipes/verify-evidence.mjs +2 -2
  62. package/esm/protocols/rollup/resume.d.mts +2 -1
  63. package/esm/protocols/rollup/resume.mjs +26 -6
  64. package/esm/protocols/rollup/update.d.mts +5 -1
  65. package/esm/protocols/rollup/update.mjs +56 -9
  66. package/esm/protocols/token/create.mjs +4 -2
  67. package/esm/protocols/token/deposit-v2.mjs +5 -3
  68. package/esm/protocols/token/withdraw-v2.mjs +5 -3
  69. package/esm/protocols/token-factory/burn.mjs +4 -2
  70. package/esm/protocols/token-factory/create.mjs +8 -4
  71. package/esm/protocols/token-factory/mint.mjs +4 -2
  72. package/esm/protocols/token-factory/update.mjs +20 -5
  73. package/esm/protocols/trade/exchange-v2.d.mts +5 -1
  74. package/esm/protocols/trade/exchange-v2.mjs +89 -4
  75. package/esm/protocols/trade/transfer-v2.mjs +15 -4
  76. package/esm/protocols/trade/transfer-v3.mjs +5 -3
  77. package/esm/stateless-prefix.d.mts +16 -0
  78. package/esm/stateless-prefix.mjs +82 -0
  79. package/esm/tx-timer.d.mts +1 -1
  80. package/esm/tx-timer.mjs +1 -1
  81. package/esm/util.mjs +2 -2
  82. package/lib/bridge-release-crypto.cjs +93 -0
  83. package/lib/bridge-release-crypto.d.cts +39 -0
  84. package/lib/bridge-release-window.cjs +69 -0
  85. package/lib/bridge-release-window.d.cts +47 -0
  86. package/lib/bridge-reserve.cjs +45 -0
  87. package/lib/bridge-reserve.d.cts +24 -0
  88. package/lib/execute.cjs +594 -19
  89. package/lib/execute.d.cts +4 -2
  90. package/lib/gas-security-guard.cjs +25 -16
  91. package/lib/gas-security-guard.d.cts +7 -2
  92. package/lib/index.cjs +10 -1
  93. package/lib/index.d.cts +37 -18
  94. package/lib/pipes/ensure-cost.cjs +37 -11
  95. package/lib/pipes/write-ledger.cjs +6 -3
  96. package/lib/pipes/write-ledger.d.cts +2 -2
  97. package/lib/protocols/account/delegate.cjs +6 -4
  98. package/lib/protocols/account/migrate.cjs +5 -3
  99. package/lib/protocols/account/revoke-delegate.cjs +5 -3
  100. package/lib/protocols/asset/acquire-v2.cjs +3 -1
  101. package/lib/protocols/asset/acquire-v3.cjs +4 -2
  102. package/lib/protocols/asset/consume.cjs +3 -1
  103. package/lib/protocols/asset/create.cjs +4 -2
  104. package/lib/protocols/asset/mint.cjs +4 -2
  105. package/lib/protocols/asset/pipes/exec-mint-hook.cjs +1 -1
  106. package/lib/protocols/asset/pipes/verify-itx-address.cjs +1 -1
  107. package/lib/protocols/asset/pipes/verify-itx-assets.cjs +1 -1
  108. package/lib/protocols/asset/update.cjs +4 -2
  109. package/lib/protocols/bridge/release.cjs +390 -0
  110. package/lib/protocols/bridge/release.d.cts +34 -0
  111. package/lib/protocols/factory/create.cjs +4 -2
  112. package/lib/protocols/governance/claim-stake.cjs +35 -11
  113. package/lib/protocols/governance/return-stake.cjs +4 -2
  114. package/lib/protocols/governance/revoke-ledger.cjs +184 -0
  115. package/lib/protocols/governance/revoke-ledger.d.cts +34 -0
  116. package/lib/protocols/governance/revoke-stake.cjs +58 -29
  117. package/lib/protocols/governance/revoke-stake.d.cts +7 -2
  118. package/lib/protocols/governance/slash-stake.cjs +14 -4
  119. package/lib/protocols/governance/stake.cjs +6 -4
  120. package/lib/protocols/rollup/bridge-create.cjs +209 -0
  121. package/lib/protocols/rollup/bridge-create.d.cts +13 -0
  122. package/lib/protocols/rollup/bridge-membership.cjs +157 -0
  123. package/lib/protocols/rollup/bridge-membership.d.cts +10 -0
  124. package/lib/protocols/rollup/bridge-migrate.cjs +212 -0
  125. package/lib/protocols/rollup/bridge-migrate.d.cts +10 -0
  126. package/lib/protocols/rollup/bridge-v2.cjs +244 -0
  127. package/lib/protocols/rollup/bridge-v2.d.cts +113 -0
  128. package/lib/protocols/rollup/claim-reward.cjs +4 -2
  129. package/lib/protocols/rollup/close.cjs +59 -6
  130. package/lib/protocols/rollup/close.d.cts +2 -1
  131. package/lib/protocols/rollup/create-block.cjs +4 -2
  132. package/lib/protocols/rollup/create.cjs +45 -6
  133. package/lib/protocols/rollup/create.d.cts +3 -0
  134. package/lib/protocols/rollup/join.cjs +31 -23
  135. package/lib/protocols/rollup/join.d.cts +2 -1
  136. package/lib/protocols/rollup/leave.cjs +32 -24
  137. package/lib/protocols/rollup/leave.d.cts +2 -1
  138. package/lib/protocols/rollup/migrate.cjs +19 -10
  139. package/lib/protocols/rollup/migrate.d.cts +2 -1
  140. package/lib/protocols/rollup/pause.cjs +50 -6
  141. package/lib/protocols/rollup/pause.d.cts +4 -1
  142. package/lib/protocols/rollup/pipes/verify-evidence.cjs +2 -2
  143. package/lib/protocols/rollup/resume.cjs +26 -6
  144. package/lib/protocols/rollup/resume.d.cts +2 -1
  145. package/lib/protocols/rollup/update.cjs +56 -9
  146. package/lib/protocols/rollup/update.d.cts +5 -1
  147. package/lib/protocols/token/create.cjs +4 -2
  148. package/lib/protocols/token/deposit-v2.cjs +5 -3
  149. package/lib/protocols/token/withdraw-v2.cjs +5 -3
  150. package/lib/protocols/token-factory/burn.cjs +4 -2
  151. package/lib/protocols/token-factory/create.cjs +8 -4
  152. package/lib/protocols/token-factory/mint.cjs +4 -2
  153. package/lib/protocols/token-factory/update.cjs +20 -5
  154. package/lib/protocols/trade/exchange-v2.cjs +90 -3
  155. package/lib/protocols/trade/exchange-v2.d.cts +5 -1
  156. package/lib/protocols/trade/transfer-v2.cjs +15 -4
  157. package/lib/protocols/trade/transfer-v3.cjs +5 -3
  158. package/lib/stateless-prefix.cjs +88 -0
  159. package/lib/stateless-prefix.d.cts +16 -0
  160. package/lib/tx-timer.cjs +1 -1
  161. package/lib/tx-timer.d.cts +1 -1
  162. package/lib/util.cjs +2 -2
  163. package/package.json +16 -16
  164. package/tools/fixtures.ts +9 -4
@@ -1,10 +1,12 @@
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 { account, asset, evidence, stake, token } from "@ocap/state";
4
+ import { markStatelessPrefix } from "../../stateless-prefix.mjs";
5
+ import { LEGACY_REVOKE_KEY, consumeStakeRevoke, normalizeStakeRevokes } from "./revoke-ledger.mjs";
5
6
  import { Runner, pipes } from "@ocap/tx-pipeline";
6
- import { BN } from "@ocap/util";
7
7
  import { CustomError } from "@ocap/util/lib/error";
8
+ import { account, asset, evidence, stake, token } from "@ocap/state";
9
+ import { BN } from "@ocap/util";
8
10
  import { getRelatedAddresses } from "@ocap/util/lib/get-related-addr";
9
11
  import Debug from "debug";
10
12
  import { patterns, v, vDID, vStripUnknown, vValidate } from "@arcblock/validator";
@@ -26,6 +28,7 @@ runner.use(({ itx }, next) => {
26
28
  const { error } = vValidate(schema, itx);
27
29
  return next(error ? new CustomError("INVALID_TX", `Invalid itx: ${error.message}`) : void 0);
28
30
  });
31
+ markStatelessPrefix(runner);
29
32
  runner.use(pipes.ExtractState({
30
33
  from: "tx.from",
31
34
  to: "senderState",
@@ -100,10 +103,15 @@ runner.use(pipes.VerifyInfo([
100
103
  error: "WITHIN_WAITING_PERIOD",
101
104
  message: "You can not claim stake before waiting period ends",
102
105
  fn: (ctx) => {
103
- const { txState, stakeState, txTime } = ctx;
106
+ const { itx, txState, stakeState, txTime } = ctx;
104
107
  const waitingMs = (stakeState.revokeWaitingPeriod || 0) * 1e3;
105
108
  const txEnd = +new Date(txState.time) + waitingMs;
106
- const stateEnd = stakeState.context?.renaissanceTime ? +new Date(stakeState.context.renaissanceTime) + waitingMs : 0;
109
+ const revokes = normalizeStakeRevokes(stakeState);
110
+ const evidenceHash = itx.evidence?.hash || "";
111
+ const trackedEntry = Object.hasOwn(revokes, evidenceHash) ? revokes[evidenceHash] : void 0;
112
+ const legacyEntry = Object.hasOwn(revokes, LEGACY_REVOKE_KEY) ? revokes[LEGACY_REVOKE_KEY] : void 0;
113
+ const baseTime = trackedEntry ? trackedEntry.txTime : legacyEntry?.txTime || stakeState.context?.renaissanceTime;
114
+ const stateEnd = baseTime ? +new Date(baseTime) + waitingMs : 0;
107
115
  const end = Math.max(txEnd, stateEnd);
108
116
  return +new Date(txTime) > end;
109
117
  }
@@ -117,13 +125,20 @@ runner.use(pipes.VerifyTxInput({
117
125
  assetsKey: "assets"
118
126
  }));
119
127
  runner.use((context, next) => {
120
- const { outputs = [], stakeState } = context;
128
+ const { itx, outputs = [], stakeState } = context;
121
129
  const ZERO = new BN(0);
130
+ const revokes = normalizeStakeRevokes(stakeState);
131
+ const evidenceHash = itx.evidence?.hash || "";
132
+ const targetBucket = Object.hasOwn(revokes, evidenceHash) ? revokes[evidenceHash] : Object.hasOwn(revokes, LEGACY_REVOKE_KEY) ? revokes[LEGACY_REVOKE_KEY] : void 0;
133
+ const bucketTokens = targetBucket?.tokens || {};
134
+ const bucketAssets = new Set(targetBucket?.assets || []);
122
135
  const availableRevokedTokens = {};
123
136
  Object.entries(stakeState.revokedTokens || {}).forEach(([addr, val]) => {
124
- availableRevokedTokens[addr] = new BN(val || "0");
137
+ const totalAvail = new BN(val || "0");
138
+ const bucketAvail = new BN(bucketTokens[addr] || "0");
139
+ availableRevokedTokens[addr] = BN.min(totalAvail, bucketAvail);
125
140
  });
126
- const availableRevokedAssets = new Set(stakeState.revokedAssets || []);
141
+ const availableRevokedAssets = new Set((stakeState.revokedAssets || []).filter((a) => bucketAssets.has(a)));
127
142
  let hasClaimable = false;
128
143
  const clampedOutputs = [];
129
144
  outputs.forEach((output) => {
@@ -266,10 +281,19 @@ runner.use(async (context, next) => {
266
281
  const [newSenderState, newReceiverStates, newStakeState, newAssetStates, newEvidenceState] = await Promise.all([
267
282
  statedb.account.update(senderState.address, account.update(senderState, Object.assign({ nonce: tx$1.nonce }, receiverUpdates[senderState.address] || (senderChange ? applyTokenChange(senderState, senderChange) : {})), context), context),
268
283
  Promise.all(uniqBy(receiverStates, "address").filter((x) => x.address !== senderState.address).map((x) => statedb.account.update(x.address, account.update(x, receiverUpdates[x.address], context), context))),
269
- statedb.stake.update(stakeState.address, stake.update(stakeState, stakeUpdates, Object.values(stakeUpdates.revokedTokens || {}).some((v$1) => new BN(v$1 || "0").gt(new BN(0))) || (stakeUpdates.revokedAssets || []).length > 0 ? {
270
- ...context,
271
- txTime: stakeState.context?.renaissanceTime || context.txTime
272
- } : context), context),
284
+ (() => {
285
+ const nextRevokes = consumeStakeRevoke(stakeState, itx.evidence.hash, outputs);
286
+ return statedb.stake.update(stakeState.address, stake.update(stakeState, {
287
+ ...stakeUpdates,
288
+ context: {
289
+ ...stakeState.context,
290
+ revokes: nextRevokes
291
+ }
292
+ }, Object.values(stakeUpdates.revokedTokens || {}).some((v$1) => new BN(v$1 || "0").gt(new BN(0))) || (stakeUpdates.revokedAssets || []).length > 0 ? {
293
+ ...context,
294
+ txTime: stakeState.context?.renaissanceTime || context.txTime
295
+ } : context), context);
296
+ })(),
273
297
  Promise.all(assetStates.map(async (x) => {
274
298
  const nextOwner = assetUpdates[x.address]?.owner;
275
299
  const updatedAsset = await statedb.asset.update(x.address, asset.update(x, assetUpdates[x.address], context), context);
@@ -1,11 +1,12 @@
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 { account, asset, stake, token } from "@ocap/state";
4
+ import { markStatelessPrefix } from "../../stateless-prefix.mjs";
5
5
  import { Runner, pipes } from "@ocap/tx-pipeline";
6
- import { BN } from "@ocap/util";
7
6
  import { CustomError } from "@ocap/util/lib/error";
8
7
  import { getListField } from "@ocap/util/lib/get-list-field";
8
+ import { account, asset, stake, token } from "@ocap/state";
9
+ import { BN } from "@ocap/util";
9
10
  import { getRelatedAddresses } from "@ocap/util/lib/get-related-addr";
10
11
  import Debug from "debug";
11
12
  import { schemas, v, vDID, vStripUnknown, vValidate } from "@arcblock/validator";
@@ -50,6 +51,7 @@ runner.use(pipes.VerifyListSize({ listKey: [
50
51
  "tokens",
51
52
  "assets"
52
53
  ] }));
54
+ markStatelessPrefix(runner);
53
55
  runner.use(pipes.ExtractState({
54
56
  from: "tx.from",
55
57
  to: "senderState",
@@ -0,0 +1,34 @@
1
+ import { IStakeRevokeEntry, IStakeState } from "@ocap/types";
2
+
3
+ //#region src/protocols/governance/revoke-ledger.d.ts
4
+ declare const LEGACY_REVOKE_KEY = "__legacy__";
5
+ interface TokenInputLike {
6
+ address: string;
7
+ value: string;
8
+ }
9
+ interface OutputLike {
10
+ tokensList?: TokenInputLike[];
11
+ tokens?: TokenInputLike[];
12
+ assetsList?: string[];
13
+ assets?: string[];
14
+ }
15
+ /**
16
+ * Normalizes `stakeState.context?.revokes` against aggregate `stakeState.revokedTokens` and `stakeState.revokedAssets`.
17
+ * Any unattributed aggregate revoked tokens/assets (e.g. from pre-upgrade legacy stakes) are placed into
18
+ * `revokes[LEGACY_REVOKE_KEY]` at the head of the FIFO queue with `renaissanceTime` as their unlock base.
19
+ */
20
+ declare function normalizeStakeRevokes(stakeState: IStakeState): Record<string, IStakeRevokeEntry>;
21
+ /**
22
+ * Records a new `revoke_stake` transaction's outputs into the per-revoke ledger under `txHash`.
23
+ */
24
+ declare function recordStakeRevoke(stakeState: IStakeState, txHash: string, txTime: string, outputs: OutputLike[]): Record<string, IStakeRevokeEntry>;
25
+ /**
26
+ * Deducts slashed revoked tokens and assets from the per-revoke ledger in FIFO order (oldest first).
27
+ */
28
+ declare function slashStakeRevokes(stakeState: IStakeState, nextRevokedTokens: Record<string, string>, nextRevokedAssets: string[], slashTxTime: string): Record<string, IStakeRevokeEntry>;
29
+ /**
30
+ * Consumes claimed tokens and assets from the target revoke entry (`evidenceHash` or `LEGACY_REVOKE_KEY`).
31
+ */
32
+ declare function consumeStakeRevoke(stakeState: IStakeState, evidenceHash: string, claimedOutputs: OutputLike[]): Record<string, IStakeRevokeEntry>;
33
+ //#endregion
34
+ export { LEGACY_REVOKE_KEY, consumeStakeRevoke, normalizeStakeRevokes, recordStakeRevoke, slashStakeRevokes };
@@ -0,0 +1,179 @@
1
+ import { getListField } from "@ocap/util/lib/get-list-field";
2
+ import { BN } from "@ocap/util";
3
+
4
+ //#region src/protocols/governance/revoke-ledger.ts
5
+ const LEGACY_REVOKE_KEY = "__legacy__";
6
+ const ZERO = new BN(0);
7
+ function hasPositiveEntry(entry) {
8
+ if (!entry) return false;
9
+ const hasTokens = Object.values(entry.tokens || {}).some((v) => new BN(String(v || "0")).gt(ZERO));
10
+ const hasAssets = Array.isArray(entry.assets) && entry.assets.length > 0;
11
+ return hasTokens || hasAssets;
12
+ }
13
+ /**
14
+ * Normalizes `stakeState.context?.revokes` against aggregate `stakeState.revokedTokens` and `stakeState.revokedAssets`.
15
+ * Any unattributed aggregate revoked tokens/assets (e.g. from pre-upgrade legacy stakes) are placed into
16
+ * `revokes[LEGACY_REVOKE_KEY]` at the head of the FIFO queue with `renaissanceTime` as their unlock base.
17
+ */
18
+ function normalizeStakeRevokes(stakeState) {
19
+ const aggTokens = stakeState.revokedTokens || {};
20
+ const aggAssets = Array.isArray(stakeState.revokedAssets) ? stakeState.revokedAssets : [];
21
+ const rawRevokes = stakeState.context?.revokes || {};
22
+ const orderedKeys = [...Object.hasOwn(rawRevokes, LEGACY_REVOKE_KEY) ? [LEGACY_REVOKE_KEY] : [], ...Object.keys(rawRevokes).filter((k) => k !== LEGACY_REVOKE_KEY)];
23
+ const remainingTokenCap = {};
24
+ for (const [tok, val] of Object.entries(aggTokens)) {
25
+ const bnVal = new BN(String(val || "0"));
26
+ if (bnVal.gt(ZERO)) remainingTokenCap[tok] = bnVal;
27
+ }
28
+ const aggAssetSet = new Set(aggAssets);
29
+ const seenAssets = /* @__PURE__ */ new Set();
30
+ const normalized = {};
31
+ for (const key of orderedKeys) {
32
+ const raw = rawRevokes[key];
33
+ if (!raw || typeof raw !== "object") continue;
34
+ const clampedTokens = {};
35
+ for (const [tok, val] of Object.entries(raw.tokens || {})) {
36
+ const cap = remainingTokenCap[tok] || ZERO;
37
+ const entryBn = new BN(String(val || "0"));
38
+ const actual = BN.min(entryBn, cap);
39
+ if (actual.gt(ZERO)) {
40
+ clampedTokens[tok] = actual.toString(10);
41
+ remainingTokenCap[tok] = cap.sub(actual);
42
+ }
43
+ }
44
+ const clampedAssets = (Array.isArray(raw.assets) ? raw.assets : []).filter((a) => {
45
+ if (aggAssetSet.has(a) && !seenAssets.has(a)) {
46
+ seenAssets.add(a);
47
+ return true;
48
+ }
49
+ return false;
50
+ });
51
+ normalized[key] = {
52
+ txTime: typeof raw.txTime === "string" ? raw.txTime : "",
53
+ tokens: clampedTokens,
54
+ assets: clampedAssets
55
+ };
56
+ }
57
+ const unattributedTokens = {};
58
+ for (const [tok, rem] of Object.entries(remainingTokenCap)) if (rem.gt(ZERO)) unattributedTokens[tok] = rem.toString(10);
59
+ const unattributedAssets = aggAssets.filter((a) => !seenAssets.has(a));
60
+ if (Object.keys(unattributedTokens).length > 0 || unattributedAssets.length > 0) {
61
+ const existingLegacy = normalized[LEGACY_REVOKE_KEY];
62
+ const mergedLegacyTokens = { ...existingLegacy?.tokens || {} };
63
+ for (const [tok, val] of Object.entries(unattributedTokens)) mergedLegacyTokens[tok] = new BN(mergedLegacyTokens[tok] || "0").add(new BN(val)).toString(10);
64
+ const mergedLegacyAssets = Array.from(new Set([...existingLegacy?.assets || [], ...unattributedAssets]));
65
+ const legacyEntry = {
66
+ txTime: existingLegacy?.txTime || stakeState.context?.renaissanceTime || stakeState.context?.genesisTime || "",
67
+ tokens: mergedLegacyTokens,
68
+ assets: mergedLegacyAssets
69
+ };
70
+ const reordered = { [LEGACY_REVOKE_KEY]: legacyEntry };
71
+ for (const [k, v] of Object.entries(normalized)) if (k !== LEGACY_REVOKE_KEY && hasPositiveEntry(v)) reordered[k] = v;
72
+ return reordered;
73
+ }
74
+ const result = {};
75
+ for (const [k, v] of Object.entries(normalized)) if (hasPositiveEntry(v)) result[k] = v;
76
+ return result;
77
+ }
78
+ /**
79
+ * Records a new `revoke_stake` transaction's outputs into the per-revoke ledger under `txHash`.
80
+ */
81
+ function recordStakeRevoke(stakeState, txHash, txTime, outputs) {
82
+ const revokes = normalizeStakeRevokes(stakeState);
83
+ const prev = Object.hasOwn(revokes, txHash) ? revokes[txHash] : void 0;
84
+ const mergedTokens = { ...prev?.tokens || {} };
85
+ const mergedAssets = new Set(prev?.assets || []);
86
+ for (const out of outputs || []) {
87
+ const tokensList = getListField(out, "tokens") || [];
88
+ const assetsList = getListField(out, "assets") || [];
89
+ for (const { address, value } of tokensList) {
90
+ const addBn = new BN(String(value || "0"));
91
+ if (addBn.gt(ZERO)) mergedTokens[address] = new BN(mergedTokens[address] || "0").add(addBn).toString(10);
92
+ }
93
+ for (const assetAddr of assetsList) mergedAssets.add(assetAddr);
94
+ }
95
+ const nextEntry = {
96
+ txTime: txTime || prev?.txTime || "",
97
+ tokens: mergedTokens,
98
+ assets: Array.from(mergedAssets)
99
+ };
100
+ if (hasPositiveEntry(nextEntry)) revokes[txHash] = nextEntry;
101
+ return revokes;
102
+ }
103
+ /**
104
+ * Deducts slashed revoked tokens and assets from the per-revoke ledger in FIFO order (oldest first).
105
+ */
106
+ function slashStakeRevokes(stakeState, nextRevokedTokens, nextRevokedAssets, slashTxTime) {
107
+ const revokes = normalizeStakeRevokes(stakeState);
108
+ const prevRevokedTokens = stakeState.revokedTokens || {};
109
+ const slashedTokens = {};
110
+ for (const [tok, prevVal] of Object.entries(prevRevokedTokens)) {
111
+ const prevBn = new BN(String(prevVal || "0"));
112
+ const nextBn = new BN(String(nextRevokedTokens?.[tok] || "0"));
113
+ const diff = prevBn.sub(nextBn);
114
+ if (diff.gt(ZERO)) slashedTokens[tok] = diff;
115
+ }
116
+ const nextAssetSet = new Set(nextRevokedAssets || []);
117
+ const result = {};
118
+ for (const [key, entry] of Object.entries(revokes)) {
119
+ let shrunk = false;
120
+ const updatedTokens = {};
121
+ for (const [tok, val] of Object.entries(entry.tokens || {})) {
122
+ const avail = new BN(String(val || "0"));
123
+ const toSlash = slashedTokens[tok] || ZERO;
124
+ const deduct = BN.min(avail, toSlash);
125
+ if (deduct.gt(ZERO)) {
126
+ shrunk = true;
127
+ slashedTokens[tok] = toSlash.sub(deduct);
128
+ }
129
+ const rem = avail.sub(deduct);
130
+ if (rem.gt(ZERO)) updatedTokens[tok] = rem.toString(10);
131
+ }
132
+ const prevAssets = entry.assets || [];
133
+ const updatedAssets = prevAssets.filter((a) => nextAssetSet.has(a));
134
+ if (updatedAssets.length < prevAssets.length) shrunk = true;
135
+ const updatedEntry = {
136
+ txTime: key === LEGACY_REVOKE_KEY && shrunk && slashTxTime ? slashTxTime : entry.txTime,
137
+ tokens: updatedTokens,
138
+ assets: updatedAssets
139
+ };
140
+ if (hasPositiveEntry(updatedEntry)) result[key] = updatedEntry;
141
+ }
142
+ return result;
143
+ }
144
+ /**
145
+ * Consumes claimed tokens and assets from the target revoke entry (`evidenceHash` or `LEGACY_REVOKE_KEY`).
146
+ */
147
+ function consumeStakeRevoke(stakeState, evidenceHash, claimedOutputs) {
148
+ const revokes = normalizeStakeRevokes(stakeState);
149
+ const targetKey = evidenceHash && Object.hasOwn(revokes, evidenceHash) ? evidenceHash : LEGACY_REVOKE_KEY;
150
+ const target = Object.hasOwn(revokes, targetKey) ? revokes[targetKey] : void 0;
151
+ if (!target) return revokes;
152
+ const claimedTokens = {};
153
+ const claimedAssets = /* @__PURE__ */ new Set();
154
+ for (const out of claimedOutputs || []) {
155
+ const tokensList = out.tokens || out.tokensList || [];
156
+ const assetsList = out.assets || out.assetsList || [];
157
+ for (const { address, value } of tokensList) claimedTokens[address] = (claimedTokens[address] || ZERO).add(new BN(String(value || "0")));
158
+ for (const assetAddr of assetsList) claimedAssets.add(assetAddr);
159
+ }
160
+ const remainingTokens = {};
161
+ for (const [tok, val] of Object.entries(target.tokens || {})) {
162
+ const avail = new BN(String(val || "0"));
163
+ const deduct = BN.min(avail, claimedTokens[tok] || ZERO);
164
+ const rem = avail.sub(deduct);
165
+ if (rem.gt(ZERO)) remainingTokens[tok] = rem.toString(10);
166
+ }
167
+ const remainingAssets = (target.assets || []).filter((a) => !claimedAssets.has(a));
168
+ const updatedTarget = {
169
+ txTime: target.txTime,
170
+ tokens: remainingTokens,
171
+ assets: remainingAssets
172
+ };
173
+ if (hasPositiveEntry(updatedTarget)) revokes[targetKey] = updatedTarget;
174
+ else delete revokes[targetKey];
175
+ return revokes;
176
+ }
177
+
178
+ //#endregion
179
+ export { LEGACY_REVOKE_KEY, consumeStakeRevoke, normalizeStakeRevokes, recordStakeRevoke, slashStakeRevokes };
@@ -1,6 +1,6 @@
1
1
  import { Runner } from "@ocap/tx-pipeline";
2
2
  import { BN } from "@ocap/util";
3
- import { IReadyContext, IWithAssets, IWithReceivers, IWithSender, IWithStake, IWithTokens, TRevokeStakeTx } from "@ocap/types";
3
+ import { IReadyContext, IWithAssets, IWithReceivers, IWithSender, IWithStake, IWithToken, IWithTokenFactory, IWithTokens, TRevokeStakeTx } from "@ocap/types";
4
4
 
5
5
  //#region src/protocols/governance/revoke-stake.d.ts
6
6
  /** Token input type */
@@ -29,7 +29,12 @@ interface TokenCondition {
29
29
  * Phase: IReadyContext (after TakeStateSnapshot)
30
30
  * Mixins: IWithSender, IWithStake, IWithReceivers, IWithTokens, IWithAssets
31
31
  */
32
- type Context = IReadyContext<TRevokeStakeTx> & IWithSender & IWithStake & Partial<IWithReceivers> & Partial<IWithTokens> & Partial<IWithAssets> & {
32
+ type Context = IReadyContext<TRevokeStakeTx> & IWithSender & IWithStake & Partial<IWithReceivers> & Partial<IWithTokens> & Partial<IWithAssets> & Partial<Pick<IWithToken, 'tokenState'>> & Partial<IWithTokenFactory> & {
33
+ /**
34
+ * Set when a locked Stake-for-Token may be released (#1422): `retire` when this tx also retires the factory,
35
+ * `retired` when the factory was retired before.
36
+ */
37
+ tokenStakeRelease?: 'retire' | 'retired';
33
38
  /** Parsed outputs from itx */
34
39
  outputs?: MultiOutput[];
35
40
  /** Receiver addresses from outputs */
@@ -1,15 +1,18 @@
1
1
  import { 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 { account, stake } from "@ocap/state";
4
+ import { markStatelessPrefix } from "../../stateless-prefix.mjs";
5
+ import { recordStakeRevoke } from "./revoke-ledger.mjs";
5
6
  import { Runner, pipes } from "@ocap/tx-pipeline";
6
- import { BN } from "@ocap/util";
7
7
  import { CustomError } from "@ocap/util/lib/error";
8
8
  import { getListField } from "@ocap/util/lib/get-list-field";
9
+ import { account, stake, tokenFactory } from "@ocap/state";
10
+ import { BN, isSameDid } from "@ocap/util";
9
11
  import { getRelatedAddresses } from "@ocap/util/lib/get-related-addr";
10
12
  import Debug from "debug";
11
13
  import { schemas, v, vDID, vStripUnknown, vValidate } from "@arcblock/validator";
12
14
  import isEmpty from "lodash/isEmpty.js";
15
+ import { isTokenFullyRedeemed, isTokenIssuanceStakeOf } from "@ocap/tx-pipeline/lib/pipes/post-execution-invariant-gate";
13
16
 
14
17
  //#region src/protocols/governance/revoke-stake.ts
15
18
  const debug = Debug("@ocap/tx-protocols:revoke-stake");
@@ -48,6 +51,7 @@ runner.use(pipes.VerifyListSize({ listKey: [
48
51
  "tokens",
49
52
  "assets"
50
53
  ] }));
54
+ markStatelessPrefix(runner);
51
55
  runner.use(pipes.ExtractState({
52
56
  from: "tx.from",
53
57
  to: "senderState",
@@ -75,31 +79,46 @@ runner.use(pipes.ExtractState({
75
79
  status: "INVALID_STAKE_STATE",
76
80
  table: "stake"
77
81
  }));
78
- runner.use(pipes.VerifyInfo([
79
- {
80
- error: "SENDER_NOT_MATCH",
81
- message: "You are not allowed to revoke stake from this address",
82
- fn: (ctx) => {
83
- const context = ctx;
84
- return getRelatedAddresses(context.senderState).includes(context.stakeState.sender);
85
- }
86
- },
87
- {
88
- error: "STAKE_NOT_REVOCABLE",
89
- message: "This stake address is not revocable",
90
- fn: (ctx) => {
91
- return ctx.stakeState.revocable;
92
- }
93
- },
94
- {
95
- error: "INVALID_TX",
96
- message: "Can not revoke assets that are not locked in the stake",
97
- fn: (ctx) => {
98
- const context = ctx;
99
- return (context.assets || []).every((x) => (context.stakeState.assets || []).includes(x));
100
- }
82
+ runner.use(pipes.VerifyInfo([{
83
+ error: "SENDER_NOT_MATCH",
84
+ message: "You are not allowed to revoke stake from this address",
85
+ fn: (ctx) => {
86
+ const context = ctx;
87
+ return getRelatedAddresses(context.senderState).includes(context.stakeState.sender);
101
88
  }
102
- ]));
89
+ }]));
90
+ runner.use(async (context, next) => {
91
+ const { stakeState, senderState, statedb, config } = context;
92
+ if (stakeState.revocable !== false) return next();
93
+ const notRevocable = (reason = "") => next(new CustomError("STAKE_NOT_REVOCABLE", `This stake address is not revocable${reason ? `: ${reason}` : ""}`));
94
+ const officialToken = config.token?.address || "";
95
+ const symbol = stakeState.nonce;
96
+ if (!officialToken || typeof symbol !== "string" || !symbol || !isSameDid(stakeState.receiver, officialToken)) return notRevocable();
97
+ const tokenAddress = await statedb.token.getAddressBySymbol(symbol.toUpperCase(), context);
98
+ const tokenState = tokenAddress ? await statedb.token.get(tokenAddress, context) : null;
99
+ if (!tokenState || !isTokenIssuanceStakeOf(stakeState, tokenState, officialToken)) return notRevocable();
100
+ const tokenFactoryState = await statedb.tokenFactory.get(tokenState.tokenFactoryAddress, context);
101
+ if (!tokenFactoryState) return notRevocable();
102
+ const label = `token ${tokenState.symbol} (${tokenState.address})`;
103
+ if (!isTokenFullyRedeemed(tokenState, tokenFactoryState)) return notRevocable(`the stake for ${label} stays locked until 100% of its supply is burned`);
104
+ const factoryStatus = tokenFactoryState.status || "ACTIVE";
105
+ if (factoryStatus === "ACTIVE") {
106
+ if (!getRelatedAddresses(senderState).some((x) => isSameDid(x, tokenFactoryState.owner))) return notRevocable(`only the current owner of the token factory can retire ${label}`);
107
+ context.tokenStakeRelease = "retire";
108
+ } else if (factoryStatus === "RETIRED") context.tokenStakeRelease = "retired";
109
+ else return notRevocable(`token factory of ${label} is ${factoryStatus}`);
110
+ context.tokenState = tokenState;
111
+ context.tokenFactoryState = tokenFactoryState;
112
+ return next();
113
+ });
114
+ runner.use(pipes.VerifyInfo([{
115
+ error: "INVALID_TX",
116
+ message: "Can not revoke assets that are not locked in the stake",
117
+ fn: (ctx) => {
118
+ const context = ctx;
119
+ return (context.assets || []).every((x) => (context.stakeState.assets || []).includes(x));
120
+ }
121
+ }]));
103
122
  runner.use(pipes.ExtractState({
104
123
  from: "tokens",
105
124
  to: "tokenStates",
@@ -139,15 +158,16 @@ runner.use(pipes.VerifyUpdater({
139
158
  assetKey: "assetStates",
140
159
  ownerKey: "stakeState"
141
160
  }));
142
- runner.use(ensure_gas_default(() => ({
161
+ runner.use(ensure_gas_default((context) => ({
143
162
  create: 0,
144
- update: 2,
163
+ update: context.tokenStakeRelease === "retire" ? 3 : 2,
145
164
  payment: 0
146
165
  })));
147
166
  runner.use(ensure_cost_default({ attachSenderChanges: true }));
148
167
  runner.use(pipes.TakeStateSnapshot());
149
168
  runner.use(async (context, next) => {
150
169
  const { tx: tx$1, itx, outputs = [], statedb, senderState, senderUpdates, stakeState, updateVaults } = context;
170
+ const { tokenStakeRelease, tokenFactoryState } = context;
151
171
  const stakeUpdates = {
152
172
  tokens: stakeState.tokens || {},
153
173
  assets: stakeState.assets || [],
@@ -162,14 +182,23 @@ runner.use(async (context, next) => {
162
182
  stakeUpdates.revokedTokens = applyTokenUpdates(tokensList, { tokens: stakeUpdates.revokedTokens }, "add").tokens;
163
183
  stakeUpdates.revokedAssets = stakeUpdates.revokedAssets.concat(...assetsList);
164
184
  });
185
+ if (tokenStakeRelease === "retire") context.tokenFactoryState = await statedb.tokenFactory.update(tokenFactoryState.address, tokenFactory.update(tokenFactoryState, { status: "RETIRED" }, context), context);
165
186
  const [newSenderState, newStakeState] = await Promise.all([statedb.account.update(senderState.address, account.update(senderState, {
166
187
  nonce: tx$1.nonce,
167
188
  ...senderUpdates
168
189
  }, context), context), (() => {
190
+ const nextRevokes = recordStakeRevoke(stakeState, context.txHash, context.txTime, outputs);
169
191
  const hasPendingRevokedTokens = Object.values(stakeState.revokedTokens || {}).some((v$1) => new BN(String(v$1 || "0")).gt(new BN(0)));
170
192
  const hasPendingRevokedAssets = Array.isArray(stakeState.revokedAssets) && stakeState.revokedAssets.length > 0;
171
193
  const preserveRenaissanceTime = (hasPendingRevokedTokens || hasPendingRevokedAssets) && stakeState.context?.renaissanceTime;
172
- return statedb.stake.update(stakeState.address, stake.update(stakeState, stakeUpdates, preserveRenaissanceTime ? {
194
+ return statedb.stake.update(stakeState.address, stake.update(stakeState, {
195
+ ...stakeUpdates,
196
+ ...tokenStakeRelease ? { revocable: true } : {},
197
+ context: {
198
+ ...stakeState.context,
199
+ revokes: nextRevokes
200
+ }
201
+ }, preserveRenaissanceTime ? {
173
202
  ...context,
174
203
  txTime: preserveRenaissanceTime
175
204
  } : context), context);
@@ -1,13 +1,15 @@
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
+ import { slashStakeRevokes } from "./revoke-ledger.mjs";
5
6
  import { types } from "@ocap/mcrypto";
6
- import { account, asset, stake, token } from "@ocap/state";
7
7
  import { Runner, pipes } from "@ocap/tx-pipeline";
8
- import { BN } 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 { toTypeInfo } from "@arcblock/did";
11
+ import { account, asset, stake, token } from "@ocap/state";
12
+ import { BN } from "@ocap/util";
11
13
  import { getRelatedAddresses } from "@ocap/util/lib/get-related-addr";
12
14
  import Debug from "debug";
13
15
  import { schemas, v, vDID, vStripUnknown, vValidate } from "@arcblock/validator";
@@ -52,6 +54,7 @@ runner.use(pipes.VerifyListSize({ listKey: [
52
54
  "tokens",
53
55
  "assets"
54
56
  ] }));
57
+ markStatelessPrefix(runner);
55
58
  runner.use(pipes.ExtractState({
56
59
  from: "tx.from",
57
60
  to: "senderState",
@@ -220,9 +223,16 @@ runner.use(async (context, next) => {
220
223
  (() => {
221
224
  const prevRevoked = stakeState.revokedTokens || {};
222
225
  const nextRevoked = stakeUpdates.revokedTokens || {};
226
+ const nextRevokes = slashStakeRevokes(stakeState, nextRevoked, stakeUpdates.revokedAssets || [], context.txTime);
223
227
  const poolShrunk = Object.keys(prevRevoked).some((k) => new BN(prevRevoked[k] || "0").gt(new BN(nextRevoked[k] || "0"))) || (stakeUpdates.revokedAssets || []).length < (stakeState.revokedAssets || []).length;
224
228
  const hasPending = Object.values(nextRevoked).some((v$1) => new BN(v$1 || "0").gt(new BN(0))) || (stakeUpdates.revokedAssets || []).length > 0;
225
- return statedb.stake.update(stakeState.address, stake.update(stakeState, stakeUpdates, hasPending && !poolShrunk ? {
229
+ return statedb.stake.update(stakeState.address, stake.update(stakeState, {
230
+ ...stakeUpdates,
231
+ context: {
232
+ ...stakeState.context,
233
+ revokes: nextRevokes
234
+ }
235
+ }, hasPending && !poolShrunk ? {
226
236
  ...context,
227
237
  txTime: stakeState.context?.renaissanceTime || context.txTime
228
238
  } : context), context);
@@ -1,14 +1,15 @@
1
1
  import { applyTokenChange, applyTokenUpdates, decodeAnySafe, isGasStakeAddress, isGasStakeInput } 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
- import { toStakeAddress } from "@arcblock/did-util";
4
+ import { markStatelessPrefix } from "../../stateless-prefix.mjs";
6
5
  import { types } from "@ocap/mcrypto";
7
- import { account, asset, stake, token } from "@ocap/state";
8
6
  import { Runner, pipes } from "@ocap/tx-pipeline";
9
- import { BN, fromTokenToUnit } from "@ocap/util";
10
7
  import { CustomError } from "@ocap/util/lib/error";
11
8
  import { getListField } from "@ocap/util/lib/get-list-field";
9
+ import { toTypeInfo } from "@arcblock/did";
10
+ import { toStakeAddress } from "@arcblock/did-util";
11
+ import { account, asset, stake, token } from "@ocap/state";
12
+ import { BN, fromTokenToUnit } from "@ocap/util";
12
13
  import pick from "lodash/pick.js";
13
14
  import Debug from "debug";
14
15
  import { schemas, v, vDID, vStripUnknown, vValidate } from "@arcblock/validator";
@@ -93,6 +94,7 @@ runner.use(pipes.VerifyListSize({ listKey: [
93
94
  "tokens",
94
95
  "assets"
95
96
  ] }));
97
+ markStatelessPrefix(runner);
96
98
  runner.use(pipes.VerifyMultiSigV2({ signersKey: "senders" }));
97
99
  runner.use(pipes.ExtractState({
98
100
  from: "itx.address",
@@ -0,0 +1,13 @@
1
+ import { PipeNext } from "@ocap/tx-pipeline";
2
+
3
+ //#region src/protocols/rollup/bridge-create.d.ts
4
+ type Ctx = any;
5
+ /**
6
+ * Everything the v1 pipes do not cover for a v2 create. Runs after the token-authority check (#1411) and the
7
+ * one-bridge-per-token check, so it only sees a creator that already controls the token.
8
+ */
9
+ declare function verifyBridgeCreate(context: Ctx, next: PipeNext): Promise<void>;
10
+ /** The state writes of a v2 create: row, reserve account (funded zero-sum from tx.from), and the three index entries. */
11
+ declare function createBridgeStep(context: Ctx, next: PipeNext): Promise<void>;
12
+ //#endregion
13
+ export { createBridgeStep, verifyBridgeCreate };