All files / src kit.ts

77.77% Statements 224/288
72.61% Branches 122/168
87.5% Functions 42/48
77.37% Lines 212/274

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895357x                 1x               1x 1x 1x               1x 1x   1x           1x 1x 1x                                                                                                                                           1x 132x 132x   132x 132x   132x         132x     132x           132x   610x   132x   132x   132x 132x         132x 1x   132x 2x     132x 1x     132x     132x   132x 132x         132x 4x   128x     132x 2x   132x 3x   132x 2x     132x 1x     132x 1x       132x         132x 4x         4x 2x   4x 14x   4x 2x           2x 2x                         2x 2x 2x 2x     2x 2x       172x 172x 242x 172x 2x   170x                   55x       54x 54x 1x   53x       54x 54x 53x   54x                                                                                                                                                                                                                                                                                                   71x 71x 73x       71x           7x           73x                   71x     71x 71x 69x 69x 69x 2x               71x 69x       69x       71x 33x     33x   32x 38x 5x 5x   33x       70x 46x 46x       70x             35x     35x 35x     35x 1x       34x   35x             34x       34x 34x       69x         69x 69x           2x           67x     67x     67x                   67x     67x     67x           67x     67x           4x 4x         3x             3x                                             70x     70x   9x   9x 1x     9x   9x 9x 4x       9x 9x 15x 8x     61x   61x 61x   25x 25x             61x 61x                 7x 7x 5x                       9x     9x 9x 5x 5x 11x             9x                   27x   27x 1x         26x                   27x                       26x 1x     26x             16x       16x 14x   13x         13x           5x 13x             105x         105x     105x   105x   105x 99x       105x 105x 105x   83x   51x 20x   51x           105x 71x 71x 71x 71x     105x               95x     95x 95x 57x 57x               81x       93x                                         1x       81x           1x     9x             4x                         2x 104x    
import {ChainDefinition, type ChainDefinitionType, type Fetch} from '@wharfkit/common'
import type {Contract} from '@wharfkit/contract'
import {
    Checksum256,
    Checksum256Type,
    Name,
    NameType,
    PermissionLevel,
    PermissionLevelType,
} from '@wharfkit/antelope'
 
import {
    AbstractLoginPlugin,
    BaseLoginPlugin,
    LoginContext,
    LoginPlugin,
    UserInterfaceWalletPlugin,
} from './login'
import {PartialSerializedSession, SerializedSession, Session, SessionType} from './session'
import {BrowserLocalStorage, SessionStorage} from './storage'
import {
    AbstractTransactPlugin,
    BaseTransactPlugin,
    BroadcastOptions,
    TransactABIDef,
    TransactPlugin,
    TransactPluginsOptions,
} from './transact'
import {WalletPlugin, WalletPluginLoginResponse, WalletPluginMetadata} from './wallet'
import {UserInterface} from './ui'
import {getFetch, getPluginTranslations} from './utils'
import {
    AccountCreationPlugin,
    CreateAccountContext,
    CreateAccountOptions,
    CreateAccountResponse,
} from './account-creation'
import {SessionKeyManager} from './sessionkey/manager'
import {SessionKeyWalletPlugin} from './sessionkey/wallet'
import {SessionKeyConfig} from './sessionkey/types'
 
export interface LoginOptions {
    arbitrary?: Record<string, any> // Arbitrary data that will be passed via context to wallet plugin
    chain?: ChainDefinition | Checksum256Type
    chains?: Checksum256Type[]
    equalityFn?: SerializedSessionEqualityFn
    loginPlugins?: LoginPlugin[]
    setAsDefault?: boolean
    transactPlugins?: TransactPlugin[]
    transactPluginsOptions?: TransactPluginsOptions
    permissionLevel?: PermissionLevelType | string
    walletPlugin?: string
}
 
export interface LoginResult {
    context: LoginContext
    response: WalletPluginLoginResponse
    session: Session
}
 
