@ocap/state 1.30.26 → 1.31.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -3,20 +3,97 @@ import { create as create$1, update as update$1 } from "../contexts/state.mjs";
3
3
  import { BN, toAddress } from "@ocap/util";
4
4
  import { CustomError } from "@ocap/util/lib/error";
5
5
  import pick from "lodash/pick.js";
6
- import { patterns, schemas, v, vBN, vBNPositive, vDID, vStripUnknown, vValidate } from "@arcblock/validator";
6
+ import uniq from "lodash/uniq.js";
7
+ import { patterns, schemas, v, vBN, vBNMin, vBNPositive, vDID, vStripUnknown, vValidate } from "@arcblock/validator";
7
8
 
8
9
  //#region src/states/rollup.ts
9
10
  var rollup_exports = /* @__PURE__ */ __exportAll({
11
+ VALID_ROLLUP_TARGET_TYPES: () => VALID_ROLLUP_TARGET_TYPES,
10
12
  close: () => close,
11
13
  create: () => create,
14
+ getRollupSupportedTokens: () => getRollupSupportedTokens,
15
+ getRollupTargetType: () => getRollupTargetType,
16
+ getRollupTokenReserve: () => getRollupTokenReserve,
17
+ hasRollupReserveTracking: () => hasRollupReserveTracking,
18
+ isProposerSponsoredDepositAllowed: () => isProposerSponsoredDepositAllowed,
19
+ isTokenSupportedByRollup: () => isTokenSupportedByRollup,
20
+ isValidRollupContractAddress: () => isValidRollupContractAddress,
21
+ isValidRollupTargetType: () => isValidRollupTargetType,
22
+ isValidRollupValidatorAddress: () => isValidRollupValidatorAddress,
23
+ isValidRollupVaultAddress: () => isValidRollupVaultAddress,
12
24
  migrateContract: () => migrateContract,
13
25
  migrateVault: () => migrateVault,
14
26
  pause: () => pause,
27
+ recordRollupDeposit: () => recordRollupDeposit,
28
+ recordRollupWithdraw: () => recordRollupWithdraw,
15
29
  resume: () => resume,
16
30
  schema: () => schema,
17
31
  update: () => update,
18
32
  validate: () => validate
19
33
  });
