@ocap/state 1.31.8 → 1.32.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/esm/index.d.mts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { account_d_exports, parseNonceBn } from "./states/account.mjs";
2
2
  import { asset_d_exports } from "./states/asset.mjs";
3
- import { ChainState, chain_d_exports } from "./states/chain.mjs";
3
+ import { ChainState, chain_d_exports, tryDeriveProtobufTokenAddress } from "./states/chain.mjs";
4
4
  import { delegation_d_exports } from "./states/delegation.mjs";
5
5
  import { evidence_d_exports } from "./states/evidence.mjs";
6
6
  import { factory_d_exports } from "./states/factory.mjs";
@@ -17,4 +17,4 @@ import Blacklist, { BlacklistOptions, TrustedAccountConfig } from "./states/blac
17
17
  declare const indexes: readonly ["account", "asset", "delegation", "tx", "factory", "token", "stake", "rollup", "rollupBlock", "rollupValidator", "tokenDistribution", "tokenFactory"];
18
18
  declare const tables: readonly ["chain", "account", "asset", "delegation", "tx", "factory", "token", "stake", "rollup", "rollupBlock", "evidence", "balance", "tokenFactory"];
19
19
  //#endregion
20
- export { Blacklist, type BlacklistOptions, type ChainState, type ItxJson, type Receipt, type ReceiptChange, type RollupTargetType, type RollupTokenReserve, TOKEN_CHARTER_KIND, type TokenCharterAssetPayload, type TokenInput, type TrustedAccountConfig, type TxContext, type TxData, type TxInput, type TxOutput, type TxResult, VALID_ROLLUP_TARGET_TYPES, account_d_exports as account, asset_d_exports as asset, buildTokenCharterAssetData, buildTokenCharterAssetState, chain_d_exports as chain, delegation_d_exports as delegation, evidence_d_exports as evidence, extractTokenUpdatesFromCharterAsset, factory_d_exports as factory, getRollupSupportedTokens, getRollupTargetType, getRollupTokenReserve, hasRollupReserveTracking, iconToNftDisplay, indexes, isProposerSponsoredDepositAllowed, isTokenCharterAsset, isTokenSupportedByRollup, isValidRollupContractAddress, isValidRollupTargetType, isValidRollupValidatorAddress, migrateTokensToCharterAssets, normalizeLegacyTokenStateForUpdate, parseNonceBn, recordRollupDeposit, recordRollupWithdraw, resolveCharterMoniker, rollup_d_exports as rollup, rollup_block_d_exports as rollupBlock, sanitizeTokenSvg, stake_d_exports as stake, syncCharterAssetWithToken, syncTokenCharterOwnership, tables, toTokenCharterAssetAddress, token_d_exports as token, token_factory_d_exports as tokenFactory, tx_d_exports as tx, websiteToNftEndpoint };
20
+ export { Blacklist, type BlacklistOptions, type ChainState, type ItxJson, type Receipt, type ReceiptChange, type RollupTargetType, type RollupTokenReserve, TOKEN_CHARTER_KIND, type TokenCharterAssetPayload, type TokenInput, type TrustedAccountConfig, type TxContext, type TxData, type TxInput, type TxOutput, type TxResult, VALID_ROLLUP_TARGET_TYPES, account_d_exports as account, asset_d_exports as asset, buildTokenCharterAssetData, buildTokenCharterAssetState, chain_d_exports as chain, delegation_d_exports as delegation, evidence_d_exports as evidence, extractTokenUpdatesFromCharterAsset, factory_d_exports as factory, getRollupSupportedTokens, getRollupTargetType, getRollupTokenReserve, hasRollupReserveTracking, iconToNftDisplay, indexes, isProposerSponsoredDepositAllowed, isTokenCharterAsset, isTokenSupportedByRollup, isValidRollupContractAddress, isValidRollupTargetType, isValidRollupValidatorAddress, migrateTokensToCharterAssets, normalizeLegacyTokenStateForUpdate, parseNonceBn, recordRollupDeposit, recordRollupWithdraw, resolveCharterMoniker, rollup_d_exports as rollup, rollup_block_d_exports as rollupBlock, sanitizeTokenSvg, stake_d_exports as stake, syncCharterAssetWithToken, syncTokenCharterOwnership, tables, toTokenCharterAssetAddress, token_d_exports as token, token_factory_d_exports as tokenFactory, tryDeriveProtobufTokenAddress, tx_d_exports as tx, websiteToNftEndpoint };
package/esm/index.mjs CHANGED
@@ -1,6 +1,6 @@
1
1
  import { account_exports, parseNonceBn } from "./states/account.mjs";
