Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .agents/skills/vortex-integration/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -497,6 +497,7 @@ const vortex = new VortexSdk({
apiBaseUrl: process.env.VORTEX_API_URL, // sandbox or prod
publicKey: process.env.VORTEX_PUBLIC_KEY, // pk_*
secretKey: process.env.VORTEX_SECRET_KEY, // sk_* — server side only
networkInitializationTimeoutMs: 15_000, // lazy per-network signing RPC timeout
storeEphemeralKeys: true // writes ephemerals_<rampId>.json locally
});
```
Expand Down
3 changes: 2 additions & 1 deletion packages/sdk/ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,8 @@ state or a user's wallet.
- `VortexSdk.ts` is the public orchestrator.
- `services/ApiService.ts` owns HTTP requests and error mapping.
- `services/NetworkManager.ts` owns the RPC connections needed for ephemeral signing and
preflight balance checks.
initializes only the networks required for ephemeral signing. Quote and registration
HTTP calls do not wait for chain WebSockets.
- `handlers/BrlHandler.ts`, `AlfredpayHandler.ts`, and `MykoboHandler.ts` adapt
corridor-specific registration and update data to the common lifecycle.
- `eip712.ts` classifies and attaches signatures for user-owned typed-data operations.
Expand Down
3 changes: 2 additions & 1 deletion packages/sdk/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -205,13 +205,14 @@ interface VortexSdkConfig {
pendulumWsUrl?: string;
moonbeamWsUrl?: string;
hydrationWsUrl?: string;
networkInitializationTimeoutMs?: number;
autoReconnect?: boolean;
alchemyApiKey?: string;
storeEphemeralKeys?: boolean;
}
```

Only the base Vortex API is required. If the RPC URL's are not provided, default public ones will be used.
Only the base Vortex API is required. Chain WebSocket APIs are initialized lazily when returned unsigned transactions require them; quote and registration HTTP requests do not wait for RPC connections. If the RPC URLs are not provided, default public ones are used. `networkInitializationTimeoutMs` defaults to 15 seconds and applies independently to each required network.

### API keys

Expand Down
16 changes: 5 additions & 11 deletions packages/sdk/src/VortexSdk.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,6 @@ export class VortexSdk {
private brlHandler: BrlHandler;
private alfredpayHandler: AlfredpayHandler;
private mykoboHandler: MykoboHandler;
private initializationPromise: Promise<void>;
private storeEphemeralKeys: boolean;

constructor(config: VortexSdkConfig) {
Expand Down Expand Up @@ -87,8 +86,6 @@ export class VortexSdk {
this.generateEphemerals.bind(this),
this.signTransactions.bind(this)
);

this.initializationPromise = this.networkManager.waitForInitialization();
}

async createQuote<T extends CreateQuoteRequest>(request: T): Promise<ExtendedQuoteResponse<T>> {
Expand Down Expand Up @@ -136,8 +133,6 @@ export class VortexSdk {
);
}

await this.ensureInitialized();

let rampProcess: RampProcess;
let unsignedTransactions: UnsignedTx[] = [];

Expand Down Expand Up @@ -354,10 +349,6 @@ export class VortexSdk {
}
}

private async ensureInitialized(): Promise<void> {
await this.initializationPromise;
}

private async generateEphemerals(): Promise<{
ephemerals: { [key in EphemeralAccountType]?: EphemeralAccount };
accountMetas: AccountMeta[];
Expand Down Expand Up @@ -390,7 +381,9 @@ export class VortexSdk {
evmEphemeral?: EphemeralAccount;
}
): Promise<PresignedTx[]> {
await this.ensureInitialized();
if (unsignedTxs.length === 0) {
return [];
}

try {
const signedTxs = await signUnsignedTransactions(
Expand All @@ -412,7 +405,8 @@ export class VortexSdk {

return signedTxs;
} catch (error) {
throw new TransactionSigningError(undefined, error as Error);
const originalError = error instanceof Error ? error : new Error(String(error));
throw new TransactionSigningError(originalError.message, originalError);
}
}
}
16 changes: 16 additions & 0 deletions packages/sdk/src/errors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -384,6 +384,22 @@ export class APINotInitializedError extends VortexSdkInternalError {
}
}