34
+ const VALID_ROLLUP_TARGET_TYPES = ["EVM", "OCAP_ISOMORPHIC"];
35
+ const ethDidSchema = vDID({
36
+ prefix: true,
37
+ wallet: "ethereum"
38
+ });
39
+ const ethVaultDidSchema = vDID({ wallet: "ethereum" });
40
+ const anyDidSchema = vDID({ prefix: true });
41
+ function isValidRollupTargetType(value) {
42
+ return typeof value === "string" && VALID_ROLLUP_TARGET_TYPES.includes(value);
43
+ }
44
+ function getRollupTargetType(state) {
45
+ const raw = state?.targetType ?? state?.data?.value?.targetType;
46
+ if (isValidRollupTargetType(raw)) return raw;
47
+ return "EVM";
48
+ }
49
+ function isValidRollupContractAddress(address, targetType = "EVM") {
50
+ if (typeof address !== "string" || address.length === 0) return false;
51
+ if (targetType === "EVM") return !vValidate(ethDidSchema, address).error;
52
+ if (targetType === "OCAP_ISOMORPHIC") return !vValidate(anyDidSchema, address).error;
53
+ return false;
54
+ }
55
+ function isValidRollupVaultAddress(address, targetType = "EVM") {
56
+ if (address === void 0 || address === null || address === "") return true;
57
+ if (typeof address !== "string") return false;
58
+ if (targetType === "EVM") return !vValidate(ethVaultDidSchema, address).error;
59
+ if (targetType === "OCAP_ISOMORPHIC") return !vValidate(anyDidSchema, address).error;
60
+ return false;
61
+ }
62
+ function isValidRollupValidatorAddress(address, targetType = "EVM") {
63
+ if (typeof address !== "string" || address.length === 0) return false;
64
+ if (targetType === "EVM") return !vValidate(ethDidSchema, address).error;
65
+ return !vValidate(anyDidSchema, address).error;
66
+ }
67
+ function getRollupSupportedTokens(state) {
68
+ const primary = typeof state?.tokenAddress === "string" && state.tokenAddress ? [state.tokenAddress] : [];
69
+ const extra = state?.supportedTokens ?? state?.data?.value?.supportedTokens;
70
+ if (!Array.isArray(extra)) return primary;
71
+ return uniq([...primary, ...extra.filter((x) => typeof x === "string" && x.length > 0)]);
72
+ }
73
+ function isTokenSupportedByRollup(state, tokenAddress) {
74
+ if (!state || !tokenAddress) return false;
75
+ if (state.tokenAddress === tokenAddress) return true;
76
+ return getRollupSupportedTokens(state).includes(tokenAddress);
77
+ }
78
+ function isProposerSponsoredDepositAllowed(state) {
79
+ const explicit = state?.allowProposerSponsor ?? state?.data?.value?.allowProposerSponsor;
80
+ if (typeof explicit === "boolean") return explicit;
81
+ return getRollupTargetType(state) !== "EVM";
82
+ }
83
+ function hasRollupReserveTracking(state) {
84
+ if (!state) return false;
85
+ if (state.reserves !== void 0) return true;
86
+ if (state.enforceReserveWatermark === true || state.data?.value?.enforceReserveWatermark === true) return true;
87
+ return getRollupTargetType(state) !== "EVM";
88
+ }
89
+ function getRollupTokenReserve(state, tokenAddress) {
90
+ const map = state?.reserves;
91
+ const entry = map && typeof map === "object" ? map[tokenAddress] : void 0;
92
+ return {
93
+ totalDeposited: typeof entry?.totalDeposited === "string" ? entry.totalDeposited : "0",
94
+ totalWithdrawn: typeof entry?.totalWithdrawn === "string" ? entry.totalWithdrawn : "0"
95
+ };
96
+ }
20
97
  const isHttpOrHttpsUrl = (s) => {
21
98
  try {
22
99
  return ["http:", "https:"].includes(new URL(s).protocol);
@@ -29,6 +106,10 @@ const validatorSchema = v.object({
29
106
  address: vDID({ prefix: true }),
30
107
  endpoint: v.pipe(v.string(), v.check(isHttpOrHttpsUrl, "Must be a valid HTTP/HTTPS URL"))
31
108
  });
109
+ const reserveItemSchema = v.object({
110
+ totalDeposited: vBN(vBNMin(0)),
111
+ totalWithdrawn: vBN(vBNMin(0))
112
+ });
32
113
  const schema = v.pipe(v.object({
33
114
  address: vDID({
34
115
  prefix: true,
@@ -38,19 +119,10 @@ const schema = v.pipe(v.object({
38
119
  prefix: true,
39
120
  role: "ROLE_TOKEN"
40
121
  }),
41
- contractAddress: vDID({
42
- prefix: true,
43
- wallet: "ethereum"
44
- }),
45
- vaultAddress: v.optional(v.nullable(v.union([v.literal(""), vDID({ wallet: "ethereum" })]))),
46
- migrateHistory: v.optional(v.array(vDID({
47
- prefix: true,
48
- wallet: "ethereum"
49
- })), []),
50
- vaultHistory: v.optional(v.array(vDID({
51
- prefix: true,
52
- wallet: "ethereum"
53
- })), []),
122
+ contractAddress: v.pipe(v.string(), v.minLength(1)),
123
+ vaultAddress: v.optional(v.nullable(v.string())),
124
+ migrateHistory: v.optional(v.array(v.pipe(v.string(), v.minLength(1))), []),
125
+ vaultHistory: v.optional(v.array(v.pipe(v.string(), v.minLength(1))), []),
54
126
  paused: v.optional(v.boolean(), false),
55
127
  closed: v.optional(v.boolean(), false),
56
128
  seedValidators: v.pipe(v.array(validatorSchema), v.minLength(1)),
@@ -81,13 +153,35 @@ const schema = v.pipe(v.object({
81
153
  leaveWaitingPeriod: v.optional(v.pipe(v.number(), v.integer()), 0),
82
154
  publishWaitingPeriod: v.optional(v.pipe(v.number(), v.integer()), 0),
83
155
  publishSlashRate: v.pipe(v.number(), v.integer(), v.minValue(1), v.maxValue(1e4)),
156
+ targetType: v.optional(v.picklist(["EVM", "OCAP_ISOMORPHIC"])),
157
+ targetChainId: v.optional(v.pipe(v.string(), v.minLength(1), v.maxLength(128))),
158
+ supportedTokens: v.optional(v.array(vDID({
159
+ prefix: true,
160
+ role: "ROLE_TOKEN"
161
+ }))),
162
+ reserves: v.optional(v.record(vDID({
163
+ prefix: true,
164
+ role: "ROLE_TOKEN"
165
+ }), reserveItemSchema)),
166
+ allowProposerSponsor: v.optional(v.boolean()),
167
+ enforceReserveWatermark: v.optional(v.boolean()),
84
168
  context: schemas.context,
85
169
  data: v.optional(v.nullable(v.any()))
86
- }), v.forward(v.check((d) => new BN(d.maxStakeAmount).gte(new BN(d.minStakeAmount)), "maxStakeAmount must be >= minStakeAmount"), ["maxStakeAmount"]), v.forward(v.check((d) => d.minSignerCount >= d.seedValidators.length, "minSignerCount must be >= seedValidators count"), ["minSignerCount"]), v.forward(v.check((d) => d.maxSignerCount >= d.minSignerCount, "maxSignerCount must be >= minSignerCount"), ["maxSignerCount"]), v.forward(v.check((d) => d.maxBlockSize >= d.minBlockSize, "maxBlockSize must be >= minBlockSize"), ["maxBlockSize"]), v.forward(v.check((d) => new BN(d.minDepositAmount).lt(new BN(d.minStakeAmount)), "minDepositAmount must be < minStakeAmount"), ["minDepositAmount"]), v.forward(v.check((d) => {
170
+ }), v.forward(v.check((d) => {
171
+ const dataTargetType = d.data?.value?.targetType;
172
+ if (dataTargetType !== void 0 && !isValidRollupTargetType(dataTargetType)) return false;
173
+ if (d.targetType !== void 0 && dataTargetType !== void 0 && d.targetType !== dataTargetType) return false;
174
+ return true;
175
+ }, "Invalid targetType in rollup state"), ["targetType"]), v.forward(v.check((d) => isValidRollupContractAddress(d.contractAddress, getRollupTargetType(d)), "Expected wallet type to be \"ethereum\" or valid target chain contract address"), ["contractAddress"]), v.forward(v.check((d) => isValidRollupVaultAddress(d.vaultAddress, getRollupTargetType(d)), "Expected wallet type to be \"ethereum\" or valid target chain vault address"), ["vaultAddress"]), v.forward(v.check((d) => Array.isArray(d.migrateHistory) && d.migrateHistory.every((addr) => isValidRollupContractAddress(addr, getRollupTargetType(d))), "Expected wallet type to be \"ethereum\" or valid target chain contract address in migrateHistory"), ["migrateHistory"]), v.forward(v.check((d) => Array.isArray(d.vaultHistory) && d.vaultHistory.every((addr) => Boolean(addr) && isValidRollupVaultAddress(addr, getRollupTargetType(d))), "Expected wallet type to be \"ethereum\" or valid target chain vault address in vaultHistory"), ["vaultHistory"]), v.forward(v.check((d) => Array.isArray(d.seedValidators) && d.seedValidators.every((val) => isValidRollupValidatorAddress(val?.address, getRollupTargetType(d))), "Seed validator must use ethereum compatible keypair and address"), ["seedValidators"]), v.forward(v.check((d) => Array.isArray(d.validators) && d.validators.every((val) => isValidRollupValidatorAddress(val?.address, getRollupTargetType(d))), "Expected wallet type to be \"ethereum\" or valid target chain validator address in validators"), ["validators"]), v.forward(v.check((d) => new BN(d.maxStakeAmount).gte(new BN(d.minStakeAmount)), "maxStakeAmount must be >= minStakeAmount"), ["maxStakeAmount"]), v.forward(v.check((d) => d.minSignerCount >= d.seedValidators.length, "minSignerCount must be >= seedValidators count"), ["minSignerCount"]), v.forward(v.check((d) => d.maxSignerCount >= d.minSignerCount, "maxSignerCount must be >= minSignerCount"), ["maxSignerCount"]), v.forward(v.check((d) => d.maxBlockSize >= d.minBlockSize, "maxBlockSize must be >= minBlockSize"), ["maxBlockSize"]), v.forward(v.check((d) => new BN(d.minDepositAmount).lt(new BN(d.minStakeAmount)), "minDepositAmount must be < minStakeAmount"), ["minDepositAmount"]), v.forward(v.check((d) => {
87
176
  const max = new BN(d.maxDepositAmount);
88
177
  return max.gt(new BN(d.minDepositAmount)) && max.lt(new BN(d.minStakeAmount));
89
178
  }, "maxDepositAmount must be > minDepositAmount and < minStakeAmount"), ["maxDepositAmount"]), v.forward(v.check((d) => new BN(d.maxWithdrawAmount).gt(new BN(d.minWithdrawAmount)), "maxWithdrawAmount must be > minWithdrawAmount"), ["maxWithdrawAmount"]), v.forward(v.check((d) => new BN(d.maxDepositFee).gte(new BN(d.minDepositFee)), "maxDepositFee must be >= minDepositFee"), ["maxDepositFee"]), v.forward(v.check((d) => new BN(d.maxWithdrawFee).gte(new BN(d.minWithdrawFee)), "maxWithdrawFee must be >= minWithdrawFee"), ["maxWithdrawFee"]), v.forward(v.check((d) => d.leaveWaitingPeriod >= d.minBlockInterval, "leaveWaitingPeriod must be >= minBlockInterval"), ["leaveWaitingPeriod"]), v.forward(v.check((d) => d.publishWaitingPeriod >= d.minBlockInterval, "publishWaitingPeriod must be >= minBlockInterval"), ["publishWaitingPeriod"]), vStripUnknown());
90
179
  const create = (attrs, context) => {
180
+ if (attrs?.data?.value?.reserves !== void 0) throw new CustomError("INVALID_ROLLUP_PROPS", "reserves cannot be defined inside data.value");
181
+ if (attrs?.reserves && typeof attrs.reserves === "object") {
182
+ 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
+ }
184
+ const dataValue = attrs?.data?.value && typeof attrs.data.value === "object" ? attrs.data.value : void 0;
91
185
  const rollup = {
92
186
  context: create$1(context),
93
187
  paused: false,
@@ -127,9 +221,22 @@ const create = (attrs, context) => {
127
221
  "publishWaitingPeriod",
128
222
  "publishSlashRate",
129
223
  "issuer",
224
+ "targetType",
225
+ "targetChainId",
226
+ "supportedTokens",
227
+ "reserves",
228
+ "allowProposerSponsor",
229
+ "enforceReserveWatermark",
130
230
  "data"
131
231
  ])
132
232
  };
233
+ if (dataValue) {
234
+ if (rollup.targetType === void 0 && dataValue.targetType !== void 0) rollup.targetType = dataValue.targetType;
235
+ if (rollup.targetChainId === void 0 && typeof dataValue.targetChainId === "string") rollup.targetChainId = dataValue.targetChainId;
236
+ if (rollup.supportedTokens === void 0 && Array.isArray(dataValue.supportedTokens)) rollup.supportedTokens = dataValue.supportedTokens;
237
+ if (rollup.allowProposerSponsor === void 0 && typeof dataValue.allowProposerSponsor === "boolean") rollup.allowProposerSponsor = dataValue.allowProposerSponsor;
238
+ if (rollup.enforceReserveWatermark === void 0 && typeof dataValue.enforceReserveWatermark === "boolean") rollup.enforceReserveWatermark = dataValue.enforceReserveWatermark;
239
+ }
133
240
  rollup.address = toAddress(rollup.address);
134
241
  return validate(rollup);
135
242
  };
@@ -142,7 +249,16 @@ const update = (state, updates, context) => {
142
249
  }
143
250
  if (typeof updates.blockHeight !== "undefined" && !updates.blockHeight) throw new CustomError("INVALID_ROLLUP_UPDATE", "blockHeight can not be unset");
144
251
  if (typeof updates.blockHash !== "undefined" && !updates.blockHash) throw new CustomError("INVALID_ROLLUP_UPDATE", "blockHash can not be unset");
145
- return validate({
252
+ if (updates?.data?.value?.reserves !== void 0) throw new CustomError("INVALID_ROLLUP_UPDATE", "reserves cannot be updated inside data.value");
253
+ const currentTargetType = getRollupTargetType(state);
254
+ const nextTargetType = updates.targetType ?? updates.data?.value?.targetType;
255
+ if (nextTargetType !== void 0 && nextTargetType !== currentTargetType) throw new CustomError("INVALID_ROLLUP_UPDATE", "targetType cannot be changed after rollup creation");
256
+ const currentChainId = state.targetChainId ?? state.data?.value?.targetChainId;
257
+ const nextChainId = updates.targetChainId ?? updates.data?.value?.targetChainId;
258
+ if (currentChainId && nextChainId !== void 0 && nextChainId !== currentChainId) throw new CustomError("INVALID_ROLLUP_UPDATE", "targetChainId cannot be changed after rollup creation");
259
+ const wasEnforcingWatermark = state.enforceReserveWatermark === true || state.data?.value?.enforceReserveWatermark === true;
260
+ if (wasEnforcingWatermark && (updates.enforceReserveWatermark === false || updates.data?.value?.enforceReserveWatermark === false)) throw new CustomError("INVALID_ROLLUP_UPDATE", "enforceReserveWatermark cannot be disabled once enabled");
261
+ const rollup = {
146
262
  ...state,
147
263
  ...pick(updates, [
148
264
  "validators",
@@ -170,10 +286,18 @@ const update = (state, updates, context) => {
170
286
  "leaveWaitingPeriod",
171
287
  "publishWaitingPeriod",
172
288
  "publishSlashRate",
289
+ "targetType",
290
+ "targetChainId",
291
+ "supportedTokens",
292
+ "reserves",
293
+ "allowProposerSponsor",
294
+ "enforceReserveWatermark",
173
295
  "data"
174
296
  ]),
175
297
  context: update$1(state.context, context)
176
- });
298
+ };
299
+ if (wasEnforcingWatermark) rollup.enforceReserveWatermark = true;
300
+ return validate(rollup);
177
301
  };
178
302
  const pause = (state, context) => {
179
303
  if (state.closed) throw new CustomError("INVALID_PAUSE_ATTEMPT", "rollup already closed");
@@ -205,6 +329,7 @@ const resume = (state, context) => {
205
329
  const migrateContract = (state, to, context) => {
206
330
  if (state.closed) throw new CustomError("INVALID_MIGRATE_ATTEMPT", "rollup is closed");
207
331
  if (state.paused === false) throw new CustomError("INVALID_MIGRATE_ATTEMPT", "rollup not paused");
332
+ if (!to || typeof to !== "string") throw new CustomError("INVALID_MIGRATE_ATTEMPT", "invalid contract address");
208
333
  if (state.contractAddress === to) throw new CustomError("INVALID_MIGRATE_ATTEMPT", "can not migrate contract to self");
209
334
  if (state.migrateHistory.includes(to)) throw new CustomError("INVALID_MIGRATE_ATTEMPT", "can not migrate contract to history contracts");
210
335
  return validate({
@@ -217,21 +342,70 @@ const migrateContract = (state, to, context) => {
217
342
  const migrateVault = (state, to, context) => {
218
343
  if (state.closed) throw new CustomError("INVALID_MIGRATE_ATTEMPT", "rollup is closed");
219
344
  if (state.paused === false) throw new CustomError("INVALID_MIGRATE_ATTEMPT", "rollup not paused");
345
+ if (!to || typeof to !== "string") throw new CustomError("INVALID_MIGRATE_ATTEMPT", "invalid vault address");
220
346
  if (state.vaultAddress === to) throw new CustomError("INVALID_MIGRATE_ATTEMPT", "can not migrate vault to self");
221
347
  if (state.vaultHistory.includes(to)) throw new CustomError("INVALID_MIGRATE_ATTEMPT", "can not migrate vault to history vaults");
222
348
  return validate({
223
349
  ...state,
224
350
  vaultAddress: to,
225
- vaultHistory: [...state.vaultHistory, state.vaultAddress],
351
+ vaultHistory: state.vaultAddress ? [...state.vaultHistory, state.vaultAddress] : [...state.vaultHistory],
226
352
  context: update$1(state.context, context)
227
353
  });
228
354
  };
355
+ const recordRollupDeposit = (state, tokenAddress, amount, context) => {
356
+ if (!isTokenSupportedByRollup(state, tokenAddress)) throw new CustomError("INVALID_ROLLUP_TOKEN", `Token ${tokenAddress} is not supported by rollup ${state.address}`);
357
+ let amountBn;
358
+ try {
359
+ amountBn = new BN(amount);
360
+ } catch {
361
+ throw new CustomError("INVALID_DEPOSIT_AMOUNT", `Invalid deposit amount: ${amount}`);
362
+ }
363
+ if (amountBn.lte(new BN(0))) throw new CustomError("INVALID_DEPOSIT_AMOUNT", `Deposit amount must be positive: ${amount}`);
364
+ const currentReserves = state.reserves ?? {};
365
+ const prev = getRollupTokenReserve(state, tokenAddress);
366
+ const nextReserve = {
367
+ totalDeposited: new BN(prev.totalDeposited).add(amountBn).toString(10),
368
+ totalWithdrawn: prev.totalWithdrawn
369
+ };
370
+ return update(state, { reserves: {
371
+ ...currentReserves,
372
+ [tokenAddress]: nextReserve
373
+ } }, context);
374
+ };
375
+ const recordRollupWithdraw = (state, tokenAddress, amount, context) => {
376
+ if (!isTokenSupportedByRollup(state, tokenAddress)) throw new CustomError("INVALID_ROLLUP_TOKEN", `Token ${tokenAddress} is not supported by rollup ${state.address}`);
377
+ let amountBn;
378
+ try {
379
+ amountBn = new BN(amount);
380
+ } catch {
381
+ throw new CustomError("INVALID_WITHDRAW_AMOUNT", `Invalid withdraw amount: ${amount}`);
382
+ }
383
+ if (amountBn.lte(new BN(0))) throw new CustomError("INVALID_WITHDRAW_AMOUNT", `Withdraw amount must be positive: ${amount}`);
384
+ const currentReserves = state.reserves ?? {};
385
+ const prev = getRollupTokenReserve(state, tokenAddress);
386
+ const nextWithdrawn = new BN(prev.totalWithdrawn).add(amountBn);
387
+ const totalDeposited = new BN(prev.totalDeposited);
388
+ if (nextWithdrawn.gt(totalDeposited)) throw new CustomError("INSUFFICIENT_ROLLUP_RESERVE", `Withdraw amount (${amount}) exceeds rollup net inflow reserve watermark for token ${tokenAddress}: cumulativeWithdrawn (${nextWithdrawn.toString(10)}) > cumulativeDeposited (${totalDeposited.toString(10)})`);
389
+ const nextReserve = {
390
+ totalDeposited: prev.totalDeposited,
391
+ totalWithdrawn: nextWithdrawn.toString(10)
392
+ };
393
+ return update(state, { reserves: {
394
+ ...currentReserves,
395
+ [tokenAddress]: nextReserve
396
+ } }, context);
397
+ };
229
398
  const validate = (state) => {
399
+ if (state?.data?.value?.reserves !== void 0) throw new CustomError("INVALID_ROLLUP_PROPS", "reserves cannot be defined inside data.value");
230
400
  const { value, error } = vValidate(schema, state);
231
401
  if (error) throw new CustomError("INVALID_ROLLUP_PROPS", error.details.map((x) => x.message).join(", "));
402
+ if (value.reserves && typeof value.reserves === "object") for (const [tokenAddr, reserve] of Object.entries(value.reserves)) {
403
+ if (!isTokenSupportedByRollup(value, tokenAddr)) throw new CustomError("INVALID_ROLLUP_PROPS", `Reserve token ${tokenAddr} is not supported by rollup`);
404
+ if (new BN(reserve.totalWithdrawn).gt(new BN(reserve.totalDeposited))) throw new CustomError("INVALID_ROLLUP_PROPS", `Cumulative withdrawn (${reserve.totalWithdrawn}) exceeds cumulative deposited (${reserve.totalDeposited}) for token ${tokenAddr}`);
405
+ }
232
406
  if (!value.data) value.data = null;
233
407
  return value;
234
408
  };
235
409
 
236
410
  //#endregion
237
- export { close, create, migrateContract, migrateVault, pause, resume, rollup_exports, schema, update, validate };
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 };
@@ -80,12 +80,13 @@ const update = (state, attrs, context) => {
80
80
  ...pick(attrs, [
81
81
  "tokens",
82
82
  "assets",
83
+ "slashers",
83
84
  "revocable",
84
- "data",
85
85
  "revokeWaitingPeriod",
86
86
  "revokedTokens",
87
87
  "revokedAssets"
88
88
  ]),
89
+ ...attrs.data !== void 0 ? { data: attrs.data } : {},
89
90
  message: state.message || "empty",
90
91
  context: update$1(state.context, context)
91
92
  });
@@ -31,13 +31,24 @@ const stateSchema = v.pipe(v.object({
31
31
  prefix: true,
32
32
  role: "ROLE_TOKEN_FACTORY"
33
33
  }),
34
- owner: v.union([vDID({
35
- prefix: true,
36
- role: "ROLE_ACCOUNT"
37
- }), vDID({
38
- prefix: true,
39
- role: "ROLE_APPLICATION"
40
- })]),
34
+ owner: v.union([
35
+ vDID({
36
+ prefix: true,
37
+ role: "ROLE_ACCOUNT"
38
+ }),
39
+ vDID({
40
+ prefix: true,
41
+ role: "ROLE_APPLICATION"
42
+ }),
43
+ vDID({
44
+ prefix: true,
45
+ role: "ROLE_BLOCKLET"
46
+ }),
47
+ vDID({
48
+ prefix: true,
49
+ role: "ROLE_ASSET"
50
+ })
51
+ ]),
41
52
  tokenAddress: vDID({
42
53
  prefix: true,
43
54
  role: "ROLE_TOKEN"
@@ -48,7 +59,11 @@ const stateSchema = v.pipe(v.object({
48
59
  }),
49
60
  currentSupply: vBN(vBNMin(0)),
50
61
  reserveBalance: vBN(vBNMin(0)),
51
- status: v.picklist(["ACTIVE", "PAUSED"]),
62
+ status: v.picklist([
63
+ "ACTIVE",
64
+ "PAUSED",
65
+ "GRADUATED"
66
+ ]),
52
67
  feeRate: v.pipe(v.number(), v.minValue(0), v.maxValue(2e3)),
53
68
  curve: v.optional(v.nullable(vCurveSchema)),
54
69
  context: schemas.context,
@@ -67,6 +82,7 @@ const create = (attrs, context) => {
67
82
  "reserveAddress",
68
83
  "curve",
69
84
  "feeRate",
85
+ "status",
70
86
  "data"
71
87
  ])
72
88
  };
@@ -76,9 +92,12 @@ const create = (attrs, context) => {
76
92
  const update = (state, attrs, context) => validate({
77
93
  ...state,
78
94
  ...pick(attrs, [
95
+ "owner",
79
96
  "currentSupply",
80
97
  "reserveBalance",
81
- "feeRate"
98
+ "feeRate",
99
+ "status",
100
+ "data"
82
101
  ]),
83
102
  context: update$1(state.context, context)
84
103
  });
@@ -1,33 +1,57 @@
1
1
  import { StateContextInput } from "../contexts/state.mjs";
2
2
  import { v } from "@arcblock/validator";
3
- import { ITokenState } from "@ocap/types";
3
+ import { IAssetState, ITokenState } from "@ocap/types";
4
4
 
5
5
  //#region src/states/token.d.ts
6
6
  declare namespace token_d_exports {
7
- export { create, metadataSchema, stateSchema, update, validate };
7
+ export { TOKEN_CHARTER_KIND, TokenCharterAssetPayload, buildTokenCharterAssetData, buildTokenCharterAssetState, create, extractTokenUpdatesFromCharterAsset, iconToNftDisplay, isTokenCharterAsset, metadataSchema, migrateTokensToCharterAssets, multiChainForeignTokenSchema, normalizeLegacyTokenStateForUpdate, resolveCharterMoniker, sanitizeTokenSvg, stateSchema, syncCharterAssetWithToken, syncTokenCharterOwnership, toTokenCharterAssetAddress, update, validate, websiteToNftEndpoint };
8
+ }
9
+ declare const TOKEN_CHARTER_KIND: "TokenCharter";
10
+ interface TokenCharterAssetPayload {
11
+ kind: typeof TOKEN_CHARTER_KIND;
12
+ tokenAddress: string;
13
+ symbol: string;
14
+ name: string;
15
+ description: string;
16
+ unit: string;
17
+ decimal: number;
18
+ icon: string;
19
+ website: string;
20
+ metadata: {
21
+ communityUrl?: string | null;
22
+ issuer: string;
23
+ } | null;
24
+ tokenFactoryAddress: string;
8
25
  }
9
26
  declare const metadataSchema: v.SchemaWithPipe<readonly [v.ObjectSchema<{
10
27
  readonly communityUrl: v.OptionalSchema<v.NullableSchema<v.UnionSchema<[v.LiteralSchema<"", undefined>, v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.MaxLengthAction<string, 256, undefined>, v.CheckAction<string, "Must be HTTPS URL">]>], undefined>, undefined>, undefined>;
11
28
  readonly issuer: v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.MaxLengthAction<string, 64, undefined>]>;
12
29
  }, undefined>, any]>;
30
+ declare const multiChainForeignTokenSchema: v.SchemaWithPipe<readonly [v.ObjectSchema<{
31
+ readonly type: v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.MinLengthAction<string, 1, undefined>, v.MaxLengthAction<string, 32, undefined>]>;
32
+ readonly contractAddress: v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.MinLengthAction<string, 1, undefined>]>;
33
+ readonly chainType: v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.MinLengthAction<string, 1, undefined>, v.MaxLengthAction<string, 32, undefined>]>;
34
+ readonly chainName: v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.MinLengthAction<string, 1, undefined>, v.MaxLengthAction<string, 32, undefined>]>;
35
+ readonly chainId: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.CheckAction<number, "Must be positive">]>;
36
+ }, undefined>, v.BaseValidation<any, any, v.CheckIssue<any>>, any]>;
13
37
  declare const stateSchema: v.SchemaWithPipe<readonly [v.ObjectSchema<{
14
38
  readonly address: any;
15
39
  readonly name: v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.MinLengthAction<string, 1, undefined>, v.MaxLengthAction<string, 32, undefined>]>;
16
40
  readonly description: v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.MinLengthAction<string, 16, undefined>, v.MaxLengthAction<string, 128, undefined>]>;
17
41
  readonly symbol: v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.MinLengthAction<string, 2, undefined>, v.MaxLengthAction<string, 6, undefined>, v.TransformAction<string, string>]>;
18
42
  readonly unit: v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.MinLengthAction<string, 1, undefined>, v.MaxLengthAction<string, 6, undefined>, v.TransformAction<string, string>]>;
19
- readonly decimal: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.MinValueAction<number, 2, undefined>, v.MaxValueAction<number, 18, undefined>]>;
43
+ readonly decimal: v.UnionSchema<[v.LiteralSchema<0, undefined>, v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.MinValueAction<number, 2, undefined>, v.MaxValueAction<number, 18, undefined>]>], undefined>;
20
44
  readonly icon: v.OptionalSchema<v.NullableSchema<v.StringSchema<undefined>, undefined>, undefined>;
21
45
  readonly totalSupply: any;
22
46
  readonly initialSupply: any;
23
47
  readonly maxTotalSupply: v.OptionalSchema<v.NullableSchema<v.UnionSchema<[v.LiteralSchema<"", undefined>, any], undefined>, undefined>, undefined>;
24
- readonly foreignToken: v.OptionalSchema<v.NullableSchema<v.ObjectSchema<{
48
+ readonly foreignToken: v.OptionalSchema<v.NullableSchema<v.SchemaWithPipe<readonly [v.ObjectSchema<{
25
49
  readonly type: v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.MinLengthAction<string, 1, undefined>, v.MaxLengthAction<string, 32, undefined>]>;
26
- readonly contractAddress: any;
50
+ readonly contractAddress: v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.MinLengthAction<string, 1, undefined>]>;
27
51
  readonly chainType: v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.MinLengthAction<string, 1, undefined>, v.MaxLengthAction<string, 32, undefined>]>;
28
52
  readonly chainName: v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.MinLengthAction<string, 1, undefined>, v.MaxLengthAction<string, 32, undefined>]>;
29
53
  readonly chainId: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.CheckAction<number, "Must be positive">]>;
30
- }, undefined>, undefined>, undefined>;
54
+ }, undefined>, v.BaseValidation<any, any, v.CheckIssue<any>>, any]>, undefined>, undefined>;
31
55
  readonly issuer: v.OptionalSchema<v.NullableSchema<v.UnionSchema<[v.LiteralSchema<"", undefined>, any], undefined>, undefined>, undefined>;