export interface LogoutContext {
    session: Session
    appName: string
    ui?: UserInterface
}
 
export interface LogoutOptions {
    equalityFn?: SerializedSessionEqualityFn
}
 
/**
 * A predicate deciding whether two sessions refer to the same thing, used to
 * deduplicate sessions in storage and to select which session a logout removes.
 */
export type SerializedSessionEqualityFn = (a: SessionType, b: SessionType) => boolean
 
export interface PersistOptions {
    setAsDefault?: boolean
    equalityFn?: SerializedSessionEqualityFn
}
 
export interface SessionKitArgs {
    appName: NameType
    chains: ChainDefinitionType[]
    ui: UserInterface
    walletPlugins: WalletPlugin[]
}
 
export interface SessionKitOptions {
    abis?: TransactABIDef[]
    allowModify?: boolean
    contracts?: Contract[]
    equalityFn?: SerializedSessionEqualityFn
    expireSeconds?: number
    fetch?: Fetch
    loginPlugins?: LoginPlugin[]
    storage?: SessionStorage
    transactPlugins?: TransactPlugin[]
    transactPluginsOptions?: TransactPluginsOptions
    awaitIrreversible?: boolean
    broadcastOptions?: BroadcastOptions
    accountCreationPlugins?: AccountCreationPlugin[]
    sessionKey?: SessionKeyConfig
}
 
/**
 * Request a session from an account.
 */
export class SessionKit {
    readonly abis: TransactABIDef[] = []
    readonly allowModify: boolean = true
    readonly appName: string
    readonly equalityFn: SerializedSessionEqualityFn = serializedSessionEquals
    readonly awaitIrreversible: boolean = false
    readonly broadcastOptions?: BroadcastOptions
    readonly expireSeconds: number = 120
    readonly fetch: Fetch
    readonly loginPlugins: AbstractLoginPlugin[]
    readonly storage: SessionStorage
    readonly transactPlugins: AbstractTransactPlugin[]
    readonly transactPluginsOptions: TransactPluginsOptions = {}
    readonly ui: UserInterface
    readonly walletPlugins: WalletPlugin[]
    readonly accountCreationPlugins: AccountCreationPlugin[] = []
    readonly sessionKeyManager?: SessionKeyManager
    public chains: ChainDefinition[]
 
