@reyaxyz/strategy-format 0.0.0-stage → 0.3.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/dist/read.js ADDED
@@ -0,0 +1,330 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.readStrategy = exports.MAX_DOCUMENT_BYTES = void 0;
7
+ const zod_1 = require("zod");
8
+ const hash_1 = require("./hash");
9
+ const workflow_v3_schema_json_1 = __importDefault(require("./schema/workflow-v3.schema.json"));
10
+ /** AGT-212's cap on a document, in UTF-8 bytes. */
11
+ exports.MAX_DOCUMENT_BYTES = 12288;
12
+ /**
13
+ * Reads a v3 document so a client can show and hash it. A convenience, never a validator: it answers
14
+ * "do I understand every byte I am about to show and hash?", and the service stays the only judge of
15
+ * whether the strategy is valid. Stops at the first failure. `path` is dotted, as the service's
16
+ * (`rules.r_5.when.band`), and empty for the whole text.
17
+ */
18
+ function readStrategy(text) {
19
+ const bytes = new TextEncoder().encode(text);
20
+ if (bytes.length > exports.MAX_DOCUMENT_BYTES) {
21
+ return refuse('document_too_large', '', `${bytes.length} bytes; at most ${exports.MAX_DOCUMENT_BYTES}`);
22
+ }
23
+ if (tooDeep(text)) {
24
+ return refuse('depth_exceeded', '', `nesting over ${MAX_DEPTH}`);
25
+ }
26
+ let parsed;
27
+ try {
28
+ parsed = JSON.parse(text);
29
+ }
30
+ catch (e) {
31
+ return refuse('json_invalid', '', e.message);
32
+ }
33
+ // One comparison refuses repeated keys, `1.0`, `1e2`, integers past 2^53, whitespace and key order.
34
+ if ((0, hash_1.canonical)(parsed) !== text) {
35
+ return refuse('not_canonical', '', 'the text is not the canonical form of the document');
36
+ }
37
+ const failure = explicitDefault(parsed) ??
38
+ lonelySurrogate(parsed) ??
39
+ schemaFailure(parsed) ??
40
+ extraChecks(parsed) ??
41
+ exprTooLarge(parsed);
42
+ if (failure)
43
+ return failure;
44
+ return {
45
+ ok: true,
46
+ doc: parsed,
47
+ versionHash: (0, hash_1.keccakHex)(bytes),
48
+ };
49
+ }
50
+ exports.readStrategy = readStrategy;
51
+ const refuse = (code, path, message) => ({
52
+ ok: false,
53
+ code,
54
+ path,
55
+ message,
56
+ });
57
+ /** The parser's nesting cap. Checked on the text before parsing, so nothing below recurses deeper. */
58
+ const MAX_DEPTH = 32;
59
+ /** The container nesting, counted as the parser's `check_depth` counts it (brackets outside strings). */
60
+ function tooDeep(text) {
61
+ let depth = 0;
62
+ let inString = false;
63
+ let escaped = false;
64
+ for (const c of text) {
65
+ if (inString) {
66
+ if (escaped)
67
+ escaped = false;
68
+ else if (c === '\\')
69
+ escaped = true;
70
+ else if (c === '"')
71
+ inString = false;
72
+ }
73
+ else if (c === '"')
74
+ inString = true;
75
+ else if (c === '[' || c === '{') {
76
+ if (++depth > MAX_DEPTH)
77
+ return true;
78
+ }
79
+ else if (c === ']' || c === '}')
80
+ depth = Math.max(0, depth - 1);
81
+ }
82
+ return false;
83
+ }
84
+ /** Calls `visit` on every object and array in `value`, depth first, with its dotted path. */
85
+ function findIn(value, visit, path = '') {
86
+ if (value === null || typeof value !== 'object')
87
+ return undefined;
88
+ const hit = visit(value, path);
89
+ if (hit)
90
+ return hit;
91
+ for (const [k, v] of Object.entries(value)) {
92
+ const hit = findIn(v, visit, path ? `${path}.${k}` : k);
93
+ if (hit)
94
+ return hit;
95
+ }
96
+ return undefined;
97
+ }
98
+ const at = (path, key) => (path ? `${path}.${key}` : key);
99
+ /**
100
+ * The format has one spelling per value, so a default written out is refused (the parser's
101
+ * `explicit_default`). The schema refuses each of these too; this names them. Only these objects
102
+ * carry these fields: a state's `name`, a resting order's `taker_ok`, a `limit_orders` action's
103
+ * `keep`, a crossing's `band`, a function's `interval_secs`.
104
+ */
105
+ function explicitDefault(doc) {
106
+ return findIn(doc, (o, path) => {
107
+ const written = (key, value) => refuse('explicit_default', at(path, key), `remove \`${key}\`; ${value} is the default`);
108
+ if (o.name === '')
109
+ return written('name', '""');
110
+ if (o.taker_ok === false)
111
+ return written('taker_ok', '`false`');
112
+ if (o.keep === false)
113
+ return written('keep', '`false`');
114
+ if (o.kind === 'cross' && o.band === '0')
115
+ return written('band', '0');
116
+ if (o.kind === 'fn' && o.interval_secs === 60)
117
+ return written('interval_secs', '60');
118
+ return undefined;
119
+ });
120
+ }
121
+ let schema;
122
+ function schemaFailure(doc) {
123
+ // `fromJSONSchema` is "semi-experimental" in zod 4: the version is pinned and reya-chain's
124
+ // fixtures, run in CI, are the guard on its behaviour.
125
+ schema ?? (schema = zod_1.z.fromJSONSchema(relaxed(workflow_v3_schema_json_1.default)));
126
+ const result = schema.safeParse(doc);
127
+ if (result.success)
128
+ return undefined;
129
+ const { path, message } = pinpoint(result.error.issues[0], []);
130
+ return refuse('schema_invalid', path.join('.'), message);
131
+ }
132
+ /**
133
+ * zod reports a fault inside a `oneOf` at the union, as "Invalid input". Step into the branch the
134
+ * document meant (its `kind` matched; else the one with the fewest faults) to name the field.
135
+ */
136
+ function pinpoint(issue, base) {
137
+ const here = [...base, ...issue.path];
138
+ const kindFailed = (b) => b.some((i) => i.path.length === 1 && i.path[0] === 'kind');
139
+ const branch = [...(issue.errors ?? [])]
140
+ .filter((b) => b.length)
141
+ .sort((a, b) => Number(kindFailed(a)) - Number(kindFailed(b)) || a.length - b.length)[0];
142
+ return branch
143
+ ? pinpoint(branch[0], here)
144
+ : { path: here, message: issue.message };
145
+ }
146
+ /**
147
+ * reya-chain writes some later-phase bounds into the schema it generates (`schema.rs`, `constrain`):
148
+ * the parser reads these fields as any u32, and the structure phase refuses the range
149
+ * (`value_out_of_range`). The reader must accept what only a later phase refuses, so it drops them.
150
+ */
151
+ const LATER_PHASE_RANGES = [
152
+ 'max_slippage_bps',
153
+ 'period',
154
+ 'ago_secs',
155
+ 'top',
156
+ 'max_size',
157
+ ];
158
+ /** `rounds` is a u32 in the parser (`integer_out_of_range` above it), but the schema says 2^53 - 1. */
159
+ const U32_ONLY = ['rounds'];
160
+ const U32_MAX = 4294967295;
161
+ function relaxed(json) {
162
+ const copy = JSON.parse(JSON.stringify(json));
163
+ (function walk(node) {
164
+ if (!node || typeof node !== 'object')
165
+ return;
166
+ const props = node.properties;
167
+ for (const name of [...LATER_PHASE_RANGES, ...U32_ONLY]) {
168
+ const p = props?.[name];
169
+ if (p) {
170
+ if (LATER_PHASE_RANGES.includes(name))
171
+ p.minimum = 0;
172
+ p.maximum = U32_MAX;
173
+ }
174
+ }
175
+ // A negative band is the structure phase's; "0" written out is `explicit_default`, checked first.
176
+ if (props?.band) {
177
+ props.band.pattern = '^-?(0\\.[0-9]*[1-9]|[1-9][0-9]*(\\.[0-9]*[1-9])?)$';
178
+ }
179
+ Object.values(node).forEach(walk);
180
+ })(copy);
181
+ return copy;
182
+ }
183
+ /** The hash is over UTF-8, so every string must be well-formed Unicode (no lone surrogate). */
184
+ function lonelySurrogate(doc) {
185
+ const bad = (s) => /[\uD800-\uDFFF]/u.test(s);
186
+ return findIn(doc, (o, path) => {
187
+ for (const [k, v] of Object.entries(o)) {
188
+ if (bad(k) || (typeof v === 'string' && bad(v))) {
189
+ return refuse('string_invalid_scalar', at(path, k), 'not well-formed Unicode');
190
+ }
191
+ }
192
+ return undefined;
193
+ });
194
+ }
195
+ /** C0, DEL, C1 and the Unicode direction controls, as the parser's `is_label_control`. */
196
+ const LABEL_CONTROL =
197
+ // eslint-disable-next-line no-control-regex
198
+ /[\u0000-\u001f\u007f-\u009f\u202a-\u202e\u2066-\u2069\u200e\u200f\u061c]/;
199
+ /**
200
+ * Four parse-phase rules the schema cannot express. Sentences are keyed by block id, so a repeated id
201
+ * would hide a line; a level with both `pct` and `distance` would show one and sign two; a control
202
+ * character can make a label read as something else.
203
+ */
204
+ function extraChecks(doc) {
205
+ const seen = new Set();
206
+ const use = (id, path) => {
207
+ if (seen.has(id))
208
+ return refuse('id_duplicate', path, `\`${id}\` is used twice`);
209
+ seen.add(id);
210
+ return undefined;
211
+ };
212
+ for (const map of ['states', 'rules', 'actions', 'series']) {
213
+ for (const id of Object.keys(doc[map] ?? {})) {
214
+ const hit = use(id, `${map}.${id}`);
215
+ if (hit)
216
+ return hit;
217
+ }
218
+ }
219
+ return findIn(doc, (o, path) => {
220
+ if (typeof o.id === 'string') {
221
+ const hit = use(o.id, at(path, 'id'));
222
+ if (hit)
223
+ return hit;
224
+ }
225
+ if ((o.kind === 'from_entry' || o.kind === 'trailing') &&
226
+ 'pct' in o === 'distance' in o) {
227
+ return refuse('one_of_violated', path, 'write exactly one of `pct`, `distance`');
228
+ }
229
+ if (o.kind === 'loop_head' && 'rounds' in o !== 'then' in o) {
230
+ return refuse('rounds_then_mismatch', path, 'write both `rounds` and `then`, or neither');
231
+ }
232
+ if (o.kind === 'prediction') {
233
+ const label = (o.label ?? {});
234
+ const fields = [
235
+ ['market', o.market],
236
+ ['outcome', o.outcome],
237
+ ['label.question', label.question],
238
+ ['label.outcome', label.outcome],
239
+ ];
240
+ for (const [key, value] of fields) {
241
+ if (typeof value === 'string' && LABEL_CONTROL.test(value)) {
242
+ return refuse('label_control_character', at(path, key), 'a control or direction character');
243
+ }
244
+ }
245
+ }
246
+ return undefined;
247
+ });
248
+ }
249
+ /** The parser's expression caps (`MAX_EXPR_DEPTH`, `MAX_EXPR_NODES_PER_DOC`): a leaf is depth 1. */
250
+ const MAX_EXPR_DEPTH = 8;
251
+ const MAX_EXPR_NODES = 256;
252
+ const children = (e) => e.kind === 'op' || e.kind === 'fn'
253
+ ? e.args
254
+ : e.kind === 'input' && e.of
255
+ ? [e.of]
256
+ : [];
257
+ const depth = (e) => 1 + Math.max(0, ...children(e).map(depth));
258
+ const nodes = (e) => children(e).reduce((n, c) => n + nodes(c), 1);
259
+ /**
260
+ * `expr_too_large`, as the parser's `expr_limits`: each tree at most 8 deep (at its root), and at most
261
+ * 256 nodes over the document's trees (at the root path). The trees are `expr_sites`', in its order.
262
+ */
263
+ function exprTooLarge(doc) {
264
+ const sites = [];
265
+ const level = (path, l) => {
266
+ if (l?.kind === 'expr')
267
+ sites.push([`${path}.value`, l.value]);
268
+ };
269
+ const size = (path, s) => {
270
+ if (s && 'expr' in s)
271
+ sites.push([`${path}.expr`, s.expr]);
272
+ };
273
+ for (const [id, r] of Object.entries(doc.rules ?? {})) {
274
+ if (r.if)
275
+ sites.push([`rules.${id}.if`, r.if]);
276
+ const w = r.when;
277
+ if (w.kind === 'cross') {
278
+ sites.push([`rules.${id}.when.value`, w.value]);
279
+ sites.push([`rules.${id}.when.level`, w.level]);
280
+ }
281
+ if (w.kind === 'stop_loss' || w.kind === 'take_profit') {
282
+ w.levels.forEach((lv, i) => {
283
+ level(`rules.${id}.when.levels.${i}.at`, lv.at);
284
+ size(`rules.${id}.when.levels.${i}.size`, lv.size);
285
+ });
286
+ }
287
+ }
288
+ for (const [id, a] of Object.entries(doc.actions ?? {})) {
289
+ const path = `actions.${id}`;
290
+ if (a.kind === 'order')
291
+ size(`${path}.size`, a.size);
292
+ if (a.kind === 'reduce')
293
+ size(`${path}.by`, a.by);
294
+ if (a.kind === 'limit_orders') {
295
+ a.orders.forEach((o, k) => {
296
+ size(`${path}.orders.${k}.size`, o.size);
297
+ size(`${path}.orders.${k}.price`, o.price);
298
+ });
299
+ }
300
+ if (a.kind === 'rebalance') {
301
+ a.weights.forEach((w, k) => {
302
+ if (w.if)
303
+ sites.push([`${path}.weights.${k}.if`, w.if]);
304
+ });
305
+ }
306
+ if (a.kind === 'move_stop')
307
+ level(`${path}.to`, a.to);
308
+ }
309
+ (doc.lists ?? []).forEach((l, i) => {
310
+ if (l.kind === 'filter')
311
+ sites.push([`lists.${i}.where`, l.where]);
312
+ if (l.kind === 'rank')
313
+ sites.push([`lists.${i}.by`, l.by]);
314
+ if (l.kind === 'fixed') {
315
+ l.members.forEach((m, j) => size(`lists.${i}.members.${j}.size`, m.size));
316
+ }
317
+ });
318
+ let total = 0;
319
+ for (const [path, e] of sites) {
320
+ const d = depth(e);
321
+ if (d > MAX_EXPR_DEPTH) {
322
+ return refuse('expr_too_large', path, `depth ${d}; at most ${MAX_EXPR_DEPTH}`);
323
+ }
324
+ total += nodes(e);
325
+ }
326
+ if (total > MAX_EXPR_NODES) {
327
+ return refuse('expr_too_large', '', `${total} expression nodes; at most ${MAX_EXPR_NODES}`);
328
+ }
329
+ return undefined;
330
+ }
@@ -0,0 +1,9 @@
1
+ {
2
+ "repo": "Reya-Labs/reya-chain",
3
+ "commit": "18d790af1b806a3778ed83a9b957c450ed0b076a",
4
+ "root": "crates/workflow-core",
5
+ "sha256": {
6
+ "schema/workflow-v3.schema.json": "a140da1fa6ced2394e1b4386e0c957f909a23b28483083f0a308029a69f55414",
7
+ "schema/workflow-v3.accepted-kinds.json": "a836cc902a26b04606248155f07f21f5c29ca53ff65c881674a718f2294cd701"
8
+ }
9
+ }
@@ -0,0 +1,226 @@
1
+ {
2
+ "devnet1": {
3
+ "actions": [
4
+ "order",
5
+ "limit_orders",
6
+ "close",
7
+ "reduce"
8
+ ],
9
+ "expr_functions": [],
10
+ "expr_inputs": [
11
+ "balance",
12
+ "position",
13
+ "entry",
14
+ "rounds",
15
+ "wins",
16
+ "losses",
17
+ "pnl",
18
+ "remembered"
19
+ ],
20
+ "expr_nodes": [
21
+ "num",
22
+ "series",
23
+ "outside",
24
+ "row",
25
+ "input",
26
+ "op"
27
+ ],
28
+ "expr_ops": [
29
+ "add",
30
+ "sub",
31
+ "mul",
32
+ "div",
33
+ "neg",
34
+ "gt",
35
+ "ge",
36
+ "lt",
37
+ "le",
38
+ "eq",
39
+ "ne",
40
+ "and",
41
+ "or",
42
+ "not"
43
+ ],
44
+ "expr_series": [
45
+ "mark",
46
+ "funding_rate",
47
+ "funding_rate_avg_15m",
48
+ "funding_paid"
49
+ ],
50
+ "lists": [
51
+ "fixed"
52
+ ],
53
+ "on_liquidation": [
54
+ "close_and_end"
55
+ ],
56
+ "on_margin_skip": [
57
+ "keep_running"
58
+ ],
59
+ "refused_shapes": [
60
+ {
61
+ "feature": "stop_ladder",
62
+ "rule": "a stop_loss or take_profit with more than one level, or a level with a size",
63
+ "shape": "stop_ladder"
64
+ },
65
+ {
66
+ "feature": "lists_more_than_one",
67
+ "rule": "more than one list",
68
+ "shape": "lists_more_than_one"
69
+ },
70
+ {
71
+ "feature": "engine_memory",
72
+ "rule": "a remembered input other than of an outside pin with remember_anchor start, or in a list",
73
+ "shape": "remembered"
74
+ },
75
+ {
76
+ "feature": "fn_window",
77
+ "rule": "anchor or interval_secs on a function",
78
+ "shape": "fn_window_fields"
79
+ },
80
+ {
81
+ "feature": "price_expr",
82
+ "rule": "a limit order price written as an expression",
83
+ "shape": "price_expr"
84
+ }
85
+ ],
86
+ "series_pins": [
87
+ "prediction"
88
+ ],
89
+ "states": [
90
+ "normal",
91
+ "loop_head",
92
+ "final"
93
+ ],
94
+ "stop_levels": [
95
+ "price",
96
+ "from_entry"
97
+ ],
98
+ "triggers": [
99
+ "start",
100
+ "cross",
101
+ "every",
102
+ "at",
103
+ "elapsed",
104
+ "filled",
105
+ "stop_loss",
106
+ "take_profit",
107
+ "instances_ended",
108
+ "refused",
109
+ "close_open",
110
+ "source_unreadable",
111
+ "source_ended"
112
+ ]
113
+ },
114
+ "mainnet": {
115
+ "actions": [
116
+ "order",
117
+ "limit_orders",
118
+ "close",
119
+ "reduce"
120
+ ],
121
+ "expr_functions": [],
122
+ "expr_inputs": [
123
+ "balance",
124
+ "position",
125
+ "entry",
126
+ "rounds",
127
+ "wins",
128
+ "losses",
129
+ "pnl",
130
+ "remembered"
131
+ ],
132
+ "expr_nodes": [
133
+ "num",
134
+ "series",
135
+ "outside",
136
+ "row",
137
+ "input",
138
+ "op"
139
+ ],
140
+ "expr_ops": [
141
+ "add",
142
+ "sub",
143
+ "mul",
144
+ "div",
145
+ "neg",
146
+ "gt",
147
+ "ge",
148
+ "lt",
149
+ "le",
150
+ "eq",
151
+ "ne",
152
+ "and",
153
+ "or",
154
+ "not"
155
+ ],
156
+ "expr_series": [
157
+ "mark",
158
+ "funding_rate",
159
+ "funding_rate_avg_15m",
160
+ "funding_paid"
161
+ ],
162
+ "lists": [
163
+ "fixed"
164
+ ],
165
+ "on_liquidation": [
166
+ "close_and_end"
167
+ ],
168
+ "on_margin_skip": [
169
+ "keep_running"
170
+ ],
171
+ "refused_shapes": [
172
+ {
173
+ "feature": "stop_ladder",
174
+ "rule": "a stop_loss or take_profit with more than one level, or a level with a size",
175
+ "shape": "stop_ladder"
176
+ },
177
+ {
178
+ "feature": "lists_more_than_one",
179
+ "rule": "more than one list",
180
+ "shape": "lists_more_than_one"
181
+ },
182
+ {
183
+ "feature": "engine_memory",
184
+ "rule": "a remembered input other than of an outside pin with remember_anchor start, or in a list",
185
+ "shape": "remembered"
186
+ },
187
+ {
188
+ "feature": "fn_window",
189
+ "rule": "anchor or interval_secs on a function",
190
+ "shape": "fn_window_fields"
191
+ },
192
+ {
193
+ "feature": "price_expr",
194
+ "rule": "a limit order price written as an expression",
195
+ "shape": "price_expr"
196
+ }
197
+ ],
198
+ "series_pins": [
199
+ "prediction"
200
+ ],
201
+ "states": [
202
+ "normal",
203
+ "loop_head",
204
+ "final"
205
+ ],
206
+ "stop_levels": [
207
+ "price",
208
+ "from_entry"
209
+ ],
210
+ "triggers": [
211
+ "start",
212
+ "cross",
213
+ "every",
214
+ "at",
215
+ "elapsed",
216
+ "filled",
217
+ "stop_loss",
218
+ "take_profit",
219
+ "instances_ended",
220
+ "refused",
221
+ "close_open",
222
+ "source_unreadable",
223
+ "source_ended"
224
+ ]
225
+ }
226
+ }