Pārlūkot izejas kodu

余额对接完成

DevYK 2 gadi atpakaļ
vecāks
revīzija
0c9a45ec43
3 mainītis faili ar 98 papildinājumiem un 24 dzēšanām
  1. 63 11
      model/db/account_info_db.js
  2. 31 13
      model/moralis_sdk.js
  3. 4 0
      test/accout_info_db_test.js

+ 63 - 11
model/db/account_info_db.js

@@ -2,6 +2,7 @@ const logger = require('../logger')
 var { db_config } = require('../../config/config.js')
 const utils = require('../utils.js')
 var mysql = require('mysql');
+const redis = require("./redis_db")  //导入 db.js
 var port = db_config.mysql.PORT
 var host = db_config.mysql.HOST
 var username = db_config.mysql.USERNAME
@@ -89,22 +90,30 @@ function addConnEvent() {
 }
 
 
+
 async function getAccountBalances_(opts) {
     logger.log('getAccountBalances', opts)
     var sql_main = 'select * from '
-    var sql_table_name = ' user_banlance '
+    var sql_table_name = ' user_balance '
     var sql_where = ' WHERE '
-    var sql_where_name = ' id= ? '
+    var sql_where_name = ' usr_address=? ORDER BY update_tm DESC '
+    var query_account_balances_params = [opts.address]
+    if (opts.type == 'native') {
+        sql_where_name = ' usr_address=? AND token_address=? ORDER BY update_tm DESC '
+        query_account_balances_params = [opts.address, '0x0000000000000000000000000000000000000000']
+    } else if (opts.type == 'token') {
+        sql_where_name = ' usr_address=? AND token_address!=? ORDER BY update_tm DESC '
+        query_account_balances_params = [opts.address, '0x0000000000000000000000000000000000000000']
+    }
     var new_sql = sql_main.concat(sql_table_name, sql_where, sql_where_name);
     var query_account_balances_sql = new_sql
 
-    var query_account_balances_params = [withdrawId]
 
     return new Promise((resolve) => {
         getMySqlInstance().getConnection(function (err, connection) {
             if (err) {
-                logger.error('getAccountBalances error', err)
-                logger.error('getAccountBalances sql', create_withdraw_sql)
+                logger.error('getAccountBalances_ error', err)
+                logger.error('getAccountBalances_ sql', create_withdraw_sql)
                 resolve(null);
                 return;
             }
@@ -112,15 +121,14 @@ async function getAccountBalances_(opts) {
                 query_account_balances_sql, query_account_balances_params,
                 function selectCb(error, results) {
                     if (error) {
-                        logger.error('create_collect_coins_task', error, query_account_balances_sql, query_account_balances_params)
+                        logger.error('getAccountBalances_', error, query_account_balances_sql, query_account_balances_params)
                         resolve(null);
                         return;
                     }
-                    logger.log('create_collect_coins_task ret=', error, results);
+                    logger.log('getAccountBalances_ ret=', error, results);
                     //用完当前连接需要释放,归还给连接池
                     connection.release();
                     resolve({
-                        err: error,
                         results: results
                     });
                 }
@@ -176,11 +184,55 @@ async function getAccountTransactions_(opts) {
     })
 }
 
+
 async function getAccountBalances(opts) {
+    var ret = await getAccountBalances_(opts);
+    var results = []
+    if (ret && ret.results) {
+        if (ret.results && Array.isArray(ret.results) && ret.results.length > 0) {
+            for (let index = 0; index < ret.results.length; index++) {
+                const element = ret.results[index];
+                if (element.token_address == '0x0000000000000000000000000000000000000000') {
+                    //
+                    results.push({
+                        type: 'native',
+                        balance: utils.scientificNotationToString(element.balance).toString()
+                    })
+                } else {
+                    // {
+                    //     token_address: '0x03716f32f72c692a0b355fa04639669e3341b94e',
+                    //     name: 'BF_BSC_XXXXXX',
+                    //     symbol: 'BSC_BF_6X',
+                    //     logo: null,
+                    //     thumbnail: null,
+                    //     decimals: 18,
+                    //     balance: '1000000000000000000000'
+                    //   }
+                    var decimals = 1
+                    try {
+                        decimals = await redis.readRedis('REDIS_ERC20_CONTRACT_DECIMALS_' + element.token_address.toLowerCase())
+                    } catch (error) {
 
+                    }
+                    results.push({
+                        type: 'token',
+                        token_address: element.token_address,
+                        balance: utils.scientificNotationToString(element.balance).toString(),
+                        decimals: decimals
+                    })
+                }
+            }
+        }
+    }
+    return {
+        code: 0,
+        data: {
+            total: results.length,
+            results: results
+        }
+    }
 }
 
-
 async function getAccountTransactions(opts) {
     var ret = await getAccountTransactions_(opts);
     if (ret && ret.results) {
@@ -207,9 +259,9 @@ async function getAccountTransactions(opts) {
                         value: element.value,
                         gas: element.gas,
                         gas_price: element.gas_price,
-                        block_timestamp: utils.getTimestampToDate(element.block_tm*1000),
+                        block_timestamp: utils.getTimestampToDate(element.block_tm * 1000),
                         trx_hash: element.trx_hash,
-                        responseType:'yqcx'
+                        responseType: 'yqcx'
                     })
                 });
                 ret.results = results

+ 31 - 13
model/moralis_sdk.js

@@ -215,9 +215,6 @@ async function getAccountBalances(options) {
     if (options.chain) {
         options.chain = utils.getChainName(options.chain)
     }
-
-
-
     //做 3次 重试,每次间隔 1s+=
     //Error: Request failed with status code 524
     //Error: Request failed with status code 500
@@ -234,10 +231,10 @@ async function getAccountBalances(options) {
         try {
             if (options.type == 'native') {
                 // result = await Moralis.Web3API.account.getNativeBalance(balance_opts);
-                result = await getBalances(balance_opts, 'native')
+                result = await getBalances(balance_opts, 'native', 1)
                 logger.log('getNativeBalance=', result);
             } else {
-                result = await getBalances(balance_opts, 'token')
+                result = await getBalances(balance_opts, 'token', 1)
                 // result = await Moralis.Web3API.account.getTokenBalances(balance_opts);
                 logger.log('getTokenBalances=', result);
             }
@@ -246,8 +243,19 @@ async function getAccountBalances(options) {
             }
             break
         } catch (error) {
+            logger.error('getBalances error:', error.toString(), JSON.stringify(balance_opts), JSON.stringify(options))
             if (tryCount == 1) {
-                logger.error('getBalances error:', error.toString(), JSON.stringify(balance_opts), JSON.stringify(options))
+                try {
+                    result = await getBalances(balance_opts, options.type, 0)
+                    if (result != null) {
+                        logger.error('sync-node-getBalances success', JSON.stringify(balance_opts), options.type)
+                        break
+                    } else {
+                        logger.error('sync-node-getBalances error', JSON.stringify(balance_opts), options.type)
+                    }
+                } catch (error) {
+                    logger.error('getBalances error:', error.toString(), JSON.stringify(balance_opts), JSON.stringify(options))
+                }
                 result = null;
                 break
             }
@@ -482,7 +490,7 @@ async function updateNativeBalance(nativeBalance, obj) {
         do {
             //上面转账完 BNB 会减去,这里再获取一次
             // var native_ret = await Moralis.Web3API.account.getNativeBalance(temp);
-            var native_ret = await getBalances(balance_opts, 'native');
+            var native_ret = await getBalances(balance_opts, 'native', 1);
             logger.log('更新余额 :', nativeBalance, native_ret, retryCount)
             if (nativeBalance != native_ret.balance && BigInt(nativeBalance) < BigInt(native_ret.balance)) {
                 return native_ret.balance;
@@ -1348,7 +1356,7 @@ async function getTransferRecord(opts, type, use_moralis_sdk_) {
                         gas_price: element.gas_price,
                         block_timestamp: element.block_timestamp,
                         trx_hash: element.hash,
-                        responseType:'moralis'
+                        responseType: 'moralis'
                     })
                 }
             }
@@ -1366,7 +1374,7 @@ async function getTransferRecord(opts, type, use_moralis_sdk_) {
                         value: element.value,
                         block_timestamp: element.block_timestamp,
                         trx_hash: element.transaction_hash,
-                        responseType:'moralis'
+                        responseType: 'moralis'
                     })
                 }
             }
@@ -1384,7 +1392,7 @@ async function getTransferRecord(opts, type, use_moralis_sdk_) {
                     gas_price: ret.gas_price,
                     block_timestamp: ret.block_timestamp,
                     trx_hash: ret.hash,
-                    responseType:'moralis'
+                    responseType: 'moralis'
                 })
         }
         return {
@@ -1413,10 +1421,10 @@ async function getTransferRecord(opts, type, use_moralis_sdk_) {
  * 获取 token or native 余额
  * @param {*} opts 
  */
-async function getBalances(opts, type) {
+async function getBalances(opts, type, use_moralis_sdk_) {
     logger.info('getBalances>>>>>>>>', opts, type)
     //是否使用 moralis sdk 进行查询
-    var use_moralis_sdk = 1
+    var use_moralis_sdk = use_moralis_sdk_
     var temp_opts = { ...opts }
     if (use_moralis_sdk) {
         if (type == 'native') {
@@ -1425,7 +1433,17 @@ async function getBalances(opts, type) {
             return await Moralis.Web3API.account.getTokenBalances(temp_opts);
         }
     } else {
-
+        if (type == 'native') {
+            temp_opts.type = 'native'
+            var ret = await account_mysql.getAccountBalances(temp_opts)
+            if (ret) {
+                return ret.results[0]
+            }
+        } else if (type == 'token') {
+            temp_opts.type = 'token'
+            var ret = await account_mysql.getAccountBalances(temp_opts)
+            return ret.results
+        }
     }
 }
 

+ 4 - 0
test/accout_info_db_test.js

@@ -9,5 +9,9 @@ router.prefix('/test/account/');
 router.post('/getAccountTransactions', async (ctx) => {
     ctx.body = await moralis.getTokenTransfersV2(ctx.request.body)
 })
+
+router.post('/getAccountBalances', async (ctx) => {
+    ctx.body = await mysql.getAccountBalances(ctx.request.body)
+})
 module.exports = router