-
Notifications
You must be signed in to change notification settings - Fork 0
/
crypto_wallet.py
71 lines (53 loc) · 1.97 KB
/
crypto_wallet.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
# Cryptocurrency Wallet
# This file contains the Ethereum transaction functions.
# Imports
import os
import requests
from dotenv import load_dotenv
load_dotenv("SAMPLE.env")
from bip44 import Wallet
from web3 import Account
from web3.auto.infura.kovan import w3
from web3 import middleware
from web3.gas_strategies.time_based import medium_gas_price_strategy
# Wallet functionality
def generate_account():
"""Create a digital wallet and Ethereum account from a mnemonic seed phrase."""
# Fetch mnemonic from environment variable.
mnemonic = str(os.getenv("MNEMONIC.env"))
# Create Wallet Object
wallet = Wallet(mnemonic)
# Derive Ethereum Private Key
private, public = wallet.derive_account("eth")
# Convert private key into an Ethereum account
account = Account.privateKeyToAccount(private)
return account
def get_balance(address):
"""Using an Ethereum account address access the balance of Ether"""
# Get balance of address in Wei
wei_balance = w3.eth.get_balance(address)
# Convert Wei value to ether
ether = w3.fromWei(wei_balance, "ether")
# Return the value in ether
return ether
def send_transaction(account, to, wage):
"""Send an authorized transaction to the Kovan testnet."""
# Set gas price strategy
w3.eth.setGasPriceStrategy(medium_gas_price_strategy)
# Convert eth amount to Wei
value = w3.toWei(wage, "ether")
# Calculate gas estimate
gasEstimate = w3.eth.estimateGas({"to": to, "from": account.address, "value": value})
# Construct a raw transaction
raw_tx = {
"to": to,
"from": account.address,
"value": value,
"gas": gasEstimate,
"gasPrice": w3.eth.generateGasPrice(),
"nonce": w3.eth.getTransactionCount(account.address)
}
# Sign the raw transaction with ethereum account
signed_tx = account.signTransaction(raw_tx)
# Send the signed transactions
return w3.eth.sendRawTransaction(signed_tx.rawTransaction)