    constructor(args: SessionKitArgs, options: SessionKitOptions = {}) {
        // Save the appName to the SessionKit instance
        this.appName = String(args.appName)
        // Map the chains provided to ChainDefinition instances
        this.chains = args.chains.map((chain) => ChainDefinition.from(chain))
        // Save the UserInterface instance to the SessionKit
        this.ui = args.ui
        // Establish default plugins for wallet flow
        this.walletPlugins = args.walletPlugins
        // Override fetch if provided
        if (options.fetch) {
            this.fetch = options.fetch
        } else E{
            this.fetch = getFetch(options)
        }
        // Add any ABIs manually provided
        if (options.abis) {
            this.abis = [...options.abis]
        }
        if (options.equalityFn) {
            this.equalityFn = options.equalityFn
        }
        // Extract any ABIs from the Contract instances provided
        if (options.contracts) {
            this.abis.push(...options.contracts.map((c) => ({account: c.account, abi: c.abi})))
        }
        // Establish default plugins for login flow
        Iif (options.loginPlugins) {
            this.loginPlugins = options.loginPlugins
        } else {
            this.loginPlugins = [new BaseLoginPlugin()]
        }
        if (options.storage) {
            this.storage = options.storage
        } else E{
            this.storage = new BrowserLocalStorage()
        }
        // Establish default plugins for transact flow
        if (options.transactPlugins) {
            this.transactPlugins = options.transactPlugins
        } else {
            this.transactPlugins = [new BaseTransactPlugin()]
        }
        // Store options passed on the kit
        if (typeof options.allowModify !== 'undefined') {
            this.allowModify = options.allowModify
        }
        if (options.awaitIrreversible !== undefined) {
            this.awaitIrreversible = options.awaitIrreversible
        }
        if (options.broadcastOptions !== undefined) {
            this.broadcastOptions = options.broadcastOptions
        }
        // Override default expireSeconds for all sessions if specified
        if (options.expireSeconds) {
            this.expireSeconds = options.expireSeconds
        }
        // Establish default options for transact plugins
        if (options.transactPluginsOptions) {
            this.transactPluginsOptions = options.transactPluginsOptions
        }
 
        // Establish default plugins for account creation
        Iif (options.accountCreationPlugins) {
            this.accountCreationPlugins = options.accountCreationPlugins
        }
 
        // Initialize session key support if configured
        if (options.sessionKey) {
            const requiredHooks = [
                'onSessionKeyConflict',
                'onSessionKeyMismatch',
                'onSessionKeyRemove',
            ]
            if (!options.sessionKey.skipConsent) {
                requiredHooks.push('onSessionKeyConsent')
            }
            const missing = requiredHooks.filter(
                (hook) => typeof (this.ui as any)[hook] !== 'function'
            )
            if (missing.length > 0) {
                throw new Error(
                    `Session keys require a UserInterface implementing: ${missing.join(
                        ', '
                    )}. The provided UserInterface does not support session keys.`
                )
            }
            this.sessionKeyManager = new SessionKeyManager(options.sessionKey, this.ui)
            this.walletPlugins = [
                ...this.walletPlugins,
                new SessionKeyWalletPlugin({
                    walletPlugins: this.walletPlugins,
                }),
            ]
        }
    }
 
    /**
     * Alters the session kit config for a specific chain to change the API endpoint in use
     */
    setEndpoint(id: Checksum256Type, url: string) {
        const modifiedChains = [...this.chains]
        const chainId = Checksum256.from(id)
        const chainIndex = this.chains.findIndex((c) => c.id.equals(chainId))
        Iif (chainIndex < 0) {
            throw new Error('Chain with specified ID not found.')
        }
        modifiedChains[chainIndex].url = url
        this.chains = modifiedChains
    }
 
    getChainDefinition(id: Checksum256Type, override?: ChainDefinition[]): ChainDefinition {
        const chains = override ? override : this.chains
        const chainId = Checksum256.from(id)
        const chain = chains.find((c) => c.id.equals(chainId))
        if (!chain) {
            throw new Error(`No chain defined with an ID of: ${chainId}`)
        }
        return chain
    }
 
    /**
     * Find a wallet plugin by its ID.
     *
     * @param id The wallet plugin ID to search for
     * @returns The wallet plugin if found, undefined otherwise
     */
    getWalletPlugin(id: string): WalletPlugin | undefined {
        return this.walletPlugins.find((plugin) => plugin.id === id)
    }
 
    private cloneWalletPlugin(id: string): WalletPlugin | undefined {
        const registered = this.getWalletPlugin(id)
        if (!registered) {
            return undefined
        }
        return registered.clone ? registered.clone() : registered
    }
 
    private walletPluginFor(serializedSession: SerializedSession): WalletPlugin | undefined {
        const walletPlugin = this.cloneWalletPlugin(serializedSession.walletPlugin.id)
        if (walletPlugin && serializedSession.walletPlugin.data) {
            walletPlugin.data = serializedSession.walletPlugin.data
        }
        return walletPlugin
    }
 
