forked from critesjosh/celo-transak
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
199 lines (173 loc) · 7.25 KB
/
index.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
const config = require('./config');
const BigNumber = require('bignumber.js');
const Web3 = require("web3");
const ContractKit = require("@celo/contractkit");
const timeOut = 20000;
const _toDecimal = (amount, decimals) => {
return new BigNumber(amount).div(`1e${decimals}`).toString(10);
}
function getTransactionLink(txId, network) {
let networkDetails = (network === 'main') ? config.networks.main : config.networks.testnet;
return networkDetails.transactionLink(txId);
}
function getWalletLink(walletAddress, network) {
let networkDetails = (network === 'main') ? config.networks.main : config.networks.testnet;
return networkDetails.walletLink(walletAddress);
}
async function getBalance(address, network, token = 'CELO') {
try {
let networkDetails = (network === 'main') ? config.networks.main : config.networks.testnet;
const web3 = new Web3(networkDetails.provider);
let contractKit = ContractKit.newKitFromWeb3(web3)
let rawBalance
if (token.toUpperCase() === 'CELO'){
rawBalance = await contractKit.connection.getBalance(address)
}
else if (token.toUpperCase() === 'CUSD') {
stableToken = await contractKit.contracts.getStableToken()
rawBalance = await stableToken.balanceOf(address)
}
else {
throw new Error("Could not get balance. Token not recognized.")
}
if (rawBalance) return Number(_toDecimal(rawBalance, 18));
else throw new Error("Could not get balance.");
} catch (e) {
console.error(e)
return "error";
}
}
async function isValidWalletAddress(address, network) {
try {
let networkDetails = (network === 'main') ? config.networks.main : config.networks.testnet;
let web3 = new Web3(networkDetails.provider)
let isValid = web3.utils.isAddress(address)
if (!isValid) return false;
else return true;
} catch (e) {
return false;
}
}
async function getTransaction(hash, network) {
let response = false;
let amount, token
try {
if (hash) {
let networkDetails = (network === 'main') ? config.networks.main : config.networks.testnet;
const web3 = new Web3(networkDetails.provider)
const contractKit = ContractKit.newKitFromWeb3(web3)
let tx = await contractKit.connection.getTransaction(hash)
let receipt = await contractKit.connection.getTransactionReceipt(hash)
celoToken = await contractKit.contracts.getGoldToken()
stableToken = await contractKit.contracts.getStableToken()
let transferLog = receipt.logs[0]
// check if the transfer is cUSD or CELO ERC20 interface
// if so, decode the logs to get the token transfer amount
if(transferLog && (transferLog.address == celoToken.address || transferLog.address == stableToken.address)){
token = transferLog.address === celoToken.address ? "CELO" : "cUSD"
if(transferLog.address != celoToken.address && transferLog.address != stableToken.address) throw new Error("Token transfer is not CELO or cUSD.")
let txInfo = web3.eth.abi.decodeLog([{
type: 'address',
name: 'from',
indexed: true
},{
type: 'address',
name: 'to',
indexed: true
},{
type: 'uint256',
name: 'value'
}],
transferLog.data,
[transferLog.topics[1], transferLog.topics[2]])
amount = txInfo.value
}
else {
token = 'CELO'
amount = tx.value
}
if (tx) {
response = {
tx: tx,
date: new Date(),
transactionHash: hash,
transactionLink: networkDetails.transactionLink(hash),
network: networkDetails.networkName,
gasPrice: tx.gasPrice,
gas: tx.gas,
feeCurrency: tx.feeCurrency,
gatewayFee: tx.gatewayFee,
gatewayFeeRecipient: tx.gatewayFeeRecipient,
gasCostInCrypto: Number(_toDecimal((tx.gasPrice * tx.gasLimit), 18)),
amount: Number(_toDecimal(amount, 18)),
token: token,
from: tx.from,
to: tx.to,
nonce: tx.nonce,
receipt: receipt
}
} else resonse = null
}
return response
} catch (e) {
console.log(e)
}
}
async function sendTransaction({to, amount, network, privateKey, token = 'CELO', feeCurrency = 'CELO'}) {
try {
//Set network
let networkDetails = (network === 'main') ? config.networks.main : config.networks.testnet;
//Set provider
let web3 = new Web3(networkDetails.provider)
let contractKit = ContractKit.newKitFromWeb3(web3)
let gasCostCryptoCurrency = (feeCurrency.toLowerCase() === 'celo') ? null : await contractKit.registry.addressFor(ContractKit.CeloContract.StableToken)
//get signer data using key
contractKit.addAccount(privateKey)
let accounts = await contractKit.connection.getAccounts()
let account = accounts[0]
let balance, tx, currentBalance
//Check balance
if (token.toUpperCase() === 'CELO'){
balance = await contractKit.connection.getBalance(account)
if (Number(_toDecimal(balance, 18)) < Number(_toDecimal(amount, 18))) throw new Error('Insufficient CELO balance in wallet')
tx = await contractKit.sendTransaction({
from: account,
to: to,
value: amount,
feeCurrency: gasCostCryptoCurrency
})
}
else if (token.toUpperCase() === 'CUSD'){
stableToken = await contractKit.contracts.getStableToken()
balance = await stableToken.balanceOf(account)
if (Number(_toDecimal(balance, 18)) < Number(_toDecimal(amount, 18))) throw new Error('Insufficient cUSD balance in wallet')
tx = await stableToken.transfer(to, amount).send({ from: account, feeCurrency: gasCostCryptoCurrency })
} else {
throw new Error('Unrecognized token')
}
let receipt = await tx.waitReceipt()
return ({
date: new Date(),
transactionHash: receipt.transactionHash,
transactionLink: networkDetails.transactionLink(receipt.transactionHash),
network: networkDetails.networkName,
gas: tx.gasUsed,
gasCostInCrypto: Number(_toDecimal((tx.gasPrice * tx.gasLimit), 18)),
gasCostCryptoCurrency: gasCostCryptoCurrency,
amount: Number(_toDecimal(tx.value, 18)),
from: account,
to: receipt.to,
receipt: receipt
});
} catch (e) {
throw(e)
}
}
module.exports = {
getTransactionLink,
getWalletLink,
getTransaction,
isValidWalletAddress,
sendTransaction,
getBalance,
};