@ocap/tx-protocols 1.31.4 → 1.31.6

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 (41) hide show
  1. package/esm/bridge-release-crypto.mjs +1 -1
  2. package/esm/execute.mjs +24 -5
  3. package/esm/gas-security-guard.d.mts +2 -8
  4. package/esm/gas-security-guard.mjs +16 -1
  5. package/esm/index.d.mts +16 -3
  6. package/esm/index.mjs +0 -2
  7. package/esm/pipes/ensure-cost.mjs +3 -0
  8. package/esm/pipes/ensure-gas.d.mts +2 -1
  9. package/esm/pipes/write-ledger.mjs +2 -1
  10. package/esm/protocols/bridge/release-checks.d.mts +69 -0
  11. package/esm/protocols/bridge/{release.mjs → release-checks.mjs} +101 -100
  12. package/esm/protocols/rollup/bridge-create.mjs +2 -2
  13. package/esm/protocols/rollup/bridge-membership.mjs +10 -12
  14. package/esm/protocols/rollup/bridge-v2.d.mts +15 -5
  15. package/esm/protocols/rollup/bridge-v2.mjs +33 -8
  16. package/esm/protocols/token/deposit-v2.mjs +126 -25
  17. package/esm/protocols/token/withdraw-v2.d.mts +13 -1
  18. package/esm/protocols/token/withdraw-v2.mjs +158 -25
  19. package/esm/protocols/trade/transfer-v2.mjs +3 -8
  20. package/lib/bridge-release-crypto.cjs +1 -1
  21. package/lib/execute.cjs +24 -5
  22. package/lib/gas-security-guard.cjs +16 -1
  23. package/lib/gas-security-guard.d.cts +2 -8
  24. package/lib/index.cjs +0 -2
  25. package/lib/index.d.cts +16 -3
  26. package/lib/pipes/ensure-cost.cjs +3 -0
  27. package/lib/pipes/ensure-gas.d.cts +2 -1
  28. package/lib/pipes/write-ledger.cjs +2 -1
  29. package/lib/protocols/bridge/{release.cjs → release-checks.cjs} +115 -101
  30. package/lib/protocols/bridge/release-checks.d.cts +69 -0
  31. package/lib/protocols/rollup/bridge-create.cjs +1 -1
  32. package/lib/protocols/rollup/bridge-membership.cjs +9 -10
  33. package/lib/protocols/rollup/bridge-v2.cjs +32 -5
  34. package/lib/protocols/rollup/bridge-v2.d.cts +15 -5
  35. package/lib/protocols/token/deposit-v2.cjs +125 -24
  36. package/lib/protocols/token/withdraw-v2.cjs +155 -22
  37. package/lib/protocols/token/withdraw-v2.d.cts +13 -1
  38. package/lib/protocols/trade/transfer-v2.cjs +2 -7
  39. package/package.json +16 -16
  40. package/esm/protocols/bridge/release.d.mts +0 -34
  41. package/lib/protocols/bridge/release.d.cts +0 -34
@@ -1,9 +1,10 @@
1
1
  import { applyTokenChange, applyTokenUpdates, getBNSum, getRewardLocker, getTxFee } from "../../util.mjs";
2
2
  import ensure_cost_default from "../../pipes/ensure-cost.mjs";
3
3
  import ensure_gas_default from "../../pipes/ensure-gas.mjs";
4
- import { rejectBridgeV2 } from "../rollup/bridge-v2.mjs";
4
+ import { ifV1, ifV2, peekBridgeFailClosed, rejectBridgeV2 } from "../rollup/bridge-v2.mjs";
5
5
  import verify_signers_default from "../rollup/pipes/verify-signers.mjs";
6
6
  import verify_status_default from "../rollup/pipes/verify-status.mjs";
7
+ import { checkReleaseCap, checkReleaseFields, checkReleaseMinimum, checkReleaseRecipient, checkReleaseRecipientState, checkReleaseRefund, checkReleaseReserve, checkReleaseTombstone, rejectReleaseDelegator, releaseGasEstimate, resolveReleaseBridge, resolveReleaseTime, verifyReleaseClaim, verifyReleaseSignatures, writeRelease } from "../bridge/release-checks.mjs";
7
8
  import { Runner, pipes } from "@ocap/tx-pipeline";
8
9
  import { CustomError } from "@ocap/util/lib/error";
9
10
  import { getListField } from "@ocap/util/lib/get-list-field";
@@ -11,6 +12,7 @@ import { toStakeAddress } from "@arcblock/did-util";
11
12
  import { account, evidence, rollup, stake } from "@ocap/state";
12
13
  import { BN, fromUnitToToken } from "@ocap/util";
13
14
  import Debug from "debug";
15
+ import { findNonDefaultDepositV2BridgeFields } from "@ocap/util/lib/deposit-v2-bridge-fields";
14
16
  import { patterns, schemas, v, vBN, vBNMin, vDID, vStripUnknown, vValidate } from "@arcblock/validator";
15
17
 
16
18
  //#region src/protocols/token/deposit-v2.ts
