@edel-finance/sdk 0.0.0-stage → 0.0.2
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/generated/asyncapi.d.ts +52 -0
- package/dist/generated/asyncapi.js +172 -0
- package/dist/generated/operations.d.ts +2820 -0
- package/dist/generated/operations.js +1627 -0
- package/dist/generated/proto/realtime-streams_pb.d.ts +3578 -0
- package/dist/generated/proto/realtime-streams_pb.js +496 -0
- package/dist/generated/rest/client/client.gen.d.ts +2 -0
- package/dist/generated/rest/client/client.gen.js +216 -0
- package/dist/generated/rest/client/index.d.ts +10 -0
- package/dist/generated/rest/client/index.js +6 -0
- package/dist/generated/rest/client/types.gen.d.ts +120 -0
- package/dist/generated/rest/client/types.gen.js +2 -0
- package/dist/generated/rest/client/utils.gen.d.ts +37 -0
- package/dist/generated/rest/client/utils.gen.js +228 -0
- package/dist/generated/rest/client.gen.d.ts +12 -0
- package/dist/generated/rest/client.gen.js +3 -0
- package/dist/generated/rest/core/auth.gen.d.ts +25 -0
- package/dist/generated/rest/core/auth.gen.js +14 -0
- package/dist/generated/rest/core/bodySerializer.gen.d.ts +25 -0
- package/dist/generated/rest/core/bodySerializer.gen.js +57 -0
- package/dist/generated/rest/core/params.gen.d.ts +43 -0
- package/dist/generated/rest/core/params.gen.js +109 -0
- package/dist/generated/rest/core/pathSerializer.gen.d.ts +33 -0
- package/dist/generated/rest/core/pathSerializer.gen.js +106 -0
- package/dist/generated/rest/core/queryKeySerializer.gen.d.ts +18 -0
- package/dist/generated/rest/core/queryKeySerializer.gen.js +92 -0
- package/dist/generated/rest/core/serverSentEvents.gen.d.ts +71 -0
- package/dist/generated/rest/core/serverSentEvents.gen.js +132 -0
- package/dist/generated/rest/core/types.gen.d.ts +83 -0
- package/dist/generated/rest/core/types.gen.js +2 -0
- package/dist/generated/rest/core/utils.gen.d.ts +19 -0
- package/dist/generated/rest/core/utils.gen.js +87 -0
- package/dist/generated/rest/index.d.ts +2 -0
- package/dist/generated/rest/index.js +2 -0
- package/dist/generated/rest/sdk.gen.d.ts +2977 -0
- package/dist/generated/rest/sdk.gen.js +6126 -0
- package/dist/generated/rest/types.gen.d.ts +30058 -0
- package/dist/generated/rest/types.gen.js +2 -0
- package/dist/index.d.ts +175 -0
- package/dist/index.js +502 -0
- package/dist/swap.d.ts +130 -0
- package/dist/swap.js +16 -0
- package/package.json +33 -3
- package/README.md +0 -3
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Thin handwritten core for @edel-finance/sdk.
|
|
3
|
+
*
|
|
4
|
+
* Handles environment routing (MainNet and TestNet only), bearer authentication,
|
|
5
|
+
* automatic Idempotency-Key injection on mutating requests, bounded retries,
|
|
6
|
+
* typed REST helpers, and resilient WebSocket subscriptions. Generated OpenAPI 3.1
|
|
7
|
+
* REST bindings and Protobuf realtime schemas are re-exported under `rest` and `proto`.
|
|
8
|
+
*/
|
|
9
|
+
import { type AsyncApiChannel, EdelRealtimeChannels, type RealtimeChannelSubscribeOptions } from "./generated/asyncapi.js";
|
|
10
|
+
import { EdelOperationsClient, type OpenApiOperationId, type OperationCallParams } from "./generated/operations.js";
|
|
11
|
+
import { type CreateSwapOrderRequest, type SubmitSwapOrderRequest, type SwapEarningsQuery, type SwapEarningsResponse, type SwapOrder, type SwapOrderStatusEvent, type SwapPair, type SwapQuote, type SwapQuoteRequest } from "./swap.js";
|
|
12
|
+
export * from "./generated/asyncapi.js";
|
|
13
|
+
export * from "./generated/operations.js";
|
|
14
|
+
export * as proto from "./generated/proto/realtime-streams_pb.js";
|
|
15
|
+
export * as rest from "./generated/rest/index.js";
|
|
16
|
+
export * from "./swap.js";
|
|
17
|
+
export type EdelNetwork = "mainnet" | "testnet";
|
|
18
|
+
export interface EdelEndpoints {
|
|
19
|
+
readonly restUrl: string;
|
|
20
|
+
readonly realtimeUrl: string;
|
|
21
|
+
}
|
|
22
|
+
export declare const NETWORK_ENDPOINTS: Record<EdelNetwork, EdelEndpoints>;
|
|
23
|
+
export interface EdelClientOptions {
|
|
24
|
+
network?: EdelNetwork;
|
|
25
|
+
baseUrl?: string;
|
|
26
|
+
realtimeUrl?: string;
|
|
27
|
+
apiKey?: string;
|
|
28
|
+
bearerToken?: string;
|
|
29
|
+
maxRetries?: number;
|
|
30
|
+
retryBaseDelayMs?: number;
|
|
31
|
+
fetchImpl?: typeof fetch;
|
|
32
|
+
webSocketImpl?: typeof WebSocket;
|
|
33
|
+
}
|
|
34
|
+
export interface RequestOptions {
|
|
35
|
+
method?: "GET" | "POST" | "PUT" | "PATCH" | "DELETE";
|
|
36
|
+
query?: Record<string, string | number | boolean | undefined>;
|
|
37
|
+
body?: unknown;
|
|
38
|
+
headers?: Record<string, string>;
|
|
39
|
+
idempotencyKey?: string;
|
|
40
|
+
signal?: AbortSignal;
|
|
41
|
+
}
|
|
42
|
+
export declare class EdelApiError extends Error {
|
|
43
|
+
readonly status: number;
|
|
44
|
+
readonly code: string;
|
|
45
|
+
readonly details: unknown;
|
|
46
|
+
constructor(status: number, code: string, message: string, details?: unknown);
|
|
47
|
+
}
|
|
48
|
+
export interface MarketSummary {
|
|
49
|
+
id?: string;
|
|
50
|
+
symbol: string;
|
|
51
|
+
base?: string;
|
|
52
|
+
quote?: string;
|
|
53
|
+
active?: boolean;
|
|
54
|
+
type?: string;
|
|
55
|
+
[key: string]: unknown;
|
|
56
|
+
}
|
|
57
|
+
export interface TickerSummary {
|
|
58
|
+
symbol: string;
|
|
59
|
+
last?: number | string | null;
|
|
60
|
+
bid?: number | string | null;
|
|
61
|
+
ask?: number | string | null;
|
|
62
|
+
baseVolume?: number | string | null;
|
|
63
|
+
quoteVolume?: number | string | null;
|
|
64
|
+
percentage?: number | string | null;
|
|
65
|
+
timestamp?: number;
|
|
66
|
+
[key: string]: unknown;
|
|
67
|
+
}
|
|
68
|
+
export interface OrderBookResponse {
|
|
69
|
+
symbol: string;
|
|
70
|
+
bids: Array<[number | string, number | string]>;
|
|
71
|
+
asks: Array<[number | string, number | string]>;
|
|
72
|
+
timestamp?: number;
|
|
73
|
+
nonce?: number;
|
|
74
|
+
[key: string]: unknown;
|
|
75
|
+
}
|
|
76
|
+
export declare class EdelClient {
|
|
77
|
+
readonly network: EdelNetwork;
|
|
78
|
+
readonly baseUrl: string;
|
|
79
|
+
readonly realtimeUrl: string;
|
|
80
|
+
private readonly token?;
|
|
81
|
+
private readonly maxRetries;
|
|
82
|
+
private readonly retryBaseDelayMs;
|
|
83
|
+
private readonly fetchImpl;
|
|
84
|
+
private readonly webSocketImpl?;
|
|
85
|
+
readonly operations: EdelOperationsClient;
|
|
86
|
+
constructor(options?: EdelClientOptions);
|
|
87
|
+
callOperation<T = unknown>(operationId: OpenApiOperationId, params?: OperationCallParams): Promise<T>;
|
|
88
|
+
request<T = unknown>(path: string, options?: RequestOptions): Promise<T>;
|
|
89
|
+
getMarkets(params?: {
|
|
90
|
+
type?: "spot" | "perps";
|
|
91
|
+
}): Promise<MarketSummary[]>;
|
|
92
|
+
getTickers(params?: {
|
|
93
|
+
type?: "spot" | "perps";
|
|
94
|
+
symbol?: string;
|
|
95
|
+
}): Promise<Record<string, TickerSummary> | TickerSummary[]>;
|
|
96
|
+
getOrderBook(symbol: string, params?: {
|
|
97
|
+
limit?: number;
|
|
98
|
+
type?: "spot" | "perps";
|
|
99
|
+
}): Promise<OrderBookResponse>;
|
|
100
|
+
getTrades(symbol: string, params?: {
|
|
101
|
+
limit?: number;
|
|
102
|
+
since?: number;
|
|
103
|
+
type?: "spot" | "perps";
|
|
104
|
+
}): Promise<unknown[]>;
|
|
105
|
+
getCandles(symbol: string, params?: {
|
|
106
|
+
timeframe?: string;
|
|
107
|
+
limit?: number;
|
|
108
|
+
since?: number;
|
|
109
|
+
type?: "spot" | "perps";
|
|
110
|
+
}): Promise<unknown[]>;
|
|
111
|
+
getFundingRates(): Promise<unknown>;
|
|
112
|
+
getAccount(accountId: string): Promise<unknown>;
|
|
113
|
+
getPositions(accountId: string): Promise<unknown>;
|
|
114
|
+
placeOrder(body: Record<string, unknown>, idempotencyKey?: string): Promise<unknown>;
|
|
115
|
+
cancelOrder(orderId: string, idempotencyKey?: string): Promise<unknown>;
|
|
116
|
+
getSwapPairs(): Promise<SwapPair[]>;
|
|
117
|
+
getSwapQuote(body: SwapQuoteRequest, idempotencyKey?: string): Promise<SwapQuote>;
|
|
118
|
+
createSwapOrder(body: CreateSwapOrderRequest, idempotencyKey?: string): Promise<SwapOrder>;
|
|
119
|
+
getSwapOrder(orderId: string): Promise<SwapOrder>;
|
|
120
|
+
submitSwapOrder(swapId: string, body?: SubmitSwapOrderRequest, idempotencyKey?: string): Promise<SwapOrder>;
|
|
121
|
+
getSwapEarnings(query?: SwapEarningsQuery): Promise<SwapEarningsResponse>;
|
|
122
|
+
realtime(options?: Omit<EdelRealtimeOptions, "url">): EdelRealtimeClient;
|
|
123
|
+
}
|
|
124
|
+
export interface EdelRealtimeOptions {
|
|
125
|
+
url: string;
|
|
126
|
+
ticket?: string;
|
|
127
|
+
heartbeatIntervalMs?: number;
|
|
128
|
+
reconnectDelayMs?: number;
|
|
129
|
+
maxReconnectDelayMs?: number;
|
|
130
|
+
webSocketImpl?: typeof WebSocket;
|
|
131
|
+
}
|
|
132
|
+
export interface RealtimeSubscription {
|
|
133
|
+
channel: string;
|
|
134
|
+
marketId?: string;
|
|
135
|
+
accountId?: string;
|
|
136
|
+
orderId?: string;
|
|
137
|
+
}
|
|
138
|
+
export declare class EdelRealtimeClient {
|
|
139
|
+
private readonly url;
|
|
140
|
+
private readonly ticket?;
|
|
141
|
+
private readonly heartbeatIntervalMs;
|
|
142
|
+
private readonly reconnectDelayMs;
|
|
143
|
+
private readonly maxReconnectDelayMs;
|
|
144
|
+
private readonly webSocketImpl;
|
|
145
|
+
private ws?;
|
|
146
|
+
private heartbeatTimer?;
|
|
147
|
+
private reconnectTimer?;
|
|
148
|
+
private reconnectAttempts;
|
|
149
|
+
private closed;
|
|
150
|
+
private readonly activeSubscriptions;
|
|
151
|
+
private readonly listeners;
|
|
152
|
+
private readonly openListeners;
|
|
153
|
+
private readonly closeListeners;
|
|
154
|
+
readonly channels: EdelRealtimeChannels;
|
|
155
|
+
constructor(options: EdelRealtimeOptions);
|
|
156
|
+
get isConnected(): boolean;
|
|
157
|
+
connect(): void;
|
|
158
|
+
subscribe(sub: RealtimeSubscription): () => void;
|
|
159
|
+
unsubscribe(sub: RealtimeSubscription): void;
|
|
160
|
+
subscribeChannel(channel: AsyncApiChannel, options?: RealtimeChannelSubscribeOptions): () => void;
|
|
161
|
+
subscribeSwapOrder(orderId: string, onStatus: (event: SwapOrderStatusEvent) => void): () => void;
|
|
162
|
+
onMessage(listener: (frame: unknown) => void): () => void;
|
|
163
|
+
onOpen(listener: () => void): () => void;
|
|
164
|
+
onClose(listener: () => void): () => void;
|
|
165
|
+
close(): void;
|
|
166
|
+
private sendSubscribeFrame;
|
|
167
|
+
private startHeartbeat;
|
|
168
|
+
private stopHeartbeat;
|
|
169
|
+
}
|
|
170
|
+
/**
|
|
171
|
+
* Generate an RFC 4122 v4 UUID safely across secure HTTPS contexts,
|
|
172
|
+
* non-HTTPS HTTP origins (such as LAN/Tailscale previews), and embedded WebViews
|
|
173
|
+
* where `crypto.randomUUID` may be undefined.
|
|
174
|
+
*/
|
|
175
|
+
export declare function generateUuidV4(): string;
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,502 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Thin handwritten core for @edel-finance/sdk.
|
|
3
|
+
*
|
|
4
|
+
* Handles environment routing (MainNet and TestNet only), bearer authentication,
|
|
5
|
+
* automatic Idempotency-Key injection on mutating requests, bounded retries,
|
|
6
|
+
* typed REST helpers, and resilient WebSocket subscriptions. Generated OpenAPI 3.1
|
|
7
|
+
* REST bindings and Protobuf realtime schemas are re-exported under `rest` and `proto`.
|
|
8
|
+
*/
|
|
9
|
+
import { EdelRealtimeChannels, } from "./generated/asyncapi.js";
|
|
10
|
+
import { EdelOperationsClient, } from "./generated/operations.js";
|
|
11
|
+
import { validateMaxSlippageBps, } from "./swap.js";
|
|
12
|
+
export * from "./generated/asyncapi.js";
|
|
13
|
+
export * from "./generated/operations.js";
|
|
14
|
+
export * as proto from "./generated/proto/realtime-streams_pb.js";
|
|
15
|
+
export * as rest from "./generated/rest/index.js";
|
|
16
|
+
export * from "./swap.js";
|
|
17
|
+
export const NETWORK_ENDPOINTS = {
|
|
18
|
+
mainnet: {
|
|
19
|
+
restUrl: "https://mainnet.edel-api.xyz",
|
|
20
|
+
realtimeUrl: "wss://realtime-mainnet.edel-api.xyz/streams/v1/ws",
|
|
21
|
+
},
|
|
22
|
+
testnet: {
|
|
23
|
+
restUrl: "https://testnet.edel-api.xyz",
|
|
24
|
+
realtimeUrl: "wss://realtime-testnet.edel-api.xyz/streams/v1/ws",
|
|
25
|
+
},
|
|
26
|
+
};
|
|
27
|
+
export class EdelApiError extends Error {
|
|
28
|
+
status;
|
|
29
|
+
code;
|
|
30
|
+
details;
|
|
31
|
+
constructor(status, code, message, details) {
|
|
32
|
+
super(message);
|
|
33
|
+
this.name = "EdelApiError";
|
|
34
|
+
this.status = status;
|
|
35
|
+
this.code = code;
|
|
36
|
+
this.details = details;
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
const MUTATING_METHODS = new Set(["POST", "PUT", "PATCH", "DELETE"]);
|
|
40
|
+
const RETRYABLE_STATUSES = new Set([408, 429, 500, 502, 503, 504]);
|
|
41
|
+
export class EdelClient {
|
|
42
|
+
network;
|
|
43
|
+
baseUrl;
|
|
44
|
+
realtimeUrl;
|
|
45
|
+
token;
|
|
46
|
+
maxRetries;
|
|
47
|
+
retryBaseDelayMs;
|
|
48
|
+
fetchImpl;
|
|
49
|
+
webSocketImpl;
|
|
50
|
+
operations;
|
|
51
|
+
constructor(options = {}) {
|
|
52
|
+
this.network = options.network ?? "mainnet";
|
|
53
|
+
const defaults = NETWORK_ENDPOINTS[this.network];
|
|
54
|
+
this.baseUrl = (options.baseUrl ?? defaults.restUrl).replace(/\/$/, "");
|
|
55
|
+
this.realtimeUrl = options.realtimeUrl ?? defaults.realtimeUrl;
|
|
56
|
+
this.token = options.bearerToken ?? options.apiKey;
|
|
57
|
+
this.maxRetries = options.maxRetries ?? 3;
|
|
58
|
+
this.retryBaseDelayMs = options.retryBaseDelayMs ?? 250;
|
|
59
|
+
this.fetchImpl = options.fetchImpl ?? globalThis.fetch;
|
|
60
|
+
this.webSocketImpl = options.webSocketImpl;
|
|
61
|
+
this.operations = new EdelOperationsClient(this);
|
|
62
|
+
}
|
|
63
|
+
callOperation(operationId, params = {}) {
|
|
64
|
+
return this.operations.call(operationId, params);
|
|
65
|
+
}
|
|
66
|
+
async request(path, options = {}) {
|
|
67
|
+
const method = options.method ?? "GET";
|
|
68
|
+
const normalizedPath = path.startsWith("/") ? path : `/${path}`;
|
|
69
|
+
const queryString = buildQueryString(options.query);
|
|
70
|
+
const url = `${this.baseUrl}${normalizedPath}${queryString}`;
|
|
71
|
+
const headers = {
|
|
72
|
+
Accept: "application/json",
|
|
73
|
+
...options.headers,
|
|
74
|
+
};
|
|
75
|
+
if (this.token) {
|
|
76
|
+
headers.Authorization = `Bearer ${this.token}`;
|
|
77
|
+
}
|
|
78
|
+
let serializedBody;
|
|
79
|
+
if (options.body !== undefined) {
|
|
80
|
+
headers["Content-Type"] = "application/json";
|
|
81
|
+
serializedBody = JSON.stringify(options.body);
|
|
82
|
+
}
|
|
83
|
+
if (MUTATING_METHODS.has(method)) {
|
|
84
|
+
headers["Idempotency-Key"] = options.idempotencyKey ?? generateUuidV4();
|
|
85
|
+
}
|
|
86
|
+
let lastError;
|
|
87
|
+
for (let attempt = 0; attempt <= this.maxRetries; attempt++) {
|
|
88
|
+
try {
|
|
89
|
+
const response = await this.fetchImpl(url, {
|
|
90
|
+
method,
|
|
91
|
+
headers,
|
|
92
|
+
body: serializedBody,
|
|
93
|
+
signal: options.signal,
|
|
94
|
+
});
|
|
95
|
+
const text = await response.text();
|
|
96
|
+
const parsed = text ? safeJsonParse(text) : undefined;
|
|
97
|
+
if (response.ok) {
|
|
98
|
+
return parsed;
|
|
99
|
+
}
|
|
100
|
+
const errCode = typeof parsed === "object" && parsed !== null && "code" in parsed
|
|
101
|
+
? String(parsed.code)
|
|
102
|
+
: `http_${response.status}`;
|
|
103
|
+
const errMessage = typeof parsed === "object" && parsed !== null && "message" in parsed
|
|
104
|
+
? String(parsed.message)
|
|
105
|
+
: response.statusText || `Request failed with status ${response.status}`;
|
|
106
|
+
const apiError = new EdelApiError(response.status, errCode, errMessage, parsed);
|
|
107
|
+
if (!RETRYABLE_STATUSES.has(response.status) || attempt === this.maxRetries) {
|
|
108
|
+
throw apiError;
|
|
109
|
+
}
|
|
110
|
+
lastError = apiError;
|
|
111
|
+
}
|
|
112
|
+
catch (err) {
|
|
113
|
+
if (err instanceof EdelApiError && !RETRYABLE_STATUSES.has(err.status)) {
|
|
114
|
+
throw err;
|
|
115
|
+
}
|
|
116
|
+
if (attempt === this.maxRetries) {
|
|
117
|
+
throw err;
|
|
118
|
+
}
|
|
119
|
+
lastError = err;
|
|
120
|
+
}
|
|
121
|
+
const delay = this.retryBaseDelayMs * 2 ** attempt;
|
|
122
|
+
await new Promise((resolve) => setTimeout(resolve, delay));
|
|
123
|
+
}
|
|
124
|
+
throw lastError;
|
|
125
|
+
}
|
|
126
|
+
// ---- Typed Market Data REST Methods (CCXT v2) ----
|
|
127
|
+
getMarkets(params) {
|
|
128
|
+
const path = params?.type === "spot"
|
|
129
|
+
? "/v2/spot/markets"
|
|
130
|
+
: params?.type === "perps"
|
|
131
|
+
? "/v2/perps/markets"
|
|
132
|
+
: "/v2/markets";
|
|
133
|
+
return this.request(path);
|
|
134
|
+
}
|
|
135
|
+
getTickers(params) {
|
|
136
|
+
const path = params?.type === "spot"
|
|
137
|
+
? "/v2/spot/tickers"
|
|
138
|
+
: params?.type === "perps"
|
|
139
|
+
? "/v2/perps/tickers"
|
|
140
|
+
: "/v2/tickers";
|
|
141
|
+
return this.request(path, {
|
|
142
|
+
query: params?.symbol ? { symbol: params.symbol } : undefined,
|
|
143
|
+
});
|
|
144
|
+
}
|
|
145
|
+
getOrderBook(symbol, params) {
|
|
146
|
+
const encoded = encodeURIComponent(symbol);
|
|
147
|
+
const prefix = params?.type === "spot"
|
|
148
|
+
? "/v2/spot/markets"
|
|
149
|
+
: params?.type === "perps"
|
|
150
|
+
? "/v2/perps/markets"
|
|
151
|
+
: "/v2/markets";
|
|
152
|
+
return this.request(`${prefix}/${encoded}/book`, {
|
|
153
|
+
query: params?.limit !== undefined ? { limit: params.limit } : undefined,
|
|
154
|
+
});
|
|
155
|
+
}
|
|
156
|
+
getTrades(symbol, params) {
|
|
157
|
+
const encoded = encodeURIComponent(symbol);
|
|
158
|
+
const prefix = params?.type === "spot"
|
|
159
|
+
? "/v2/spot/markets"
|
|
160
|
+
: params?.type === "perps"
|
|
161
|
+
? "/v2/perps/markets"
|
|
162
|
+
: "/v2/markets";
|
|
163
|
+
return this.request(`${prefix}/${encoded}/trades`, {
|
|
164
|
+
query: {
|
|
165
|
+
limit: params?.limit,
|
|
166
|
+
since: params?.since,
|
|
167
|
+
},
|
|
168
|
+
});
|
|
169
|
+
}
|
|
170
|
+
getCandles(symbol, params) {
|
|
171
|
+
const encoded = encodeURIComponent(symbol);
|
|
172
|
+
const prefix = params?.type === "spot"
|
|
173
|
+
? "/v2/spot/markets"
|
|
174
|
+
: params?.type === "perps"
|
|
175
|
+
? "/v2/perps/markets"
|
|
176
|
+
: "/v2/markets";
|
|
177
|
+
return this.request(`${prefix}/${encoded}/candles`, {
|
|
178
|
+
query: {
|
|
179
|
+
timeframe: params?.timeframe,
|
|
180
|
+
limit: params?.limit,
|
|
181
|
+
since: params?.since,
|
|
182
|
+
},
|
|
183
|
+
});
|
|
184
|
+
}
|
|
185
|
+
getFundingRates() {
|
|
186
|
+
return this.request("/v2/funding-rates");
|
|
187
|
+
}
|
|
188
|
+
// ---- Typed Account & Order REST Methods (CCXT v2) ----
|
|
189
|
+
getAccount(accountId) {
|
|
190
|
+
return this.request(`/v2/accounts/${encodeURIComponent(accountId)}`);
|
|
191
|
+
}
|
|
192
|
+
getPositions(accountId) {
|
|
193
|
+
return this.request(`/v2/accounts/${encodeURIComponent(accountId)}/positions`);
|
|
194
|
+
}
|
|
195
|
+
placeOrder(body, idempotencyKey) {
|
|
196
|
+
return this.request("/v2/orders", {
|
|
197
|
+
method: "POST",
|
|
198
|
+
body,
|
|
199
|
+
idempotencyKey,
|
|
200
|
+
});
|
|
201
|
+
}
|
|
202
|
+
cancelOrder(orderId, idempotencyKey) {
|
|
203
|
+
return this.request(`/v2/orders/${encodeURIComponent(orderId)}/cancel`, {
|
|
204
|
+
method: "POST",
|
|
205
|
+
idempotencyKey,
|
|
206
|
+
});
|
|
207
|
+
}
|
|
208
|
+
// ---- Typed Swap RFQ REST Methods ----
|
|
209
|
+
getSwapPairs() {
|
|
210
|
+
return this.request("/v2/swap/pairs");
|
|
211
|
+
}
|
|
212
|
+
getSwapQuote(body, idempotencyKey) {
|
|
213
|
+
const maxSlippageBps = validateMaxSlippageBps(body.maxSlippageBps ?? body.slippageBps);
|
|
214
|
+
return this.request("/v2/swap/quotes", {
|
|
215
|
+
method: "POST",
|
|
216
|
+
body: {
|
|
217
|
+
...body,
|
|
218
|
+
maxSlippageBps,
|
|
219
|
+
},
|
|
220
|
+
idempotencyKey,
|
|
221
|
+
});
|
|
222
|
+
}
|
|
223
|
+
createSwapOrder(body, idempotencyKey) {
|
|
224
|
+
const maxSlippageBps = validateMaxSlippageBps(body.maxSlippageBps);
|
|
225
|
+
return this.request("/v2/swap/orders", {
|
|
226
|
+
method: "POST",
|
|
227
|
+
body: {
|
|
228
|
+
...body,
|
|
229
|
+
maxSlippageBps,
|
|
230
|
+
},
|
|
231
|
+
idempotencyKey,
|
|
232
|
+
});
|
|
233
|
+
}
|
|
234
|
+
getSwapOrder(orderId) {
|
|
235
|
+
return this.request(`/v2/swap/orders/${encodeURIComponent(orderId)}`);
|
|
236
|
+
}
|
|
237
|
+
submitSwapOrder(swapId, body = {}, idempotencyKey) {
|
|
238
|
+
return this.request(`/v2/swaps/orders/${encodeURIComponent(swapId)}/submit`, {
|
|
239
|
+
method: "POST",
|
|
240
|
+
body,
|
|
241
|
+
idempotencyKey,
|
|
242
|
+
});
|
|
243
|
+
}
|
|
244
|
+
getSwapEarnings(query) {
|
|
245
|
+
return this.request("/v2/swaps/earnings", {
|
|
246
|
+
query: query
|
|
247
|
+
? {
|
|
248
|
+
integratorId: query.integratorId,
|
|
249
|
+
fromEpochMs: query.fromEpochMs,
|
|
250
|
+
toEpochMs: query.toEpochMs,
|
|
251
|
+
asset: query.asset,
|
|
252
|
+
}
|
|
253
|
+
: undefined,
|
|
254
|
+
});
|
|
255
|
+
}
|
|
256
|
+
realtime(options = {}) {
|
|
257
|
+
return new EdelRealtimeClient({
|
|
258
|
+
webSocketImpl: this.webSocketImpl,
|
|
259
|
+
...options,
|
|
260
|
+
url: this.realtimeUrl,
|
|
261
|
+
});
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
export class EdelRealtimeClient {
|
|
265
|
+
url;
|
|
266
|
+
ticket;
|
|
267
|
+
heartbeatIntervalMs;
|
|
268
|
+
reconnectDelayMs;
|
|
269
|
+
maxReconnectDelayMs;
|
|
270
|
+
webSocketImpl;
|
|
271
|
+
ws;
|
|
272
|
+
heartbeatTimer;
|
|
273
|
+
reconnectTimer;
|
|
274
|
+
reconnectAttempts = 0;
|
|
275
|
+
closed = false;
|
|
276
|
+
activeSubscriptions = new Map();
|
|
277
|
+
listeners = new Set();
|
|
278
|
+
openListeners = new Set();
|
|
279
|
+
closeListeners = new Set();
|
|
280
|
+
channels;
|
|
281
|
+
constructor(options) {
|
|
282
|
+
this.url = options.url;
|
|
283
|
+
this.ticket = options.ticket;
|
|
284
|
+
this.heartbeatIntervalMs = options.heartbeatIntervalMs ?? 20_000;
|
|
285
|
+
this.reconnectDelayMs = options.reconnectDelayMs ?? 1_500;
|
|
286
|
+
this.maxReconnectDelayMs = options.maxReconnectDelayMs ?? 30_000;
|
|
287
|
+
this.webSocketImpl = options.webSocketImpl ?? globalThis.WebSocket;
|
|
288
|
+
this.channels = new EdelRealtimeChannels(this);
|
|
289
|
+
}
|
|
290
|
+
get isConnected() {
|
|
291
|
+
return this.ws !== undefined && this.ws.readyState === this.webSocketImpl.OPEN;
|
|
292
|
+
}
|
|
293
|
+
connect() {
|
|
294
|
+
this.closed = false;
|
|
295
|
+
if (this.reconnectTimer) {
|
|
296
|
+
clearTimeout(this.reconnectTimer);
|
|
297
|
+
this.reconnectTimer = undefined;
|
|
298
|
+
}
|
|
299
|
+
const target = this.ticket ? `${this.url}?ticket=${encodeURIComponent(this.ticket)}` : this.url;
|
|
300
|
+
const ws = new this.webSocketImpl(target);
|
|
301
|
+
this.ws = ws;
|
|
302
|
+
ws.addEventListener("open", () => {
|
|
303
|
+
this.reconnectAttempts = 0;
|
|
304
|
+
this.startHeartbeat();
|
|
305
|
+
for (const sub of this.activeSubscriptions.values()) {
|
|
306
|
+
this.sendSubscribeFrame(sub);
|
|
307
|
+
}
|
|
308
|
+
for (const listener of this.openListeners) {
|
|
309
|
+
listener();
|
|
310
|
+
}
|
|
311
|
+
});
|
|
312
|
+
ws.addEventListener("message", (event) => {
|
|
313
|
+
const data = event.data;
|
|
314
|
+
const payload = typeof data === "string" ? safeJsonParse(data) : data;
|
|
315
|
+
for (const listener of this.listeners) {
|
|
316
|
+
listener(payload);
|
|
317
|
+
}
|
|
318
|
+
});
|
|
319
|
+
ws.addEventListener("close", () => {
|
|
320
|
+
this.stopHeartbeat();
|
|
321
|
+
for (const listener of this.closeListeners) {
|
|
322
|
+
listener();
|
|
323
|
+
}
|
|
324
|
+
if (!this.closed) {
|
|
325
|
+
const delay = Math.min(this.reconnectDelayMs * 2 ** this.reconnectAttempts, this.maxReconnectDelayMs);
|
|
326
|
+
this.reconnectAttempts += 1;
|
|
327
|
+
this.reconnectTimer = setTimeout(() => this.connect(), delay);
|
|
328
|
+
}
|
|
329
|
+
});
|
|
330
|
+
}
|
|
331
|
+
subscribe(sub) {
|
|
332
|
+
const key = subscriptionKey(sub);
|
|
333
|
+
this.activeSubscriptions.set(key, sub);
|
|
334
|
+
if (this.isConnected) {
|
|
335
|
+
this.sendSubscribeFrame(sub);
|
|
336
|
+
}
|
|
337
|
+
return () => {
|
|
338
|
+
this.unsubscribe(sub);
|
|
339
|
+
};
|
|
340
|
+
}
|
|
341
|
+
unsubscribe(sub) {
|
|
342
|
+
const key = subscriptionKey(sub);
|
|
343
|
+
this.activeSubscriptions.delete(key);
|
|
344
|
+
if (this.isConnected && this.ws) {
|
|
345
|
+
this.ws.send(JSON.stringify({
|
|
346
|
+
type: "unsubscribe",
|
|
347
|
+
version: "realtime-contract/v1",
|
|
348
|
+
request_id: generateUuidV4(),
|
|
349
|
+
channel: sub.channel,
|
|
350
|
+
market_id: sub.marketId,
|
|
351
|
+
account_id: sub.accountId,
|
|
352
|
+
order_id: sub.orderId,
|
|
353
|
+
}));
|
|
354
|
+
}
|
|
355
|
+
}
|
|
356
|
+
subscribeChannel(channel, options = {}) {
|
|
357
|
+
const unsubChannel = this.subscribe({
|
|
358
|
+
channel,
|
|
359
|
+
marketId: options.marketId,
|
|
360
|
+
accountId: options.accountId,
|
|
361
|
+
orderId: options.orderId,
|
|
362
|
+
});
|
|
363
|
+
if (!options.onMessage) {
|
|
364
|
+
return unsubChannel;
|
|
365
|
+
}
|
|
366
|
+
const onMessage = options.onMessage;
|
|
367
|
+
const unsubListener = this.onMessage((frame) => {
|
|
368
|
+
if (typeof frame === "object" && frame !== null) {
|
|
369
|
+
const record = frame;
|
|
370
|
+
if (record.channel === undefined || record.channel === channel) {
|
|
371
|
+
onMessage(frame);
|
|
372
|
+
}
|
|
373
|
+
}
|
|
374
|
+
});
|
|
375
|
+
return () => {
|
|
376
|
+
unsubListener();
|
|
377
|
+
unsubChannel();
|
|
378
|
+
};
|
|
379
|
+
}
|
|
380
|
+
subscribeSwapOrder(orderId, onStatus) {
|
|
381
|
+
const unsubChannel = this.subscribe({
|
|
382
|
+
channel: "swap.order",
|
|
383
|
+
orderId,
|
|
384
|
+
});
|
|
385
|
+
const unsubListener = this.onMessage((frame) => {
|
|
386
|
+
if (typeof frame !== "object" || frame === null)
|
|
387
|
+
return;
|
|
388
|
+
const record = frame;
|
|
389
|
+
const payload = typeof record.payload === "object" && record.payload !== null
|
|
390
|
+
? record.payload
|
|
391
|
+
: record;
|
|
392
|
+
if (payload.orderId === orderId && typeof payload.status === "string") {
|
|
393
|
+
onStatus({
|
|
394
|
+
orderId,
|
|
395
|
+
status: payload.status,
|
|
396
|
+
txHash: typeof payload.txHash === "string" ? payload.txHash : undefined,
|
|
397
|
+
settlementTxHash: typeof payload.settlementTxHash === "string" ? payload.settlementTxHash : undefined,
|
|
398
|
+
updatedAtEpochMs: typeof payload.updatedAtEpochMs === "number" ? payload.updatedAtEpochMs : Date.now(),
|
|
399
|
+
});
|
|
400
|
+
}
|
|
401
|
+
});
|
|
402
|
+
return () => {
|
|
403
|
+
unsubListener();
|
|
404
|
+
unsubChannel();
|
|
405
|
+
};
|
|
406
|
+
}
|
|
407
|
+
onMessage(listener) {
|
|
408
|
+
this.listeners.add(listener);
|
|
409
|
+
return () => this.listeners.delete(listener);
|
|
410
|
+
}
|
|
411
|
+
onOpen(listener) {
|
|
412
|
+
this.openListeners.add(listener);
|
|
413
|
+
return () => this.openListeners.delete(listener);
|
|
414
|
+
}
|
|
415
|
+
onClose(listener) {
|
|
416
|
+
this.closeListeners.add(listener);
|
|
417
|
+
return () => this.closeListeners.delete(listener);
|
|
418
|
+
}
|
|
419
|
+
close() {
|
|
420
|
+
this.closed = true;
|
|
421
|
+
this.stopHeartbeat();
|
|
422
|
+
if (this.reconnectTimer) {
|
|
423
|
+
clearTimeout(this.reconnectTimer);
|
|
424
|
+
this.reconnectTimer = undefined;
|
|
425
|
+
}
|
|
426
|
+
this.ws?.close();
|
|
427
|
+
}
|
|
428
|
+
sendSubscribeFrame(sub) {
|
|
429
|
+
if (!this.ws || this.ws.readyState !== this.webSocketImpl.OPEN)
|
|
430
|
+
return;
|
|
431
|
+
this.ws.send(JSON.stringify({
|
|
432
|
+
type: "subscribe",
|
|
433
|
+
version: "realtime-contract/v1",
|
|
434
|
+
request_id: generateUuidV4(),
|
|
435
|
+
channel: sub.channel,
|
|
436
|
+
market_id: sub.marketId,
|
|
437
|
+
account_id: sub.accountId,
|
|
438
|
+
order_id: sub.orderId,
|
|
439
|
+
}));
|
|
440
|
+
}
|
|
441
|
+
startHeartbeat() {
|
|
442
|
+
this.stopHeartbeat();
|
|
443
|
+
this.heartbeatTimer = setInterval(() => {
|
|
444
|
+
if (this.ws?.readyState === this.webSocketImpl.OPEN) {
|
|
445
|
+
this.ws.send(JSON.stringify({ type: "ping", ts: Date.now() }));
|
|
446
|
+
}
|
|
447
|
+
}, this.heartbeatIntervalMs);
|
|
448
|
+
}
|
|
449
|
+
stopHeartbeat() {
|
|
450
|
+
if (this.heartbeatTimer) {
|
|
451
|
+
clearInterval(this.heartbeatTimer);
|
|
452
|
+
this.heartbeatTimer = undefined;
|
|
453
|
+
}
|
|
454
|
+
}
|
|
455
|
+
}
|
|
456
|
+
function subscriptionKey(sub) {
|
|
457
|
+
return `${sub.channel}|${sub.marketId ?? ""}|${sub.accountId ?? ""}|${sub.orderId ?? ""}`;
|
|
458
|
+
}
|
|
459
|
+
function buildQueryString(query) {
|
|
460
|
+
if (!query)
|
|
461
|
+
return "";
|
|
462
|
+
const params = new URLSearchParams();
|
|
463
|
+
for (const [k, v] of Object.entries(query)) {
|
|
464
|
+
if (v !== undefined) {
|
|
465
|
+
params.set(k, String(v));
|
|
466
|
+
}
|
|
467
|
+
}
|
|
468
|
+
const encoded = params.toString();
|
|
469
|
+
return encoded ? `?${encoded}` : "";
|
|
470
|
+
}
|
|
471
|
+
function safeJsonParse(raw) {
|
|
472
|
+
try {
|
|
473
|
+
return JSON.parse(raw);
|
|
474
|
+
}
|
|
475
|
+
catch {
|
|
476
|
+
return raw;
|
|
477
|
+
}
|
|
478
|
+
}
|
|
479
|
+
/**
|
|
480
|
+
* Generate an RFC 4122 v4 UUID safely across secure HTTPS contexts,
|
|
481
|
+
* non-HTTPS HTTP origins (such as LAN/Tailscale previews), and embedded WebViews
|
|
482
|
+
* where `crypto.randomUUID` may be undefined.
|
|
483
|
+
*/
|
|
484
|
+
export function generateUuidV4() {
|
|
485
|
+
const cryptoObj = globalThis.crypto;
|
|
486
|
+
if (typeof cryptoObj?.randomUUID === "function") {
|
|
487
|
+
return cryptoObj.randomUUID();
|
|
488
|
+
}
|
|
489
|
+
if (typeof cryptoObj?.getRandomValues === "function") {
|
|
490
|
+
const bytes = new Uint8Array(16);
|
|
491
|
+
cryptoObj.getRandomValues(bytes);
|
|
492
|
+
bytes[6] = ((bytes[6] ?? 0) & 0x0f) | 0x40;
|
|
493
|
+
bytes[8] = ((bytes[8] ?? 0) & 0x3f) | 0x80;
|
|
494
|
+
const hex = Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
|
|
495
|
+
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20, 32)}`;
|
|
496
|
+
}
|
|
497
|
+
const ts = Date.now().toString(16).padStart(12, "0");
|
|
498
|
+
const randHex = () => Math.floor(Math.random() * 0x10000)
|
|
499
|
+
.toString(16)
|
|
500
|
+
.padStart(4, "0");
|
|
501
|
+
return `${ts.slice(0, 8)}-${ts.slice(8, 12)}-4${randHex().slice(1)}-${(8 + Math.floor(Math.random() * 4)).toString(16)}${randHex().slice(1)}-${randHex()}${randHex()}${randHex()}`;
|
|
502
|
+
}
|