Skip to content

Commit 8c5ab89

Browse files
committed
getting balance and sending token success with interchain-kit provider
1 parent 815ad79 commit 8c5ab89

File tree

2 files changed

+25
-61
lines changed

2 files changed

+25
-61
lines changed

examples/ethereum/app/page.tsx

Lines changed: 25 additions & 58 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,6 @@ import { Box, Button, TextField, NumberField, FieldLabel, Callout } from "@inter
44
import React, { useState, useEffect } from "react"
55
import { Wallet, ArrowRight, RefreshCw, AlertCircle } from "lucide-react"
66
import { SignerFromBrowser } from "@interchainjs/ethereum/signers/SignerFromBrowser"
7-
// import { IEthereumProvider } from "@keplr-wallet/types";
87
import { MetaMaskInpageProvider } from "@metamask/providers";
98
import BigNumber from "bignumber.js";
109
import { useChain } from '@interchain-kit/react'
@@ -21,72 +20,53 @@ const CardTitle = Box
2120
const CardDescription = Box
2221

2322
export default function WalletPage() {
24-
const [account, setAccount] = useState<string>("")
2523
const [balance, setBalance] = useState<string>("0")
26-
const [isConnected, setIsConnected] = useState(false)
2724
const [isLoading, setIsLoading] = useState(false)
2825
const [recipient, setRecipient] = useState("")
2926
const [amount, setAmount] = useState<number>(0)
3027
const [error, setError] = useState("")
3128
const [ethereum, setEthereum] = useState<EthereumProvider>()
3229

33-
const { wallet, status } = useChain('ethereum')
30+
const { wallet, status, connect, address: account, disconnect } = useChain('ethereum')
3431

3532
useEffect(() => {
3633
console.log('status from useChain:', status)
3734
if (status === WalletState.Connected) {
3835
const setEthProviderFromWallet = async () => {
36+
await new Promise(resolve => setTimeout(resolve, 500))
3937
const ethProviderFromWallet = await wallet.getProvider('1') as EthereumProvider
4038
console.log("Ethereum provider:", ethProviderFromWallet)
4139
setEthereum(ethProviderFromWallet)
4240
}
4341
setEthProviderFromWallet()
4442
}
43+
setIsLoading(status === WalletState.Connecting)
4544
}, [status])
4645

47-
// Check if MetaMask is installed
48-
const checkIfWalletIsInstalled = () => {
49-
return typeof window !== "undefined" && typeof window.ethereum !== "undefined"
50-
}
51-
5246
// Connect wallet
5347
const connectWallet = async () => {
54-
setIsLoading(true)
55-
setError("")
56-
57-
try {
58-
if (!checkIfWalletIsInstalled()) {
59-
throw new Error("Please install MetaMask wallet")
60-
}
61-
62-
// Request account access
63-
const accounts = await ethereum!.request({ method: "eth_requestAccounts" }) as any
64-
65-
if (accounts.length > 0) {
66-
setAccount(accounts[0])
67-
setIsConnected(true)
68-
await getBalance(accounts[0])
69-
}
70-
} catch (err: any) {
71-
setError(err.message || "Failed to connect wallet")
72-
} finally {
73-
setIsLoading(false)
74-
}
48+
connect()
7549
}
7650

7751
// Disconnect wallet
7852
const disconnectWallet = () => {
79-
setAccount("")
53+
disconnect()
8054
setBalance("0")
81-
setIsConnected(false)
8255
setError("")
8356
}
8457

8558
// Get balance
86-
const getBalance = async (address: string) => {
59+
const getBalance = async () => {
60+
if (!ethereum) return
8761
try {
88-
const wallet = new SignerFromBrowser(ethereum!)
62+
console.log('ethereum in getBalance:', ethereum)
63+
const wallet = new SignerFromBrowser(
64+
ethereum!
65+
// window.ethereum as EthereumProvider
66+
)
67+
console.log('wallet in getBalance:', wallet)
8968
const balance = await wallet.getBalance()
69+
console.log('balance in getBalance:', balance)
9070
setBalance(new BigNumber(balance.toString()).div(10 ** 18).toString())
9171
} catch (err: any) {
9272
console.error("Failed to get balance:", err)
@@ -96,8 +76,9 @@ export default function WalletPage() {
9676

9777
// Refresh balance
9878
const refreshBalance = async () => {
79+
console.log('account in refreshBalance:', account)
9980
if (account) {
100-
await getBalance(account)
81+
await getBalance()
10182
}
10283
}
10384

@@ -130,7 +111,7 @@ export default function WalletPage() {
130111
await transaction.wait()
131112

132113
// Update balance
133-
await getBalance(account)
114+
await getBalance()
134115

135116
// Clear form
136117
setRecipient("")
@@ -144,39 +125,25 @@ export default function WalletPage() {
144125

145126
// Listen for account changes
146127
useEffect(() => {
147-
if (!ethereum) return
148-
if (checkIfWalletIsInstalled()) {
149-
ethereum.on("accountsChanged", (accounts: string[]) => {
150-
if (accounts.length > 0) {
151-
setAccount(accounts[0])
152-
getBalance(accounts[0])
153-
} else {
154-
setAccount("")
155-
setBalance("0")
156-
setIsConnected(false)
157-
}
158-
})
159-
}
160-
161-
return () => {
162-
if (checkIfWalletIsInstalled()) {
163-
ethereum.removeListener("accountsChanged", () => { })
164-
}
128+
if (account) {
129+
getBalance()
130+
return
165131
}
166-
}, [ethereum])
132+
setBalance("0")
133+
}, [account, ethereum])
167134

168135
return (
169136
<main className="container mx-auto py-10 px-4">
170137
<h1 className="text-3xl font-bold text-center mb-8">Ethereum Wallet</h1>
171138

172-
<Box className={`grid gap-6 ${isConnected ? "md:grid-cols-2" : ""}`}>
139+
<Box className={`grid gap-6 ${status === WalletState.Connected ? "md:grid-cols-2" : ""}`}>
173140
<Card className='border border-1 p-5 rounded-md'>
174141
<CardHeader className='mb-4'>
175142
<CardTitle className='font-bold text-2xl'>Wallet Connection</CardTitle>
176143
<CardDescription className='text-gray-500'>Connect your Ethereum wallet to view balance</CardDescription>
177144
</CardHeader>
178145
<CardContent>
179-
{!isConnected ? (
146+
{status !== WalletState.Connected ? (
180147
<Button onClick={connectWallet} disabled={isLoading} className="w-full">
181148
{isLoading ? "Connecting..." : "Connect Wallet"}
182149
<Wallet className="ml-2 h-4 w-4" />
@@ -206,7 +173,7 @@ export default function WalletPage() {
206173
</CardContent>
207174
</Card>
208175

209-
{isConnected && (
176+
{status === WalletState.Connected && (
210177
<Card className='border border-1 p-5 rounded-md'>
211178
<CardHeader className='mb-4'>
212179
<CardTitle className='font-bold text-2xl'>Send Ethereum</CardTitle>

examples/ethereum/app/provider.tsx

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,14 +4,11 @@ import './globals.css'
44
import "@interchain-ui/react/styles";
55
import { ThemeProvider } from "@interchain-ui/react";
66
import { ChainProvider } from "@interchain-kit/react";
7-
import { BaseWallet } from "@interchain-kit/core";
87
import { metaMaskWallet } from '@interchain-kit/metamask-extension'
98
import { assetList, chain } from '@chain-registry/v2/mainnet/ethereum'
10-
import { keplrWallet } from '@interchain-kit/keplr-extension'
119

1210
const _wallets = [
1311
metaMaskWallet,
14-
// keplrWallet
1512
];
1613

1714
export default function Provider({

0 commit comments

Comments
 (0)