Skip to content

How to implement web3.js using GunDB key pair

mimiza edited this page Oct 10, 2024 · 1 revision

GunDB private key can be used to create compatible private key that can be used on blockchains like ETH or BSC (and many others, you name it)

First, we must convert the GunDB private key (which is in base64url format) into hex format:

import Web3 from "web3"

const rpc = "https://data-seed-prebsc-1-s1.binance.org:8545/" // BSC testnet

const web3 = new Web3(rpc)

const base64UrlToHex = (base64url) => {
    const padding = "=".repeat((4 - (base64url.length % 4)) % 4)
    const base64 = base64url.replace(/-/g, "+").replace(/_/g, "/") + padding
    const binary = atob(base64)
    return binary
        .split("")
        .map((char) => char.charCodeAt(0).toString(16).padStart(2, "0"))
        .join("")
}
const hex = base64UrlToHex(user._.sea.priv)

Now we have the hex format of GunDB private key. In ETH or BSC blockchains, you must add "0x" as prefix to the hex formatted private key.

const privateKey = "0x" + hex

Now we have the private key in (for example BSC blockchain), let's create an account and get the public key.

const account = web3.eth.accounts.privateKeyToAccount(privateKey) // This is your account
const publicKey = account.address // This is your public key

Now you can use web3.js with GunDB private key :D

This wiki is where all the GUN website documentation comes from.

You can read it here or on the website, but the website has some special features like rendering some markdown extensions to create interactive coding tutorials.

Please feel free to improve the docs itself, we need contributions!

Clone this wiki locally