@recta/client 0.1.13 → 0.1.14
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 +9 -1
- package/dist/client.d.ts +3 -3
- package/dist/client.js +13 -4
- package/dist/constants.d.ts +2 -2
- package/dist/constants.js +1 -1
- package/dist/index.d.ts +1 -0
- package/dist/index.js +1 -0
- package/dist/names.d.ts +111 -0
- package/dist/names.js +516 -0
- package/dist/preflight.d.ts +10 -9
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -97,7 +97,15 @@ const bridgeTool = withPreflightTool(myBridgeTool, (input) =>
|
|
|
97
97
|
|
|
98
98
|
`preflight(transfer)` makes one check directly; `transferFromChainTokens` and `lifiTransfer` turn chain ids, token
|
|
99
99
|
addresses and atomic amounts into Recta's network and asset keys. Requests carry `recta-client/<version> (preflight)`
|
|
100
|
-
and nothing else about you.
|
|
100
|
+
and nothing else about you. 20 free preflight checks a day per IP address.
|
|
101
|
+
|
|
102
|
+
## Network, asset and route names
|
|
103
|
+
|
|
104
|
+
`RECTA_NETWORK_KEYS`, `RECTA_ASSET_KEYS` and `RECTA_PROVIDER_KEYS` list Recta's keys, and the types `RectaNetwork`,
|
|
105
|
+
`RectaAsset` and `RectaProvider` let your editor offer them. Common names are read as those keys before anything is
|
|
106
|
+
signed: any case, `"Ethereum Mainnet"`, `"BSC"`, `"Arbitrum One"`, a chain ID such as `8453`, `"eip155:8453"`,
|
|
107
|
+
`"Tether"`, `"LI.FI"` (`networkKeyOf`, `assetKeyOf`, `providerKeyOf`, `readTransferNames`). A misspelt name is not
|
|
108
|
+
guessed before a signature; `preflight` sends it as written and the service reads it and says what it understood.
|
|
101
109
|
|
|
102
110
|
## Which route to declare
|
|
103
111
|
|
package/dist/client.d.ts
CHANGED
|
@@ -63,7 +63,7 @@ export type FeeOutcome = {
|
|
|
63
63
|
* `checkExecutionArtifact`); they cannot be turned off.
|
|
64
64
|
*/
|
|
65
65
|
export declare function createRectaClient(options: RectaClientOptions): {
|
|
66
|
-
evaluate: (
|
|
66
|
+
evaluate: (given: EvaluationRequestView & Record<string, unknown>, opts?: {
|
|
67
67
|
readonly idempotencyKey?: string;
|
|
68
68
|
}) => Promise<Record<string, unknown>>;
|
|
69
69
|
authorizeFee: (resultId: string, opts?: {
|
|
@@ -73,8 +73,8 @@ export declare function createRectaClient(options: RectaClientOptions): {
|
|
|
73
73
|
readonly fee: FeeOutcome;
|
|
74
74
|
readonly artifact: unknown;
|
|
75
75
|
}>;
|
|
76
|
-
check: (resultId: string, artifact: unknown,
|
|
77
|
-
execute: (resultId: string, artifact: unknown,
|
|
76
|
+
check: (resultId: string, artifact: unknown, given: EvaluationRequestView) => Promise<CheckedArtifact>;
|
|
77
|
+
execute: (resultId: string, artifact: unknown, given: EvaluationRequestView) => Promise<{
|
|
78
78
|
readonly approvalTxHash?: Hex;
|
|
79
79
|
readonly originTxHash: Hex;
|
|
80
80
|
}>;
|
package/dist/client.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { keccak256 } from "viem";
|
|
2
|
+
import { preflightNormalizedOf } from "./names.js";
|
|
2
3
|
import { checkExecutionArtifact } from "./artifact.js";
|
|
3
4
|
import { FEE_CHAIN_ID, ISSUED_AT_HEADER, PATHS, RECTA_ORIGIN, SIGNATURE_HEADER, SIGNED_REQUEST_PREFIX, SIGNER_CHAIN_HEADER, SIGNER_HEADER, SMART_ACCOUNT_SIGNED_REQUEST_PREFIX, USER_AGENT } from "./constants.js";
|
|
4
5
|
import { RectaCheckError, RectaDebtError, RectaHttpError, RectaSendUnknownError } from "./errors.js";
|
|
@@ -141,7 +142,9 @@ export function createRectaClient(options) {
|
|
|
141
142
|
policyChecked = true;
|
|
142
143
|
}
|
|
143
144
|
/** Step 1: a durable decision (free). Throws RectaDebtError when the sender owes a fee first. */
|
|
144
|
-
async function evaluate(
|
|
145
|
+
async function evaluate(given, opts = {}) {
|
|
146
|
+
// BIT-OPS-207: names read as Recta reads them («Base Mainnet», «usdc», «LI.FI») before the body is signed.
|
|
147
|
+
const request = canonicalRequest(given);
|
|
145
148
|
if (typeof request.sender !== "string" || request.sender.toLowerCase() !== payer)
|
|
146
149
|
throw new RectaCheckError("sender", "the request's sender must be the signer");
|
|
147
150
|
// Recta accepts a smart account on Base only (its address proves one account on one chain).
|
|
@@ -167,7 +170,7 @@ export function createRectaClient(options) {
|
|
|
167
170
|
async function authorizeFee(resultId, opts = {}) {
|
|
168
171
|
const id = resultIdOf(resultId);
|
|
169
172
|
const artifactPath = `${PATHS.evaluations}/${id}/execution-artifact`;
|
|
170
|
-
const reserve = opts.request === undefined ? 0n : routeReserveOf(opts.request);
|
|
173
|
+
const reserve = opts.request === undefined ? 0n : routeReserveOf(canonicalRequest(opts.request));
|
|
171
174
|
for (let attempt = 0; attempt < 2; attempt += 1) {
|
|
172
175
|
const a = await call("GET", artifactPath);
|
|
173
176
|
if (a.status === 200) {
|
|
@@ -220,13 +223,15 @@ export function createRectaClient(options) {
|
|
|
220
223
|
throw new RectaHttpError(409, { reason_code: "OFFER_STALE" });
|
|
221
224
|
}
|
|
222
225
|
/** Checks the artifact against the request and the package's pinned routes; nothing is sent. */
|
|
223
|
-
async function check(resultId, artifact,
|
|
226
|
+
async function check(resultId, artifact, given) {
|
|
227
|
+
const request = canonicalRequest(given);
|
|
224
228
|
await walletPolicy();
|
|
225
229
|
return checkExecutionArtifact(artifact, { resultId: resultIdOf(resultId), request, limits: { signer: payer, nowUnix: nowUnix(), maxNativeValueWei: limits.maxNativeValueWei, minOutputBps: limits.minOutputBps } });
|
|
226
230
|
}
|
|
227
231
|
/** Step 3: checks, then sends the transactions in order: each mined successfully before the next, or, with a signer
|
|
228
232
|
* that can (`sendInSequence`), all of them back to back and then awaited (`executeInSequence`). */
|
|
229
|
-
async function execute(resultId, artifact,
|
|
233
|
+
async function execute(resultId, artifact, given) {
|
|
234
|
+
const request = canonicalRequest(given);
|
|
230
235
|
// The last moment before anything is sent: with a fee authorized for this decision, the payer must still hold it
|
|
231
236
|
// in USDC on Base (plus the transfer itself when it starts from Base USDC) with the Permit2 allowance for it.
|
|
232
237
|
const fee = feeAmounts.get(resultIdOf(resultId));
|
|
@@ -382,3 +387,7 @@ export function createRectaClient(options) {
|
|
|
382
387
|
}
|
|
383
388
|
return { evaluate, authorizeFee, check, execute, report, ledger, payDebt, run, walletPolicy, feeFunds, feeApproval };
|
|
384
389
|
}
|
|
390
|
+
/** BIT-OPS-207: a request with its names, amount and classes in Recta's canonical form (the same reading as the service). */
|
|
391
|
+
function canonicalRequest(request) {
|
|
392
|
+
return preflightNormalizedOf(request).body;
|
|
393
|
+
}
|
package/dist/constants.d.ts
CHANGED
|
@@ -7,9 +7,9 @@
|
|
|
7
7
|
*/
|
|
8
8
|
export declare const RECTA_ORIGIN = "https://api.recta.build";
|
|
9
9
|
/** This package's version (equal to package.json, checked in CI). */
|
|
10
|
-
export declare const CLIENT_VERSION = "0.1.
|
|
10
|
+
export declare const CLIENT_VERSION = "0.1.14";
|
|
11
11
|
/** Sent on every request so Recta can count real use of this package apart from other clients (no address, no key). */
|
|
12
|
-
export declare const USER_AGENT = "recta-client/0.1.
|
|
12
|
+
export declare const USER_AGENT = "recta-client/0.1.14";
|
|
13
13
|
/** The fee: x402 `upto` on Base, a Permit2 `permitWitnessTransferFrom`. All lowercase. */
|
|
14
14
|
export declare const FEE_CHAIN_ID = 8453;
|
|
15
15
|
export declare const PERMIT2 = "0x000000000022d473030f116ddee9f6b43ac78ba3";
|
package/dist/constants.js
CHANGED
|
@@ -7,7 +7,7 @@
|
|
|
7
7
|
*/
|
|
8
8
|
export const RECTA_ORIGIN = "https://api.recta.build";
|
|
9
9
|
/** This package's version (equal to package.json, checked in CI). */
|
|
10
|
-
export const CLIENT_VERSION = "0.1.
|
|
10
|
+
export const CLIENT_VERSION = "0.1.14";
|
|
11
11
|
/** Sent on every request so Recta can count real use of this package apart from other clients (no address, no key). */
|
|
12
12
|
export const USER_AGENT = `recta-client/${CLIENT_VERSION}`;
|
|
13
13
|
/** The fee: x402 `upto` on Base, a Permit2 `permitWitnessTransferFrom`. All lowercase. */
|
package/dist/index.d.ts
CHANGED
|
@@ -8,3 +8,4 @@ export { viemSigner, viemChainReader, cdpSigner, smartAccountSigner, DEFAULT_USE
|
|
|
8
8
|
export { RectaCheckError, RectaHttpError, RectaDebtError, RectaSendUnknownError } from "./errors.js";
|
|
9
9
|
export * as pins from "./constants.js";
|
|
10
10
|
export { preflight, withPreflight, withPreflightTool, preflightSummary, lifiTransfer, transferFromChainTokens, decimalAmount, RectaSavingFoundError, PreflightInputError, preflightBody, PREFLIGHT_PATH, PREFLIGHT_USER_AGENT, type PreflightTransfer, type PreflightAnswer, type PreflightOptions, type PreflightRouteEstimate, type WithPreflightOptions, type ChainTokenTransfer } from "./preflight.js";
|
|
11
|
+
export { networkKeyOf, assetKeyOf, providerKeyOf, amountTextOf, closestNetworkOf, preflightNormalizedOf as readTransferNames, RECTA_NETWORK_KEYS, RECTA_ASSET_KEYS, RECTA_PROVIDER_KEYS, type PreflightNormalizedField as RectaNameRead, type RectaNetwork, type RectaAsset, type RectaProvider } from "./names.js";
|
package/dist/index.js
CHANGED
|
@@ -8,3 +8,4 @@ export { viemSigner, viemChainReader, cdpSigner, smartAccountSigner, DEFAULT_USE
|
|
|
8
8
|
export { RectaCheckError, RectaHttpError, RectaDebtError, RectaSendUnknownError } from "./errors.js";
|
|
9
9
|
export * as pins from "./constants.js";
|
|
10
10
|
export { preflight, withPreflight, withPreflightTool, preflightSummary, lifiTransfer, transferFromChainTokens, decimalAmount, RectaSavingFoundError, PreflightInputError, preflightBody, PREFLIGHT_PATH, PREFLIGHT_USER_AGENT } from "./preflight.js";
|
|
11
|
+
export { networkKeyOf, assetKeyOf, providerKeyOf, amountTextOf, closestNetworkOf, preflightNormalizedOf as readTransferNames, RECTA_NETWORK_KEYS, RECTA_ASSET_KEYS, RECTA_PROVIDER_KEYS } from "./names.js";
|
package/dist/names.d.ts
ADDED
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A copy of api.recta.build's own name reader (route-hint src/api/network-names.ts), so this package reads names exactly as
|
|
3
|
+
* the service does before it signs a request.
|
|
4
|
+
*
|
|
5
|
+
* BIT-OPS-207 (Miguel, 2026-12-05: «si alguien pone Ethereum Mainnet, Recta debería saber que está hablando de
|
|
6
|
+
* Ethereum»). On 2026-12-04 a real @recta/mcp user got three 400s from the fit check because it wrote network names the
|
|
7
|
+
* way people write them («Ethereum Mainnet», «bsc») and not as Recta's keys. A name is not a secret and carries no
|
|
8
|
+
* economic meaning, so every unsigned public entry reads any reasonable name for a network or an asset as the key it
|
|
9
|
+
* means: case, spaces and punctuation are ignored, common names and exchange labels (ETH, mainnet, BSC, BEP20, Arbitrum
|
|
10
|
+
* One, OP Mainnet…), chain IDs (decimal or hex, as text or number) and CAIP-2 ids (eip155:8453) are recognised. A
|
|
11
|
+
* name that still means nothing is refused with the valid keys and the closest one. Only unambiguous names are mapped:
|
|
12
|
+
* a name that could mean two networks or two tokens (USDC.e, «L2») is never guessed.
|
|
13
|
+
*
|
|
14
|
+
* The signed evaluation is signed byte for byte, so it keeps taking only the keys; the answers that lead to it (the
|
|
15
|
+
* preflight's `body_to_sign`, the template) already carry them.
|
|
16
|
+
*/
|
|
17
|
+
/** Every network key Recta serves (as of BIT-OPS-207, 2026-12-05), sorted. Kept equal to api.recta.build's lists. */
|
|
18
|
+
export declare const RECTA_NETWORK_KEYS: readonly string[];
|
|
19
|
+
/** A network key, for editors that offer it as a choice; any other name is still read (`networkKeyOf`). */
|
|
20
|
+
export type RectaNetwork = "arbitrum" | "arc" | "avalanche" | "base" | "bitcoin_l1" | "bnb_chain" | "ethereum" | "hyperevm" | "ink" | "linea" | "monad" | "optimism" | "polygon" | "robinhood_chain" | "solana_mainnet" | "tron_mainnet" | "unichain";
|
|
21
|
+
/** An asset key. */
|
|
22
|
+
export type RectaAsset = "BTC" | "ETH" | "USDC" | "USDC_BINANCE_PEG" | "USDG" | "USDT" | "USDT_BINANCE_PEG" | "USDT_OP_BRIDGED";
|
|
23
|
+
/** A route key. */
|
|
24
|
+
export type RectaProvider = "across" | "cctp_v2_fast" | "cctp_v2_standard" | "chainflip" | "debridge_dln" | "lifi" | "relay" | "stargate_v2" | "thorchain" | "usdg_oft" | "usdt0";
|
|
25
|
+
/** Every asset key Recta serves, sorted. */
|
|
26
|
+
export declare const RECTA_ASSET_KEYS: readonly string[];
|
|
27
|
+
/**
|
|
28
|
+
* How a value is read. EXACT (every path, the signing ones included): case, spaces, signs and accents; the listed names;
|
|
29
|
+
* filler words (mainnet, network…); a chain ID or CAIP-2 id; the network's own key for a plain token. NEAR (only the
|
|
30
|
+
* unsigned answers that list what they read): also one slip in a long name («solanu», «Etherium», «polgyon»), and amounts
|
|
31
|
+
* written with separators or a unit. Fable on BIT-OPS-207: a guess must never reach a request that is signed.
|
|
32
|
+
*/
|
|
33
|
+
export interface ReadOptions {
|
|
34
|
+
readonly near?: boolean;
|
|
35
|
+
}
|
|
36
|
+
/** The network key a name means, or undefined. With `near`, a slip in a long name pointing to one network alone is read. */
|
|
37
|
+
export declare function networkKeyOf(raw: unknown, options?: ReadOptions): string | undefined;
|
|
38
|
+
/**
|
|
39
|
+
* The asset key a name means, or undefined. With the side's network, a plain USDC or USDT on BNB Chain is its
|
|
40
|
+
* Binance-Peg key. USDT on Optimism is never guessed (USDT0 there is not the served USDT_OP_BRIDGED). With `near`, one
|
|
41
|
+
* slip in a long name («tehter») that is not another token's own name.
|
|
42
|
+
*/
|
|
43
|
+
export declare function assetKeyOf(raw: unknown, network?: string, options?: ReadOptions): string | undefined;
|
|
44
|
+
/** The network key to suggest for an unreadable name (never one that names another chain). */
|
|
45
|
+
export declare function closestNetworkOf(raw: unknown): string | undefined;
|
|
46
|
+
/** Every route key a body may name as `baseline_provider`, sorted. */
|
|
47
|
+
export declare const RECTA_PROVIDER_KEYS: readonly string[];
|
|
48
|
+
/** The route key a name means («LI.FI», «Stargate», «deBridge»), or undefined; with `near`, one slip in a name of 7
|
|
49
|
+
* letters or more («Stargte v2», «Chainfilp»). */
|
|
50
|
+
export declare function providerKeyOf(raw: unknown, options?: ReadOptions): string | undefined;
|
|
51
|
+
/**
|
|
52
|
+
* An amount as Recta's decimal string. Always: a number, or a canonical decimal with spaces around it. With `near`, as
|
|
53
|
+
* people write it: «1,000,000», «1,000.50», «1.000,50», «1,5», «$1000», «1000 USDC» (the unit must be the source
|
|
54
|
+
* asset, or USD/dollars for a stablecoin). A single dot is always the decimal point («0.001», «1.234»). A single comma
|
|
55
|
+
* followed by exactly three digits («1,234») is ambiguous and never read.
|
|
56
|
+
*/
|
|
57
|
+
export declare function amountTextOf(raw: unknown, sourceAsset?: string, options?: ReadOptions): string | undefined;
|
|
58
|
+
/** The four corridor fields. */
|
|
59
|
+
export declare const CORRIDOR_NAME_FIELDS: readonly ["source_network", "source_asset", "destination_network", "destination_asset"];
|
|
60
|
+
type CorridorNameField = (typeof CORRIDOR_NAME_FIELDS)[number];
|
|
61
|
+
/** Reads one corridor field's value as its key, with the side's own network read first for an asset. */
|
|
62
|
+
export declare function corridorKeyOf(field: CorridorNameField, raw: unknown, values: Readonly<Record<string, unknown>>, options?: ReadOptions): string | undefined;
|
|
63
|
+
/**
|
|
64
|
+
* What a refusal of an unknown network or asset adds: the valid keys and, when one is close, the key it most likely
|
|
65
|
+
* meant. Public text (BIT-OPS-207).
|
|
66
|
+
*/
|
|
67
|
+
export declare function unknownNameHelpOf(field: string, raw: unknown, values?: Readonly<Record<string, unknown>>): Record<string, unknown>;
|
|
68
|
+
/** Public text (BIT-OPS-207): the guides' line on names. */
|
|
69
|
+
export declare const NAMES_LINE = "Names: in the free checks (preflight, trial, fit check, saving odds, template), write networks, assets and routes as you know them, in any case or spelling (\"Ethereum Mainnet\", \"BSC\", \"Arbitrum One\", a chain ID such as 8453, a CAIP-2 id such as \"eip155:8453\", \"Tether\", \"LI.FI\", a slip in a longer name such as \"Etherium\"), and amounts as \"1,000,000\" or \"1000 USDC\". Recta reads them as its own keys (the service descriptor and the MCP tools list them) and says what it read in `normalized` or `names_read`; a name it cannot read is answered with the valid ones and the closest. Anything that gets a route or is signed reads only exact names (any case, listed names, chain IDs): use the keys the free checks gave you.";
|
|
70
|
+
/** Public text (BIT-OPS-207): how names are read. */
|
|
71
|
+
export declare const NAMES_NOTE = "Networks and assets are read by name in any case or spelling Recta recognises (e.g. \"Ethereum Mainnet\", \"ETH\", \"BSC\", \"Arbitrum One\", chain ID 8453, \"eip155:8453\"; \"usdt\" or \"Tether\"). The keys above are the canonical ones; the fit check lists which pairs are covered.";
|
|
72
|
+
/** One value Recta read as another key: listed in the answer, so the agent sees what was understood. */
|
|
73
|
+
export interface NameRead {
|
|
74
|
+
readonly field: string;
|
|
75
|
+
readonly from: unknown;
|
|
76
|
+
readonly to: string;
|
|
77
|
+
}
|
|
78
|
+
/** Public text (BIT-OPS-207): the note beside `names_read`. */
|
|
79
|
+
export declare const NAMES_READ_NOTE = "Recta read these values as the names it uses. Check them; the signed evaluation takes only these canonical names.";
|
|
80
|
+
/**
|
|
81
|
+
* A free helper's query value (fit check, saving odds, template) as its key. `value` is the key when the name is
|
|
82
|
+
* recognised; a well-formed name Recta does not know is kept as it was written (in its case) so the helper can answer
|
|
83
|
+
* that it is not covered; anything else is undefined (refused with the valid names). `read` is set when the key differs
|
|
84
|
+
* from the value in more than case.
|
|
85
|
+
*/
|
|
86
|
+
export declare function readQueryName(field: string, raw: string | null, values: Readonly<Record<string, unknown>>): {
|
|
87
|
+
readonly value?: string;
|
|
88
|
+
readonly read?: NameRead;
|
|
89
|
+
};
|
|
90
|
+
/** Public text (BIT-OPS-207): a free helper's refusal of a name it could not read. */
|
|
91
|
+
export declare function unknownQueryNameMessage(field: string, params: readonly string[]): string;
|
|
92
|
+
/** A closed value («any», «Finality bound», «finality-bound») as the one of `allowed` it names; null stays null; a value
|
|
93
|
+
* that names none is returned as given, for the caller's own refusal. */
|
|
94
|
+
export declare function enumValueOf<T extends string>(raw: string | null, allowed: readonly T[]): T | string | null;
|
|
95
|
+
/** BIT-OPS-187: one value of a body read in its canonical form. */
|
|
96
|
+
export interface PreflightNormalizedField {
|
|
97
|
+
readonly field: string;
|
|
98
|
+
readonly from: unknown;
|
|
99
|
+
readonly to: string;
|
|
100
|
+
}
|
|
101
|
+
/**
|
|
102
|
+
* BIT-OPS-187 / BIT-OPS-207: an unsigned body (preflight, trial, free route, x402 route) read as the agent meant it:
|
|
103
|
+
* camelCase field names, any name of a network, asset or route, the amount as people write it and the constraint classes
|
|
104
|
+
* in any case. Each change is listed; a value Recta cannot read is left (trimmed, in the key's case) for the usual
|
|
105
|
+
* refusal, which then lists the valid names.
|
|
106
|
+
*/
|
|
107
|
+
export declare function preflightNormalizedOf(body: unknown, options?: ReadOptions): {
|
|
108
|
+
readonly body: unknown;
|
|
109
|
+
readonly normalized: readonly PreflightNormalizedField[];
|
|
110
|
+
};
|
|
111
|
+
export {};
|
package/dist/names.js
ADDED
|
@@ -0,0 +1,516 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A copy of api.recta.build's own name reader (route-hint src/api/network-names.ts), so this package reads names exactly as
|
|
3
|
+
* the service does before it signs a request.
|
|
4
|
+
*
|
|
5
|
+
* BIT-OPS-207 (Miguel, 2026-12-05: «si alguien pone Ethereum Mainnet, Recta debería saber que está hablando de
|
|
6
|
+
* Ethereum»). On 2026-12-04 a real @recta/mcp user got three 400s from the fit check because it wrote network names the
|
|
7
|
+
* way people write them («Ethereum Mainnet», «bsc») and not as Recta's keys. A name is not a secret and carries no
|
|
8
|
+
* economic meaning, so every unsigned public entry reads any reasonable name for a network or an asset as the key it
|
|
9
|
+
* means: case, spaces and punctuation are ignored, common names and exchange labels (ETH, mainnet, BSC, BEP20, Arbitrum
|
|
10
|
+
* One, OP Mainnet…), chain IDs (decimal or hex, as text or number) and CAIP-2 ids (eip155:8453) are recognised. A
|
|
11
|
+
* name that still means nothing is refused with the valid keys and the closest one. Only unambiguous names are mapped:
|
|
12
|
+
* a name that could mean two networks or two tokens (USDC.e, «L2») is never guessed.
|
|
13
|
+
*
|
|
14
|
+
* The signed evaluation is signed byte for byte, so it keeps taking only the keys; the answers that lead to it (the
|
|
15
|
+
* preflight's `body_to_sign`, the template) already carry them.
|
|
16
|
+
*/
|
|
17
|
+
/** Every network key Recta serves (as of BIT-OPS-207, 2026-12-05), sorted. Kept equal to api.recta.build's lists. */
|
|
18
|
+
export const RECTA_NETWORK_KEYS = Object.freeze(["arbitrum", "arc", "avalanche", "base", "bitcoin_l1", "bnb_chain", "ethereum", "hyperevm", "ink", "linea", "monad", "optimism", "polygon", "robinhood_chain", "solana_mainnet", "tron_mainnet", "unichain"]);
|
|
19
|
+
/** Every asset key Recta serves, sorted. */
|
|
20
|
+
export const RECTA_ASSET_KEYS = Object.freeze(["BTC", "ETH", "USDC", "USDC_BINANCE_PEG", "USDG", "USDT", "USDT_BINANCE_PEG", "USDT_OP_BRIDGED"]);
|
|
21
|
+
/** Lowercase letters and digits only: «Ethereum Mainnet», «ethereum-mainnet» and «ETHEREUM_MAINNET» are one name. */
|
|
22
|
+
const compact = (s) => plain(s).replace(/[^a-z0-9]/g, "");
|
|
23
|
+
/** Lowercase without accents («Etheréum» is «ethereum»). */
|
|
24
|
+
const plain = (s) => s.normalize("NFD").replace(/[̀-ͯ]/g, "").toLowerCase();
|
|
25
|
+
/** Fable #391 F-1 / re-audit B3: after accents are dropped, a name must be printable ASCII (no «ⓔthereum», full-width
|
|
26
|
+
* digits, zero-width or control characters). */
|
|
27
|
+
const readable = (s) => /^[\x20-\x7e]*$/.test(plain(s));
|
|
28
|
+
/** Longest text read as a name; anything longer is left as sent. */
|
|
29
|
+
const MAX_NAME = 64;
|
|
30
|
+
/** EVM chain IDs of the served networks. */
|
|
31
|
+
const EVM_CHAIN_IDS = Object.freeze({
|
|
32
|
+
ethereum: 1, optimism: 10, bnb_chain: 56, unichain: 130, polygon: 137, monad: 143, hyperevm: 999, robinhood_chain: 4663,
|
|
33
|
+
arc: 5042, base: 8453, arbitrum: 42161, avalanche: 43114, ink: 57073, linea: 59144,
|
|
34
|
+
});
|
|
35
|
+
/** Tron's chain ID (0x2b6653dc), as wallets and CAIP-2 (`tron:0x2b6653dc`) give it. */
|
|
36
|
+
const TRON_CHAIN_ID = 728126428;
|
|
37
|
+
/** CAIP-2 ids of the non-EVM networks (lowercase, exact). */
|
|
38
|
+
const NON_EVM_CAIP2 = Object.freeze({
|
|
39
|
+
"solana:5eykt4usfv8p8njdtrepy1vzqkqzkvdp": "solana_mainnet",
|
|
40
|
+
"tron:0x2b6653dc": "tron_mainnet",
|
|
41
|
+
"tron:728126428": "tron_mainnet",
|
|
42
|
+
"bip122:000000000019d6689c085ae165831e93": "bitcoin_l1",
|
|
43
|
+
});
|
|
44
|
+
/** Names people and models use for each network (compacted), beyond the key itself. Only unambiguous ones. */
|
|
45
|
+
const NETWORK_ALIASES = Object.freeze({
|
|
46
|
+
ethereum: ["eth", "ether", "mainnet", "ethmainnet", "ethereummainnet", "homestead", "erc20"],
|
|
47
|
+
arbitrum: ["arb", "arb1", "arbitrumone", "arbone"],
|
|
48
|
+
base: ["basemainnet"],
|
|
49
|
+
optimism: ["op", "opmainnet", "optimismmainnet"],
|
|
50
|
+
polygon: ["matic", "pol", "polygonpos", "polygonmainnet", "maticmainnet"],
|
|
51
|
+
avalanche: ["avax", "avalanchec", "avalanchecchain", "avaxc", "avaxcchain", "cchain"],
|
|
52
|
+
bnb_chain: ["bsc", "bnb", "bnbchain", "bnbsmartchain", "binancesmartchain", "bep20", "bscmainnet", "binance", "bnbsmart", "binancesmart"],
|
|
53
|
+
linea: ["lineamainnet"],
|
|
54
|
+
unichain: ["unichainmainnet"],
|
|
55
|
+
ink: ["inkmainnet"],
|
|
56
|
+
hyperevm: ["hyperliquidevm"],
|
|
57
|
+
monad: ["monadmainnet"],
|
|
58
|
+
arc: ["arcmainnet"],
|
|
59
|
+
robinhood_chain: ["robinhood", "robinhoodchain"],
|
|
60
|
+
solana_mainnet: ["solana", "sol", "solanamainnetbeta", "mainnetbeta"],
|
|
61
|
+
tron_mainnet: ["tron", "trx", "trc20"],
|
|
62
|
+
bitcoin_l1: ["bitcoin", "btc", "bitcoinmainnet"],
|
|
63
|
+
});
|
|
64
|
+
/** The long names a slip is measured against (no short alias: «op», «bsc», «base» are one slip from other chains). */
|
|
65
|
+
const NETWORK_NEAR_NAMES = Object.freeze({
|
|
66
|
+
ethereum: ["ethereum"], arbitrum: ["arbitrum"], optimism: ["optimism"], polygon: ["polygon"], avalanche: ["avalanche"],
|
|
67
|
+
bnb_chain: ["binancesmart", "bnbsmart"], unichain: ["unichain"], hyperevm: ["hyperliquid", "hyperevm"], robinhood_chain: ["robinhood"],
|
|
68
|
+
solana_mainnet: ["solana"], bitcoin_l1: ["bitcoin"], linea: ["linea"], monad: ["monad"],
|
|
69
|
+
});
|
|
70
|
+
const NETWORK_BY_NAME = (() => {
|
|
71
|
+
const m = new Map();
|
|
72
|
+
for (const key of RECTA_NETWORK_KEYS) {
|
|
73
|
+
m.set(compact(key), key);
|
|
74
|
+
for (const alias of NETWORK_ALIASES[key] ?? [])
|
|
75
|
+
m.set(alias, key);
|
|
76
|
+
}
|
|
77
|
+
return m;
|
|
78
|
+
})();
|
|
79
|
+
const NETWORK_NEAR = new Map(Object.entries(NETWORK_NEAR_NAMES).filter(([k]) => RECTA_NETWORK_KEYS.includes(k)).flatMap(([k, names]) => names.map((n) => [n, k])));
|
|
80
|
+
const CHAIN_ID_TO_NETWORK = new Map([
|
|
81
|
+
...Object.entries(EVM_CHAIN_IDS).filter(([k]) => RECTA_NETWORK_KEYS.includes(k)).map(([k, id]) => [BigInt(id), k]),
|
|
82
|
+
...(RECTA_NETWORK_KEYS.includes("tron_mainnet") ? [[BigInt(TRON_CHAIN_ID), "tron_mainnet"]] : []),
|
|
83
|
+
]);
|
|
84
|
+
/**
|
|
85
|
+
* Another chain, a test network or a word that changes which chain is meant: never read as a served network, even inside
|
|
86
|
+
* brackets («Ethereum (Sepolia)», «opBNB Chain», «Arbitrum Nova», «Bitcoin SV», «Polygon zkEVM», «Linera»).
|
|
87
|
+
*/
|
|
88
|
+
const OTHER_CHAIN_WORDS = /(test|devnet|sepolia|goerli|holesky|hoodi|amoy|mumbai|fuji|chapel|shasta|nile|signet|regtest|nova|zk|cardona|bartio|opbnb|bob|blast|mint|sei|okx|linera|litecoin|bitcoinsv|bsv|cash|classic|gold|ethw|ethpow|xchain|pchain|subnet|sidechain|beacon|bridged|wrapped|staging|local|fork|old|legacy|v1)/;
|
|
89
|
+
/** Filler words, read only whole («Ethereum Mainnet», «Linea network», «the BNB chain»). */
|
|
90
|
+
const FILLER_WORDS = new Set(["mainnet", "network", "blockchain", "chain", "main", "net", "the", "l1", "evm", "one", "l2", "layer2", "rollup", "id", "chainid"]);
|
|
91
|
+
/** Fable re-audit A3/A4: filler words that name a kind of chain fit only those chains («Hyperliquid L1» is HyperCore,
|
|
92
|
+
* «Avalanche L1» a subnet, «Ethereum L2» none). */
|
|
93
|
+
const FILLER_ONLY_FOR = Object.freeze({
|
|
94
|
+
l1: ["ethereum", "bitcoin_l1"],
|
|
95
|
+
one: ["arbitrum"],
|
|
96
|
+
l2: L2_NETWORKS(), layer2: L2_NETWORKS(), rollup: L2_NETWORKS(),
|
|
97
|
+
// Fable N2: «Solana EVM» is Neon, not Solana.
|
|
98
|
+
evm: Object.keys(EVM_CHAIN_IDS),
|
|
99
|
+
});
|
|
100
|
+
function L2_NETWORKS() { return ["arbitrum", "base", "optimism", "linea", "unichain", "ink"]; }
|
|
101
|
+
/** Gas paid in ETH: «Base (ETH)», «Arbitrum One (ETH)» as exchanges label them. */
|
|
102
|
+
const ETH_GAS_NETWORKS = new Set(["ethereum", ...L2_NETWORKS()]);
|
|
103
|
+
/** Names read only in the free checks that list what they read: they may mean a neighbour Recta does not serve
|
|
104
|
+
* («Hyperliquid» alone can be HyperCore). */
|
|
105
|
+
const NETWORK_NEAR_ONLY = new Map([["hyperliquid", "hyperevm"]]);
|
|
106
|
+
/** Another chain one slip from a served name: never read from a slip. */
|
|
107
|
+
const OTHER_CHAIN_SLIPS = new Set(["litcoin", "lightcoin", "inichain", "gonad", "nomad", "linear", "alinea", "arbitrumnova", "bitcoins"]);
|
|
108
|
+
/** The network a written chain ID names: decimal, 0x hex or eip155:<id> only (never «1.0» or «Base (84532)»). */
|
|
109
|
+
function networkOfChainId(text) {
|
|
110
|
+
const m = /^(?:eip155[:_-])?(0x[0-9a-f]{1,16}|[0-9]{1,20})$/i.exec(text);
|
|
111
|
+
return m === null ? undefined : CHAIN_ID_TO_NETWORK.get(BigInt(m[1]));
|
|
112
|
+
}
|
|
113
|
+
/** The network key a name means, or undefined. With `near`, a slip in a long name pointing to one network alone is read. */
|
|
114
|
+
export function networkKeyOf(raw, options = {}) {
|
|
115
|
+
if (typeof raw === "number")
|
|
116
|
+
return Number.isSafeInteger(raw) && raw > 0 ? CHAIN_ID_TO_NETWORK.get(BigInt(raw)) : undefined;
|
|
117
|
+
if (typeof raw !== "string" || raw.length === 0 || raw.length > MAX_NAME || !readable(raw))
|
|
118
|
+
return undefined;
|
|
119
|
+
const text = plain(raw.trim());
|
|
120
|
+
const byId = networkOfChainId(text);
|
|
121
|
+
if (byId !== undefined)
|
|
122
|
+
return byId;
|
|
123
|
+
const caip = NON_EVM_CAIP2[text];
|
|
124
|
+
if (caip !== undefined)
|
|
125
|
+
return RECTA_NETWORK_KEYS.includes(caip) ? caip : undefined;
|
|
126
|
+
if (OTHER_CHAIN_WORDS.test(compact(text)))
|
|
127
|
+
return undefined;
|
|
128
|
+
// «Base (8453)»: a chain ID in brackets must be the same network; any other bracket word is read with the name.
|
|
129
|
+
const bracket = /^(.*?)[([](.*?)[)\]]\s*$/.exec(text);
|
|
130
|
+
let name = text;
|
|
131
|
+
if (bracket !== null) {
|
|
132
|
+
const inner = bracket[2].trim();
|
|
133
|
+
const innerId = /^[0-9a-fx:]+$/i.test(inner) ? networkOfChainId(inner) : undefined;
|
|
134
|
+
const outer = networkKeyOf(bracket[1], options);
|
|
135
|
+
if (/^[0-9a-fx:]+$/i.test(inner))
|
|
136
|
+
return innerId !== undefined && innerId === outer ? outer : undefined;
|
|
137
|
+
// «Ethereum (ERC20)», «Tron (TRC20)», «Polygon (MATIC)», «Base (L2)», «Base (ETH)»: the bracket names the same
|
|
138
|
+
// network, its kind or its gas token; anything else is read with the name.
|
|
139
|
+
if (outer !== undefined) {
|
|
140
|
+
const innerKey = networkKeyOf(inner);
|
|
141
|
+
const kind = compact(inner);
|
|
142
|
+
// Fable N1: the gas rule only for the token's own name («Base (Ethereum)», «ARB (ERC20)», «Base (eip155:1)» are not it).
|
|
143
|
+
if (innerKey === outer || (["eth", "ether"].includes(kind) && ETH_GAS_NETWORKS.has(outer)) || (FILLER_ONLY_FOR[kind] ?? []).includes(outer))
|
|
144
|
+
return outer;
|
|
145
|
+
}
|
|
146
|
+
name = `${bracket[1]} ${inner}`;
|
|
147
|
+
}
|
|
148
|
+
// «Base Layer 2», «layer-1».
|
|
149
|
+
name = name.replace(/\blayer[\s_-]*([12])\b/g, "l$1");
|
|
150
|
+
const words = name.split(/[^a-z0-9]+/).filter((w) => w.length > 0);
|
|
151
|
+
const kept = words.filter((w) => !FILLER_WORDS.has(w));
|
|
152
|
+
const fits = (key) => words.every((w) => FILLER_ONLY_FOR[w] === undefined || FILLER_ONLY_FOR[w].includes(key));
|
|
153
|
+
// «chain 8453», «chain id 8453».
|
|
154
|
+
if (kept.length === 1 && /^[0-9]+$/.test(kept[0])) {
|
|
155
|
+
// Fable N3: only filler words around the ID («chain 8453», «chain id 8453»), nothing else.
|
|
156
|
+
const id = networkOfChainId(kept[0]);
|
|
157
|
+
return id !== undefined && /^[a-z0-9 ]+$/.test(name.trim()) && words.every((w) => w === kept[0] || ["chain", "id", "chainid"].includes(w)) ? id : undefined;
|
|
158
|
+
}
|
|
159
|
+
const forms = [...new Set([compact(name), kept.join("")])].filter((f) => f.length > 0);
|
|
160
|
+
for (const form of forms) {
|
|
161
|
+
const hit = NETWORK_BY_NAME.get(form) ?? (options.near === true ? NETWORK_NEAR_ONLY.get(form) : undefined);
|
|
162
|
+
if (hit !== undefined)
|
|
163
|
+
return form === compact(name) && NETWORK_BY_NAME.get(form) !== undefined ? hit : fits(hit) ? hit : undefined;
|
|
164
|
+
}
|
|
165
|
+
if (options.near !== true)
|
|
166
|
+
return undefined;
|
|
167
|
+
// A slip in a long filler word too («mainet», «netwrok»).
|
|
168
|
+
const form = kept.filter((w) => !(w.length >= 6 && ["mainnet", "network", "blockchain"].some((f) => distance(w, f) <= 1))).join("");
|
|
169
|
+
if (form.length < 5 || /[0-9]/.test(form) || OTHER_CHAIN_SLIPS.has(form))
|
|
170
|
+
return undefined;
|
|
171
|
+
const near = nearestOf(form, NETWORK_NEAR);
|
|
172
|
+
return near !== undefined && near.unique && near.d <= (form.length >= 10 ? 2 : 1) && plausibleSlip(form, near.name) && fits(near.key) ? near.key : undefined;
|
|
173
|
+
}
|
|
174
|
+
/** Names for each asset (compacted) beyond the key itself. Only exact names: tickers are never read from a slip. */
|
|
175
|
+
const ASSET_ALIASES = Object.freeze({
|
|
176
|
+
USDC: ["usdcoin", "circleusdc", "nativeusdc", "usdollarcoin", "usdcnative"],
|
|
177
|
+
USDT: ["tether", "tetherusd", "tetherusdt", "usdt0", "usdtzero"],
|
|
178
|
+
ETH: ["ether", "ethereum", "nativeeth"],
|
|
179
|
+
BTC: ["bitcoin", "xbt"],
|
|
180
|
+
USDG: ["globaldollar", "paxosglobaldollar"],
|
|
181
|
+
});
|
|
182
|
+
/** Long asset names a slip is measured against («tehter», «usd coinn»). */
|
|
183
|
+
const ASSET_NEAR = new Map([["usdcoin", "USDC"], ["tether", "USDT"], ["tetherusd", "USDT"], ["globaldollar", "USDG"]]);
|
|
184
|
+
/** Words that make it another token («bridged», «wrapped», «eur», «.e»). */
|
|
185
|
+
const OTHER_TOKEN_WORDS = /(bridged|wrapped|eur|aud|gbp|jpy|staked|liquid|yield|savings|synthetic|^w|^a(?=usd)|^c(?=usd)|^s(?=usd|eth|btc)|^m(?=eth)|^o(?=eth)|^r(?=eth|btc)|^st|^cb|^we|e$|b$)/;
|
|
186
|
+
const ASSET_BY_NAME = (() => {
|
|
187
|
+
const m = new Map();
|
|
188
|
+
for (const key of RECTA_ASSET_KEYS) {
|
|
189
|
+
m.set(compact(key), key);
|
|
190
|
+
for (const alias of ASSET_ALIASES[key] ?? [])
|
|
191
|
+
m.set(alias, key);
|
|
192
|
+
}
|
|
193
|
+
return m;
|
|
194
|
+
})();
|
|
195
|
+
/** On BNB Chain the only USDC and USDT are Binance-Peg: the plain names mean those keys there. */
|
|
196
|
+
const PLAIN_ON_NETWORK = Object.freeze({
|
|
197
|
+
bnb_chain: { usdc: "USDC_BINANCE_PEG", usdcoin: "USDC_BINANCE_PEG", usdt: "USDT_BINANCE_PEG", tether: "USDT_BINANCE_PEG", tetherusd: "USDT_BINANCE_PEG" },
|
|
198
|
+
});
|
|
199
|
+
/**
|
|
200
|
+
* The asset key a name means, or undefined. With the side's network, a plain USDC or USDT on BNB Chain is its
|
|
201
|
+
* Binance-Peg key. USDT on Optimism is never guessed (USDT0 there is not the served USDT_OP_BRIDGED). With `near`, one
|
|
202
|
+
* slip in a long name («tehter») that is not another token's own name.
|
|
203
|
+
*/
|
|
204
|
+
export function assetKeyOf(raw, network, options = {}) {
|
|
205
|
+
if (typeof raw !== "string" || raw.length === 0 || raw.length > MAX_NAME || !readable(raw.replace(/₮/g, "t")))
|
|
206
|
+
return undefined;
|
|
207
|
+
// «USD₮0», as Tether's own contracts name USDT0.
|
|
208
|
+
const name = compact(raw.trim().replace(/₮/g, "t"));
|
|
209
|
+
const onNetwork = network === undefined ? undefined : PLAIN_ON_NETWORK[network]?.[name];
|
|
210
|
+
if (onNetwork !== undefined)
|
|
211
|
+
return onNetwork;
|
|
212
|
+
const key = ASSET_BY_NAME.get(name);
|
|
213
|
+
if (key !== undefined)
|
|
214
|
+
return pegOn(key, network);
|
|
215
|
+
if (options.near !== true || name.length < 6 || /[0-9]/.test(name) || OTHER_TOKEN_WORDS.test(name))
|
|
216
|
+
return undefined;
|
|
217
|
+
const near = nearestOf(name, ASSET_NEAR);
|
|
218
|
+
if (near === undefined || !near.unique || near.d > 1 || !plausibleSlip(name, near.name))
|
|
219
|
+
return undefined;
|
|
220
|
+
// Fable re-audit A1: a name holding another ticker («usdt coin», «usde coin», «tether usds») is that token.
|
|
221
|
+
const ticker = /usd[a-z]/.exec(name.replace(/usdollar/g, ""))?.[0];
|
|
222
|
+
if (ticker !== undefined && ticker !== { USDC: "usdc", USDT: "usdt" }[near.key])
|
|
223
|
+
return undefined;
|
|
224
|
+
return pegOn(near.key, network);
|
|
225
|
+
}
|
|
226
|
+
/** On BNB Chain the only USDC and USDT are Binance-Peg: any name of them means that key there (re-audit B7). */
|
|
227
|
+
function pegOn(key, network) {
|
|
228
|
+
return (network === undefined ? undefined : PLAIN_ON_NETWORK[network]?.[key.toLowerCase()]) ?? key;
|
|
229
|
+
}
|
|
230
|
+
/** Edit distance with a swap of two neighbouring letters counted as one slip («polgyon»); names are short. */
|
|
231
|
+
function distance(a, b) {
|
|
232
|
+
if (Math.abs(a.length - b.length) > 3)
|
|
233
|
+
return 99;
|
|
234
|
+
const d = Array.from({ length: a.length + 1 }, (_, i) => Array.from({ length: b.length + 1 }, (_, j) => (i === 0 ? j : j === 0 ? i : 0)));
|
|
235
|
+
for (let i = 1; i <= a.length; i++) {
|
|
236
|
+
for (let j = 1; j <= b.length; j++) {
|
|
237
|
+
const cost = a[i - 1] === b[j - 1] ? 0 : 1;
|
|
238
|
+
d[i][j] = Math.min(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + cost);
|
|
239
|
+
if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1])
|
|
240
|
+
d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + 1);
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
return d[a.length][b.length];
|
|
244
|
+
}
|
|
245
|
+
/** The key whose name is nearest to `name`, its distance, and whether no other key is as near. */
|
|
246
|
+
function nearestOf(name, names) {
|
|
247
|
+
if (name.length > 40)
|
|
248
|
+
return undefined;
|
|
249
|
+
let best;
|
|
250
|
+
for (const [alias, key] of names) {
|
|
251
|
+
const d = distance(name, alias);
|
|
252
|
+
if (best === undefined || d < best.d)
|
|
253
|
+
best = { key, name: alias, d, unique: true };
|
|
254
|
+
else if (d === best.d && key !== best.key)
|
|
255
|
+
best.unique = false;
|
|
256
|
+
}
|
|
257
|
+
return best;
|
|
258
|
+
}
|
|
259
|
+
/**
|
|
260
|
+
* Fable re-audit A1/A2: a slip people make, not another name. The first letter must be the same («gonad», «aether»,
|
|
261
|
+
* «ebridge» are other names), and the whole name plus one more letter is another name («bitcoinz», «linear»,
|
|
262
|
+
* «ethereumx») unless the letter is doubled («bitcoinn»).
|
|
263
|
+
*/
|
|
264
|
+
function plausibleSlip(written, target) {
|
|
265
|
+
if (written[0] !== target[0])
|
|
266
|
+
return false;
|
|
267
|
+
if (written.length === target.length + 1 && written.startsWith(target))
|
|
268
|
+
return written.at(-1) === target.at(-1);
|
|
269
|
+
return true;
|
|
270
|
+
}
|
|
271
|
+
/** The network key to suggest for an unreadable name (never one that names another chain). */
|
|
272
|
+
export function closestNetworkOf(raw) {
|
|
273
|
+
const known = networkKeyOf(raw, { near: true });
|
|
274
|
+
if (known !== undefined || typeof raw !== "string" || raw.length > MAX_NAME || !readable(raw) || OTHER_CHAIN_WORDS.test(compact(raw)))
|
|
275
|
+
return known;
|
|
276
|
+
const name = compact(raw);
|
|
277
|
+
if (name.length < 4 || /[0-9]/.test(name))
|
|
278
|
+
return undefined;
|
|
279
|
+
if (OTHER_CHAIN_SLIPS.has(name))
|
|
280
|
+
return undefined;
|
|
281
|
+
const near = nearestOf(name, NETWORK_NEAR);
|
|
282
|
+
return near !== undefined && near.unique && near.d <= Math.max(1, Math.floor(name.length / 3)) && plausibleSlip(name, near.name) ? near.key : undefined;
|
|
283
|
+
}
|
|
284
|
+
/** Every route key a body may name as `baseline_provider`, sorted. */
|
|
285
|
+
export const RECTA_PROVIDER_KEYS = Object.freeze(["across", "cctp_v2_fast", "cctp_v2_standard", "chainflip", "debridge_dln", "lifi", "relay", "stargate_v2", "thorchain", "usdg_oft", "usdt0"]);
|
|
286
|
+
/** Names for each route (compacted). Never «cctp» or «cctp v2» alone (fast or standard), never a token's name. */
|
|
287
|
+
const PROVIDER_ALIASES = Object.freeze({
|
|
288
|
+
lifi: ["lifiprotocol", "lifiapi", "jumper", "jumperexchange"],
|
|
289
|
+
across: ["acrossprotocol", "acrossbridge"],
|
|
290
|
+
stargate_v2: ["stargatev2", "stargatefinancev2"],
|
|
291
|
+
cctp_v2_standard: ["cctpstandard", "cctpv2standardtransfer", "cctpstandardtransfer"],
|
|
292
|
+
cctp_v2_fast: ["cctpfast", "cctpv2fasttransfer", "cctpfasttransfer"],
|
|
293
|
+
relay: ["relaylink", "relayprotocol"],
|
|
294
|
+
usdt0: ["usdt0oft", "usdt0bridge"],
|
|
295
|
+
usdg_oft: ["usdgoft"],
|
|
296
|
+
debridge_dln: ["debridge", "dln", "debridgedln"],
|
|
297
|
+
thorchain: ["thorchainswap"],
|
|
298
|
+
chainflip: [],
|
|
299
|
+
});
|
|
300
|
+
/** Long route names a slip is measured against. */
|
|
301
|
+
const PROVIDER_NEAR = new Map([["chainflip", "chainflip"], ["thorchain", "thorchain"], ["debridge", "debridge_dln"], ["stargatev2", "stargate_v2"], ["acrossprotocol", "across"]]);
|
|
302
|
+
/** Other bridges, never read as one of Recta's routes («Starkgate», «Stargate v1», «op bridge»). */
|
|
303
|
+
const OTHER_ROUTE_WORDS = /(starkgate|v1|opbridge|zkbridge|hop|synapse|orbiter|cbridge|wormhole|allbridge|meson|rhino|squid|socket|bungee|mayan|symbiosis|connext|everclear|native|canonical|official)/;
|
|
304
|
+
/** Other names one slip from a route's (Tor, a clip): never read from a slip. */
|
|
305
|
+
const OTHER_ROUTE_SLIPS = new Set(["torchain", "chainclip", "chainslip", "ebridge", "rebridge"]);
|
|
306
|
+
const PROVIDER_BY_NAME = (() => {
|
|
307
|
+
const m = new Map();
|
|
308
|
+
for (const key of RECTA_PROVIDER_KEYS) {
|
|
309
|
+
m.set(compact(key), key);
|
|
310
|
+
for (const alias of PROVIDER_ALIASES[key] ?? [])
|
|
311
|
+
m.set(alias, key);
|
|
312
|
+
}
|
|
313
|
+
// «Stargate» alone: v2 is the only Stargate in service.
|
|
314
|
+
if (RECTA_PROVIDER_KEYS.includes("stargate_v2"))
|
|
315
|
+
m.set("stargate", "stargate_v2");
|
|
316
|
+
if (RECTA_PROVIDER_KEYS.includes("across"))
|
|
317
|
+
m.set("across", "across");
|
|
318
|
+
return m;
|
|
319
|
+
})();
|
|
320
|
+
/** The route key a name means («LI.FI», «Stargate», «deBridge»), or undefined; with `near`, one slip in a name of 7
|
|
321
|
+
* letters or more («Stargte v2», «Chainfilp»). */
|
|
322
|
+
export function providerKeyOf(raw, options = {}) {
|
|
323
|
+
if (typeof raw !== "string" || raw.length === 0 || raw.length > MAX_NAME || !readable(raw))
|
|
324
|
+
return undefined;
|
|
325
|
+
const name = compact(raw.trim());
|
|
326
|
+
if (OTHER_ROUTE_WORDS.test(name) || OTHER_ROUTE_SLIPS.has(name))
|
|
327
|
+
return undefined;
|
|
328
|
+
const hit = PROVIDER_BY_NAME.get(name);
|
|
329
|
+
if (hit !== undefined || options.near !== true || name.length < 7)
|
|
330
|
+
return hit;
|
|
331
|
+
const near = nearestOf(name, PROVIDER_NEAR);
|
|
332
|
+
if (near === undefined || !near.unique || near.d > 1 || !plausibleSlip(name, near.name))
|
|
333
|
+
return undefined;
|
|
334
|
+
const target = near.name;
|
|
335
|
+
return target.replace(/[^0-9]/g, "") === name.replace(/[^0-9]/g, "") ? near.key : undefined;
|
|
336
|
+
}
|
|
337
|
+
/**
|
|
338
|
+
* An amount as Recta's decimal string. Always: a number, or a canonical decimal with spaces around it. With `near`, as
|
|
339
|
+
* people write it: «1,000,000», «1,000.50», «1.000,50», «1,5», «$1000», «1000 USDC» (the unit must be the source
|
|
340
|
+
* asset, or USD/dollars for a stablecoin). A single dot is always the decimal point («0.001», «1.234»). A single comma
|
|
341
|
+
* followed by exactly three digits («1,234») is ambiguous and never read.
|
|
342
|
+
*/
|
|
343
|
+
export function amountTextOf(raw, sourceAsset, options = {}) {
|
|
344
|
+
if (typeof raw === "number")
|
|
345
|
+
return Number.isFinite(raw) && raw > 0 && CANONICAL_AMOUNT.test(String(raw)) ? String(raw) : undefined;
|
|
346
|
+
if (typeof raw !== "string" || raw.length > 64)
|
|
347
|
+
return undefined;
|
|
348
|
+
const trimmed = raw.trim();
|
|
349
|
+
if (CANONICAL_AMOUNT.test(trimmed))
|
|
350
|
+
return trimmed;
|
|
351
|
+
if (options.near !== true)
|
|
352
|
+
return undefined;
|
|
353
|
+
let t = trimmed.replace(/^\$\s*/, "");
|
|
354
|
+
const usdSign = t !== trimmed;
|
|
355
|
+
const unit = /^(.*?[0-9.,])\s*([A-Za-z₮][A-Za-z0-9_.₮]*)$/.exec(t);
|
|
356
|
+
if (unit !== null) {
|
|
357
|
+
const unitKey = assetKeyOf(unit[2]);
|
|
358
|
+
const stable = sourceAsset !== undefined && /^(USDC|USDT|USDG)/.test(sourceAsset);
|
|
359
|
+
const sameAsset = unitKey !== undefined && sourceAsset !== undefined && (unitKey === sourceAsset || sourceAsset.startsWith(`${unitKey}_`));
|
|
360
|
+
if (!(sameAsset || (stable && /^(usd|dollars?)$/i.test(unit[2]))))
|
|
361
|
+
return undefined;
|
|
362
|
+
t = unit[1].trim();
|
|
363
|
+
}
|
|
364
|
+
if (usdSign && sourceAsset !== undefined && !/^(USDC|USDT|USDG)/.test(sourceAsset))
|
|
365
|
+
return undefined;
|
|
366
|
+
t = t.replace(/(?<=[0-9])[ _ ](?=[0-9]{3}(?![0-9]))/g, "");
|
|
367
|
+
if (/^[1-9][0-9]{0,2}(,[0-9]{3}){2,}(\.[0-9]+)?$/.test(t) || /^[1-9][0-9]{0,2}(,[0-9]{3})+\.[0-9]+$/.test(t))
|
|
368
|
+
t = t.replace(/,/g, "");
|
|
369
|
+
else if (/^[1-9][0-9]{0,2}(\.[0-9]{3}){2,}(,[0-9]+)?$/.test(t) || /^[1-9][0-9]{0,2}(\.[0-9]{3})+,[0-9]+$/.test(t))
|
|
370
|
+
t = t.replace(/\./g, "").replace(",", ".");
|
|
371
|
+
else if (/^[0-9]+,([0-9]{1,2}|[0-9]{4,})$/.test(t))
|
|
372
|
+
t = t.replace(",", ".");
|
|
373
|
+
if (/^\.[0-9]+$/.test(t))
|
|
374
|
+
t = `0${t}`;
|
|
375
|
+
return CANONICAL_AMOUNT.test(t) && !/^0+(\.0*)?$/.test(t) ? t : undefined;
|
|
376
|
+
}
|
|
377
|
+
/** The four corridor fields. */
|
|
378
|
+
export const CORRIDOR_NAME_FIELDS = ["source_network", "source_asset", "destination_network", "destination_asset"];
|
|
379
|
+
const networkOfField = (field) => (field.startsWith("source") ? "source_network" : "destination_network");
|
|
380
|
+
/** Reads one corridor field's value as its key, with the side's own network read first for an asset. */
|
|
381
|
+
export function corridorKeyOf(field, raw, values, options = {}) {
|
|
382
|
+
if (field.endsWith("_network"))
|
|
383
|
+
return networkKeyOf(raw, options);
|
|
384
|
+
return assetKeyOf(raw, networkKeyOf(values[networkOfField(field)], options), options);
|
|
385
|
+
}
|
|
386
|
+
/**
|
|
387
|
+
* What a refusal of an unknown network or asset adds: the valid keys and, when one is close, the key it most likely
|
|
388
|
+
* meant. Public text (BIT-OPS-207).
|
|
389
|
+
*/
|
|
390
|
+
export function unknownNameHelpOf(field, raw, values = {}) {
|
|
391
|
+
const isNetwork = field.endsWith("_network");
|
|
392
|
+
const side = field.startsWith("source") ? "source_network" : "destination_network";
|
|
393
|
+
const suggestion = isNetwork ? closestNetworkOf(raw) : assetKeyOf(raw, networkKeyOf(values[side], { near: true }), { near: true });
|
|
394
|
+
return {
|
|
395
|
+
...(suggestion === undefined || suggestion === raw ? {} : { did_you_mean: suggestion }),
|
|
396
|
+
valid_networks: RECTA_NETWORK_KEYS,
|
|
397
|
+
valid_assets: RECTA_ASSET_KEYS,
|
|
398
|
+
names_note: NAMES_NOTE,
|
|
399
|
+
};
|
|
400
|
+
}
|
|
401
|
+
/** Public text (BIT-OPS-207): the guides' line on names. */
|
|
402
|
+
export const NAMES_LINE = "Names: in the free checks (preflight, trial, fit check, saving odds, template), write networks, assets and routes as you know them, in any case or spelling (\"Ethereum Mainnet\", \"BSC\", \"Arbitrum One\", a chain ID such as 8453, a CAIP-2 id such as \"eip155:8453\", \"Tether\", \"LI.FI\", a slip in a longer name such as \"Etherium\"), and amounts as \"1,000,000\" or \"1000 USDC\". Recta reads them as its own keys (the service descriptor and the MCP tools list them) and says what it read in `normalized` or `names_read`; a name it cannot read is answered with the valid ones and the closest. Anything that gets a route or is signed reads only exact names (any case, listed names, chain IDs): use the keys the free checks gave you.";
|
|
403
|
+
/** Public text (BIT-OPS-207): how names are read. */
|
|
404
|
+
export const NAMES_NOTE = "Networks and assets are read by name in any case or spelling Recta recognises (e.g. \"Ethereum Mainnet\", \"ETH\", \"BSC\", \"Arbitrum One\", chain ID 8453, \"eip155:8453\"; \"usdt\" or \"Tether\"). The keys above are the canonical ones; the fit check lists which pairs are covered.";
|
|
405
|
+
/** Public text (BIT-OPS-207): the note beside `names_read`. */
|
|
406
|
+
export const NAMES_READ_NOTE = "Recta read these values as the names it uses. Check them; the signed evaluation takes only these canonical names.";
|
|
407
|
+
/**
|
|
408
|
+
* A free helper's query value (fit check, saving odds, template) as its key. `value` is the key when the name is
|
|
409
|
+
* recognised; a well-formed name Recta does not know is kept as it was written (in its case) so the helper can answer
|
|
410
|
+
* that it is not covered; anything else is undefined (refused with the valid names). `read` is set when the key differs
|
|
411
|
+
* from the value in more than case.
|
|
412
|
+
*/
|
|
413
|
+
export function readQueryName(field, raw, values) {
|
|
414
|
+
if (raw === null)
|
|
415
|
+
return {};
|
|
416
|
+
const near = { near: true };
|
|
417
|
+
const key = field === "baseline_provider" ? providerKeyOf(raw, near) : CORRIDOR_NAME_FIELDS.includes(field) ? corridorKeyOf(field, raw, values, near) : undefined;
|
|
418
|
+
if (key !== undefined)
|
|
419
|
+
return { value: key, ...(raw.toLowerCase() === key.toLowerCase() ? {} : { read: { field, from: raw, to: key } }) };
|
|
420
|
+
if (!/^[A-Za-z0-9_]{1,40}$/.test(raw))
|
|
421
|
+
return {};
|
|
422
|
+
return { value: field.endsWith("_asset") ? raw.toUpperCase() : raw.toLowerCase() };
|
|
423
|
+
}
|
|
424
|
+
/** Public text (BIT-OPS-207): a free helper's refusal of a name it could not read. */
|
|
425
|
+
export function unknownQueryNameMessage(field, params) {
|
|
426
|
+
return `${field} was not recognised. Give ${params.join(", ")} as query parameters: a network from valid_networks and an asset from valid_assets (any case, a common name, a chain ID or a CAIP-2 id also works); did_you_mean, when present, is the closest name.`;
|
|
427
|
+
}
|
|
428
|
+
/** A closed value («any», «Finality bound», «finality-bound») as the one of `allowed` it names; null stays null; a value
|
|
429
|
+
* that names none is returned as given, for the caller's own refusal. */
|
|
430
|
+
export function enumValueOf(raw, allowed) {
|
|
431
|
+
if (raw === null)
|
|
432
|
+
return null;
|
|
433
|
+
return allowed.find((a) => compact(a) === compact(raw)) ?? raw;
|
|
434
|
+
}
|
|
435
|
+
const CANONICAL_AMOUNT = /^(0|[1-9][0-9]*)(\.[0-9]+)?$/;
|
|
436
|
+
/** BIT-OPS-201: camelCase field names (as @recta/client ≤ 0.1.10 sent them) to Recta's own. */
|
|
437
|
+
const PREFLIGHT_CAMEL_CASE_FIELDS = Object.freeze({
|
|
438
|
+
sourceNetwork: "source_network", sourceAsset: "source_asset", destinationNetwork: "destination_network",
|
|
439
|
+
destinationAsset: "destination_asset", baselineProvider: "baseline_provider",
|
|
440
|
+
});
|
|
441
|
+
const isRecord = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
|
|
442
|
+
/**
|
|
443
|
+
* BIT-OPS-187 / BIT-OPS-207: an unsigned body (preflight, trial, free route, x402 route) read as the agent meant it:
|
|
444
|
+
* camelCase field names, any name of a network, asset or route, the amount as people write it and the constraint classes
|
|
445
|
+
* in any case. Each change is listed; a value Recta cannot read is left (trimmed, in the key's case) for the usual
|
|
446
|
+
* refusal, which then lists the valid names.
|
|
447
|
+
*/
|
|
448
|
+
export function preflightNormalizedOf(body, options = {}) {
|
|
449
|
+
if (!isRecord(body))
|
|
450
|
+
return { body, normalized: [] };
|
|
451
|
+
const out = { ...body };
|
|
452
|
+
const normalized = [];
|
|
453
|
+
const set = (field, to) => {
|
|
454
|
+
if (out[field] === to)
|
|
455
|
+
return;
|
|
456
|
+
normalized.push({ field, from: out[field], to });
|
|
457
|
+
out[field] = to;
|
|
458
|
+
};
|
|
459
|
+
// BIT-OPS-201 (owner Ok 2026-11-21): @recta/client 0.1.10 and earlier sent camelCase names as given (BIT-OPS-196). A
|
|
460
|
+
// camelCase name is read under Recta's name when that name is absent; both present is left to the usual checks.
|
|
461
|
+
for (const [camel, field] of Object.entries(PREFLIGHT_CAMEL_CASE_FIELDS)) {
|
|
462
|
+
if (!(camel in out))
|
|
463
|
+
continue;
|
|
464
|
+
if (field in out)
|
|
465
|
+
continue;
|
|
466
|
+
out[field] = out[camel];
|
|
467
|
+
delete out[camel];
|
|
468
|
+
normalized.push({ field: camel, from: camel, to: field });
|
|
469
|
+
}
|
|
470
|
+
// BIT-OPS-207 (Miguel, 2026-12-05): names read as meant (exact readings always; slips and written amounts only with
|
|
471
|
+
// `near`). A value Recta cannot read is left exactly as sent, for the usual refusal with the valid names; so reading
|
|
472
|
+
// twice gives the same body.
|
|
473
|
+
for (const field of ["source_network", "destination_network"]) {
|
|
474
|
+
const key = networkKeyOf(out[field], options);
|
|
475
|
+
if (key !== undefined)
|
|
476
|
+
set(field, key);
|
|
477
|
+
}
|
|
478
|
+
for (const field of ["source_asset", "destination_asset"]) {
|
|
479
|
+
const key = corridorKeyOf(field, out[field], out, options);
|
|
480
|
+
if (key !== undefined)
|
|
481
|
+
set(field, key);
|
|
482
|
+
}
|
|
483
|
+
const provider = providerKeyOf(out["baseline_provider"], options);
|
|
484
|
+
if (provider !== undefined)
|
|
485
|
+
set("baseline_provider", provider);
|
|
486
|
+
const text = amountTextOf(out["amount"], typeof out["source_asset"] === "string" ? out["source_asset"] : undefined, options);
|
|
487
|
+
if (text !== undefined)
|
|
488
|
+
set("amount", text);
|
|
489
|
+
// The classes at the top level, as the MCP tools take them, and inside `constraints`.
|
|
490
|
+
for (const [k, allowed] of CLASS_FIELDS) {
|
|
491
|
+
const v = out[k];
|
|
492
|
+
if (typeof v !== "string")
|
|
493
|
+
continue;
|
|
494
|
+
const to = enumValueOf(v, allowed);
|
|
495
|
+
if (to !== null)
|
|
496
|
+
set(k, to);
|
|
497
|
+
}
|
|
498
|
+
const constraints = out["constraints"];
|
|
499
|
+
if (isRecord(constraints)) {
|
|
500
|
+
const fixed = { ...constraints };
|
|
501
|
+
for (const [k, allowed] of [...CLASS_FIELDS, ["destination_execution", ["AGENT_CAN_EXECUTE", "NONE"]]]) {
|
|
502
|
+
const v = fixed[k];
|
|
503
|
+
if (typeof v !== "string")
|
|
504
|
+
continue;
|
|
505
|
+
const to = enumValueOf(v, allowed);
|
|
506
|
+
if (to !== null && to !== v) {
|
|
507
|
+
normalized.push({ field: `constraints.${k}`, from: v, to });
|
|
508
|
+
fixed[k] = to;
|
|
509
|
+
}
|
|
510
|
+
}
|
|
511
|
+
if (normalized.some((n) => n.field.startsWith("constraints.")))
|
|
512
|
+
out["constraints"] = fixed;
|
|
513
|
+
}
|
|
514
|
+
return { body: normalized.length === 0 ? body : out, normalized };
|
|
515
|
+
}
|
|
516
|
+
const CLASS_FIELDS = [["guarantee_class", ["COMMITTED_ENFORCED", "ANY"]], ["latency_class", ["SECONDS", "MINUTES", "FINALITY_BOUND", "ANY"]]];
|
package/dist/preflight.d.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import type { RectaAsset, RectaNetwork, RectaProvider } from "./names.js";
|
|
1
2
|
/**
|
|
2
3
|
* Recta Preflight (POST https://api.recta.build/v1/preflight): a free, unsigned check before a cross-chain USDC/USDT
|
|
3
4
|
* transfer. It answers the route's total cost and arrival time, and whether Recta proves a cheaper route. No key, no
|
|
@@ -6,19 +7,19 @@
|
|
|
6
7
|
*/
|
|
7
8
|
export declare const PREFLIGHT_PATH = "/v1/preflight";
|
|
8
9
|
/** Sent on every preflight this package makes, so Recta can count use of the wrapper apart from other clients. */
|
|
9
|
-
export declare const PREFLIGHT_USER_AGENT = "recta-client/0.1.
|
|
10
|
+
export declare const PREFLIGHT_USER_AGENT = "recta-client/0.1.14 (preflight)";
|
|
10
11
|
export interface PreflightTransfer {
|
|
11
|
-
/**
|
|
12
|
-
readonly source_network: string;
|
|
13
|
-
/** USDC, USDT… */
|
|
14
|
-
readonly source_asset: string;
|
|
15
|
-
readonly destination_network: string;
|
|
12
|
+
/** Recta's network key (your editor lists them), or any name Recta reads: "Ethereum Mainnet", "BSC", 8453… */
|
|
13
|
+
readonly source_network: RectaNetwork | (string & {});
|
|
14
|
+
/** USDC, USDT… (or "usd coin", "tether"…) */
|
|
15
|
+
readonly source_asset: RectaAsset | (string & {});
|
|
16
|
+
readonly destination_network: RectaNetwork | (string & {});
|
|
16
17
|
/** USDC, USDT… (required by the preflight, even when it is the source asset). */
|
|
17
|
-
readonly destination_asset: string;
|
|
18
|
+
readonly destination_asset: RectaAsset | (string & {});
|
|
18
19
|
/** Whole tokens: "1000" (or 1000) with USDC is 1,000 USDC. */
|
|
19
20
|
readonly amount: string | number | bigint;
|
|
20
|
-
/** The route you would use (
|
|
21
|
-
readonly baseline_provider?: string;
|
|
21
|
+
/** The route you would use (one of RECTA_PROVIDER_KEYS). Absent: LI.FI, or Across where LI.FI does not apply. */
|
|
22
|
+
readonly baseline_provider?: RectaProvider | (string & {});
|
|
22
23
|
/** Your sending address, for the most exact figure. */
|
|
23
24
|
readonly sender?: string;
|
|
24
25
|
readonly recipient?: string;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@recta/client",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.14",
|
|
4
4
|
"description": "Client for Recta (api.recta.build): evaluate a cross-chain stablecoin transfer, authorize Recta's 5 %-of-verified-saving fee, execute the committed route and report it, with local checks before every signature.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"author": "Recta (https://recta.build)",
|