@ocap/state 1.31.1 → 1.31.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,7 @@
1
1
  import { __exportAll } from "../_virtual/rolldown_runtime.mjs";
2
2
  import { create as create$1, update as update$1 } from "../contexts/state.mjs";
3
+ import { BRIDGE_CREATE_KEYS, BRIDGE_LONE_PAUSE_COOLDOWN, BRIDGE_LONE_PAUSE_TTL, BRIDGE_MAX_DELAY, BRIDGE_MAX_EPOCH_LEAD, BRIDGE_MAX_PAUSERS, BRIDGE_MAX_VALIDATORS, BRIDGE_MIN_EPOCH_LEAD, BRIDGE_MIN_VALIDATORS, BRIDGE_OWNER_TIMELOCK, BRIDGE_PATCH_ACTION_KEYS, BRIDGE_PATCH_VALUE_KEYS, BRIDGE_RESERVE_MIGRATION_WINDOW, BRIDGE_V1_ZERO_FIELDS, BRIDGE_VERSION, activeEpochAt, applyLonePause, assertBridgeTransition, assertV1FieldsUnused, effectiveOwnerAt, getBridgeBody, isBridgeFinalAt, isBridgePausedAt, isBridgeV2, isBridgeV2Data, isQuorumPaused, isValidOwnerCandidate, isZeroish, lc, lonePauseTrack, materializeBridgeAt, maxVoucherValidity, parseBridgeCreateData, pendingEpochAt, planBridgePatch, planMembership, sameAddress, syncBridgeView, toSeconds, validateBridgeBody } from "./rollup-v2.mjs";
4
+ import { bridgeSchema, createBridge, updateBridge, validateBridge } from "./rollup-bridge.mjs";
3
5
  import { BN, toAddress } from "@ocap/util";
4
6
  import { CustomError } from "@ocap/util/lib/error";
5
7
  import pick from "lodash/pick.js";