@@ -27,20 +29,70 @@ const schema = v.pipe(v.object({
27
29
  actualFee: vBN(vBNMin(0)),
28
30
  data: v.optional(v.nullable(v.any()))
29
31
  }), vStripUnknown());
32
+ /**
33
+ * itx shape of the bridge branch (#1692 §2.2, §2.5). The release fields map onto the deposit fields: `rollup` is the bridge
34
+ * (canonical spelling, checked against the stored row), `token.value` the amount, `evidence.hash` the evidence (lowercase
35
+ * `0x` only: the tombstone key is derived from the exact spelling), `validatorSignatures` the OcapRelease signatures.
36
+ * `proposer` must be empty, `actualFee` empty or `'0'`, `data` empty (checked next to the schema).
37
+ */
38
+ const bridgeSchema = v.pipe(v.object({
39
+ kind: v.picklist([
40
+ 1,
41
+ 2,
42
+ 3
43
+ ]),
44
+ rollup: v.pipe(v.string(), v.minLength(1), v.maxLength(128)),
45
+ evidence: v.object({ hash: v.pipe(v.string(), v.regex(/^0x[0-9a-f]{64}$/)) }),
46
+ ordinal: v.pipe(v.number(), v.integer(), v.minValue(0)),
47
+ to: schemas.tokenHolder,
48
+ token: v.object({
49
+ address: v.pipe(v.string(), v.minLength(1), v.maxLength(128)),
50
+ value: v.pipe(v.string(), v.regex(/^[1-9]\d{0,77}$/))
51
+ }),
52
+ epoch: v.pipe(v.number(), v.integer(), v.minValue(0), v.maxValue(Number.MAX_SAFE_INTEGER)),
53
+ ethSender: v.optional(v.string(), ""),
54
+ claimSignature: v.optional(v.string(), ""),
55
+ proposer: v.optional(v.nullable(v.literal("")), ""),
56
+ actualFee: v.optional(v.nullable(v.union([v.literal(""), v.literal("0")])), ""),
57
+ data: v.optional(v.nullable(v.any()))
58
+ }), vStripUnknown());
59
+ /** An absent or empty `google.protobuf.Any` (jspb decodes an unset `data` as undefined, CBOR may leave it out). */
60
+ const isEmptyAny = (value) => {
61
+ if (value === void 0 || value === null || value === "") return true;
62
+ if (typeof value !== "object") return false;
63
+ const { typeUrl, type, value: inner, ...rest } = value;
64
+ const empty = (x) => x === void 0 || x === null || x === "" || (x instanceof Uint8Array || Array.isArray(x)) && x.length === 0;
65
+ return empty(typeUrl) && empty(type) && empty(inner) && Object.keys(rest).length === 0;
66
+ };
30
67
  const runner = new Runner("deposit_token_v2");
