forked from octalmage/terrajs-examples
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
178 lines (165 loc) · 6.84 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
const { LCDClient, MnemonicKey, MsgSend, isTxError, Coin, MsgExecuteContract } = require("@terra-money/terra.js")
const { consoleError, getGasPrice, _fetchStatusFromLogs, _fetchTrasactionData, _fetchFeeFromTx, _toCrypto, _toDecimal, _getNetworkDetails } = require("./utils.js")
const validWallet = /terra1[a-z0-9]{38}/g
const _ = require("lodash")
const getTerra = (network) => {
return new LCDClient({
URL: _getNetworkDetails(network).provider,
chainID: _getNetworkDetails(network).networkName,
})
}
const getTransactionLink = (txId, network) => _getNetworkDetails(network).transactionLink(txId)
const getWalletLink = (walletAddress, network) => _getNetworkDetails(network).walletLink(walletAddress)
const _getBalance = (address, network) => getTerra(network).bank.balance(address)
const _getCW20Balance = ({ walletAddress, contractAddress, network }) => {
return getTerra(network).wasm.contractQuery(contractAddress, { balance: { address: walletAddress } })
// return fetch(`${_getNetworkDetails(network).provider}/wasm/contract/${contractAddress}/store?query_msg={"balance":{"address":"${walletAddress}"}}`)
}
const getBalance = async (address, network, denom, contractAddress = null, decimals = 6) => {
try {
let balanceInDec
if (!contractAddress) {
const balances = await _getBalance(address, network)
const balance = _.get(balances[0]._coins, denom, {}).amount || 0
balanceInDec = Number(_toDecimal(balance.toString(), decimals))
} else {
const balance = (await _getCW20Balance({ walletAddress: address, contractAddress, network })).balance
balanceInDec = balance ? Number(_toDecimal(balance, decimals)) : 0
}
return balanceInDec
} catch (err) {
consoleError({
message: `some error occured fetching balance for address ${address} on network ${network} for original error look into extra field`,
err,
})
return false
}
}
// returns Boolean
const isValidWalletAddress = (address) => new RegExp(validWallet).test(address)
// return number
const getNonce = async ({ network, mnemonic }) => {
return await getTerra(network).wallet(new MnemonicKey({ mnemonic })).sequence()
}
// return Object
const sendTransaction = async ({ to, memo, amount, network, mnemonic, nonce, denom, gasPrice, contractAddress, decimals = 6 }) => {
try {
//Get Provider
const terra = getTerra(network)
// format amount in base currecy (eg. uluna for LUNA) format
const amoutnInCrypto = _toCrypto(amount, decimals).toString()
// get wallet for signing
const mk = new MnemonicKey({
mnemonic,
})
const wallet = terra.wallet(mk)
// crypto transfer message
const send = !contractAddress
? new MsgSend(wallet.key.accAddress, to, {
[denom]: amoutnInCrypto,
})
: new MsgExecuteContract(
wallet.key.accAddress,
contractAddress, // CW20 token address.
{
transfer: {
amount: amoutnInCrypto,
recipient: to,
},
}
)
// sign transaction
const transaction = await wallet.createAndSignTx({
msgs: [send],
gasPrices: [new Coin("uluna", gasPrice || "0.15")],
...(nonce ? { nonce } : {}),
...(memo ? { memo } : {}),
})
const sendRes = await terra.tx.broadcast(transaction)
if (isTxError(sendRes)) {
throw new Error(`encountered an error while running the transaction: ${sendRes.code} ${sendRes.codespace} message : ${sendRes.raw_log}`)
}
return {
transactionData: sendRes,
receipt: {
date: new Date(),
transactionHash: sendRes.txhash,
transactionLink: _getNetworkDetails(network).transactionLink(sendRes.txhash),
network: _getNetworkDetails(network).networkName,
gasPrice: Number((Number(_.get(transaction, "auth_info.fee.amount._coins.uluna.amount", 0)) / sendRes.gas_wanted).toFixed(6)),
gasLimit: sendRes.gas_wanted,
gasUsed: sendRes.gas_wanted,
gasCostInCrypto: Number(_fetchFeeFromTx(transaction)),
gasCostCryptoCurrency: "LUNA",
amount: amount,
from: wallet.key.accAddress,
to: to,
nonce: _.get(transaction, "auth_info.signer_infos")[0].sequence,
},
}
} catch (err) {
consoleError({
message: `some error occured sending transaction to ${to} of amount ${amount} for original error look into extra field`,
err,
})
throw err
}
}
const getTransaction = async (txId, network, decimals = 6) => {
try {
const txInfo = await getTerra(network).tx.txInfo(txId)
const status = txInfo.code === 0
const isSuccessful = txInfo.code === 0
const { to, from, value, denom, fee, nonce } = _fetchTrasactionData(txInfo.tx)
const gasPrice = Number((Number(_toCrypto(fee, decimals).toString()) / txInfo.gas_wanted).toFixed(decimals))
response = {
transactionData: txInfo,
date: new Date(),
transactionHash: txInfo.txhash,
transactionLink: getTransactionLink(txInfo.txhash, network),
network: _getNetworkDetails(network).networkName,
gasPrice,
amount: value,
from,
to,
nonce,
gasLimit: txInfo.gas_wanted,
feeCurrency: "LUNA",
receipt: {
date: new Date(),
transactionHash: txInfo.txhash,
transactionLink: getTransactionLink(txInfo.txhash, network),
network: _getNetworkDetails(network).networkName,
gasPrice,
gasLimit: txInfo.gas_wanted,
gasUsed: txInfo.gas_wanted, // unsused gas is not refunded in terra .
gasCostInCrypto: Number(fee),
gasCostCryptoCurrency: "LUNA",
amount: Number(value),
from,
to,
nonce,
status,
isSuccessful,
...(status ? {} : { error: txInfo.raw_log }),
},
}
return response
} catch (err) {
consoleError({
message: `Error encountered fetching transaction with hash ${txId} on ${network} for original error look into extra field`,
err,
})
return false
}
}
module.exports = {
getTransactionLink,
getWalletLink,
getTransaction,
isValidWalletAddress,
sendTransaction,
getBalance,
getNonce,
getGasPrice,
}