@orbs-network/spot 2.2.0 → 2.2.4
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/README.md +10 -9
- package/SKILL.md +9 -6
- package/index.css +4 -2
- package/index.html +1 -1
- package/package.json +1 -1
- package/server.json +2 -2
- package/skill/references/01-quickstart.md +9 -10
- package/skill/references/02-params.md +3 -3
- package/skill/references/03-sign.md +1 -2
- package/skill/references/04-patterns.md +1 -1
- package/skill/scripts/order.js +244 -20
package/README.md
CHANGED
|
@@ -10,7 +10,7 @@ Start with these files:
|
|
|
10
10
|
|
|
11
11
|
1. [`SKILL.md`](./SKILL.md) for the execution workflow
|
|
12
12
|
2. [`manifest.json`](./manifest.json) for machine-readable discovery
|
|
13
|
-
3. [`skill/scripts/order.js`](./skill/scripts/order.js)
|
|
13
|
+
3. [`skill/scripts/order.js`](./skill/scripts/order.js) as the canonical skill helper entrypoint
|
|
14
14
|
|
|
15
15
|
The skill bundle is available through these surfaces:
|
|
16
16
|
|
|
@@ -24,7 +24,7 @@ The skill bundle is available through these surfaces:
|
|
|
24
24
|
- 🎯 **Intent Mapping**: Translate user intent into market, limit, TWAP, stop-loss, take-profit, and delayed-start orders
|
|
25
25
|
- ✍️ **Signing Prep**: Produce approval calldata, EIP-712 typed data, and relay-ready payloads
|
|
26
26
|
- 🔎 **Machine Discovery**: Read supported chains, runtime addresses, references, and assets from `manifest.json`
|
|
27
|
-
- 🧰 **Direct Execution Tooling**: Use `skill/scripts/order.js`
|
|
27
|
+
- 🧰 **Direct Execution Tooling**: Use `skill/scripts/order.js` as the canonical skill helper
|
|
28
28
|
|
|
29
29
|
## Protocol Guarantees
|
|
30
30
|
|
|
@@ -86,9 +86,9 @@ struct Input {
|
|
|
86
86
|
|
|
87
87
|
struct Output {
|
|
88
88
|
address token; // Output token address
|
|
89
|
-
uint256 limit; // Minimum acceptable output (limit)
|
|
90
|
-
uint256 triggerLower; // Lower trigger boundary (stop-loss style)
|
|
91
|
-
uint256 triggerUpper; // Upper trigger boundary (take-profit style)
|
|
89
|
+
uint256 limit; // Minimum acceptable output (limit), in output-token decimals, per chunks
|
|
90
|
+
uint256 triggerLower; // Lower trigger boundary (stop-loss style), in output-token decimals, per chunk
|
|
91
|
+
uint256 triggerUpper; // Upper trigger boundary (take-profit style), in output-token decimals, per chunk
|
|
92
92
|
address recipient; // Where to send output tokens
|
|
93
93
|
}
|
|
94
94
|
|
|
@@ -98,10 +98,11 @@ struct Output {
|
|
|
98
98
|
|
|
99
99
|
1. **Order Creation**: User signs one EIP-712 order with chunk size, total amount, limits, slippage tolerance, epoch interval, and deadline
|
|
100
100
|
2. **Price Attestation**: Cosigner signs both trigger and current market price data (input/output token ratios)
|
|
101
|
-
3. **
|
|
102
|
-
4. **
|
|
103
|
-
5. **
|
|
104
|
-
6. **
|
|
101
|
+
3. **Trigger Units**: `output.limit`, `triggerLower`, and `triggerUpper` are per-chunk output-token amounts encoded in the output token's decimals
|
|
102
|
+
4. **Execution**: Whitelisted executor calls `Executor.execute()` with order and execution parameters
|
|
103
|
+
5. **Validation**: OrderReactor validates signatures, checks epoch windows, enforces `start`, checks trigger/current timestamp ordering, and applies slippage protection
|
|
104
|
+
6. **Settlement**: Reactor transfers input tokens, executor runs adapter logic via delegatecall, ensures minimum output, and settles
|
|
105
|
+
7. **Distribution**: Surplus tokens are automatically distributed between swapper and optional referrer based on configured shares
|
|
105
106
|
|
|
106
107
|
## Order Types & Examples
|
|
107
108
|
|
package/SKILL.md
CHANGED
|
@@ -39,22 +39,25 @@ Before executing this skill in any host agent platform or skill runner:
|
|
|
39
39
|
|
|
40
40
|
1. Read [skill/references/01-quickstart.md](skill/references/01-quickstart.md) for the minimum end-to-end flow.
|
|
41
41
|
2. Read [skill/references/02-params.md](skill/references/02-params.md) when you need field semantics, defaults, units, or validation rules.
|
|
42
|
-
3. Read [skill/references/03-sign.md](skill/references/03-sign.md) for signing,
|
|
42
|
+
3. Read [skill/references/03-sign.md](skill/references/03-sign.md) for signing, signature formats, and direct onchain cancel.
|
|
43
43
|
4. Read [skill/references/04-patterns.md](skill/references/04-patterns.md) to map user intent into market, limit, stop-loss, take-profit, delayed, or chunked orders.
|
|
44
44
|
5. Optional helper for token lookup: [skill/assets/token-addressbook.md](skill/assets/token-addressbook.md).
|
|
45
45
|
6. Use [skill/assets/repermit.skeleton.json](skill/assets/repermit.skeleton.json) when you need the raw RePermit witness typed-data skeleton.
|
|
46
46
|
7. Use [skill/assets/web3-sign-and-submit.example.js](skill/assets/web3-sign-and-submit.example.js) for a browser or injected-provider signing and submit example.
|
|
47
47
|
8. Inspect [manifest.json](manifest.json) for the machine-readable entrypoint, references, live supported-chain matrix, sink URL, and runtime contract addresses.
|
|
48
|
-
9. Use only [skill/scripts/order.js](skill/scripts/order.js) to prepare, submit, and
|
|
48
|
+
9. Use only [skill/scripts/order.js](skill/scripts/order.js) to prepare, submit, query, and watch orders.
|
|
49
49
|
|
|
50
50
|
## Guardrails
|
|
51
51
|
|
|
52
52
|
1. Supported chains and runtime addresses live in [manifest.json](manifest.json).
|
|
53
53
|
2. Use only the provided [skill/scripts/order.js](skill/scripts/order.js). Do not send typed data or signatures anywhere else.
|
|
54
|
-
3.
|
|
54
|
+
3. Use [skill/references/02-params.md](skill/references/02-params.md) as the authoritative source for native-asset rules and for `output.limit` / trigger units.
|
|
55
|
+
4. Detailed order behavior, parameter rules, signing rules, and order-shape guidance live in the reference files above.
|
|
55
56
|
|
|
56
57
|
## Commands
|
|
57
58
|
|
|
58
|
-
1. `node skill/scripts/order.js prepare --params <params.json|-> [--out <prepared.json>]`
|
|
59
|
-
2. `node skill/scripts/order.js submit --prepared <prepared.json|-> --signature <0x...|json>`
|
|
60
|
-
3.
|
|
59
|
+
1. Prepare: `node skill/scripts/order.js prepare --params <params.json|-> [--out <prepared.json>]`
|
|
60
|
+
2. Submit: `node skill/scripts/order.js submit --prepared <prepared.json|-> --signature <0x...|json>`
|
|
61
|
+
3. Submit variants: `--signature-file <file|->` or `--r <0x...> --s <0x...> --v <0x...>`
|
|
62
|
+
4. Query: `node skill/scripts/order.js query --swapper <0x...>` or `--hash <0x...>`
|
|
63
|
+
5. Watch: `node skill/scripts/order.js watch --hash <0x...> [--interval <seconds>] [--timeout <seconds>]`
|
package/index.css
CHANGED
|
@@ -30,7 +30,8 @@ body {
|
|
|
30
30
|
}
|
|
31
31
|
|
|
32
32
|
main {
|
|
33
|
-
|
|
33
|
+
width: fit-content;
|
|
34
|
+
max-width: 100%;
|
|
34
35
|
margin: 0 auto;
|
|
35
36
|
padding: 28px 24px;
|
|
36
37
|
border: 1px solid var(--panel-border);
|
|
@@ -48,9 +49,10 @@ ol {
|
|
|
48
49
|
}
|
|
49
50
|
|
|
50
51
|
h1 {
|
|
51
|
-
font-size: clamp(
|
|
52
|
+
font-size: clamp(1rem, 4.8vw, 3rem);
|
|
52
53
|
line-height: 0.95;
|
|
53
54
|
letter-spacing: -0.04em;
|
|
55
|
+
white-space: nowrap;
|
|
54
56
|
}
|
|
55
57
|
|
|
56
58
|
p {
|
package/index.html
CHANGED
|
@@ -10,7 +10,7 @@
|
|
|
10
10
|
<body>
|
|
11
11
|
<main>
|
|
12
12
|
<h1>Spot Advanced Swap Orders</h1>
|
|
13
|
-
<p>Hosted raw files for AI agents.</p>
|
|
13
|
+
<p>Use for gasless non-custodial EVM market, limit, TWAP, stop-loss, take-profit, delayed-start orders. Hosted raw files for AI agents.</p>
|
|
14
14
|
|
|
15
15
|
<section>
|
|
16
16
|
<h2>Skill</h2>
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@orbs-network/spot",
|
|
3
|
-
"version": "2.2.
|
|
3
|
+
"version": "2.2.4",
|
|
4
4
|
"mcpName": "io.github.orbs-network/spot",
|
|
5
5
|
"description": "**A DeFi protocol for noncustodial advanced order types on EVM chains.**",
|
|
6
6
|
"homepage": "https://github.com/orbs-network/spot#readme",
|
package/server.json
CHANGED
|
@@ -7,12 +7,12 @@
|
|
|
7
7
|
"url": "https://github.com/orbs-network/spot",
|
|
8
8
|
"source": "github"
|
|
9
9
|
},
|
|
10
|
-
"version": "2.2.
|
|
10
|
+
"version": "2.2.4",
|
|
11
11
|
"packages": [
|
|
12
12
|
{
|
|
13
13
|
"registryType": "npm",
|
|
14
14
|
"identifier": "@orbs-network/spot",
|
|
15
|
-
"version": "2.2.
|
|
15
|
+
"version": "2.2.4",
|
|
16
16
|
"transport": {
|
|
17
17
|
"type": "stdio"
|
|
18
18
|
}
|
|
@@ -1,13 +1,12 @@
|
|
|
1
1
|
# Quickstart
|
|
2
2
|
|
|
3
3
|
1. Required fields: `chainId`, `swapper`, `input.token`, `input.amount`, `output.token`.
|
|
4
|
-
2.
|
|
5
|
-
3.
|
|
6
|
-
4.
|
|
7
|
-
5.
|
|
8
|
-
6.
|
|
9
|
-
7.
|
|
10
|
-
8.
|
|
11
|
-
9.
|
|
12
|
-
10.
|
|
13
|
-
11. When measuring a fill onchain, sum both transfers to the swapper: the main fill and the surplus refund. Measuring only the main fill undercounts actual output by up to the slippage tolerance.
|
|
4
|
+
2. Choose the intended order shape before preparing: market, limit, stop-loss, take-profit, delayed-start, or chunked/TWAP.
|
|
5
|
+
3. Prepare the order with the helper.
|
|
6
|
+
4. If approval is needed, send `prepared.approval.tx`.
|
|
7
|
+
5. Prefer infinite approval to `RePermit` to save future approval gas costs; no approval reset is needed.
|
|
8
|
+
6. Sign `prepared.typedData` as the `swapper`.
|
|
9
|
+
7. Submit the signed order.
|
|
10
|
+
8. Query the order by `swapper` or `hash`.
|
|
11
|
+
9. Watch until terminal state. Default polling is every 5 seconds, timeout `0` means no timeout, and transient network errors are retried automatically.
|
|
12
|
+
10. When measuring a fill onchain, sum both transfers to the swapper: the main fill and the surplus refund. Measuring only the main fill undercounts actual output by up to the slippage tolerance.
|
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
# Params
|
|
2
2
|
|
|
3
|
-
Use this file for field semantics, defaults, units, and validation.
|
|
3
|
+
Use this file for field semantics, defaults, units, and validation.
|
|
4
4
|
|
|
5
5
|
1. Required: `chainId`, `swapper`, `input.token`, `input.amount`, `output.token`.
|
|
6
6
|
2. Optional: `input.maxAmount`, `nonce`, `start`, `deadline`, `epoch`, `slippage`, `output.limit`, `output.triggerLower`, `output.triggerUpper`, `output.recipient`.
|
|
7
7
|
3. `input.amount` is the fixed per-chunk size. `input.maxAmount` is total size and approval amount. If omitted, it defaults to `input.amount`. If it is not divisible by `input.amount`, the helper rounds it down to a whole number of chunks.
|
|
8
|
-
4. `output.limit`, `output.triggerLower`, and `output.triggerUpper` are output-token
|
|
8
|
+
4. `output.limit`, `output.triggerLower`, and `output.triggerUpper` are output-token amounts per chunk, encoded in the output token's decimals.
|
|
9
9
|
5. Future `start` delays the first fill. `epoch` is the delay between chunks, but it is not exact: each chunk can fill anywhere inside its epoch window, only once. Large `epoch` is not a delayed order by itself.
|
|
10
10
|
6. Chunked orders should use `epoch > 0`; with `epoch = 0`, only the first chunk can fill.
|
|
11
11
|
7. Defaults:
|
|
@@ -19,7 +19,7 @@ Use this file for field semantics, defaults, units, and validation. Use [04-patt
|
|
|
19
19
|
- `output.recipient = swapper`
|
|
20
20
|
8. Higher slippage is still protected by oracle pricing and offchain executors.
|
|
21
21
|
9. `output.recipient` is dangerous to change away from `swapper`.
|
|
22
|
-
10. Native input is not supported. Wrap to WNATIVE first. Native output is supported with `output.token = 0x0000000000000000000000000000000000000000`.
|
|
22
|
+
10. Native input is not supported. Wrap to WNATIVE first. Native output, including "back to native" orders, is supported directly with `output.token = 0x0000000000000000000000000000000000000000`.
|
|
23
23
|
11. Example:
|
|
24
24
|
|
|
25
25
|
```json
|
|
@@ -3,5 +3,4 @@
|
|
|
3
3
|
1. Sign `prepared.typedData` with any EIP-712-capable wallet or library. The signer must equal `swapper`. `eth_signTypedData_v4` is only one example.
|
|
4
4
|
2. Submit with `--prepared <prepared.json|->` and exactly one signature mode: `--signature <0x...|json>`, `--signature-file <sig.txt|sig.json|->`, or `--r <0x...> --s <0x...> --v <0x...>`.
|
|
5
5
|
3. The helper accepts a full 65-byte signature, a JSON string, or JSON/object `r/s/v`.
|
|
6
|
-
4.
|
|
7
|
-
5. Cancel trustlessly onchain by calling `RePermit.cancel([digest])` as the swapper for the signed RePermit digest.
|
|
6
|
+
4. Cancel trustlessly onchain by calling `RePermit.cancel([digest])` as the swapper for the signed RePermit digest.
|
|
@@ -8,5 +8,5 @@
|
|
|
8
8
|
6. Time-spaced chunked order: set `epoch > 0`. For example, `epoch = 60` means one chunk can fill once anywhere inside each 60-second epoch window.
|
|
9
9
|
7. `N chunks`: use one TWAP order instead of manually submitting `N` separate orders. Use `input.maxAmount` as the requested total amount, set `input.amount = floor(total / N)`, and accept any rounded-down remainder as dust.
|
|
10
10
|
8. If timing is omitted for a chunked or TWAP order, `epoch` defaults to `60`. Single orders default to `0`.
|
|
11
|
-
9. Native output: set `output.token = 0x0000000000000000000000000000000000000000`.
|
|
11
|
+
9. Native output or back to native exposure: set `output.token = 0x0000000000000000000000000000000000000000`.
|
|
12
12
|
10. Best execution and oracle protection apply regardless of `output.limit`.
|
package/skill/scripts/order.js
CHANGED
|
@@ -12,6 +12,9 @@ const REF_SHARE = 0;
|
|
|
12
12
|
const FRESHNESS = 30;
|
|
13
13
|
const TTL = 300n;
|
|
14
14
|
const U32_MAX = 4294967295n;
|
|
15
|
+
const DEF_WATCH_INTERVAL = 5;
|
|
16
|
+
const DEF_WATCH_TIMEOUT = 0;
|
|
17
|
+
const TERMINAL_ORDER_STATUSES = new Set(['filled', 'completed', 'cancelled', 'canceled', 'expired', 'failed', 'rejected']);
|
|
15
18
|
const NOTE_ORACLE = 'Oracle protection applies to all order types and every chunk.';
|
|
16
19
|
const NOTE_EPOCH = 'epoch is the delay between chunks, but it is not exact: one chunk can fill once anywhere inside each epoch window.';
|
|
17
20
|
const NOTE_SIGN = 'Sign typedData with any EIP-712 flow. eth_signTypedData_v4 is only an example.';
|
|
@@ -55,6 +58,10 @@ function warn(message) {
|
|
|
55
58
|
process.stderr.write(`warning: ${message}\n`);
|
|
56
59
|
}
|
|
57
60
|
|
|
61
|
+
function note(message) {
|
|
62
|
+
process.stderr.write(`info: ${message}\n`);
|
|
63
|
+
}
|
|
64
|
+
|
|
58
65
|
function firstDefined(...values) {
|
|
59
66
|
for (const value of values) {
|
|
60
67
|
if (value !== undefined && value !== null) {
|
|
@@ -179,6 +186,22 @@ function requireHex(value, name) {
|
|
|
179
186
|
return `0x${raw}`;
|
|
180
187
|
}
|
|
181
188
|
|
|
189
|
+
function formatError(error) {
|
|
190
|
+
if (!error) {
|
|
191
|
+
return 'unknown error';
|
|
192
|
+
}
|
|
193
|
+
const parts = [];
|
|
194
|
+
if (error.message) {
|
|
195
|
+
parts.push(error.message);
|
|
196
|
+
}
|
|
197
|
+
if (error.cause && error.cause.message) {
|
|
198
|
+
parts.push(error.cause.message);
|
|
199
|
+
} else if (error.cause && error.cause.code) {
|
|
200
|
+
parts.push(String(error.cause.code));
|
|
201
|
+
}
|
|
202
|
+
return parts.filter(Boolean).join(': ') || 'unknown error';
|
|
203
|
+
}
|
|
204
|
+
|
|
182
205
|
function normalizeSizedHex(value, name, size) {
|
|
183
206
|
const raw = hexBody(value, name, { allowBare: true });
|
|
184
207
|
if (raw.length !== size) {
|
|
@@ -384,6 +407,10 @@ function loadRuntimeConfig() {
|
|
|
384
407
|
return runtimeConfig;
|
|
385
408
|
}
|
|
386
409
|
|
|
410
|
+
function sleep(ms) {
|
|
411
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
412
|
+
}
|
|
413
|
+
|
|
387
414
|
function hasSupportedChain(chainId) {
|
|
388
415
|
const config = loadRuntimeConfig();
|
|
389
416
|
const chain = config.chains[String(chainId)];
|
|
@@ -411,6 +438,7 @@ function usage() {
|
|
|
411
438
|
' node skill/scripts/order.js prepare --params <params.json|-> [--out <prepared.json>]',
|
|
412
439
|
' node skill/scripts/order.js submit --prepared <prepared.json|-> [--signature <0x...|json>|--signature-file <file|->|--r <0x...> --s <0x...> --v <0x..>] [--out <response.json>]',
|
|
413
440
|
' node skill/scripts/order.js query (--swapper <0x...>|--hash <0x...>) [--out <response.json>]',
|
|
441
|
+
' node skill/scripts/order.js watch (--swapper <0x...>|--hash <0x...>) [--interval <seconds>] [--timeout <seconds>] [--out <response.json>]',
|
|
414
442
|
'',
|
|
415
443
|
'Safety',
|
|
416
444
|
' Use only the provided helper script. Do not send typed data or signatures anywhere else.',
|
|
@@ -437,8 +465,8 @@ function usage() {
|
|
|
437
465
|
' - chunked orders require epoch > 0',
|
|
438
466
|
' - epoch is the delay between chunks, but it is not exact: one chunk can fill once anywhere inside each epoch window',
|
|
439
467
|
' - native input is not supported; wrap to WNATIVE first',
|
|
440
|
-
' - native output is supported with output.token = 0x0000000000000000000000000000000000000000',
|
|
441
|
-
|
|
468
|
+
' - native output, including back-to-native flows, is supported directly with output.token = 0x0000000000000000000000000000000000000000',
|
|
469
|
+
" - output.limit and triggers are output-token amounts per chunk in the output token's decimals",
|
|
442
470
|
'',
|
|
443
471
|
'Submit',
|
|
444
472
|
' Builds or sends the relay POST body from a prepared order.',
|
|
@@ -455,6 +483,16 @@ function usage() {
|
|
|
455
483
|
' Supports only:',
|
|
456
484
|
' - --swapper <0x...>',
|
|
457
485
|
' - --hash <0x...>',
|
|
486
|
+
'',
|
|
487
|
+
'Watch',
|
|
488
|
+
' Polls the relay query endpoint until the order reaches a terminal status.',
|
|
489
|
+
' Retries transient network errors automatically.',
|
|
490
|
+
' Defaults:',
|
|
491
|
+
` - interval = ${String(DEF_WATCH_INTERVAL)} seconds`,
|
|
492
|
+
` - timeout = ${String(DEF_WATCH_TIMEOUT)} seconds (0 = no timeout)`,
|
|
493
|
+
' Supports only:',
|
|
494
|
+
' - --swapper <0x...> when exactly one order matches',
|
|
495
|
+
' - --hash <0x...> (recommended)',
|
|
458
496
|
];
|
|
459
497
|
process.stdout.write(`${lines.join('\n')}\n`);
|
|
460
498
|
}
|
|
@@ -789,7 +827,12 @@ function selectOrderPayload(prepared) {
|
|
|
789
827
|
}
|
|
790
828
|
|
|
791
829
|
async function requestJson(url, options) {
|
|
792
|
-
|
|
830
|
+
let response;
|
|
831
|
+
try {
|
|
832
|
+
response = await fetch(url, options);
|
|
833
|
+
} catch (error) {
|
|
834
|
+
die(`request failed: ${formatError(error)}`);
|
|
835
|
+
}
|
|
793
836
|
const text = await response.text();
|
|
794
837
|
return {
|
|
795
838
|
ok: response.ok,
|
|
@@ -798,6 +841,95 @@ async function requestJson(url, options) {
|
|
|
798
841
|
};
|
|
799
842
|
}
|
|
800
843
|
|
|
844
|
+
function secondsOption(value, name, fallback) {
|
|
845
|
+
const selected = trim(value) ? value : fallback;
|
|
846
|
+
const parsed = decimalString(selected, name);
|
|
847
|
+
ensureU32(parsed, name);
|
|
848
|
+
return Number(parsed);
|
|
849
|
+
}
|
|
850
|
+
|
|
851
|
+
function buildQueryUrl(rawSwapper, rawHash) {
|
|
852
|
+
let swapper = trim(rawSwapper);
|
|
853
|
+
let hash = trim(rawHash);
|
|
854
|
+
|
|
855
|
+
if (!swapper && !hash) {
|
|
856
|
+
die('query needs --swapper or --hash');
|
|
857
|
+
}
|
|
858
|
+
|
|
859
|
+
let url = QUERY_URL;
|
|
860
|
+
if (swapper) {
|
|
861
|
+
swapper = parseAddress(swapper, 'swapper');
|
|
862
|
+
url = `${url}?swapper=${encodeURIComponent(swapper)}`;
|
|
863
|
+
}
|
|
864
|
+
if (hash) {
|
|
865
|
+
if (!/^0x[0-9a-fA-F]{64}$/.test(hash)) {
|
|
866
|
+
die('hash must be 32-byte 0x hex');
|
|
867
|
+
}
|
|
868
|
+
url = url.includes('?') ? `${url}&hash=${encodeURIComponent(hash)}` : `${url}?hash=${encodeURIComponent(hash)}`;
|
|
869
|
+
}
|
|
870
|
+
|
|
871
|
+
return { swapper, hash, url };
|
|
872
|
+
}
|
|
873
|
+
|
|
874
|
+
function responseOrders(response) {
|
|
875
|
+
return isPlainObject(response) && Array.isArray(response.orders) ? response.orders : [];
|
|
876
|
+
}
|
|
877
|
+
|
|
878
|
+
function watchSnapshot(response, { hash }) {
|
|
879
|
+
const orders = responseOrders(response);
|
|
880
|
+
if (!hash && orders.length > 1) {
|
|
881
|
+
die('watch with --swapper requires exactly one matching order; use --hash to disambiguate');
|
|
882
|
+
}
|
|
883
|
+
|
|
884
|
+
const order = isPlainObject(orders[0]) ? orders[0] : null;
|
|
885
|
+
const metadata = objectOrEmpty(order && order.metadata);
|
|
886
|
+
const status = trim(firstDefined(metadata.status, order && order.status));
|
|
887
|
+
const chunkStatuses = Array.isArray(metadata.chunks)
|
|
888
|
+
? metadata.chunks.map((chunk) => trim(chunk && chunk.status)).filter(Boolean)
|
|
889
|
+
: [];
|
|
890
|
+
|
|
891
|
+
return {
|
|
892
|
+
count: orders.length,
|
|
893
|
+
status,
|
|
894
|
+
chunkStatuses,
|
|
895
|
+
};
|
|
896
|
+
}
|
|
897
|
+
|
|
898
|
+
function watchOutput(result, url, watchMeta) {
|
|
899
|
+
return {
|
|
900
|
+
ok: result.ok,
|
|
901
|
+
status: result.status,
|
|
902
|
+
url,
|
|
903
|
+
response: result.response,
|
|
904
|
+
watch: watchMeta,
|
|
905
|
+
};
|
|
906
|
+
}
|
|
907
|
+
|
|
908
|
+
function buildWatchMeta({
|
|
909
|
+
polls,
|
|
910
|
+
queryErrors,
|
|
911
|
+
intervalSeconds,
|
|
912
|
+
timeoutSeconds,
|
|
913
|
+
startedAt,
|
|
914
|
+
finalStatus,
|
|
915
|
+
chunkStatuses,
|
|
916
|
+
timedOut,
|
|
917
|
+
lastError,
|
|
918
|
+
}) {
|
|
919
|
+
return {
|
|
920
|
+
command: 'watch',
|
|
921
|
+
polls,
|
|
922
|
+
queryErrors,
|
|
923
|
+
intervalSeconds,
|
|
924
|
+
timeoutSeconds,
|
|
925
|
+
elapsedSeconds: Math.floor((Date.now() - startedAt) / 1000),
|
|
926
|
+
finalStatus,
|
|
927
|
+
chunkStatuses,
|
|
928
|
+
timedOut,
|
|
929
|
+
lastError,
|
|
930
|
+
};
|
|
931
|
+
}
|
|
932
|
+
|
|
801
933
|
async function submit(args) {
|
|
802
934
|
loadRuntimeConfig();
|
|
803
935
|
|
|
@@ -869,27 +1001,12 @@ async function submit(args) {
|
|
|
869
1001
|
async function query(args) {
|
|
870
1002
|
loadRuntimeConfig();
|
|
871
1003
|
|
|
872
|
-
|
|
1004
|
+
const { swapper: rawSwapper, hash: rawHash, outFile } = parseOptions(
|
|
873
1005
|
args,
|
|
874
1006
|
{ '--swapper': 'swapper', '--hash': 'hash', '--out': 'outFile' },
|
|
875
1007
|
'query',
|
|
876
1008
|
);
|
|
877
|
-
|
|
878
|
-
if (!swapper && !hash) {
|
|
879
|
-
die('query needs --swapper or --hash');
|
|
880
|
-
}
|
|
881
|
-
|
|
882
|
-
let url = QUERY_URL;
|
|
883
|
-
if (swapper) {
|
|
884
|
-
swapper = parseAddress(swapper, 'swapper');
|
|
885
|
-
url = `${url}?swapper=${encodeURIComponent(swapper)}`;
|
|
886
|
-
}
|
|
887
|
-
if (hash) {
|
|
888
|
-
if (!/^0x[0-9a-fA-F]{64}$/.test(hash)) {
|
|
889
|
-
die('hash must be 32-byte 0x hex');
|
|
890
|
-
}
|
|
891
|
-
url = url.includes('?') ? `${url}&hash=${encodeURIComponent(hash)}` : `${url}?hash=${encodeURIComponent(hash)}`;
|
|
892
|
-
}
|
|
1009
|
+
const { url } = buildQueryUrl(rawSwapper, rawHash);
|
|
893
1010
|
|
|
894
1011
|
const result = await requestJson(url, { method: 'GET' });
|
|
895
1012
|
writeOutput(
|
|
@@ -905,6 +1022,111 @@ async function query(args) {
|
|
|
905
1022
|
return result.ok ? 0 : 1;
|
|
906
1023
|
}
|
|
907
1024
|
|
|
1025
|
+
async function watchOrder(args) {
|
|
1026
|
+
loadRuntimeConfig();
|
|
1027
|
+
const watchCommand = 'watch';
|
|
1028
|
+
|
|
1029
|
+
const { swapper: rawSwapper, hash: rawHash, interval, timeout, outFile } = parseOptions(
|
|
1030
|
+
args,
|
|
1031
|
+
{
|
|
1032
|
+
'--swapper': 'swapper',
|
|
1033
|
+
'--hash': 'hash',
|
|
1034
|
+
'--interval': 'interval',
|
|
1035
|
+
'--timeout': 'timeout',
|
|
1036
|
+
'--out': 'outFile',
|
|
1037
|
+
},
|
|
1038
|
+
watchCommand,
|
|
1039
|
+
);
|
|
1040
|
+
|
|
1041
|
+
const intervalSeconds = secondsOption(interval, 'interval', String(DEF_WATCH_INTERVAL));
|
|
1042
|
+
const timeoutSeconds = secondsOption(timeout, 'timeout', String(DEF_WATCH_TIMEOUT));
|
|
1043
|
+
const { hash, url } = buildQueryUrl(rawSwapper, rawHash);
|
|
1044
|
+
const startedAt = Date.now();
|
|
1045
|
+
let polls = 0;
|
|
1046
|
+
let queryErrors = 0;
|
|
1047
|
+
let lastResult = {
|
|
1048
|
+
ok: false,
|
|
1049
|
+
status: 0,
|
|
1050
|
+
response: null,
|
|
1051
|
+
};
|
|
1052
|
+
let lastError = '';
|
|
1053
|
+
|
|
1054
|
+
while (true) {
|
|
1055
|
+
polls += 1;
|
|
1056
|
+
try {
|
|
1057
|
+
lastResult = await requestJson(url, { method: 'GET' });
|
|
1058
|
+
lastError = '';
|
|
1059
|
+
} catch (error) {
|
|
1060
|
+
queryErrors += 1;
|
|
1061
|
+
lastError = formatError(error);
|
|
1062
|
+
note(`${watchCommand} retry ${String(queryErrors)} after ${lastError}`);
|
|
1063
|
+
if (timeoutSeconds !== 0 && Date.now() - startedAt >= timeoutSeconds * 1000) {
|
|
1064
|
+
const waitMeta = buildWatchMeta({
|
|
1065
|
+
polls,
|
|
1066
|
+
queryErrors,
|
|
1067
|
+
intervalSeconds,
|
|
1068
|
+
timeoutSeconds,
|
|
1069
|
+
startedAt,
|
|
1070
|
+
finalStatus: '',
|
|
1071
|
+
chunkStatuses: [],
|
|
1072
|
+
timedOut: true,
|
|
1073
|
+
lastError,
|
|
1074
|
+
});
|
|
1075
|
+
writeOutput(watchOutput(lastResult, url, waitMeta), outFile);
|
|
1076
|
+
return 1;
|
|
1077
|
+
}
|
|
1078
|
+
await sleep(intervalSeconds * 1000);
|
|
1079
|
+
continue;
|
|
1080
|
+
}
|
|
1081
|
+
|
|
1082
|
+
if (!lastResult.ok) {
|
|
1083
|
+
queryErrors += 1;
|
|
1084
|
+
lastError = `query returned HTTP ${String(lastResult.status)}`;
|
|
1085
|
+
note(`${watchCommand} retry ${String(queryErrors)} after ${lastError}`);
|
|
1086
|
+
} else {
|
|
1087
|
+
const snapshot = watchSnapshot(lastResult.response, { hash });
|
|
1088
|
+
const finalStatus = snapshot.status || '';
|
|
1089
|
+
const chunkStatuses = snapshot.chunkStatuses;
|
|
1090
|
+
note(`watch status=${finalStatus || 'pending'} chunks=${chunkStatuses.join(',') || '-'}`);
|
|
1091
|
+
|
|
1092
|
+
if (TERMINAL_ORDER_STATUSES.has(lower(finalStatus))) {
|
|
1093
|
+
const waitMeta = buildWatchMeta({
|
|
1094
|
+
polls,
|
|
1095
|
+
queryErrors,
|
|
1096
|
+
intervalSeconds,
|
|
1097
|
+
timeoutSeconds,
|
|
1098
|
+
startedAt,
|
|
1099
|
+
finalStatus,
|
|
1100
|
+
chunkStatuses,
|
|
1101
|
+
timedOut: false,
|
|
1102
|
+
lastError,
|
|
1103
|
+
});
|
|
1104
|
+
writeOutput(watchOutput(lastResult, url, waitMeta), outFile);
|
|
1105
|
+
return 0;
|
|
1106
|
+
}
|
|
1107
|
+
}
|
|
1108
|
+
|
|
1109
|
+
if (timeoutSeconds !== 0 && Date.now() - startedAt >= timeoutSeconds * 1000) {
|
|
1110
|
+
const snapshot = lastResult.ok ? watchSnapshot(lastResult.response, { hash }) : { status: '', chunkStatuses: [] };
|
|
1111
|
+
const waitMeta = buildWatchMeta({
|
|
1112
|
+
polls,
|
|
1113
|
+
queryErrors,
|
|
1114
|
+
intervalSeconds,
|
|
1115
|
+
timeoutSeconds,
|
|
1116
|
+
startedAt,
|
|
1117
|
+
finalStatus: snapshot.status,
|
|
1118
|
+
chunkStatuses: snapshot.chunkStatuses,
|
|
1119
|
+
timedOut: true,
|
|
1120
|
+
lastError,
|
|
1121
|
+
});
|
|
1122
|
+
writeOutput(watchOutput(lastResult, url, waitMeta), outFile);
|
|
1123
|
+
return 1;
|
|
1124
|
+
}
|
|
1125
|
+
|
|
1126
|
+
await sleep(intervalSeconds * 1000);
|
|
1127
|
+
}
|
|
1128
|
+
}
|
|
1129
|
+
|
|
908
1130
|
async function run() {
|
|
909
1131
|
const args = process.argv.slice(2);
|
|
910
1132
|
const command = args[0] || '';
|
|
@@ -921,6 +1143,8 @@ async function run() {
|
|
|
921
1143
|
return submit(args.slice(1));
|
|
922
1144
|
case 'query':
|
|
923
1145
|
return query(args.slice(1));
|
|
1146
|
+
case 'watch':
|
|
1147
|
+
return watchOrder(args.slice(1));
|
|
924
1148
|
default:
|
|
925
1149
|
usage();
|
|
926
1150
|
return 1;
|