Skip to content

Commit

Permalink
fix code for vanillaJS to call smart Contracts or transfers (#273)
Browse files Browse the repository at this point in the history
  • Loading branch information
rtomas authored Jan 30, 2025
1 parent 564b336 commit 2d35e53
Show file tree
Hide file tree
Showing 2 changed files with 76 additions and 106 deletions.
68 changes: 34 additions & 34 deletions docs/appkit/javascript/core/installation.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -141,25 +141,33 @@ Create a new project on Reown Cloud at https://cloud.reown.com and obtain a new
</PlatformTabItem>
</PlatformTabs>

## Smart Contract Interaction
## Blockchain Interaction

<PlatformTabs groupId="eth-lib" activeOptions={["wagmi", "ethers","solana"]}>

<PlatformTabItem value="wagmi">
You need to install @wagmi/core to interact with smart contracts:

```bash npm2yarn
npm install @wagmi/core
```

[Wagmi actions](https://wagmi.sh/core/api/actions/readContract) can help us interact with wallets and smart contracts:

For this use case, we need to import the `wagmiConfig`from our AppKit WagmiAdapter configuration.
```tsx
import { readContract } from '@wagmi/core'
import { USDTAbi } from '../abi/USDTAbi'

const USDTAddress = '0x...'

const data = readContract({
const data = readContract(wagmiConfig, {
address: USDTAddress,
abi: USDTAbi,
functionName: 'symbol'
functionName: 'totalSupply',
args: []
})

```

Read more about Wagmi actions for smart contract interaction [here](https://wagmi.sh/core/actions/readContract).
Expand All @@ -170,39 +178,31 @@ Read more about Wagmi actions for smart contract interaction [here](https://wagm
[Ethers](https://docs.ethers.org/v6/) can help us interact with wallets and smart contracts:

```tsx
import { useAppKitProvider, useAppKitAccount } from "@reown/appkit";
import { BrowserProvider, Contract, formatUnits } from 'ethers'

const USDTAddress = '0x617f3112bf5397D0467D315cC709EF968D9ba546'

// The ERC-20 Contract ABI, which is a common contract interface
// for tokens (this is the Human-Readable ABI format)
const USDTAbi = [
'function name() view returns (string)',
'function symbol() view returns (string)',
'function balanceOf(address) view returns (uint)',
'function transfer(address to, uint amount)',
'event Transfer(address indexed from, address indexed to, uint amount)'
]

function Components() {
const { address, isConnected } = useAppKitAccount()
const { walletProvider } = useAppKitProvider()

async function getBalance() {
if (!isConnected) throw Error('User disconnected')

const ethersProvider = new BrowserProvider(walletProvider)
const signer = await ethersProvider.getSigner()
// The Contract object
const USDTContract = new Contract(USDTAddress, USDTAbi, signer)
const USDTBalance = await USDTContract.balanceOf(address)

console.log(formatUnits(USDTBalance, 18))
}
import { BrowserProvider, Contract, parseEther } from 'ethers'

const provider = await modal.subscribeProviders(state => {
return state['eip155'];
})

const addressFrom = await modal.subscribeAccount(state => {
return state;
})

return <button onClick={getBalance}>Get User Balance</button>
if (!provider) throw Error('No provider found');
if (!addressFrom) throw Error('No address found');

function sendTransaction() {
const tx = {
from: addressFrom,
to: "0x...", // any address
value: parseEther("0.0001")
}
const ethersProvider = new BrowserProvider(provider);
const signer = await ethersProvider.getSigner();
const tx = await signer.sendTransaction(tx);
console.log("transaction:", tx)
}

```

</PlatformTabItem>
Expand Down
114 changes: 42 additions & 72 deletions docs/appkit/javascript/solana/about/programs.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -3,83 +3,53 @@
For a practical example of how it works, you can refer to our [lab dApp](https://appkit-lab.reown.com/library/solana/).

```js
import {
SystemProgram,
PublicKey,
Keypair,
Transaction,
TransactionInstruction,
LAMPORTS_PER_SOL
} from '@solana/web3.js'
import { useAppKitAccount, useAppKitProvider } from '@reown/appkit'
import type { Provider } from '@reown/appkit-adapter-solana'
import { PublicKey, LAMPORTS_PER_SOL, Transaction, SystemProgram } from "@solana/web3.js";

function deserializeCounterAccount(data) {
if (data?.byteLength !== 8) {
throw Error('Need exactly 8 bytes to deserialize counter')
}
import type { Provider } from '@reown/appkit-adapter-solana'

return {
count: Number(data[0])
}
const solanaProvider = {};
const solanaConnection = {};
modal.subscribeProviders(state => {
solanaProvider = state['solana'];
const url = solanaProvider.getActiveChain().rpcUrls.default.http[0];
const solanaConnection = new Connection(url);
})

const addressFrom = await modal.subscribeAccount(state => {
return state;
})

const sendTransaction = async () => {
if (!addressFrom || !solanaConnection) throw Error('user is disconnected');

const wallet = new PublicKey(addressFrom);
if (!wallet) throw Error('wallet provider is not available');

const latestBlockhash = await solanaConnection.getLatestBlockhash();

const transaction = new Transaction({
feePayer: wallet,
recentBlockhash: latestBlockhash?.blockhash,
}).add(
SystemProgram.transfer({
fromPubkey: wallet,
toPubkey: new PublicKey(address), // destination address
lamports: 1000,
})
);

return await provider.sendTransaction(transaction, solanaConnection);
}

const { address } = useAppKitAccount()
const { walletProvider, connection } = useAppKitProvider<Provider>('solana')

async function onIncrementCounter() {
const PROGRAM_ID = new PublicKey('Cb5aXEgXptKqHHWLifvXu5BeAuVLjojQ5ypq6CfQj1hy')

const counterKeypair = Keypair.generate()
const counter = counterKeypair.publicKey

const balance = await connection.getBalance(walletProvider.publicKey)
if (balance < LAMPORTS_PER_SOL / 100) {
throw Error('Not enough SOL in wallet')
}

const COUNTER_ACCOUNT_SIZE = 8
const allocIx = SystemProgram.createAccount({
fromPubkey: walletProvider.publicKey,
newAccountPubkey: counter,
lamports: await connection.getMinimumBalanceForRentExemption(COUNTER_ACCOUNT_SIZE),
space: COUNTER_ACCOUNT_SIZE,
programId: PROGRAM_ID
})
const getBalance = async () => {
if (!addressFrom || !solanaConnection) throw Error('user is disconnected');

const incrementIx = new TransactionInstruction({
programId: PROGRAM_ID,
keys: [
{
pubkey: counter,
isSigner: false,
isWritable: true
}
],
data: Buffer.from([0x0])
})

const tx = new Transaction().add(allocIx).add(incrementIx)

tx.feePayer = walletProvider.publicKey
tx.recentBlockhash = (await connection.getLatestBlockhash('confirmed')).blockhash

await walletProvider.signAndSendTransaction(tx, [counterKeypair])

const counterAccountInfo = await connection.getAccountInfo(counter, {
commitment: 'confirmed'
})

if (!counterAccountInfo) {
throw new Error('Expected counter account to have been created')
const wallet = new PublicKey(addressFrom);
const balance = await solanaConnection?.getBalance(wallet);
if (balance !== undefined) {
return `${balance / LAMPORTS_PER_SOL}`;
} else {
return '-';
}

const counterAccount = deserializeCounterAccount(counterAccountInfo?.data)

if (counterAccount.count !== 1) {
throw new Error('Expected count to have been 1')
}

console.log(`[alloc+increment] count is: ${counterAccount.count}`);
}
```

0 comments on commit 2d35e53

Please sign in to comment.