'Call Solana web3.js from HTML
I am trying to run web3.js from HTML. Now so far I have been able to call window.solana.connect();
and window.solana.disconnect();
functions. However when I try run below code it doesn't work. I have tested it various options, like removing "web3." from the code but still didn't work. I would apprecaite if someone can guide me on how I can establish the connection.
const connection = new web3.Connection(web3.clusterApiUrl("devnet"));
Majority of my codes below is from the research done on Stackoveflow. Links below: Solana : Adding Sollet / Phantom Wallet Connect to my website - Steps? I would like to mint a new token on solana. How can I do this using solana-web3.js? How can you transfer SOL using the web3.js sdk for Solana? How to properly transfer Solana SOL using web3js via Phantom
Unfortunately docs on Phantom website don't help either. https://docs.phantom.app/integrating/establishing-a-connection
My existing codes below:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Welcome to Decentralized Ecommerce</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/web3/3.0.0-rc.5/web3.min.js" integrity="sha512-jRzb6jM5wynT5UHyMW2+SD+yLsYPEU5uftImpzOcVTdu1J7VsynVmiuFTsitsoL5PJVQi+OtWbrpWq/I+kkF4Q==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script src="{{ url_for('static', filename='app.js') }}"></script>
<script src="https://unpkg.com/@solana/web3.js@latest/lib/index.iife.js"></script>
<script src="/static/solana.js"></script>
<script type="text/javascript">
async function transferSOL() {
//Changes are only here, in the beginning
if (window.solana.isConnected === false){
const resp = await window.solana.connect();
}
const pubKey = await window.solana.publicKey;
console.log("Public Key: ", pubKey);
// Establishing connection
const connection = new web3.Connection(web3.clusterApiUrl("devnet"));
alert('hello2');
// I have hardcoded my secondary wallet address here. You can take this address either from user input or your DB or wherever
var recieverWallet = new web3.PublicKey("4iSD5Q6AnyhRHu6Uz4u1KAzXh3TwNwwQshEGhZbEXUTw");
alert('hello3');
// Airdrop some SOL to the sender's wallet, so that it can handle the txn fee
var airdropSignature = await connection.requestAirdrop(
provider.publicKey,
web3.LAMPORTS_PER_SOL,
);
// Confirming that the airdrop went through
await connection.confirmTransaction(airdropSignature);
console.log("Airdropped");
var transaction = new web3.Transaction().add(
web3.SystemProgram.transfer({
fromPubkey: provider.publicKey,
toPubkey: recieverWallet,
lamports: web3.LAMPORTS_PER_SOL //Investing 1 SOL. Remember 1 Lamport = 10^-9 SOL.
}),
);
// Setting the variables for the transaction
transaction.feePayer = await provider.publicKey;
let blockhashObj = await connection.getRecentBlockhash();
transaction.recentBlockhash = await blockhashObj.blockhash;
// Transaction constructor initialized successfully
if(transaction) {
console.log("Txn created successfully");
}
// Request creator to sign the transaction (allow the transaction)
let signed = await provider.signTransaction(transaction);
// The signature is generated
let signature = await connection.sendRawTransaction(signed.serialize());
// Confirm whether the transaction went through or not
await connection.confirmTransaction(signature);
//Signature or the txn hash
console.log("Signature: ", signature);
}
</script>
</head>
Solution 1:[1]
After importing the script on the HTML:
<script src="https://unpkg.com/@solana/web3.js@latest/lib/index.iife.js"> </script>
You should be able to call:
const connection = new solanaWeb3.Connection(solanaWeb3.clusterApiUrl("mainnet-beta"));
Note it is solanaWeb3 not web3
Solution 2:[2]
Here is an example with Solana Web3 1.4:
import { Connection, clusterApiUrl } from "@solana/web3.js";
const connection = new Connection(clusterApiUrl("devnet"), "confirmed");
Make sure to have installed the library via, npm install @solana/web3.js
.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | mursang |
Solution 2 | Zorayr |