    /**
     * Request account creation.
     */
    async createAccount(options?: CreateAccountOptions): Promise<CreateAccountResponse> {
        try {
            Iif (this.accountCreationPlugins.length === 0) {
                throw new Error('No account creation plugins available.')
            }
 
            // Eestablish defaults based on options
            let chain = options?.chain
            let requiresChainSelect = !chain
            let requiresPluginSelect = !options?.pluginId
 
            let accountCreationPlugin: AccountCreationPlugin | undefined
 
            // Developer specified a plugin during createAccount call
            Iif (options?.pluginId) {
                requiresPluginSelect = false
 
                // Find the plugin
                accountCreationPlugin = this.accountCreationPlugins.find(
                    (p) => p.id === options.pluginId
                )
 
                // Ensure the plugin exists
                Iif (!accountCreationPlugin) {
                    throw new Error('Invalid account creation plugin selected.')
                }
 
                // Override the chain selection requirement based on the plugin
                Iif (accountCreationPlugin?.config.requiresChainSelect !== undefined) {
                    requiresChainSelect = accountCreationPlugin?.config.requiresChainSelect
                }
 
                // If the plugin does not require chain select and has one supported chain, set it as the default
                Iif (
                    !accountCreationPlugin.config.requiresChainSelect &&
                    accountCreationPlugin.config.supportedChains &&
                    accountCreationPlugin.config.supportedChains.length === 1
                ) {
                    chain = accountCreationPlugin.config.supportedChains[0]
                }
            }
 
            // The chains available to select from, based on the Session Kit
            let chains = this.chains
 
            // If a plugin is selected, filter the chains available down to only the ones supported by the plugin
            Iif (accountCreationPlugin && accountCreationPlugin?.config.supportedChains?.length) {
                chains = chains.filter((availableChain) => {
                    return accountCreationPlugin?.config.supportedChains?.find((c) => {
                        return c.id.equals(availableChain.id)
                    })
                })
            }
 
            const context = new CreateAccountContext({
                accountCreationPlugins: this.accountCreationPlugins,
                appName: this.appName,
                chain,
                chains,
                fetch: this.fetch,
                ui: this.ui,
                uiRequirements: {
                    requiresChainSelect,
                    requiresPluginSelect,
                },
            })
 
            // If UI interaction is required before triggering the plugin
            Iif (requiresPluginSelect || requiresChainSelect) {
                // Call the UI with the context
                const response = await context.ui.onAccountCreate(context)
 
                // Set pluginId based on options first, then response
                const pluginId = options?.pluginId || response.pluginId
 
                // Ensure we have a pluginId
                Iif (!pluginId) {
                    throw new Error('No account creation plugin selected.')
                }
 
                // Determine plugin selected based on response
                accountCreationPlugin = context.accountCreationPlugins.find(
                    (p) => p.id === pluginId
                )
                Iif (!accountCreationPlugin) {
                    throw new Error('No account creation plugin selected.')
                }
 
                // If the plugin does not require chain select and has one supported chain, set it as the default
                Iif (
                    !accountCreationPlugin.config.requiresChainSelect &&
                    accountCreationPlugin.config.supportedChains &&
                    accountCreationPlugin.config.supportedChains.length === 1
                ) {
                    context.chain = accountCreationPlugin.config.supportedChains[0]
                }
 
                // Set chain based on response
                Iif (response.chain) {
                    context.chain = this.getChainDefinition(response.chain, context.chains)
                }
 
                // Ensure a chain was selected and is supported by the plugin
                Iif (accountCreationPlugin.config.requiresChainSelect && !context.chain) {
                    throw new Error(
                        `Account creation plugin (${pluginId}) requires chain selection, and no chain was selected.`
                    )
                }
            }
 
            // Ensure a plugin was selected
            Iif (!accountCreationPlugin) {
                throw new Error('No account creation plugin selected')
            }
 
            // Call the account creation plugin with the context
            const accountCreationData = await accountCreationPlugin.create(context)
 
            // Notify the UI we're done
            await context.ui.onAccountCreateComplete()
 
            // Return the data
            return accountCreationData
        } catch (error: any) {
            await this.ui.onError(error)
            throw new Error(error)
        }
    }
 
