@ocap/tx-protocols 1.30.26 → 1.31.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (122) hide show
  1. package/esm/execute.d.mts +11 -2
  2. package/esm/execute.mjs +724 -80
  3. package/esm/gas-security-guard.d.mts +375 -0
  4. package/esm/gas-security-guard.mjs +1103 -0
  5. package/esm/index.d.mts +36 -6
  6. package/esm/index.mjs +4 -2
  7. package/esm/pipes/ensure-cost.mjs +335 -59
  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 +115 -11
  29. package/esm/protocols/governance/return-stake.mjs +44 -12
  30. package/esm/protocols/governance/revoke-ledger.d.mts +34 -0
  31. package/esm/protocols/governance/revoke-ledger.mjs +179 -0
  32. package/esm/protocols/governance/revoke-stake.mjs +25 -5
  33. package/esm/protocols/governance/slash-stake.mjs +72 -25
  34. package/esm/protocols/governance/stake.mjs +63 -13
  35. package/esm/protocols/rollup/claim-reward.mjs +39 -20
  36. package/esm/protocols/rollup/close.mjs +1 -1
  37. package/esm/protocols/rollup/create-block.mjs +8 -7
  38. package/esm/protocols/rollup/create.mjs +17 -6
  39. package/esm/protocols/rollup/join.mjs +3 -3
  40. package/esm/protocols/rollup/leave.mjs +1 -1
  41. package/esm/protocols/rollup/migrate.mjs +7 -4
  42. package/esm/protocols/rollup/pipes/verify-evidence.mjs +12 -4
  43. package/esm/protocols/rollup/update.mjs +6 -1
  44. package/esm/protocols/token/create.mjs +23 -12
  45. package/esm/protocols/token/deposit-v2.d.mts +5 -1
  46. package/esm/protocols/token/deposit-v2.mjs +81 -29
  47. package/esm/protocols/token/withdraw-v2.mjs +33 -16
  48. package/esm/protocols/token-factory/burn.mjs +43 -10
  49. package/esm/protocols/token-factory/create.mjs +23 -14
  50. package/esm/protocols/token-factory/mint.mjs +54 -21
  51. package/esm/protocols/token-factory/pipes/verify-icon.mjs +1 -1
  52. package/esm/protocols/token-factory/update.mjs +16 -6
  53. package/esm/protocols/trade/exchange-v2.d.mts +4 -0
  54. package/esm/protocols/trade/exchange-v2.mjs +78 -22
  55. package/esm/protocols/trade/transfer-v2.mjs +44 -13
  56. package/esm/protocols/trade/transfer-v3.mjs +72 -31
  57. package/esm/util.d.mts +3 -1
  58. package/esm/util.mjs +26 -17
  59. package/lib/execute.cjs +724 -76
  60. package/lib/execute.d.cts +11 -2
  61. package/lib/gas-security-guard.cjs +1142 -0
  62. package/lib/gas-security-guard.d.cts +375 -0
  63. package/lib/index.cjs +124 -1
  64. package/lib/index.d.cts +37 -7
  65. package/lib/pipes/ensure-cost.cjs +334 -58
  66. package/lib/protocols/account/delegate.cjs +64 -16
  67. package/lib/protocols/account/migrate.cjs +235 -35
  68. package/lib/protocols/account/migrate.d.cts +3 -0
  69. package/lib/protocols/account/revoke-delegate.cjs +71 -39
  70. package/lib/protocols/account/revoke-delegate.d.cts +3 -3
  71. package/lib/protocols/asset/acquire-v2.cjs +28 -11
  72. package/lib/protocols/asset/acquire-v3.cjs +77 -20
  73. package/lib/protocols/asset/calls/transfer-token.cjs +3 -2
  74. package/lib/protocols/asset/calls/transfer.cjs +1 -0
  75. package/lib/protocols/asset/consume.cjs +11 -3
  76. package/lib/protocols/asset/create.cjs +19 -6
  77. package/lib/protocols/asset/mint.cjs +23 -1
  78. package/lib/protocols/asset/pipes/exec-mint-hook.cjs +117 -1
  79. package/lib/protocols/asset/pipes/exec-mint-hook.d.cts +21 -1
  80. package/lib/protocols/asset/pipes/extract-factory-tokens.cjs +14 -9
  81. package/lib/protocols/asset/pipes/verify-itx-address.cjs +9 -0
  82. package/lib/protocols/asset/pipes/verify-itx-assets.cjs +21 -5
  83. package/lib/protocols/asset/update.cjs +131 -12
  84. package/lib/protocols/asset/update.d.cts +13 -2
  85. package/lib/protocols/factory/create.cjs +14 -6
  86. package/lib/protocols/governance/claim-stake.cjs +115 -10
  87. package/lib/protocols/governance/claim-stake.d.cts +1 -1
  88. package/lib/protocols/governance/return-stake.cjs +44 -11
  89. package/lib/protocols/governance/return-stake.d.cts +1 -1
  90. package/lib/protocols/governance/revoke-ledger.cjs +184 -0
  91. package/lib/protocols/governance/revoke-ledger.d.cts +34 -0
  92. package/lib/protocols/governance/revoke-stake.cjs +25 -5
  93. package/lib/protocols/governance/revoke-stake.d.cts +1 -1
  94. package/lib/protocols/governance/slash-stake.cjs +72 -24
  95. package/lib/protocols/governance/slash-stake.d.cts +1 -1
  96. package/lib/protocols/governance/stake.cjs +65 -14
  97. package/lib/protocols/rollup/claim-reward.cjs +39 -20
  98. package/lib/protocols/rollup/close.cjs +1 -1
  99. package/lib/protocols/rollup/create-block.cjs +9 -8
  100. package/lib/protocols/rollup/create-block.d.cts +1 -1
  101. package/lib/protocols/rollup/create.cjs +18 -7
  102. package/lib/protocols/rollup/join.cjs +3 -3
  103. package/lib/protocols/rollup/leave.cjs +1 -1
  104. package/lib/protocols/rollup/migrate.cjs +7 -4
  105. package/lib/protocols/rollup/pipes/verify-evidence.cjs +11 -3
  106. package/lib/protocols/rollup/update.cjs +6 -1
  107. package/lib/protocols/token/create.cjs +24 -13
  108. package/lib/protocols/token/deposit-v2.cjs +80 -28
  109. package/lib/protocols/token/deposit-v2.d.cts +5 -1
  110. package/lib/protocols/token/withdraw-v2.cjs +32 -15
  111. package/lib/protocols/token-factory/burn.cjs +42 -9
  112. package/lib/protocols/token-factory/create.cjs +24 -15
  113. package/lib/protocols/token-factory/mint.cjs +53 -20
  114. package/lib/protocols/token-factory/pipes/verify-icon.cjs +1 -1
  115. package/lib/protocols/token-factory/update.cjs +16 -6
  116. package/lib/protocols/trade/exchange-v2.cjs +76 -20
  117. package/lib/protocols/trade/exchange-v2.d.cts +4 -0
  118. package/lib/protocols/trade/transfer-v2.cjs +45 -14
  119. package/lib/protocols/trade/transfer-v3.cjs +72 -30
  120. package/lib/util.cjs +26 -17
  121. package/lib/util.d.cts +4 -2
  122. package/package.json +16 -16
