Transferring Ether to another account

So far, you have a list of accounts in the sidebar and can see the balance of each account by selecting them. Now, it's time to implement transfers between accounts.

First of all, we need at least three parameters to perform a successful transaction:

  • Source account
  • Target account
  • Amount to transfer

We are going to use React Hooks since this is the most efficient and fastest way to get started. You need at least three pairs of hooks. Let's get started:

  1. Introduce a pair of React hooks for each attribute:
const [account, setAccount] = useState(null);
const [targetAccount, setTargetAccount] = useState(null);
const [transferAmount, setTransferAmount] = useState(0);

We already handle account selection via the onSelectAccount function. This function can also be updated to keep track of the selected account so that we can use that value to perform transactions.

  1. Update the onSelectAccount function so that you can set and reset the account state:
const onSelectAccount = keys => {
const [account] = keys;

if (account && account !== 'accounts') {
web3.eth.getBalance(account).then(function(result) {
setBalance(web3.utils.fromWei(result, 'ether'));
setAccount(account);
});
} else {
setBalance(0);
setAccount(null);
}
};

Now, you need a form to collect all of the user input and a button to perform the transaction. The Ant Design library can provide you with everything you need.

  1. Import the following extra components to build the form:
import { Layout, Tree, Statistic, Select, Form, Input, Button, message } from 'antd';

At this point, you can start building the form layout. You already have the account state maintained, so let's display it at the top of the form.

  1. Insert the following code inside the Form component:
<Content>
<Statistic
title="Account Balance (Eth)"
value={balance}
precision={2}
/>
<Form style={{ width: 450 }}>
<Form.Item>
<Input value={account} disabled={true}></Input>
</Form.Item>
</Form>
</Content>

As you can see, we're showing the input element but are preventing our users from editing it. The only way to change the field is to pick another account from the tree component in the sidebar.

The next field should allow users to pick the target account. We should already have a list of accounts to back the tree component. We can use the account list to build the picker component.

  1. Append the following input to the Form component:
<Form.Item>
<Select
placeholder="Select target account"
onChange={value => setTargetAccount(value)}
>
{accounts
.filter(acc => acc !== account)
.map(account => (
<Select.Option key={account} value={account}>
{account}
</Select.Option>
))}
</Select>
</Form.Item>
Note that we don't allow the target account to be used as the source account. Each time Select is rendered, we filter out the selected account from the list.

The third field in Form is the number input so that we can provide the amount we wish to transfer.

  1. Append the Input component to Form, as shown in the following code:
<Form.Item>
<Input
type="number"
min="0"
placeholder="Amount"
value={transferAmount}
onChange={e => setTransferAmount(e.target.value)}
></Input>
</Form.Item>
  1. Add the Transfer button to the bottom of the Form:
<Button disabled={!canTransfer()} onClick={onTransferClick}>
Transfer
</Button>

As you can see, the button needs two additional functions: canTransfer, which controls the state of the button, and the onTransferClick event handler for the click event.

  1. Add the button-related functions to the component function:
const canTransfer = () => {
return account && targetAccount && transferAmount && transferAmount > 0;
};

const onTransferClick = () => {
console.log('from', account);
console.log('to', targetAccount);
console.log('amount', transferAmount);
};

canTransfer allows you to disable button unless the following criteria are met:

  • The account is selected in the sidebar.
  • The target account is selected.
  • The transfer amount is provided and it's a non-zero number.

As for the onTransferClick code, we send the form values to the console log for now.

  1. Run the web application and try entering some data. However, leave the amount input with the default zero value. Note that the Transfer button is disabled:

  1. Set the transfer amount field to a non-zero value such as 5. This time, the Transfer button will be enabled:

You can try changing the value to see how the button reacts to the values you enter in real time.
  1. Click the Transfer button and check the browser's console log. You should see the following output:
from 0x528D7a95fCc59C5CCcb3e7f76Ad36b512b223776
to 0xcc188bbcEA06832AB2ce4F5677D07b922a96bF0a
amount 5

As you can see, all three parameters are collected upon the Transfer button being clicked. Now is an excellent time to implement the transaction functionality.

  1. Replace onTransferClick with the following code:
const onTransferClick = () => {
const transaction = {
from: account,
to: targetAccount,
value: web3.utils.toWei(transferAmount, 'ether')
};
web3.eth.sendTransaction(transaction, function(error, hash) {
if (error) {
console.error('Transaction error', error);
} else {
message.info(`Successfully transferred ${transferAmount}. Hash: ${hash}`);
onSelectAccount([account]);
setTransferAmount(0);
}
});
};

In the preceding code, we built the transaction payload and converted the number value into the expected format. Then, we used the web3.eth.sendTransaction API to perform the actual transaction and raised a message popup as soon as the function call succeeded.

Finally, we reloaded the current account information by invoking the onSelectAccount handler. We also reset the current transfer amount input so that our users can't perform another transaction by mistake.

  1. Fill in all of the form parameters and click on the Transfer button. You should see the following output:

We have successfully transferred some Ether from one account to another.

For more details about the message component, as well as documentation and examples, please refer to https://ant.design/components/message/.

Congratulations on completing this section! Now, you have a working digital wallet application. Finally, let's learn how to prepare the application for packaging.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset