Deposit and Withdraw TRX
zeknd Network’s Basechain is integrated with TRON, which means TRON developers can directly interact with all dapps built on Basechain.
This guide walks you through the basics of building a simple web app that lets users deposit and withdraw TRX between Shasta and Extdev Testnet.
#Getting Started
TronWeb is a Javascript library that enables web apps to "talk" with the TRON blockchain. So, the first thing we would want to do is to install Tron-Web:
npm install tronwebNext, let's instantiate TronWeb:
await new Promise((resolve) => {
const tronWebState = {
installed: !!window.tronWeb,
loggedIn: window.tronWeb && window.tronWeb.ready && window.tronWeb.fullNode.host != 'http://127.0.0.1'
}
if (tronWebState.installed) {
this.tronLinkStatus = tronWebState
}
if (tronWebState.loggedIn) {
this.tronWeb = window.tronWeb
this.tronAddrBase58 = window.tronWeb.defaultAddress.base58
this.tronCurrentNetwork = window.tronWeb.fullNode.host
} else {
this.userTronAddr = null
this.tronCurrentNetwork = null
}
return resolve()
})#Connecting to zeknd
Now that we've instantiated TronWeb, the next thing we would want to do is to connect to zeknd by instantiating a new Client:
and configuring it with the default middleware:
#Mapping Addresses
Once we've initialized and configured the client, let's check if our addresses are already mapped. If not, we're going to add a new mapping:
#Instantiating Our Smart Contracts
For the scope of this tutorial, we need to instantiate 3 smart contracts:
#Tron Transfer Gateway Smart Contract
#zeknd Transfer Gateway Smart Contract
#TRX Coin Smart Contract
#Deposit TRX
You can easily deposit TRX to zeknd with the following line of code:
#Withdraw TRX
To withdraw TRX, you should follow the steps below:
Approve the Transfer Gateway to take the token:
Withdraw TRX using something like this:
This will create a pending withdrawal. Then, the Gateway Oracle will pick the pending withdrawal and, after a small delay, it will sign the pending withdrawal and submit the signature to the DAppChain Gateway. In turn, the DAppChain Gateway emits an event to notify us that the pending withdrawal has been signed. Here's how we can make sure that the event has been emitted:
Then, we can get the withdrawal receipt and the signature using something like this:
Lastly, let's withdraw TRX to our TRON account:
#Refreshing Balances
We'll be using a simple function to refresh our balances:
On zeknd, we can just listen to events using something like this:
Since TRX is a native token on TRON, there are no events we could listen to. Thus, to make it so that the web UI automatically updates our balance on TRON, we will poll the account balance as follows:
#Wrapping it up
We've built a small demo project to showcase this functionality. The source code is available here.
Last updated