Skip to main content

Integrate Web3Auth with the Aptos Blockchain

While using the Web3Auth Web SDK for a non-EVM chain like Aptos, you get a standard provider from which you can obtain the private key of the user. Using this private key, you can utilize the corresponding libraries of the blockchain to make calls like fetching the user's account, retrieving balance, signing transactions, sending transactions, or interacting with smart contracts. We will focus on Testnet for this guide.

Aptos Configuration and Enums

For configuring Aptos, we will use the AptosConfig class from the @aptos-labs/ts-sdk package. The network parameter in AptosConfig uses an enum, which allows us to select the network environment (e.g., Testnet).

Here are the available networks in the enum:

declare enum Network {
MAINNET = "mainnet",
TESTNET = "testnet",
DEVNET = "devnet",
LOCAL = "local",
CUSTOM = "custom",
}

For this guide, we'll be using the TESTNET network.

import { Aptos, AptosConfig, Network } from "@aptos-labs/ts-sdk";

// Initialize the Aptos SDK with Testnet configuration
const config = new AptosConfig({ network: Network.TESTNET });
const aptos = new Aptos(config);

Installation

To begin, install the Aptos SDK:

npm install --save @aptos-labs/ts-sdk

Initializing Provider

Getting the chainConfig

const chainConfig = {
chainNamespace: "other",
chainId: "0x1",
rpcTarget: "https://rpc.ankr.com/http/aptos/v1",
displayName: "Aptos Mainnet",
blockExplorerUrl: "https://explorer.aptoslabs.com/",
ticker: "APT",
tickerName: "Aptos",
};

Initializing and instantiating the Web3Auth SDK

import { Web3Auth } from "@web3auth/modal";
import { CommonPrivateKeyProvider } from "@web3auth/base-provider";
import { WEB3AUTH_NETWORK, CHAIN_NAMESPACES } from "@web3auth/base";

const privateKeyProvider = new CommonPrivateKeyProvider({
config: { chainConfig: chainConfig },
});

const web3auth = new Web3Auth({
// Get it from Web3Auth Dashboard
clientId,
web3AuthNetwork: WEB3AUTH_NETWORK.SAPPHIRE_MAINNET,
privateKeyProvider: privateKeyProvider,
});

Getting the Web3Auth provider

After initializing Web3Auth, the next step is to initialize the provider and use it for your operations.

// Initialize for PnP Modal SDK
await web3auth.initModal();

// Trigger the login
await web3auth.connect();

// Get the provider
const provider = web3auth.provider;

// Continue using the `provider`

Get Account and Key

Once a user logs in, the Web3Auth SDK returns a provider. Since Web3Auth doesn't have a native provider for Aptos, we need to directly use the private key for making 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 Aptos EC Curve specific signing functions, hence, we first derive the Aptos Account using the getAptosAccount() function.

On the underhood, it uses the helper functions from the aptos library to derive the key pair.

import { Account, Aptos, AptosConfig, Network } from "@aptos-labs/ts-sdk";

/*
Use code from the above InitializeWeb3Auth and get provider steps
*/

const privateKey = await web3authProvider.request({ method: "private_key" });
const privateKeyUint8Array = new Uint8Array(
privateKey.match(/.{1,2}/g)!.map((byte: any) => parseInt(byte, 16)),
);
const aptosAccount = Account.fromPrivateKey({ privateKey: privateKeyUint8Array });
const aptosAccountAddress = aptosAccount.accountAddress.toString();

Get Balance

import { Account, Aptos, AptosConfig, Network } from "@aptos-labs/ts-sdk";

/*
Use code from the above InitializeWeb3Auth and get provider steps
*/

const privateKey = await web3authProvider.request({ method: "private_key" });
const privateKeyUint8Array = new Uint8Array(
privateKey.match(/.{1,2}/g)!.map((byte: any) => parseInt(byte, 16)),
);
const aptosAccount = Account.fromPrivateKey({ privateKey: privateKeyUint8Array });
const aptosAccountAddress = aptosAccount.accountAddress.toString();

const aptos = new Aptos(new AptosConfig({ network: Network.TESTNET }));

let resources = await aptos.account.getAccountResources({ accountAddress: aptosAccountAddress });
let coinResource = resources.find((resource) => resource.type.includes("0x1::coin::CoinStore"));
let balance = parseInt(coinResource.data.coin.value);

Send Transaction

import { Account, Aptos, AptosConfig, Network } from "@aptos-labs/ts-sdk";

/*
Use code from the above InitializeWeb3Auth and get provider steps
*/

const privateKey = await web3authProvider.request({ method: "private_key" });
const privateKeyUint8Array = new Uint8Array(
privateKey.match(/.{1,2}/g)!.map((byte: any) => parseInt(byte, 16)),
);
const aptosAccount = Account.fromPrivateKey({ privateKey: privateKeyUint8Array });
const aptosAccountAddress = aptosAccount.accountAddress.toString();

const aptos = new Aptos(new AptosConfig({ network: Network.TESTNET }));

const transaction = await aptos.transaction.build.simple({
sender: aptosAccountAddress,
data: {
function: "0x1::coin::transfer",
typeArguments: ["0x1::aptos_coin::AptosCoin"],
functionArguments: [aptosAccountAddress, "717"],
},
});

const senderAuthenticator = await aptos.transaction.sign({
signer: aptosAccount,
transaction,
});

const committedTxn = await aptos.transaction.submit.simple({
transaction,
senderAuthenticator,
});

await aptos.waitForTransaction({ transactionHash: committedTxn.hash });

Airdrop Request

You can request test tokens (Aptos coins) for your account by using the getAirdrop method in the testnet environment. This allows you to receive a certain amount of AptosCoin for testing purposes.

Here is how you can implement it:

import { Aptos, AptosConfig, Network } from "@aptos-labs/ts-sdk";

/*
Use code from the above InitializeWeb3Auth and get provider steps
*/

const aptos = new Aptos(new AptosConfig({ network: Network.TESTNET }));

async function requestAirdrop(accountAddress: string, amount: number) {
console.log(`Requesting airdrop for account: ${accountAddress} with amount: ${amount}`);

const transaction = await aptos.fundAccount({
accountAddress: accountAddress,
amount: amount,
});

console.log(`Airdrop transaction hash: ${transaction.hash}`);

const executedTransaction = await aptos.waitForTransaction({
transactionHash: transaction.hash,
});

console.log("Airdrop executed:", executedTransaction);
return executedTransaction;
}

This method will provide your account with test APT from Aptos Testnet, which can be used to test transactions and other operations.

Conclusion

With Web3Auth and Aptos integration, you can easily set up authentication for your Aptos dApps, get account information, check balances, and even send transactions.