File size: 2,439 Bytes
80d4bc1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1b99e9c
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
import { supabase } from "../../db/supabase";
import { createLogger } from "../../utils/logger";

const logger = createLogger('BotSettings');

/**
 * Get bot settings from database
 * @param botId Bot UUID
 * @returns Bot settings object or null if not found
 */
export const getBotSettings = async (botId: string) => {
  try {
    const { data, error } = await supabase
      .from('bots')
      .select('*')
      .eq('id', botId)
      .single();
      
    if (error) {
      logger.error(`Error fetching bot settings: ${error.message}`);
      return null;
    }
    
    return {
      ...data.settings,
      currency: data.currency,
      profit: {
        type: data.profit_type,
        percentage: data.profit_value_percentage,
        fix: data.profit_value_fix
      },
      version: data.version
    };
  } catch (error: any) {
    logger.error(`Unexpected error getting bot settings: ${error.message}`);
    return null;
  }
};

/**
 * Save bot state to database
 * @param botId Bot UUID
 * @param state State object to save
 * @returns Success status
 */
export const saveBotState = async (botId: string, state: Record<string, any>) => {
  try {
    const { error } = await supabase
      .from('bots')
      .update({
        state: state,
        last_activity: new Date().toISOString()
      })
      .eq('id', botId);
      
    if (error) {
      logger.error(`Error saving bot state: ${error.message}`);
      return false;
    }
    
    return true;
  } catch (error: any) {
    logger.error(`Unexpected error saving bot state: ${error.message}`);
    return false;
  }
};

/**
 * Calculate profit based on bot settings
 * @param botId Bot UUID
 * @param amount Base amount
 * @returns Amount with profit applied
 */
export const calculateProfit = async (botId: string, amount: number) => {
  try {
    const { data, error } = await supabase
      .from('bots')
      .select('profit_type, profit_value_percentage, profit_value_fix')
      .eq('id', botId)
      .single();
      
    if (error || !data) {
      logger.error(`Error fetching profit settings: ${error?.message}`);
      return amount;
    }
    
    if (data.profit_type === 'percentage') {
      return amount * (1 + data.profit_value_percentage / 100);
    } else {
      return amount + data.profit_value_fix;
    }
  } catch (error: any) {
    logger.error(`Unexpected error calculating profit: ${error.message}`);
    return amount;
  }
};