    /**
     * Request a session from an account.
     *
     * @mermaid - Login sequence diagram
     * flowchart LR
     *   A((Login)) --> B{{"Hook(s): beforeLogin"}}
     *   B --> C[Wallet Plugin]
     *   C --> D{{"Hook(s): afterLogin"}}
     *   D --> E[Session]
     */
    async login(options?: LoginOptions): Promise<LoginResult> {
        try {
            const selectableWalletPlugins = this.walletPlugins.filter(
                (plugin) => plugin.id !== 'session-key-wallet'
            )
 
            // Create LoginContext for this login request.
            const context = new LoginContext({
                appName: this.appName,
                arbitrary: options?.arbitrary || {},
                chain: undefined,
                chains:
                    options && options?.chains
                        ? options.chains.map((c) => this.getChainDefinition(c))
                        : this.chains,
                fetch: this.fetch,
                loginPlugins: this.loginPlugins,
                ui: this.ui,
                walletPlugins: selectableWalletPlugins.map((plugin): UserInterfaceWalletPlugin => {
                    return {
                        config: plugin.config,
                        metadata: WalletPluginMetadata.from(plugin.metadata),
                        retrievePublicKey: plugin.retrievePublicKey?.bind(plugin),
                    }
                }),
                sessionKeyManager: this.sessionKeyManager,
            })
 
            // Tell the UI a login request is beginning.
            await context.ui.onLogin()
 
            // Predetermine WalletPlugin (if possible) to prevent uneeded UI interactions.
            let walletPlugin: WalletPlugin | undefined = undefined
            if (selectableWalletPlugins.length === 1) {
                walletPlugin = selectableWalletPlugins[0] // Default to first when only one.
                context.walletPluginIndex = this.walletPlugins.indexOf(walletPlugin)
                context.uiRequirements.requiresWalletSelect = false
            I} else if (options?.walletPlugin) {
                walletPlugin = this.getWalletPlugin(options.walletPlugin)
                Iif (walletPlugin) {
                    context.walletPluginIndex = this.walletPlugins.indexOf(walletPlugin)
                    context.uiRequirements.requiresWalletSelect = false
                }
            }
            // Set any uiRequirement overrides from the wallet plugin
            if (walletPlugin) {
                context.uiRequirements = {
                    ...context.uiRequirements,
                    ...walletPlugin.config,
                }
                context.ui.addTranslations(getPluginTranslations(walletPlugin))
            }
 
            // Predetermine chain (if possible) to prevent uneeded UI interactions.
            if (options && options.chain) {
                Iif (options.chain instanceof ChainDefinition) {
                    context.chain = options.chain
                } else {
                    context.chain = this.getChainDefinition(options.chain, context.chains)
                }
                context.uiRequirements.requiresChainSelect = false
            } else if (context.chains.length === 1) {
                context.chain = context.chains[0]
                context.uiRequirements.requiresChainSelect = false
            } else {
                context.uiRequirements.requiresChainSelect = true
            }
 
            // Predetermine permission (if possible) to prevent uneeded UI interactions.
            if (options?.permissionLevel) {
                context.permissionLevel = PermissionLevel.from(options.permissionLevel)
                context.uiRequirements.requiresPermissionSelect = false
            }
 
            // Determine if the login process requires any user interaction.
            if (
                context.uiRequirements.requiresChainSelect ||
                context.uiRequirements.requiresPermissionSelect ||
                context.uiRequirements.requiresPermissionEntry ||
                context.uiRequirements.requiresWalletSelect
            ) {
                // Perform UserInterface.login() flow to get determine the chain, permission, and WalletPlugin.
                const uiLoginResponse = await context.ui.login(context)
 
                // Attempt to set the current WalletPlugin to the index the UI requested
                if (uiLoginResponse.walletPluginIndex !== undefined) {
                    walletPlugin = this.walletPlugins[uiLoginResponse.walletPluginIndex]
                }
 
                if (!walletPlugin) {
                    throw new Error('UserInterface did not return a valid WalletPlugin index.')
                }
 
                // Attempt to set the current chain to match the UI response
                if (uiLoginResponse.chainId) {
                    // Ensure the chain ID returned by the UI is in the list of chains
                    Iif (!context.chains.some((c) => c.id.equals(uiLoginResponse.chainId!))) {
                        throw new Error(
                            'UserInterface did not return a chain ID matching the subset of chains.'
                        )
                    }
 
                    // Set the context.chain definition from the new chain ID
                    context.chain = this.getChainDefinition(uiLoginResponse.chainId, context.chains)
                }
 
                // Set the PermissionLevel from the UI response to the context
                if (uiLoginResponse.permissionLevel) {
                    context.permissionLevel = PermissionLevel.from(uiLoginResponse.permissionLevel)
                }
            }
 
            Iif (!walletPlugin) {
                throw new Error('No WalletPlugin available to perform the login.')
            }
 
            // Ensure the wallet plugin supports the chain that was selected
            const {supportedChains} = walletPlugin.config
            if (
                context.chain &&
                supportedChains &&
                supportedChains.length &&
                !supportedChains.includes(String(context.chain.id))
            ) {
                throw new Error(
                    `The wallet plugin '${walletPlugin.metadata.name}' does not support the chain '${context.chain.id}'`
                )
            }
 
            // Call the `beforeLogin` hooks that were registered by the LoginPlugins
            for (const hook of context.hooks.beforeLogin) await hook(context)
 
            // Perform the login request against the selected walletPlugin
            const response: WalletPluginLoginResponse = await walletPlugin.login(context)
 
            // Create a session from the resulting login response
            const session = new Session(
                {
                    chain: this.getChainDefinition(response.chain),
                    permissionLevel: response.permissionLevel,
                    walletPlugin,
                },
                this.getSessionOptions(options)
            )
 
            // Make session available to afterLogin hooks
            context.session = session
 
            // Call the `afterLogin` hooks that were registered by the LoginPlugins
            for (const hook of context.hooks.afterLogin) await hook(context)
 
            // Save the session to storage if it has a storage instance.
            await this.persistSession(session, {
                setAsDefault: options?.setAsDefault,
                equalityFn: options?.equalityFn,
            })
 
            // Notify the UI that the login request has completed.
            await context.ui.onLoginComplete()
 
            // Return the results of the login request.
            return {
                context,
                response,
                session,
            }
        } catch (error: any) {
            await this.ui.onError(error)
            throw new Error(error)
        }
    }
 
    logoutParams(session: SessionType, walletPlugin: WalletPlugin): LogoutContext {
        Iif (session instanceof Session) {
            return {
                session,
                appName: this.appName,
                ui: this.ui,
            }
        } else {
            return {
                session: new Session({
                    chain: this.getChainDefinition(session.chain),
                    permissionLevel: PermissionLevel.from({
                        actor: session.actor,
                        permission: session.permission,
                    }),
                    walletPlugin,
                }),
                appName: this.appName,
                ui: this.ui,
            }
        }
    }
 
    /**
     * Log a session out, or every session when none is named.
     *
     * Logging out a session affects only that session: other sessions keep their
     * `default` flags, and the default `session` key is cleared only when it held
     * the session being logged out. Nothing is promoted in its place.
     */
    async logout(session?: SessionType, options: LogoutOptions = {}) {
        Iif (!this.storage) {
            throw new Error('An instance of Storage must be provided to utilize the logout method.')
        }
        if (session) {
            const walletPlugin =
                session instanceof Session ? session.walletPlugin : this.walletPluginFor(session)
 
            if (walletPlugin?.logout) {
                await walletPlugin.logout(this.logoutParams(session, walletPlugin))
            }
 
            const equalityFn = options.equalityFn || this.equalityFn
 
            const current = await this.storage.read('session')
            if (current && equalityFn(JSON.parse(current), session)) {
                await this.storage.remove('session')
            }
 
            // Every session, not getSessions(): its plugin filter would drop unregistered ones here
            const sessions = await this.readAllSessions()
            if (sessions.length) {
                const other = sessions.filter((s) => !equalityFn(s, session))
                await this.storage.write('sessions', JSON.stringify(other))
            }
        } else {
            const sessions = await this.getSessions()
 
            if (sessions) {
                await Promise.allSettled(
                    sessions.map((s) => {
                        const walletPlugin = this.walletPluginFor(s)
                        return walletPlugin?.logout
                            ? walletPlugin.logout(this.logoutParams(s, walletPlugin))
                            : Promise.resolve()
                    })
                )
            }
 
            await this.storage.remove('session')
            await this.storage.remove('sessions')
        }
    }
 
