lcx-liberty-sdk 1.0.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/README.md +171 -0
- package/dist/constants.d.ts +28 -0
- package/dist/constants.js +28 -0
- package/dist/errors.d.ts +27 -0
- package/dist/errors.js +51 -0
- package/dist/index.d.ts +31 -0
- package/dist/index.js +84 -0
- package/dist/resources/account.d.ts +48 -0
- package/dist/resources/account.js +30 -0
- package/dist/resources/crosschain.d.ts +36 -0
- package/dist/resources/crosschain.js +59 -0
- package/dist/resources/prices.d.ts +78 -0
- package/dist/resources/prices.js +52 -0
- package/dist/resources/swap.d.ts +76 -0
- package/dist/resources/swap.js +61 -0
- package/dist/resources/tokens.d.ts +44 -0
- package/dist/resources/tokens.js +29 -0
- package/dist/transport.d.ts +10 -0
- package/dist/transport.js +107 -0
- package/dist/types.d.ts +349 -0
- package/dist/types.js +7 -0
- package/package.json +51 -0
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
/** USD pricing: one token, many tokens, or one token on a past day. */
|
|
2
|
+
import { LibertyError } from "../errors.js";
|
|
3
|
+
/** The server refuses more than this per call. */
|
|
4
|
+
export const MAX_TOKENS_PER_BATCH = 250;
|
|
5
|
+
export class PricesResource {
|
|
6
|
+
t;
|
|
7
|
+
constructor(t) {
|
|
8
|
+
this.t = t;
|
|
9
|
+
}
|
|
10
|
+
/**
|
|
11
|
+
* USD price from real pool depth, not a mid-market feed.
|
|
12
|
+
*
|
|
13
|
+
* Null when nobody can price the token — never 0, which would read as
|
|
14
|
+
* "worthless". Guard for null before doing arithmetic. (Keyed calls answer
|
|
15
|
+
* from our own index only; the anonymous tier may also serve a
|
|
16
|
+
* CoinGecko-licensed gap-fill figure, labeled `source: "external"` on the
|
|
17
|
+
* wire, which requires GeckoTerminal attribution if rendered and may not be
|
|
18
|
+
* redistributed.)
|
|
19
|
+
*/
|
|
20
|
+
async get(params) {
|
|
21
|
+
const d = await this.t.request("GET", "/v1/price", undefined, params);
|
|
22
|
+
return d.usd;
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* Many tokens in one round trip. Prefer this over looping `get()`.
|
|
26
|
+
*
|
|
27
|
+
* Pass `decimals` positionally alongside `tokens` when you know them: without
|
|
28
|
+
* it the server falls back to its registry and then to 18, and a wrong guess
|
|
29
|
+
* is wrong by a factor of 10^(18 - decimals).
|
|
30
|
+
*/
|
|
31
|
+
// `async` so the guard below REJECTS rather than throwing synchronously. A
|
|
32
|
+
// method typed `Promise<T>` that throws before returning one blows past
|
|
33
|
+
// `.catch()` and lands as an uncaught exception, which is a nasty way to
|
|
34
|
+
// learn you sent 251 tokens.
|
|
35
|
+
async batch(params) {
|
|
36
|
+
if (params.tokens.length > MAX_TOKENS_PER_BATCH) {
|
|
37
|
+
// Refused here rather than by the server, so the caller sees the limit
|
|
38
|
+
// instead of a `too_many_tokens` after a round trip.
|
|
39
|
+
throw new LibertyError("bad_request", `At most ${MAX_TOKENS_PER_BATCH} tokens per batch; got ${params.tokens.length}`, 400);
|
|
40
|
+
}
|
|
41
|
+
return this.t.request("POST", "/v1/prices", params);
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* The close for one token on one past day.
|
|
45
|
+
*
|
|
46
|
+
* `day` is `yyyy-mm-dd` and is required — there is no range form. Ask for the
|
|
47
|
+
* days you need.
|
|
48
|
+
*/
|
|
49
|
+
history(params) {
|
|
50
|
+
return this.t.request("GET", "/v1/price/history", undefined, params);
|
|
51
|
+
}
|
|
52
|
+
}
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
import type { Transport } from "../transport.js";
|
|
2
|
+
import type { Allowance, PermitTypedData, Quote, QuoteParams, SwapParams, SwapResult, Transaction } from "../types.js";
|
|
3
|
+
/** What `/v1/submit` answers with once the transaction is away. */
|
|
4
|
+
export interface SubmitResult {
|
|
5
|
+
/** The hash the caller computed — the raw bytes are forwarded unchanged. */
|
|
6
|
+
txHash: string;
|
|
7
|
+
/** Which route it took: `titan` is the private builder path. */
|
|
8
|
+
path: string;
|
|
9
|
+
/** Seconds until an unincluded transaction is re-broadcast publicly. */
|
|
10
|
+
fallbackAfterSecs: number;
|
|
11
|
+
note?: string;
|
|
12
|
+
}
|
|
13
|
+
export declare class SwapResource {
|
|
14
|
+
private readonly t;
|
|
15
|
+
constructor(t: Transport);
|
|
16
|
+
/**
|
|
17
|
+
* Best route and expected output. Read-only — nothing is executed.
|
|
18
|
+
*
|
|
19
|
+
* Use this when showing a price before the user commits. When you already know
|
|
20
|
+
* they want to execute, `execute()` does both in one round trip.
|
|
21
|
+
*/
|
|
22
|
+
quote(params: QuoteParams): Promise<{
|
|
23
|
+
quote: Quote;
|
|
24
|
+
}>;
|
|
25
|
+
/** Quote AND signable calldata in one call. */
|
|
26
|
+
execute(params: SwapParams): Promise<SwapResult>;
|
|
27
|
+
/**
|
|
28
|
+
* Calldata for a quote you already hold.
|
|
29
|
+
*
|
|
30
|
+
* The floor is derived from the quote the user was SHOWN, not from a fresh
|
|
31
|
+
* price — which is the point of passing a `quoteId` rather than re-quoting.
|
|
32
|
+
*/
|
|
33
|
+
build(params: {
|
|
34
|
+
quoteId: string;
|
|
35
|
+
recipient: string;
|
|
36
|
+
slippageBps?: number;
|
|
37
|
+
deadlineSecs?: number;
|
|
38
|
+
}): Promise<{
|
|
39
|
+
swap: Transaction;
|
|
40
|
+
} & Record<string, unknown>>;
|
|
41
|
+
/** Whether `taker` must approve before swapping, and the exact spender. */
|
|
42
|
+
allowance(params: {
|
|
43
|
+
chainId: number;
|
|
44
|
+
token: string;
|
|
45
|
+
taker: string;
|
|
46
|
+
/** Raw units — the quote's `input.amount`. Required: the API answers
|
|
47
|
+
* `bad_request` without it. `"0"` asks whether any allowance exists. */
|
|
48
|
+
amount: string;
|
|
49
|
+
}): Promise<Allowance>;
|
|
50
|
+
/**
|
|
51
|
+
* EIP-2612 typed data for a gasless approval.
|
|
52
|
+
*
|
|
53
|
+
* Throws `PERMIT_UNSUPPORTED` for tokens that do not implement 2612 — catch it
|
|
54
|
+
* and fall back to Permit2 or a one-time approval.
|
|
55
|
+
*/
|
|
56
|
+
permit(params: {
|
|
57
|
+
chainId: number;
|
|
58
|
+
token: string;
|
|
59
|
+
owner: string;
|
|
60
|
+
amount?: string;
|
|
61
|
+
deadlineSeconds?: number;
|
|
62
|
+
}): Promise<PermitTypedData>;
|
|
63
|
+
/**
|
|
64
|
+
* Broadcast a transaction the wallet already signed.
|
|
65
|
+
*
|
|
66
|
+
* Optional: a wallet that can send its own transaction should. This exists for
|
|
67
|
+
* the case where it cannot, and for the private path — the signed bytes go to
|
|
68
|
+
* a block builder first, so a maker's price update can be sequenced ahead of
|
|
69
|
+
* the swap instead of behind it. The bytes are forwarded unchanged, so the
|
|
70
|
+
* hash the caller computed is the hash that lands, on either path.
|
|
71
|
+
*/
|
|
72
|
+
submit(params: {
|
|
73
|
+
chainId: number;
|
|
74
|
+
rawTransaction: string;
|
|
75
|
+
}): Promise<SubmitResult>;
|
|
76
|
+
}
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
/** Same-chain swapping: price it, build it, sign it, send it. */
|
|
2
|
+
import { LibertyError } from "../errors.js";
|
|
3
|
+
export class SwapResource {
|
|
4
|
+
t;
|
|
5
|
+
constructor(t) {
|
|
6
|
+
this.t = t;
|
|
7
|
+
}
|
|
8
|
+
/**
|
|
9
|
+
* Best route and expected output. Read-only — nothing is executed.
|
|
10
|
+
*
|
|
11
|
+
* Use this when showing a price before the user commits. When you already know
|
|
12
|
+
* they want to execute, `execute()` does both in one round trip.
|
|
13
|
+
*/
|
|
14
|
+
quote(params) {
|
|
15
|
+
return this.t.request("POST", "/v1/quote", params);
|
|
16
|
+
}
|
|
17
|
+
/** Quote AND signable calldata in one call. */
|
|
18
|
+
execute(params) {
|
|
19
|
+
return this.t.request("POST", "/v1/swap", params);
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* Calldata for a quote you already hold.
|
|
23
|
+
*
|
|
24
|
+
* The floor is derived from the quote the user was SHOWN, not from a fresh
|
|
25
|
+
* price — which is the point of passing a `quoteId` rather than re-quoting.
|
|
26
|
+
*/
|
|
27
|
+
build(params) {
|
|
28
|
+
return this.t.request("POST", "/v1/build", params);
|
|
29
|
+
}
|
|
30
|
+
/** Whether `taker` must approve before swapping, and the exact spender. */
|
|
31
|
+
allowance(params) {
|
|
32
|
+
return this.t.request("GET", "/v1/allowance", undefined, params);
|
|
33
|
+
}
|
|
34
|
+
/**
|
|
35
|
+
* EIP-2612 typed data for a gasless approval.
|
|
36
|
+
*
|
|
37
|
+
* Throws `PERMIT_UNSUPPORTED` for tokens that do not implement 2612 — catch it
|
|
38
|
+
* and fall back to Permit2 or a one-time approval.
|
|
39
|
+
*/
|
|
40
|
+
permit(params) {
|
|
41
|
+
return this.t.request("POST", "/v1/permit", params);
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* Broadcast a transaction the wallet already signed.
|
|
45
|
+
*
|
|
46
|
+
* Optional: a wallet that can send its own transaction should. This exists for
|
|
47
|
+
* the case where it cannot, and for the private path — the signed bytes go to
|
|
48
|
+
* a block builder first, so a maker's price update can be sequenced ahead of
|
|
49
|
+
* the swap instead of behind it. The bytes are forwarded unchanged, so the
|
|
50
|
+
* hash the caller computed is the hash that lands, on either path.
|
|
51
|
+
*/
|
|
52
|
+
// `async` for the same reason as `prices.batch`: a `Promise`-typed method must
|
|
53
|
+
// reject, not throw, or the guard escapes the caller's `.catch()`.
|
|
54
|
+
async submit(params) {
|
|
55
|
+
if (!params.rawTransaction.startsWith("0x")) {
|
|
56
|
+
// Caught here rather than spending a round trip to be told the same thing.
|
|
57
|
+
throw new LibertyError("bad_request", "rawTransaction must be 0x-prefixed hex", 400);
|
|
58
|
+
}
|
|
59
|
+
return this.t.request("POST", "/v1/submit", params);
|
|
60
|
+
}
|
|
61
|
+
}
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
/** The token registry: what we index, and what we vouch for. */
|
|
2
|
+
import type { Transport } from "../transport.js";
|
|
3
|
+
import type { Token } from "../types.js";
|
|
4
|
+
export declare class TokensResource {
|
|
5
|
+
private readonly t;
|
|
6
|
+
constructor(t: Transport);
|
|
7
|
+
/**
|
|
8
|
+
* Tokens on a chain, ranked by pool count. Search by symbol, name or address.
|
|
9
|
+
*
|
|
10
|
+
* ⚠️ A SYMBOL IS NOT AN IDENTIFIER. Several distinct contracts ship the same
|
|
11
|
+
* ticker on the same chain, so resolve by address wherever a user's funds are
|
|
12
|
+
* involved. `listed` marks the contract we vouch for; the rest are merely
|
|
13
|
+
* indexed, and being indexed is not an endorsement.
|
|
14
|
+
*/
|
|
15
|
+
list(params: {
|
|
16
|
+
chainId: number;
|
|
17
|
+
search?: string;
|
|
18
|
+
limit?: number;
|
|
19
|
+
offset?: number;
|
|
20
|
+
}): Promise<Token[]>;
|
|
21
|
+
/**
|
|
22
|
+
* One page, with the cursor to ask for the next.
|
|
23
|
+
*
|
|
24
|
+
* `list()` hands back the rows and drops the paging fields, which is what most
|
|
25
|
+
* callers want. Use this when you intend to walk past the first page: the
|
|
26
|
+
* server caps `limit`, so a caller who assumes one call is the whole registry
|
|
27
|
+
* silently sees a prefix of it.
|
|
28
|
+
*/
|
|
29
|
+
page(params: {
|
|
30
|
+
chainId: number;
|
|
31
|
+
search?: string;
|
|
32
|
+
limit?: number;
|
|
33
|
+
offset?: number;
|
|
34
|
+
}): Promise<{
|
|
35
|
+
tokens: Token[];
|
|
36
|
+
offset: number;
|
|
37
|
+
limit: number;
|
|
38
|
+
/** What the server actually served, if it clamped `limit`. */
|
|
39
|
+
requestedLimit: number | null;
|
|
40
|
+
hasMore: boolean;
|
|
41
|
+
/** Pass back as `offset`; null at the end. */
|
|
42
|
+
nextOffset: number | null;
|
|
43
|
+
}>;
|
|
44
|
+
}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
export class TokensResource {
|
|
2
|
+
t;
|
|
3
|
+
constructor(t) {
|
|
4
|
+
this.t = t;
|
|
5
|
+
}
|
|
6
|
+
/**
|
|
7
|
+
* Tokens on a chain, ranked by pool count. Search by symbol, name or address.
|
|
8
|
+
*
|
|
9
|
+
* ⚠️ A SYMBOL IS NOT AN IDENTIFIER. Several distinct contracts ship the same
|
|
10
|
+
* ticker on the same chain, so resolve by address wherever a user's funds are
|
|
11
|
+
* involved. `listed` marks the contract we vouch for; the rest are merely
|
|
12
|
+
* indexed, and being indexed is not an endorsement.
|
|
13
|
+
*/
|
|
14
|
+
async list(params) {
|
|
15
|
+
const d = await this.t.request("GET", "/v1/tokens", undefined, params);
|
|
16
|
+
return d.tokens;
|
|
17
|
+
}
|
|
18
|
+
/**
|
|
19
|
+
* One page, with the cursor to ask for the next.
|
|
20
|
+
*
|
|
21
|
+
* `list()` hands back the rows and drops the paging fields, which is what most
|
|
22
|
+
* callers want. Use this when you intend to walk past the first page: the
|
|
23
|
+
* server caps `limit`, so a caller who assumes one call is the whole registry
|
|
24
|
+
* silently sees a prefix of it.
|
|
25
|
+
*/
|
|
26
|
+
page(params) {
|
|
27
|
+
return this.t.request("GET", "/v1/tokens", undefined, params);
|
|
28
|
+
}
|
|
29
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import type { LibertyOptions } from "./types.js";
|
|
2
|
+
export declare class Transport {
|
|
3
|
+
private readonly apiKey?;
|
|
4
|
+
readonly baseUrl: string;
|
|
5
|
+
private readonly timeoutMs;
|
|
6
|
+
private readonly maxRetries;
|
|
7
|
+
private readonly fetchImpl;
|
|
8
|
+
constructor(options?: LibertyOptions);
|
|
9
|
+
request<T>(method: "GET" | "POST", path: string, body?: unknown, query?: Record<string, string | number | undefined>): Promise<T>;
|
|
10
|
+
}
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The HTTP layer every resource shares.
|
|
3
|
+
*
|
|
4
|
+
* Split out of the client so that adding a product surface is adding a file
|
|
5
|
+
* under `resources/`, not editing a class that already owns the transport.
|
|
6
|
+
* Resources receive this and call `request`; they hold no fetch logic of their
|
|
7
|
+
* own, so retry, timeout, auth and error classification are defined once.
|
|
8
|
+
*/
|
|
9
|
+
import { DEFAULT_BASE_URL, VERSION } from "./constants.js";
|
|
10
|
+
import { LibertyError } from "./errors.js";
|
|
11
|
+
export class Transport {
|
|
12
|
+
apiKey;
|
|
13
|
+
baseUrl;
|
|
14
|
+
timeoutMs;
|
|
15
|
+
maxRetries;
|
|
16
|
+
fetchImpl;
|
|
17
|
+
constructor(options = {}) {
|
|
18
|
+
this.apiKey = options.apiKey;
|
|
19
|
+
this.baseUrl = (options.baseUrl ?? DEFAULT_BASE_URL).replace(/\/+$/, "");
|
|
20
|
+
// The commercial host answers every request with 401 without a key, so a
|
|
21
|
+
// keyless client pointed at it is misconfigured before it makes a call.
|
|
22
|
+
// Caught here with a message that says where a key comes from and how to
|
|
23
|
+
// evaluate without one, rather than surfacing as a 401 on the first quote.
|
|
24
|
+
if (!this.apiKey && this.baseUrl === DEFAULT_BASE_URL) {
|
|
25
|
+
throw new LibertyError("api_key_required", "LibertyDex needs an apiKey for swap-api.lcx.com. Create a free one in the developer " +
|
|
26
|
+
"dashboard, or pass { baseUrl: PUBLIC_BASE_URL } to evaluate on the keyless public tier.", 0);
|
|
27
|
+
}
|
|
28
|
+
this.timeoutMs = options.timeoutMs ?? 20_000;
|
|
29
|
+
this.maxRetries = options.maxRetries ?? 2;
|
|
30
|
+
this.fetchImpl = options.fetch ?? globalThis.fetch;
|
|
31
|
+
if (typeof this.fetchImpl !== "function") {
|
|
32
|
+
throw new Error("No fetch available. Use Node 18+, or pass one via `new LibertyDex({ fetch })`.");
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
async request(method, path, body, query) {
|
|
36
|
+
const url = new URL(this.baseUrl + path);
|
|
37
|
+
for (const [k, v] of Object.entries(query ?? {})) {
|
|
38
|
+
if (v !== undefined)
|
|
39
|
+
url.searchParams.set(k, String(v));
|
|
40
|
+
}
|
|
41
|
+
const headers = {
|
|
42
|
+
"content-type": "application/json",
|
|
43
|
+
// Lets us see which SDK versions are in the wild, which is what makes a
|
|
44
|
+
// breaking change safe to plan.
|
|
45
|
+
"x-liberty-sdk": `ts/${VERSION}`,
|
|
46
|
+
};
|
|
47
|
+
// Header only, never a query parameter — query strings end up in access logs
|
|
48
|
+
// and browser history.
|
|
49
|
+
if (this.apiKey)
|
|
50
|
+
headers.authorization = `Bearer ${this.apiKey}`;
|
|
51
|
+
let lastError;
|
|
52
|
+
// Recorded rather than thrown from inside the try. The `catch` below has to
|
|
53
|
+
// catch LibertyError — a failed `res.json()` produces one — so a `throw`
|
|
54
|
+
// inside the try is swallowed by it and the loop keeps going. That made the
|
|
55
|
+
// classification just below dead code: every failure, including a 400 the
|
|
56
|
+
// caller can never fix, was sent maxRetries+1 times.
|
|
57
|
+
let fatal;
|
|
58
|
+
for (let attempt = 0; attempt <= this.maxRetries; attempt++) {
|
|
59
|
+
const controller = new AbortController();
|
|
60
|
+
const timer = setTimeout(() => controller.abort(), this.timeoutMs);
|
|
61
|
+
try {
|
|
62
|
+
const res = await this.fetchImpl(url.toString(), {
|
|
63
|
+
method,
|
|
64
|
+
headers,
|
|
65
|
+
body: body === undefined ? undefined : JSON.stringify(body),
|
|
66
|
+
signal: controller.signal,
|
|
67
|
+
});
|
|
68
|
+
clearTimeout(timer);
|
|
69
|
+
const payload = (await res.json().catch(() => null));
|
|
70
|
+
if (payload?.success === true)
|
|
71
|
+
return payload.data;
|
|
72
|
+
const code = payload?.code ?? `http_${res.status}`;
|
|
73
|
+
const message = payload?.message ?? `Request failed (${res.status})`;
|
|
74
|
+
const err = new LibertyError(code, message, res.status, payload);
|
|
75
|
+
// Retry only what a retry can fix. Repeating a bad request spends the
|
|
76
|
+
// caller's quota to get the same answer, so this checks the classified
|
|
77
|
+
// error rather than the status alone.
|
|
78
|
+
const retryable = !err.isClientError && !err.isNoLiquidity && (res.status >= 500 || res.status === 429);
|
|
79
|
+
if (!retryable || attempt === this.maxRetries) {
|
|
80
|
+
fatal = err;
|
|
81
|
+
break;
|
|
82
|
+
}
|
|
83
|
+
lastError = err;
|
|
84
|
+
}
|
|
85
|
+
catch (e) {
|
|
86
|
+
clearTimeout(timer);
|
|
87
|
+
if (e instanceof LibertyError) {
|
|
88
|
+
if (attempt === this.maxRetries)
|
|
89
|
+
throw e;
|
|
90
|
+
lastError = e;
|
|
91
|
+
}
|
|
92
|
+
else {
|
|
93
|
+
// Network failure or timeout.
|
|
94
|
+
if (attempt === this.maxRetries) {
|
|
95
|
+
throw new LibertyError("network_error", e instanceof Error ? e.message : "Network request failed", 0, e);
|
|
96
|
+
}
|
|
97
|
+
lastError = e;
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
// Exponential backoff with jitter. Without jitter, every client that
|
|
101
|
+
// tripped the same limit retries in lockstep and trips it again.
|
|
102
|
+
const base = 250 * 2 ** attempt;
|
|
103
|
+
await new Promise((r) => setTimeout(r, base + Math.random() * base));
|
|
104
|
+
}
|
|
105
|
+
throw fatal ?? lastError;
|
|
106
|
+
}
|
|
107
|
+
}
|