export class NetworkApiInitializationError extends VortexSdkInternalError {
public readonly network: string;
public readonly timeoutMs: number;

constructor(network: string, timeoutMs: number, originalError?: Error) {
const displayName = `${network.charAt(0).toUpperCase()}${network.slice(1)}`;
const message = originalError
? `Failed to initialize ${displayName} WebSocket API: ${originalError.message}`
: `Timed out initializing ${displayName} WebSocket API after ${timeoutMs}ms`;
super(message, originalError);
this.name = "NetworkApiInitializationError";
this.network = network;
this.timeoutMs = timeoutMs;
}
}

export class EphemeralGenerationError extends VortexSdkInternalError {
constructor(network: string, originalError?: Error) {
super(`Failed to generate ephemeral account for network: ${network}`, originalError);
Expand Down
68 changes: 60 additions & 8 deletions packages/sdk/src/services/NetworkManager.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
import { ApiPromise, WsProvider } from "@polkadot/api";
import { Networks } from "@vortexfi/shared";
import { NetworkApiInitializationError } from "../errors";
import type { NetworkConfig, VortexSdkConfig } from "../types";

const DEFAULT_NETWORK_INITIALIZATION_TIMEOUT_MS = 15_000;

const DEFAULT_NETWORKS: NetworkConfig[] = [
{
name: "assethub",
Expand Down Expand Up @@ -31,10 +34,6 @@ export class NetworkManager {

constructor(private readonly config: VortexSdkConfig) {}

async waitForInitialization(): Promise<void> {
return;
}

async getPendulumApi(): Promise<ApiPromise> {
if (this.pendulumApi) {
return this.pendulumApi;
Expand Down Expand Up @@ -105,10 +104,63 @@ export class NetworkManager {
throw new Error(`${network} WebSocket URL must be provided or configured.`);
}

const provider = new WsProvider(wsUrl, 2_500, {}, 60_000, 102400, 10 * 60_000);
const api = await ApiPromise.create({ provider });
await api.isReady;
return api;
const timeoutMs = this.config.networkInitializationTimeoutMs ?? DEFAULT_NETWORK_INITIALIZATION_TIMEOUT_MS;
let provider: WsProvider;
try {
provider = new WsProvider(wsUrl, 2_500, {}, 60_000, 102400, 10 * 60_000);
} catch (error) {
const originalError = error instanceof Error ? error : new Error(String(error));
throw new NetworkApiInitializationError(network, timeoutMs, originalError);
}

let api: ApiPromise | undefined;
let initializationFailed = false;

const initialization = ApiPromise.create({ provider }).then(async createdApi => {
api = createdApi;
await createdApi.isReady;

if (initializationFailed) {
this.disconnect(createdApi, provider);
}

return createdApi;
});

let timeout: ReturnType<typeof setTimeout> | undefined;
try {
return await Promise.race([
initialization,
new Promise<ApiPromise>((_, reject) => {
timeout = setTimeout(() => {
reject(new NetworkApiInitializationError(network, timeoutMs));
}, timeoutMs);
})
]);
} catch (error) {
initializationFailed = true;
this.disconnect(api, provider);

if (error instanceof NetworkApiInitializationError) {
throw error;
}

const originalError = error instanceof Error ? error : new Error(String(error));
throw new NetworkApiInitializationError(network, timeoutMs, originalError);
} finally {
if (timeout) {
clearTimeout(timeout);
}
}
}

private disconnect(api: ApiPromise | undefined, provider: WsProvider): void {
try {
const disconnect = api ? api.disconnect() : provider.disconnect();
void Promise.resolve(disconnect).catch(() => undefined);
} catch {
// Preserve the initialization error; disconnect is best-effort cleanup.
}
}

private getWsUrl(network: Networks.Pendulum | Networks.Moonbeam | Networks.Hydration): string | undefined {
Expand Down
6 changes: 6 additions & 0 deletions packages/sdk/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -238,6 +238,12 @@ export interface VortexSdkConfig {
pendulumWsUrl?: string;
moonbeamWsUrl?: string;
hydrationWsUrl?: string;
/**
* Maximum time to wait when a signing operation first needs a Substrate
* WebSocket API. Chain APIs are initialized lazily and independently.
* @default 15000
*/
networkInitializationTimeoutMs?: number;
autoReconnect?: boolean;
alchemyApiKey?: string;
storeEphemeralKeys?: boolean;
Expand Down
Loading
Loading