Now, let's write a decentralized application with this library. The simplest decentralized application script would be sending money from one account to another. Name the script send_money_ganache.py:
from web3 import Web3, HTTPProvider
w3 = Web3(HTTPProvider('http://localhost:7545'))
private_key = '59e31694256f71b8d181f47fc67914798c4b96990e835fc1407bf4673ead30e2'
transaction = {
'to': Web3.toChecksumAddress('0x9049386D4d5808e0Cd9e294F2aA3d70F01Fbf0C5'),
'value': w3.toWei('1', 'ether'),
'gas': 100000,
'gasPrice': w3.toWei('1', 'gwei'),
'nonce': 0
}
signed = w3.eth.account.signTransaction(transaction, private_key)
tx = w3.eth.sendRawTransaction(signed.rawTransaction)
Before you execute this script, launch Ganache first. After doing so, take any public address you like and put it into the to field in the transaction dictionary. This account will be the receiver. Then find another account, look at its private key, and input the value in theĀ private_key variable:
Put one ether in theĀ value field. This means you want to send 1 ether to another account. This is a simple script to illustrate how sending a transaction works. It does not show best practice because you shouldn't put a private key embedded in the code like this. You could read a private key from the file with restricted permission, for example, or you could request the private key from the standard input.
If you execute this script, you would notice that the receiver's balance would increase by 1 ETH, while the sender's balance would decrease by 1 ETH:
Here is the following output: