How to create, import and open a wallet

Describes how to create or open a wallet

  /**
   * Creates a wallet account
   * @param accountName Account name
   * @param passphrase Passphrase
   */
  async createAccount(accountName: string, passphrase: string) {
  // Set isWeb for browser usage
    const xdvWallet = new Wallet({ isWeb: true })
    
    // Unlocks wallet
    await xdvWallet.open(accountName, passphrase)
    
    // Will be deprecated, enrolls account in DB
    await xdvWallet.enrollAccount({
      passphrase,
      accountName,
    })
  }

  /**
   * Creates a wallet
   * @param accountName Account name
   * @param passphrase Passphrase
   * @returns
   */
  async createWallet(accountName: string, passphrase: string) {
    const xdvWallet = new Wallet({ isWeb: true })
    await xdvWallet.open(accountName, passphrase)

    // Gets account, if null, user needs to enroll
    const acct = (await xdvWallet.getAccount()) as any
    let walletId

    if (acct.keystores.length === 0) {
      // Adds a wallet. 
      walletId = await xdvWallet.addWallet()
    } else {
      // Gets first wallet 
      walletId = acct.keystores[0].walletId
    }

    // Creates a wallet based on crypto suite
    const wallet = await xdvWallet.createEd25519({
      passphrase: passphrase,
      walletId: walletId,
    })

    return wallet as any
  }

  /**
   * Imports an existing seed phrase
   * @param accountName Account name
   * @param passphrase Passphrase
   * @param mnemonic Seed phrase
   * @returns
   */
  async importWallet(
    accountName: string,
    passphrase: string,
    mnemonic: string,
  ) {
    const xdvWallet = new Wallet({ isWeb: true })
    await xdvWallet.open(accountName, passphrase)

    const acct = (await xdvWallet.getAccount()) as any

    if (acct.keystores.length > 0) {
      // already imported
      return xdvWallet
    }

    // Import wallet using existing mnemonic
    const walletId = await xdvWallet.addWallet({
      mnemonic,
    })

    const wallet = await xdvWallet.createEd25519({
      passphrase: passphrase,
      walletId: walletId,
    })

    return wallet as any
  }

Last updated