    /**
     * Find the session to restore when the caller named none: the default
     * session in storage.
     */
    private async restoreWithoutArgs(): Promise<SerializedSession | undefined> {
        const data = await this.storage.read('session')
        if (data) {
            return JSON.parse(data)
        }
    }
 
    /**
     * Find the session to restore from the arguments given: the arguments
     * themselves when they fully specify a session, otherwise the default
     * session in storage for the named chain.
     */
    private async restoreWithArgs(
        args: PartialSerializedSession
    ): Promise<SerializedSession | undefined> {
        const chainId = Checksum256.from(
            args.chain instanceof ChainDefinition ? args.chain.id : args.chain
        )
        let serializedSession = upgradePossibleSerializedSession({...args, chain: chainId})
        if (!serializedSession) {
            const sessions = await this.readAllSessions()
            serializedSession = sessions.find((s) =>
                args.actor && args.permission
                    ? chainId.equals(s.chain) &&
                      Name.from(s.actor).equals(args.actor) &&
                      Name.from(s.permission).equals(args.permission)
                    : chainId.equals(s.chain) && s.default
            )
        }
        return serializedSession
    }
 
    /**
     * Resolve the wallet plugin a serialized session names, loaded with that
     * session's wallet data.
     *
     * @throws Error if no wallet plugin with that ID is registered
     */
    private getWalletPluginFromSerialized(serializedSession: SerializedSession): WalletPlugin {
        const walletPlugin = this.walletPluginFor(serializedSession)
 
        if (!walletPlugin) {
            throw new Error(
                `No WalletPlugin found with the ID of: '${serializedSession.walletPlugin.id}'`
            )
        }
 
        return walletPlugin
    }
 
    /**
     * Build a live [[Session]] from serialized session data.
     */
    private serializedToSession(
        serializedSession: SerializedSession,
        options: LoginOptions = {}
    ): Session {
        const session = new Session(
            {
                chain: this.getChainDefinition(serializedSession.chain),
                permissionLevel: PermissionLevel.from({
                    actor: serializedSession.actor,
                    permission: serializedSession.permission,
                }),
                walletPlugin: this.getWalletPluginFromSerialized(serializedSession),
            },
            this.getSessionOptions(options)
        )
 
        if (serializedSession.data) {
            session.data = serializedSession.data
        }
 
        return session
    }
 
    async restore(
        args?: PartialSerializedSession,
        options?: LoginOptions
    ): Promise<Session | undefined> {
        const serializedSession = args
            ? await this.restoreWithArgs(args)
            : await this.restoreWithoutArgs()
 
        if (serializedSession) {
            const session = this.serializedToSession(serializedSession, options)
 
            await this.persistSession(session, {
                setAsDefault: options?.setAsDefault,
                equalityFn: options?.equalityFn,
            })
 
            return session
        }
    }
 
    /** Build a live session for every stored session with a registered wallet plugin. Reads storage without writing to it. */
    async restoreAll(): Promise<Session[]> {
        const serializedSessions = await this.getSessions()
        return serializedSessions.map((s) => this.serializedToSession(s))
    }
 
