@ocap/tx-protocols 1.30.25 → 1.31.0

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 (118) hide show
  1. package/esm/execute.d.mts +7 -0
  2. package/esm/execute.mjs +196 -71
  3. package/esm/gas-security-guard.d.mts +374 -0
  4. package/esm/gas-security-guard.mjs +1101 -0
  5. package/esm/index.d.mts +35 -5
  6. package/esm/index.mjs +3 -1
  7. package/esm/pipes/ensure-cost.mjs +314 -58
  8. package/esm/protocols/account/delegate.mjs +64 -16
  9. package/esm/protocols/account/migrate.d.mts +3 -0
  10. package/esm/protocols/account/migrate.mjs +235 -35
  11. package/esm/protocols/account/revoke-delegate.d.mts +3 -3
  12. package/esm/protocols/account/revoke-delegate.mjs +70 -38
  13. package/esm/protocols/asset/acquire-v2.mjs +29 -12
  14. package/esm/protocols/asset/acquire-v3.mjs +78 -22
  15. package/esm/protocols/asset/calls/transfer-token.mjs +2 -1
  16. package/esm/protocols/asset/calls/transfer.mjs +1 -0
  17. package/esm/protocols/asset/consume.mjs +12 -4
  18. package/esm/protocols/asset/create.mjs +18 -5
  19. package/esm/protocols/asset/mint.mjs +23 -1
  20. package/esm/protocols/asset/pipes/exec-mint-hook.d.mts +21 -1
  21. package/esm/protocols/asset/pipes/exec-mint-hook.mjs +115 -1
  22. package/esm/protocols/asset/pipes/extract-factory-tokens.mjs +14 -8
  23. package/esm/protocols/asset/pipes/verify-itx-address.mjs +9 -0
  24. package/esm/protocols/asset/pipes/verify-itx-assets.mjs +21 -5
  25. package/esm/protocols/asset/update.d.mts +13 -2
  26. package/esm/protocols/asset/update.mjs +133 -14
  27. package/esm/protocols/factory/create.mjs +14 -6
  28. package/esm/protocols/governance/claim-stake.mjs +92 -10
  29. package/esm/protocols/governance/return-stake.mjs +44 -12
  30. package/esm/protocols/governance/revoke-stake.mjs +17 -5
  31. package/esm/protocols/governance/slash-stake.mjs +64 -25
  32. package/esm/protocols/governance/stake.mjs +63 -13
  33. package/esm/protocols/rollup/claim-reward.mjs +39 -20
  34. package/esm/protocols/rollup/close.mjs +1 -1
  35. package/esm/protocols/rollup/create-block.mjs +8 -7
  36. package/esm/protocols/rollup/create.mjs +17 -6
  37. package/esm/protocols/rollup/join.mjs +3 -3
  38. package/esm/protocols/rollup/leave.mjs +1 -1
  39. package/esm/protocols/rollup/migrate.mjs +7 -4
  40. package/esm/protocols/rollup/pipes/verify-evidence.mjs +12 -4
  41. package/esm/protocols/rollup/update.mjs +6 -1
  42. package/esm/protocols/token/create.mjs +23 -12
  43. package/esm/protocols/token/deposit-v2.d.mts +5 -1
  44. package/esm/protocols/token/deposit-v2.mjs +81 -29
  45. package/esm/protocols/token/withdraw-v2.mjs +33 -16
  46. package/esm/protocols/token-factory/burn.mjs +43 -10
  47. package/esm/protocols/token-factory/create.mjs +23 -14
  48. package/esm/protocols/token-factory/mint.mjs +54 -21
  49. package/esm/protocols/token-factory/pipes/verify-icon.mjs +1 -1
  50. package/esm/protocols/token-factory/update.mjs +16 -6
  51. package/esm/protocols/trade/exchange-v2.d.mts +4 -0
  52. package/esm/protocols/trade/exchange-v2.mjs +78 -22
  53. package/esm/protocols/trade/transfer-v2.mjs +44 -13
  54. package/esm/protocols/trade/transfer-v3.mjs +72 -31
  55. package/esm/util.d.mts +3 -1
  56. package/esm/util.mjs +26 -17
  57. package/lib/execute.cjs +193 -67
  58. package/lib/execute.d.cts +7 -0
  59. package/lib/gas-security-guard.cjs +1140 -0
  60. package/lib/gas-security-guard.d.cts +374 -0
  61. package/lib/index.cjs +122 -1
  62. package/lib/index.d.cts +36 -6
  63. package/lib/pipes/ensure-cost.cjs +313 -57
  64. package/lib/protocols/account/delegate.cjs +64 -16
  65. package/lib/protocols/account/migrate.cjs +235 -35
  66. package/lib/protocols/account/migrate.d.cts +3 -0
  67. package/lib/protocols/account/revoke-delegate.cjs +71 -39
  68. package/lib/protocols/account/revoke-delegate.d.cts +3 -3
  69. package/lib/protocols/asset/acquire-v2.cjs +28 -11
  70. package/lib/protocols/asset/acquire-v3.cjs +77 -20
  71. package/lib/protocols/asset/calls/transfer-token.cjs +3 -2
  72. package/lib/protocols/asset/calls/transfer.cjs +1 -0
  73. package/lib/protocols/asset/consume.cjs +11 -3
  74. package/lib/protocols/asset/create.cjs +19 -6
  75. package/lib/protocols/asset/mint.cjs +23 -1
  76. package/lib/protocols/asset/pipes/exec-mint-hook.cjs +117 -1
  77. package/lib/protocols/asset/pipes/exec-mint-hook.d.cts +21 -1
  78. package/lib/protocols/asset/pipes/extract-factory-tokens.cjs +14 -9
  79. package/lib/protocols/asset/pipes/verify-itx-address.cjs +9 -0
  80. package/lib/protocols/asset/pipes/verify-itx-assets.cjs +21 -5
  81. package/lib/protocols/asset/update.cjs +131 -12
  82. package/lib/protocols/asset/update.d.cts +13 -2
  83. package/lib/protocols/factory/create.cjs +14 -6
  84. package/lib/protocols/governance/claim-stake.cjs +92 -9
  85. package/lib/protocols/governance/claim-stake.d.cts +1 -1
  86. package/lib/protocols/governance/return-stake.cjs +44 -11
  87. package/lib/protocols/governance/return-stake.d.cts +1 -1
  88. package/lib/protocols/governance/revoke-stake.cjs +17 -5
  89. package/lib/protocols/governance/revoke-stake.d.cts +1 -1
  90. package/lib/protocols/governance/slash-stake.cjs +64 -24
  91. package/lib/protocols/governance/slash-stake.d.cts +1 -1
  92. package/lib/protocols/governance/stake.cjs +65 -14
  93. package/lib/protocols/rollup/claim-reward.cjs +39 -20
  94. package/lib/protocols/rollup/close.cjs +1 -1
  95. package/lib/protocols/rollup/create-block.cjs +9 -8
  96. package/lib/protocols/rollup/create-block.d.cts +1 -1
  97. package/lib/protocols/rollup/create.cjs +18 -7
  98. package/lib/protocols/rollup/join.cjs +3 -3
  99. package/lib/protocols/rollup/leave.cjs +1 -1
  100. package/lib/protocols/rollup/migrate.cjs +7 -4
  101. package/lib/protocols/rollup/pipes/verify-evidence.cjs +11 -3
  102. package/lib/protocols/rollup/update.cjs +6 -1
  103. package/lib/protocols/token/create.cjs +24 -13
  104. package/lib/protocols/token/deposit-v2.cjs +80 -28
  105. package/lib/protocols/token/deposit-v2.d.cts +5 -1
  106. package/lib/protocols/token/withdraw-v2.cjs +32 -15
  107. package/lib/protocols/token-factory/burn.cjs +42 -9
  108. package/lib/protocols/token-factory/create.cjs +24 -15
  109. package/lib/protocols/token-factory/mint.cjs +53 -20
  110. package/lib/protocols/token-factory/pipes/verify-icon.cjs +1 -1
  111. package/lib/protocols/token-factory/update.cjs +16 -6
  112. package/lib/protocols/trade/exchange-v2.cjs +76 -20
  113. package/lib/protocols/trade/exchange-v2.d.cts +4 -0
  114. package/lib/protocols/trade/transfer-v2.cjs +45 -14
  115. package/lib/protocols/trade/transfer-v3.cjs +72 -30
  116. package/lib/util.cjs +26 -17
  117. package/lib/util.d.cts +4 -2
  118. package/package.json +16 -16