31
- runner.use(({ itx }, next) => {
68
+ runner.use(peekBridgeFailClosed("deposit_token_v2", "PeekDepositBridge"));
69
+ /** The guarded pipe keeps the name of the pipe it wraps (structural tests and debugging find pipes by name). */
70
+ const named = (guarded, pipe) => Object.defineProperty(guarded, "name", {
71
+ value: pipe.name,
72
+ configurable: true
73
+ });
74
+ /** Add a pipe of the v1 branch (skipped for a v2 bridge). */
75
+ const useV1 = (pipe, opts) => runner.use(named(ifV1(pipe), pipe), opts);
76
+ /** Add a pipe of the bridge branch (skipped for anything else). */
77
+ const useV2 = (pipe, opts) => runner.use(named(ifV2(pipe), pipe), opts);
78
+ useV1(({ itx }, next) => {
79
+ const fields = findNonDefaultDepositV2BridgeFields(itx);
80
+ if (fields.length) return next(new CustomError("INVALID_TX", `Invalid itx: a legacy rollup deposit must not carry bridge fields: ${fields.join(", ")}`));
81
+ return next();
82
+ });
83
+ useV1(({ itx }, next) => {
32
84
  const { error } = vValidate(schema, itx);
33
85
  if (error) return next(new CustomError("INVALID_TX", `Invalid itx: ${error.message}`));
34
86
  return next();
35
87
  });
36
- runner.use(pipes.ExtractState({
88
+ useV1(pipes.ExtractState({
37
89
  from: "itx.rollup",
38
90
  to: "rollupState",
39
91
  status: "INVALID_ROLLUP",
40
92
  table: "rollup"
41
93
  }));
42
- runner.use(rejectBridgeV2("deposit_token_v2"));
43
- runner.use((context, next) => {
94
+ useV1(rejectBridgeV2("deposit_token_v2"));
95
+ useV1((context, next) => {
44
96
  const { tx: tx$1, itx, rollupState } = context;
45
97
  if (rollup.getRollupTargetType(rollupState) === "EVM") {
46
98
  if (vValidate(vDID({
@@ -61,53 +113,53 @@ runner.use((context, next) => {
61
113
  if (isProposerSponsor && signatures.some((x) => x.signer === itx.to)) return next(new CustomError("INVALID_TX", "itx.to should not exist in signatures"));
62
114
  return next();
63
115
  });
64
- runner.use(verify_status_default({ paused: false }));
65
- runner.use((context, next) => {
116
+ useV1(verify_status_default({ paused: false }));
117
+ useV1((context, next) => {
66
118
  const { itx, rollupState } = context;
67
119
  if (!rollup.isTokenSupportedByRollup(rollupState, itx.token.address)) return next(new CustomError("INVALID_TX", "Deposit token address does not match with rollup state"));
68
120
  if (rollupState.validators.some((x) => x.address === itx.proposer) === false) return next(new CustomError("INVALID_TX", "itx.proposer does not exist in validators"));
69
121
  return next();
70
122
  });
71
- runner.use(pipes.ExtractState({
123
+ useV1(pipes.ExtractState({
72
124
  from: "itx.evidence.hash",
73
125
  to: "evidenceState",
74
126
  status: "OK",
75
127
  table: "evidence"
76
128
  }));
77
- runner.use(({ evidenceState }, next) => {
129
+ useV1(({ evidenceState }, next) => {
78
130
  if (evidenceState) return next(new CustomError("INVALID_TX", "Deposit evidence already seen on this chain"));
79
131
  return next();
80
132
  });
81
- runner.use(verify_signers_default({
133
+ useV1(verify_signers_default({
82
134
  signersKey: "tx.signaturesList",
83
135
  allowSender: true
84
136
  }));
85
- runner.use(pipes.VerifyMultiSigV2({ signersKey: "signers" }));
86
- runner.use(pipes.ExtractState({
137
+ useV1(pipes.VerifyMultiSigV2({ signersKey: "signers" }));
138
+ useV1(pipes.ExtractState({
87
139
  from: "itx.token.address",
88
140
  to: "tokenState",
89
141
  status: "INVALID_TOKEN",
90
142
  table: "token"
91
143
  }));
92
- runner.use((context, next) => {
144
+ useV1((context, next) => {
93
145
  const { itx } = context;
94
146
  context.stakeAddress = toStakeAddress(itx.proposer, itx.rollup);
95
147
  context.lockerAddress = getRewardLocker(itx.rollup);
96
148
  return next();
97
149
  });
98
- runner.use(pipes.ExtractState({
150
+ useV1(pipes.ExtractState({
99
151
  from: "lockerAddress",
100
152
  to: "lockerState",
101
153
  status: "OK",
102
154
  table: "stake"
103
155
  }));
104
- runner.use(pipes.ExtractState({
156
+ useV1(pipes.ExtractState({
105
157
  from: "stakeAddress",
106
158
  to: "stakeState",
107
159
  status: "INVALID_STAKE_STATE",
108
160
  table: "stake"
109
161
  }));
110
- runner.use((context, next) => {
162
+ useV1((context, next) => {
111
163
  const { itx, stakeState, tokenState, rollupState } = context;
112
164
  if (stakeState.revocable === true) return next(new CustomError("INVALID_STAKE_STATE", `Staking not locked for deposit: ${stakeState.address}`));
113
165
  const depositAmount = new BN(itx.token.value).add(new BN(itx.actualFee));
@@ -119,7 +171,7 @@ runner.use((context, next) => {
119
171
  if (depositAmount.gt(stakedAmount)) return next(new CustomError("INSUFFICIENT_STAKE", `Deposit amount must be less than available stake: ${fromUnitToToken(stakedAmount, tokenState.decimal)}`));
120
172
  return next();
121
173
  });
122
- runner.use((context, next) => {
174
+ useV1((context, next) => {
123
175
  const { itx, rollupState, tokenState } = context;
124
176
  const { depositFeeRate, maxDepositFee, minDepositFee } = rollupState;
125
177
  const { reward } = getTxFee({
@@ -131,36 +183,36 @@ runner.use((context, next) => {
131
183
  if (new BN(itx.actualFee).lt(new BN(reward))) return next(new CustomError("INVALID_TX", `itx.actualFee too low, expect at least ${fromUnitToToken(reward, tokenState.decimal)}, got ${fromUnitToToken(itx.actualFee, tokenState.decimal)}`));
132
184
  return next();
133
185
  });
134
- runner.use(pipes.ExtractState({
186
+ useV1(pipes.ExtractState({
135
187
  from: "tx.from",
136
188
  to: "senderState",
137
189
  status: "OK",
138
190
  table: "account"
139
191
  }));
140
- runner.use(async (context, next) => {
192
+ useV1(async (context, next) => {
141
193
  if (context.isProposerSponsor) {
142
194
  context.receiverState = await context.statedb.account.get(context.itx.to, context);
143
195
  if (context.receiverState && (context.receiverState.address !== context.itx.to || account.isMigrated(context.receiverState))) return next(new CustomError("ACCOUNT_MIGRATED", `Recipient account is already migrated: ${context.itx.to}`));
144
196
  }
145
197
  return next();
146
198
  });
147
- runner.use(pipes.ExtractState({
199
+ useV1(pipes.ExtractState({
148
200
  from: "signers",
149
201
  to: "signerStates",
150
202
  status: "INVALID_SIGNER_STATE",
151
203
  table: "account"
152
204
  }));
153
- runner.use(pipes.VerifyAccountMigration({
205
+ useV1(pipes.VerifyAccountMigration({
154
206
  signerKey: "signerStates",
155
207
  stateKey: "senderState",
156
208
  addressKey: "tx.from"
157
209
  }));
158
- runner.use(pipes.VerifyBlocked({ stateKeys: [
210
+ useV1(pipes.VerifyBlocked({ stateKeys: [
159
211
  "senderState",
160
212
  "receiverState",
161
213
  "signerStates"
162
214
  ] }));
163
- runner.use(ensure_gas_default((context) => {
215
+ useV1(ensure_gas_default((context) => {
164
216
  const result = {
165
217
  create: 1,
166
218
  update: 1,
@@ -174,9 +226,57 @@ runner.use(ensure_gas_default((context) => {
174
226
  else result.create += 1;
175
227
  return result;
176
228
  }));
177
- runner.use(ensure_cost_default({ attachSenderChanges: true }));
229
+ useV1(ensure_cost_default({ attachSenderChanges: true }));
230
+ useV2(pipes.VerifyMultiSig(0));
231
+ useV2(function BridgeDepositSchema(context, next) {
232
+ const { error } = vValidate(bridgeSchema, context.itx);
233
+ if (error) return next(new CustomError("INVALID_TX", `Invalid itx: ${error.message}`));
234
+ const itx = context.itx;
235
+ if (!isEmptyAny(itx.data)) return next(new CustomError("INVALID_TX", "Invalid itx: a bridge deposit carries no data"));
236
+ const signatures = getListField(itx, "validatorSignatures");
237
+ if (!Array.isArray(signatures) || signatures.length > 16 || signatures.some((x) => typeof x !== "string")) return next(new CustomError("INVALID_TX", "Invalid itx: validatorSignatures must be at most 16 strings"));
238
+ context.releaseItx = {
239
+ kind: itx.kind,
240
+ bridge: itx.rollup,
241
+ evidence: itx.evidence.hash,
242
+ ordinal: itx.ordinal,
243
+ to: itx.to,
244
+ amount: itx.token.value,
245
+ epoch: itx.epoch,
246
+ ethSender: itx.ethSender ?? "",
247
+ claimSignature: itx.claimSignature ?? "",
248
+ signaturesList: signatures
249
+ };
250
+ return next();
251
+ });
252
+ useV2(checkReleaseFields);
253
+ useV2(rejectReleaseDelegator);
254
+ useV2(resolveReleaseTime);
255
+ useV2(resolveReleaseBridge({ token: (context) => context.itx.token?.address }));
256
+ useV2(checkReleaseMinimum);
257
+ useV2(checkReleaseRecipient);
258
+ useV2(checkReleaseTombstone);
259
+ useV2(verifyReleaseSignatures);
260
+ useV2(verifyReleaseClaim);
261
+ useV2(checkReleaseRefund);
262
+ useV2(checkReleaseRecipientState);
263
+ useV2(checkReleaseCap);
264
+ useV2(checkReleaseReserve);
265
+ useV2(ensure_gas_default(releaseGasEstimate));
266
+ useV2(pipes.ExtractState({
267
+ from: "tx.from",
268
+ to: "senderState",
269
+ status: "INVALID_SENDER_STATE",
270
+ table: "account"
271
+ }));
272
+ useV2(pipes.VerifyAccountMigration({
273
+ stateKey: "senderState",
274
+ addressKey: "tx.from"
275
+ }));
276
+ useV2(pipes.VerifyBlocked({ stateKeys: ["senderState", "receiverState"] }));
277
+ useV2(ensure_cost_default({ attachSenderChanges: true }));
178
278
  runner.use(pipes.TakeStateSnapshot());
179
- runner.use(async (context, next) => {
279
+ useV1(async (context, next) => {
180
280
  const { tx: tx$1, itx, statedb, rollupState, senderState, receiverState, isProposerSponsor, stakeState, stakeAddress, lockerState, lockerAddress, senderChange, updateVaults } = context;
181
281
  const user = itx.token.value;
182
282
  const fee = itx.actualFee;
@@ -269,6 +369,7 @@ runner.use(async (context, next) => {
269
369
  debug("deposit-token-v2", itx);
270
370
  next();
271
371
  }, { persistError: true });
372
+ useV2(writeRelease, { persistError: true });
272
373
  runner.use(pipes.VerifyStateDiff());
273
374
  var deposit_v2_default = runner;
274
375
 
@@ -1,4 +1,4 @@
1
- import { Runner } from "@ocap/tx-pipeline";
1
+ import { ResolvedBridge, Runner } from "@ocap/tx-pipeline";
2
2
  import { IReadyContext, IStakeState, IWithRollup, IWithSender, IWithSigners, IWithStake, IWithToken, TWithdrawTokenV2Tx } from "@ocap/types";
3
3
 
4
4
  //#region src/protocols/token/withdraw-v2.d.ts
@@ -35,6 +35,18 @@ type Context = IReadyContext<TWithdrawTokenV2Tx> & IWithSender & Partial<IWithSi
35
35
  delta: string;
36
36
  action: string;
37
37
  }>;
38
+ /** set by the first pipe: `itx.rollup` is a v2 bridge, i.e. the bridge branch runs */
39
+ isBridgeV2?: boolean;
40
+ /** bridge branch: the bridge `itx.rollup` resolves to (pre-tx row, flags at txTime) */
41
+ bridge?: ResolvedBridge;
42
+ /** bridge branch: the validated withdraw */
43
+ bridgeWithdraw?: {
44
+ amount: string;
45
+ ethRecipient: string;
46
+ };
47
+ /** bridge branch: `toBridgeReserveAddress(itx.rollup)`, recomputed, and its account */
48
+ reserveAddress?: string;
49
+ reserveState?: any;
38
50
  };
39
51
  declare const runner: Runner<Context>;
40
52
  //#endregion
@@ -1,16 +1,18 @@
1
1
  import { applyTokenChange, applyTokenUpdates, getBNSum, getRewardLocker, getTxFee } from "../../util.mjs";
2
2
  import ensure_cost_default from "../../pipes/ensure-cost.mjs";
3
3
  import ensure_gas_default from "../../pipes/ensure-gas.mjs";
4
- import { rejectBridgeV2 } from "../rollup/bridge-v2.mjs";
4
+ import { ifV1, ifV2, peekBridgeFailClosed, rejectBridgeV2 } from "../rollup/bridge-v2.mjs";
5
5
  import verify_status_default from "../rollup/pipes/verify-status.mjs";
6
- import { Runner, pipes } from "@ocap/tx-pipeline";
6
+ import { Runner, pipes, resolveBridge } from "@ocap/tx-pipeline";
7
7
  import { CustomError } from "@ocap/util/lib/error";
8
8
  import { getListField } from "@ocap/util/lib/get-list-field";
9
- import { toStakeAddress } from "@arcblock/did-util";
9
+ import { toBridgeReserveAddress, toStakeAddress } from "@arcblock/did-util";
10
10
  import { account, rollup, stake } from "@ocap/state";
11
11
  import { BN, fromUnitToToken } from "@ocap/util";
12
12
  import Debug from "debug";
13
13
  import { schemas, v, vBN, vBNMin, vDID, vStripUnknown, vValidate } from "@arcblock/validator";
14
+ import { checkBridgeWithdrawV2, decodeBridgeWithdrawV2Fields, isBridgeWithdrawFailure } from "@ocap/tx-pipeline/lib/helpers/bridge-withdraw";
15
+ import { assertBridgeWithdrawEnvelopeInBranch } from "@ocap/tx-pipeline/lib/helpers/replay-guard";
14
16
 
15
17
  //#region src/protocols/token/withdraw-v2.ts
16
18
  const debug = Debug("@ocap/tx-protocols:withdraw-token");
@@ -28,19 +30,30 @@ const schema = v.pipe(v.object({
28
30
  data: v.optional(v.nullable(v.any()))
29
31
  }), vStripUnknown());
30
32
  const runner = new Runner("withdraw_token_v2");
31
- runner.use(({ itx }, next) => {
33
+ const PeekWithdrawBridge = peekBridgeFailClosed("withdraw_token_v2", "PeekWithdrawBridge");
34
+ runner.use(PeekWithdrawBridge);
35
+ /** The guarded pipe keeps the name of the pipe it wraps (structural tests and debugging find pipes by name). */
36
+ const named = (guarded, pipe) => Object.defineProperty(guarded, "name", {
37
+ value: pipe.name,
38
+ configurable: true
39
+ });
40
+ /** Add a pipe of the v1 branch (skipped for a v2 bridge). */
41
+ const useV1 = (pipe, opts) => runner.use(named(ifV1(pipe), pipe), opts);
42
+ /** Add a pipe of the bridge branch (skipped for anything else). */
43
+ const useV2 = (pipe, opts) => runner.use(named(ifV2(pipe), pipe), opts);
44
+ useV1(({ itx }, next) => {
32
45
  const { error } = vValidate(schema, itx);
33
46
  if (error) return next(new CustomError("INVALID_TX", `Invalid itx: ${error.message}`));
34
47
  return next();
35
48
  });
36
- runner.use(pipes.ExtractState({
49
+ useV1(pipes.ExtractState({
37
50
  from: "itx.rollup",
38
51
  to: "rollupState",
39
52
  status: "INVALID_ROLLUP",
40
53
  table: "rollup"
41
54
  }));
42
- runner.use(rejectBridgeV2("withdraw_token_v2"));
43
- runner.use((context, next) => {
55
+ useV1(rejectBridgeV2("withdraw_token_v2"));
56
+ useV1((context, next) => {
44
57
  const { tx: tx$1, itx, rollupState } = context;
45
58
  if (rollup.getRollupTargetType(rollupState) === "EVM") {
46
59
  if (vValidate(vDID({
@@ -55,8 +68,8 @@ runner.use((context, next) => {
55
68
  if (itx.to !== tx$1.from) return next(new CustomError("INVALID_TX", "You can only withdraw to tx sender account"));
56
69
  return next();
57
70
  });
58
- runner.use(verify_status_default({ paused: false }));
59
- runner.use((context, next) => {
71
+ useV1(verify_status_default({ paused: false }));
72
+ useV1((context, next) => {
60
73
  const { itx, rollupState } = context;
61
74
  if (!rollup.isTokenSupportedByRollup(rollupState, itx.token.address)) return next(new CustomError("INVALID_TX", "Withdraw token address does not match with rollup"));
62
75
  if (rollup.hasRollupReserveTracking(rollupState)) {
@@ -67,19 +80,19 @@ runner.use((context, next) => {
67
80
  }
68
81
  return next();
69
82
  });
70
- runner.use(pipes.ExtractState({
83
+ useV1(pipes.ExtractState({
71
84
  from: "itx.token.address",
72
85
  to: "tokenState",
73
86
  status: "INVALID_TOKEN",
74
87
  table: "token"
75
88
  }));
76
- runner.use(pipes.ExtractState({
89
+ useV1(pipes.ExtractState({
77
90
  from: "tx.from",
78
91
  to: "senderState",
79
92
  status: "INVALID_SENDER_STATE",
80
93
  table: "account"
81
94
  }));
82
- runner.use((context, next) => {
95
+ useV1((context, next) => {
83
96
  const { tx: tx$1, itx, tokenState, rollupState } = context;
84
97
  const withdrawAmount = new BN(itx.token.value);
85
98
  const minWithdrawAmount = new BN(rollupState.minWithdrawAmount);
@@ -96,11 +109,11 @@ runner.use((context, next) => {
96
109
  };
97
110
  return next();
98
111
  });
99
- runner.use(pipes.VerifyTokenBalance({
112
+ useV1(pipes.VerifyTokenBalance({
100
113
  ownerKey: "senderState",
101
114
  conditionKey: "tokenConditions"
102
115
  }));
103
- runner.use((context, next) => {
116
+ useV1((context, next) => {
104
117
  const { itx, rollupState, tokenState } = context;
105
118
  const { withdrawFeeRate, maxWithdrawFee, minWithdrawFee } = rollupState;
106
119
  const { reward } = getTxFee({
@@ -117,7 +130,7 @@ runner.use((context, next) => {
117
130
  }
118
131
  return next();
119
132
  });
120
- runner.use((context, next) => {
133
+ useV1((context, next) => {
121
134
  const { tx: tx$1, itx, rollupState } = context;
122
135
  if (new BN(itx.maxFee).isZero()) return next();
123
136
  if ((rollupState.validators ?? []).map((x) => x.address).includes(itx.proposer) === false) return next(new CustomError("INVALID_TX", `itx.proposer ${itx.proposer} does not exist in validator whitelist`));
@@ -127,42 +140,42 @@ runner.use((context, next) => {
127
140
  context.signers = signatures.map((x) => x.signer);
128
141
  verifyMultiSigV2(context, next);
129
142
  });
130
- runner.use(pipes.ExtractState({
143
+ useV1(pipes.ExtractState({
131
144
  from: "signers",
132
145
  to: "signerStates",
133
146
  status: "INVALID_SIGNER_STATE",
134
147
  table: "account"
135
148
  }));
136
- runner.use(pipes.VerifyAccountMigration({
149
+ useV1(pipes.VerifyAccountMigration({
137
150
  signerKey: "signerStates",
138
151
  stateKey: "senderState",
139
152
  addressKey: "tx.from"
140
153
  }));
141
- runner.use(pipes.VerifyBlocked({ stateKeys: ["senderState", "signerStates"] }));
142
- runner.use((context, next) => {
154
+ useV1(pipes.VerifyBlocked({ stateKeys: ["senderState", "signerStates"] }));
155
+ useV1((context, next) => {
143
156
  const { itx, senderState } = context;
144
157
  context.stakeAddress = toStakeAddress(senderState.address, itx.rollup);
145
158
  context.lockerAddress = getRewardLocker(itx.rollup);
146
159
  return next();
147
160
  });
148
- runner.use(pipes.ExtractState({
161
+ useV1(pipes.ExtractState({
149
162
  from: "lockerAddress",
150
163
  to: "lockerState",
151
164
  status: "OK",
152
165
  table: "stake"
153
166
  }));
154
- runner.use(pipes.ExtractState({
167
+ useV1(pipes.ExtractState({
155
168
  from: "stakeAddress",
156
169
  to: "stakeState",
157
170
  status: "OK",
158
171
  table: "stake"
159
172
  }));
160
- runner.use((context, next) => {
173
+ useV1((context, next) => {
161
174
  const { stakeState } = context;
162
175
  if (stakeState && stakeState.revocable === true) return next(new CustomError("INVALID_STAKE_STATE", `Staking not locked for withdraw: ${stakeState.address}`));
163
176
  return next();
164
177
  });
165
- runner.use(ensure_gas_default((context) => {
178
+ useV1(ensure_gas_default((context) => {
166
179
  const result = {
167
180
  create: 0,
168
181
  update: 1,
@@ -174,9 +187,94 @@ runner.use(ensure_gas_default((context) => {
174
187
  else result.create += 1;
175
188
  return result;
176
189
  }));
177
- runner.use(ensure_cost_default({ attachSenderChanges: true }));
190
+ useV1(ensure_cost_default({ attachSenderChanges: true }));
191
+ useV2(async (context, next) => {
192
+ let bridge;
193
+ try {
194
+ bridge = await resolveBridge(context, context.itx.rollup);
195
+ } catch (err) {
196
+ return next(err);
197
+ }
198
+ if (!bridge) return next(new CustomError("BRIDGE_WITHDRAW_RESERVE", `${context.itx.rollup} is not a v2 bridge that can be withdrawn from`));
199
+ const result = checkBridgeWithdrawV2({
200
+ ...context,
201
+ txType: "withdraw_token_v2"
202
+ }, bridge);
203
+ if (isBridgeWithdrawFailure(result)) return next(new CustomError(result.code, result.message));
204
+ context.bridge = bridge;
205
+ context.bridgeWithdraw = result;
206
+ context.reserveAddress = toBridgeReserveAddress(bridge.address);
207
+ return next();
208
+ });
209
+ useV2((context, next) => {
210
+ const bridge = context.bridge;
211
+ const fields = decodeBridgeWithdrawV2Fields(context.itx, bridge.token);
212
+ if (!fields) return next(new CustomError("INVALID_SIGNATURE", "Bridge withdraw envelope can not be matched to the transaction"));
213
+ const problem = assertBridgeWithdrawEnvelopeInBranch(context, {
214
+ bridge: bridge.address,
215
+ amount: fields.amount,
216
+ token: bridge.token,
217
+ ethRecipient: fields.ethRecipient
218
+ });
219
+ if (problem) return next(new CustomError("INVALID_SIGNATURE", `Bridge withdraw envelope does not match: ${problem}`));
220
+ return next();
221
+ });
222
+ useV2(pipes.ExtractState({
223
+ from: "tx.from",
224
+ to: "senderState",
225
+ status: "INVALID_SENDER_STATE",
226
+ table: "account"
227
+ }));
228
+ useV2((context, next) => {
229
+ context.tokenConditions = {
230
+ owner: context.tx.from,
231
+ tokens: [{
232
+ address: context.bridge.token,
233
+ value: context.bridgeWithdraw.amount
234
+ }]
235
+ };
236
+ return next();
237
+ });
238
+ useV2(pipes.VerifyTokenBalance({
239
+ ownerKey: "senderState",
240
+ conditionKey: "tokenConditions"
241
+ }));
242
+ useV2(pipes.VerifyAccountMigration({
243
+ signerKey: "signerStates",
244
+ stateKey: "senderState",
245
+ addressKey: "tx.from"
246
+ }));
247
+ useV2(pipes.VerifyBlocked({ stateKeys: ["senderState"] }));
248
+ useV2((context, next) => {
249
+ context.bridgeTokens = [context.bridge.token];
250
+ return next();
251
+ });
252
+ useV2(pipes.ExtractState({
253
+ from: "bridgeTokens",
254
+ to: "bridgeTokenStates",
255
+ status: "INVALID_TOKEN",
256
+ table: "token"
257
+ }));
258
+ useV2(pipes.verifyTokenAccess({
259
+ statesKey: "bridgeTokenStates",
260
+ listFieldKey: "spenders",
261
+ accountKeys: ["senderState"],
262
+ errorMessage: "Account {address} is not allowed to transfer token {tokenAddress}"
263
+ }));
264
+ useV2(pipes.ExtractState({
265
+ from: "reserveAddress",
266
+ to: "reserveState",
267
+ status: "BRIDGE_WITHDRAW_RESERVE",
268
+ table: "account"
269
+ }));
270
+ useV2(ensure_gas_default((context) => ({
271
+ create: 0,
272
+ update: 2,
273
+ payment: context.bridge.token === context.config.token.address ? context.bridgeWithdraw.amount : 0
274
+ })));
275
+ useV2(ensure_cost_default({ attachSenderChanges: true }));
178
276
  runner.use(pipes.TakeStateSnapshot());
179
- runner.use(async (context, next) => {
277
+ useV1(async (context, next) => {
180
278
  const { tx: tx$1, itx, statedb, stakeState, senderState, lockerState, lockerAddress, stakeAddress, senderChange, updateVaults } = context;
181
279
  const total = getBNSum(itx.token.value, itx.actualFee, itx.maxFee);
182
280
  const fee = getBNSum(itx.actualFee, itx.maxFee);
@@ -244,6 +342,41 @@ runner.use(async (context, next) => {
244
342
  debug("withdraw-token-v2", itx);
245
343
  next();
246
344
  }, { persistError: true });
345
+ useV2(async (context, next) => {
346
+ const { tx: tx$1, statedb, senderState, reserveState, senderChange, updateVaults } = context;
347
+ const token$1 = context.bridge.token;
348
+ const { amount } = context.bridgeWithdraw;
349
+ let senderUpdates = applyTokenUpdates([{
350
+ address: token$1,
351
+ value: amount
352
+ }], senderState, "sub");
353
+ if (senderChange) senderUpdates = applyTokenChange(senderUpdates, senderChange);
354
+ const reserveUpdates = applyTokenUpdates([{
355
+ address: token$1,
356
+ value: amount
357
+ }], reserveState, "add");
358
+ const [newSenderState, newReserveState] = await Promise.all([statedb.account.update(senderState.address, account.update(senderState, {
359
+ nonce: tx$1.nonce,
360
+ ...senderUpdates
361
+ }, context), context), statedb.account.update(reserveState.address, account.update(reserveState, reserveUpdates, context), context)]);
362
+ if (updateVaults) await updateVaults();
363
+ context.senderState = newSenderState;
364
+ context.reserveState = newReserveState;
365
+ context.updatedAccounts = context.updatedAccounts || [];
366
+ context.updatedAccounts.push({
367
+ address: senderState.address,
368
+ token: token$1,
369
+ delta: `-${amount}`,
370
+ action: "transfer"
371
+ }, {
372
+ address: reserveState.address,
373
+ token: token$1,
374
+ delta: amount,
375
+ action: "transfer"
376
+ });
377
+ debug("withdraw-token-v2 (bridge)", context.itx);
378
+ next();
379
+ }, { persistError: true });
247
380
  runner.use(pipes.VerifyStateDiff());
248
381
  var withdraw_v2_default = runner;
249
382
 
@@ -3,7 +3,7 @@ import ensure_cost_default from "../../pipes/ensure-cost.mjs";
3
3
  import ensure_gas_default from "../../pipes/ensure-gas.mjs";
4
4
  import { markStatelessPrefix } from "../../stateless-prefix.mjs";
5
5
  import { types } from "@ocap/mcrypto";
6
- import { Runner, isBridgeReserveRole, pipes, resolveBridgeForReserve, verifyAssetHierarchy } from "@ocap/tx-pipeline";
6
+ import { Runner, isBridgeReserveRole, pipes, verifyAssetHierarchy } from "@ocap/tx-pipeline";
7
7
  import { CustomError } from "@ocap/util/lib/error";
8
8
  import { getListField } from "@ocap/util/lib/get-list-field";
9
9
  import { toTypeInfo } from "@arcblock/did";
@@ -14,7 +14,6 @@ import { getRelatedAddresses } from "@ocap/util/lib/get-related-addr";
14
14
  import { decodeBigInt } from "@ocap/message";
15
15
  import { schemas, v, vDID, vStripUnknown, vValidate } from "@arcblock/validator";
16
16
  import isEmpty from "lodash/isEmpty.js";
17
- import { checkBridgeWithdraw, isBridgeWithdrawFailure } from "@ocap/tx-pipeline/lib/helpers/bridge-withdraw";
18
17
 
19
18
  //#region src/protocols/trade/transfer-v2.ts
20
19
  const runner = new Runner("transfer_v2");
@@ -107,12 +106,8 @@ runner.use((context, next) => {
107
106
  }
108
107
  next();
109
108
  });
110
- runner.use(async (context, next) => {
111
- if (!isBridgeReserveRole(context.itx.to)) return next();
112
- const bridge = await resolveBridgeForReserve(context, context.itx.to);
113
- if (!bridge) return next(new CustomError("BRIDGE_WITHDRAW_RESERVE", `${context.itx.to} has the bridge reserve role but is not the reserve of any bridge`));
114
- const result = checkBridgeWithdraw(context, bridge);
115
- if (isBridgeWithdrawFailure(result)) return next(new CustomError(result.code, result.message));
109
+ runner.use((context, next) => {
110
+ if (isBridgeReserveRole(context.itx.to)) return next(new CustomError("BRIDGE_WITHDRAW_RESERVE", `${context.itx.to} is a bridge reserve: transfer_v2 can not credit it, withdraw with withdraw_token_v2`));
116
111
  return next();
117
112
  });
118
113
  runner.use(ensure_gas_default((context) => {
@@ -3,7 +3,7 @@ let _ocap_mcrypto = require("@ocap/mcrypto");
3
3
 
4
4
  //#region src/bridge-release-crypto.ts
5
5
  /**
6
- * EIP-712 digests and signature recovery for `release_bridge_token` (#1466, bridge/docs/ocap-protocols.md §3).
6
+ * EIP-712 digests and signature recovery for the bridge release of `deposit_token_v2` (#1466, bridge/docs/ocap-protocols.md §3).
7
7
  *
8
8
  * The structs mirror `@arcblock/bridge-types` (`OcapRelease`, `DepositClaim`; domain `ArcBridge` v1). The chain can
9
9
  * not depend on that package (it is private and pulls in viem), so the encoding is re-implemented here and pinned to