UNPKG

@effectai/sdk

Version:

Effect Network Javscript/Typescript SDK (for [https://effect.network](https://effect.network))

74 lines 2.96 kB
import { APIClient, FetchProvider, } from "@wharfkit/antelope"; import { MemoryCache } from "./cache"; import { IDBCache, createCacheManager } from "./cache"; import { getOrCreateVAccount } from "./actions/vaccount/getOrCreate"; import { EffectSession } from "./session"; import { networks } from "./constants/network"; const defaultClientOpts = { ipfsCacheDurationInMs: 600_000, // 10 minutes }; export class Client { get session() { return this._session; } constructor(network, options) { this._session = null; this.setSession = async (session) => { try { if (!session) { this._session = null; return this._session; } // Get or create the vAccount const account = await getOrCreateVAccount({ client: this, actor: session.actor, session, }); // Only set the session if the vAccount was created successfully this._session = session ? new EffectSession(session, account) : null; return this._session; } catch (e) { console.error(e); throw new Error("Failed to set session"); } }; this.options = { ...defaultClientOpts, ...options }; this.network = network; this.fetchProvider = new FetchProvider(this.network.url, { fetch: this.options.fetchProvider?.fetch, }); this.provider = new APIClient({ provider: this.fetchProvider }); if (this.options.cacheImplementation) { this.cache = createCacheManager(this.options.cacheImplementation); } else if (typeof indexedDB !== "undefined") { this.cache = createCacheManager(new IDBCache()); } else { this.cache = createCacheManager(new MemoryCache()); } } } export const createClient = async ({ network, session, options = {}, }) => { if (!network && !session) { throw new Error("Network or Session configuration is required to create a client."); } // TODO: We should also check that network and session.network are the same if (session) { // if session is given here, retrieve the network from session const chain = networks.find((network) => network.id === session.chain.id.hexString); if (!chain) throw new Error("Chain associated with session not found or not supported."); const client = new Client(chain, options); // automatically set the session whenever the session is provided await client.setSession(session); return client; } if (!network) { throw new Error("Network configuration is required to create a client."); } return new Client(network, options); }; //# sourceMappingURL=client.js.map