Skip to content

Instantly share code, notes, and snippets.

@dabit3
Created September 11, 2021 14:24
Show Gist options
  • Save dabit3/a03e0481502c98ad31c1994057870910 to your computer and use it in GitHub Desktop.
Save dabit3/a03e0481502c98ad31c1994057870910 to your computer and use it in GitHub Desktop.
Solana + Anchor Counter front end (for example from docs)
import './App.css';
import { useEffect, useState } 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() {
const [account, setAccount] = useState(null)
useEffect(() => {
window.solana.on("connect", () => {
console.log('updated...')
})
return () => {
window.solana.disconnect();
}
}, [])
async function sendTransaction() {
const wallet = window.solana
// const network = clusterApiUrl("devnet")
const network = "http://127.0.0.1:8899"
const connection = new Connection(network, opts.preflightCommitment);
const provider = new Provider(
connection, wallet, opts.preflightCommitment,
)
const program = new Program(idl, programID, provider);
const counter = web3.Keypair.generate();
setAccount(counter)
await program.rpc.create(provider.wallet.publicKey, {
accounts: {
counter: counter.publicKey,
user: provider.wallet.publicKey,
systemProgram: SystemProgram.programId,
},
signers: [counter],
})
const acc = await program.account.counter.fetch(counter.publicKey)
console.log('acc: ', acc.count.toString())
}
async function increment() {
const wallet = window.solana
// const network = clusterApiUrl("devnet")
const network = "http://127.0.0.1:8899"
const connection = new Connection(network, opts.preflightCommitment);
const provider = new Provider(
connection, wallet, opts.preflightCommitment,
)
const program = new Program(idl, programID, provider);
const counter = account
await program.rpc.increment({
accounts: {
counter: counter.publicKey,
authority: provider.wallet.publicKey,
}
})
const acc = await program.account.counter.fetch(counter.publicKey)
console.log('acc: ', acc.count.toString())
}
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={increment}>increment</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