32
56
  readonly website: v.OptionalSchema<v.NullableSchema<v.UnionSchema<[v.LiteralSchema<"", undefined>, v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.MaxLengthAction<string, 256, undefined>, v.CheckAction<string, "Must be valid URL">]>], undefined>, undefined>, undefined>;
33
57
  readonly metadata: v.OptionalSchema<v.NullableSchema<v.ObjectSchema<{
@@ -52,5 +76,85 @@ declare const stateSchema: v.SchemaWithPipe<readonly [v.ObjectSchema<{
52
76
  declare const create: (attrs: Partial<ITokenState>, context: StateContextInput) => ITokenState;
53
77
  declare const update: (state: ITokenState, attrs: Partial<ITokenState>) => ITokenState;
54
78
  declare const validate: (state: ITokenState) => ITokenState;
79
+ /**
80
+ * Deterministically derive the companion Master Charter NFT address (`ROLE_ASSET`)
81
+ * for a given Fungible Token address (`ROLE_TOKEN`).
82
+ */
83
+ declare const toTokenCharterAssetAddress: (tokenAddress: string) => string;
84
+ /**
85
+ * Strip dangerous XSS elements/attributes (`<script>`, `<foreignObject>`, `<iframe>`,
86
+ * inline `on*` event handlers, and `javascript:`/`data:text/html` URIs) from SVG strings.
87
+ */
88
+ declare const sanitizeTokenSvg: (svg: string) => string;
89
+ declare const iconToNftDisplay: (icon?: string | null) => IAssetState["display"];
90
+ declare const websiteToNftEndpoint: (website?: string | null) => IAssetState["endpoint"];
91
+ declare const buildTokenCharterAssetData: (tokenState: ITokenState) => {
92
+ type: "json";
93
+ value: TokenCharterAssetPayload;
94
+ };
95
+ declare const resolveCharterMoniker: (tokenState: ITokenState) => string;
96
+ /**
97
+ * Build the companion Master Charter `AssetState` (`ROLE_ASSET`) for a `TokenState`.
98
+ */
99
+ declare const buildTokenCharterAssetState: (tokenState: ITokenState, context?: StateContextInput, ownerOverride?: string) => IAssetState;
100
+ /**
101
+ * Verify whether an `AssetState` is a genuine, cryptographically bound Token Charter NFT.
102
+ * Checks both the `TokenCharter` payload structure and the deterministic 1:1 DID binding
103
+ * (`toTokenCharterAssetAddress(tokenAddress) === assetState.address`) to prevent spoofing.
104
+ */
105
+ declare const isTokenCharterAsset: (assetState?: Partial<IAssetState> | null) => boolean;
106
+ /**
107
+ * Extract validated `TokenState` field updates when a Token Charter NFT is updated via `UpdateAssetTx`
108
+ * or transferred via `UpdateOwner`.
109
+ */
110
+ declare const extractTokenUpdatesFromCharterAsset: (tokenState: ITokenState, charterAsset: IAssetState) => Partial<ITokenState>;
111
+ /**
112
+ * Synchronize an existing Token Charter `AssetState` with updated `TokenState` fields.
113
+ */
114
+ declare const syncCharterAssetWithToken: (charterAsset: IAssetState, tokenState: ITokenState, context: StateContextInput, ownerOverride?: string) => IAssetState;
115
+ /**
116
+ * Normalize legacy `TokenState` fields (such as short descriptions or non-ISO context dates)
117
+ * before re-validating during ownership transfer or migration so legacy rows never brick updates.
118
+ */
119
+ declare const normalizeLegacyTokenStateForUpdate: (existingToken: ITokenState) => ITokenState;
120
+ /**
121
+ * Atomically synchronize `TokenState.issuer` and `TokenFactoryState.owner` whenever
122
+ * a Token Charter NFT changes owner (via `UpdateOwner`, `TransferV3Tx`, `ClaimStakeTx`,
123
+ * `ReturnStakeTx`, or `SlashStakeTx`).
124
+ * Validates all target state updates BEFORE writing to `statedb` to prevent partial writes.
125
+ */
126
+ declare const syncTokenCharterOwnership: (charterAsset: Partial<IAssetState> | null | undefined, newOwnerAddress: string | undefined, statedb: {
127
+ token?: {
128
+ get?: (key: string, ctx?: any) => Promise<ITokenState | null>;
129
+ update?: (key: string, state: ITokenState, ctx?: any) => Promise<ITokenState>;
130
+ };
131
+ tokenFactory?: {
132
+ get?: (key: string, ctx?: any) => Promise<any>;
133
+ update?: (key: string, state: any, ctx?: any) => Promise<any>;
134
+ };
135
+ }, context: StateContextInput) => Promise<void>;
136
+ /**
137
+ * Programmatic state migration helper: scans all existing `TokenState` records in `statedb.token`
138
+ * and idempotently backfills their companion Master Charter `AssetState` records in `statedb.asset`.
139
+ */
140
+ declare const migrateTokensToCharterAssets: (statedb: {
141
+ token?: {
142
+ findAll?: (query?: Record<string, unknown>, ctx?: unknown) => Promise<ITokenState[]>;
143
+ find?: (query?: Record<string, unknown>, ctx?: unknown) => Promise<ITokenState[]>;
144
+ };
145
+ asset?: {
146
+ get: (key: string, ctx?: unknown) => Promise<IAssetState | null>;
147
+ create: (key: string, state: IAssetState, ctx?: unknown) => Promise<IAssetState>;
148
+ };
149
+ tokenFactory?: {
150
+ get: (key: string, ctx?: unknown) => Promise<{
151
+ owner?: string;
152
+ } | null>;
153
+ };
154
+ }, operationContext?: unknown) => Promise<{
155
+ migrated: number;
156
+ skipped: number;
157
+ charterAddresses: string[];
158
+ }>;
55
159
  //#endregion
56
- export { create, metadataSchema, stateSchema, token_d_exports, update, validate };
160
+ export { TOKEN_CHARTER_KIND, TokenCharterAssetPayload, buildTokenCharterAssetData, buildTokenCharterAssetState, create, extractTokenUpdatesFromCharterAsset, iconToNftDisplay, isTokenCharterAsset, metadataSchema, migrateTokensToCharterAssets, multiChainForeignTokenSchema, normalizeLegacyTokenStateForUpdate, resolveCharterMoniker, sanitizeTokenSvg, stateSchema, syncCharterAssetWithToken, syncTokenCharterOwnership, toTokenCharterAssetAddress, token_d_exports, update, validate, websiteToNftEndpoint };