How to build Web3 in Algorand Blockchain
Tags: blockchain, javascript, web3, tutorial
Published: 2023-03-05 20:06:11

While using the Web3Auth Web SDK for a non EVM chain like Algorand you get a standard provider from which you can get the private key of the user. Using this private key, you can use the corresponding libraries of the blockchain to make blockchain calls like getting user's account, fetch balance, sign transaction, send transaction, read from and write to the smart contract, etc. We have highlighted a few methods here for getting you started quickly on that.

## Initializing Provider
 

```
import { Web3Auth } from "@web3auth/modal";
import { OpenloginAdapter } from "@web3auth/openlogin-adapter";

const web3auth = new Web3Auth({
  clientId: "YOUR_WEB3AUTH_CLIENT_ID", // get it from Web3Auth Dashboard
  web3AuthNetwork: "cyan",
  chainConfig: {
    chainNamespace: "other", // for all non EVM and SOLANA chains, use "other"
  },
});

// "other" is supported through @web3auth/openlogin-adapter package.
const openloginAdapter = new OpenloginAdapter({
  adapterSettings: {
    uxMode: "popup",
  },
});
web3auth.configureAdapter(openloginAdapter);

await web3auth.initModal();

const web3authProvider = web3auth.connect(); // web3auth.provider
```

## Get User Info

Once logged in, Web3Auth instance returns you some information about your logged in user. This is fetched directly from the JWT token and Web3Auth doesn't store this info anywhere. Hence, this information in available in social logins only after the user has logged into your application.

```
const user = await web3auth.getUserInfo(); // web3auth instance
```

## Get Account and KeyPair
Once a user logs in, the Web3Auth SDK returns a provider. Since Web3Auth doesn't have a native provider for Algorand, we need to directly use the private key to make the RPC calls.

Using the function, web3auth.provider.request({method: "private_key"}) from Web3Auth provider, the application can have access to the user's private key. However, we cannot use this key with Algorand specific signing functions, hence, we first derive the Algorand Key using the getAlgorandKeyPair() function.

On the underhood, it uses the algosdk.secretKeyToMnemonic() function, where we need to pass the Buffer.from(privateKey, "hex"), ie. the hexadecimal to Uint8Array converted private key. We get a mnemonic seed phrase which can be used to derive the keypair using the algosdk.mnemonicToSecretKey(), this returns a keypair. We can use the returned private key pair from this and use on Algorand transactions.

```
import { SafeEventEmitterProvider } from "@web3auth/base";
import algosdk from "algosdk";


/*
  Use code from the above Initializing Provider here
*/

// web3authProvider is web3auth.provider from above
const privateKey = await web3authProvider.request({ method: "private_key" });

// derive the Algorand Key Pair from the private key
var passphrase = algosdk.secretKeyToMnemonic(Buffer.from(privateKey, "hex"));
var keyPair = algosdk.mnemonicToSecretKey(passphrase);

// keyPair.addr is the account address.
const account = keyPair.addr;
```

## Get Balance

```
import { SafeEventEmitterProvider } from "@web3auth/base";
import algosdk from "algosdk";

/*
  Use code from the above Initializing Provider here
*/

// web3authProvider is web3auth.provider from above
const privateKey = await web3authProvider.request({ method: "private_key" });

// derive the Algorand Key Pair from the private key
var passphrase = algosdk.secretKeyToMnemonic(Buffer.from(privateKey, "hex"));
var keyPair = algosdk.mnemonicToSecretKey(passphrase);

// keyPair.addr is the account address.
const account = keyPair.addr;

// Making a connection to the Algorand TestNet
const algodToken = {
  "x-api-key": "YOUR_ALGOD_API_KEY",
};
const algodServer = "https://testnet-algorand.api.purestake.io/ps2"; // for testnet
const algodPort = "";
const algodClient = new algosdk.Algodv2(algodToken, algodServer, algodPort);
const balance = await client.accountInformation(keyPair.addr).do();

```

## Send Transaction

```
import { SafeEventEmitterProvider } from "@web3auth/base";
import algosdk from "algosdk";

/*
  Use code from the above Initializing Provider here
*/

// web3authProvider is web3auth.provider from above
const privateKey = await web3authProvider.request({ method: "private_key" });

// derive the Algorand Key Pair from the private key
var passphrase = algosdk.secretKeyToMnemonic(Buffer.from(privateKey, "hex"));
var keyPair = algosdk.mnemonicToSecretKey(passphrase);

// keyPair.addr is the account address.
const account = keyPair.addr;

// Making a connection to the Algorand TestNet
const algodToken = {
  "x-api-key": "YOUR_ALGOD_API_KEY",
};
const algodServer = "https://testnet-algorand.api.purestake.io/ps2"; // for testnet
const algodPort = "";
const algodClient = new algosdk.Algodv2(algodToken, algodServer, algodPort);

// Creating the transaction

const params = await client.getTransactionParams().do();
const enc = new TextEncoder();
const message = enc.encode("Web3Auth says hello!");

// You need to have some funds in your account to send a transaction
// You can get some testnet funds here: https://bank.testnet.algorand.network/

const txn = algosdk.makePaymentTxnWithSuggestedParams(
  keyPair.addr, // sender
  keyPair.addr, // receiver
  1000,
  undefined,
  message,
  params
);
let signedTxn = algosdk.signTransaction(txn, keyPair.sk);

const txHash = await client.sendRawTransaction(signedTxn.blob).do();
```


## Sign Message

```
import { SafeEventEmitterProvider } from "@web3auth/base";
import algosdk from "algosdk";

/*
  Use code from the above Initializing Provider here
*/

// web3authProvider is web3auth.provider from above
const privateKey = await web3authProvider.request({ method: "private_key" });

// derive the Algorand Key Pair from the private key
var passphrase = algosdk.secretKeyToMnemonic(Buffer.from(privateKey, "hex"));
var keyPair = algosdk.mnemonicToSecretKey(passphrase);

// keyPair.addr is the account address.
const account = keyPair.addr;

// Making a connection to the Algorand TestNet

const algodToken = {
  "x-api-key": "YOUR_ALGOD_API_KEY",
};
const algodServer = "https://testnet-algorand.api.purestake.io/ps2"; // for testnet
const algodPort = "";
const algodClient = new algosdk.Algodv2(algodToken, algodServer, algodPort);

// Generating the message to sign

const params = await client.getTransactionParams().do();
const enc = new TextEncoder();
const message = enc.encode("Web3Auth says hello!");
const txn = algosdk.makePaymentTxnWithSuggestedParams(keyPair.addr, keyPair.addr, 0, undefined, message, params);
let signedTxn = algosdk.signTransaction(txn, keyPair.sk);
let txId = signedTxn.txID;
```