@@ -8,28 +10,72 @@ import { patterns, schemas, v, vBN, vBNMin, vBNPositive, vDID, vStripUnknown, vV
8
10
 
9
11
  //#region src/states/rollup.ts
10
12
  var rollup_exports = /* @__PURE__ */ __exportAll({
13
+ BRIDGE_CREATE_KEYS: () => BRIDGE_CREATE_KEYS,
14
+ BRIDGE_LONE_PAUSE_COOLDOWN: () => BRIDGE_LONE_PAUSE_COOLDOWN,
15
+ BRIDGE_LONE_PAUSE_TTL: () => BRIDGE_LONE_PAUSE_TTL,
16
+ BRIDGE_MAX_DELAY: () => BRIDGE_MAX_DELAY,
17
+ BRIDGE_MAX_EPOCH_LEAD: () => BRIDGE_MAX_EPOCH_LEAD,
18
+ BRIDGE_MAX_PAUSERS: () => BRIDGE_MAX_PAUSERS,
19
+ BRIDGE_MAX_VALIDATORS: () => BRIDGE_MAX_VALIDATORS,
20
+ BRIDGE_MIN_EPOCH_LEAD: () => BRIDGE_MIN_EPOCH_LEAD,
21
+ BRIDGE_MIN_VALIDATORS: () => BRIDGE_MIN_VALIDATORS,
22
+ BRIDGE_OWNER_TIMELOCK: () => BRIDGE_OWNER_TIMELOCK,
23
+ BRIDGE_PATCH_ACTION_KEYS: () => BRIDGE_PATCH_ACTION_KEYS,
24
+ BRIDGE_PATCH_VALUE_KEYS: () => BRIDGE_PATCH_VALUE_KEYS,
25
+ BRIDGE_RESERVE_MIGRATION_WINDOW: () => BRIDGE_RESERVE_MIGRATION_WINDOW,
26
+ BRIDGE_V1_ZERO_FIELDS: () => BRIDGE_V1_ZERO_FIELDS,
27
+ BRIDGE_VERSION: () => BRIDGE_VERSION,
11
28
  VALID_ROLLUP_TARGET_TYPES: () => VALID_ROLLUP_TARGET_TYPES,
29
+ activeEpochAt: () => activeEpochAt,
30
+ applyLonePause: () => applyLonePause,
31
+ assertBridgeTransition: () => assertBridgeTransition,
32
+ assertV1FieldsUnused: () => assertV1FieldsUnused,
33
+ bridgeSchema: () => bridgeSchema,
12
34
  close: () => close,
13
35
  create: () => create,
36
+ createBridge: () => createBridge,
37
+ effectiveOwnerAt: () => effectiveOwnerAt,
38
+ getBridgeBody: () => getBridgeBody,
14
39
  getRollupSupportedTokens: () => getRollupSupportedTokens,
15
40
  getRollupTargetType: () => getRollupTargetType,
16
41
  getRollupTokenReserve: () => getRollupTokenReserve,
17
42
  hasRollupReserveTracking: () => hasRollupReserveTracking,
43
+ isBridgeFinalAt: () => isBridgeFinalAt,
44
+ isBridgePausedAt: () => isBridgePausedAt,
45
+ isBridgeV2: () => isBridgeV2,
46
+ isBridgeV2Data: () => isBridgeV2Data,
18
47
  isProposerSponsoredDepositAllowed: () => isProposerSponsoredDepositAllowed,
48
+ isQuorumPaused: () => isQuorumPaused,
19
49
  isTokenSupportedByRollup: () => isTokenSupportedByRollup,
50
+ isValidOwnerCandidate: () => isValidOwnerCandidate,
20
51
  isValidRollupContractAddress: () => isValidRollupContractAddress,
21
52
  isValidRollupTargetType: () => isValidRollupTargetType,
22
53
  isValidRollupValidatorAddress: () => isValidRollupValidatorAddress,
23
54
  isValidRollupVaultAddress: () => isValidRollupVaultAddress,
55
+ isZeroish: () => isZeroish,
56
+ lc: () => lc,
57
+ lonePauseTrack: () => lonePauseTrack,
58
+ materializeBridgeAt: () => materializeBridgeAt,
59
+ maxVoucherValidity: () => maxVoucherValidity,
24
60
  migrateContract: () => migrateContract,
25
61
  migrateVault: () => migrateVault,
62
+ parseBridgeCreateData: () => parseBridgeCreateData,
26
63
  pause: () => pause,
64
+ pendingEpochAt: () => pendingEpochAt,
65
+ planBridgePatch: () => planBridgePatch,
66
+ planMembership: () => planMembership,
27
67
  recordRollupDeposit: () => recordRollupDeposit,
28
68
  recordRollupWithdraw: () => recordRollupWithdraw,
29
69
  resume: () => resume,
70
+ sameAddress: () => sameAddress,
30
71
  schema: () => schema,
72
+ syncBridgeView: () => syncBridgeView,
73
+ toSeconds: () => toSeconds,
31
74
  update: () => update,
32
- validate: () => validate
75
+ updateBridge: () => updateBridge,
76
+ validate: () => validate,
77
+ validateBridge: () => validateBridge,
78
+ validateBridgeBody: () => validateBridgeBody
33
79
  });
34
80
  const VALID_ROLLUP_TARGET_TYPES = ["EVM", "OCAP_ISOMORPHIC"];
35
81
  const ethDidSchema = vDID({
@@ -181,6 +227,7 @@ const create = (attrs, context) => {
181
227
  if (attrs?.reserves && typeof attrs.reserves === "object") {
182
228
  for (const [tokenAddr, reserve] of Object.entries(attrs.reserves)) if (new BN(reserve?.totalDeposited || "0").gt(new BN(0)) || new BN(reserve?.totalWithdrawn || "0").gt(new BN(0))) throw new CustomError("INVALID_ROLLUP_PROPS", `Cannot pre-seed non-zero reserve watermark for token ${tokenAddr} on rollup creation`);
183
229
  }
230
+ if (isBridgeV2Data(attrs?.data)) return createBridge(attrs, context);
184
231
  const dataValue = attrs?.data?.value && typeof attrs.data.value === "object" ? attrs.data.value : void 0;
185
232
  const rollup = {
186
233
  context: create$1(context),
@@ -241,6 +288,8 @@ const create = (attrs, context) => {
241
288
  return validate(rollup);
242
289
  };
243
290
  const update = (state, updates, context) => {
291
+ if (updates.data !== void 0 && updates.data !== null && isBridgeV2Data(updates.data) !== isBridgeV2(state)) throw new CustomError("INVALID_ROLLUP_UPDATE", "data.version is immutable: v1 and v2 rollups can not be converted");
292
+ if (isBridgeV2(state)) return updateBridge(state, updates, context);
244
293
  if (updates.blockHeight && !updates.blockHash) throw new CustomError("INVALID_ROLLUP_UPDATE", "blockHash must be updated together with blockHeight");
245
294
  if (updates.blockHash && !updates.blockHeight) throw new CustomError("INVALID_ROLLUP_UPDATE", "blockHeight must be updated together with blockHash");
246
295
  if (updates.blockHeight && updates.blockHash) {
@@ -397,6 +446,7 @@ const recordRollupWithdraw = (state, tokenAddress, amount, context) => {
397
446
  };
398
447
  const validate = (state) => {
399
448
  if (state?.data?.value?.reserves !== void 0) throw new CustomError("INVALID_ROLLUP_PROPS", "reserves cannot be defined inside data.value");
449
+ if (isBridgeV2Data(state?.data)) return validateBridge(state);
400
450
  const { value, error } = vValidate(schema, state);
401
451
  if (error) throw new CustomError("INVALID_ROLLUP_PROPS", error.details.map((x) => x.message).join(", "));
402
452
  if (value.reserves && typeof value.reserves === "object") for (const [tokenAddr, reserve] of Object.entries(value.reserves)) {
@@ -408,4 +458,4 @@ const validate = (state) => {
408
458
  };
409
459
 
410
460
  //#endregion
411
- export { VALID_ROLLUP_TARGET_TYPES, close, create, getRollupSupportedTokens, getRollupTargetType, getRollupTokenReserve, hasRollupReserveTracking, isProposerSponsoredDepositAllowed, isTokenSupportedByRollup, isValidRollupContractAddress, isValidRollupTargetType, isValidRollupValidatorAddress, isValidRollupVaultAddress, migrateContract, migrateVault, pause, recordRollupDeposit, recordRollupWithdraw, resume, rollup_exports, schema, update, validate };
461
+ export { BRIDGE_CREATE_KEYS, BRIDGE_LONE_PAUSE_COOLDOWN, BRIDGE_LONE_PAUSE_TTL, BRIDGE_MAX_DELAY, BRIDGE_MAX_EPOCH_LEAD, BRIDGE_MAX_PAUSERS, BRIDGE_MAX_VALIDATORS, BRIDGE_MIN_EPOCH_LEAD, BRIDGE_MIN_VALIDATORS, BRIDGE_OWNER_TIMELOCK, BRIDGE_PATCH_ACTION_KEYS, BRIDGE_PATCH_VALUE_KEYS, BRIDGE_RESERVE_MIGRATION_WINDOW, BRIDGE_V1_ZERO_FIELDS, BRIDGE_VERSION, VALID_ROLLUP_TARGET_TYPES, activeEpochAt, applyLonePause, assertBridgeTransition, assertV1FieldsUnused, bridgeSchema, close, create, createBridge, effectiveOwnerAt, getBridgeBody, getRollupSupportedTokens, getRollupTargetType, getRollupTokenReserve, hasRollupReserveTracking, isBridgeFinalAt, isBridgePausedAt, isBridgeV2, isBridgeV2Data, isProposerSponsoredDepositAllowed, isQuorumPaused, isTokenSupportedByRollup, isValidOwnerCandidate, isValidRollupContractAddress, isValidRollupTargetType, isValidRollupValidatorAddress, isValidRollupVaultAddress, isZeroish, lc, lonePauseTrack, materializeBridgeAt, maxVoucherValidity, migrateContract, migrateVault, parseBridgeCreateData, pause, pendingEpochAt, planBridgePatch, planMembership, recordRollupDeposit, recordRollupWithdraw, resume, rollup_exports, sameAddress, schema, syncBridgeView, toSeconds, update, updateBridge, validate, validateBridge, validateBridgeBody };
@@ -62,7 +62,8 @@ const stateSchema = v.pipe(v.object({
62
62
  status: v.picklist([
63
63
  "ACTIVE",
64
64
  "PAUSED",
65
- "GRADUATED"
65
+ "GRADUATED",
66
+ "RETIRED"
66
67
  ]),
67
68
  feeRate: v.pipe(v.number(), v.minValue(0), v.maxValue(2e3)),
68
69
  curve: v.optional(v.nullable(vCurveSchema)),
package/esm/states/tx.mjs CHANGED
@@ -52,7 +52,8 @@ const getTxReceiver = ({ tx, itx, typeUrl }) => {
52
52
  case "TransferTx":
53
53
  case "ExchangeTx":
54
54
  case "TransferV2Tx":
55
- case "ExchangeV2Tx": return itx.to;
55
+ case "ExchangeV2Tx":
56
+ case "ReleaseBridgeTokenTx": return itx.to;
56
57
  case "MintAssetTx": return itx.owner;
57
58
  case "CreateTokenTx":
58
59
  case "CreateAssetTx":
@@ -193,6 +194,33 @@ const getReceiptsFromGasPaid = (tx, { config, typeUrl }) => {
193
194
  }]
194
195
  }];
195
196
  };
197
+ /**
198
+ * `release_bridge_token` (#1466): the reserve pays `amount` of the official token to `itx.to`. The reserve address is
199
+ * not part of the itx (the protocol derives it from `itx.bridge`), so the protocol hands the paying reserve over as
200
+ * `ctx.bridgeReserve` and the bridge token as `ctx.bridgeToken`.
201
+ */
202
+ const getReleaseBridgeTokenReceipts = (tx, ctx) => {
203
+ const reserve = ctx.bridgeReserve;
204
+ const tokenAddress = ctx.bridgeToken || ctx.config?.token?.address;
205
+ const amount = tx.itxJson?.amount;
206
+ const to = tx.itxJson?.to;
207
+ if (!reserve || !tokenAddress || !amount || !to) return [];
208
+ return [{
209
+ address: reserve,
210
+ changes: [{
211
+ target: tokenAddress,
212
+ action: "transfer",
213
+ value: `-${amount}`
214
+ }]
215
+ }, {
216
+ address: to,
217
+ changes: [{
218
+ target: tokenAddress,
219
+ action: "transfer",
220
+ value: amount
221
+ }]
222
+ }];
223
+ };
196
224
  const getTransferV3Receipts = (tx) => [...getReceiptsFromTxInput(tx.itxJson.inputs || [], "-", "transfer"), ...getReceiptsFromTxInput(tx.itxJson.outputs || [], "", "transfer")];
197
225
  const getExchangeReceipts = (tx, ctx) => {
198
226
  const { senderState, receiverState } = ctx;
@@ -762,6 +790,7 @@ const getTxReceipts = ({ tx, code }, ctx = {}) => {
762
790
  let receipts = Array.isArray(ctx.receipts) ? ctx.receipts : [];
763
791
  if (["TransferTx", "TransferV2Tx"].includes(typeUrl)) receipts = receipts.concat(getTransferReceipts(tx));
764
792
  else if (["TransferV3Tx"].includes(typeUrl)) receipts = receipts.concat(getTransferV3Receipts(tx));
793
+ else if (["ReleaseBridgeTokenTx"].includes(typeUrl)) receipts = receipts.concat(getReleaseBridgeTokenReceipts(tx, ctx));
765
794
  else if (["ExchangeTx", "ExchangeV2Tx"].includes(typeUrl)) receipts = receipts.concat(getExchangeReceipts(tx, ctx));
766
795
  else if (["CreateAssetTx"].includes(typeUrl)) receipts = receipts.concat(getCreateAssetReceipts(tx));
767
796
  else if (["MintAssetTx"].includes(typeUrl)) receipts = receipts.concat(getMintAssetReceipts(tx, ctx));
@@ -14,6 +14,7 @@ let _arcblock_validator = require("@arcblock/validator");
14
14
 
15
15
  //#region src/states/account.ts
16
16
  var account_exports = /* @__PURE__ */ require_rolldown_runtime.__exportAll({
17
+ DELEGATED_NONCE_MAX_FUTURE_MS: () => DELEGATED_NONCE_MAX_FUTURE_MS,
17
18
  create: () => create,
18
19
  ensureChecksumAddress: () => ensureChecksumAddress,
19
20
  isMigrated: () => isMigrated,
@@ -75,6 +76,28 @@ const parseNonceBn = (rawNonce) => {
75
76
  }
76
77
  return null;
77
78
  };
79
+ /**
80
+ * How far above the tx time the nonce of a delegated tx may be (#1418). Wallets use `Date.now()` as nonce, so
81
+ * the allowance only has to absorb the clock error of an honest delegatee. Enforced at admission by `VerifyTx`.
82
+ */
83
+ const DELEGATED_NONCE_MAX_FUTURE_MS = 1440 * 60 * 1e3;
84
+ /**
85
+ * Nonce ceiling for an account nonce written by a delegated tx (#1418), or `null` when the write is not part of
86
+ * a delegated tx.
87
+ *
88
+ * A delegated tx is signed by the delegatee (`tx.delegator`) but advances the nonce of the delegator's account
89
+ * (`tx.from`). Wallets sign with `nonce = Date.now()`, so a delegatee that could park that nonce in the future
90
+ * would lock the delegator out of every tx of its own - `revoke_delegate` and `account_migrate` included. The
91
+ * ceiling is the tx time: whatever a delegated tx writes, the next `Date.now()` nonce of the delegator exceeds it.
92
+ * A delegated tx without a usable tx time gets a zero ceiling (advance by one); `validate` refuses such a state
93
+ * context anyway, so the unbounded nonce never reaches the store.
94
+ */
95
+ const getDelegatedNonceCeiling = (context) => {
96
+ const { tx, txTime } = context || {};
97
+ if (!tx || typeof tx.delegator !== "string" || tx.delegator === "") return null;
98
+ const txTimeMs = txTime ? new Date(txTime).getTime() : NaN;
99
+ return Number.isFinite(txTimeMs) && txTimeMs > 0 ? new _ocap_util.BN(String(Math.floor(txTimeMs)), 10) : new _ocap_util.BN(0);
100
+ };
78
101
  const update = (state, attrs, context) => {
79
102
  const hasExplicitNonce = attrs.nonce !== void 0 && attrs.nonce !== null;
80
103
  let shouldUpdateNonce = false;
@@ -84,7 +107,9 @@ const update = (state, attrs, context) => {
84
107
  const currentNonceBn = parseNonceBn(state.nonce) ?? new _ocap_util.BN(0);
85
108
  if (!incomingNonceBn || incomingNonceBn.lte(currentNonceBn) || incomingNonceBn.lte(new _ocap_util.BN(0))) throw new _ocap_util_lib_error.CustomError("INVALID_NONCE", "nonce must be greater in newer transactions");
86
109
  shouldUpdateNonce = true;
87
- normalizedNonce = incomingNonceBn.lte(new _ocap_util.BN(Number.MAX_SAFE_INTEGER)) ? incomingNonceBn.toNumber() : incomingNonceBn.toString(10);
110
+ const ceilingBn = getDelegatedNonceCeiling(context);
111
+ const nextNonceBn = ceilingBn && incomingNonceBn.gt(ceilingBn) ? _ocap_util.BN.max(ceilingBn, currentNonceBn.addn(1)) : incomingNonceBn;
112
+ normalizedNonce = nextNonceBn.lte(new _ocap_util.BN(Number.MAX_SAFE_INTEGER)) ? nextNonceBn.toNumber() : nextNonceBn.toString(10);
88
113
  }
89
114
  if (attrs.pk && (0, _arcblock_did.isFromPublicKey)(state.address, attrs.pk) === false) delete attrs.pk;
90
115
  const pickFields = shouldUpdateNonce ? [
@@ -124,6 +149,7 @@ const isMigrated = (state) => (state.migratedTo || []).length > 0;
124
149
  const ensureChecksumAddress = (address) => (0, _arcblock_did_lib_type.isEthereumDid)(address) ? (0, _arcblock_did_lib_type.toChecksumAddress)(address) : address;
125
150
 
126
151
  //#endregion
152
+ exports.DELEGATED_NONCE_MAX_FUTURE_MS = DELEGATED_NONCE_MAX_FUTURE_MS;
127
153
  Object.defineProperty(exports, 'account_exports', {
128
154
  enumerable: true,
129
155
  get: function () {
@@ -5,7 +5,7 @@ import { v } from "@arcblock/validator";
5
5
 
6
6
  //#region src/states/account.d.ts
7
7
  declare namespace account_d_exports {
8
- export { create, ensureChecksumAddress, isMigrated, parseNonceBn, schema, update, updateOrCreate, validate };
8
+ export { DELEGATED_NONCE_MAX_FUTURE_MS, create, ensureChecksumAddress, isMigrated, parseNonceBn, schema, update, updateOrCreate, validate };
9
9
  }
10
10
  declare const schema: v.SchemaWithPipe<readonly [v.ObjectSchema<{
11
11
  readonly address: any;
@@ -26,6 +26,11 @@ declare const schema: v.SchemaWithPipe<readonly [v.ObjectSchema<{
26
26
  }, undefined>, any]>;
27
27
  declare const create: (attrs: Partial<IAccountState>, context: StateContextInput) => IAccountState;
28
28
  declare const parseNonceBn: (rawNonce: unknown) => InstanceType<typeof BN> | null;
29
+ /**
30
+ * How far above the tx time the nonce of a delegated tx may be (#1418). Wallets use `Date.now()` as nonce, so
31
+ * the allowance only has to absorb the clock error of an honest delegatee. Enforced at admission by `VerifyTx`.
32
+ */
33
+ declare const DELEGATED_NONCE_MAX_FUTURE_MS: number;
29
34
  declare const update: (state: IAccountState, attrs: Partial<IAccountState>, context: StateContextInput) => IAccountState;
30
35
  declare const updateOrCreate: (state: IAccountState | null, attrs: Partial<IAccountState>, context: StateContextInput) => IAccountState;
31
36
  declare const validate: (state: IAccountState) => IAccountState;
@@ -34,4 +39,4 @@ declare const isMigrated: (state: {
34
39
  }) => boolean;
35
40
  declare const ensureChecksumAddress: (address: string) => string;
36
41
  //#endregion
37
- export { account_d_exports, create, ensureChecksumAddress, isMigrated, parseNonceBn, schema, update, updateOrCreate, validate };
42
+ export { DELEGATED_NONCE_MAX_FUTURE_MS, account_d_exports, create, ensureChecksumAddress, isMigrated, parseNonceBn, schema, update, updateOrCreate, validate };
@@ -13,9 +13,12 @@ var chain_exports = /* @__PURE__ */ require_rolldown_runtime.__exportAll({
13
13
  create: () => create,
14
14
  update: () => update
15
15
  });
16
- const create = (attrs) => {
16
+ const create = (attrs, contextArg) => {
17
17
  return {
18
- context: require_contexts_state.create({ txTime: (/* @__PURE__ */ new Date()).toISOString() }),
18
+ context: require_contexts_state.create({
19
+ txTime: contextArg?.txTime || attrs?.context?.txTime || (/* @__PURE__ */ new Date()).toISOString(),
20
+ ...contextArg?.txHash !== void 0 ? { txHash: contextArg.txHash } : attrs?.context?.txHash !== void 0 ? { txHash: attrs.context.txHash } : {}
21
+ }),
19
22
  ...(0, lodash_pick.default)(attrs, [
20
23
  "address",
21
24
  "chainId",
@@ -37,7 +40,7 @@ const update = (state, updates) => {
37
40
  ];
38
41
  if (!process.env.CHAIN_TOKEN_ADDRESS) immutableAttrs.push("token.name", "token.description", "token.unit", "token.totalSupply", "token.initialSupply", "token.foreignToken");
39
42
  for (const attr of immutableAttrs) if ((0, lodash_get.default)(updates, attr) && !(0, lodash_isEqual.default)((0, lodash_get.default)(updates, attr), (0, lodash_get.default)(state, attr))) throw new _ocap_util_lib_error.CustomError("FORBIDDEN", `Cannot update ${attr} field on chain state`);
40
- const context = { txTime: (/* @__PURE__ */ new Date()).toISOString() };
43
+ const context = { txTime: updates?.context?.txTime || (/* @__PURE__ */ new Date()).toISOString() };
41
44
  return {
42
45
  ...state,
43
46
  ...(0, lodash_pick.default)(updates, [
@@ -24,7 +24,15 @@ interface ChainState {
24
24
  vaults?: unknown;
25
25
  context: StateContext;
26
26
  }
27
- declare const create: (attrs: Partial<ChainState>) => ChainState;
27
+ declare const create: (attrs: Partial<ChainState> & {
28
+ context?: {
29
+ txTime?: string;
30
+ txHash?: string;
31
+ };
32
+ }, contextArg?: {
33
+ txTime?: string;
34
+ txHash?: string;
35
+ }) => ChainState;
28
36
  declare const update: (state: ChainState, updates: Partial<ChainState>) => ChainState;
29
37
  //#endregion
30
38
  export { ChainState, chain_d_exports, create, update };
@@ -0,0 +1,170 @@
1
+ const require_rolldown_runtime = require('../_virtual/rolldown_runtime.cjs');
2
+ const require_contexts_state = require('../contexts/state.cjs');
3
+ const require_states_rollup_v2 = require('./rollup-v2.cjs');
4
+ let _ocap_util = require("@ocap/util");
5
+ let _ocap_util_lib_error = require("@ocap/util/lib/error");
6
+ let lodash_pick = require("lodash/pick");
7
+ lodash_pick = require_rolldown_runtime.__toESM(lodash_pick);
8
+ let _arcblock_validator = require("@arcblock/validator");
9
+
10
+ //#region src/states/rollup-bridge.ts
11
+ /**
12
+ * v2 bridge rows (bridge/docs/ocap-protocols.md §v2.1): create / update / validate of a `RollupState` whose
13
+ * `data.value.version == 2`. Kept apart from `rollup.ts` so the v1 code path stays byte-for-byte what it was.
14
+ */
15
+ const ethDidSchema = (0, _arcblock_validator.vDID)({
16
+ prefix: true,
17
+ wallet: "ethereum"
18
+ });
19
+ const ethVaultDidSchema = (0, _arcblock_validator.vDID)({ wallet: "ethereum" });
20
+ const isHttpOrHttpsUrl = (s) => {
21
+ try {
22
+ return ["http:", "https:"].includes(new URL(s).protocol);
23
+ } catch {
24
+ return false;
25
+ }
26
+ };
27
+ const bridgeValidatorSchema = _arcblock_validator.v.object({
28
+ pk: _arcblock_validator.v.string(),
29
+ address: ethDidSchema,
30
+ endpoint: _arcblock_validator.v.pipe(_arcblock_validator.v.string(), _arcblock_validator.v.check(isHttpOrHttpsUrl, "Must be a valid HTTP/HTTPS URL"))
31
+ });
32
+ /** Row schema of a v2 bridge: the v1 stake / block / fee checks do not apply (those fields must be zero or empty). */
33
+ const bridgeSchema = _arcblock_validator.v.pipe(_arcblock_validator.v.object({
34
+ address: (0, _arcblock_validator.vDID)({
35
+ prefix: true,
36
+ role: "ROLE_ROLLUP"
37
+ }),
38
+ tokenAddress: (0, _arcblock_validator.vDID)({
39
+ prefix: true,
40
+ role: "ROLE_TOKEN"
41
+ }),
42
+ contractAddress: ethDidSchema,
43
+ vaultAddress: _arcblock_validator.v.optional(_arcblock_validator.v.nullable(_arcblock_validator.v.string())),
44
+ migrateHistory: _arcblock_validator.v.optional(_arcblock_validator.v.array(ethDidSchema), []),
45
+ vaultHistory: _arcblock_validator.v.optional(_arcblock_validator.v.array(ethVaultDidSchema), []),
46
+ paused: _arcblock_validator.v.optional(_arcblock_validator.v.boolean(), false),
47
+ closed: _arcblock_validator.v.optional(_arcblock_validator.v.boolean(), false),
48
+ seedValidators: _arcblock_validator.v.pipe(_arcblock_validator.v.array(bridgeValidatorSchema), _arcblock_validator.v.minLength(1), _arcblock_validator.v.maxLength(1)),
49
+ validators: _arcblock_validator.v.optional(_arcblock_validator.v.pipe(_arcblock_validator.v.array(bridgeValidatorSchema), _arcblock_validator.v.maxLength(24)), []),
50
+ minSignerCount: _arcblock_validator.v.pipe(_arcblock_validator.v.number(), _arcblock_validator.v.integer(), _arcblock_validator.v.minValue(1)),
51
+ maxSignerCount: _arcblock_validator.v.pipe(_arcblock_validator.v.number(), _arcblock_validator.v.integer(), _arcblock_validator.v.minValue(1), _arcblock_validator.v.maxValue(16)),
52
+ minBlockConfirmation: _arcblock_validator.v.pipe(_arcblock_validator.v.number(), _arcblock_validator.v.integer(), _arcblock_validator.v.minValue(1), _arcblock_validator.v.maxValue(100)),
53
+ issuer: (0, _arcblock_validator.vDID)({ prefix: true }),
54
+ minStakeAmount: _arcblock_validator.v.optional(_arcblock_validator.v.any()),
55
+ maxStakeAmount: _arcblock_validator.v.optional(_arcblock_validator.v.any()),
56
+ minBlockSize: _arcblock_validator.v.optional(_arcblock_validator.v.any()),
57
+ maxBlockSize: _arcblock_validator.v.optional(_arcblock_validator.v.any()),
58
+ minBlockInterval: _arcblock_validator.v.optional(_arcblock_validator.v.any()),
59
+ minDepositAmount: _arcblock_validator.v.optional(_arcblock_validator.v.any()),
60
+ maxDepositAmount: _arcblock_validator.v.optional(_arcblock_validator.v.any()),
61
+ minWithdrawAmount: _arcblock_validator.v.optional(_arcblock_validator.v.any()),
62
+ maxWithdrawAmount: _arcblock_validator.v.optional(_arcblock_validator.v.any()),
63
+ depositFeeRate: _arcblock_validator.v.optional(_arcblock_validator.v.any()),
64
+ withdrawFeeRate: _arcblock_validator.v.optional(_arcblock_validator.v.any()),
65
+ proposerFeeShare: _arcblock_validator.v.optional(_arcblock_validator.v.any()),
66
+ publisherFeeShare: _arcblock_validator.v.optional(_arcblock_validator.v.any()),
67
+ minDepositFee: _arcblock_validator.v.optional(_arcblock_validator.v.any()),
68
+ maxDepositFee: _arcblock_validator.v.optional(_arcblock_validator.v.any()),
69
+ minWithdrawFee: _arcblock_validator.v.optional(_arcblock_validator.v.any()),
70
+ maxWithdrawFee: _arcblock_validator.v.optional(_arcblock_validator.v.any()),
71
+ blockHeight: _arcblock_validator.v.optional(_arcblock_validator.v.any()),
72
+ blockHash: _arcblock_validator.v.optional(_arcblock_validator.v.any()),
73
+ leaveWaitingPeriod: _arcblock_validator.v.optional(_arcblock_validator.v.any()),
74
+ publishWaitingPeriod: _arcblock_validator.v.optional(_arcblock_validator.v.any()),
75
+ publishSlashRate: _arcblock_validator.v.optional(_arcblock_validator.v.any()),
76
+ context: _arcblock_validator.schemas.context,
77
+ data: _arcblock_validator.v.any()
78
+ }), (0, _arcblock_validator.vStripUnknown)());
79
+ const BRIDGE_ZERO_DEFAULTS = {
80
+ minStakeAmount: "0",
81
+ maxStakeAmount: "0",
82
+ minBlockSize: 0,
83
+ maxBlockSize: 0,
84
+ minBlockInterval: 0,
85
+ minDepositAmount: "0",
86
+ maxDepositAmount: "0",
87
+ minWithdrawAmount: "0",
88
+ maxWithdrawAmount: "0",
89
+ depositFeeRate: 0,
90
+ withdrawFeeRate: 0,
91
+ proposerFeeShare: 0,
92
+ publisherFeeShare: 0,
93
+ minDepositFee: "0",
94
+ maxDepositFee: "0",
95
+ minWithdrawFee: "0",
96
+ maxWithdrawFee: "0",
97
+ blockHeight: 0,
98
+ blockHash: "",
99
+ leaveWaitingPeriod: 0,
100
+ publishWaitingPeriod: 0,
101
+ publishSlashRate: 0
102
+ };
103
+ const BRIDGE_ROW_KEYS = [
104
+ "address",
105
+ "tokenAddress",
106
+ "vaultAddress",
107
+ "contractAddress",
108
+ "seedValidators",
109
+ "validators",
110
+ "minSignerCount",
111
+ "maxSignerCount",
112
+ "minBlockConfirmation",
113
+ "issuer",
114
+ "data"
115
+ ];
116
+ const createBridge = (attrs, context) => {
117
+ require_states_rollup_v2.assertV1FieldsUnused(attrs, "INVALID_ROLLUP_PROPS");
118
+ const row = {
119
+ context: require_contexts_state.create(context),
120
+ paused: false,
121
+ closed: false,
122
+ migrateHistory: [],
123
+ vaultHistory: [],
124
+ ...BRIDGE_ZERO_DEFAULTS,
125
+ ...(0, lodash_pick.default)(attrs, BRIDGE_ROW_KEYS)
126
+ };
127
+ row.address = (0, _ocap_util.toAddress)(row.address);
128
+ return validateBridge(row);
129
+ };
130
+ /** Update of a v2 row. Only fields a v2 governance tx may touch are copied; the transition rules run on the result. */
131
+ const updateBridge = (state, updates, context) => {
132
+ require_states_rollup_v2.assertV1FieldsUnused(updates, "INVALID_ROLLUP_UPDATE");
133
+ const next = {
134
+ ...state,
135
+ ...(0, lodash_pick.default)(updates, [
136
+ "validators",
137
+ "seedValidators",
138
+ "minSignerCount",
139
+ "maxSignerCount",
140
+ "minBlockConfirmation",
141
+ "data",
142
+ "paused",
143
+ "closed",
144
+ "vaultAddress",
145
+ "vaultHistory"
146
+ ]),
147
+ context: require_contexts_state.update(state.context, context)
148
+ };
149
+ require_states_rollup_v2.assertBridgeTransition(state, next, context?.txTime ? require_states_rollup_v2.toSeconds(context.txTime) : null);
150
+ return validateBridge(next);
151
+ };
152
+ const validateBridge = (state) => {
153
+ const { value, error } = (0, _arcblock_validator.vValidate)(bridgeSchema, state);
154
+ if (error) throw new _ocap_util_lib_error.CustomError("INVALID_ROLLUP_PROPS", error.details.map((x) => x.message).join(", "));
155
+ require_states_rollup_v2.assertV1FieldsUnused(value, "INVALID_ROLLUP_PROPS");
156
+ const body = require_states_rollup_v2.getBridgeBody(value);
157
+ require_states_rollup_v2.validateBridgeBody(body);
158
+ if (body.pendingOwner) validateBridge(require_states_rollup_v2.materializeBridgeAt(value, body.pendingOwner.effectiveAt));
159
+ if (value.seedValidators.length !== 1 || value.seedValidators[0].address.toLowerCase() !== body.owner.toLowerCase()) throw new _ocap_util_lib_error.CustomError("INVALID_ROLLUP_PROPS", "seed_validators must be the bridge owner alone");
160
+ if (value.paused === false && body.lonePause !== null) throw new _ocap_util_lib_error.CustomError("INVALID_ROLLUP_PROPS", "lonePause requires paused");
161
+ if (value.closed && body.closingAt === null) throw new _ocap_util_lib_error.CustomError("INVALID_ROLLUP_PROPS", "a closed bridge needs closingAt");
162
+ if (!value.closed && body.closingAt !== null) throw new _ocap_util_lib_error.CustomError("INVALID_ROLLUP_PROPS", "closingAt requires closed");
163
+ return value;
164
+ };
165
+
166
+ //#endregion
167
+ exports.bridgeSchema = bridgeSchema;
168
+ exports.createBridge = createBridge;
169
+ exports.updateBridge = updateBridge;
170
+ exports.validateBridge = validateBridge;
@@ -0,0 +1,78 @@
1
+ import { StateContextInput } from "../contexts/state.cjs";
2
+ import { IRollupState } from "@ocap/types";
3
+ import { v } from "@arcblock/validator";
4
+
5
+ //#region src/states/rollup-bridge.d.ts
6
+
7
+ /** Row schema of a v2 bridge: the v1 stake / block / fee checks do not apply (those fields must be zero or empty). */
8
+ declare const bridgeSchema: v.SchemaWithPipe<readonly [v.ObjectSchema<{
9
+ readonly address: any;
10
+ readonly tokenAddress: any;
11
+ readonly contractAddress: any;
12
+ readonly vaultAddress: v.OptionalSchema<v.NullableSchema<v.StringSchema<undefined>, undefined>, undefined>;
13
+ readonly migrateHistory: v.OptionalSchema<v.ArraySchema<any, undefined>, readonly []>;
14
+ readonly vaultHistory: v.OptionalSchema<v.ArraySchema<any, undefined>, readonly []>;
15
+ readonly paused: v.OptionalSchema<v.BooleanSchema<undefined>, false>;
16
+ readonly closed: v.OptionalSchema<v.BooleanSchema<undefined>, false>;
17
+ readonly seedValidators: v.SchemaWithPipe<readonly [v.ArraySchema<v.ObjectSchema<{
18
+ readonly pk: v.StringSchema<undefined>;
19
+ readonly address: any;
20
+ readonly endpoint: v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.CheckAction<string, "Must be a valid HTTP/HTTPS URL">]>;
21
+ }, undefined>, undefined>, v.MinLengthAction<{
22
+ pk: string;
23
+ readonly address?: any;
24
+ endpoint: string;
25
+ }[], 1, undefined>, v.MaxLengthAction<{
26
+ pk: string;
27
+ readonly address?: any;
28
+ endpoint: string;
29
+ }[], 1, undefined>]>;
30
+ readonly validators: v.OptionalSchema<v.SchemaWithPipe<readonly [v.ArraySchema<v.ObjectSchema<{
31
+ readonly pk: v.StringSchema<undefined>;
32
+ readonly address: any;
33
+ readonly endpoint: v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.CheckAction<string, "Must be a valid HTTP/HTTPS URL">]>;
34
+ }, undefined>, undefined>, v.MaxLengthAction<{
35
+ pk: string;
36
+ readonly address?: any;
37
+ endpoint: string;
38
+ }[], 24, undefined>]>, readonly []>;
39
+ readonly minSignerCount: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.IntegerAction<number, undefined>, v.MinValueAction<number, 1, undefined>]>;
40
+ readonly maxSignerCount: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.IntegerAction<number, undefined>, v.MinValueAction<number, 1, undefined>, v.MaxValueAction<number, 16, undefined>]>;
41
+ readonly minBlockConfirmation: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.IntegerAction<number, undefined>, v.MinValueAction<number, 1, undefined>, v.MaxValueAction<number, 100, undefined>]>;
42
+ readonly issuer: any;
43
+ readonly minStakeAmount: v.OptionalSchema<v.AnySchema, undefined>;
44
+ readonly maxStakeAmount: v.OptionalSchema<v.AnySchema, undefined>;
45
+ readonly minBlockSize: v.OptionalSchema<v.AnySchema, undefined>;
46
+ readonly maxBlockSize: v.OptionalSchema<v.AnySchema, undefined>;
47
+ readonly minBlockInterval: v.OptionalSchema<v.AnySchema, undefined>;
48
+ readonly minDepositAmount: v.OptionalSchema<v.AnySchema, undefined>;
49
+ readonly maxDepositAmount: v.OptionalSchema<v.AnySchema, undefined>;
50
+ readonly minWithdrawAmount: v.OptionalSchema<v.AnySchema, undefined>;
51
+ readonly maxWithdrawAmount: v.OptionalSchema<v.AnySchema, undefined>;
52
+ readonly depositFeeRate: v.OptionalSchema<v.AnySchema, undefined>;
53
+ readonly withdrawFeeRate: v.OptionalSchema<v.AnySchema, undefined>;
54
+ readonly proposerFeeShare: v.OptionalSchema<v.AnySchema, undefined>;
55
+ readonly publisherFeeShare: v.OptionalSchema<v.AnySchema, undefined>;
56
+ readonly minDepositFee: v.OptionalSchema<v.AnySchema, undefined>;
57
+ readonly maxDepositFee: v.OptionalSchema<v.AnySchema, undefined>;
58
+ readonly minWithdrawFee: v.OptionalSchema<v.AnySchema, undefined>;
59
+ readonly maxWithdrawFee: v.OptionalSchema<v.AnySchema, undefined>;
60
+ readonly blockHeight: v.OptionalSchema<v.AnySchema, undefined>;
61
+ readonly blockHash: v.OptionalSchema<v.AnySchema, undefined>;
62
+ readonly leaveWaitingPeriod: v.OptionalSchema<v.AnySchema, undefined>;
63
+ readonly publishWaitingPeriod: v.OptionalSchema<v.AnySchema, undefined>;
64
+ readonly publishSlashRate: v.OptionalSchema<v.AnySchema, undefined>;
65
+ readonly context: v.ObjectSchema<{
66
+ readonly genesisTime: v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.CheckAction<string, "Must be valid ISO date">]>;
67
+ readonly genesisTx: v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.CheckAction<string, "Must match tx hash pattern or be empty">]>;
68
+ readonly renaissanceTime: v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.CheckAction<string, "Must be valid ISO date">]>;
69
+ readonly renaissanceTx: v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.CheckAction<string, "Must match tx hash pattern or be empty">]>;
70
+ }, undefined>;
71
+ readonly data: v.AnySchema;
72
+ }, undefined>, any]>;
73
+ declare const createBridge: (attrs: Partial<IRollupState> & Record<string, any>, context: StateContextInput) => IRollupState;
74
+ /** Update of a v2 row. Only fields a v2 governance tx may touch are copied; the transition rules run on the result. */
75
+ declare const updateBridge: (state: IRollupState, updates: Partial<IRollupState> & Record<string, any>, context: StateContextInput) => IRollupState;
76
+ declare const validateBridge: (state: IRollupState & Record<string, any>) => IRollupState;
77
+ //#endregion
78
+ export { bridgeSchema, createBridge, updateBridge, validateBridge };