m2pool_backend_app/public/distribution-shares.js

49 lines
1.7 KiB
JavaScript
Raw Permalink Normal View History

2025-04-10 10:53:16 +00:00
/**
* 截取小数点后dots位
* @param {Number} number 要截取的小数
* @param {Number} dots 小数点位数
* @returns
*/
function truncateToTenDecimals(number, dots) {
const str = number.toString();
const decimalIndex = str.indexOf(".");
// 如果没有小数部分,直接返回原始数值
if (decimalIndex === -1) {
return str;
}
// 截取到小数点后 10 位
const truncatedStr = str.slice(0, decimalIndex + dots + 1);
return Number(truncatedStr);
}
/**
* 根据shares队列计算每个user本轮次的分配占比
* @param {Array} data [{user:"user1", pool_diff:100, miner_diff:100}, ]
* @returns {"1x1":{totalWeight:10, weightRatio:0.1}}
*/
function calculate_shares_weight(data) {
// Step 1: 按照 user 分类计算每个 user 的总 weight
const userWeights = data.reduce((acc, item) => {
const weight = item.miner_diff / item.pool_diff;
if (!acc[item.user]) {
acc[item.user] = { totalWeight: 0, data: [] };
}
acc[item.user].totalWeight += weight;
acc[item.user].data.push(item);
return acc;
}, {});
// Step 2: 计算所有 user 的总 weight
const totalWeight = Object.values(userWeights).reduce((acc, user) => acc + user.totalWeight, 0);
// Step 3: 计算每个 user 的 weight 占总 weight 的比重并返回所需格式
const userWeightRatios = Object.keys(userWeights).reduce((acc, user) => {
const weightRatio = truncateToTenDecimals(userWeights[user].totalWeight / totalWeight, 10);
acc[user] = Number(weightRatio);
return acc;
}, {});
return userWeightRatios;
}
module.exports = { calculate_shares_weight, truncateToTenDecimals };