@@ -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 { account, asset, evidence, stake } from "@ocap/state";
4
+ import { account, asset, evidence, stake, token } from "@ocap/state";
5
5
  import { Runner, pipes } from "@ocap/tx-pipeline";
6
6
  import { BN } from "@ocap/util";
7
7
  import { CustomError } from "@ocap/util/lib/error";
8
+ import { getRelatedAddresses } from "@ocap/util/lib/get-related-addr";
8
9
  import Debug from "debug";
9
10
  import { patterns, v, vDID, vStripUnknown, vValidate } from "@arcblock/validator";
10
- import { getRelatedAddresses } from "@ocap/util/lib/get-related-addr";
11
+ import uniqBy from "lodash/uniqBy.js";
11
12
 
12
13
  //#region src/protocols/governance/claim-stake.ts
13
14
  const debug = Debug("@ocap/tx-protocols:claim-stake");
@@ -41,6 +42,7 @@ runner.use(pipes.VerifyAccountMigration({
41
42
  stateKey: "senderState",
42
43
  addressKey: "tx.from"
43
44
  }));
45
+ runner.use(pipes.VerifyBlocked({ stateKeys: ["senderState", "delegatorState"] }));
44
46
  runner.use(pipes.VerifyInfo([{
45
47
  error: "SENDER_NOT_MATCH",
46
48
  message: "You are not allowed to claim stake from this address",
@@ -99,7 +101,10 @@ runner.use(pipes.VerifyInfo([
99
101
  message: "You can not claim stake before waiting period ends",
100
102
  fn: (ctx) => {
101
103
  const { txState, stakeState, txTime } = ctx;
102
- const end = +new Date(txState.time) + (stakeState.revokeWaitingPeriod || 0) * 1e3;
104
+ const waitingMs = (stakeState.revokeWaitingPeriod || 0) * 1e3;
105
+ const txEnd = +new Date(txState.time) + waitingMs;
106
+ const stateEnd = stakeState.context?.renaissanceTime ? +new Date(stakeState.context.renaissanceTime) + waitingMs : 0;
107
+ const end = Math.max(txEnd, stateEnd);
103
108
  return +new Date(txTime) > end;
104
109
  }
105
110
  }
@@ -111,12 +116,62 @@ runner.use(pipes.VerifyTxInput({
111
116
  tokensKey: "tokens",
112
117
  assetsKey: "assets"
113
118
  }));
119
+ runner.use((context, next) => {
120
+ const { outputs = [], stakeState } = context;
121
+ const ZERO = new BN(0);
122
+ const availableRevokedTokens = {};
123
+ Object.entries(stakeState.revokedTokens || {}).forEach(([addr, val]) => {
124
+ availableRevokedTokens[addr] = new BN(val || "0");
125
+ });
126
+ const availableRevokedAssets = new Set(stakeState.revokedAssets || []);
127
+ let hasClaimable = false;
128
+ const clampedOutputs = [];
129
+ outputs.forEach((output) => {
130
+ const rawTokens = output.tokens || output.tokensList || [];
131
+ const clampedTokens = [];
132
+ rawTokens.forEach(({ address, value }) => {
133
+ const requested = new BN(value || "0");
134
+ const available = availableRevokedTokens[address] || ZERO;
135
+ const actual = BN.min(requested, available);
136
+ if (actual.gt(ZERO)) {
137
+ clampedTokens.push({
138
+ address,
139
+ value: actual.toString(10)
140
+ });
141
+ availableRevokedTokens[address] = available.sub(actual);
142
+ hasClaimable = true;
143
+ }
144
+ });
145
+ const clampedAssets = (output.assets || output.assetsList || []).filter((assetAddr) => {
146
+ if (availableRevokedAssets.has(assetAddr)) {
147
+ availableRevokedAssets.delete(assetAddr);
148
+ hasClaimable = true;
149
+ return true;
150
+ }
151
+ return false;
152
+ });
153
+ if (clampedTokens.length > 0 || clampedAssets.length > 0) clampedOutputs.push({
154
+ ...output,
155
+ tokens: clampedTokens,
156
+ tokensList: clampedTokens,
157
+ assets: clampedAssets,
158
+ assetsList: clampedAssets
159
+ });
160
+ });
161
+ if (!hasClaimable) return next(new CustomError("INSUFFICIENT_FUND", "Account does not have enough token balance"));
162
+ context.outputs = clampedOutputs;
163
+ context.receivers = Array.from(new Set(clampedOutputs.map((o) => o.owner)));
164
+ context.tokens = Array.from(new Set(clampedOutputs.flatMap((o) => o.tokens.map((t) => t.address))));
165
+ context.assets = Array.from(new Set(clampedOutputs.flatMap((o) => o.assets)));
166
+ return next();
167
+ });
114
168
  runner.use(pipes.ExtractState({
115
169
  from: "receivers",
116
170
  to: "receiverStates",
117
171
  status: "INVALID_RECEIVER_STATE",
118
172
  table: "account"
119
173
  }));
174
+ runner.use(pipes.VerifyBlocked({ stateKeys: ["receiverStates"] }));
120
175
  runner.use(pipes.ExtractState({
121
176
  from: "tokens",
122
177
  to: "tokenStates",
@@ -149,10 +204,27 @@ runner.use(pipes.VerifyTokenBalance({
149
204
  runner.use(pipes.ExtractState({
150
205
  from: "assets",
151
206
  to: "assetStates",
152
- status: "OK",
207
+ status: "INVALID_ASSET_STATE",
153
208
  table: "asset"
154
209
  }));
155
- runner.use(pipes.VerifyTransferrable({ assets: "assetStates" }));
210
+ runner.use(pipes.VerifyTransferrable({
211
+ assets: "assetStates",
212
+ allowConsumed: true
213
+ }));
214
+ runner.use(pipes.VerifyInfo([{
215
+ error: "UNTRANSFERRABLE_ASSET",
216
+ message: "Consumed assets can only be claimed back to the stake sender",
217
+ fn: (ctx) => {
218
+ const { outputs = [], assetStates = [], receiverStates = [], stakeState } = ctx;
219
+ const consumed = new Set(assetStates.filter((a) => a.consumedTime).map((a) => a.address));
220
+ if (consumed.size === 0) return true;
221
+ return outputs.every((o) => {
222
+ if (!(o.assets || o.assetsList || []).some((a) => consumed.has(a))) return true;
223
+ const rs = receiverStates.find((s) => getRelatedAddresses(s).includes(o.owner));
224
+ return !!rs && getRelatedAddresses(rs).includes(stakeState.sender);
225
+ });
226
+ }
227
+ }]));
156
228
  runner.use(pipes.VerifyUpdater({
157
229
  assetKey: "assetStates",
158
230
  ownerKey: "stakeState"
@@ -180,8 +252,10 @@ runner.use(async (context, next) => {
180
252
  outputs.forEach((x) => {
181
253
  const { owner, tokens, assets } = x;
182
254
  const ownerState = receiverStates.find((s) => getRelatedAddresses(s).includes(owner));
183
- receiverUpdates[ownerState.address] = applyTokenUpdates(tokens || [], ownerState, "add");
184
- if (senderChange && ownerState.address === senderChange.address) receiverUpdates[ownerState.address] = applyTokenChange(receiverUpdates[ownerState.address], senderChange);
255
+ const alreadyUpdated = Boolean(receiverUpdates[ownerState.address]);
256
+ const baseState = receiverUpdates[ownerState.address] || ownerState;
257
+ receiverUpdates[ownerState.address] = applyTokenUpdates(tokens || [], baseState, "add");
258
+ if (!alreadyUpdated && senderChange && ownerState.address === senderChange.address) receiverUpdates[ownerState.address] = applyTokenChange(receiverUpdates[ownerState.address], senderChange);
185
259
  (assets || []).forEach((a) => {
186
260
  assetUpdates[a] = { owner: ownerState.address };
187
261
  });
@@ -191,9 +265,17 @@ runner.use(async (context, next) => {
191
265
  const isAlsoSigner = !!receiverUpdates[senderState.address];
192
266
  const [newSenderState, newReceiverStates, newStakeState, newAssetStates, newEvidenceState] = await Promise.all([
193
267
  statedb.account.update(senderState.address, account.update(senderState, Object.assign({ nonce: tx$1.nonce }, receiverUpdates[senderState.address] || (senderChange ? applyTokenChange(senderState, senderChange) : {})), context), context),
194
- Promise.all(receiverStates.filter((x) => x.address !== senderState.address).map((x) => statedb.account.update(x.address, account.update(x, receiverUpdates[x.address], context), context))),
195
- statedb.stake.update(stakeState.address, stake.update(stakeState, stakeUpdates, context), context),
196
- Promise.all(assetStates.map((x) => statedb.asset.update(x.address, asset.update(x, assetUpdates[x.address], context), context))),
268
+ 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),
273
+ Promise.all(assetStates.map(async (x) => {
274
+ const nextOwner = assetUpdates[x.address]?.owner;
275
+ const updatedAsset = await statedb.asset.update(x.address, asset.update(x, assetUpdates[x.address], context), context);
276
+ if (nextOwner && token.isTokenCharterAsset(x)) await token.syncTokenCharterOwnership(x, nextOwner, statedb, context);
277
+ return updatedAsset;
278
+ })),
197
279
  statedb.evidence.create(itx.evidence.hash, evidence.create({
198
280
  hash: itx.evidence.hash,
199
281
  data: "claim-stake"
@@ -1,14 +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 { account, asset, stake } from "@ocap/state";
4
+ import { account, asset, stake, token } from "@ocap/state";
5
5
  import { Runner, pipes } from "@ocap/tx-pipeline";
6
6
  import { BN } from "@ocap/util";
7
7
  import { CustomError } from "@ocap/util/lib/error";
8
- import Debug from "debug";
9
8
  import { getListField } from "@ocap/util/lib/get-list-field";
10
- import { schemas, v, vDID, vStripUnknown, vValidate } from "@arcblock/validator";
11
9
  import { getRelatedAddresses } from "@ocap/util/lib/get-related-addr";
10
+ import Debug from "debug";
11
+ import { schemas, v, vDID, vStripUnknown, vValidate } from "@arcblock/validator";
12
+ import uniqBy from "lodash/uniqBy.js";
12
13
  import isEmpty from "lodash/isEmpty.js";
13
14
 
14
15
  //#region src/protocols/governance/return-stake.ts
@@ -61,7 +62,11 @@ runner.use(pipes.ExtractState({
61
62
  status: "INVALID_RECEIVER_STATE",
62
63
  table: "account"
63
64
  }));
64
- runner.use(pipes.VerifyBlocked({ stateKeys: ["receiverStates"] }));
65
+ runner.use(pipes.VerifyBlocked({ stateKeys: [
66
+ "senderState",
67
+ "delegatorState",
68
+ "receiverStates"
69
+ ] }));
65
70
  runner.use(pipes.VerifyAccountMigration({
66
71
  stateKey: "senderState",
67
72
  addressKey: "tx.from"
@@ -73,6 +78,14 @@ runner.use(pipes.ExtractState({
73
78
  table: "stake"
74
79
  }));
75
80
  runner.use(pipes.VerifyInfo([
81
+ {
82
+ error: "STAKE_NOT_REVOCABLE",
83
+ message: "This stake address is not revocable",
84
+ fn: (ctx) => {
85
+ const context = ctx;
86
+ return Boolean(context.stakeState.revocable);
87
+ }
88
+ },
76
89
  {
77
90
  error: "INVALID_TX",
78
91
  message: "Can only return from none-self staking",
@@ -146,7 +159,10 @@ runner.use(pipes.ExtractState({
146
159
  status: "INVALID_ASSET_STATE",
147
160
  table: "asset"
148
161
  }));
149
- runner.use(pipes.VerifyTransferrable({ assets: "assetStates" }));
162
+ runner.use(pipes.VerifyTransferrable({
163
+ assets: "assetStates",
164
+ allowConsumed: true
165
+ }));
150
166
  runner.use(pipes.VerifyUpdater({
151
167
  assetKey: "assetStates",
152
168
  ownerKey: "stakeState"
@@ -178,21 +194,37 @@ runner.use(async (context, next) => {
178
194
  stakeUpdates.assets = stakeUpdates.assets.filter((a) => assetsList.includes(a) === false);
179
195
  stakeUpdates.tokens = applyTokenUpdates(tokensList, { tokens: stakeUpdates.tokens }, "sub").tokens;
180
196
  const ownerState = receiverStates.find((s) => getRelatedAddresses(s).includes(owner));
181
- receiverUpdates[ownerState.address] = applyTokenUpdates(tokensList, ownerState, "add");
182
- if (senderChange && ownerState.address === senderChange.address) receiverUpdates[ownerState.address] = applyTokenChange(receiverUpdates[ownerState.address], senderChange);
197
+ const alreadyUpdated = Boolean(receiverUpdates[ownerState.address]);
198
+ const baseState = receiverUpdates[ownerState.address] || ownerState;
199
+ receiverUpdates[ownerState.address] = applyTokenUpdates(tokensList, baseState, "add");
200
+ if (!alreadyUpdated && senderChange && ownerState.address === senderChange.address) receiverUpdates[ownerState.address] = applyTokenChange(receiverUpdates[ownerState.address], senderChange);
183
201
  assetsList.forEach((a) => {
184
202
  assetUpdates[a] = { owner: ownerState.address };
185
203
  });
186
204
  });
205
+ const isAlsoSigner = !!receiverUpdates[senderState.address];
187
206
  const [newSenderState, newReceiverStates, newStakeState, newAssetStates] = await Promise.all([
188
- statedb.account.update(senderState.address, account.update(senderState, Object.assign({ nonce: tx$1.nonce }, senderChange ? applyTokenChange(senderState, senderChange) : {}), context), context),
189
- Promise.all(receiverStates.map((x) => statedb.account.update(x.address, account.update(x, receiverUpdates[x.address], context), context))),
190
- statedb.stake.update(stakeState.address, stake.update(stakeState, stakeUpdates, context), context),
191
- Promise.all(assetStates.map((x) => statedb.asset.update(x.address, asset.update(x, assetUpdates[x.address], context), context)))
207
+ statedb.account.update(senderState.address, account.update(senderState, Object.assign({ nonce: tx$1.nonce }, receiverUpdates[senderState.address] || (senderChange ? applyTokenChange(senderState, senderChange) : {})), context), context),
208
+ 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))),
209
+ (() => {
210
+ const hasPendingRevokedTokens = Object.values(stakeState.revokedTokens || {}).some((v$1) => new BN(String(v$1 || "0")).gt(new BN(0)));
211
+ const hasPendingRevokedAssets = Array.isArray(stakeState.revokedAssets) && stakeState.revokedAssets.length > 0;
212
+ const preserveRenaissanceTime = (hasPendingRevokedTokens || hasPendingRevokedAssets) && stakeState?.context?.renaissanceTime;
213
+ return statedb.stake.update(stakeState.address, stake.update(stakeState, stakeUpdates, preserveRenaissanceTime ? {
214
+ ...context,
215
+ txTime: preserveRenaissanceTime
216
+ } : context), context);
217
+ })(),
218
+ Promise.all(assetStates.map(async (x) => {
219
+ const nextOwner = assetUpdates[x.address]?.owner;
220
+ const updatedAsset = await statedb.asset.update(x.address, asset.update(x, assetUpdates[x.address], context), context);
221
+ if (nextOwner && token.isTokenCharterAsset(x)) await token.syncTokenCharterOwnership(x, nextOwner, statedb, context);
222
+ return updatedAsset;
223
+ }))
192
224
  ]);
193
225
  if (updateVaults) await updateVaults();
194
226
  context.senderState = newSenderState;
195
- context.receiverStates = newReceiverStates;
227
+ context.receiverStates = isAlsoSigner ? newReceiverStates.concat(newSenderState) : newReceiverStates;
196
228
  context.stakeState = newStakeState;
197
229
  context.assetStates = newAssetStates;
198
230
  debug("return-stake", {
@@ -5,10 +5,10 @@ import { account, stake } from "@ocap/state";
5
5
  import { Runner, pipes } from "@ocap/tx-pipeline";
6
6
  import { BN } from "@ocap/util";
7
7
  import { CustomError } from "@ocap/util/lib/error";
8
- import Debug from "debug";
9
8
  import { getListField } from "@ocap/util/lib/get-list-field";
10
- import { schemas, v, vDID, vStripUnknown, vValidate } from "@arcblock/validator";
11
9
  import { getRelatedAddresses } from "@ocap/util/lib/get-related-addr";
10
+ import Debug from "debug";
11
+ import { schemas, v, vDID, vStripUnknown, vValidate } from "@arcblock/validator";
12
12
  import isEmpty from "lodash/isEmpty.js";
13
13
 
14
14
  //#region src/protocols/governance/revoke-stake.ts
@@ -60,7 +60,11 @@ runner.use(pipes.ExtractState({
60
60
  status: "INVALID_RECEIVER_STATE",
61
61
  table: "account"
62
62
  }));
63
- runner.use(pipes.VerifyBlocked({ stateKeys: ["receiverStates"] }));
63
+ runner.use(pipes.VerifyBlocked({ stateKeys: [
64
+ "senderState",
65
+ "delegatorState",
66
+ "receiverStates"
67
+ ] }));
64
68
  runner.use(pipes.VerifyAccountMigration({
65
69
  stateKey: "senderState",
66
70
  addressKey: "tx.from"
@@ -127,7 +131,7 @@ runner.use(pipes.VerifyTokenBalance({
127
131
  runner.use(pipes.ExtractState({
128
132
  from: "assets",
129
133
  to: "assetStates",
130
- status: "OK",
134
+ status: "INVALID_ASSET_STATE",
131
135
  table: "asset"
132
136
  }));
133
137
  runner.use(pipes.VerifyTransferrable({ assets: "assetStates" }));
@@ -161,7 +165,15 @@ runner.use(async (context, next) => {
161
165
  const [newSenderState, newStakeState] = await Promise.all([statedb.account.update(senderState.address, account.update(senderState, {
162
166
  nonce: tx$1.nonce,
163
167
  ...senderUpdates
164
- }, context), context), statedb.stake.update(stakeState.address, stake.update(stakeState, stakeUpdates, context), context)]);
168
+ }, context), context), (() => {
169
+ const hasPendingRevokedTokens = Object.values(stakeState.revokedTokens || {}).some((v$1) => new BN(String(v$1 || "0")).gt(new BN(0)));
170
+ const hasPendingRevokedAssets = Array.isArray(stakeState.revokedAssets) && stakeState.revokedAssets.length > 0;
171
+ const preserveRenaissanceTime = (hasPendingRevokedTokens || hasPendingRevokedAssets) && stakeState.context?.renaissanceTime;
172
+ return statedb.stake.update(stakeState.address, stake.update(stakeState, stakeUpdates, preserveRenaissanceTime ? {
173
+ ...context,
174
+ txTime: preserveRenaissanceTime
175
+ } : context), context);
176
+ })()]);
165
177
  if (updateVaults) await updateVaults();
166
178
  context.senderState = newSenderState;
167
179
  context.stakeState = newStakeState;
@@ -1,14 +1,17 @@
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 } from "@ocap/state";
4
+ import { toTypeInfo } from "@arcblock/did";
5
+ import { types } from "@ocap/mcrypto";
6
+ import { account, asset, stake, token } from "@ocap/state";
5
7
  import { Runner, pipes } from "@ocap/tx-pipeline";
6
8
  import { BN } from "@ocap/util";
7
9
  import { CustomError } from "@ocap/util/lib/error";
8
- import Debug from "debug";
9
10
  import { getListField } from "@ocap/util/lib/get-list-field";
10
- import { schemas, v, vDID, vStripUnknown, vValidate } from "@arcblock/validator";
11
11
  import { getRelatedAddresses } from "@ocap/util/lib/get-related-addr";
12
+ import Debug from "debug";
13
+ import { schemas, v, vDID, vStripUnknown, vValidate } from "@arcblock/validator";
14
+ import uniqBy from "lodash/uniqBy.js";
12
15
  import isEmpty from "lodash/isEmpty.js";
13
16
 
14
17
  //#region src/protocols/governance/slash-stake.ts
@@ -61,7 +64,11 @@ runner.use(pipes.ExtractState({
61
64
  status: "INVALID_RECEIVER_STATE",
62
65
  table: "account"
63
66
  }));
64
- runner.use(pipes.VerifyBlocked({ stateKeys: ["receiverStates"] }));
67
+ runner.use(pipes.VerifyBlocked({ stateKeys: [
68
+ "senderState",
69
+ "delegatorState",
70
+ "receiverStates"
71
+ ] }));
65
72
  runner.use(pipes.VerifyAccountMigration({
66
73
  stateKey: "senderState",
67
74
  addressKey: "tx.from"
@@ -78,23 +85,39 @@ runner.use(pipes.ExtractState({
78
85
  status: "INVALID_SLASH_STATE",
79
86
  table: "account"
80
87
  }));
81
- runner.use(pipes.VerifyInfo([{
82
- error: "INVALID_TX",
83
- message: "You are not allowed to slash from this stake",
84
- fn: (ctx) => {
85
- const context = ctx;
86
- const slasherStates = context.slasherStates || [];
87
- return (isEmpty(slasherStates) ? [context.stakeState.receiver] : slasherStates.map((x) => x.address)).includes(context.senderState.address);
88
+ runner.use(pipes.VerifyInfo([
89
+ {
90
+ error: "INVALID_STAKE_STATE",
91
+ message: "Cannot slash permanently locked protocol token stake",
92
+ fn: (ctx) => {
93
+ const context = ctx;
94
+ if (!context.stakeState.revocable) {
95
+ const receiverRole = toTypeInfo(context.stakeState.receiver).role;
96
+ if (context.stakeState.receiver === context.config.token.address || receiverRole === types.RoleType.ROLE_TOKEN || receiverRole === types.RoleType.ROLE_TOKEN_FACTORY || receiverRole === types.RoleType.ROLE_ASSET) return false;
97
+ }
98
+ return true;
99
+ }
100
+ },
101
+ {
102
+ error: "INVALID_TX",
103
+ message: "You are not allowed to slash from this stake",
104
+ fn: (ctx) => {
105
+ const context = ctx;
106
+ const slasherStates = context.slasherStates || [];
107
+ const senderAddresses = getRelatedAddresses(context.senderState);
108
+ return (isEmpty(slasherStates) ? context.stakeState.revocable ? [context.stakeState.receiver] : [] : slasherStates.map((x) => x.address)).some((addr) => senderAddresses.includes(addr));
109
+ }
110
+ },
111
+ {
112
+ error: "INVALID_TX",
113
+ message: "Can only send slashed token/assets to vault or specified slasher",
114
+ fn: (ctx) => {
115
+ const context = ctx;
116
+ const slasherStates = context.slasherStates || [];
117
+ return (context.receivers || []).every((x) => x === context.config.vaults.slashedStake || slasherStates.some((s) => s.address === x));
118
+ }
88
119
  }
89
- }, {
90
- error: "INVALID_TX",
91
- message: "Can only send slashed token/assets to vault or specified slasher",
92
- fn: (ctx) => {
93
- const context = ctx;
94
- const slasherStates = context.slasherStates || [];
95
- return (context.receivers || []).every((x) => x === context.config.vaults.slashedStake || slasherStates.some((s) => s.address === x));
96
- }
97
- }]));
120
+ ]));
98
121
  runner.use(pipes.ExtractState({
99
122
  from: "tokens",
100
123
  to: "tokenStates",
@@ -183,17 +206,33 @@ runner.use(async (context, next) => {
183
206
  stakeUpdates.tokens = newTokens.tokens;
184
207
  stakeUpdates.revokedTokens = newRevoked.tokens;
185
208
  const ownerState = receiverStates.find((s) => getRelatedAddresses(s).includes(owner));
186
- receiverUpdates[ownerState.address] = applyTokenUpdates(tokensList, ownerState, "add");
187
- if (senderChange && ownerState.address === senderChange.address) receiverUpdates[ownerState.address] = applyTokenChange(receiverUpdates[ownerState.address], senderChange);
209
+ const alreadyUpdated = Boolean(receiverUpdates[ownerState.address]);
210
+ const baseState = receiverUpdates[ownerState.address] || ownerState;
211
+ receiverUpdates[ownerState.address] = applyTokenUpdates(tokensList, baseState, "add");
212
+ if (!alreadyUpdated && senderChange && ownerState.address === senderChange.address) receiverUpdates[ownerState.address] = applyTokenChange(receiverUpdates[ownerState.address], senderChange);
188
213
  assetsList.forEach((a) => {
189
214
  assetUpdates[a] = { owner: ownerState.address };
190
215
  });
191
216
  });
192
217
  const [newSenderState, newReceiverStates, newStakeState, newAssetStates] = await Promise.all([
193
218
  statedb.account.update(senderState.address, account.update(senderState, Object.assign({ nonce: tx$1.nonce }, receiverUpdates[senderState.address] || (senderChange ? applyTokenChange(senderState, senderChange) : {})), context), context),
194
- Promise.all(receiverStates.filter((x) => x.address !== senderState.address).map((x) => statedb.account.update(x.address, account.update(x, receiverUpdates[x.address], context), context))),
195
- statedb.stake.update(stakeState.address, stake.update(stakeState, stakeUpdates, context), context),
196
- Promise.all(assetStates.map((x) => statedb.asset.update(x.address, asset.update(x, assetUpdates[x.address], context), context)))
219
+ 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))),
220
+ (() => {
221
+ const prevRevoked = stakeState.revokedTokens || {};
222
+ const nextRevoked = stakeUpdates.revokedTokens || {};
223
+ 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
+ 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 ? {
226
+ ...context,
227
+ txTime: stakeState.context?.renaissanceTime || context.txTime
228
+ } : context), context);
229
+ })(),
230
+ Promise.all(assetStates.map(async (x) => {
231
+ const nextOwner = assetUpdates[x.address]?.owner;
232
+ const updatedAsset = await statedb.asset.update(x.address, asset.update(x, assetUpdates[x.address], context), context);
233
+ if (nextOwner && token.isTokenCharterAsset(x)) await token.syncTokenCharterOwnership(x, nextOwner, statedb, context);
234
+ return updatedAsset;
235
+ }))
197
236
  ]);
198
237
  if (updateVaults) await updateVaults();
199
238
  context.senderState = newSenderState;
@@ -1,16 +1,19 @@
1
- import { applyTokenChange, applyTokenUpdates, isGasStakeAddress, isGasStakeInput } from "../../util.mjs";
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 { account, asset, stake } from "@ocap/state";
4
+ import { toTypeInfo } from "@arcblock/did";
5
+ import { toStakeAddress } from "@arcblock/did-util";
6
+ import { types } from "@ocap/mcrypto";
7
+ import { account, asset, stake, token } from "@ocap/state";
5
8
  import { Runner, pipes } from "@ocap/tx-pipeline";
6
9
  import { BN, fromTokenToUnit } from "@ocap/util";
7
10
  import { CustomError } from "@ocap/util/lib/error";
11
+ import { getListField } from "@ocap/util/lib/get-list-field";
8
12
  import pick from "lodash/pick.js";
9
- import { toStakeAddress } from "@arcblock/did-util";
10
13
  import Debug from "debug";
11
- import { getListField } from "@ocap/util/lib/get-list-field";
12
14
  import { schemas, v, vDID, vStripUnknown, vValidate } from "@arcblock/validator";
13
15
  import { promisify } from "node:util";
16
+ import uniqBy from "lodash/uniqBy.js";
14
17
  import isEmpty from "lodash/isEmpty.js";
15
18
 
16
19
  //#region src/protocols/governance/stake.ts
@@ -70,6 +73,18 @@ runner.use(pipes.VerifyInfo([
70
73
  const context = ctx;
71
74
  return !(isEmpty(context.tokens) && isEmpty(context.assets));
72
75
  }
76
+ },
77
+ {
78
+ error: "INVALID_TX",
79
+ message: "Permanently locked token stake cannot have slashers",
80
+ fn: (ctx) => {
81
+ const context = ctx;
82
+ if (context.itx.locked) {
83
+ const receiverRole = toTypeInfo(context.itx.receiver).role;
84
+ if (context.itx.receiver === context.config.token.address || receiverRole === types.RoleType.ROLE_TOKEN || receiverRole === types.RoleType.ROLE_TOKEN_FACTORY || receiverRole === types.RoleType.ROLE_ASSET) return getListField(context.itx, "slashers").length === 0;
85
+ }
86
+ return true;
87
+ }
73
88
  }
74
89
  ]));
75
90
  runner.use(pipes.VerifyListSize({ listKey: [
@@ -107,7 +122,12 @@ runner.use(pipes.ExtractState({
107
122
  to: "receiverState",
108
123
  status: "INVALID_RECEIVER_STATE"
109
124
  }));
110
- runner.use(pipes.VerifyBlocked({ stateKeys: ["signerStates", "receiverState"] }));
125
+ runner.use(pipes.VerifyBlocked({ stateKeys: [
126
+ "senderState",
127
+ "delegatorState",
128
+ "signerStates",
129
+ "receiverState"
130
+ ] }));
111
131
  runner.use(pipes.VerifyAccountMigration({
112
132
  stateKey: "receiverState",
113
133
  addressKey: "itx.receiver"
@@ -131,16 +151,18 @@ runner.use(pipes.verifyTokenAccess({
131
151
  runner.use(pipes.ExtractState({
132
152
  from: "assets",
133
153
  to: "assetStates",
134
- status: "OK",
154
+ status: "INVALID_ASSET_STATE",
135
155
  table: "asset"
136
156
  }));
137
157
  runner.use(pipes.VerifyTransferrable({ assets: "assetStates" }));
138
158
  runner.use(async (context, next) => {
139
159
  const { inputs = [], assetStates = [], signerStates = [] } = context;
160
+ if (assetStates.some((x) => token.isTokenCharterAsset(x))) return next(new CustomError("INVALID_TX", "Token charter asset cannot be staked"));
140
161
  for (const input of inputs) {
141
162
  const { owner } = input;
142
163
  const assetsList = getListField(input, "assets");
143
164
  const states = assetStates.filter((x) => assetsList.includes(x.address));
165
+ if (states.length !== new Set(assetsList).size) return next(new CustomError("INVALID_ASSET_STATE", "Input asset does not exist on chain"));
144
166
  const signer = signerStates.find((x) => x.address === owner);
145
167
  try {
146
168
  await verifyAssetOwner({
@@ -168,14 +190,18 @@ runner.use((context, next) => {
168
190
  const { config } = context;
169
191
  const { token: token$1, transaction } = config;
170
192
  const { minStake, maxStake } = transaction.txGas;
171
- context.isGasStake = isGasStakeAddress(tx$1.from, itx.address) && isGasStakeInput(inputs, token$1.address);
193
+ const isGasAddress = isGasStakeAddress(tx$1.from, itx.address);
194
+ const isValidGasInput = isGasStakeInput(inputs, token$1.address);
195
+ if (isGasAddress && !isValidGasInput) return next(new CustomError("INVALID_TX", "Invalid input for gas stake"));
196
+ context.isGasStake = isGasAddress && isValidGasInput;
172
197
  if (context.isGasStake) {
173
198
  const [tokenInput] = getListField(inputs[0], "tokens");
174
199
  const actualStake = new BN(tokenInput.value);
200
+ const cumulativeStake = new BN(context.stakeState?.tokens?.[token$1.address] || 0).add(actualStake);
175
201
  const expectedMinStake = fromTokenToUnit(minStake, token$1.decimal);
176
202
  const expectedMaxStake = fromTokenToUnit(maxStake, token$1.decimal);
177
203
  if (actualStake.lt(expectedMinStake)) return next(new CustomError("INVALID_TX", `Stake for gas should be greater than: ${minStake}`));
178
- if (actualStake.gt(expectedMaxStake)) return next(new CustomError("INVALID_TX", `Stake for gas should be less than: ${maxStake}`));
204
+ if (cumulativeStake.gt(expectedMaxStake)) return next(new CustomError("INVALID_TX", `Stake for gas should be less than: ${maxStake}`));
179
205
  }
180
206
  if (context.isGasStake) {
181
207
  context.revokeWaitingPeriod = transaction.txGas.stakeLockPeriod;
@@ -192,7 +218,7 @@ runner.use(ensure_gas_default((context) => {
192
218
  update: 0,
193
219
  payment: 0
194
220
  };
195
- if ((context.senderState ? context.senderState.address : context.tx.from) === (context.receiverState ? context.receiverState.address : context.itx.receiver)) {
221
+ if (context.isGasStake) {
196
222
  Object.defineProperty(context, "txBaseGas", { value: false });
197
223
  return result;
198
224
  }
@@ -209,10 +235,26 @@ runner.use(pipes.TakeStateSnapshot());
209
235
  runner.use(async (context, next) => {
210
236
  const { tx: tx$1, itx, inputs = [], statedb, senderState, senderChange, stakeState, signerStates = [], updateVaults, assetStates = [] } = context;
211
237
  const signerUpdates = {};
238
+ const hasNonEmptyItxData = itx.data !== void 0 && itx.data !== null && Boolean(itx.data.typeUrl || itx.data.type || itx.data.value);
239
+ const hasProtectedStakeData = (() => {
240
+ if (!stakeState?.data) return false;
241
+ try {
242
+ const rawVal = decodeAnySafe(stakeState.data)?.value ?? stakeState.data.value;
243
+ if (!rawVal) return false;
244
+ const parsed = typeof rawVal === "string" ? JSON.parse(rawVal) : rawVal;
245
+ if (parsed && typeof parsed === "object") return [
246
+ "creditPool",
247
+ "cardReserve",
248
+ "distributorRebate",
249
+ "unmaturedRebate"
250
+ ].some((k) => k in parsed);
251
+ } catch {}
252
+ return false;
253
+ })();
212
254
  const stakeUpdates = stakeState ? {
213
255
  tokens: stakeState.tokens,
214
256
  assets: stakeState.assets || [],
215
- data: itx.data
257
+ ...stakeState.revocable && !hasProtectedStakeData && hasNonEmptyItxData ? { data: itx.data } : {}
216
258
  } : {
217
259
  tokens: {},
218
260
  assets: [],
@@ -232,10 +274,18 @@ runner.use(async (context, next) => {
232
274
  statedb.account.updateOrCreate(senderState ?? null, account.updateOrCreate(senderState ?? null, Object.assign({
233
275
  address: tx$1.from,
234
276
  nonce: tx$1.nonce,
235
- pk: tx$1.pk
277
+ pk: tx$1.delegator ? senderState?.pk || tx$1.pk : tx$1.pk
236
278
  }, signerUpdates[tx$1.from] || (senderChange ? applyTokenChange(senderState ?? {}, senderChange) : {})), context), context),
237
- Promise.all(signerStates.filter((x) => x.address !== tx$1.from).map((x) => statedb.account.update(x.address, account.update(x, signerUpdates[x.address], context), context))),
238
- stakeState ? statedb.stake.update(stakeState.address, stake.update(stakeState, stakeUpdates, context), context) : statedb.stake.create(itx.address, stake.create({
279
+ Promise.all(uniqBy(signerStates, "address").filter((x) => x.address !== tx$1.from).map((x) => statedb.account.update(x.address, account.update(x, signerUpdates[x.address], context), context))),
280
+ stakeState ? (() => {
281
+ const hasPendingRevokedTokens = Object.values(stakeState.revokedTokens || {}).some((v$1) => new BN(String(v$1 || "0")).gt(new BN(0)));
282
+ const hasPendingRevokedAssets = Array.isArray(stakeState.revokedAssets) && stakeState.revokedAssets.length > 0;
283
+ const preserveRenaissanceTime = (hasPendingRevokedTokens || hasPendingRevokedAssets) && stakeState?.context?.renaissanceTime;
284
+ return statedb.stake.update(stakeState.address, stake.update(stakeState, stakeUpdates, preserveRenaissanceTime ? {
285
+ ...context,
286
+ txTime: preserveRenaissanceTime
287
+ } : context), context);
288
+ })() : statedb.stake.create(itx.address, stake.create({
239
289
  sender: tx$1.from,
240
290
  revocable: !itx.locked,
241
291
  slashers: context.slashers,