Last active
December 16, 2024 19:03
-
-
Save dabit3/9bac597eb307107991fcf736974af4f3 to your computer and use it in GitHub Desktop.
Working example of Solana and Anchor on JavaScript Client - React
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import './App.css'; | |
import { useEffect } from 'react'; | |
import { | |
Program, | |
Provider, | |
BN, | |
web3, | |
} from '@project-serum/anchor' | |
import { | |
Connection, | |
clusterApiUrl, | |
PublicKey | |
} from '@solana/web3.js' | |
import idl from './idl.json' | |
const opts = { | |
preflightCommitment: "recent", | |
}; | |
const { SystemProgram } = web3 | |
const programID = new PublicKey("FRs2XJmvEULEm4X1Y17nZ8rmKMU7R1EqJVLMZxCTez6Q") | |
function App() { | |
useEffect(() => { | |
window.solana.on("connect", () => { | |
console.log('updated...') | |
}) | |
return () => { | |
window.solana.disconnect(); | |
} | |
}, []) | |
async function sendTransaction() { | |
const wallet = window.solana | |
const network = clusterApiUrl("devnet") | |
const connection = new Connection(network, opts.preflightCommitment); | |
const provider = new Provider( | |
connection, wallet, opts.preflightCommitment, | |
) | |
const program = new Program(idl, programID, provider); | |
const localAccount = web3.Keypair.generate(); | |
await program.rpc.initialize(new BN(1234), { | |
accounts: { | |
myAccount: localAccount.publicKey, | |
user: provider.wallet.publicKey, | |
systemProgram: SystemProgram.programId, | |
}, | |
signers: [localAccount], | |
}) | |
const acc = await program.account.myAccount.fetch(localAccount.publicKey) | |
console.log('acc: ', acc) | |
} | |
async function read() { | |
try { | |
const wallet = window.solana; | |
const network = clusterApiUrl("devnet") | |
const connection = new Connection(network); | |
const provider = new Provider( | |
connection, wallet, { commitment: "processed" }, | |
) | |
} catch (err) { | |
console.log('error: ', err) | |
} | |
} | |
async function getWallet() { | |
try { | |
const wallet = typeof window !== 'undefined' && window.solana; | |
await wallet.connect() | |
} catch (err) { | |
console.log('err: ', err) | |
} | |
} | |
return ( | |
<div className="App"> | |
<header className="App-header"> | |
<button onClick={getWallet}>getWallet</button> | |
<button onClick={sendTransaction}>sendTransaction</button> | |
<button onClick={read}>read</button> | |
</header> | |
</div> | |
); | |
} | |
export default App; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
use this command "npx create-solana-dapp@latest" when setting up your Dapp, this will help in terms of some errors that may occur due to wallet connections.