UNPKG

@ponziland/account

Version:

Account management library for Starknet with wallet modal and connection state

87 lines (86 loc) 2.55 kB
import { getContext, onMount, setContext } from 'svelte'; import Controller, {} from '@cartridge/controller'; import {} from '../consts.js'; export class SvelteController extends Controller { _account; _username; async connect() { // If the user is already logged in, return the existing account if (this._account) { return this._account; } try { // This is a temporary fix for the type mismatch due to different versions of starknet.js const res = (await super.connect()); if (res) { this._account = res; this._username = await super.username(); console.info(`User ${this.getUsername()} has logged in successfully!\nAddress; ${this._account?.address}`); return res; } else { throw 'Empty response!'; } } catch (e) { console.error(e); } } async setupSession() { // no-op } async loadSession(storage) { // no-op } getWalletAccount() { return this.getAccount(); } supportsSession() { return true; } async disconnect() { this._account = undefined; this._username = undefined; await super.disconnect(); } getAccount() { return this._account; } getUsername() { return this._username; } } const accountKey = Symbol('controller'); export async function connect(controller) { } function a2hex(str) { var arr = []; for (var i = 0, l = str.length; i < l; i++) { var hex = Number(str.charCodeAt(i)).toString(16); arr.push(hex); } return '0x' + arr.join(''); } export async function setupController(config) { if (typeof window === 'undefined') { // We are on the server. Return nothing. return undefined; } const controllerOptions = { defaultChainId: config.chainId === 'mainnet' ? a2hex('SN_MAIN') : a2hex('SN_SEPOLIA'), chains: [{ rpcUrl: config.rpcUrl }], }; // Only add policies if provided if (config.policies) { controllerOptions.policies = config.policies; } else { controllerOptions.policies = {}; } const controller = new SvelteController(controllerOptions); console.info('Starting controller!'); // Check if the controller is already connected if (await controller.probe()) { await controller.connect(); } return controller; }