This example demonstrates how to use TonWeb with React (create-react-app).
- Create new React app using CRA:
npx create-react-app tonweb-react-example --template typescript
- Install TonWeb packages:
npm i -S tonweb tonweb-mnemonic
- Install Buffer polyfill:
npm i -S buffer
- Create
polyfills.ts
file to load the polyfill:
import { Buffer } from 'buffer'
globalThis.Buffer = Buffer
- Import the
polyfills.ts
from the top of yourindex.ts
(before all other imports):
import './polyfills';
// all other imports…
- Create the TonWeb instance:
const httpApiUrl = 'https://toncenter.com/api/v2/jsonRPC';
const provider = new TonWeb.HttpProvider(httpApiUrl, {
/**
* Get your own API key at: {@link https://t.me/tonapibot}
*/
apiKey: '',
});
const tonweb = new TonWeb(provider);
- Use it in your components:
const address = 'EQCD39VS5jcptHL8vMjEXrzGaRcCVYto7HUn4bpAOg8xqB2N';
export default function App() {
const [balance, setBalance] = useState<string | undefined>(
undefined
);
const [newAddress, setNewAddress] = useState<string | undefined>(
undefined
);
useEffect(() => {
(async () => {
setBalance(await getBalance(address));
})();
}, [address]);
useEffect(() => {
(async () => {
setNewAddress(await createNewWallet());
})();
}, []);
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<p>
Address:<br/>
<strong>{address}</strong>
</p>
{ balance && (
<p>
Balance:<br/>
<strong>{balance} TON</strong>
</p>
) }
{ newAddress && (
<p>
New Wallet Address:<br/>
<strong>{newAddress}</strong>
</p>
) }
</header>
</div>
);
}
async function createNewWallet(): Promise<string> {
const words = await mnemonic.generateMnemonic();
const keyPair = await mnemonic.mnemonicToKeyPair(words);
const wallet = new TonWeb.Wallets.all.v4R2(provider, {
publicKey: keyPair.publicKey,
});
const address = await wallet.getAddress();
return address.toString(true, true, true);
}
async function getBalance(address: string): Promise<string> {
const info = await provider.getWalletInfo(address);
return tonweb.utils.fromNano(info.balance);
}
Look at this commit for example.