2
2
  import { asset_exports } from "./states/asset.mjs";
3
- import { chain_exports } from "./states/chain.mjs";
3
+ import { chain_exports, tryDeriveProtobufTokenAddress } from "./states/chain.mjs";
4
4
  import { delegation_exports } from "./states/delegation.mjs";
5
5
  import { evidence_exports } from "./states/evidence.mjs";
6
6
  import { factory_exports } from "./states/factory.mjs";
@@ -44,4 +44,4 @@ const tables = [
44
44
  ];
45
45
 
46
46
  //#endregion
47
- export { blacklist_default as Blacklist, TOKEN_CHARTER_KIND, VALID_ROLLUP_TARGET_TYPES, account_exports as account, asset_exports as asset, buildTokenCharterAssetData, buildTokenCharterAssetState, chain_exports as chain, delegation_exports as delegation, evidence_exports as evidence, extractTokenUpdatesFromCharterAsset, factory_exports as factory, getRollupSupportedTokens, getRollupTargetType, getRollupTokenReserve, hasRollupReserveTracking, iconToNftDisplay, indexes, isProposerSponsoredDepositAllowed, isTokenCharterAsset, isTokenSupportedByRollup, isValidRollupContractAddress, isValidRollupTargetType, isValidRollupValidatorAddress, migrateTokensToCharterAssets, normalizeLegacyTokenStateForUpdate, parseNonceBn, recordRollupDeposit, recordRollupWithdraw, resolveCharterMoniker, rollup_exports as rollup, rollup_block_exports as rollupBlock, sanitizeTokenSvg, stake_exports as stake, syncCharterAssetWithToken, syncTokenCharterOwnership, tables, toTokenCharterAssetAddress, token_exports as token, token_factory_exports as tokenFactory, tx_exports as tx, websiteToNftEndpoint };
47
+ export { blacklist_default as Blacklist, TOKEN_CHARTER_KIND, VALID_ROLLUP_TARGET_TYPES, account_exports as account, asset_exports as asset, buildTokenCharterAssetData, buildTokenCharterAssetState, chain_exports as chain, delegation_exports as delegation, evidence_exports as evidence, extractTokenUpdatesFromCharterAsset, factory_exports as factory, getRollupSupportedTokens, getRollupTargetType, getRollupTokenReserve, hasRollupReserveTracking, iconToNftDisplay, indexes, isProposerSponsoredDepositAllowed, isTokenCharterAsset, isTokenSupportedByRollup, isValidRollupContractAddress, isValidRollupTargetType, isValidRollupValidatorAddress, migrateTokensToCharterAssets, normalizeLegacyTokenStateForUpdate, parseNonceBn, recordRollupDeposit, recordRollupWithdraw, resolveCharterMoniker, rollup_exports as rollup, rollup_block_exports as rollupBlock, sanitizeTokenSvg, stake_exports as stake, syncCharterAssetWithToken, syncTokenCharterOwnership, tables, toTokenCharterAssetAddress, token_exports as token, token_factory_exports as tokenFactory, tryDeriveProtobufTokenAddress, tx_exports as tx, websiteToNftEndpoint };
@@ -58,9 +58,10 @@ var Blacklist = class {
58
58
  }
59
59
  dump() {
60
60
  try {
61
+ if (!this.dumpPath) return;
61
62
  const exported = this.filter.saveAsJSON();
62
- const tmpFile = `${this.dumpPath}~`;
63
- fs.writeFileSync(tmpFile, JSON.stringify(exported));
63
+ const tmpFile = `${this.dumpPath}.${process.pid}.${Date.now()}.${Math.random().toString(36).slice(2, 8)}.tmp`;
64
+ fs.writeFileSync(tmpFile, JSON.stringify(exported), { mode: 384 });
64
65
  fs.renameSync(tmpFile, this.dumpPath);
65
66
  } catch (_err) {}
66
67
  }
@@ -2,7 +2,7 @@ import { StateContext } from "../contexts/state.mjs";
2
2
 
3
3
  //#region src/states/chain.d.ts
4
4
  declare namespace chain_d_exports {
5
- export { ChainState, create, update };
5
+ export { ChainState, create, tryDeriveProtobufTokenAddress, update };
6
6
  }
