DEV Community

Swatantra goswami
Swatantra goswami

Posted on

Wallet Creation by Alchemy SDK

Initialize Object
Alchemy Supported chain list:
https://www.alchemy.com/docs/wallets/supported-chains

const { Alchemy } = require('alchemy-sdk')

const getAlchemy = (chainId) => {
    const alchemyApiKey = ''

    return new Alchemy({
        apiKey: alchemyApiKey,
        network: 'eth-sepolia' // chain-id
    })
}

const getTokenMetaDataFromAlchemy = async (tokenAddress, chainId) => {
    try {
        const alchemy = getAlchemy(chainId)
        return alchemy.core.getTokenMetadata(tokenAddress)
    } catch (error) {
        console.log(error)
    }
    return
}

/** 
    const addresses = [
        {
            address: '0xED1B7De57918f6B7c8a7a7767557f09A80eC2a35',
            networks: ['eth-sepolia', 'eth-mainnet']
        }
    ] 
*/
const getPortfolio = async (addresses, chainId) => {
    try {
        const withPrices = true
        const includeNativeTokens = true
        const withMetadata = true
        const alchemy = getAlchemy(chainId)
        const { data } = await alchemy.portfolio.getTokensByWallet(
            addresses,
            withMetadata,
            withPrices,
            includeNativeTokens
        )
        const wei = BigInt(data.tokens[0].tokenBalance)
        const eth = Number(wei) / 1e18 // safe here because value is small

        console.log('ETH balance:', eth) // 0.05
        return JSON.stringify(data, null, 2)
    } catch (error) {
        console.log(error)
    }
}

module.exports = {
    getAlchemy,
    getTokenMetaDataFromAlchemy,
    getPortfolio
}

Enter fullscreen mode Exit fullscreen mode

Now it's time to call the alchemy function

const {
    getAlchemy,
    getTokenMetaDataFromAlchemy,
    getPortfolio
} = require('./getAlchemy')

const callingFUntion = async () => {
    const addresses = [
        {
            address: '0xED1B7De57918f6B7c8a7a7767557f09A80eC2a35',
            networks: ['eth-sepolia', 'eth-mainnet']
        }
    ]
    console.log(await getPortfolio(addresses, '1'))
}
callingFUntion()
Enter fullscreen mode Exit fullscreen mode

Top comments (0)