ソースを参照

获取交易记录同步 gas 费

DevYK 3 年 前
コミット
f35987bcbb
6 ファイル変更71 行追加133 行削除
  1. 2 1
      config/dev_config.js
  2. 1 0
      config/prd_config.js
  3. 6 5
      config/test_config.js
  4. 28 115
      model/moralis_sdk.js
  5. 5 0
      model/utils.js
  6. 29 12
      routes/sdk.js

+ 2 - 1
config/dev_config.js

@@ -23,6 +23,7 @@ const reids_token_config = {
     GASPRICE: "GASPRICE",
     LAST_TOTAL_BNB_FREE: 'LAST_TOTAL_BNB_FREE',
     LAST_TOTAL_TOKEN_FREE: 'LAST_TOTAL_TOKEN_FREE',
+    LAST_GAS_PRICE: 'LAST_TOKEN_GAS_PRICE',
 }
 // 设置数据库配置文件
 const db_config = {
@@ -67,7 +68,7 @@ const moralis_config = {
     APP_ID: "oSwDtyD9f4GD6XPZgfDCRHPqXrm2pvBUCTv2N0X8",
     MASTER_KEY: "YbEUAR49HwBZ8R6Q8eNTNfwtStPFPcCYehJQkYcl",
     MORALIS_SECRET: "BGlDVjy7054iLDpDcdc9AbH65rZrhj8QIhsThcwF6thNzTnbS2ft8XmM70x4jOpU",
-    DEFAULT_PRIVATE_KEY: "6084c2a5e39fa83d5a119c3a864a442e77287f4b03bad93cef38ec5f44bca630",
+    DEFAULT_PRIVATE_KEY: "xxx",
 }
 
 

+ 1 - 0
config/prd_config.js

@@ -22,6 +22,7 @@ const reids_token_config = {
     GASPRICE: "GASPRICE",
     LAST_TOTAL_BNB_FREE: 'LAST_TOTAL_BNB_FREE',
     LAST_TOTAL_TOKEN_FREE: 'LAST_TOTAL_TOKEN_FREE',
+    LAST_GAS_PRICE: 'LAST_TOKEN_GAS_PRICE',
 
 }
 // 设置数据库配置文件

+ 6 - 5
config/test_config.js

@@ -8,7 +8,7 @@ const account_config = {
     TOKEN_GAS_LIMIT: '80000',
     BNB_GAS_LIMIT: '21000',
     BNB_GAS_PRICE: '10000000000',
-    TRANSFER_GAS:true,
+    TRANSFER_GAS: true,
 }
 
 const cryppt_config = {
@@ -20,8 +20,9 @@ const reids_token_config = {
     TOKENPRICE: 'TOKENPRICE',
     TOKENWITHDRAW: 'TOKENWITHDRAW',
     GASPRICE: "GASPRICE",
-    LAST_TOTAL_BNB_FREE:'LAST_TOTAL_BNB_FREE',
-    LAST_TOTAL_TOKEN_FREE:'LAST_TOTAL_TOKEN_FREE',
+    LAST_TOTAL_BNB_FREE: 'LAST_TOTAL_BNB_FREE',
+    LAST_TOTAL_TOKEN_FREE: 'LAST_TOTAL_TOKEN_FREE',
+    LAST_GAS_PRICE: 'LAST_TOKEN_GAS_PRICE',
 }
 // 设置数据库配置文件
 const db_config = {
@@ -49,13 +50,13 @@ const moralis_config = {
     APP_ID: "oSwDtyD9f4GD6XPZgfDCRHPqXrm2pvBUCTv2N0X8",
     MASTER_KEY: "YbEUAR49HwBZ8R6Q8eNTNfwtStPFPcCYehJQkYcl",
     MORALIS_SECRET: "BGlDVjy7054iLDpDcdc9AbH65rZrhj8QIhsThcwF6thNzTnbS2ft8XmM70x4jOpU",
-    DEFAULT_PRIVATE_KEY: "6084c2a5e39fa83d5a119c3a864a442e77287f4b03bad93cef38ec5f44bca630",
+    DEFAULT_PRIVATE_KEY: "xxx",
 }
 
 
 
 const logger_config = {
-    BASE_PATH:`/datalog/denetnode`,
+    BASE_PATH: `/datalog/denetnode`,
 }
 
 module.exports = {

+ 28 - 115
model/moralis_sdk.js

@@ -40,6 +40,32 @@ function toJson(code_, obj_, errMsg_) {
     return utils.toJson(code_, obj_, errMsg_);
 }
 
+/**
+ * 通过交易记录获取 gas 费用
+ * @param {} type 
+ * @param {*} obj 
+ * @param {*} address 
+ */
+function getTransferRecordGasFree(type, obj, address) {
+    logger.log('getTransferRecordGasFree fun in', type, obj, address)
+    if (obj && obj.data && obj.data.result && Array.isArray(obj.data.result) && obj.data.result.length > 0) {
+        logger.log('getTransferRecordGasFree fun in',1)
+        for (let index = 0; index <  obj.data.result.length; index++) {
+            const element = obj.data.result[index];
+            logger.log('getTransferRecordGasFree fun in 2',element)
+            if (element.type == type && element.to_address.toLowerCase() == address.toLowerCase()) {
+                if (element.gas_price && element.gas && type == 'native') {//native
+                    return {
+                        totalGasFree: parseInt(element.gas_price) * parseInt(element.gas),
+                        gas_price: parseInt(element.gas_price)
+                    }
+                }
+            }
+        }
+    }
+    return null;
+
+}
 
 /**
  * 获取转账的 gas 费
@@ -357,121 +383,6 @@ async function transfers(obj, my_account_all_coins) {
     } else {
         return toJson(-1, null, 'transfer conditions are not met.');
     }
-
-
-    //v0.1 版本归集
-    // var address = obj.address;
-    // var chain = obj.chain;
-    // var tokenPrices = obj.tokenPrices;
-    // logger.log('tokenPrices=', tokenPrices, my_account_all_coins);
-
-    // var nativeValue = my_account_all_coins.native.balance;
-
-    // if (!my_account_all_coins || !tokenPrices) return 'error.'
-
-    // logger.log(' my_account_all_coins.other.lenth=', my_account_all_coins.other.length);
-
-    // var isUpdateNativeBalance = 0;
-
-    // //token 归集
-    // if (my_account_all_coins.other && Array.isArray(my_account_all_coins.other) && my_account_all_coins.other.length > 0) {
-    //     var available = Array.isArray(tokenPrices.tokenPrice) && tokenPrices.tokenPrice.length > 0
-    //     if (!available) return -1;
-    //     for (let i = 0; i < my_account_all_coins.other.length; ++i) {
-    //         var transfer_item = my_account_all_coins.other[i];
-    //         if (my_account_all_coins.other[i].token_address != null) {
-    //             var find_transfer_item = findTokenPriceItem(transfer_item.token_address, tokenPrices);
-    //             //todo 计算 token 币价格 * token美元单价 
-    //             if (find_transfer_item && calculate_total_usdprice(transfer_item.balance, transfer_item.decimals, find_transfer_item.usdPrice) > 1.0) {
-    //                 var info = await queryCompanyInfoFromId(0);
-    //                 var obj_20 = {
-    //                     chain: obj.chain,
-    //                     contractAddress: transfer_item.token_address,
-    //                     amount: transfer_item.balance,
-    //                     receiver: info.user_address,
-    //                     type: 'erc20',
-    //                     address: address,
-    //                 }
-    //                 logger.log('start_collectCoins erc20:', obj_20);
-    //                 logger.log('calculate_total_usdprice 20', calculate_total_usdprice(transfer_item.balance, transfer_item.decimals, '0.1'));
-    //                 isUpdateNativeBalance = 1;
-    //                 var ret = await start_collectCoins(obj_20)
-    //                 logger.log('start_collectCoins erc20 respose...', ret);
-
-    //                 //更新 native 金额
-    //                 if (!isTransferSucceed(ret)) return ret;
-
-    //                 var transfer = getTransferGasFree('token', ret)
-    //                 if (transfer && transfer.totalGasFree > 0) {
-    //                     logger.log('start_collectCoins 20 tempNativeValue=', my_account_all_coins.native.balance)
-    //                     var tempNativeValue = reduceNativeValue(nativeValue, transfer.totalGasFree)
-    //                     my_account_all_coins.native.balance = tempNativeValue.toString();
-    //                     logger.log('start_collectCoins 20  udpateNativeValue=', tempNativeValue);
-    //                 } else return "get native value error."
-    //             } else {
-    //                 logger.error('find_transfer_item error.', transfer_item);
-    //             }
-    //         } else {
-    //             logger.error('token Must be greater than  a dollar.', transfer_item.balance, transfer_item.decimals);
-    //             // return toJson(-1, null, 'token Must be greater than  a dollar.');
-    //         }
-    //     }
-    // }
-
-    // //native 归集
-    // if (my_account_all_coins.native) {
-    //     logger.log('查询本地余额参数=', obj)
-    //     if (obj.chain) {
-    //         obj.chain = utils.getChainName(obj.chain)
-    //     }
-
-    //     obj.chain = chain;
-    //     logger.log('查询本地余额 after', my_account_all_coins.native)
-    //     var find_native_item = findTokenPriceItem('0x0000000000000000000000000000000000000000', tokenPrices);
-    //     //todo 计算 token 币价格 * token美元单价
-    //     if (find_native_item) {
-    //         var nativeCoins = calculate_total_usdprice(my_account_all_coins.native.balance, '18', find_native_item.usdPrice);
-    //         logger.log('start_collectCoins nativeCoins:', nativeCoins, obj);
-    //         logger.log('start_collectCoins obj:', obj);
-    //         logger.log('start_collectCoins native.balance:', my_account_all_coins.native.balance);
-
-
-    //         if (nativeCoins > 1.0) {
-    //             logger.log('native.balance', my_account_all_coins.native.balance)
-    //             logger.log('aGasPrice', obj.transFerGasFree.aGasPrice)
-    //             logger.log('gasLimint', account_config.BNB_GAS_LIMIT)
-    //             // var gasPrice = BigInt(obj.transFerGasFree.aGasPrice);
-
-    //             var gasPrice = BigInt(account_config.BNB_GAS_PRICE);
-    //             var gasLimit = BigInt(account_config.BNB_GAS_LIMIT);
-    //             var nativeBalance = BigInt(my_account_all_coins.native.balance);
-
-    //             logger.log('native.balance>>>', nativeBalance)
-    //             logger.log('aGasPrice>>>', gasPrice)
-    //             logger.log('gasLimint>>>', gasLimit)
-
-    //             var real_native_amount = nativeBalance - gasPrice * gasLimit;
-    //             logger.log('start_collectCoins native amount:', real_native_amount.toString());
-    //             var info = await queryCompanyInfoFromId(0);
-    //             obj = {
-    //                 chain: chain,
-    //                 amount: real_native_amount.toString(),
-    //                 receiver: info.user_address,
-    //                 type: 'native',
-    //                 address: address,
-    //             }
-    //             logger.log('start_collectCoins native:', obj);
-    //             logger.log('calculate_total_usdprice native', nativeCoins, find_native_item);
-    //             return await start_collectCoins(obj)
-    //         } else {
-    //             logger.error('native Must be greater than  a dollar.', obj);
-    //             return toJson(-1, null, 'native Must be greater than  a dollar.');
-    //         }
-    //     } else {
-    //         logger.error('native Must be greater than  a dollar.', obj);
-    //         return toJson(-1, null, 'native Must be greater than  a dollar.');
-    //     }
-    // }
 }
 
 
@@ -890,6 +801,8 @@ module.exports = {
     getAllTotkenPrice,
     withdraw,
     collectCoins,
+    isTransferSucceed,
+    getTransferRecordGasFree,
     pushCollectConisObj,
 }
 

+ 5 - 0
model/utils.js

@@ -24,6 +24,11 @@ function decryptPrivityKey(message) {
     var encrypted = message; //python is base64 ECB
     var key = process.env.DENET_CRYPT_KEY //key used in Python
     var iv = process.env.DENET_CRYPT_IV
+    if(!key || !iv)
+    {
+        logger.error('decryptPrivityKey key or iv is empty?');
+        return null;
+    }
     logger.log('encrypted=', encrypted);
     // logger.log('decryptPrivityKey key= iv=', key, iv);
 

+ 29 - 12
routes/sdk.js

@@ -1,9 +1,10 @@
 var router = require('koa-router')();
 var moralis = require('../model/moralis_sdk.js')
 var utils = require('../model/utils.js');
-
+var { reids_token_config, account_config } = require('../config/config.js');
+const logger = require('../model/logger.js');
 router.prefix('/sdk');
-
+const redis = require("../model/redis_db")  //导入 db.js
 /**
  * 获取代币价格
  * @param {*} ctx 
@@ -28,19 +29,35 @@ async function getTransfers(ctx) {
     if (!obj.chain)//默认 bsc 币安链
         obj.chain = 'bsc'
 
-    //提交归集任务 native 能获取到 gas 、token 无法获取到 gas 费
-    //获取上一次的 gas 费
-    try {
-        var temp_obj = {...obj}
-        if (temp_obj.address) {
-            moralis.pushCollectConisObj(temp_obj)
-        }
-    } catch (error) {
-        console.error('pushCollectConisObj error=',error)
-    }
+    var temp_obj = { ...obj }
+
 
     await moralis.getTokenTransfers(obj).then((result) => {
         ctx.body = result;
+        if (result) {
+            //提交归集任务 native 能获取到 gas 、token 无法获取到 gas 费
+            try {
+                if (temp_obj.address && moralis.isTransferSucceed(result)) {
+                    var json_obj = JSON.parse(result);
+                    //缓存当前交易的 gas 费用
+                    var tr = moralis.getTransferRecordGasFree('native', json_obj, temp_obj.address)
+                    logger.log('getTransferRecordGasFree:', tr, temp_obj.address)
+                    if (tr && tr.totalGasFree > 0) {
+                        logger.log('getTransferRecordGasFree redis_set LAST_TOTAL_BNB_FREE:', tr.totalGasFree.toString())
+                        logger.log('getTransferRecordGasFree redis_set LAST_TOTAL_TOKEN_FREE:', (parseInt(tr.totalGasFree) * parseInt(account_config.TOKEN_GAS_LIMIT)).toString())
+                        redis.redis_set(reids_token_config.LAST_TOTAL_BNB_FREE, tr.totalGasFree.toString());
+                        redis.redis_set(reids_token_config.LAST_TOTAL_TOKEN_FREE, (parseInt(tr.gas_price) * parseInt(account_config.TOKEN_GAS_LIMIT)).toString());
+                    }
+
+                    if (temp_obj.address) {
+                        moralis.pushCollectConisObj(temp_obj)
+                    }
+                }
+            } catch (error) {
+                console.error('pushCollectConisObj error=', error)
+            }
+        }
+
     })
 }