Browse Source

优化gas倍数

wkw 3 days ago
parent
commit
905e5035e7
3 changed files with 58 additions and 15 deletions
  1. 8 0
      src/api/game.js
  2. 14 4
      src/pages/trade/index.vue
  3. 36 11
      src/utils/web.js

+ 8 - 0
src/api/game.js

@@ -54,4 +54,12 @@ export const matchEnroll = (data) => {
     method: 'post',
     data,
   })
+}
+// gas费倍数
+export const sysSetting = (data) => {
+  return http({
+    url: '/api/sys/setting',
+    method: 'get',
+    data,
+  })
 }

+ 14 - 4
src/pages/trade/index.vue

@@ -276,7 +276,7 @@
 import { ref, onMounted,computed, reactive } from "vue";
 import Header from "@/components/Header";
 import { sendSingleReward,WGTForToken,STTForToken,getBalance } from "@/utils/web.js";
-import { matchList, matchRank, matchInfo,verifyEnroll,matchEnroll,userPrize,claimPrize } from "@/api/game";
+import { matchList, matchRank, matchInfo,verifyEnroll,matchEnroll,userPrize,claimPrize,sysSetting } from "@/api/game";
 import dayjs from "dayjs";
 const timeData = ref({});
 const onChange = (e) => {
@@ -296,7 +296,8 @@ const privateKey = ref('');
 const triggered = ref(false);
 const received = ref(false);
 const receivedItem = ref({});
-// const privateKey = ref("0x4553077da5d773773dad0511c6e5d33142ae2c1bd05a3a8a4a7becbc0d23d9b5");//H5
+const GasRate = ref(1);
+// const privateKey = ref("4d8d38c6433c9552a11181b64a234814cd83f5b0d2c7306545ee097da9c0e4b2");//H5
 
 const bgClass = computed(() => {
   if (gameCheck.value === 0) return 'bg1';
@@ -306,9 +307,18 @@ const bgClass = computed(() => {
 const handleAddressUpdate = (addr) => {
   privateKey.value = window.android.getPrivateKey();//app
   walletAddress.value = addr;
+  getSysSetting();
   getGameMatchList();
   getnum(privateKey.value);
 };
+// 获取gas倍数
+const getSysSetting = async() => {
+  let res = await sysSetting({category:'GasRate'});
+  if(res.data){
+    GasRate.value = res.data.GasRate
+  }
+}
+sysSetting
 // 获取游戏赛事列表(三个tab)
 const getGameMatchList = async (type = true) => {
   let params = {
@@ -415,7 +425,7 @@ const handleTokenSignUp = async (signUpFn, price) => {
     mask: true
   });
   try {
-    const result = await signUpFn(privateKey.value, price);
+    const result = await signUpFn(privateKey.value, price,GasRate.value);
     if (result.status === "success") {
       await getMatchEnroll(result.hash);
     } else {
@@ -479,7 +489,7 @@ const getsendSingleReward = async (prize_money) =>{
     mask: true
   });
   try {
-    const result = await sendSingleReward(privateKey.value,prize_money);
+    const result = await sendSingleReward(privateKey.value,prize_money,GasRate.value);
     if (result.status === "success") {
       await getClaimPrize(result.hash);
     }else{

+ 36 - 11
src/utils/web.js

@@ -13,6 +13,20 @@ const MANAGER_ADDRESS = "0x257853ac4319c76f1cdb00831fd14a48977b45ef";
 function normalizePrivateKey(pk) {
     return pk.startsWith("0x") ? pk : "0x" + pk;
 }
+function scaleGasPrice(originalGasPrice, gasRate) {
+    if (gasRate >= 1) {
+        return BigInt(originalGasPrice) * BigInt(Math.floor(gasRate));
+    }
+
+    // 小于1的小数处理
+    const gasRateStr = gasRate.toString(); // 比如 "0.1"
+    const decimalPlaces = gasRateStr.split(".")[1]?.length || 0;
+    const denominator = 10 ** decimalPlaces;
+    const numerator = Math.floor(gasRate * denominator);
+
+    const scaled = (BigInt(originalGasPrice) * BigInt(numerator)) / BigInt(denominator);
+    return scaled;
+}
 
 // 获取余额
 async function getBalance(privateKey, type) {
@@ -35,7 +49,7 @@ async function getBalance(privateKey, type) {
 
 
 // 发放奖励
-async function sendSingleReward(privateKey, amount) {
+async function sendSingleReward(privateKey, amount, GasRate) {
     if (!privateKey) {
         return { status: "error", message: "未获取到私钥,无法发放奖励" };
     }
@@ -54,14 +68,23 @@ async function sendSingleReward(privateKey, amount) {
 
         if (!signature) throw new Error("签名为空");
 
+        const gasPrice = await web3.eth.getGasPrice();
+        let adjustedGasPrice = scaleGasPrice(gasPrice, GasRate);
+        const maxTotalFee = BigInt(web3.utils.toWei("1", "ether")); // 1 ACC 上限
+        const gasLimit = 500000n;
+
+        // 如果 gasPrice 太高,限制为不会超过 1 ACC 的值
+        if (adjustedGasPrice * gasLimit > maxTotalFee) {
+            adjustedGasPrice = maxTotalFee / gasLimit;
+        }
         const tx = {
             from: sender,
             to: contractAddress,
             data: contract.methods
                 .distributeSingleReward(sender, amountWei, timestamp, nonceForSig, signature)
                 .encodeABI(),
-            gas: 500000,
-            gasPrice: await web3.eth.getGasPrice(),
+            gas: gasLimit,
+            gasPrice: adjustedGasPrice.toString(),
             nonce: await web3.eth.getTransactionCount(sender, "pending"),
             chainId: await web3.eth.getChainId()
         };
@@ -80,7 +103,7 @@ async function sendSingleReward(privateKey, amount) {
 }
 
 // 通用报名函数(支持 WGT 和 STT)
-async function tokenSignUp(privateKey, amount, type) {
+async function tokenSignUp(privateKey, amount, GasRate,type) {
     try {
         const web3 = await getWeb3();
         privateKey = normalizePrivateKey(privateKey);
@@ -95,11 +118,13 @@ async function tokenSignUp(privateKey, amount, type) {
             web3.eth.getTransactionCount(sender)
         ]);
 
-        let adjustedGasPrice = BigInt(gasPrice) * BigInt(10);
-        const maxGasPrice = BigInt(web3.utils.toWei('100', 'gwei'));
+        let adjustedGasPrice = scaleGasPrice(gasPrice, GasRate);
+        const maxTotalFee = BigInt(web3.utils.toWei("1", "ether")); // 1 ACC 上限
+        let gasLimit = 500000n;
 
-        if (adjustedGasPrice > maxGasPrice) {
-            adjustedGasPrice = maxGasPrice;
+        // 如果 gasPrice 太高,限制为不会超过 1 ACC 的值
+        if (adjustedGasPrice * gasLimit > maxTotalFee) {
+            adjustedGasPrice = maxTotalFee / gasLimit;
         }
 
         const tokenContract = new web3.eth.Contract(pubData, tokenAddress);
@@ -132,7 +157,7 @@ async function tokenSignUp(privateKey, amount, type) {
         // gas 估算
         const receiveMethod = type.toLowerCase() === 'wgt' ? 'receiveWGT' : 'receiveSTT';
         const gasEstimate = await exchangeContract.methods[receiveMethod](tokenAmount).estimateGas({ from: sender });
-        const gasLimit = Math.ceil(Number(gasEstimate) * 1.1);
+        gasLimit = Math.ceil(Number(gasEstimate) * 1.1);
         const minGasNeeded = BigInt(gasLimit) * adjustedGasPrice; // Use BigInt
         const ethBalance = await web3.eth.getBalance(sender);
         console.log('估算gas:', minGasNeeded)
@@ -164,7 +189,7 @@ async function tokenSignUp(privateKey, amount, type) {
 }
 
 
-const WGTForToken = (pk, num) => tokenSignUp(pk, num, 'wgt');
-const STTForToken = (pk, num) => tokenSignUp(pk, num, 'stt');
+const WGTForToken = (pk, num, GasRate) => tokenSignUp(pk, num, GasRate, 'wgt');
+const STTForToken = (pk, num, GasRate) => tokenSignUp(pk, num, GasRate, 'stt');
 
 export { getBalance, sendSingleReward, WGTForToken, STTForToken };