@ocap/state 1.31.1 → 1.31.3
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/states/account.d.mts +7 -2
- package/esm/states/account.mjs +29 -4
- package/esm/states/chain.d.mts +9 -1
- package/esm/states/chain.mjs +6 -3
- package/esm/states/rollup-bridge.d.mts +78 -0
- package/esm/states/rollup-bridge.mjs +165 -0
- package/esm/states/rollup-v2.d.mts +188 -0
- package/esm/states/rollup-v2.mjs +597 -0
- package/esm/states/rollup.d.mts +4 -2
- package/esm/states/rollup.mjs +52 -2
- package/esm/states/token-factory.mjs +2 -1
- package/esm/states/tx.mjs +30 -1
- package/lib/states/account.cjs +27 -1
- package/lib/states/account.d.cts +7 -2
- package/lib/states/chain.cjs +6 -3
- package/lib/states/chain.d.cts +9 -1
- package/lib/states/rollup-bridge.cjs +170 -0
- package/lib/states/rollup-bridge.d.cts +78 -0
- package/lib/states/rollup-v2.cjs +637 -0
- package/lib/states/rollup-v2.d.cts +188 -0
- package/lib/states/rollup.cjs +96 -2
- package/lib/states/rollup.d.cts +4 -2
- package/lib/states/token-factory.cjs +2 -1
- package/lib/states/tx.cjs +30 -1
- package/package.json +9 -9
package/esm/states/account.d.mts
CHANGED
|
@@ -5,7 +5,7 @@ import { IAccountState } from "@ocap/types";
|
|
|
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 };
|
package/esm/states/account.mjs
CHANGED
|
@@ -1,7 +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
3
|
import { isFromPublicKey } from "@arcblock/did";
|
|
4
|
-
import { isEthereumDid, toChecksumAddress } from "@arcblock/did/lib/type";
|
|
4
|
+
import { isEthereumDid as isEthereumDid$1, toChecksumAddress } from "@arcblock/did/lib/type";
|
|
5
5
|
import { BN, toAddress, toBase58 } from "@ocap/util";
|
|
6
6
|
import { CustomError } from "@ocap/util/lib/error";
|
|
7
7
|
import flatten from "lodash/flatten.js";
|
|
@@ -11,6 +11,7 @@ import { schemas, v, vBN, vBNMin, vDID, vFilteredRecord, vStripUnknown, vValidat
|
|
|
11
11
|
|
|
12
12
|
//#region src/states/account.ts
|
|
13
13
|
var account_exports = /* @__PURE__ */ __exportAll({
|
|
14
|
+
DELEGATED_NONCE_MAX_FUTURE_MS: () => DELEGATED_NONCE_MAX_FUTURE_MS,
|
|
14
15
|
create: () => create,
|
|
15
16
|
ensureChecksumAddress: () => ensureChecksumAddress,
|
|
16
17
|
isMigrated: () => isMigrated,
|
|
@@ -72,6 +73,28 @@ const parseNonceBn = (rawNonce) => {
|
|
|
72
73
|
}
|
|
73
74
|
return null;
|
|
74
75
|
};
|
|
76
|
+
/**
|
|
77
|
+
* How far above the tx time the nonce of a delegated tx may be (#1418). Wallets use `Date.now()` as nonce, so
|
|
78
|
+
* the allowance only has to absorb the clock error of an honest delegatee. Enforced at admission by `VerifyTx`.
|
|
79
|
+
*/
|
|
80
|
+
const DELEGATED_NONCE_MAX_FUTURE_MS = 1440 * 60 * 1e3;
|
|
81
|
+
/**
|
|
82
|
+
* Nonce ceiling for an account nonce written by a delegated tx (#1418), or `null` when the write is not part of
|
|
83
|
+
* a delegated tx.
|
|
84
|
+
*
|
|
85
|
+
* A delegated tx is signed by the delegatee (`tx.delegator`) but advances the nonce of the delegator's account
|
|
86
|
+
* (`tx.from`). Wallets sign with `nonce = Date.now()`, so a delegatee that could park that nonce in the future
|
|
87
|
+
* would lock the delegator out of every tx of its own - `revoke_delegate` and `account_migrate` included. The
|
|
88
|
+
* ceiling is the tx time: whatever a delegated tx writes, the next `Date.now()` nonce of the delegator exceeds it.
|
|
89
|
+
* A delegated tx without a usable tx time gets a zero ceiling (advance by one); `validate` refuses such a state
|
|
90
|
+
* context anyway, so the unbounded nonce never reaches the store.
|
|
91
|
+
*/
|
|
92
|
+
const getDelegatedNonceCeiling = (context) => {
|
|
93
|
+
const { tx, txTime } = context || {};
|
|
94
|
+
if (!tx || typeof tx.delegator !== "string" || tx.delegator === "") return null;
|
|
95
|
+
const txTimeMs = txTime ? new Date(txTime).getTime() : NaN;
|
|
96
|
+
return Number.isFinite(txTimeMs) && txTimeMs > 0 ? new BN(String(Math.floor(txTimeMs)), 10) : new BN(0);
|
|
97
|
+
};
|
|
75
98
|
const update = (state, attrs, context) => {
|
|
76
99
|
const hasExplicitNonce = attrs.nonce !== void 0 && attrs.nonce !== null;
|
|
77
100
|
let shouldUpdateNonce = false;
|
|
@@ -81,7 +104,9 @@ const update = (state, attrs, context) => {
|
|
|
81
104
|
const currentNonceBn = parseNonceBn(state.nonce) ?? new BN(0);
|
|
82
105
|
if (!incomingNonceBn || incomingNonceBn.lte(currentNonceBn) || incomingNonceBn.lte(new BN(0))) throw new CustomError("INVALID_NONCE", "nonce must be greater in newer transactions");
|
|
83
106
|
shouldUpdateNonce = true;
|
|
84
|
-
|
|
107
|
+
const ceilingBn = getDelegatedNonceCeiling(context);
|
|
108
|
+
const nextNonceBn = ceilingBn && incomingNonceBn.gt(ceilingBn) ? BN.max(ceilingBn, currentNonceBn.addn(1)) : incomingNonceBn;
|
|
109
|
+
normalizedNonce = nextNonceBn.lte(new BN(Number.MAX_SAFE_INTEGER)) ? nextNonceBn.toNumber() : nextNonceBn.toString(10);
|
|
85
110
|
}
|
|
86
111
|
if (attrs.pk && isFromPublicKey(state.address, attrs.pk) === false) delete attrs.pk;
|
|
87
112
|
const pickFields = shouldUpdateNonce ? [
|
|
@@ -118,7 +143,7 @@ const validate = (state) => {
|
|
|
118
143
|
return value;
|
|
119
144
|
};
|
|
120
145
|
const isMigrated = (state) => (state.migratedTo || []).length > 0;
|
|
121
|
-
const ensureChecksumAddress = (address) => isEthereumDid(address) ? toChecksumAddress(address) : address;
|
|
146
|
+
const ensureChecksumAddress = (address) => isEthereumDid$1(address) ? toChecksumAddress(address) : address;
|
|
122
147
|
|
|
123
148
|
//#endregion
|
|
124
|
-
export { account_exports, create, ensureChecksumAddress, isMigrated, parseNonceBn, schema, update, updateOrCreate, validate };
|
|
149
|
+
export { DELEGATED_NONCE_MAX_FUTURE_MS, account_exports, create, ensureChecksumAddress, isMigrated, parseNonceBn, schema, update, updateOrCreate, validate };
|
package/esm/states/chain.d.mts
CHANGED
|
@@ -24,7 +24,15 @@ interface ChainState {
|
|
|
24
24
|
vaults?: unknown;
|
|
25
25
|
context: StateContext;
|
|
26
26
|
}
|
|
27
|
-
declare const create: (attrs: Partial<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 };
|
package/esm/states/chain.mjs
CHANGED
|
@@ -10,9 +10,12 @@ var chain_exports = /* @__PURE__ */ __exportAll({
|
|
|
10
10
|
create: () => create,
|
|
11
11
|
update: () => update
|
|
12
12
|
});
|
|
13
|
-
const create = (attrs) => {
|
|
13
|
+
const create = (attrs, contextArg) => {
|
|
14
14
|
return {
|
|
15
|
-
context: create$1({
|
|
15
|
+
context: create$1({
|
|
16
|
+
txTime: contextArg?.txTime || attrs?.context?.txTime || (/* @__PURE__ */ new Date()).toISOString(),
|
|
17
|
+
...contextArg?.txHash !== void 0 ? { txHash: contextArg.txHash } : attrs?.context?.txHash !== void 0 ? { txHash: attrs.context.txHash } : {}
|
|
18
|
+
}),
|
|
16
19
|
...pick(attrs, [
|
|
17
20
|
"address",
|
|
18
21
|
"chainId",
|
|
@@ -34,7 +37,7 @@ const update = (state, updates) => {
|
|
|
34
37
|
];
|
|
35
38
|
if (!process.env.CHAIN_TOKEN_ADDRESS) immutableAttrs.push("token.name", "token.description", "token.unit", "token.totalSupply", "token.initialSupply", "token.foreignToken");
|
|
36
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`);
|
|
37
|
-
const context = { txTime: (/* @__PURE__ */ new Date()).toISOString() };
|
|
40
|
+
const context = { txTime: updates?.context?.txTime || (/* @__PURE__ */ new Date()).toISOString() };
|
|
38
41
|
return {
|
|
39
42
|
...state,
|
|
40
43
|
...pick(updates, [
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
import { StateContextInput } from "../contexts/state.mjs";
|
|
2
|
+
import { v } from "@arcblock/validator";
|
|
3
|
+
import { IRollupState } from "@ocap/types";
|
|
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 };
|
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
import { create, update } from "../contexts/state.mjs";
|
|
2
|
+
import { assertBridgeTransition, assertV1FieldsUnused, getBridgeBody, materializeBridgeAt, toSeconds, validateBridgeBody } from "./rollup-v2.mjs";
|
|
3
|
+
import { toAddress } from "@ocap/util";
|
|
4
|
+
import { CustomError } from "@ocap/util/lib/error";
|
|
5
|
+
import pick from "lodash/pick.js";
|
|
6
|
+
import { schemas, v, vDID, vStripUnknown, vValidate } from "@arcblock/validator";
|
|
7
|
+
|
|
8
|
+
//#region src/states/rollup-bridge.ts
|
|
9
|
+
/**
|
|
10
|
+
* v2 bridge rows (bridge/docs/ocap-protocols.md §v2.1): create / update / validate of a `RollupState` whose
|
|
11
|
+
* `data.value.version == 2`. Kept apart from `rollup.ts` so the v1 code path stays byte-for-byte what it was.
|
|
12
|
+
*/
|
|
13
|
+
const ethDidSchema = vDID({
|
|
14
|
+
prefix: true,
|
|
15
|
+
wallet: "ethereum"
|
|
16
|
+
});
|
|
17
|
+
const ethVaultDidSchema = vDID({ wallet: "ethereum" });
|
|
18
|
+
const isHttpOrHttpsUrl = (s) => {
|
|
19
|
+
try {
|
|
20
|
+
return ["http:", "https:"].includes(new URL(s).protocol);
|
|
21
|
+
} catch {
|
|
22
|
+
return false;
|
|
23
|
+
}
|
|
24
|
+
};
|
|
25
|
+
const bridgeValidatorSchema = v.object({
|
|
26
|
+
pk: v.string(),
|
|
27
|
+
address: ethDidSchema,
|
|
28
|
+
endpoint: v.pipe(v.string(), v.check(isHttpOrHttpsUrl, "Must be a valid HTTP/HTTPS URL"))
|
|
29
|
+
});
|
|
30
|
+
/** Row schema of a v2 bridge: the v1 stake / block / fee checks do not apply (those fields must be zero or empty). */
|
|
31
|
+
const bridgeSchema = v.pipe(v.object({
|
|
32
|
+
address: vDID({
|
|
33
|
+
prefix: true,
|
|
34
|
+
role: "ROLE_ROLLUP"
|
|
35
|
+
}),
|
|
36
|
+
tokenAddress: vDID({
|
|
37
|
+
prefix: true,
|
|
38
|
+
role: "ROLE_TOKEN"
|
|
39
|
+
}),
|
|
40
|
+
contractAddress: ethDidSchema,
|
|
41
|
+
vaultAddress: v.optional(v.nullable(v.string())),
|
|
42
|
+
migrateHistory: v.optional(v.array(ethDidSchema), []),
|
|
43
|
+
vaultHistory: v.optional(v.array(ethVaultDidSchema), []),
|
|
44
|
+
paused: v.optional(v.boolean(), false),
|
|
45
|
+
closed: v.optional(v.boolean(), false),
|
|
46
|
+
seedValidators: v.pipe(v.array(bridgeValidatorSchema), v.minLength(1), v.maxLength(1)),
|
|
47
|
+
validators: v.optional(v.pipe(v.array(bridgeValidatorSchema), v.maxLength(24)), []),
|
|
48
|
+
minSignerCount: v.pipe(v.number(), v.integer(), v.minValue(1)),
|
|
49
|
+
maxSignerCount: v.pipe(v.number(), v.integer(), v.minValue(1), v.maxValue(16)),
|
|
50
|
+
minBlockConfirmation: v.pipe(v.number(), v.integer(), v.minValue(1), v.maxValue(100)),
|
|
51
|
+
issuer: vDID({ prefix: true }),
|
|
52
|
+
minStakeAmount: v.optional(v.any()),
|
|
53
|
+
maxStakeAmount: v.optional(v.any()),
|
|
54
|
+
minBlockSize: v.optional(v.any()),
|
|
55
|
+
maxBlockSize: v.optional(v.any()),
|
|
56
|
+
minBlockInterval: v.optional(v.any()),
|
|
57
|
+
minDepositAmount: v.optional(v.any()),
|
|
58
|
+
maxDepositAmount: v.optional(v.any()),
|
|
59
|
+
minWithdrawAmount: v.optional(v.any()),
|
|
60
|
+
maxWithdrawAmount: v.optional(v.any()),
|
|
61
|
+
depositFeeRate: v.optional(v.any()),
|
|
62
|
+
withdrawFeeRate: v.optional(v.any()),
|
|
63
|
+
proposerFeeShare: v.optional(v.any()),
|
|
64
|
+
publisherFeeShare: v.optional(v.any()),
|
|
65
|
+
minDepositFee: v.optional(v.any()),
|
|
66
|
+
maxDepositFee: v.optional(v.any()),
|
|
67
|
+
minWithdrawFee: v.optional(v.any()),
|
|
68
|
+
maxWithdrawFee: v.optional(v.any()),
|
|
69
|
+
blockHeight: v.optional(v.any()),
|
|
70
|
+
blockHash: v.optional(v.any()),
|
|
71
|
+
leaveWaitingPeriod: v.optional(v.any()),
|
|
72
|
+
publishWaitingPeriod: v.optional(v.any()),
|
|
73
|
+
publishSlashRate: v.optional(v.any()),
|
|
74
|
+
context: schemas.context,
|
|
75
|
+
data: v.any()
|
|
76
|
+
}), vStripUnknown());
|
|
77
|
+
const BRIDGE_ZERO_DEFAULTS = {
|
|
78
|
+
minStakeAmount: "0",
|
|
79
|
+
maxStakeAmount: "0",
|
|
80
|
+
minBlockSize: 0,
|
|
81
|
+
maxBlockSize: 0,
|
|
82
|
+
minBlockInterval: 0,
|
|
83
|
+
minDepositAmount: "0",
|
|
84
|
+
maxDepositAmount: "0",
|
|
85
|
+
minWithdrawAmount: "0",
|
|
86
|
+
maxWithdrawAmount: "0",
|
|
87
|
+
depositFeeRate: 0,
|
|
88
|
+
withdrawFeeRate: 0,
|
|
89
|
+
proposerFeeShare: 0,
|
|
90
|
+
publisherFeeShare: 0,
|
|
91
|
+
minDepositFee: "0",
|
|
92
|
+
maxDepositFee: "0",
|
|
93
|
+
minWithdrawFee: "0",
|
|
94
|
+
maxWithdrawFee: "0",
|
|
95
|
+
blockHeight: 0,
|
|
96
|
+
blockHash: "",
|
|
97
|
+
leaveWaitingPeriod: 0,
|
|
98
|
+
publishWaitingPeriod: 0,
|
|
99
|
+
publishSlashRate: 0
|
|
100
|
+
};
|
|
101
|
+
const BRIDGE_ROW_KEYS = [
|
|
102
|
+
"address",
|
|
103
|
+
"tokenAddress",
|
|
104
|
+
"vaultAddress",
|
|
105
|
+
"contractAddress",
|
|
106
|
+
"seedValidators",
|
|
107
|
+
"validators",
|
|
108
|
+
"minSignerCount",
|
|
109
|
+
"maxSignerCount",
|
|
110
|
+
"minBlockConfirmation",
|
|
111
|
+
"issuer",
|
|
112
|
+
"data"
|
|
113
|
+
];
|
|
114
|
+
const createBridge = (attrs, context) => {
|
|
115
|
+
assertV1FieldsUnused(attrs, "INVALID_ROLLUP_PROPS");
|
|
116
|
+
const row = {
|
|
117
|
+
context: create(context),
|
|
118
|
+
paused: false,
|
|
119
|
+
closed: false,
|
|
120
|
+
migrateHistory: [],
|
|
121
|
+
vaultHistory: [],
|
|
122
|
+
...BRIDGE_ZERO_DEFAULTS,
|
|
123
|
+
...pick(attrs, BRIDGE_ROW_KEYS)
|
|
124
|
+
};
|
|
125
|
+
row.address = toAddress(row.address);
|
|
126
|
+
return validateBridge(row);
|
|
127
|
+
};
|
|
128
|
+
/** Update of a v2 row. Only fields a v2 governance tx may touch are copied; the transition rules run on the result. */
|
|
129
|
+
const updateBridge = (state, updates, context) => {
|
|
130
|
+
assertV1FieldsUnused(updates, "INVALID_ROLLUP_UPDATE");
|
|
131
|
+
const next = {
|
|
132
|
+
...state,
|
|
133
|
+
...pick(updates, [
|
|
134
|
+
"validators",
|
|
135
|
+
"seedValidators",
|
|
136
|
+
"minSignerCount",
|
|
137
|
+
"maxSignerCount",
|
|
138
|
+
"minBlockConfirmation",
|
|
139
|
+
"data",
|
|
140
|
+
"paused",
|
|
141
|
+
"closed",
|
|
142
|
+
"vaultAddress",
|
|
143
|
+
"vaultHistory"
|
|
144
|
+
]),
|
|
145
|
+
context: update(state.context, context)
|
|
146
|
+
};
|
|
147
|
+
assertBridgeTransition(state, next, context?.txTime ? toSeconds(context.txTime) : null);
|
|
148
|
+
return validateBridge(next);
|
|
149
|
+
};
|
|
150
|
+
const validateBridge = (state) => {
|
|
151
|
+
const { value, error } = vValidate(bridgeSchema, state);
|
|
152
|
+
if (error) throw new CustomError("INVALID_ROLLUP_PROPS", error.details.map((x) => x.message).join(", "));
|
|
153
|
+
assertV1FieldsUnused(value, "INVALID_ROLLUP_PROPS");
|
|
154
|
+
const body = getBridgeBody(value);
|
|
155
|
+
validateBridgeBody(body);
|
|
156
|
+
if (body.pendingOwner) validateBridge(materializeBridgeAt(value, body.pendingOwner.effectiveAt));
|
|
157
|
+
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
|
+
if (value.paused === false && body.lonePause !== null) throw new CustomError("INVALID_ROLLUP_PROPS", "lonePause requires paused");
|
|
159
|
+
if (value.closed && body.closingAt === null) throw new CustomError("INVALID_ROLLUP_PROPS", "a closed bridge needs closingAt");
|
|
160
|
+
if (!value.closed && body.closingAt !== null) throw new CustomError("INVALID_ROLLUP_PROPS", "closingAt requires closed");
|
|
161
|
+
return value;
|
|
162
|
+
};
|
|
163
|
+
|
|
164
|
+
//#endregion
|
|
165
|
+
export { bridgeSchema, createBridge, updateBridge, validateBridge };
|
|
@@ -0,0 +1,188 @@
|
|
|
1
|
+
//#region src/states/rollup-v2.d.ts
|
|
2
|
+
declare const BRIDGE_MIN_EPOCH_LEAD = 3600;
|
|
3
|
+
declare const BRIDGE_MAX_EPOCH_LEAD: number;
|
|
4
|
+
declare const BRIDGE_OWNER_TIMELOCK: number;
|
|
5
|
+
declare const BRIDGE_LONE_PAUSE_TTL: number;
|
|
6
|
+
declare const BRIDGE_LONE_PAUSE_COOLDOWN: number;
|
|
7
|
+
declare const BRIDGE_RESERVE_MIGRATION_WINDOW: number;
|
|
8
|
+
declare const BRIDGE_MAX_PAUSERS = 3;
|
|
9
|
+
declare const BRIDGE_MIN_VALIDATORS = 3;
|
|
10
|
+
declare const BRIDGE_MAX_VALIDATORS = 16;
|
|
11
|
+
declare const BRIDGE_MAX_DELAY: number;
|
|
12
|
+
declare const BRIDGE_VERSION = 2;
|
|
13
|
+
/** 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"];
|
|
15
|
+
/** 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"];
|
|
17
|
+
declare const BRIDGE_PATCH_ACTION_KEYS: readonly ["cancelPendingEpoch", "proposeOwner", "cancelOwnerProposal"];
|
|
18
|
+
interface BridgeEpoch {
|
|
19
|
+
epoch: number;
|
|
20
|
+
activeFrom: number;
|
|
21
|
+
threshold: number;
|
|
22
|
+
/** lowercase Ethereum addresses, strictly ascending */
|
|
23
|
+
validators: string[];
|
|
24
|
+
voucherValidity: number;
|
|
25
|
+
}
|
|
26
|
+
interface BridgeMember {
|
|
27
|
+
address: string;
|
|
28
|
+
pk: string;
|
|
29
|
+
endpoint: string;
|
|
30
|
+
}
|
|
31
|
+
interface BridgeBodyV2 {
|
|
32
|
+
version: 2;
|
|
33
|
+
owner: string;
|
|
34
|
+
ethChainId: string;
|
|
35
|
+
gateway: string;
|
|
36
|
+
/** informational: loaders recompute `toBridgeReserveAddress(bridge)` */
|
|
37
|
+
reserve: string;
|
|
38
|
+
minDeposit: string;
|
|
39
|
+
minWithdraw: string;
|
|
40
|
+
maxWithdraw: string;
|
|
41
|
+
withdrawFee: string;
|
|
42
|
+
releaseDailyCap: string;
|
|
43
|
+
refundDailyCap: string;
|
|
44
|
+
releaseGrace: number;
|
|
45
|
+
refundDelay: number;
|
|
46
|
+
transitionPeriod: number;
|
|
47
|
+
epochs: BridgeEpoch[];
|
|
48
|
+
members: Record<string, BridgeMember>;
|
|
49
|
+
salt: string;
|
|
50
|
+
pausers: string[];
|
|
51
|
+
lonePause: {
|
|
52
|
+
by: string;
|
|
53
|
+
until: number;
|
|
54
|
+
} | null;
|
|
55
|
+
/** txTime (s) of the last lone pause by the owner / by any other pauser: two independent cooldown tracks */
|
|
56
|
+
lastLonePause: {
|
|
57
|
+
owner?: number;
|
|
58
|
+
others?: number;
|
|
59
|
+
};
|
|
60
|
+
pendingOwner: {
|
|
61
|
+
address: string;
|
|
62
|
+
pk: string;
|
|
63
|
+
endpoint: string;
|
|
64
|
+
proposedAt: number;
|
|
65
|
+
effectiveAt: number;
|
|
66
|
+
} | null;
|
|
67
|
+
pendingMigration: {
|
|
68
|
+
to: string;
|
|
69
|
+
announcedAt: number;
|
|
70
|
+
effectiveAt: number;
|
|
71
|
+
} | null;
|
|
72
|
+
closingAt: number | null;
|
|
73
|
+
depositCutoffEthBlock: string | null;
|
|
74
|
+
/** closingAt + maxVoucherValidity + refundDelay, fixed at close */
|
|
75
|
+
finalAt: number | null;
|
|
76
|
+
migratedTo: string | null;
|
|
77
|
+
/**
|
|
78
|
+
* Refund ledger (#1505, for #1466): the amount of the bridge token that `migrate_rollup { reserve }` moved to the
|
|
79
|
+
* successor's reserve, written together with `migratedTo`. A REFUND of the migrated source debits the successor's reserve
|
|
80
|
+
* and MUST be capped by this ledger and decrement it, or the source's validators could drain the successor's own funds.
|
|
81
|
+
* Absent on bodies written before #1505 (read as null).
|
|
82
|
+
*/
|
|
83
|
+
migratedAmount?: string | null;
|
|
84
|
+
ethOwnerAttestation: {
|
|
85
|
+
address: string;
|
|
86
|
+
signature: string;
|
|
87
|
+
};
|
|
88
|
+
}
|
|
89
|
+
type AnyState = Record<string, any>;
|
|
90
|
+
/** Whether a rollup `data` field (`{ type, value }`) is a v2 body. */
|
|
91
|
+
declare function isBridgeV2Data(data: unknown): boolean;
|
|
92
|
+
/** Whether the rollup row is a v2 bridge. Rows without `data.value.version == 2` are v1 and keep today's behaviour. */
|
|
93
|
+
declare function isBridgeV2(state: unknown): boolean;
|
|
94
|
+
declare function getBridgeBody(state: unknown): BridgeBodyV2 | null;
|
|
95
|
+
declare const toSeconds: (iso: string | number | Date | undefined | null) => number;
|
|
96
|
+
declare const lc: (address: string) => string;
|
|
97
|
+
/** Ethereum addresses compare case-insensitively; OCAP addresses may carry a DID prefix. */
|
|
98
|
+
declare const sameAddress: (a: unknown, b: unknown) => boolean;
|
|
99
|
+
/** `epochAt(t) = max{ e : activeFrom(e) <= t }`, undefined (null) before the first epoch. */
|
|
100
|
+
declare function activeEpochAt(body: BridgeBodyV2, t: number): BridgeEpoch | null;
|
|
101
|
+
/** The epoch whose `activeFrom` is still in the future at `t` (there is at most one). */
|
|
102
|
+
declare function pendingEpochAt(body: BridgeBodyV2, t: number): BridgeEpoch | null;
|
|
103
|
+
declare function maxVoucherValidity(body: BridgeBodyV2): number;
|
|
104
|
+
/**
|
|
105
|
+
* Effective pause at `t`. A lone pause expires 24h after it was issued, purely by time: the persisted `paused` flag
|
|
106
|
+
* stays true, so every reader MUST use this function instead of reading `paused`.
|
|
107
|
+
*/
|
|
108
|
+
declare function isBridgePausedAt(state: AnyState, t: number): boolean;
|
|
109
|
+
/** Quorum pause = paused with no running (or expired) lone pause marker. */
|
|
110
|
+
declare function isQuorumPaused(state: AnyState): boolean;
|
|
111
|
+
/** Whether the bridge is final at `t` (closed and `closingAt + maxVoucherValidity + refundDelay` has passed). */
|
|
112
|
+
declare function isBridgeFinalAt(body: BridgeBodyV2, t: number): boolean;
|
|
113
|
+
/** The owner at `t`: a pending replacement takes effect `effectiveAt` after it was proposed. */
|
|
114
|
+
declare function effectiveOwnerAt(body: BridgeBodyV2, t: number): string;
|
|
115
|
+
/**
|
|
116
|
+
* Whether a proposed owner can be written into `owner` / `seed_validators`: a bare (no DID prefix), checksummed,
|
|
117
|
+
* non-zero Ethereum address, the public key of that address, and an http(s) endpoint.
|
|
118
|
+
*/
|
|
119
|
+
declare function isValidOwnerCandidate(p: AnyState | null | undefined): boolean;
|
|
120
|
+
/**
|
|
121
|
+
* Re-derive the informational mirrors (`validators`, `min/maxSignerCount`) from the active epoch. Called on every v2
|
|
122
|
+
* state write, so they are exact as of the last governance tx. Authority checks never read them; they read `epochs`.
|
|
123
|
+
*/
|
|
124
|
+
declare function syncBridgeView(state: AnyState, txSec: number): AnyState;
|
|
125
|
+
/**
|
|
126
|
+
* Apply every time-driven transition that is due at `txSec` to the state: a pending owner replacement whose timelock
|
|
127
|
+
* has run out rewrites BOTH `owner` and `seedValidators`. Returns the (possibly new) state; never mutates its input.
|
|
128
|
+
*/
|
|
129
|
+
declare function materializeBridgeAt(state: AnyState, txSec: number): AnyState;
|
|
130
|
+
/** Full structural validation of a stored v2 body. */
|
|
131
|
+
declare function validateBridgeBody(body: BridgeBodyV2): BridgeBodyV2;
|
|
132
|
+
/** Whether a v1 numeric field is "zero or empty" (the v2 requirement for unused v1 fields). */
|
|
133
|
+
declare function isZeroish(v: unknown): boolean;
|
|
134
|
+
/** v1 fields a v2 bridge must leave at zero / empty (stake, block size / interval, fees, block height / hash, waits). */
|
|
135
|
+
declare const BRIDGE_V1_ZERO_FIELDS: readonly string[];
|
|
136
|
+
declare function assertV1FieldsUnused(attrs: AnyState, errorCode: 'INVALID_ROLLUP_PROPS' | 'INVALID_ROLLUP_UPDATE'): void;
|
|
137
|
+
/**
|
|
138
|
+
* Structural rules for any transition of a v2 row, enforced by the state layer on every `update`:
|
|
139
|
+
* `version`, `gateway`, `ethChainId`, `reserve`, `salt`, `withdrawFee`, `transitionPeriod`, `ethOwnerAttestation`,
|
|
140
|
+
* `issuer` and the token fields are immutable; epochs are append-only (one new epoch, or the last pending one removed);
|
|
141
|
+
* `members` only grows; the owner changes only through a due `pendingOwner`; `migratedTo` is written once.
|
|
142
|
+
*/
|
|
143
|
+
declare function assertBridgeTransition(prev: AnyState, next: AnyState, txSec: number | null): void;
|
|
144
|
+
interface BridgeConsent {
|
|
145
|
+
address: string;
|
|
146
|
+
endpoint: string;
|
|
147
|
+
signature: string;
|
|
148
|
+
}
|
|
149
|
+
interface BridgeCreateInput {
|
|
150
|
+
body: Omit<BridgeBodyV2, 'owner' | 'reserve' | 'members' | 'lonePause' | 'lastLonePause' | 'pendingOwner' | 'pendingMigration' | 'closingAt' | 'depositCutoffEthBlock' | 'finalAt' | 'migratedTo' | 'migratedAmount'>;
|
|
151
|
+
consents: BridgeConsent[];
|
|
152
|
+
initialReserve: string;
|
|
153
|
+
}
|
|
154
|
+
/** Parse and validate `itx.data.value` of a v2 `create_rollup` (pure shape checks; signatures are checked by the protocol). */
|
|
155
|
+
declare function parseBridgeCreateData(value: AnyState): BridgeCreateInput;
|
|
156
|
+
type BridgePatchKind = 'owner-quorum' | 'propose-owner' | 'cancel-owner-proposal';
|
|
157
|
+
interface BridgePatchPlan {
|
|
158
|
+
kind: BridgePatchKind;
|
|
159
|
+
/** the body after the patch */
|
|
160
|
+
body: BridgeBodyV2;
|
|
161
|
+
/** a pending epoch was removed */
|
|
162
|
+
cancelledEpoch: BridgeEpoch | null;
|
|
163
|
+
}
|
|
164
|
+
/**
|
|
165
|
+
* 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
|
|
167
|
+
* else needs owner + quorum. Frozen keys (version, epochs, reserve, gateway, ethChainId, token fields...) are rejected.
|
|
168
|
+
*/
|
|
169
|
+
declare function planBridgePatch(body: BridgeBodyV2, patch: AnyState, txSec: number): BridgePatchPlan;
|
|
170
|
+
interface MembershipRequest {
|
|
171
|
+
action: 'join' | 'leave';
|
|
172
|
+
validator: string;
|
|
173
|
+
threshold: number;
|
|
174
|
+
activeFrom: number;
|
|
175
|
+
voucherValidity: number;
|
|
176
|
+
}
|
|
177
|
+
interface MembershipPlan {
|
|
178
|
+
epoch: BridgeEpoch;
|
|
179
|
+
/** the epoch whose quorum must sign: the active epoch at txTime */
|
|
180
|
+
signingEpoch: BridgeEpoch;
|
|
181
|
+
}
|
|
182
|
+
/** Epoch rules of §v2.2: `epoch = last + 1`, lead window, `2*threshold > n`, `n >= 3`, at most one pending epoch. */
|
|
183
|
+
declare function planMembership(body: BridgeBodyV2, req: MembershipRequest, txSec: number): MembershipPlan;
|
|
184
|
+
declare function lonePauseTrack(body: BridgeBodyV2, by: string): 'owner' | 'others';
|
|
185
|
+
/** Validate and apply a lone pause by `by` (a member of `pausers`) at `txSec`. */
|
|
186
|
+
declare function applyLonePause(body: BridgeBodyV2, by: string, txSec: number): BridgeBodyV2;
|
|
187
|
+
//#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 };
|