moralis_sdk.js 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267
  1. /* import moralis */
  2. const Moralis = require("moralis/node");
  3. var utils = require('./utils.js');
  4. var config = require('../config/config.js');
  5. const redis = require("../model/redis_db") //导入 db.js
  6. /* Moralis init code */
  7. var serverUrl = config.moralis_config.test_server.SERVER_URL;
  8. var appId = config.moralis_config.test_server.APP_ID;
  9. var masterKey = config.moralis_config.test_server.MASTER_KEY;
  10. var moralisSecret = config.moralis_config.test_server.MORALIS_SECRET;
  11. if (config.build_config.open_test == 0) {
  12. serverUrl = config.moralis_config.main_server.SERVER_URL;
  13. appId = config.moralis_config.main_server.APP_ID;
  14. masterKey = config.moralis_config.main_server.MASTER_KEY;
  15. moralisSecret = config.moralis_config.main_server.MORALIS_SECRET;
  16. }
  17. // 内部异常
  18. const ERROR_CODE_001 = -1;
  19. const SUCCEED_CODE = 0;
  20. /**
  21. * 初始化 moralis
  22. * https://st94nif1cq.feishu.cn/docs/doccnNxG2UwHPCdZXbywgbdy13f#
  23. */
  24. async function initMasterSDK() {
  25. await Moralis.start({ serverUrl, appId, masterKey });
  26. }
  27. async function initMoralisSecretSDK() {
  28. await Moralis.start({ serverUrl, appId, moralisSecret });
  29. }
  30. function toJson(code_, obj_, errMsg_) {
  31. return utils.toJson(code_, obj_, errMsg_);
  32. }
  33. const transfer = async (obj) => {
  34. console.debug("fun transfer in ", obj);
  35. console.debug("fun transfer serverUrl ", serverUrl);
  36. console.debug("fun transfer appId ", serverUrl);
  37. console.debug("fun transfer moralisSecret ", moralisSecret);
  38. await initMoralisSecretSDK();
  39. // initSDK(moralisSecret);
  40. console.debug("fun transfer start ok ");
  41. const opts = {};
  42. opts.chainId = 'bsc_testnet';
  43. opts.privateKey = config.moralis_config.test_server.DEFAULT_PRIVATE_KEY;
  44. opts.type = "erc20"; //native erc20
  45. if (!obj.receiver || !obj.amount || parseFloat(obj.amount) <= 0) {
  46. console.error("fun transfer parameter error.");
  47. return toJson(ERROR_CODE_001, null, "please check receiver or amount parameter is ok ?");
  48. }
  49. if (obj.chain != null) {
  50. opts.chainId = utils.getChainId(obj.chain);
  51. console.log("chainId:", opts.chain);
  52. }
  53. if (obj.type != null) {
  54. opts.type = obj.type;
  55. }
  56. if (obj.from_block != null) {
  57. opts.from_block = obj.from_block;
  58. }
  59. if (obj.to_block != null) {
  60. opts.to_block = obj.to_block;
  61. }
  62. opts.contractAddress = obj.contractAddress;
  63. opts.receiver = obj.receiver;
  64. //调用者传入
  65. // opts.amount = Moralis.Units.Token(obj.amount, 18);
  66. opts.amount = obj.amount;
  67. if (obj.privateKey != null) {
  68. opts.privateKey = obj.privateKey;
  69. }
  70. //解密私钥
  71. // var privateKey = utils.decryptPrivityKey(process.env.NENET_CRYPT_KEY, opts.privateKey);
  72. var privateKey = utils.decryptPrivityKey(opts.privateKey);
  73. if (privateKey == null) {
  74. return toJson(-1, null, "decryptPrivityKey error.");
  75. }
  76. try {
  77. // sending 0.5 DAI tokens with 18 decimals on BSC testnet
  78. var options = Moralis.TransferOptions = {}
  79. if (opts.contractAddress) { //如果存在就是代币
  80. options = Moralis.TransferOptions = {
  81. type: opts.type,
  82. amount: opts.amount,
  83. receiver: opts.receiver, //接收钱包地址
  84. contractAddress: opts.contractAddress //用户合约地址
  85. };
  86. // console.log("options=",options);
  87. } else { //ETH or BNB
  88. options = Moralis.TransferOptions = {
  89. type: opts.type,
  90. amount: opts.amount,
  91. receiver: opts.receiver, //接收钱包地址
  92. };
  93. // console.log("options else=",options);
  94. }
  95. // Enable web3
  96. await Moralis.enableWeb3({
  97. //BSC mainnet = 0x38-56 testnet:0x61-97
  98. chainId: opts.chainId,
  99. privateKey: opts.privateKey,
  100. });
  101. var ret = await Moralis.transfer(options);
  102. return toJson(SUCCEED_CODE, ret, "");
  103. } catch (error) {
  104. console.log('transfer error:', error);
  105. if (error.reason != null) {
  106. return toJson(ERROR_CODE_001, null, error.toString());;
  107. } else {
  108. return toJson(ERROR_CODE_001, null, error);;
  109. }
  110. }
  111. };
  112. const getAllTokenWithdrawInfoLists = async (obj) => {
  113. await initMasterSDK();
  114. console.log('queryAllTokenBalance:', JSON.stringify(config.token_balance_config.TOKEN_BALANCE));
  115. return toJson(SUCCEED_CODE, JSON.stringify(config.token_balance_config.TOKEN_BALANCE), null);
  116. }
  117. /**
  118. * 获取代币价格 -> usdPrice
  119. */
  120. const getAllTotkenPrice = async (address, chain) => {
  121. await initMasterSDK();
  122. // const options = {
  123. // address: address,
  124. // chain: chain,
  125. // };
  126. // options.address = '0x7083609fCE4d1d8Dc0C979AAb8c869Ea2C873402'
  127. // options.chain = 'bsc'
  128. // for (let index = 0; index < 1000; index++) {
  129. // var ret = await Moralis.Web3API.token.getTokenPrice(options);
  130. // console.log("getTokenPrice=", index, ret);
  131. // }
  132. // if (1) return '';
  133. try {
  134. var token_price_key = config.reids_token_config.TOKENPRICE;
  135. await redis.redis_get(token_price_key).then((result) => {
  136. console.log("redis_get=", error, result); // Prints "value"
  137. if (result)
  138. return toJson(SUCCEED_CODE, config.token_price_config, null);
  139. else return toJson(ERROR_CODE_001, null, error);
  140. });
  141. // // console.debug("fun getTotkenPrice in ", options);
  142. // if (Array.isArray(config.token_price_config)) {
  143. // // const arrays = JSON.parse(config.token_price_config);
  144. // return toJson(SUCCEED_CODE, config.token_price_config, null);
  145. // }
  146. // // var ret = await Moralis.Web3API.token.getTokenPrice(options);
  147. // return toJson(ERROR_CODE_001, null, 'getTotkenPrice error.');
  148. } catch (error) {
  149. console.error("getTotkenPrice=", error);
  150. return toJson(ERROR_CODE_001, null, error.toString());;
  151. }
  152. }
  153. //获取交易记录
  154. //hash 0xe09ba3a4c9f7a8902e01af68d0f1f91906f3f7db1195227e61c45c0e86b2630a
  155. async function getTokenTransfers(opt) {
  156. await initMasterSDK();
  157. console.debug("fun getTokenTransfers in ", opt);
  158. const options = {};
  159. options.type = 'all';
  160. options.chain = 'bsc_mainnet';
  161. if (opt.chain != null) {
  162. options.chain = utils.getChainName(opt.chain);
  163. console.log('getTokenTransfers=', options.chain);
  164. }
  165. if (opt.order != null) {
  166. options.order = opt.order;
  167. }
  168. if (opt.startTime != null) {
  169. options.from_date = opt.startTime;
  170. }
  171. if (opt.endTime != null) {
  172. options.to_date = opt.endTime;
  173. }
  174. if (opt.from_block != null) {
  175. options.from_block = opt.from_block;
  176. }
  177. if (opt.to_block != null) {
  178. options.to_block = opt.to_block;
  179. }
  180. if (opt.transaction_hash) {
  181. options.transaction_hash = opt.transaction_hash;
  182. options.type = 'transaction_hash';
  183. }
  184. console.debug('getTokenTransfers-->>>', options);
  185. if (options.type == 'all') {//查询主流币和 20 币所有的交易
  186. try {
  187. if (opt.address != null) {
  188. options.address = opt.address;
  189. } else {
  190. return toJson(ERROR_CODE_001, null, "please check address parameter is ok ?");
  191. }
  192. //主流币
  193. var t_1 = await Moralis.Web3API.account.getTransactions(options);
  194. //20币
  195. var t_2 = await Moralis.Web3API.account.getTokenTransfers(options);
  196. let arr = t_1.result;
  197. let arr1 = t_2.result;
  198. if (Array.isArray(arr1) && Array.isArray(arr)) {
  199. let arr2 = arr.concat(arr1);
  200. t_1.result = arr2;
  201. }
  202. return toJson(SUCCEED_CODE, t_1, null);
  203. } catch (error) {
  204. console.error("getTransactions error:", error)
  205. return toJson(ERROR_CODE_001, null, error);;
  206. }
  207. } else if (options.type == 'transaction_hash') {//根据哈希查询
  208. try {
  209. //native
  210. const transaction = await Moralis.Web3API.native.getTransaction(options);
  211. var arr = [];
  212. if (transaction)
  213. arr.push(transaction)
  214. var obj = { result: arr }
  215. return toJson(SUCCEED_CODE, obj, null);
  216. } catch (error) {
  217. console.error("native getTransaction error:", error)
  218. return toJson(ERROR_CODE_001, null, error);;
  219. }
  220. } else {
  221. return toJson(ERROR_CODE_001, null, "This type is not supported.");;
  222. }
  223. }
  224. module.exports = {
  225. transfer,
  226. getTokenTransfers,
  227. toJson,
  228. getAllTokenWithdrawInfoLists,
  229. getAllTotkenPrice,
  230. }