@@ -1,14 +1,18 @@
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 { slashStakeRevokes } from "./revoke-ledger.mjs";
5
+ import { toTypeInfo } from "@arcblock/did";
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 } from "@ocap/util";
7
10
  import { CustomError } from "@ocap/util/lib/error";
8
- import Debug from "debug";
9
11
  import { getListField } from "@ocap/util/lib/get-list-field";
10
- import { schemas, v, vDID, vStripUnknown, vValidate } from "@arcblock/validator";
11
12
  import { getRelatedAddresses } from "@ocap/util/lib/get-related-addr";
13
+ import Debug from "debug";
14
+ import { schemas, v, vDID, vStripUnknown, vValidate } from "@arcblock/validator";
15
+ import uniqBy from "lodash/uniqBy.js";
12
16
  import isEmpty from "lodash/isEmpty.js";
13
17
 
14
18
  //#region src/protocols/governance/slash-stake.ts
@@ -61,7 +65,11 @@ runner.use(pipes.ExtractState({
61
65
  status: "INVALID_RECEIVER_STATE",
62
66
  table: "account"
63
67
  }));
64
- runner.use(pipes.VerifyBlocked({ stateKeys: ["receiverStates"] }));
68
+ runner.use(pipes.VerifyBlocked({ stateKeys: [
69
+ "senderState",
70
+ "delegatorState",
71
+ "receiverStates"
72
+ ] }));
65
73
  runner.use(pipes.VerifyAccountMigration({
66
74
  stateKey: "senderState",
67
75
  addressKey: "tx.from"
@@ -78,23 +86,39 @@ runner.use(pipes.ExtractState({
78
86
  status: "INVALID_SLASH_STATE",
79
87
  table: "account"
80
88
  }));
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);
89
+ runner.use(pipes.VerifyInfo([
90
+ {
91
+ error: "INVALID_STAKE_STATE",
92
+ message: "Cannot slash permanently locked protocol token stake",
93
+ fn: (ctx) => {
94
+ const context = ctx;
95
+ if (!context.stakeState.revocable) {
96
+ const receiverRole = toTypeInfo(context.stakeState.receiver).role;
97
+ 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;
98
+ }
99
+ return true;
100
+ }
101
+ },
102
+ {
103
+ error: "INVALID_TX",
104
+ message: "You are not allowed to slash from this stake",
105
+ fn: (ctx) => {
106
+ const context = ctx;
107
+ const slasherStates = context.slasherStates || [];
108
+ const senderAddresses = getRelatedAddresses(context.senderState);
109
+ return (isEmpty(slasherStates) ? context.stakeState.revocable ? [context.stakeState.receiver] : [] : slasherStates.map((x) => x.address)).some((addr) => senderAddresses.includes(addr));
110
+ }
111
+ },
112
+ {
113
+ error: "INVALID_TX",
114
+ message: "Can only send slashed token/assets to vault or specified slasher",
115
+ fn: (ctx) => {
116
+ const context = ctx;
117
+ const slasherStates = context.slasherStates || [];
118
+ return (context.receivers || []).every((x) => x === context.config.vaults.slashedStake || slasherStates.some((s) => s.address === x));
119
+ }
88
120
  }
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
- }]));
121
+ ]));
98
122
  runner.use(pipes.ExtractState({
99
123
  from: "tokens",
100
124
  to: "tokenStates",
@@ -183,17 +207,40 @@ runner.use(async (context, next) => {
183
207
  stakeUpdates.tokens = newTokens.tokens;
184
208
  stakeUpdates.revokedTokens = newRevoked.tokens;
185
209
  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);
210
+ const alreadyUpdated = Boolean(receiverUpdates[ownerState.address]);
211
+ const baseState = receiverUpdates[ownerState.address] || ownerState;
212
+ receiverUpdates[ownerState.address] = applyTokenUpdates(tokensList, baseState, "add");
213
+ if (!alreadyUpdated && senderChange && ownerState.address === senderChange.address) receiverUpdates[ownerState.address] = applyTokenChange(receiverUpdates[ownerState.address], senderChange);
188
214
  assetsList.forEach((a) => {
189
215
  assetUpdates[a] = { owner: ownerState.address };
190
216
  });
191
217
  });
192
218
  const [newSenderState, newReceiverStates, newStakeState, newAssetStates] = await Promise.all([
193
219
  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)))
220
+ 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))),
221
+ (() => {
222
+ const prevRevoked = stakeState.revokedTokens || {};
223
+ const nextRevoked = stakeUpdates.revokedTokens || {};
224
+ const nextRevokes = slashStakeRevokes(stakeState, nextRevoked, stakeUpdates.revokedAssets || [], context.txTime);
225
+ const poolShrunk = Object.keys(prevRevoked).some((k) => new BN(prevRevoked[k] || "0").gt(new BN(nextRevoked[k] || "0"))) || (stakeUpdates.revokedAssets || []).length < (stakeState.revokedAssets || []).length;
226
+ const hasPending = Object.values(nextRevoked).some((v$1) => new BN(v$1 || "0").gt(new BN(0))) || (stakeUpdates.revokedAssets || []).length > 0;
227
+ return statedb.stake.update(stakeState.address, stake.update(stakeState, {
228
+ ...stakeUpdates,
229
+ context: {
230
+ ...stakeState.context,
231
+ revokes: nextRevokes
232
+ }
233
+ }, hasPending && !poolShrunk ? {
234
+ ...context,
235
+ txTime: stakeState.context?.renaissanceTime || context.txTime
236
+ } : context), context);
237
+ })(),
238
+ Promise.all(assetStates.map(async (x) => {
239
+ const nextOwner = assetUpdates[x.address]?.owner;
240
+ const updatedAsset = await statedb.asset.update(x.address, asset.update(x, assetUpdates[x.address], context), context);
241
+ if (nextOwner && token.isTokenCharterAsset(x)) await token.syncTokenCharterOwnership(x, nextOwner, statedb, context);
242
+ return updatedAsset;
243
+ }))
197
244
  ]);
