Get wallet address for multiple chains in cosmos app chains
Taylor Lee
Posted on June 8, 2024
In the Cosmos ecosystem, each chain has its own specific prefix for Bech32 addresses. When you connect your Keplr wallet to a Cosmos SDK-based chain, you receive a wallet address specific to that chain. However, the underlying public key remains the same across these chains, and you can derive the addresses for other chains by converting the address prefix.
Here's how you can derive the address for multiple chains using JavaScript, assuming you have the wallet address for one chain:
Extract the Public Key: You need the public key associated with the address. This step typically involves interacting with the Keplr wallet to get the public key.
Convert the Address Prefix: Use the Bech32 encoding library to convert the address prefix to the desired chain's prefix.
Show me the code
Below is an example using JavaScript and the bech32 library to convert an address from the Osmosis chain to the Stargaze chain:
- Install the necessary libraries:
npm install @cosmjs/encoding @cosmjs/crypto
- JavaScript code to convert the address prefix:
const { Bech32 } = require('@cosmjs/encoding');
/**
* Converts a Bech32 address to another Bech32 address with a different prefix.
* @param {string} address - The original Bech32 address.
* @param {string} newPrefix - The new prefix for the Bech32 address.
* @returns {string} - The new Bech32 address with the specified prefix.
*/
function convertAddressPrefix(address, newPrefix) {
const { prefix, data } = Bech32.decode(address);
return Bech32.encode(newPrefix, data);
}
// Example usage
const osmosisAddress = 'osmo1n3v7hdf3lj6gr7hyluq7x4hj4snmajsze3fnlq';
const stargazePrefix = 'stars';
const stargazeAddress = convertAddressPrefix(osmosisAddress, stargazePrefix);
console.log('Stargaze Address:', stargazeAddress);
This code will convert an Osmosis address to a Stargaze address by changing the Bech32 prefix.
Summary
By extracting the public key from Keplr and using a Bech32 conversion, you can derive addresses for multiple chains in the Cosmos ecosystem. This approach leverages the shared public key across these chains and the flexibility of Bech32 encoding.
Thanks for your time. Happy coding!
Posted on June 8, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.