Skip to content
by Unity Nodes
Development

Retrieve all wallet addresses from public key

1 posts163 viewsLast activity Jul 2023

  1. neuneuOP

    I’m trying to get an account balance from a seed phrase.

    I’m first retrieving the public key from the seed const { publicKey, /*privateKey*/ } = parseSeedPhrase(seedPhrase);.

    And then I’d like to retrieve all the account addresses associated to that public key, whether it’s a named account or an implicit account. I’m try with the following: const address = nearAPI.utils.PublicKey.fromString(publicKey).data.hexSlice(); but it only returns one address.

    Here is the full code:

    const nearAPI = require("near-api-js");
    const { parseSeedPhrase } = require('near-seed-phrase');
    require('dotenv').config();
    
    const seedPhrase = process.env.SEED_PHRASE;
    console.log(seedPhrase);
    
    // To recover keys from the seed phrase
    const { publicKey, /*privateKey*/ } = parseSeedPhrase(seedPhrase);
    console.log(publicKey);
    
    // To recover address from the public key
    const address = nearAPI.utils.PublicKey.fromString(publicKey).data.hexSlice();
    console.log(address);
    
    const { connect } = nearAPI;
    
    const connectionConfig = {
      networkId: "mainnet",
      nodeUrl: "https://rpc.mainnet.near.org",
      walletUrl: "https://wallet.mainnet.near.org",
      helperUrl: "https://helper.mainnet.near.org",
      explorerUrl: "https://explorer.mainnet.near.org",
    };
    
    // gets account balance
    const getBalance = async() => {
      try {
        const nearConnection = await connect(connectionConfig);
        const account = await nearConnection.account(address);
        const balance = await account.getAccountBalance();
    
        if (parseFloat(balance.total) > 0) {
          console.log(balance);
        };
      } catch (e) {
        console.log(e);
      }
    }
    
    getBalance();