@moonwell-fi/moonwell-sdk
Version:
TypeScript Interface for Moonwell
164 lines (156 loc) • 4 kB
text/typescript
import type { Narrow, Prettify } from "viem";
import {
type ArbitrumEnvironment,
type AvalancheEnvironment,
type BaseEnvironment,
type Environment,
type EthereumEnvironment,
type MoonbeamEnvironment,
type MoonriverEnvironment,
type OptimismEnvironment,
type PolygonEnvironment,
type SupportedChains,
arbitrum,
avalanche,
base,
createEnvironment,
ethereum,
moonbeam,
moonriver,
optimism,
polygon,
} from "../environments/index.js";
import { actions } from "./createActions.js";
export type MoonwellClient<
environments = { [name in SupportedChains]?: Environment },
> = {
environments: Prettify<
{
[]: BaseEnvironment;
} & {
[]: OptimismEnvironment;
} & {
[]: MoonbeamEnvironment;
} & {
[]: MoonriverEnvironment;
} & {
[]: EthereumEnvironment;
} & {
[]: AvalancheEnvironment;
} & {
[]: ArbitrumEnvironment;
} & {
[]: PolygonEnvironment;
}
>;
};
export type NetworkConfig = {
rpcUrls: string[];
};
export type NetworksConfig<networks> = {} extends networks
? {}
: { [name in SupportedChains]?: NetworkConfig };
export const createMoonwellClient = <const networks>(config: {
networks: NetworksConfig<Narrow<networks>>;
onError?: (
error: unknown,
context: { source: string; chainId: number },
) => void;
}) => {
const environments = Object.entries(
config.networks as NetworksConfig<SupportedChains>,
).reduce((prev, [curr, networkConfig]) => {
if (!networkConfig) return prev;
return {
...prev,
[]: createEnvironment({
chain:
curr === "base"
? base
: curr === "optimism"
? optimism
: curr === "moonbeam"
? moonbeam
: curr === "moonriver"
? moonriver
: curr === "ethereum"
? ethereum
: curr === "avalanche"
? avalanche
: curr === "arbitrum"
? arbitrum
: polygon,
rpcUrls: networkConfig.rpcUrls,
}),
};
}, {}) as Prettify<
{
[]: BaseEnvironment;
} & {
[]: OptimismEnvironment;
} & {
[]: MoonbeamEnvironment;
} & {
[]: MoonriverEnvironment;
} & {
[]: EthereumEnvironment;
} & {
[]: AvalancheEnvironment;
} & {
[]: ArbitrumEnvironment;
} & {
[]: PolygonEnvironment;
}
>;
if (config.onError) {
const onError = config.onError;
for (const env of Object.values(
environments as Record<string, Environment>,
)) {
env.onError = onError;
}
}
const client = {
environments,
};
return Object.assign(client, actions<typeof environments>(client as any));
};