@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.
@@ -0,0 +1,234 @@
1
+ /**
2
+ * The WAGMI.PRO API client: market data, your account, every trading action (built, signed and sent), "sent" and
3
+ * "confirmed", and the websocket. docs.wagmi.pro/api/client-libraries.
4
+ */
5
+ import { type AssetInfo, type MarketInfo, type RunRequest, type TradeRequest } from './action.js';
6
+ import { WagmiStream, type StreamMessage } from './stream.js';
7
+ export interface ClientOptions {
8
+ /** Your API key id (fx_...) and secret: account data and trading. Market data needs neither. */
9
+ apiKey?: string;
10
+ apiSecret?: string;
11
+ /** The same as apiKey and apiSecret (0.4.1): the names WagmiPartner takes, accepted here too. */
12
+ keyId?: string;
13
+ secret?: string;
14
+ /** For trading: the signing key (0x and 64 hex) and grant ID shown with a key that has Trade. */
15
+ signingKey?: string;
16
+ grantId?: string;
17
+ baseUrl?: string;
18
+ wsUrl?: string;
19
+ fetch?: typeof fetch;
20
+ WebSocket?: ConstructorParameters<typeof WagmiStream>[0] extends infer O ? O extends {
21
+ WebSocket?: infer W;
22
+ } ? W : never : never;
23
+ /** Your clock in ms (tests). */
24
+ now?: () => number;
25
+ /** withdrawExternal: off until the API offers withdrawals to another address (the Agent Key's next version). */
26
+ enableWithdrawExternal?: boolean;
27
+ }
28
+ export interface OrderResult {
29
+ orderId: string;
30
+ clientOrderId: string;
31
+ symbol: string;
32
+ marketId: number;
33
+ kind: string;
34
+ state: 'filled' | 'partially_filled' | 'resting' | 'waiting_trigger' | 'cancelled' | null;
35
+ side: 'buy' | 'sell' | null;
36
+ size: string;
37
+ filledSize: string;
38
+ remainingSize: string;
39
+ averagePrice: string | null;
40
+ price: string;
41
+ triggerPrice: string | null;
42
+ error?: string;
43
+ message?: string;
44
+ }
45
+ export interface TradeResult {
46
+ /** sent: the exchange took it, the confirmation follows on the orders channel; confirmed: done (orders); refused: not done. */
47
+ status: 'sent' | 'confirmed' | 'refused';
48
+ httpStatus: number;
49
+ sentAt?: string;
50
+ confirmedAt?: string;
51
+ orders?: OrderResult[];
52
+ txHashes?: string[];
53
+ error?: string;
54
+ message?: string;
55
+ /** Set when the answer was "sent" and you asked to wait: the orders channel's confirmed or refused event, or null. */
56
+ event?: StreamMessage | null;
57
+ }
58
+ export interface TradeOptions {
59
+ /** X-FX-Idempotency-Key; default a new random one. Send the same one again to learn a lost answer. */
60
+ idempotencyKey?: string;
61
+ /** When the answer is "sent": wait this long on `stream` for the confirmation (subscribe it to "orders" first). */
62
+ waitMs?: number;
63
+ stream?: WagmiStream;
64
+ /** Your builder code, on every order of a user you set up as a builder (WagmiPartner): your fee is added to it. */
65
+ partner?: string;
66
+ }
67
+ export declare class WagmiClient {
68
+ readonly baseUrl: string;
69
+ private marketCache;
70
+ private assetCache;
71
+ private readonly o;
72
+ constructor(options?: ClientOptions);
73
+ private now;
74
+ private fetch;
75
+ /** A new client order index: unique per process, below 2^48 (milliseconds x 1000 + a counter). */
76
+ static clientOrderIndex(now?: number): number;
77
+ /** One request. With a key it is signed (any path; account paths need it); without, market data is answered anonymously. */
78
+ request(method: 'GET' | 'POST' | 'PUT' | 'DELETE', path: string, query?: Record<string, string | number | undefined>, body?: string, extra?: Record<string, string>): Promise<{
79
+ status: number;
80
+ json: any;
81
+ headers: Headers;
82
+ }>;
83
+ private post;
84
+ private get;
85
+ markets(): Promise<MarketInfo[]>;
86
+ market(symbol: string): Promise<MarketInfo>;
87
+ assets(): Promise<AssetInfo[]>;
88
+ asset(symbol: string): Promise<AssetInfo>;
89
+ tickers(symbol?: string): Promise<any>;
90
+ orderbook(symbol: string, depth?: number): Promise<any>;
91
+ trades(symbol: string, limit?: number): Promise<any>;
92
+ candles(symbol: string, resolution: string, q?: {
93
+ from?: number;
94
+ to?: number;
95
+ limit?: number;
96
+ }): Promise<any>;
97
+ fundingRates(symbol: string, q?: {
98
+ from?: number;
99
+ to?: number;
100
+ limit?: number;
101
+ }): Promise<any>;
102
+ notices(): Promise<any>;
103
+ balances(): Promise<any>;
104
+ positions(): Promise<any>;
105
+ openOrders(q?: {
106
+ symbol?: string;
107
+ }): Promise<any>;
108
+ orderHistory(q?: Record<string, string | number>): Promise<any>;
109
+ endedOrders(q?: Record<string, string | number>): Promise<any>;
110
+ fills(q?: Record<string, string | number>): Promise<any>;
111
+ fundingPayments(q?: Record<string, string | number>): Promise<any>;
112
+ transfers(q?: Record<string, string | number>): Promise<any>;
113
+ depositInfo(): Promise<any>;
114
+ rewards(): Promise<any>;
115
+ advancedOrders(): Promise<any>;
116
+ margin(): Promise<any>;
117
+ feeRate(): Promise<any>;
118
+ leverageSettings(): Promise<any>;
119
+ spotApproval(): Promise<any>;
120
+ agentKey(): Promise<any>;
121
+ /**
122
+ * NOT AVAILABLE YET (answers 403 withdraw_external_not_enabled until the Agent Key's next version is out): the networks a
123
+ * withdrawal to another address can go to, or one quote (chainId, address, amount): what arrives, the fees, the time.
124
+ */
125
+ withdrawQuote(q?: {
126
+ chainId?: string;
127
+ address?: string;
128
+ amount?: string;
129
+ }): Promise<any>;
130
+ /** Builds the action, signs it with the signing key, signs the request with the key and sends it. */
131
+ trade(target: {
132
+ symbol: string;
133
+ } | {
134
+ asset: string;
135
+ } | Record<string, never>, request: TradeRequest, opts?: TradeOptions): Promise<TradeResult>;
136
+ placeOrder(symbol: string, o: Omit<Extract<TradeRequest, {
137
+ type: 'order';
138
+ }>, 'type' | 'clientOrderIndex'> & {
139
+ clientOrderIndex?: number;
140
+ }, opts?: TradeOptions): Promise<TradeResult>;
141
+ close(symbol: string, o: {
142
+ side: 'buy' | 'sell';
143
+ size: string;
144
+ price: string;
145
+ clientOrderIndex?: number;
146
+ }, opts?: TradeOptions): Promise<TradeResult>;
147
+ trigger(symbol: string, o: Omit<Extract<TradeRequest, {
148
+ type: 'trigger';
149
+ }>, 'type' | 'clientOrderIndex'> & {
150
+ clientOrderIndex?: number;
151
+ }, opts?: TradeOptions): Promise<TradeResult>;
152
+ scale(symbol: string, o: Omit<Extract<TradeRequest, {
153
+ type: 'scale';
154
+ }>, 'type'>, opts?: TradeOptions): Promise<TradeResult>;
155
+ /**
156
+ * NOT AVAILABLE YET: a USDC withdrawal to a chosen network and address (POST /v1/withdrawals, type withdraw_external).
157
+ * Needs the client option enableWithdrawExternal and, on the server, the Agent Key's next version; until then the API
158
+ * answers 403 withdraw_external_not_enabled. `ownerSignature` is your wallet's signature over the venue's transfer text.
159
+ */
160
+ withdrawExternal(w: {
161
+ route: 'fast' | 'relay';
162
+ chainId: string;
163
+ address: string;
164
+ amount: string;
165
+ fee: string;
166
+ txNonce: number;
167
+ memo?: string;
168
+ ownerSignature: string;
169
+ }, opts?: TradeOptions): Promise<TradeResult>;
170
+ /** Cancels every open order of the account now, or only `symbol`'s (POST /v1/orders/cancel, type cancel_all). */
171
+ cancelAll(o?: {
172
+ symbol?: string;
173
+ }, opts?: TradeOptions): Promise<TradeResult>;
174
+ /** USDC into an isolated position (POST /v1/leverage, type margin); the answer carries liquidationPrice {before, after}. */
175
+ addMargin(symbol: string, amount: string, opts?: TradeOptions): Promise<TradeResult>;
176
+ /** USDC out of an isolated position; refused margin_below_maintenance (with maxRemove) past what the position can give. */
177
+ removeMargin(symbol: string, amount: string, opts?: TradeOptions): Promise<TradeResult>;
178
+ /**
179
+ * Closes every open position at market, reduce-only, or only `symbol`'s, in ONE request (POST /v1/orders, type
180
+ * close_all): reads your positions, signs one close per position at the mark moved by at most `maxSlippagePercent`
181
+ * against you (default 2, the website's bound), and answers per position (confirmed, partly filled, refused).
182
+ */
183
+ closeAll(o?: {
184
+ symbol?: string;
185
+ maxSlippagePercent?: number;
186
+ }, opts?: TradeOptions): Promise<{
187
+ status: string;
188
+ positions: number;
189
+ confirmed: number;
190
+ results: Array<Record<string, any>>;
191
+ httpStatus: number;
192
+ }>;
193
+ modify(symbol: string, o: Omit<Extract<TradeRequest, {
194
+ type: 'modify';
195
+ }>, 'type'>, opts?: TradeOptions): Promise<TradeResult>;
196
+ cancel(symbol: string, ref: {
197
+ orderId: string;
198
+ } | {
199
+ orderIndex: string;
200
+ }, opts?: TradeOptions): Promise<TradeResult>;
201
+ setLeverage(symbol: string, leverage: number, marginMode: 'cross' | 'isolated', opts?: TradeOptions): Promise<TradeResult>;
202
+ setAssetMargin(asset: string, enabled: boolean, opts?: TradeOptions): Promise<TradeResult>;
203
+ transfer(asset: string, from: 'perps' | 'spot', to: 'perps' | 'spot', amount: string, opts?: TradeOptions): Promise<TradeResult>;
204
+ withdraw(asset: string, route: 'perps' | 'spot', amount: string, opts?: TradeOptions): Promise<TradeResult>;
205
+ /** A TWAP: one market order every intervalSeconds for durationSeconds. runId defaults to a new one. */
206
+ twap(symbol: string, o: Omit<Extract<RunRequest, {
207
+ type: 'twap' | 'chase_twap';
208
+ }>, 'type' | 'runId'> & {
209
+ runId?: string;
210
+ }, opts?: TradeOptions): Promise<TradeResult>;
211
+ /** A Chase TWAP: the same timing, each slice a limit order at the best price, chased when it moves. */
212
+ chaseTwap(symbol: string, o: Omit<Extract<RunRequest, {
213
+ type: 'twap' | 'chase_twap';
214
+ }>, 'type' | 'runId'> & {
215
+ runId?: string;
216
+ }, opts?: TradeOptions): Promise<TradeResult>;
217
+ /** A Swarm: `clips` market orders every intervalSeconds (irregular: each within 20% of equal). */
218
+ swarm(symbol: string, o: Omit<Extract<RunRequest, {
219
+ type: 'swarm';
220
+ }>, 'type' | 'runId'> & {
221
+ runId?: string;
222
+ }, opts?: TradeOptions): Promise<TradeResult>;
223
+ /** Stops a run: nothing more is placed, its resting order is cancelled, what filled stays. `runId` is "run_...". */
224
+ cancelRun(symbol: string, runId: string, opts?: TradeOptions): Promise<TradeResult>;
225
+ /** Your runs, running and ended (each with its progress), with your other advanced orders. */
226
+ runs(): Promise<any>;
227
+ cashbackQuote(amount: string, destination?: 'payout_wallet' | 'trading_account'): Promise<any>;
228
+ cashbackClaim(claimRef: string): Promise<any>;
229
+ referralQuote(amount: string, destination?: 'payout_wallet' | 'trading_account'): Promise<any>;
230
+ referralClaim(claimRef: string): Promise<any>;
231
+ claimStatus(claimRef: string): Promise<any>;
232
+ /** A websocket with this client's key (account channels) or none (public channels only). */
233
+ stream(): WagmiStream;
234
+ }
package/dist/client.js ADDED
@@ -0,0 +1,244 @@
1
+ /**
2
+ * The WAGMI.PRO API client: market data, your account, every trading action (built, signed and sent), "sent" and
3
+ * "confirmed", and the websocket. docs.wagmi.pro/api/client-libraries.
4
+ */
5
+ import { buildAction, WagmiError, newRunId, ROUTE_OF } from './action.js';
6
+ import { keyHeaders, newNonce, requestMessage, signRequest } from './sign.js';
7
+ import { WagmiStream } from './stream.js';
8
+ let lastCoi = 0;
9
+ export class WagmiClient {
10
+ baseUrl;
11
+ marketCache = null;
12
+ assetCache = null;
13
+ o;
14
+ constructor(options = {}) {
15
+ // one set of names for both classes (0.4.1): keyId / secret are apiKey / apiSecret
16
+ this.o = { ...options, apiKey: options.apiKey ?? options.keyId, apiSecret: options.apiSecret ?? options.secret };
17
+ this.baseUrl = (this.o.baseUrl ?? 'https://api.wagmi.pro').replace(/\/$/, '');
18
+ }
19
+ now() { return (this.o.now ?? Date.now)(); }
20
+ fetch() { const f = this.o.fetch ?? globalThis.fetch; if (!f)
21
+ throw new Error('no fetch: Node 20 or later, or pass options.fetch'); return f; }
22
+ /** A new client order index: unique per process, below 2^48 (milliseconds x 1000 + a counter). */
23
+ static clientOrderIndex(now = Date.now()) {
24
+ const v = Math.max(lastCoi + 1, (now % 2 ** 38) * 1000);
25
+ lastCoi = v;
26
+ return v;
27
+ }
28
+ /** One request. With a key it is signed (any path; account paths need it); without, market data is answered anonymously. */
29
+ async request(method, path, query, body, extra = {}) {
30
+ const qs = query ? Object.entries(query).filter(([, v]) => v !== undefined).map(([k, v]) => `${encodeURIComponent(k)}=${encodeURIComponent(String(v))}`).join('&') : '';
31
+ const pq = qs ? `${path}?${qs}` : path;
32
+ const headers = { accept: 'application/json', ...extra };
33
+ if (body !== undefined)
34
+ headers['content-type'] = 'application/json';
35
+ if (this.o.apiKey)
36
+ Object.assign(headers, await keyHeaders(this.o.apiKey, this.o.apiSecret ?? '', method, pq, body ?? '', this.now()));
37
+ const res = await this.fetch()(`${this.baseUrl}${pq}`, { method, headers, ...(body !== undefined ? { body } : {}) });
38
+ const text = await res.text();
39
+ let json = null;
40
+ try {
41
+ json = text ? JSON.parse(text) : null;
42
+ }
43
+ catch {
44
+ json = { error: 'not_json', message: text.slice(0, 200) };
45
+ }
46
+ return { status: res.status, json, headers: res.headers };
47
+ }
48
+ async post(path, body) {
49
+ const r = await this.request('POST', path, undefined, JSON.stringify(body));
50
+ if (r.status >= 400)
51
+ throw new WagmiError(r.json?.error ?? `http_${r.status}`, r.json?.message ?? `HTTP ${r.status}`, r.status, r.json);
52
+ return r.json;
53
+ }
54
+ async get(path, query) {
55
+ const r = await this.request('GET', path, query);
56
+ if (r.status >= 400)
57
+ throw new WagmiError(r.json?.error ?? `http_${r.status}`, r.json?.message ?? `HTTP ${r.status}`, r.status, r.json);
58
+ return r.json;
59
+ }
60
+ /* ── market data ─────────────────────────────────────────────────────────────────────────────── */
61
+ async markets() {
62
+ if (!this.marketCache || Date.now() - this.marketCache.at > 60_000)
63
+ this.marketCache = { at: Date.now(), list: (await this.get('/v1/markets')).markets };
64
+ return this.marketCache.list;
65
+ }
66
+ async market(symbol) {
67
+ const m = (await this.markets()).find((x) => x.symbol === symbol);
68
+ if (!m)
69
+ throw new WagmiError('unknown_symbol', `no market ${symbol}`);
70
+ return m;
71
+ }
72
+ async assets() {
73
+ if (!this.assetCache || Date.now() - this.assetCache.at > 60_000)
74
+ this.assetCache = { at: Date.now(), list: (await this.get('/v1/assets')).assets };
75
+ return this.assetCache.list;
76
+ }
77
+ async asset(symbol) {
78
+ const a = (await this.assets()).find((x) => x.symbol === symbol);
79
+ if (!a)
80
+ throw new WagmiError('unknown_asset', `no asset ${symbol}`);
81
+ return a;
82
+ }
83
+ tickers(symbol) { return this.get('/v1/tickers', { symbol }); }
84
+ orderbook(symbol, depth) { return this.get('/v1/orderbook', { symbol, depth }); }
85
+ trades(symbol, limit) { return this.get('/v1/trades', { symbol, limit }); }
86
+ candles(symbol, resolution, q = {}) { return this.get('/v1/candles', { symbol, resolution, ...q }); }
87
+ fundingRates(symbol, q = {}) { return this.get('/v1/funding', { symbol, ...q }); }
88
+ notices() { return this.get('/v1/notices'); }
89
+ /* ── your account (a key with Read account) ─────────────────────────────────────────────────── */
90
+ balances() { return this.get('/v1/account/balances'); }
91
+ positions() { return this.get('/v1/account/positions'); }
92
+ openOrders(q = {}) { return this.get('/v1/account/orders', q); }
93
+ orderHistory(q = {}) { return this.get('/v1/account/orders/history', q); }
94
+ endedOrders(q = {}) { return this.get('/v1/account/orders/ended', q); }
95
+ fills(q = {}) { return this.get('/v1/account/fills', q); }
96
+ fundingPayments(q = {}) { return this.get('/v1/account/funding', q); }
97
+ transfers(q = {}) { return this.get('/v1/account/transfers', q); }
98
+ depositInfo() { return this.get('/v1/account/deposit-info'); }
99
+ rewards() { return this.get('/v1/account/rewards'); }
100
+ advancedOrders() { return this.get('/v1/account/advanced-orders'); }
101
+ margin() { return this.get('/v1/account/margin'); }
102
+ feeRate() { return this.get('/v1/account/fee-rate'); }
103
+ leverageSettings() { return this.get('/v1/account/leverage'); }
104
+ spotApproval() { return this.get('/v1/account/spot-approval'); }
105
+ agentKey() { return this.get('/v1/account/agent-key'); }
106
+ /**
107
+ * NOT AVAILABLE YET (answers 403 withdraw_external_not_enabled until the Agent Key's next version is out): the networks a
108
+ * withdrawal to another address can go to, or one quote (chainId, address, amount): what arrives, the fees, the time.
109
+ */
110
+ withdrawQuote(q = {}) { return this.get('/v1/account/withdraw-quote', q); }
111
+ /* ── trading (a key with Trade, its signing key and grant ID) ──────────────────────────────── */
112
+ /** Builds the action, signs it with the signing key, signs the request with the key and sends it. */
113
+ async trade(target, request, opts = {}) {
114
+ if (!this.o.apiKey || !this.o.apiSecret || !this.o.signingKey || !this.o.grantId)
115
+ throw new WagmiError('missing_auth', 'trading needs apiKey, apiSecret, signingKey and grantId');
116
+ const ts = this.now();
117
+ const ctx = 'symbol' in target ? { market: await this.market(target.symbol), signedAt: ts, now: ts } : 'asset' in target ? { asset: await this.asset(target.asset), signedAt: ts, now: ts } : { signedAt: ts, now: ts };
118
+ const action = buildAction(request, ctx);
119
+ const nonce = newNonce();
120
+ const sig = await signRequest(this.o.signingKey, await requestMessage(this.o.grantId, ts, nonce, action));
121
+ const body = JSON.stringify({ ...target, request, action, auth: { ts, nonce, sig }, ...(opts.partner ? { partner: opts.partner } : {}) });
122
+ const idem = opts.idempotencyKey ?? `fx-${newNonce()}`;
123
+ const r = await this.request('POST', ROUTE_OF[request.type], undefined, body, { 'X-FX-Idempotency-Key': idem });
124
+ const j = r.json ?? {};
125
+ // A run answers "started" (or "cancelled" for cancel_run); every other request "sent", "confirmed" or "refused".
126
+ if (j.status !== 'sent' && j.status !== 'confirmed' && j.status !== 'refused' && j.status !== 'started' && j.status !== 'cancelled') {
127
+ throw new WagmiError(j.error ?? `http_${r.status}`, j.message ?? `HTTP ${r.status}`, r.status, j);
128
+ }
129
+ const out = { ...j, httpStatus: r.status };
130
+ if (out.status === 'sent' && opts.stream && opts.waitMs) {
131
+ const ref = 'clientOrderIndex' in request ? { clientOrderId: request.clientOrderIndex } : 'orderId' in request && request.orderId ? { orderId: request.orderId } : 'orderIndex' in request && request.orderIndex ? { clientOrderId: request.orderIndex } : null;
132
+ out.event = ref ? await opts.stream.waitForOrder(ref, opts.waitMs) : null;
133
+ }
134
+ return out;
135
+ }
136
+ placeOrder(symbol, o, opts) {
137
+ return this.trade({ symbol }, { type: 'order', clientOrderIndex: o.clientOrderIndex ?? WagmiClient.clientOrderIndex(), ...o }, opts);
138
+ }
139
+ close(symbol, o, opts) {
140
+ return this.trade({ symbol }, { type: 'close', clientOrderIndex: o.clientOrderIndex ?? WagmiClient.clientOrderIndex(), ...o }, opts);
141
+ }
142
+ trigger(symbol, o, opts) {
143
+ return this.trade({ symbol }, { type: 'trigger', clientOrderIndex: o.clientOrderIndex ?? WagmiClient.clientOrderIndex(), ...o }, opts);
144
+ }
145
+ scale(symbol, o, opts) { return this.trade({ symbol }, { type: 'scale', ...o }, opts); }
146
+ /**
147
+ * NOT AVAILABLE YET: a USDC withdrawal to a chosen network and address (POST /v1/withdrawals, type withdraw_external).
148
+ * Needs the client option enableWithdrawExternal and, on the server, the Agent Key's next version; until then the API
149
+ * answers 403 withdraw_external_not_enabled. `ownerSignature` is your wallet's signature over the venue's transfer text.
150
+ */
151
+ async withdrawExternal(w, opts = {}) {
152
+ if (!this.o.enableWithdrawExternal)
153
+ throw new WagmiError('withdraw_external_not_enabled', 'Withdrawals to another address are not available through the API yet (set enableWithdrawExternal once they are).');
154
+ if (!this.o.apiKey || !this.o.apiSecret || !this.o.signingKey || !this.o.grantId)
155
+ throw new WagmiError('missing_auth', 'trading needs apiKey, apiSecret, signingKey and grantId');
156
+ const micro = (v, p) => { const m = /^(\d{1,9})(?:\.(\d{1,6}))?$/.exec(v); if (!m)
157
+ throw new WagmiError('invalid_param', `${p} is USDC as a decimal string, at most 6 decimals`); return String(BigInt(m[1]) * 1000000n + BigInt((m[2] ?? '').padEnd(6, '0'))); };
158
+ const address = /^0x/i.test(w.address) ? w.address.toLowerCase() : w.address;
159
+ const memo = w.memo ? w.memo.toLowerCase() : undefined;
160
+ const action = `{"type":"withdraw_external","route":${JSON.stringify(w.route)},"chainId":${JSON.stringify(w.chainId)},"address":${JSON.stringify(address)},"amount":${micro(w.amount, 'amount')},"fee":${micro(w.fee, 'fee')}${memo ? `,"memo":${JSON.stringify(memo)}` : ''},"txNonce":${w.txNonce},"ownerSignature":${JSON.stringify(w.ownerSignature.toLowerCase())}}`;
161
+ const ts = this.now();
162
+ const nonce = newNonce();
163
+ const sig = await signRequest(this.o.signingKey, await requestMessage(this.o.grantId, ts, nonce, action));
164
+ const request = { type: 'withdraw_external', ...w };
165
+ const body = JSON.stringify({ asset: 'USDC', request, action, auth: { ts, nonce, sig } });
166
+ const r = await this.request('POST', '/v1/withdrawals', undefined, body, { 'X-FX-Idempotency-Key': opts.idempotencyKey ?? `fx-${newNonce()}` });
167
+ const j = r.json ?? {};
168
+ if (j.status !== 'sent' && j.status !== 'confirmed' && j.status !== 'refused')
169
+ throw new WagmiError(j.error ?? `http_${r.status}`, j.message ?? `HTTP ${r.status}`, r.status, j);
170
+ return { ...j, httpStatus: r.status };
171
+ }
172
+ /** Cancels every open order of the account now, or only `symbol`'s (POST /v1/orders/cancel, type cancel_all). */
173
+ cancelAll(o = {}, opts) { return this.trade(o.symbol ? { symbol: o.symbol } : {}, { type: 'cancel_all' }, opts); }
174
+ /** USDC into an isolated position (POST /v1/leverage, type margin); the answer carries liquidationPrice {before, after}. */
175
+ addMargin(symbol, amount, opts) { return this.trade({ symbol }, { type: 'margin', direction: 'add', amount }, opts); }
176
+ /** USDC out of an isolated position; refused margin_below_maintenance (with maxRemove) past what the position can give. */
177
+ removeMargin(symbol, amount, opts) { return this.trade({ symbol }, { type: 'margin', direction: 'remove', amount }, opts); }
178
+ /**
179
+ * Closes every open position at market, reduce-only, or only `symbol`'s, in ONE request (POST /v1/orders, type
180
+ * close_all): reads your positions, signs one close per position at the mark moved by at most `maxSlippagePercent`
181
+ * against you (default 2, the website's bound), and answers per position (confirmed, partly filled, refused).
182
+ */
183
+ async closeAll(o = {}, opts = {}) {
184
+ if (!this.o.apiKey || !this.o.apiSecret || !this.o.signingKey || !this.o.grantId)
185
+ throw new WagmiError('missing_auth', 'trading needs apiKey, apiSecret, signingKey and grantId');
186
+ const slip = o.maxSlippagePercent ?? 2;
187
+ if (!(slip > 0 && slip < 50))
188
+ throw new WagmiError('invalid_param', 'maxSlippagePercent is above 0 and below 50');
189
+ const now = await this.positions();
190
+ // never from positions the server says may be old: closing nothing would look like success
191
+ if (now.stale === true && now.positionsCurrent !== true)
192
+ throw new WagmiError('account_data_stale', 'your open positions are still loading; nothing was closed, retry in a few seconds');
193
+ const open = (now.positions ?? []).filter((p) => Number(p.size) > 0 && (!o.symbol || p.symbol === o.symbol));
194
+ if (!open.length)
195
+ return { status: 'closed', positions: 0, confirmed: 0, results: [], httpStatus: 200 };
196
+ const ts = this.now();
197
+ const closes = [];
198
+ for (const p of open) {
199
+ const m = await this.market(p.symbol);
200
+ const side = p.side === 'long' ? 'sell' : 'buy';
201
+ const f = 10 ** m.priceDecimals;
202
+ const raw = Number(p.markPrice) * (side === 'sell' ? 1 - slip / 100 : 1 + slip / 100);
203
+ const price = ((side === 'sell' ? Math.floor(raw * f) : Math.ceil(raw * f)) / f).toFixed(m.priceDecimals);
204
+ const request = { type: 'close', side, size: String(p.size), price, clientOrderIndex: WagmiClient.clientOrderIndex() };
205
+ const action = buildAction(request, { market: m, signedAt: ts, now: ts });
206
+ const nonce = newNonce();
207
+ const sig = await signRequest(this.o.signingKey, await requestMessage(this.o.grantId, ts, nonce, action));
208
+ closes.push({ symbol: p.symbol, request, action, auth: { ts, nonce, sig } });
209
+ }
210
+ const body = JSON.stringify({ request: { type: 'close_all' }, closes, ...(opts.partner ? { partner: opts.partner } : {}) });
211
+ const r = await this.request('POST', '/v1/orders', undefined, body, { 'X-FX-Idempotency-Key': opts.idempotencyKey ?? `fx-${newNonce()}` });
212
+ const j = r.json ?? {};
213
+ if (!Array.isArray(j.results))
214
+ throw new WagmiError(j.error ?? `http_${r.status}`, j.message ?? `HTTP ${r.status}`, r.status, j);
215
+ return { ...j, httpStatus: r.status };
216
+ }
217
+ modify(symbol, o, opts) { return this.trade({ symbol }, { type: 'modify', ...o }, opts); }
218
+ cancel(symbol, ref, opts) { return this.trade({ symbol }, { type: 'cancel', ...ref }, opts); }
219
+ setLeverage(symbol, leverage, marginMode, opts) { return this.trade({ symbol }, { type: 'leverage', leverage, marginMode }, opts); }
220
+ setAssetMargin(asset, enabled, opts) { return this.trade({ asset }, { type: 'asset_margin', enabled }, opts); }
221
+ transfer(asset, from, to, amount, opts) { return this.trade({ asset }, { type: 'own_transfer', from, to, amount }, opts); }
222
+ withdraw(asset, route, amount, opts) { return this.trade({ asset }, { type: 'withdraw', route, amount }, opts); }
223
+ /* ── background runs: signed once, carried out by your Agent Key with your client closed (Background orders on) ── */
224
+ /** A TWAP: one market order every intervalSeconds for durationSeconds. runId defaults to a new one. */
225
+ twap(symbol, o, opts) { return this.trade({ symbol }, { type: 'twap', ...o, runId: o.runId ?? newRunId() }, opts); }
226
+ /** A Chase TWAP: the same timing, each slice a limit order at the best price, chased when it moves. */
227
+ chaseTwap(symbol, o, opts) { return this.trade({ symbol }, { type: 'chase_twap', ...o, runId: o.runId ?? newRunId() }, opts); }
228
+ /** A Swarm: `clips` market orders every intervalSeconds (irregular: each within 20% of equal). */
229
+ swarm(symbol, o, opts) { return this.trade({ symbol }, { type: 'swarm', ...o, runId: o.runId ?? newRunId() }, opts); }
230
+ /** Stops a run: nothing more is placed, its resting order is cancelled, what filled stays. `runId` is "run_...". */
231
+ cancelRun(symbol, runId, opts) { return this.trade({ symbol }, { type: 'cancel_run', runId }, opts); }
232
+ /** Your runs, running and ended (each with its progress), with your other advanced orders. */
233
+ runs() { return this.get('/v1/account/advanced-orders'); }
234
+ /* ── reward claims (key permission Claim): quote, then claim the quote within its 3 minutes ───────────────── */
235
+ cashbackQuote(amount, destination) { return this.post('/v1/rewards/cashback/quote', { amount, ...(destination ? { destination } : {}) }); }
236
+ cashbackClaim(claimRef) { return this.post('/v1/rewards/cashback/claim', { claimRef }); }
237
+ referralQuote(amount, destination) { return this.post('/v1/rewards/referrals/quote', { amount, ...(destination ? { destination } : {}) }); }
238
+ referralClaim(claimRef) { return this.post('/v1/rewards/referrals/claim', { claimRef }); }
239
+ claimStatus(claimRef) { return this.get('/v1/rewards/claims/status', { claimRef }); }
240
+ /** A websocket with this client's key (account channels) or none (public channels only). */
241
+ stream() {
242
+ return new WagmiStream({ url: this.o.wsUrl ?? `${this.baseUrl.replace(/^http/, 'ws')}/v1/ws`, ...(this.o.apiKey ? { apiKey: this.o.apiKey, apiSecret: this.o.apiSecret } : {}), ...(this.o.WebSocket ? { WebSocket: this.o.WebSocket } : {}), ...(this.o.now ? { now: this.o.now } : {}) });
243
+ }
244
+ }
@@ -0,0 +1,9 @@
1
+ export { buildAction, toUnits, WagmiError, ROUTE_OF, ORDER_LIFE_MS, MAX_CLIENT_ORDER_INDEX, MAX_SCALE_ORDERS, newRunId, RUN_LIMITS } from './action.js';
2
+ export type { MarketInfo, AssetInfo, TradeRequest, Side, ExitLeg, BuildContext, RunRequest, RunType } from './action.js';
3
+ export { requestMessage, signRequest, sha256Hex, hmacHex, keyHeaders, newNonce, REQUEST_PREFIX } from './sign.js';
4
+ export { WagmiClient } from './client.js';
5
+ export type { ClientOptions, TradeResult, TradeOptions, OrderResult } from './client.js';
6
+ export { WagmiStream } from './stream.js';
7
+ export type { StreamMessage, StreamOptions } from './stream.js';
8
+ export { WagmiPartner, newRequestKey, signDraft, viemWallet, ethersWallet } from './partner.js';
9
+ export type { PartnerOptions, PartnerFee, PartnerMe, SideFee, SetupDraft, SetupStep, SetupWallet, Withdrawal, WithdrawalDraft, WithdrawalTransaction } from './partner.js';
package/dist/index.js ADDED
@@ -0,0 +1,5 @@
1
+ export { buildAction, toUnits, WagmiError, ROUTE_OF, ORDER_LIFE_MS, MAX_CLIENT_ORDER_INDEX, MAX_SCALE_ORDERS, newRunId, RUN_LIMITS } from './action.js';
2
+ export { requestMessage, signRequest, sha256Hex, hmacHex, keyHeaders, newNonce, REQUEST_PREFIX } from './sign.js';
3
+ export { WagmiClient } from './client.js';
4
+ export { WagmiStream } from './stream.js';
5
+ export { WagmiPartner, newRequestKey, signDraft, viemWallet, ethersWallet } from './partner.js';