-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathuranik-eth-lib.js
executable file
·220 lines (183 loc) · 5.95 KB
/
uranik-eth-lib.js
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
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
'use strict';
var Web3 = require('web3')
var net = require('net');
var web3 = new Web3(new Web3.providers.HttpProvider('http://127.0.0.1:8588')); //rpc 8545 real eth net, 8588 rolsen testnet
//var web3 = new Web3('\\\\.\\pipe\\geth.ipc', net); // ipc connection
// The minimum ABI to get ERC20 Token balance and name and symbol info
let minABI = [
//name
{"constant":true,"inputs":[],"name":"name","outputs":[{"name":"","type":"string"}],"payable":false,"stateMutability":"view","type":"function"},
//symbol
{"constant":true,"inputs":[],"name":"symbol","outputs":[{"name":"","type":"string"}],"payable":false,"stateMutability":"view","type":"function"},
// balanceOf
{
"constant":true,
"inputs":[{"name":"_owner","type":"address"}],
"name":"balanceOf",
"outputs":[{"name":"balance","type":"uint256"}],
"type":"function"
},
// decimals
{
"constant":true,
"inputs":[],
"name":"decimals",
"outputs":[{"name":"","type":"uint8"}],
"type":"function"
},
// transfer token coins
{
"constant":false,
"inputs":[{"name":"to","type":"address"},{"name":"value","type":"uint256"}],
"name":"transfer",
"outputs":[{"name":"","type":"bool"}],
"payable":false,
"stateMutability":"nonpayable",
"type":"function"
}
];
class Token{
constructor(parent) {
this.parent=parent;
}
setTokenContract(contractAddress){
this.contract = new web3.eth.Contract(minABI,contractAddress);
}
async getName(){
let name=await this.contract.methods.name().call();
return name;
}
async getSymbol(){
let symbol=await this.contract.methods.symbol().call();
return symbol;
}
async getBalance(ethaddress){
let balance=await this.contract.methods.balanceOf(ethaddress).call();
let decimals = await this.contract.methods.decimals().call();
return balance/Math.pow(10,decimals);
}
async transfer(fromAddrPrivateKey,toAddr, tokenAmount ){
let decimals = await this.contract.methods.decimals().call();
let to,skey,amount,fee;
to=toAddr;
skey=fromAddrPrivateKey;
amount=0; // eth amount = 0 for token transfer
// if fee undefined - calculated automativally
let internalAmount= tokenAmount * Math.pow(10,decimals);
let params={to,skey,amount,fee};
params.data = await this.contract.methods.transfer(toAddr, internalAmount).encodeABI();
let hash = await this.parent.sendRawTx(params);
return hash;
}
}
class Eth{
constructor() {
this.token=new Token(this);
}
async getNewAddress(){
var addrobj = await web3.eth.accounts.create();
return addrobj;
}
// return balance in ETH
async getBalance(addr,blocknumber){
let balance;
if(blocknumber){
balance =await web3.eth.getBalance(addr,blocknumber);
}else{
balance =await web3.eth.getBalance(addr);
}
let ethBalance=await web3.utils.fromWei(balance, 'ether');
return ethBalance;
}
// return balance in Wei
async getBalanceWei(addr,blocknumber){
let balance;
if(blocknumber){
balance =await web3.eth.getBalance(addr,blocknumber);
}else{
balance =await web3.eth.getBalance(addr);
}
let WeiBalance=balance;
return WeiBalance;
}
async getBlockNumber(){
return await web3.eth.getBlockNumber();
}
async mainAccount(){
var addressArr = await web3.eth.getAccounts();
if(!addressArr || addressArr.length===0){
throw new Error('error get main eth address');
}
return addressArr[0];
}
// async transfer(fromAddr,toAddr, value){
// var localKeys = await web3.eth.getAccounts();
// var personalAccount = localKeys[0];
// const tx = await web3.eth.sendTransaction({to: toAddr, from: fromAddr, value: value });
// return tx;
// }
// call any web3.eth method
async call(method,params=null){
if(params===null){
return await web3.eth[method]();
}else{
let args=[];
for(let i=1;i<arguments.length;i++){
args.push(arguments[i]);
}
return await web3.eth[method].apply(this, args);
}
}
// params is object {to,skey,amount,fee}
// where amount in ETH, fee in ETH
// to - destination address
// skey - private key
async sendRawTx(params){
var Tx = require('ethereumjs-tx').Transaction;
//var privateKey = Buffer.from(params.skey, 'hex');
if(!params.to || !params.skey || typeof params.amount == "undefined"){
throw new Error('bad arguments');
}
if(params.amount<0){
throw new Error('amount less 0');
}
let gasPrice=await web3.eth.getGasPrice();
let wei=await web3.utils.toWei( String(params.amount) , "ether");
let gasLimit='21000'; // standart limit for send ETH coins
let weifee=Math.round( (+gasPrice)*(+gasLimit) );
let ethfee=await web3.utils.fromWei(String(weifee), 'ether');
let txGasPrice;
if(params.fee)
txGasPrice= String( Math.round( await web3.utils.toWei( String(params.fee) , "ether")/21000 ) );
else
txGasPrice= gasPrice;
let gasamount=(+txGasPrice)*21000;
let wei2=Math.round(+wei-gasamount);
let txObj={
to: params.to,
value: web3.utils.toHex( String(wei2) ),
gasLimit: gasLimit,
gasPrice: String( Math.round(txGasPrice) )
};
if(typeof params.nonce !== "undefined"){
txObj.nonce=params.nonce;
}
if(typeof params.data !== "undefined"){
txObj.data=params.data;
}
let rawtx=await web3.eth.accounts.signTransaction(txObj, params.skey);
if(!rawtx.rawTransaction){
throw new Error('error create raw transaction');
}
function getHashAndSendSignedTransaction() {
return new Promise( function(resolve, reject) {
web3.eth.sendSignedTransaction(rawtx.rawTransaction)
.on('transactionHash', function(hash){ return resolve(hash) })
.on('error', function(error){return reject(error)});
});
}
let res=await getHashAndSendSignedTransaction();
return res; // return hash example 0x452dfcc00d44af1624b74bbd02809c200feffeb3
}
}
module.exports = Eth;