dominant-strategies / quais.js

JavaScript library for interacting with Quai Network.
MIT License
2 stars 5 forks source link

[Quais] - Improve implementation of deserialization method on AbstractHDWallet #195

Closed alejoacosta74 closed 2 months ago

alejoacosta74 commented 3 months ago

The current implementation works, but contains a cyclic dependency between base class AbstractHDWallet and its childrens QiHDWallet and QuaiHDWallet:


    static async deserialize<T extends AbstractHDWallet>(
        this: new (root: HDNodeWallet, provider?: Provider) => T,
        serialized: SerializedHDWallet
    ): Promise<QuaiHDWallet|QiHDWallet> {
        if (serialized.version !== (this as any)._version) {
            throw new Error(`Invalid version ${serialized.version} for wallet (expected ${(this as any)._version})`);
        }
        if (serialized.coinType !== (this as any)._coinType) {
            throw new Error(`Invalid coinType ${serialized.coinType} for wallet (expected ${(this as any)._coinType})`);
        }

        const mnemonic = Mnemonic.fromPhrase(serialized.phrase);
        const path = (this as any).parentPath(serialized.coinType);
        const root = HDNodeWallet.fromMnemonic(mnemonic, path );
        const wallet = new this(root, serialized.provider);

        for (const addressInfo of serialized.addresses) {
            wallet._addresses.set(addressInfo.address, addressInfo);
        }

        for (const address of serialized.addresses) {
            if (!wallet._accounts.has(address.account)) {
                wallet.addAccount(address.account);
            }
        }

        return wallet as T;
    }