198
245
  if (updateVaults) await updateVaults();
199
246
  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,
@@ -4,13 +4,13 @@ import ensure_gas_default from "../../pipes/ensure-gas.mjs";
4
4
  import ensure_validator_default from "./pipes/ensure-validator.mjs";
5
5
  import verify_signers_default from "./pipes/verify-signers.mjs";
6
6
  import verify_status_default from "./pipes/verify-status.mjs";
7
- import { account, evidence, rollupBlock, stake } from "@ocap/state";
7
+ import { toStakeAddress } from "@arcblock/did-util";
8
+ import { account, evidence, rollup, rollupBlock, stake } from "@ocap/state";
8
9
  import { Runner, pipes } from "@ocap/tx-pipeline";
9
10
  import { BN } from "@ocap/util";
10
11
  import { CustomError } from "@ocap/util/lib/error";
11
- import { toStakeAddress } from "@arcblock/did-util";
12
- import Debug from "debug";
13
12
  import cloneDeep from "lodash/cloneDeep.js";
13
+ import Debug from "debug";
14
14
  import groupBy from "lodash/groupBy.js";
15
15
  import { patterns, v, vDID, vStripUnknown, vValidate } from "@arcblock/validator";
16
16
  import uniqBy from "lodash/uniqBy.js";
