@wagmipro/sdk 0.0.0-stage → 0.6.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/LICENSE ADDED
@@ -0,0 +1,16 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 WAGMI.PRO
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
6
+ documentation files (the "Software"), to deal in the Software without restriction, including without limitation the
7
+ rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit
8
+ persons to whom the Software is furnished to do so, subject to the following conditions:
9
+
10
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the
11
+ Software.
12
+
13
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
14
+ WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
15
+ COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
16
+ OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,52 @@
1
- # Temporary Holding Version
1
+ # WAGMI.PRO API client for JavaScript and TypeScript
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ The official client of the [WAGMI.PRO API](https://docs.wagmi.pro/api): market data, your account, every trading action
4
+ built and signed for you, the "sent" and "confirmed" stages, and the websocket. No dependencies. Node 20 or later, or a
5
+ current browser (the websocket needs Node 22, a browser, or the `ws` package).
6
+
7
+ ```sh
8
+ npm install @wagmipro/sdk
9
+ ```
10
+
11
+ ```js
12
+ import { WagmiClient } from '@wagmipro/sdk'
13
+
14
+ const fx = new WagmiClient({
15
+ apiKey: process.env.WAGMIPRO_API_KEY, // wp_...
16
+ apiSecret: process.env.WAGMIPRO_API_SECRET,
17
+ signingKey: process.env.WAGMIPRO_SIGNING_KEY, // shown once with a key that has Trade
18
+ grantId: process.env.WAGMIPRO_GRANT_ID,
19
+ })
20
+
21
+ const book = await fx.orderbook('BTC', 5)
22
+ const r = await fx.placeOrder('BTC', { side: 'buy', orderType: 'limit', size: '0.001', price: '50000' })
23
+ // r.status: "confirmed" (r.orders[0].state: resting, filled...), "sent" or "refused" (r.error)
24
+ ```
25
+
26
+ ## Keep one client
27
+
28
+ Create one client when your program starts and reuse it for every request. It keeps its HTTPS connection open, so every
29
+ order goes out on a connection that is already set up. A new client (or a new process for every order) opens a new
30
+ connection first, which adds about 1 second to its first order (https://docs.wagmi.pro/api/conventions#keep-the-connection-open).
31
+
32
+ The signing format, with test vectors (`testvectors.json` in this package): https://docs.wagmi.pro/api/signing-format.
33
+ `npm test` checks this library against every one of them.
34
+
35
+ ## For builders
36
+
37
+ `WagmiPartner` is your backend's client with your builder key (`fxp_...`): users, deposits inside your app, each
38
+ user's setup signed by their own wallet (`onboardUser` with `viemWallet` or `ethersWallet`), your fee, earnings, reports
39
+ and your one stream for every user. `createSandboxKey()` gives you a sandbox to build against. A walkthrough:
40
+ https://docs.wagmi.pro/api/build-a-terminal, every route: https://docs.wagmi.pro/api/partners.
41
+
42
+ ### Withdrawals, by the user's own wallet
43
+
44
+ A user withdraws with their own wallet; no key you or we hold is involved. `withdraw` asks for the transaction, the
45
+ user's wallet sends it on Ethereum (it pays the gas in ETH, about 132,000 gas), and the money goes to that same wallet
46
+ on Ethereum, the only place it can go:
47
+
48
+ const w = await partner.withdraw('user-1842', { amount: '25', wallet: viemWallet(usersWalletClient) })
49
+ // w.status: 'sent', then 'mined' and 'arrived' on your stream ({type: 'withdrawal', data})
50
+
51
+ Or step by step: `withdrawalDraft`, your app has the wallet send `draft.transaction`, then `recordWithdrawal` with its
52
+ hash. `withdrawals(externalRef)` lists them. Details: https://docs.wagmi.pro/api/partners#withdrawals.
@@ -0,0 +1,156 @@
1
+ /**
2
+ * The action text of every WAGMI.PRO API trading request (signing format v1). The API builds the same text from your
3
+ * `request` and refuses any difference, so this must match it byte for byte: docs.wagmi.pro/api/signing-format.
4
+ */
5
+ export interface MarketInfo {
6
+ symbol: string;
7
+ /** The WAGMI.PRO market id (GET /v1/markets marketId). */
8
+ marketId: number;
9
+ type: 'perp' | 'spot';
10
+ sizeDecimals: number;
11
+ priceDecimals: number;
12
+ minSize?: string | null;
13
+ minNotional?: string | null;
14
+ }
15
+ export interface AssetInfo {
16
+ symbol: string;
17
+ /** The asset id (GET /v1/assets assetId, the same as in your balances). */
18
+ assetId: number;
19
+ decimals: number;
20
+ }
21
+ export type Side = 'buy' | 'sell';
22
+ export interface ExitLeg {
23
+ triggerPrice: string;
24
+ price?: string;
25
+ clientOrderIndex?: number;
26
+ }
27
+ export type TradeRequest = {
28
+ type: 'order';
29
+ side: Side;
30
+ orderType: 'market' | 'limit';
31
+ size: string;
32
+ price: string;
33
+ clientOrderIndex: number;
34
+ expiry?: number;
35
+ takeProfit?: ExitLeg;
36
+ stopLoss?: ExitLeg;
37
+ } | {
38
+ type: 'close';
39
+ side: Side;
40
+ size: string;
41
+ price: string;
42
+ clientOrderIndex: number;
43
+ } | {
44
+ type: 'trigger';
45
+ side: Side;
46
+ size: string;
47
+ triggerPrice: string;
48
+ direction: 'rises' | 'falls';
49
+ reduceOnly: boolean;
50
+ clientOrderIndex: number;
51
+ limitPrice?: string;
52
+ price?: string;
53
+ expiryDays?: 1 | 7 | 28;
54
+ expiry?: number;
55
+ } | {
56
+ type: 'scale';
57
+ side: Side;
58
+ postOnly: boolean;
59
+ reduceOnly: boolean;
60
+ orders: Array<{
61
+ price: string;
62
+ size: string;
63
+ clientOrderIndex: number;
64
+ }>;
65
+ expiry?: number;
66
+ } | {
67
+ type: 'modify';
68
+ orderId?: string;
69
+ orderIndex?: string;
70
+ size: string;
71
+ price: string;
72
+ triggerPrice?: string;
73
+ } | {
74
+ type: 'cancel';
75
+ orderId?: string;
76
+ orderIndex?: string;
77
+ } | {
78
+ type: 'leverage';
79
+ leverage: number;
80
+ marginMode: 'cross' | 'isolated';
81
+ } | {
82
+ type: 'asset_margin';
83
+ enabled: boolean;
84
+ } | {
85
+ type: 'own_transfer';
86
+ from: 'perps' | 'spot';
87
+ to: 'perps' | 'spot';
88
+ amount: string;
89
+ } | {
90
+ type: 'withdraw';
91
+ route: 'perps' | 'spot';
92
+ amount: string;
93
+ } | {
94
+ type: 'cancel_all';
95
+ } | {
96
+ type: 'margin';
97
+ direction: 'add' | 'remove';
98
+ amount: string;
99
+ } | RunRequest;
100
+ /** A request refused before it is sent; `code` is the API's own error code for it. */
101
+ export declare class WagmiError extends Error {
102
+ readonly code: string;
103
+ readonly status?: number | undefined;
104
+ readonly body?: unknown | undefined;
105
+ constructor(code: string, message: string, status?: number | undefined, body?: unknown | undefined);
106
+ }
107
+ export declare const ORDER_LIFE_MS: number;
108
+ export declare const MAX_CLIENT_ORDER_INDEX: number;
109
+ export declare const MAX_SCALE_ORDERS = 50;
110
+ /** Which route each request type is sent to. */
111
+ export declare const ROUTE_OF: Record<TradeRequest['type'], string>;
112
+ /** A decimal string as whole units of 10^-decimals, exactly (trailing zeros allowed; more decimals refused). */
113
+ export declare function toUnits(value: unknown, decimals: number, param: string): bigint;
114
+ export interface BuildContext {
115
+ market?: MarketInfo;
116
+ asset?: AssetInfo;
117
+ /** auth.ts of the request (ms): every default expiry counts from it. */
118
+ signedAt: number;
119
+ /** Your clock (ms), only to refuse an expiry already past; default signedAt. */
120
+ now?: number;
121
+ }
122
+ export type RunType = 'twap' | 'chase_twap' | 'swarm';
123
+ export type RunRequest = {
124
+ type: 'twap' | 'chase_twap';
125
+ side: Side;
126
+ size: string;
127
+ durationSeconds: number;
128
+ intervalSeconds: number;
129
+ worstPrice: string;
130
+ runId: string;
131
+ randomise?: boolean;
132
+ reduceOnly?: boolean;
133
+ } | {
134
+ type: 'swarm';
135
+ side: Side;
136
+ size: string;
137
+ clips: number;
138
+ intervalSeconds: number;
139
+ worstPrice: string;
140
+ runId: string;
141
+ irregular?: boolean;
142
+ reduceOnly?: boolean;
143
+ } | {
144
+ type: 'cancel_run';
145
+ runId: string;
146
+ };
147
+ export declare const RUN_LIMITS: {
148
+ readonly maxSlices: 10000;
149
+ readonly maxSpanMs: number;
150
+ readonly minIntervalMs: 1000;
151
+ readonly minSwarmIntervalMs: 600;
152
+ };
153
+ /** A new run id: 32 lowercase hex characters, new for every run (the API shows it as "run_" + it). */
154
+ export declare function newRunId(): string;
155
+ /** The exact action text to sign for `request` (signing format v1). Throws WagmiError with the API's code. */
156
+ export declare function buildAction(request: TradeRequest | Record<string, unknown>, ctx: BuildContext): string;
package/dist/action.js ADDED
@@ -0,0 +1,379 @@
1
+ /**
2
+ * The action text of every WAGMI.PRO API trading request (signing format v1). The API builds the same text from your
3
+ * `request` and refuses any difference, so this must match it byte for byte: docs.wagmi.pro/api/signing-format.
4
+ */
5
+ /** A request refused before it is sent; `code` is the API's own error code for it. */
6
+ export class WagmiError extends Error {
7
+ code;
8
+ status;
9
+ body;
10
+ constructor(code, message, status, body) {
11
+ super(message);
12
+ this.code = code;
13
+ this.status = status;
14
+ this.body = body;
15
+ this.name = 'WagmiError';
16
+ }
17
+ }
18
+ const refuse = (code, message) => { throw new WagmiError(code, message); };
19
+ export const ORDER_LIFE_MS = 28 * 86_400_000;
20
+ export const MAX_CLIENT_ORDER_INDEX = 2 ** 48 - 1;
21
+ export const MAX_SCALE_ORDERS = 50;
22
+ const ORDER_TYPE = { limit: 0, market: 1, stopLoss: 2, stopLossLimit: 3, takeProfit: 4, takeProfitLimit: 5 };
23
+ const TIF = { immediateOrCancel: 0, goodTillTime: 1, postOnly: 2 };
24
+ const GROUPING = { oto: 1, otoco: 3 };
25
+ const ROUTE = { perps: 0, spot: 1 };
26
+ const U32_MAX = 4294967295n;
27
+ const I64_MAX = 9223372036854775807n;
28
+ const U64_MAX = 18446744073709551615n;
29
+ const KEYS = {
30
+ order: { need: ['side', 'orderType', 'size', 'price', 'clientOrderIndex'], may: ['takeProfit', 'stopLoss', 'expiry'] },
31
+ close: { need: ['side', 'size', 'price', 'clientOrderIndex'], may: [] },
32
+ trigger: { need: ['side', 'size', 'triggerPrice', 'direction', 'reduceOnly', 'clientOrderIndex'], may: ['limitPrice', 'price', 'expiryDays', 'expiry'] },
33
+ scale: { need: ['side', 'postOnly', 'reduceOnly', 'orders'], may: ['expiry'] },
34
+ modify: { need: ['size', 'price'], may: ['orderId', 'orderIndex', 'triggerPrice'] },
35
+ cancel: { need: [], may: ['orderId', 'orderIndex'] },
36
+ leverage: { need: ['leverage', 'marginMode'], may: [] },
37
+ asset_margin: { need: ['enabled'], may: [] },
38
+ own_transfer: { need: ['from', 'to', 'amount'], may: [] },
39
+ withdraw: { need: ['route', 'amount'], may: [] },
40
+ cancel_all: { need: [], may: [] },
41
+ margin: { need: ['direction', 'amount'], may: [] },
42
+ };
43
+ const NOT_OFFERED = {
44
+ twap: 'background orders run as runs, not as a single order type',
45
+ oco: 'a take profit and stop loss pair is set on an order when it is placed, or one at a time on a position',
46
+ reduceOnly: 'reduce-only is offered on close, trigger and scale requests, not on a plain order',
47
+ postOnly: 'post-only is offered on scale requests, not on a plain order',
48
+ timeInForce: 'a market order is immediate-or-cancel and a limit order good till time; no other choice is offered',
49
+ };
50
+ /** Which route each request type is sent to. */
51
+ export const ROUTE_OF = {
52
+ order: '/v1/orders', close: '/v1/orders', trigger: '/v1/orders', scale: '/v1/orders',
53
+ twap: '/v1/orders', chase_twap: '/v1/orders', swarm: '/v1/orders', cancel_run: '/v1/orders/cancel',
54
+ modify: '/v1/orders/modify', cancel: '/v1/orders/cancel', leverage: '/v1/leverage', cancel_all: '/v1/orders/cancel', margin: '/v1/leverage',
55
+ asset_margin: '/v1/asset-margin', own_transfer: '/v1/transfers', withdraw: '/v1/withdrawals',
56
+ };
57
+ /** A decimal string as whole units of 10^-decimals, exactly (trailing zeros allowed; more decimals refused). */
58
+ export function toUnits(value, decimals, param) {
59
+ if (typeof value !== 'string' || !/^(0|[1-9]\d{0,29})(\.\d{1,30})?$/.test(value))
60
+ return refuse('invalid_param', `${param} is a decimal string, e.g. "0.25"`);
61
+ const [whole, frac = ''] = value.split('.');
62
+ const trimmed = frac.replace(/0+$/, '');
63
+ if (trimmed.length > decimals)
64
+ return refuse('too_many_decimals', `${param} takes at most ${decimals} decimals here`);
65
+ return BigInt(whole + trimmed.padEnd(decimals, '0'));
66
+ }
67
+ const positive = (v, max, param) => (v > 0n && v <= max ? v : refuse('invalid_param', `${param} is out of range`));
68
+ function coi(v, param) {
69
+ if (typeof v !== 'number' || !Number.isSafeInteger(v) || v < 1 || v > MAX_CLIENT_ORDER_INDEX)
70
+ return refuse('invalid_param', `${param} is a whole number from 1 to ${MAX_CLIENT_ORDER_INDEX}`);
71
+ return v;
72
+ }
73
+ function orderRef(r) {
74
+ if ((r.orderId === undefined) === (r.orderIndex === undefined))
75
+ return refuse('invalid_param', 'name the order by orderId (the id the API shows) or by orderIndex (its client order index)');
76
+ if (r.orderId !== undefined) {
77
+ if (typeof r.orderId !== 'string' || !/^(0|[1-9]\d{0,19})$/.test(r.orderId) || BigInt(r.orderId) >= 1n << 64n)
78
+ return refuse('invalid_param', 'orderId is the order id the API shows, a string of digits');
79
+ return { orderId: r.orderId };
80
+ }
81
+ const v = r.orderIndex;
82
+ if (typeof v !== 'string' || !/^[1-9]\d{0,18}$/.test(v) || BigInt(v) > I64_MAX)
83
+ return refuse('invalid_param', 'orderIndex is the order id, a string of digits');
84
+ return { orderIndex: BigInt(v) };
85
+ }
86
+ const sideOf = (v) => (v === 'buy' || v === 'sell' ? v : refuse('invalid_param', 'side is "buy" or "sell"'));
87
+ const needPerp = (m, what) => { if (m.type !== 'perp')
88
+ refuse('not_offered', `${what} is offered on perpetual markets only`); };
89
+ const sizeOf = (m, v, p = 'size') => positive(toUnits(v, m.sizeDecimals, p), I64_MAX, p);
90
+ const priceOf = (m, v, p = 'price') => positive(toUnits(v, m.priceDecimals, p), U32_MAX, p);
91
+ /** 2% past the trigger, rounded half up: lower for a sell, higher for a buy. */
92
+ function boundFrom(trigger, isAsk) {
93
+ const v = (trigger * (isAsk ? 98n : 102n) + 50n) / 100n;
94
+ return v > 0n && v <= U32_MAX ? v : refuse('invalid_param', 'triggerPrice is out of range');
95
+ }
96
+ function triggerType(side, direction, limit) {
97
+ const stop = (side === 'buy') === (direction === 'rises');
98
+ if (stop)
99
+ return limit ? ORDER_TYPE.stopLossLimit : ORDER_TYPE.stopLoss;
100
+ return limit ? ORDER_TYPE.takeProfitLimit : ORDER_TYPE.takeProfit;
101
+ }
102
+ function expiryOf(r, ctx, defaultMs) {
103
+ if (!Number.isSafeInteger(ctx.signedAt) || ctx.signedAt <= 0)
104
+ return refuse('invalid_param', 'signedAt is auth.ts, a Unix time in milliseconds');
105
+ if (r.expiry === undefined)
106
+ return ctx.signedAt + defaultMs;
107
+ const e = r.expiry;
108
+ if (typeof e !== 'number' || !Number.isSafeInteger(e) || e <= 0)
109
+ return refuse('invalid_expiry', 'expiry is a Unix time in milliseconds (a whole number)');
110
+ if (e <= (ctx.now ?? ctx.signedAt))
111
+ return refuse('invalid_expiry', 'expiry is in the past: set a time later than now');
112
+ if (e > ctx.signedAt + ORDER_LIFE_MS)
113
+ return refuse('invalid_expiry', 'expiry is more than 28 days after auth.ts: set a time within 28 days of the request');
114
+ return e;
115
+ }
116
+ function exitLeg(m, leg, kind, closeIsAsk, expiry) {
117
+ if (!leg || typeof leg !== 'object' || Array.isArray(leg))
118
+ return refuse('invalid_param', `${kind} is an object`);
119
+ const l = leg;
120
+ for (const k of Object.keys(l))
121
+ if (!['triggerPrice', 'price', 'clientOrderIndex'].includes(k))
122
+ refuse('invalid_param', `${kind} takes no ${k.slice(0, 40)}`);
123
+ const trigger = priceOf(m, l.triggerPrice, `${kind}.triggerPrice`);
124
+ return {
125
+ marketId: m.marketId, clientOrderIndex: l.clientOrderIndex === undefined ? 0 : coi(l.clientOrderIndex, `${kind}.clientOrderIndex`), baseAmount: 0n,
126
+ price: l.price === undefined ? boundFrom(trigger, closeIsAsk) : priceOf(m, l.price, `${kind}.price`), isAsk: closeIsAsk,
127
+ orderType: kind === 'takeProfit' ? ORDER_TYPE.takeProfit : ORDER_TYPE.stopLoss, timeInForce: TIF.immediateOrCancel, reduceOnly: true, triggerPrice: trigger, orderExpiry: expiry,
128
+ };
129
+ }
130
+ function text(v) {
131
+ if (typeof v === 'bigint')
132
+ return v.toString();
133
+ if (Array.isArray(v))
134
+ return `[${v.map(text).join(',')}]`;
135
+ if (typeof v === 'object')
136
+ return `{${Object.entries(v).map(([k, x]) => `${JSON.stringify(k)}:${text(x)}`).join(',')}}`;
137
+ return JSON.stringify(v);
138
+ }
139
+ const fields = (o) => ({ marketId: o.marketId, clientOrderIndex: o.clientOrderIndex, baseAmount: o.baseAmount, price: o.price, isAsk: o.isAsk, orderType: o.orderType, timeInForce: o.timeInForce, reduceOnly: o.reduceOnly, triggerPrice: o.triggerPrice, orderExpiry: o.orderExpiry });
140
+ const RUN_KEYS = {
141
+ twap: { need: ['side', 'size', 'durationSeconds', 'intervalSeconds', 'worstPrice', 'runId'], may: ['randomise', 'reduceOnly'] },
142
+ chase_twap: { need: ['side', 'size', 'durationSeconds', 'intervalSeconds', 'worstPrice', 'runId'], may: ['randomise', 'reduceOnly'] },
143
+ swarm: { need: ['side', 'size', 'clips', 'intervalSeconds', 'worstPrice', 'runId'], may: ['irregular', 'reduceOnly'] },
144
+ };
145
+ const RUN_KINDS = Object.keys(RUN_KEYS);
146
+ export const RUN_LIMITS = { maxSlices: 10_000, maxSpanMs: 7 * 86_400_000, minIntervalMs: 1_000, minSwarmIntervalMs: 600 };
147
+ const RUN_ID_RE = /^[0-9a-f]{32}$/;
148
+ /** A new run id: 32 lowercase hex characters, new for every run (the API shows it as "run_" + it). */
149
+ export function newRunId() {
150
+ const b = new Uint8Array(16);
151
+ (globalThis.crypto ?? (() => { throw new Error('no WebCrypto'); })()).getRandomValues(b);
152
+ return Array.from(b, (x) => x.toString(16).padStart(2, '0')).join('');
153
+ }
154
+ function buildRun(r, ctx) {
155
+ const type = r.type;
156
+ if (type === 'cancel_run') {
157
+ const id = typeof r.runId === 'string' && /^run_[0-9a-f]{32}$/.test(r.runId) ? r.runId.slice(4) : null;
158
+ if (!id || Object.keys(r).some((k) => k !== 'type' && k !== 'runId'))
159
+ refuse('invalid_param', 'cancel_run takes runId, the run\'s id ("run_..."), and nothing else');
160
+ return `{"type":"cancel_run","runId":${JSON.stringify(id)}}`;
161
+ }
162
+ const kind = type;
163
+ if (!RUN_KINDS.includes(kind))
164
+ refuse('invalid_param', 'type is twap, chase_twap or swarm');
165
+ const k = RUN_KEYS[kind];
166
+ for (const key of Object.keys(r))
167
+ if (key !== 'type' && !k.need.includes(key) && !k.may.includes(key))
168
+ refuse('invalid_param', `${kind} takes no ${key.slice(0, 40)}`);
169
+ for (const key of k.need)
170
+ if (r[key] === undefined || r[key] === null)
171
+ refuse('invalid_param', `${kind} needs ${key}`);
172
+ const m = ctx.market ?? refuse('unknown_symbol', 'no such market');
173
+ if (m.type !== 'perp')
174
+ refuse('not_offered', 'runs are offered on perpetual markets only');
175
+ if (r.side !== 'buy' && r.side !== 'sell')
176
+ refuse('invalid_param', 'side is "buy" or "sell"');
177
+ if (typeof r.runId !== 'string' || !RUN_ID_RE.test(r.runId))
178
+ refuse('invalid_param', 'runId is 32 lowercase hex characters, new for every run');
179
+ const whole = (v, min, max) => (typeof v === 'number' && Number.isSafeInteger(v) && v >= min && v <= max ? v : null);
180
+ const flag = (v) => (v === undefined ? false : typeof v === 'boolean' ? v : null);
181
+ const iv = r.intervalSeconds;
182
+ const intervalMs = typeof iv === 'number' && Number.isFinite(iv) ? Math.round(iv * 1000) : NaN;
183
+ const minMs = kind === 'swarm' ? RUN_LIMITS.minSwarmIntervalMs : RUN_LIMITS.minIntervalMs;
184
+ if (!Number.isSafeInteger(intervalMs) || Math.abs(intervalMs - iv * 1000) > 1e-6 || intervalMs < minMs || intervalMs > 86_400_000) {
185
+ refuse('invalid_param', `intervalSeconds is a number of seconds (at most 3 decimals) from ${minMs / 1000} to 86400`);
186
+ }
187
+ let slices;
188
+ if (kind === 'swarm') {
189
+ const clips = whole(r.clips, 1, RUN_LIMITS.maxSlices);
190
+ if (clips === null)
191
+ return refuse('invalid_param', `clips is a whole number from 1 to ${RUN_LIMITS.maxSlices}`);
192
+ slices = clips;
193
+ }
194
+ else {
195
+ const duration = whole(r.durationSeconds, 1, RUN_LIMITS.maxSpanMs / 1000);
196
+ if (duration === null || duration * 1000 < intervalMs)
197
+ return refuse('invalid_param', 'durationSeconds is a whole number, at least intervalSeconds and at most 7 days');
198
+ slices = Math.max(1, Math.floor((duration * 1000) / intervalMs));
199
+ if (slices > RUN_LIMITS.maxSlices)
200
+ refuse('invalid_param', `at most ${RUN_LIMITS.maxSlices} slices: a longer interval or a shorter duration`);
201
+ }
202
+ if (slices * intervalMs > RUN_LIMITS.maxSpanMs)
203
+ refuse('invalid_param', 'a run lasts at most 7 days');
204
+ const randomise = flag(kind === 'swarm' ? r.irregular : r.randomise);
205
+ const reduceOnly = flag(r.reduceOnly);
206
+ if (randomise === null)
207
+ refuse('invalid_param', `${kind === 'swarm' ? 'irregular' : 'randomise'} is true or false`);
208
+ if (reduceOnly === null)
209
+ refuse('invalid_param', 'reduceOnly is true or false');
210
+ const totalBase = toUnits(r.size, m.sizeDecimals, 'size');
211
+ const worstPrice = toUnits(r.worstPrice, m.priceDecimals, 'worstPrice');
212
+ if (totalBase <= 0n || totalBase > 9223372036854775807n)
213
+ refuse('invalid_param', 'size is out of range');
214
+ if (worstPrice <= 0n || worstPrice > 4294967295n)
215
+ refuse('invalid_param', 'worstPrice is out of range');
216
+ if (!Number.isSafeInteger(ctx.signedAt) || ctx.signedAt <= 0)
217
+ refuse('invalid_param', 'signedAt is auth.ts, a Unix time in milliseconds');
218
+ const clientOrderBase = 200_000_000_000_000 + (parseInt(r.runId.slice(0, 8), 16) % 800_000_000) * 100_000;
219
+ const expiresAt = ctx.signedAt + Math.floor((slices * intervalMs * 12) / 10) + 600_000;
220
+ return `{"type":"start_run","runId":${JSON.stringify(r.runId)},"kind":${JSON.stringify(kind)},"marketId":${m.marketId},"isAsk":${r.side === 'sell'},"totalBase":${totalBase},`
221
+ + `"reduceOnly":${reduceOnly},"slices":${slices},"intervalMs":${intervalMs},"randomise":${randomise},"worstPrice":${worstPrice},`
222
+ + `"clientOrderBase":${clientOrderBase},"sizeDecimals":${m.sizeDecimals},"expiresAt":${expiresAt}}`;
223
+ }
224
+ /** The exact action text to sign for `request` (signing format v1). Throws WagmiError with the API's code. */
225
+ export function buildAction(request, ctx) {
226
+ const r = request;
227
+ if (!r || typeof r !== 'object' || Array.isArray(r))
228
+ return refuse('invalid_param', 'the request is a JSON object');
229
+ const type = r.type;
230
+ if (type === 'cancel_all_orders')
231
+ return refuse('invalid_param', 'the request type is cancel_all');
232
+ if (type === 'update_margin')
233
+ return refuse('invalid_param', 'the request type is margin');
234
+ if (type === 'twap' || type === 'chase_twap' || type === 'swarm' || type === 'cancel_run')
235
+ return buildRun(r, ctx);
236
+ if (type === 'oco')
237
+ return refuse('not_offered', NOT_OFFERED.oco);
238
+ if (typeof type !== 'string' || !(type in KEYS))
239
+ return refuse('invalid_param', `unknown request type; one of ${Object.keys(KEYS).join(', ')}`);
240
+ const k = KEYS[type];
241
+ for (const key of Object.keys(r)) {
242
+ if (key === 'type' || k.need.includes(key) || k.may.includes(key))
243
+ continue;
244
+ if (NOT_OFFERED[key])
245
+ refuse('not_offered', NOT_OFFERED[key]);
246
+ refuse('invalid_param', `${type} takes no ${key.slice(0, 40)}`);
247
+ }
248
+ for (const key of k.need)
249
+ if (r[key] === undefined || r[key] === null)
250
+ refuse('invalid_param', `${type} needs ${key}`);
251
+ const market = () => ctx.market ?? refuse('unknown_symbol', 'no such market');
252
+ const asset = () => ctx.asset ?? refuse('unknown_asset', 'no such asset');
253
+ switch (type) {
254
+ case 'order': {
255
+ const m = market();
256
+ const side = sideOf(r.side);
257
+ const limit = r.orderType === 'limit' ? true : r.orderType === 'market' ? false : refuse('invalid_param', 'orderType is "market" or "limit"');
258
+ const exits = r.takeProfit !== undefined || r.stopLoss !== undefined;
259
+ if (exits)
260
+ needPerp(m, 'A take profit or stop loss');
261
+ if (!limit && !exits && r.expiry !== undefined)
262
+ refuse('invalid_param', 'a market order takes no expiry (it fills at once or not at all)');
263
+ const expiry = limit ? expiryOf(r, ctx, ORDER_LIFE_MS) : 0;
264
+ const parent = { marketId: m.marketId, clientOrderIndex: coi(r.clientOrderIndex, 'clientOrderIndex'), baseAmount: sizeOf(m, r.size), price: priceOf(m, r.price), isAsk: side === 'sell', orderType: limit ? ORDER_TYPE.limit : ORDER_TYPE.market, timeInForce: limit ? TIF.goodTillTime : TIF.immediateOrCancel, reduceOnly: false, triggerPrice: 0n, orderExpiry: expiry };
265
+ if (!exits)
266
+ return text({ type: 'create_order', ...fields(parent) });
267
+ const legExpiry = expiryOf(r, ctx, ORDER_LIFE_MS);
268
+ const closeIsAsk = side === 'buy';
269
+ const legs = [];
270
+ if (r.takeProfit !== undefined)
271
+ legs.push(exitLeg(m, r.takeProfit, 'takeProfit', closeIsAsk, legExpiry));
272
+ if (r.stopLoss !== undefined)
273
+ legs.push(exitLeg(m, r.stopLoss, 'stopLoss', closeIsAsk, legExpiry));
274
+ return text({ type: 'grouped_orders', grouping: legs.length === 2 ? GROUPING.otoco : GROUPING.oto, orders: [parent, ...legs].map(fields) });
275
+ }
276
+ case 'close': {
277
+ const m = market();
278
+ const side = sideOf(r.side);
279
+ return text({ type: 'create_order', ...fields({ marketId: m.marketId, clientOrderIndex: coi(r.clientOrderIndex, 'clientOrderIndex'), baseAmount: sizeOf(m, r.size), price: priceOf(m, r.price), isAsk: side === 'sell', orderType: ORDER_TYPE.market, timeInForce: TIF.immediateOrCancel, reduceOnly: m.type === 'perp', triggerPrice: 0n, orderExpiry: 0 }) });
280
+ }
281
+ case 'trigger': {
282
+ const m = market();
283
+ needPerp(m, 'A trigger order');
284
+ const side = sideOf(r.side);
285
+ const direction = r.direction === 'rises' || r.direction === 'falls' ? r.direction : refuse('invalid_param', 'direction is "rises" or "falls"');
286
+ if (typeof r.reduceOnly !== 'boolean')
287
+ refuse('invalid_param', 'reduceOnly is true or false');
288
+ if (r.expiryDays !== undefined && r.expiry !== undefined)
289
+ refuse('invalid_param', 'a trigger takes expiryDays or expiry, not both');
290
+ if (r.expiryDays !== undefined && (typeof r.expiryDays !== 'number' || ![1, 7, 28].includes(r.expiryDays)))
291
+ refuse('invalid_param', 'expiryDays is one of 1, 7, 28');
292
+ const limit = r.limitPrice !== undefined;
293
+ if (limit && r.price !== undefined)
294
+ refuse('invalid_param', 'a limit trigger order takes limitPrice, not price');
295
+ const trigger = priceOf(m, r.triggerPrice, 'triggerPrice');
296
+ const isAsk = side === 'sell';
297
+ return text({ type: 'create_order', ...fields({
298
+ marketId: m.marketId, clientOrderIndex: coi(r.clientOrderIndex, 'clientOrderIndex'), baseAmount: sizeOf(m, r.size),
299
+ price: limit ? priceOf(m, r.limitPrice, 'limitPrice') : r.price !== undefined ? priceOf(m, r.price) : boundFrom(trigger, isAsk),
300
+ isAsk, orderType: triggerType(side, direction, limit), timeInForce: limit ? TIF.goodTillTime : TIF.immediateOrCancel, reduceOnly: r.reduceOnly,
301
+ triggerPrice: trigger, orderExpiry: expiryOf(r, ctx, (r.expiryDays ?? 28) * 86_400_000),
302
+ }) });
303
+ }
304
+ case 'scale': {
305
+ const m = market();
306
+ needPerp(m, 'A scale order');
307
+ const side = sideOf(r.side);
308
+ if (typeof r.postOnly !== 'boolean' || typeof r.reduceOnly !== 'boolean')
309
+ refuse('invalid_param', 'postOnly and reduceOnly are true or false');
310
+ if (!Array.isArray(r.orders) || r.orders.length < 1 || r.orders.length > MAX_SCALE_ORDERS)
311
+ refuse('invalid_param', `orders is a list of 1 to ${MAX_SCALE_ORDERS}`);
312
+ const expiry = expiryOf(r, ctx, ORDER_LIFE_MS);
313
+ const orders = r.orders.map((raw, i) => {
314
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw))
315
+ return refuse('invalid_param', `orders[${i}] is an object`);
316
+ const o = raw;
317
+ for (const kk of Object.keys(o))
318
+ if (!['price', 'size', 'clientOrderIndex'].includes(kk))
319
+ refuse('invalid_param', `orders[${i}] takes no ${kk.slice(0, 40)}`);
320
+ return { marketId: m.marketId, clientOrderIndex: coi(o.clientOrderIndex, `orders[${i}].clientOrderIndex`), baseAmount: sizeOf(m, o.size, `orders[${i}].size`), price: priceOf(m, o.price, `orders[${i}].price`), isAsk: side === 'sell', orderType: ORDER_TYPE.limit, timeInForce: r.postOnly ? TIF.postOnly : TIF.goodTillTime, reduceOnly: r.reduceOnly, triggerPrice: 0n, orderExpiry: expiry };
321
+ });
322
+ return text({ type: 'batch_orders', orders: orders.map(fields) });
323
+ }
324
+ case 'modify': {
325
+ const m = market();
326
+ return text({ type: 'modify_order', marketId: m.marketId, ...orderRef(r), baseAmount: sizeOf(m, r.size), price: priceOf(m, r.price), triggerPrice: r.triggerPrice === undefined ? 0n : priceOf(m, r.triggerPrice, 'triggerPrice') });
327
+ }
328
+ case 'cancel': {
329
+ const m = market();
330
+ return text({ type: 'cancel_order', marketId: m.marketId, ...orderRef(r) });
331
+ }
332
+ case 'cancel_all': {
333
+ // every market, or the one in ctx.market (the body's symbol)
334
+ return ctx.market ? text({ type: 'cancel_all_orders', timeInForce: 0, time: 0, marketId: ctx.market.marketId }) : text({ type: 'cancel_all_orders', timeInForce: 0, time: 0 });
335
+ }
336
+ case 'margin': {
337
+ const m = market();
338
+ needPerp(m, 'Isolated margin');
339
+ const direction = r.direction === 'add' ? 1 : r.direction === 'remove' ? 0 : refuse('invalid_param', 'direction is "add" or "remove"');
340
+ const usdcAmount = toUnits(r.amount, 6, 'amount');
341
+ if (usdcAmount <= 0n || usdcAmount > 9223372036854775807n)
342
+ refuse('invalid_param', 'amount is out of range');
343
+ return text({ type: 'update_margin', marketId: m.marketId, usdcAmount, direction });
344
+ }
345
+ case 'leverage': {
346
+ const m = market();
347
+ needPerp(m, 'Leverage');
348
+ const lev = r.leverage;
349
+ if (typeof lev !== 'number' || !Number.isFinite(lev) || lev < 1 || lev > 10_000)
350
+ return refuse('invalid_param', 'leverage is a number from 1');
351
+ if (!Number.isInteger(lev))
352
+ refuse('leverage_not_whole', 'leverage is a whole number (1, 2, 3, ...), as on the website');
353
+ const mode = r.marginMode === 'cross' ? 0 : r.marginMode === 'isolated' ? 1 : refuse('invalid_margin_mode', 'marginMode is "cross" or "isolated"');
354
+ return text({ type: 'update_leverage', marketId: m.marketId, initialMarginFraction: Math.round(10_000 / lev), marginMode: mode });
355
+ }
356
+ case 'asset_margin': {
357
+ const a = asset();
358
+ if (typeof r.enabled !== 'boolean')
359
+ refuse('invalid_param', 'enabled is true or false');
360
+ if (a.symbol === 'USDC')
361
+ refuse('asset_not_supported', 'USDC always backs your trades and cannot be switched; asset_margin takes the coins accepted as margin, such as ETH');
362
+ return text({ type: 'update_asset_margin', assetIndex: a.assetId, enabled: r.enabled });
363
+ }
364
+ case 'own_transfer': {
365
+ const a = asset();
366
+ const from = r.from === 'perps' || r.from === 'spot' ? ROUTE[r.from] : refuse('invalid_param', 'from is "perps" or "spot"');
367
+ const to = r.to === 'perps' || r.to === 'spot' ? ROUTE[r.to] : refuse('invalid_param', 'to is "perps" or "spot"');
368
+ if (from === to)
369
+ refuse('invalid_param', 'from and to differ');
370
+ return text({ type: 'own_transfer', assetIndex: a.assetId, fromRoute: from, toRoute: to, amount: positive(toUnits(r.amount, a.decimals, 'amount'), I64_MAX, 'amount') });
371
+ }
372
+ case 'withdraw': {
373
+ const a = asset();
374
+ const route = r.route === 'perps' || r.route === 'spot' ? ROUTE[r.route] : refuse('invalid_param', 'route is "perps" or "spot"');
375
+ return text({ type: 'withdraw', assetIndex: a.assetId, routeType: route, amount: positive(toUnits(r.amount, a.decimals, 'amount'), U64_MAX, 'amount') });
376
+ }
377
+ }
378
+ return refuse('invalid_param', 'unknown request type');
379
+ }