7
7
  interface ChainState {
8
8
  address?: string;
@@ -12,18 +12,24 @@ interface ChainState {
12
12
  moderator?: unknown;
13
13
  accounts?: unknown;
14
14
  token?: {
15
+ address?: string;
15
16
  symbol?: string;
16
17
  decimal?: number;
17
18
  name?: string;
18
19
  description?: string;
19
20
  unit?: string;
20
- totalSupply?: string;
21
- initialSupply?: string;
21
+ totalSupply?: string | number;
22
+ initialSupply?: string | number;
22
23
  foreignToken?: unknown;
23
24
  };
24
25
  vaults?: unknown;
25
26
  context: StateContext;
26
27
  }
28
+ /**
29
+ * Pure helper mirroring `Config.genTokenItx` (`core/config/src/index.ts`) byte-for-byte (#1811).
30
+ * Returns `null` when `token` or `issuer` is incomplete (e.g., partial unit-test mocks).
31
+ */
32
+ declare const tryDeriveProtobufTokenAddress: (token: ChainState["token"] | undefined, issuer: string | undefined) => string | null;
27
33
  declare const create: (attrs: Partial<ChainState> & {
28
34
  context?: {
29
35
  txTime?: string;
@@ -35,4 +41,4 @@ declare const create: (attrs: Partial<ChainState> & {
35
41
  }) => ChainState;
36
42
  declare const update: (state: ChainState, updates: Partial<ChainState>) => ChainState;
37
43
  //#endregion
38
- export { ChainState, chain_d_exports, create, update };
44
+ export { ChainState, chain_d_exports, create, tryDeriveProtobufTokenAddress, update };
@@ -1,15 +1,44 @@
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 { fromTokenToUnit } from "@ocap/util";
3
4
  import { CustomError } from "@ocap/util/lib/error";
4
5
  import pick from "lodash/pick.js";
6
+ import { toTokenAddress } from "@arcblock/did-util";
5
7
  import get from "lodash/get.js";
6
8
  import isEqual from "lodash/isEqual.js";
7
9
 
8
10
  //#region src/states/chain.ts
9
11
  var chain_exports = /* @__PURE__ */ __exportAll({
10
12
  create: () => create,
13
+ tryDeriveProtobufTokenAddress: () => tryDeriveProtobufTokenAddress,
11
14
  update: () => update
12
15
  });
16
+ /**
17
+ * Pure helper mirroring `Config.genTokenItx` (`core/config/src/index.ts`) byte-for-byte (#1811).
18
+ * Returns `null` when `token` or `issuer` is incomplete (e.g., partial unit-test mocks).
19
+ */
20
+ const tryDeriveProtobufTokenAddress = (token, issuer) => {
21
+ try {
22
+ if (!token || typeof token !== "object" || typeof issuer !== "string" || !issuer.trim()) return null;
23
+ if (typeof token.name !== "string" || typeof token.description !== "string" || typeof token.symbol !== "string" || typeof token.unit !== "string" || typeof token.decimal !== "number" || !Number.isFinite(token.decimal) || token.totalSupply === void 0 || token.totalSupply === null || token.totalSupply === "") return null;
24
+ const totalSupply = fromTokenToUnit(token.totalSupply, token.decimal).toString();
25
+ const initialSupply = fromTokenToUnit(token.initialSupply !== void 0 && token.initialSupply !== null && token.initialSupply !== "" ? token.initialSupply : token.totalSupply, token.decimal).toString();
26
+ const derived = toTokenAddress({
27
+ name: token.name,
28
+ description: token.description,
29
+ symbol: token.symbol,
30
+ unit: token.unit,
31
+ decimal: token.decimal,
32
+ totalSupply,
33
+ initialSupply,
34
+ issuer,
35
+ foreignToken: token.foreignToken ?? void 0
36
+ }, "protobuf");
37
+ return typeof derived === "string" && derived ? derived : null;
38
+ } catch {
39
+ return null;
40
+ }
41
+ };
13
42
  const create = (attrs, contextArg) => {
14
43
  return {
15
44
  context: create$1({
@@ -28,6 +57,17 @@ const create = (attrs, contextArg) => {
28
57
  ])
29
58
  };
30
59
  };
60
+ const normalizeForeignTokenForCompare = (value) => {
61
+ if (!value || typeof value !== "object") return value;
62
+ const ft = value;
63
+ const chainType = typeof ft.chainType === "string" ? ft.chainType.toLowerCase() : "";
64
+ const contractAddress = ft.contractAddress;
65
+ if (chainType !== "ocap" && chainType !== "abt" && typeof contractAddress === "string" && /^0x[0-9a-fA-F]{40}$/.test(contractAddress)) return {
66
+ ...ft,
67
+ contractAddress: contractAddress.toLowerCase()
68
+ };
69
+ return value;
70
+ };
31
71
  const update = (state, updates) => {
32
72
  const immutableAttrs = [
33
73
  "chainId",
@@ -35,8 +75,16 @@ const update = (state, updates) => {
35
75
  "token.symbol",
36
76
  "token.decimal"
37
77
  ];
38
- if (!process.env.CHAIN_TOKEN_ADDRESS) immutableAttrs.push("token.name", "token.description", "token.unit", "token.totalSupply", "token.initialSupply", "token.foreignToken");
39
- for (const attr of immutableAttrs) if (get(updates, attr) && !isEqual(get(updates, attr), get(state, attr))) throw new CustomError("FORBIDDEN", `Cannot update ${attr} field on chain state`);
78
+ if (state.token?.address) immutableAttrs.push("token.address");
79
+ const moderatorAddr = state.moderator && typeof state.moderator === "object" ? state.moderator.address : void 0;
80
+ const derivedFromState = tryDeriveProtobufTokenAddress(state.token, moderatorAddr);
81
+ if (!(Boolean(process.env.CHAIN_TOKEN_ADDRESS) || Boolean(state.token?.address) && derivedFromState !== null && state.token.address !== derivedFromState)) immutableAttrs.push("token.name", "token.description", "token.unit", "token.totalSupply", "token.initialSupply", "token.foreignToken");
82
+ for (const attr of immutableAttrs) {
83
+ const updatedAttr = get(updates, attr);
84
+ if (attr === "token.address" ? updatedAttr === void 0 : !updatedAttr) continue;
85
+ const currentAttr = get(state, attr);
86
+ if (!(attr === "token.foreignToken" ? isEqual(normalizeForeignTokenForCompare(updatedAttr), normalizeForeignTokenForCompare(currentAttr)) : isEqual(updatedAttr, currentAttr))) throw new CustomError("FORBIDDEN", `Cannot update ${attr} field on chain state`);
87
+ }
40
88
  const context = { txTime: updates?.context?.txTime || (/* @__PURE__ */ new Date()).toISOString() };
41
89
  return {
42
90
  ...state,
@@ -52,4 +100,4 @@ const update = (state, updates) => {
52
100
  };
53
101
 
54
102
  //#endregion
55
- export { chain_exports, create, update };
103
+ export { chain_exports, create, tryDeriveProtobufTokenAddress, update };
@@ -7,7 +7,7 @@ declare namespace evidence_d_exports {
7
7
  export { create, schema, validate };
8
8
  }
9
9
  declare const schema: v.SchemaWithPipe<readonly [v.ObjectSchema<{
10
- readonly hash: v.UnionSchema<[v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.RegexAction<string, undefined>]>, v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.RegexAction<string, undefined>]>], undefined>;
10
+ readonly hash: v.UnionSchema<[v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.RegexAction<string, undefined>]>, v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.RegexAction<string, undefined>]>, v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.RegexAction<string, undefined>]>], undefined>;
11
11
  readonly context: v.ObjectSchema<{
12
12
  readonly genesisTime: v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.CheckAction<string, "Must be valid ISO date">]>;
13
13
  readonly genesisTx: v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.CheckAction<string, "Must match tx hash pattern or be empty">]>;
@@ -3,7 +3,7 @@ import { create as create$1 } from "../contexts/state.mjs";
3
3
  import { CustomError } from "@ocap/util/lib/error";
4
4
  import pick from "lodash/pick.js";
5
5
  import { patterns, schemas, v, vStripUnknown, vValidate } from "@arcblock/validator";
6
- import { BRIDGE_RELEASE_KEY_PATTERN } from "@ocap/mcrypto";
6
+ import { BRIDGE_GOV_KEY_PATTERN, BRIDGE_RELEASE_KEY_PATTERN } from "@ocap/mcrypto";
7
7
 
8
8
  //#region src/states/evidence.ts
9
9
  var evidence_exports = /* @__PURE__ */ __exportAll({
@@ -12,7 +12,11 @@ var evidence_exports = /* @__PURE__ */ __exportAll({
12
12
  validate: () => validate
13
13
  });
14
14
  const schema = v.pipe(v.object({
15
- hash: v.union([v.pipe(v.string(), v.regex(patterns.txHash)), v.pipe(v.string(), v.regex(BRIDGE_RELEASE_KEY_PATTERN))]),
15
+ hash: v.union([
16
+ v.pipe(v.string(), v.regex(patterns.txHash)),
17
+ v.pipe(v.string(), v.regex(BRIDGE_RELEASE_KEY_PATTERN)),
18
+ v.pipe(v.string(), v.regex(BRIDGE_GOV_KEY_PATTERN))
19
+ ]),
16
20
  context: schemas.context,
17
21
  data: v.optional(v.nullable(v.any()))
18
22
  }), vStripUnknown());
@@ -8,32 +8,32 @@ import { IRollupState } from "@ocap/types";
8
8
  declare const bridgeSchema: v.SchemaWithPipe<readonly [v.ObjectSchema<{
9
9
  readonly address: any;
10
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 []>;
11
+ readonly contractAddress: v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.CheckAction<string, v.ErrorMessage<v.CheckIssue<TInput$1>> | undefined>, any]>;
12
+ readonly vaultAddress: v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.CheckAction<string, v.ErrorMessage<v.CheckIssue<TInput$1>> | undefined>, any]>;
13
+ readonly migrateHistory: v.OptionalSchema<v.ArraySchema<v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.CheckAction<string, v.ErrorMessage<v.CheckIssue<TInput$1>> | undefined>, any]>, undefined>, readonly []>;
14
+ readonly vaultHistory: v.OptionalSchema<v.ArraySchema<v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.CheckAction<string, v.ErrorMessage<v.CheckIssue<TInput$1>> | undefined>, any]>, undefined>, readonly []>;
15
15
  readonly paused: v.OptionalSchema<v.BooleanSchema<undefined>, false>;
16
16
  readonly closed: v.OptionalSchema<v.BooleanSchema<undefined>, false>;
17
17
  readonly seedValidators: v.SchemaWithPipe<readonly [v.ArraySchema<v.ObjectSchema<{
18
18
  readonly pk: v.StringSchema<undefined>;
19
- readonly address: any;
19
+ readonly address: v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.CheckAction<string, v.ErrorMessage<v.CheckIssue<TInput$1>> | undefined>, any]>;
20
20
  readonly endpoint: v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.CheckAction<string, "Must be a valid HTTP/HTTPS URL">]>;
21
21
  }, undefined>, undefined>, v.MinLengthAction<{
22
22
  pk: string;
23
- readonly address?: any;
23
+ readonly address: any;
24
24
  endpoint: string;
25
25
  }[], 1, undefined>, v.MaxLengthAction<{
26
26
  pk: string;
27
- readonly address?: any;
27
+ readonly address: any;
28
28
  endpoint: string;
29
29
  }[], 1, undefined>]>;
30
30
  readonly validators: v.OptionalSchema<v.SchemaWithPipe<readonly [v.ArraySchema<v.ObjectSchema<{
31
31
  readonly pk: v.StringSchema<undefined>;
32
- readonly address: any;
32
+ readonly address: v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.CheckAction<string, v.ErrorMessage<v.CheckIssue<TInput$1>> | undefined>, any]>;
33
33
  readonly endpoint: v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.CheckAction<string, "Must be a valid HTTP/HTTPS URL">]>;
34
34
  }, undefined>, undefined>, v.MaxLengthAction<{
35
35
  pk: string;
36
- readonly address?: any;
36
+ readonly address: any;
37
37
  endpoint: string;
38
38
  }[], 24, undefined>]>, readonly []>;