@@ -26,10 +26,7 @@ const schema = v.pipe(v.object({
26
26
  blockHeight: v.pipe(v.number(), v.integer(), v.check((n) => n > 0, "Must be > 0")),
27
27
  blockHash: v.pipe(v.string(), v.regex(patterns.txHash)),
28
28
  evidence: v.object({ hash: v.pipe(v.string(), v.regex(patterns.txHash)) }),
29
- publisher: vDID({
30
- prefix: true,
31
- wallet: "ethereum"
32
- }),
29
+ publisher: vDID({ prefix: true }),
33
30
  data: v.optional(v.nullable(v.any()))
34
31
  }), vStripUnknown());
35
32
  runner.use((context, next) => {
@@ -63,6 +60,14 @@ runner.use(pipes.ExtractState({
63
60
  status: "INVALID_ROLLUP",
64
61
  table: "rollup"
65
62
  }));
63
+ runner.use((context, next) => {
64
+ const { itx, rollupState } = context;
65
+ if (rollup.getRollupTargetType(rollupState) === "EVM" && vValidate(vDID({
66
+ prefix: true,
67
+ wallet: "ethereum"
68
+ }), itx.publisher).error) return next(new CustomError("INVALID_TX", "\"publisher\" Expected wallet type to be \"ethereum\""));
69
+ return next();
70
+ });
66
71
  runner.use(ensure_validator_default(false));
67
72
  runner.use(verify_status_default({ closed: false }));
68
73
  runner.use(pipes.ExtractState({
@@ -146,23 +151,27 @@ runner.use((context, next) => {
146
151
  const slashShare = slashAmount.div(new BN(2));
147
152
  changes.stake.push({
148
153
  address: stakeState.address,
154
+ token: tokenState.address,
149
155
  delta: `-${slashAmount.toString(10)}`,
150
156
  action: "slash"
151
157
  });
152
158
  changes.stake.push({
153
159
  address: lockerState.address,
160
+ token: tokenState.address,
154
161
  delta: slashShare.toString(10),
155
162
  action: "slash"
156
163
  });
157
164
  changes.account.push({
158
165
  address: itx.publisher,
166
+ token: tokenState.address,
159
167
  delta: slashShare.toString(10),
160
168
  action: "reward"
161
169
  });
162
170
  }
163
171
  (txs || []).forEach((x) => {
164
172
  const txData = x.tx;
165
- const { actualFee } = txData.itxJson;
173
+ const { actualFee, token: txTokenObj } = txData.itxJson;
174
+ const txToken = txTokenObj?.address || tokenState.address;
166
175
  const { publisher, proposer, validator } = splitTxFee({
167
176
  total: actualFee,
168
177
  shares,
@@ -170,11 +179,13 @@ runner.use((context, next) => {
170
179
  });
171
180
  changes.stake.push({
172
181
  address: lockerState.address,
182
+ token: txToken,
173
183
  delta: `-${actualFee}`,
174
184
  action: "claim"
175
185
  });
176
186
  changes.account.push({
177
187
  address: itx.publisher,
188
+ token: txToken,
178
189
  delta: publisher.toString(10),
179
190
  action: "fee"
180
191
  });
@@ -182,6 +193,7 @@ runner.use((context, next) => {
182
193
  const txItxJson = txData.itxJson;
183
194
  changes.account.push({
184
195
  address: txItxJson.proposer,
196
+ token: txToken,
185
197
  delta: proposer.toString(10),
186
198
  action: "fee"
187
199
  });
@@ -191,12 +203,14 @@ runner.use((context, next) => {
191
203
  const validatorShare = validator.div(new BN(validators.length));
192
204
  validators.forEach((v$1) => changes.account.push({
193
205
  address: v$1,
206
+ token: txToken,
194
207
  delta: validatorShare.toString(10),
195
208
  action: "fee"
196
209
  }));
197
210
  } else if (x.type === "withdraw_token_v2") {
198
211
  changes.account.push({
199
212
  address: blockState.proposer,
213
+ token: txToken,
200
214
  delta: proposer.toString(10),
201
215
  action: "fee"
202
216
  });
@@ -212,6 +226,7 @@ runner.use((context, next) => {
212
226
  });
213
227
  Object.keys(validatorShares).forEach((v$1) => changes.account.push({
214
228
  address: v$1,
229
+ token: txToken,
215
230
  delta: validatorShares[v$1],
216
231
  action: "fee"
217
232
  }));
@@ -221,23 +236,27 @@ runner.use((context, next) => {
221
236
  account: groupBy(changes.account, "address"),
222
237
  stake: groupBy(changes.stake, "address")
223
238
  };
239
+ const aggregateChanges = (items, addr) => {
240
+ const byToken = groupBy(items, (c) => c.token || tokenState.address);
241
+ const perToken = Object.keys(byToken).map((tok) => ({
242
+ address: addr,
243
+ token: tok,
244
+ delta: getBNSum(...byToken[tok].map((c) => c.delta)),
245
+ action: byToken[tok][byToken[tok].length - 1].action
246
+ }));
247
+ if (perToken.length === 1) return perToken[0];
248
+ return {
249
+ ...perToken[perToken.length - 1],
250
+ changes: perToken
251
+ };
252
+ };
224
253
  const updates = {
225
254
  stake: Object.keys(grouped.stake).reduce((acc, x) => {
226
- acc[x] = {
227
- address: x,
228
- token: tokenState.address,
229
- delta: getBNSum(...grouped.stake[x].map((c) => c.delta)),
230
- action: grouped.stake[x][grouped.stake[x].length - 1].action
231
- };
255
+ acc[x] = aggregateChanges(grouped.stake[x], x);
232
256
  return acc;
233
257
  }, {}),
234
258
  account: Object.keys(grouped.account).reduce((acc, x) => {
235
- acc[x] = {
236
- address: x,
237
- token: tokenState.address,
238
- delta: getBNSum(...grouped.account[x].map((c) => c.delta)),
239
- action: grouped.account[x][grouped.account[x].length - 1].action
240
- };
259
+ acc[x] = aggregateChanges(grouped.account[x], x);
241
260
  return acc;
242
261
  }, {})
243
262
  };
@@ -3,10 +3,10 @@ import ensure_gas_default from "../../pipes/ensure-gas.mjs";
3
3
  import ensure_validator_default from "./pipes/ensure-validator.mjs";
4
4
  import verify_signers_default from "./pipes/verify-signers.mjs";
5
5
  import verify_status_default from "./pipes/verify-status.mjs";
6
+ import { toStakeAddress } from "@arcblock/did-util";
6
7
  import { account, rollup, stake } from "@ocap/state";
7
8
  import { Runner, pipes } from "@ocap/tx-pipeline";
8
9
  import { CustomError } from "@ocap/util/lib/error";
9
- import { toStakeAddress } from "@arcblock/did-util";
10
10
  import { v, vBN, vBNPositive, vDID, vStripUnknown, vValidate } from "@arcblock/validator";
11
11
 
12
12
  //#region src/protocols/rollup/close.ts
@@ -5,15 +5,15 @@ import ensure_validator_default from "./pipes/ensure-validator.mjs";
5
5
  import verify_signers_default from "./pipes/verify-signers.mjs";
6
6
  import verify_status_default from "./pipes/verify-status.mjs";
7
7
  import verify_evidence_default from "./pipes/verify-evidence.mjs";
8
+ import { toStakeAddress } from "@arcblock/did-util";
8
9
  import { account, rollup, rollupBlock, stake, tx } from "@ocap/state";
9
10
  import { Runner, pipes } from "@ocap/tx-pipeline";
10
11
  import { CustomError } from "@ocap/util/lib/error";
12
+ import { getListField } from "@ocap/util/lib/get-list-field";
13
+ import cloneDeep from "lodash/cloneDeep.js";
11
14
  import pick from "lodash/pick.js";
12
- import { toStakeAddress } from "@arcblock/did-util";
13
15
  import Debug from "debug";
14
16
  import { formatMessage } from "@ocap/message";
15
- import { getListField } from "@ocap/util/lib/get-list-field";
16
- import cloneDeep from "lodash/cloneDeep.js";
17
17
  import { patterns, schemas, v, vBN, vBNMin, vDID, vStripUnknown, vValidate } from "@arcblock/validator";
18
18
  import MerkleTree from "@ocap/merkle-tree";
19
19
 
@@ -28,10 +28,7 @@ const schema = v.pipe(v.object({
28
28
  previousHash: v.optional(v.nullable(v.string())),
29
29
  txsHash: txHashString,
30
30
  txsList: v.pipe(v.array(txHashString), v.minLength(1)),
31
- proposer: vDID({
32
- prefix: true,
33
- wallet: "ethereum"
34
- }),
31
+ proposer: vDID({ prefix: true }),
35
32
  signaturesList: v.pipe(schemas.multiSig, v.minLength(1)),
36
33
  rollup: vDID({
37
34
  prefix: true,
@@ -73,6 +70,10 @@ runner.use(ensure_validator_default(false));
73
70
  runner.use(verify_status_default({ closed: false }));
74
71
  runner.use((context, next) => {
75
72
  const { itx, rollupState } = context;
73
+ if (rollup.getRollupTargetType(rollupState) === "EVM" && vValidate(vDID({
74
+ prefix: true,
75
+ wallet: "ethereum"
76
+ }), itx.proposer).error) return next(new CustomError("INVALID_TX", "\"proposer\" Expected wallet type to be \"ethereum\""));
76
77
  if (itx.height !== (rollupState?.blockHeight || 0) + 1) return next(new CustomError("INVALID_TX", `Expect new block height to be ${(rollupState?.blockHeight || 0) + 1}, got ${itx.height}`));
77
78
  const itxTxsList = getListField(itx, "txs");
78
79
  if (itx.governance) {
@@ -1,15 +1,15 @@
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 { isEthereumDid, isFromPublicKey } from "@arcblock/did";
5
+ import { toRollupAddress } from "@arcblock/did-util";
4
6
  import { account, delegation, rollup } from "@ocap/state";
5
7
  import { Runner, pipes } from "@ocap/tx-pipeline";
6
8
  import { CustomError } from "@ocap/util/lib/error";
7
- import { isEthereumDid, isFromPublicKey } from "@arcblock/did";
8
- import { toRollupAddress } from "@arcblock/did-util";
9
- import Debug from "debug";
10
- import { formatMessage } from "@ocap/message";
11
9
  import { getListField } from "@ocap/util/lib/get-list-field";
12
10
  import cloneDeep from "lodash/cloneDeep.js";
11
+ import Debug from "debug";
12
+ import { formatMessage } from "@ocap/message";
13
13
  import isEmpty from "lodash/isEmpty.js";
14
14
 
15
15
  //#region src/protocols/rollup/create.ts
@@ -19,8 +19,13 @@ runner.use(pipes.VerifyMultiSig(0));
19
19
  runner.use((context, next) => {
20
20
  const { itx } = context;
21
21
  context.formattedItx = formatMessage("CreateRollupTx", itx);
22
+ const decodedData = decodeAnySafe(itx.data ?? null);
23
+ context.rollupData = decodedData;
22
24
  try {
23
- rollup.create(context.formattedItx, context);
25
+ rollup.create({
26
+ ...context.formattedItx,
27
+ data: decodedData
28
+ }, context);
24
29
  } catch (err) {
25
30
  return next(new CustomError("INVALID_TX", err.message));
26
31
  }
@@ -46,7 +51,13 @@ runner.use(pipes.VerifyInfo([
46
51
  error: "INVALID_TX",
47
52
  message: "Seed validator must use ethereum compatible address",
48
53
  fn: (ctx) => {
49
- return (ctx.formattedItx?.seedValidators || []).every(({ address }) => isEthereumDid(address));
54
+ const context = ctx;
55
+ const targetType = rollup.getRollupTargetType({
56
+ ...context.formattedItx,
57
+ data: context.rollupData
58
+ });
59
+ const seedValidators = context.formattedItx?.seedValidators || [];
60
+ return targetType === "EVM" ? seedValidators.every(({ address }) => isEthereumDid(address)) : true;
50
61
  }
51
62
  },
52
63
  {
@@ -5,12 +5,12 @@ import verify_signers_default from "./pipes/verify-signers.mjs";
5
5
  import verify_status_default from "./pipes/verify-status.mjs";
6
6
  import verify_evidence_default from "./pipes/verify-evidence.mjs";
7
7
  import { any, check, minLength, nullable, object, optional, pipe, regex, string } from "../../node_modules/valibot/dist/index.mjs";
8
+ import { isEthereumDid } from "@arcblock/did";
9
+ import { toStakeAddress } from "@arcblock/did-util";
8
10
  import { account, evidence, rollup, stake } from "@ocap/state";
9
11
  import { Runner, pipes } from "@ocap/tx-pipeline";
10
12
  import { BN, toHex } from "@ocap/util";
11
13
  import { CustomError } from "@ocap/util/lib/error";
12
- import { isEthereumDid } from "@arcblock/did";
13
- import { toStakeAddress } from "@arcblock/did-util";
14
14
  import Debug from "debug";
15
15
  import { patterns, schemas, vDID, vStripUnknown, vValidate } from "@arcblock/validator";
16
16
  import MerkleTree from "@ocap/merkle-tree";
@@ -47,7 +47,7 @@ runner.use((context, next) => {
47
47
  address: tx$1.from,
48
48
  endpoint: itx.endpoint
49
49
  };
50
- if (isEthereumDid(tx$1.from) === false) return next(new CustomError("INVALID_TX", "Invalid tx.from: only ethereum compatible address can join rollup"));
50
+ if (rollup.getRollupTargetType(rollupState) === "EVM" && isEthereumDid(tx$1.from) === false) return next(new CustomError("INVALID_TX", "Invalid tx.from: only ethereum compatible address can join rollup"));
51
51
  if (rollupState?.validators.some((x) => x.address === validator.address)) return next(new CustomError("INVALID_TX", `Address ${validator.address} already exist in validators`));
52
52
  if (rollupState?.validators.some((x) => joinUrl(x.endpoint, "/") === joinUrl(validator.endpoint, "/"))) return next(new CustomError("INVALID_TX", `Endpoint ${validator.endpoint} already exist in validators`));
53
53
  context.newValidator = validator;
@@ -5,10 +5,10 @@ import verify_signers_default from "./pipes/verify-signers.mjs";
5
5
  import verify_status_default from "./pipes/verify-status.mjs";
6
6
  import verify_evidence_default from "./pipes/verify-evidence.mjs";
7
7
  import { any, minLength, nullable, object, optional, pipe, regex, string } from "../../node_modules/valibot/dist/index.mjs";
8
+ import { toStakeAddress } from "@arcblock/did-util";
8
9
  import { account, evidence, rollup, stake } from "@ocap/state";
9
10
  import { Runner, pipes } from "@ocap/tx-pipeline";
10
11
  import { CustomError } from "@ocap/util/lib/error";
11
- import { toStakeAddress } from "@arcblock/did-util";
12
12
  import Debug from "debug";
13
13
  import { patterns, schemas, vDID, vStripUnknown, vValidate } from "@arcblock/validator";
14
14
  import MerkleTree from "@ocap/merkle-tree";
@@ -15,10 +15,7 @@ const schema = v.pipe(v.object({
15
15
  prefix: true,
16
16
  role: "ROLE_ROLLUP"
17
17
  }),
18
- to: vDID({
19
- prefix: true,
20
- wallet: "ethereum"
21
- }),
18
+ to: v.pipe(v.string(), v.minLength(1)),
22
19
  type: v.pipe(v.string(), v.trim(), v.check((s) => s === "vault" || s === "contract", "Must be vault or contract")),
23
20
  message: v.pipe(v.string(), v.trim(), v.minLength(1), v.maxLength(512)),
24
21
  data: v.optional(v.nullable(v.any()))
@@ -33,6 +30,12 @@ runner.use(pipes.ExtractState({
33
30
  status: "INVALID_ROLLUP",
34
31
  table: "rollup"
35
32
  }));
33
+ runner.use((context, next) => {
34
+ const { itx, rollupState } = context;
35
+ const targetType = rollup.getRollupTargetType(rollupState);
36
+ if (!(itx.type === "vault" ? Boolean(itx.to) && rollup.isValidRollupVaultAddress(itx.to, targetType) : rollup.isValidRollupContractAddress(itx.to, targetType))) return next(new CustomError("INVALID_TX", "Invalid itx: \"to\" Expected wallet type to be \"ethereum\""));
37
+ return next();
38
+ });
36
39
  runner.use(ensure_validator_default(true));
37
40
  runner.use(verify_status_default({
38
41
  paused: true,
@@ -1,24 +1,32 @@
1
+ import { isEthereumDid, isFromPublicKey, toTypeInfo } from "@arcblock/did";
2
+ import { rollup } from "@ocap/state";
1
3
  import { toHex } from "@ocap/util";
2
4
  import { CustomError } from "@ocap/util/lib/error";
3
- import get from "lodash/get.js";
4
- import { toTypeInfo } from "@arcblock/did";
5
5
  import { getListField } from "@ocap/util/lib/get-list-field";
6
+ import get from "lodash/get.js";
6
7
  import { fromPublicKey as fromPublicKey$1 } from "@ocap/wallet";
7
8
 
8
9
  //#region src/protocols/rollup/pipes/verify-evidence.ts
9
10
  function CreateVerifyEvidencePipe({ evidenceKey, signaturesKey, verifyMethod = "verify" }) {
10
11
  if (["verify", "ethVerify"].includes(verifyMethod) === false) throw new CustomError("INVALID_ARGUMENT", `Invalid verify method: ${verifyMethod}, supported methods are: verify, ethVerify`);
11
12
  return async (context, next) => {
12
- const evidence = get(context, evidenceKey);
13
+ const evidence$1 = get(context, evidenceKey);
13
14
  const signatures = getListField(context, signaturesKey);
14
15
  const signers = signatures.map((s) => s.signer);
15
16
  if (new Set(signers).size !== signers.length) return next(new CustomError("INVALID_SIGNATURE", `Duplicate signers in ${signaturesKey} are not allowed`));
16
17
  for (const sig of signatures) {
17
18
  const { signer, pk, delegator, signature } = sig;
18
19
  const address = delegator || signer;
20
+ if (isFromPublicKey(address, pk) === false) return next(new CustomError("INVALID_SIGNATURE", `Signature for evidence signer ${address} and pk do not match`));
19
21
  const wallet = fromPublicKey$1(pk, toTypeInfo(address));
20
22
  try {
21
- if (await wallet[verifyMethod](toHex(evidence), toHex(signature)) === false) return next(new CustomError("INVALID_SIGNATURE", `Signature for evidence from ${address} is not valid`));
23
+ const targetType = rollup.getRollupTargetType(context.rollupState);
24
+ const effectiveMethod = verifyMethod === "ethVerify" && targetType !== "EVM" && !isEthereumDid(address) ? "verify" : verifyMethod;
25
+ const hexEvidence = toHex(evidence$1);
26
+ const hexSig = toHex(signature);
27
+ let verified = await wallet[effectiveMethod](hexEvidence, hexSig);
28
+ if (!verified && verifyMethod === "ethVerify" && targetType !== "EVM" && isEthereumDid(address)) verified = await wallet.verify(hexEvidence, hexSig);
29
+ if (verified === false) return next(new CustomError("INVALID_SIGNATURE", `Signature for evidence from ${address} is not valid`));
22
30
  } catch (err) {
23
31
  return next(new CustomError("INVALID_SIGNATURE", `Signature for evidence from ${address} verify failed: ${err.message}`));
24
32
  }