    async persistSession(session: Session, options: PersistOptions = {}) {
        // TODO: Allow disabling of session persistence via kit options
 
        // If no storage exists, do nothing.
        Iif (!this.storage) {
            return
        }
 
        // Serialize session passed in
        const serialized = session.serialize()
 
        // Specify whether or not this is now the default for the given chain
        serialized.default = options.setAsDefault ?? true
 
        const equalityFn = options.equalityFn || this.equalityFn
 
        if (serialized.default) {
            await this.storage.write('session', JSON.stringify(serialized))
        }
 
        // Add the current session to the list of sessions, preventing duplication.
        const existing = await this.storage.read('sessions')
        const stored: SerializedSession[] = existing ? JSON.parse(existing) : []
        const orderedSessions = [
            ...stored
                .filter((s) => !equalityFn(s, serialized))
                .map((s): SerializedSession => {
                    if (serialized.default && session.chain.id.equals(s.chain)) {
                        s.default = false
                    }
                    return s
                }),
            serialized,
        ]
 
        // Sort sessions by chain, actor, and permission
        orderedSessions.sort((a: SerializedSession, b: SerializedSession) => {
            const chain = String(a.chain).localeCompare(String(b.chain))
            const actor = String(a.actor).localeCompare(String(b.actor))
            const permission = String(a.permission).localeCompare(String(b.permission))
            return chain || actor || permission
        })
 
        await this.storage.write('sessions', JSON.stringify(orderedSessions))
    }
 
    /**
     * Read every session held in storage, including those whose wallet plugin is
     * not registered with this kit.
     */
    private async readAllSessions(): Promise<SerializedSession[]> {
        Iif (!this.storage) {
            throw new Error('No storage instance is available to retrieve sessions from.')
        }
        const data = await this.storage.read('sessions')
        if (!data) return []
        try {
            return JSON.parse(data)
        } catch (e) {
            throw new Error(`Failed to parse sessions from storage (${e})`)
        }
    }
 
    async getSessions(): Promise<SerializedSession[]> {
        // Only return sessions that have a wallet plugin that is currently registered.
        return getSessionsMatchingWalletPlugins(await this.readAllSessions(), this.walletPlugins)
    }
 
    getSessionOptions(options?: LoginOptions) {
        return {
            abis: this.abis,
            allowModify: this.allowModify,
            appName: this.appName,
            expireSeconds: this.expireSeconds,
            fetch: this.fetch,
            storage: this.storage,
            transactPlugins: options?.transactPlugins || this.transactPlugins,
            transactPluginsOptions: options?.transactPluginsOptions || this.transactPluginsOptions,
            awaitIrreversible: this.awaitIrreversible,
            broadcastOptions: this.broadcastOptions,
            ui: this.ui,
            sessionKeyManager: this.sessionKeyManager,
            onPersist: (session: Session) => this.persistSession(session),
        }
    }
}
 
/**
 * Filter a list of serialized sessions down to those whose wallet plugin is registered.
 */
export function getSessionsMatchingWalletPlugins(
    sessions: SerializedSession[],
    walletPlugins: WalletPlugin[]
) {
    return sessions.filter((s) => walletPlugins.some((p) => p.id === s.walletPlugin.id))
}
 
/**
 * Promote a partially specified session to a full one, when it carries every required field.
 */
export function upgradePossibleSerializedSession(
    possible: PartialSerializedSession | undefined
): SerializedSession | undefined {
    if (
        possible &&
        possible.actor !== undefined &&
        possible.chain !== undefined &&
        possible.permission !== undefined &&
        possible.walletPlugin !== undefined
    ) {
        return {
            actor: possible.actor,
            chain: possible.chain instanceof ChainDefinition ? possible.chain.id : possible.chain,
            permission: possible.permission,
            walletPlugin: possible.walletPlugin,
            data: possible.data,
        }
    }
}
 
/**
 * The default [[SerializedSessionEqualityFn]], matching on chain, actor and permission.
 */
export function serializedSessionEquals(a: SessionType, b: SessionType): boolean {
    return Session.matches(a, b)
}