39
39
  readonly minSignerCount: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.IntegerAction<number, undefined>, v.MinValueAction<number, 1, undefined>]>;
@@ -1,5 +1,5 @@
1
1
  import { create, update } from "../contexts/state.mjs";
2
- import { assertBridgeTransition, assertV1FieldsUnused, getBridgeBody, materializeBridgeAt, toSeconds, validateBridgeBody } from "./rollup-v2.mjs";
2
+ import { assertBridgeTransition, assertV1FieldsUnused, bareEthAddress, getBridgeBody, materializeBridgeAt, toSeconds, validateBridgeBody } from "./rollup-v2.mjs";
3
3
  import { toAddress } from "@ocap/util";
4
4
  import { CustomError } from "@ocap/util/lib/error";
5
5
  import pick from "lodash/pick.js";
@@ -10,11 +10,13 @@ import { schemas, v, vDID, vStripUnknown, vValidate } from "@arcblock/validator"
10
10
  * v2 bridge rows (bridge/docs/ocap-protocols.md §v2.1): create / update / validate of a `RollupState` whose
11
11
  * `data.value.version == 2`. Kept apart from `rollup.ts` so the v1 code path stays byte-for-byte what it was.
12
12
  */
13
- const ethDidSchema = vDID({
13
+ const ZERO_ETH_ADDRESS = "0x0000000000000000000000000000000000000000";
14
+ const noSurroundingWhitespace = v.check((s) => s === s.trim(), "Must not have leading or trailing whitespace");
15
+ const ethDidSchema = v.pipe(v.string(), noSurroundingWhitespace, vDID({
14
16
  prefix: true,
15
17
  wallet: "ethereum"
16
- });
17
- const ethVaultDidSchema = vDID({ wallet: "ethereum" });
18
+ }));
19
+ const ethVaultDidSchema = v.pipe(v.string(), noSurroundingWhitespace, vDID({ wallet: "ethereum" }));
18
20
  const isHttpOrHttpsUrl = (s) => {
19
21
  try {
20
22
  return ["http:", "https:"].includes(new URL(s).protocol);
@@ -38,7 +40,7 @@ const bridgeSchema = v.pipe(v.object({
38
40
  role: "ROLE_TOKEN"
39
41
  }),
40
42
  contractAddress: ethDidSchema,
41
- vaultAddress: v.optional(v.nullable(v.string())),
43
+ vaultAddress: ethVaultDidSchema,
42
44
  migrateHistory: v.optional(v.array(ethDidSchema), []),
43
45
  vaultHistory: v.optional(v.array(ethVaultDidSchema), []),
44
46
  paused: v.optional(v.boolean(), false),
@@ -153,6 +155,19 @@ const validateBridge = (state) => {
153
155
  assertV1FieldsUnused(value, "INVALID_ROLLUP_PROPS");
154
156
  const body = getBridgeBody(value);
155
157
  validateBridgeBody(body);
158
+ const ethToken = bareEthAddress(value.contractAddress);
159
+ const ethVault = bareEthAddress(value.vaultAddress);
160
+ const ethGateway = bareEthAddress(body.gateway);
161
+ if (ethToken === ZERO_ETH_ADDRESS || ethToken === ethGateway) throw new CustomError("INVALID_ROLLUP_PROPS", "contractAddress must be a non-zero ethereum token address distinct from gateway");
162
+ if (ethVault === ZERO_ETH_ADDRESS || ethVault === ethToken || ethVault === ethGateway) throw new CustomError("INVALID_ROLLUP_PROPS", "vaultAddress must be a non-zero ethereum address distinct from contractAddress and gateway");
163
+ if (body.evmGovernance && body.evmGovernance.vaultSignerManager === null) throw new CustomError("INVALID_ROLLUP_PROPS", "evmGovernance.vaultSignerManager is required when vaultAddress is configured");
164
+ const seenVaults = new Set([ethVault]);
165
+ for (const h of value.vaultHistory || []) {
166
+ const eh = bareEthAddress(h);
167
+ if (eh === ZERO_ETH_ADDRESS || eh === ethToken || eh === ethGateway) throw new CustomError("INVALID_ROLLUP_PROPS", "vaultHistory entries must be non-zero ethereum addresses distinct from contractAddress and gateway");
168
+ if (seenVaults.has(eh)) throw new CustomError("INVALID_ROLLUP_PROPS", "vaultHistory must not repeat vaultAddress or prior history entries");
169
+ seenVaults.add(eh);
170
+ }
156
171
  if (body.pendingOwner) validateBridge(materializeBridgeAt(value, body.pendingOwner.effectiveAt));
157
172
  if (value.seedValidators.length !== 1 || value.seedValidators[0].address.toLowerCase() !== body.owner.toLowerCase()) throw new CustomError("INVALID_ROLLUP_PROPS", "seed_validators must be the bridge owner alone");
158
173
  if (value.paused === false && body.lonePause !== null) throw new CustomError("INVALID_ROLLUP_PROPS", "lonePause requires paused");
@@ -1,3 +1,5 @@
1
+ import { EvmGovernanceRosterConfig, EvmSignerManagerRoster } from "@ocap/mcrypto";
2
+
1
3
  //#region src/states/rollup-v2.d.ts
2
4
  declare const BRIDGE_MIN_EPOCH_LEAD = 3600;
3
5
  declare const BRIDGE_MAX_EPOCH_LEAD: number;
@@ -11,10 +13,11 @@ declare const BRIDGE_MAX_VALIDATORS = 16;
11
13
  declare const BRIDGE_MAX_DELAY: number;
12
14
  declare const BRIDGE_VERSION = 2;
13
15
  /** Keys a creator may put in `itx.data.value` of a v2 `create_rollup`. Everything else is derived by the chain. */
14
- declare const BRIDGE_CREATE_KEYS: readonly ["version", "ethChainId", "gateway", "minDeposit", "minWithdraw", "maxWithdraw", "withdrawFee", "releaseDailyCap", "refundDailyCap", "releaseGrace", "refundDelay", "transitionPeriod", "epochs", "salt", "pausers", "ethOwnerAttestation", "consents", "initialReserve"];
16
+ declare const BRIDGE_CREATE_KEYS: readonly ["version", "ethChainId", "gateway", "minDeposit", "minWithdraw", "maxWithdraw", "withdrawFee", "releaseDailyCap", "refundDailyCap", "releaseGrace", "refundDelay", "transitionPeriod", "epochs", "salt", "pausers", "ethOwnerAttestation", "consents", "initialReserve", "evmGovernance"];
15
17
  /** Keys `update_rollup` may patch. `proposeOwner` / `cancelOwnerProposal` / `cancelPendingEpoch` are actions. */
16
- declare const BRIDGE_PATCH_VALUE_KEYS: readonly ["minDeposit", "minWithdraw", "maxWithdraw", "releaseDailyCap", "refundDailyCap", "releaseGrace", "refundDelay", "pausers"];
18
+ declare const BRIDGE_PATCH_VALUE_KEYS: readonly ["minDeposit", "minWithdraw", "maxWithdraw", "releaseDailyCap", "refundDailyCap", "releaseGrace", "refundDelay", "pausers", "evmGovernance"];
17
19
  declare const BRIDGE_PATCH_ACTION_KEYS: readonly ["cancelPendingEpoch", "proposeOwner", "cancelOwnerProposal"];
20
+ declare const BRIDGE_PATCH_PROOF_KEYS: readonly ["evmGovernanceSync"];
18
21
  interface BridgeEpoch {
19
22
  epoch: number;
20
23
  activeFrom: number;
@@ -28,6 +31,12 @@ interface BridgeMember {
28
31
  pk: string;
29
32
  endpoint: string;
30
33
  }
34
+ type BridgeEvmGovernance = EvmGovernanceRosterConfig;
35
+ type BridgeEvmSignerSet = EvmSignerManagerRoster;
36
+ interface BridgeEvmGovernanceSyncProof {
37
+ expiresAt: number | string;
38
+ signatures: string[];
39
+ }
31
40
  interface BridgeBodyV2 {
32
41
  version: 2;
33
42
  owner: string;
@@ -81,6 +90,11 @@ interface BridgeBodyV2 {
81
90
  * Absent on bodies written before #1505 (read as null).
82
91
  */
83
92
  migratedAmount?: string | null;
93
+ /**
94
+ * Registered Ethereum `SignerManagerV2` governance roster (#1880). Stored as `null` when unconfigured (never `undefined`)
95
+ * so `canonicalJson(body)` in off-chain readers stays deterministic.
96
+ */
97
+ evmGovernance?: BridgeEvmGovernance | null;
84
98
  ethOwnerAttestation: {
85
99
  address: string;
86
100
  signature: string;
@@ -94,6 +108,8 @@ declare function isBridgeV2(state: unknown): boolean;
94
108
  declare function getBridgeBody(state: unknown): BridgeBodyV2 | null;
95
109
  declare const toSeconds: (iso: string | number | Date | undefined | null) => number;
96
110
  declare const lc: (address: string) => string;
111
+ /** Strip a case-insensitive `did:abt:` prefix and whitespace, returning a lowercase bare Ethereum address. */
112
+ declare const bareEthAddress: (a: unknown) => string;
97
113
  /** Ethereum addresses compare case-insensitively; OCAP addresses may carry a DID prefix. */
98
114
  declare const sameAddress: (a: unknown, b: unknown) => boolean;
99
115
  /** `epochAt(t) = max{ e : activeFrom(e) <= t }`, undefined (null) before the first epoch. */
@@ -127,6 +143,19 @@ declare function syncBridgeView(state: AnyState, txSec: number): AnyState;
127
143
  * has run out rewrites BOTH `owner` and `seedValidators`. Returns the (possibly new) state; never mutates its input.
128
144
  */
129
145
  declare function materializeBridgeAt(state: AnyState, txSec: number): AnyState;
146
+ /**
147
+ * Verifies a `BridgeEvmGovernanceSync` EIP-712 proof signed by the OLD `prev` EVM governance roster (`signerManager`,
148
+ * and `vaultSignerManager` when distinct and modified), bound to `(ocapChainId, bridge, next.version, configHash(next))`
149
+ * and `txSec < expiresAt`.
150
+ */
151
+ declare function verifyBridgeEvmGovernanceSync(o: {
152
+ ocapChainId: string;
153
+ bridge: string;
154
+ prev: BridgeEvmGovernance | null | undefined;
155
+ next: BridgeEvmGovernance;
156
+ proof: unknown;
157
+ txSec: number;
158
+ }): void;
130
159
  /** Full structural validation of a stored v2 body. */
131
160
  declare function validateBridgeBody(body: BridgeBodyV2): BridgeBodyV2;
132
161
  /** Whether a v1 numeric field is "zero or empty" (the v2 requirement for unused v1 fields). */
@@ -153,20 +182,27 @@ interface BridgeCreateInput {
153
182
  }
154
183
  /** Parse and validate `itx.data.value` of a v2 `create_rollup` (pure shape checks; signatures are checked by the protocol). */
155
184
  declare function parseBridgeCreateData(value: AnyState): BridgeCreateInput;
156
- type BridgePatchKind = 'owner-quorum' | 'propose-owner' | 'cancel-owner-proposal';
185
+ type BridgePatchKind = 'owner-quorum' | 'propose-owner' | 'cancel-owner-proposal' | 'evm-governance-sync';
157
186
  interface BridgePatchPlan {
158
187
  kind: BridgePatchKind;
159
188
  /** the body after the patch */
160
189
  body: BridgeBodyV2;
161
190
  /** a pending epoch was removed */
162
191
  cancelledEpoch: BridgeEpoch | null;
192
+ /** optional Path-A EIP-712 proof from the previous EVM governance roster */
193
+ evmGovernanceSync?: unknown;
163
194
  }
164
195
  /**
165
196
  * Validate an `update_rollup` patch (`itx.data.value`) against the allow-list and compute the resulting body.
166
- * `proposeOwner` is its own transaction kind (2/3 quorum), `cancelOwnerProposal` needs the current owner alone, anything
197
+ * `proposeOwner` is its own transaction kind (2/3 quorum), `cancelOwnerProposal` needs the current owner alone,
198
+ * standalone `{ evmGovernance, evmGovernanceSync }` is verified against the previous EVM governance roster, and anything
167
199
  * else needs owner + quorum. Frozen keys (version, epochs, reserve, gateway, ethChainId, token fields...) are rejected.
168
200
  */
169
- declare function planBridgePatch(body: BridgeBodyV2, patch: AnyState, txSec: number): BridgePatchPlan;
201
+ declare function planBridgePatch(body: BridgeBodyV2, patch: AnyState, txSec: number, syncCtx?: {
202
+ ocapChainId: string;
203
+ bridge: string;
204
+ vaultAddress?: string | null;
205
+ }): BridgePatchPlan;
170
206
  interface MembershipRequest {
171
207
  action: 'join' | 'leave';
172
208
  validator: string;
@@ -185,4 +221,4 @@ declare function lonePauseTrack(body: BridgeBodyV2, by: string): 'owner' | 'othe
185
221
  /** Validate and apply a lone pause by `by` (a member of `pausers`) at `txSec`. */
186
222
  declare function applyLonePause(body: BridgeBodyV2, by: string, txSec: number): BridgeBodyV2;
187
223
  //#endregion
188
- 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, BridgeBodyV2, BridgeConsent, BridgeCreateInput, BridgeEpoch, BridgeMember, BridgePatchKind, BridgePatchPlan, MembershipPlan, MembershipRequest, 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 };
224
+ 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_PROOF_KEYS, BRIDGE_PATCH_VALUE_KEYS, BRIDGE_RESERVE_MIGRATION_WINDOW, BRIDGE_V1_ZERO_FIELDS, BRIDGE_VERSION, BridgeBodyV2, BridgeConsent, BridgeCreateInput, BridgeEpoch, BridgeEvmGovernance, BridgeEvmGovernanceSyncProof, BridgeEvmSignerSet, BridgeMember, BridgePatchKind, BridgePatchPlan, MembershipPlan, MembershipRequest, activeEpochAt, applyLonePause, assertBridgeTransition, assertV1FieldsUnused, bareEthAddress, effectiveOwnerAt, getBridgeBody, isBridgeFinalAt, isBridgePausedAt, isBridgeV2, isBridgeV2Data, isQuorumPaused, isValidOwnerCandidate, isZeroish, lc, lonePauseTrack, materializeBridgeAt, maxVoucherValidity, parseBridgeCreateData, pendingEpochAt, planBridgePatch, planMembership, sameAddress, syncBridgeView, toSeconds, validateBridgeBody, verifyBridgeEvmGovernanceSync };