forked from xf00f/web3x
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.ts
More file actions
149 lines (126 loc) · 4.94 KB
/
index.ts
File metadata and controls
149 lines (126 loc) · 4.94 KB
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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
import { Address } from 'web3x-es/address';
import { ENS } from 'web3x-es/ens';
import { Eth } from 'web3x-es/eth';
import { Net } from 'web3x-es/net';
import { LegacyProvider, LegacyProviderAdapter } from 'web3x-es/providers';
import { fromWei, toWei } from 'web3x-es/utils';
import { Wallet } from 'web3x-es/wallet';
import { DaiContract } from './contracts/DaiContract';
declare const web3: {
currentProvider: LegacyProvider;
};
/*
Demonstrates how to create a minimally sized build. If you only need to provide access to Ethereum calls over a
websocket connection, with no local accounts (e.g. interfacing with Metamask or a remote node with accounts),
then it makes no sense to bundle all the crypto/provider/accounts code with your app. Construct only
the components you need and keep things lean.
Demonstrates use of a code generated contract with full type safety.
*/
async function main() {
const eth = new Eth(new LegacyProviderAdapter(web3.currentProvider));
const net = new Net(eth);
const network = await net.getNetworkType();
addMessage(`Connected to network: ${network}`);
addMessage(`Network Id: ${await eth.getId()}`);
addMessage(`Provider info: ${await eth.getNodeInfo()}`);
// Work with a code generated contract.
await addDaiBalance(eth);
if (network === 'main') {
addMessage('Join a testnet to test sending transactions.');
addBr();
} else {
await addSendingExamples(eth);
}
// Work with ENS.
await addEnsExamples(eth);
}
/*
Prints the amount of DAI stored at the zero address.
Contract is fully type safe as types were generated by web3x-codegen and contracts.json.
*/
async function addDaiBalance(eth: Eth) {
const DAI_CONTRACT_ADDRESS = Address.fromString('0xc4375b7de8af5a38a93548eb8453a498222c4ff2');
try {
const contract = new DaiContract(eth, DAI_CONTRACT_ADDRESS);
const daiBalance = await contract.methods.balanceOf(Address.ZERO).call();
addMessage(`Balance of DAI 0 address: ${fromWei(daiBalance, 'ether')}`);
addBr();
} catch (_) {
addMessage('Failed to get DAI 0 address balance, probably not on kovan?');
addBr();
}
}
/*
Add some buttons to allow sending to and from the provider account (usually MetaMask) and
the local, in app generated account.
*/
async function addSendingExamples(eth: Eth) {
const providerAddress = (await eth.getAccounts())[0];
if (!providerAddress) {
addMessage('No account returned from provider. Is provider unlocked?');
return;
}
eth.defaultFromAddress = providerAddress;
const providerBalance = await eth.getBalance(providerAddress);
addMessage(`Balance of provider account: ${fromWei(providerBalance, 'ether')} ETH`);
addBr();
// Create and save local account.
const wallet = (await Wallet.fromLocalStorage('my_password')) || new Wallet();
if (!wallet.length) {
wallet.create(1);
await wallet.saveToLocalStorage('my_password');
}
// Make eth aware of wallet so it can use accounts for sending etc.
// Alternatively you can use sendTransaction directly on Account object.
eth.wallet = wallet;
const walletAccount = wallet.get(0)!;
const localBalance = await eth.getBalance(wallet.get(0)!.address);
addMessage(`Balance of local account: ${fromWei(localBalance, 'ether')} ETH`);
addMessage('The following button will send ETH from provider account to local account.');
addSendTo(eth, providerAddress, walletAccount.address);
addBr();
addMessage('The following button will send ETH from local account to provider account.');
addSendTo(eth, walletAccount.address, providerAddress);
addBr();
}
async function addSendTo(eth: Eth, from: Address, to: Address) {
const button = document.createElement('button');
button.onclick = () => send(eth, from, to);
button.textContent = `Send 0.01 ETH`;
document.body.appendChild(button);
addBr();
}
async function send(eth: Eth, from: Address, to: Address) {
try {
const sendTx = await eth.sendTransaction({ value: toWei('0.01', 'ether'), from, to, gas: 50000 });
const txHash = await sendTx.getTxHash();
addMessage(`Sent transaction ${txHash}`);
const receipt = await sendTx.getReceipt();
addMessage(`Transaction complete for ${receipt.transactionHash}.`);
addMessage(`New 'from' balance: ${fromWei(await eth.getBalance(from), 'ether')}`);
addMessage(`New 'to' balance: ${fromWei(await eth.getBalance(to), 'ether')}`);
addBr();
} catch (err) {
addMessage(err.message);
}
}
async function addEnsExamples(eth: Eth) {
try {
const ens = new ENS(eth);
const address = await ens.getAddress('ethereum.eth');
addMessage(`The ENS address ethereum.eth resolves to ${address}`);
addBr();
} catch (err) {
addMessage(err.message);
}
}
function addMessage(msg: string) {
const div = document.createElement('div');
div.innerText = msg;
document.body.appendChild(div);
}
function addBr() {
document.body.appendChild(document.createElement('br'));
}
// tslint:disable-next-line:no-console
main().catch(console.error);