diff --git a/packages/plugin-starknet/src/actions/subdomain.ts b/packages/plugin-starknet/src/actions/subdomain.ts index de92342330f..84d3a0d7eb9 100644 --- a/packages/plugin-starknet/src/actions/subdomain.ts +++ b/packages/plugin-starknet/src/actions/subdomain.ts @@ -93,16 +93,17 @@ export default { ): Promise => { elizaLogger.log("Starting CREATE_SUBDOMAIN handler..."); - // Initialize or update state - if (!state) { - state = (await runtime.composeState(message)) as State; + // Fix: Create new variable instead of reassigning parameter + let currentState = state; + if (!currentState) { + currentState = (await runtime.composeState(message)) as State; } else { - state = await runtime.updateRecentMessageState(state); + currentState = await runtime.updateRecentMessageState(currentState); } // Compose transfer context const transferContext = composeContext({ - state, + state: currentState, template: transferTemplate, }); @@ -146,13 +147,11 @@ export default { const tx = await account.execute(transferCall); elizaLogger.success( - "Transfer completed successfully! tx: " + tx.transaction_hash + `Transfer completed successfully! tx: ${tx.transaction_hash}` ); if (callback) { callback({ - text: - "Transfer completed successfully! tx: " + - tx.transaction_hash, + text: `Transfer completed successfully! tx: ${tx.transaction_hash}`, content: {}, }); } diff --git a/packages/plugin-starknet/src/actions/swap.ts b/packages/plugin-starknet/src/actions/swap.ts index 29db4330a8e..c0b1d8c12d3 100644 --- a/packages/plugin-starknet/src/actions/swap.ts +++ b/packages/plugin-starknet/src/actions/swap.ts @@ -94,14 +94,17 @@ export const executeSwap: Action = { callback?: HandlerCallback ): Promise => { elizaLogger.log("Starting EXECUTE_STARKNET_SWAP handler..."); - if (!state) { - state = (await runtime.composeState(message)) as State; + + // Fix: Create new variable instead of reassigning parameter + let currentState = state; + if (!currentState) { + currentState = (await runtime.composeState(message)) as State; } else { - state = await runtime.updateRecentMessageState(state); + currentState = await runtime.updateRecentMessageState(currentState); } const swapContext = composeContext({ - state, + state: currentState, template: swapTemplate, }); @@ -139,18 +142,17 @@ export const executeSwap: Action = { ); elizaLogger.log( - "Swap completed successfully! tx: " + swapResult.transactionHash + `Swap completed successfully! tx: ${swapResult.transactionHash}` ); callback?.({ text: - "Swap completed successfully! tx: " + - swapResult.transactionHash, + `Swap completed successfully! tx: ${swapResult.transactionHash}`, }); return true; } catch (error) { elizaLogger.error("Error during token swap:", error); - callback?.({ text: `Error during swap:` }); + callback?.({ text: `Error during swap: ${error.message}` }); return false; } }, diff --git a/packages/plugin-starknet/src/actions/takeOrder.ts b/packages/plugin-starknet/src/actions/takeOrder.ts index 3cbaf1421a7..d414118c5d6 100644 --- a/packages/plugin-starknet/src/actions/takeOrder.ts +++ b/packages/plugin-starknet/src/actions/takeOrder.ts @@ -9,7 +9,7 @@ import { ModelClass, settings, } from "@elizaos/core"; -import * as fs from "fs"; +import * as fs from "node:fs"; // Added node: protocol import { validateStarknetConfig } from "../environment"; interface Order { @@ -54,7 +54,9 @@ const take_order: Action = { const _text = (message.content as Content).text; const userId = message.userId; - let ticker, contractAddress; + // Fix: Declare variables separately with explicit types + let ticker: string | undefined; + let contractAddress: string | undefined; // TODO: diff --git a/packages/plugin-starknet/src/actions/transfer.ts b/packages/plugin-starknet/src/actions/transfer.ts index 534f5788ab2..523b0e98c38 100644 --- a/packages/plugin-starknet/src/actions/transfer.ts +++ b/packages/plugin-starknet/src/actions/transfer.ts @@ -122,16 +122,17 @@ export default { ): Promise => { elizaLogger.log("Starting SEND_TOKEN handler..."); - // Initialize or update state - if (!state) { - state = (await runtime.composeState(message)) as State; + // Fix: Create new variable instead of reassigning parameter + let currentState = state; + if (!currentState) { + currentState = (await runtime.composeState(message)) as State; } else { - state = await runtime.updateRecentMessageState(state); + currentState = await runtime.updateRecentMessageState(currentState); } // Compose transfer context const transferContext = composeContext({ - state, + state: currentState, template: transferTemplate, }); @@ -162,7 +163,7 @@ export default { const decimals = await erc20Token.decimals(); // Convert decimal amount to integer before converting to BigInt const amountInteger = Math.floor( - Number(content.amount) * Math.pow(10, Number(decimals)) + Number(content.amount) * (10 ** Number(decimals)) // Fix: Use exponentiation operator instead of Math.pow ); const amountWei = BigInt(amountInteger.toString()); const recipient = @@ -182,13 +183,11 @@ export default { const tx = await account.execute(transferCall); elizaLogger.success( - "Transfer completed successfully! tx: " + tx.transaction_hash + `Transfer completed successfully! tx: ${tx.transaction_hash}` // Fix: Use template literal ); if (callback) { callback({ - text: - "Transfer completed successfully! tx: " + - tx.transaction_hash, + text: `Transfer completed successfully! tx: ${tx.transaction_hash}`, // Fix: Use template literal content: {}, }); } diff --git a/packages/plugin-starknet/src/actions/unruggable.ts b/packages/plugin-starknet/src/actions/unruggable.ts index 2cc0d1e6645..2637ac49042 100644 --- a/packages/plugin-starknet/src/actions/unruggable.ts +++ b/packages/plugin-starknet/src/actions/unruggable.ts @@ -99,14 +99,16 @@ export const deployToken: Action = { elizaLogger.log( "Starting DEPLOY_STARKNET_UNRUGGABLE_MEME_TOKEN handler..." ); - if (!state) { - state = (await runtime.composeState(message)) as State; + // Fix: Create new variable instead of reassigning parameter + let currentState = state; + if (!currentState) { + currentState = (await runtime.composeState(message)) as State; } else { - state = await runtime.updateRecentMessageState(state); + currentState = await runtime.updateRecentMessageState(currentState); } const deployContext = composeContext({ - state, + state: currentState, template: deployTemplate, }); @@ -116,7 +118,7 @@ export const deployToken: Action = { modelClass: ModelClass.MEDIUM, }); - elizaLogger.log("init supply." + response.initialSupply); + elizaLogger.log(`init supply. ${response.initialSupply}`); elizaLogger.log(response); if (!isDeployTokenContent(response)) { @@ -148,10 +150,7 @@ export const deployToken: Action = { ); elizaLogger.log( - "Token deployment initiated for: " + - response.name + - " at address: " + - tokenAddress + `Token deployment initiated for: ${response.name} at address: ${tokenAddress}` ); await launchOnEkubo(config, { @@ -181,11 +180,7 @@ export const deployToken: Action = { }); callback?.({ - text: - "Token Deployment completed successfully!" + - response.symbol + - " deployed in tx: " + - transactionHash, + text: `Token Deployment completed successfully! ${response.symbol} deployed in tx: ${transactionHash}`, }); return true; diff --git a/packages/plugin-starknet/src/providers/portfolioProvider.ts b/packages/plugin-starknet/src/providers/portfolioProvider.ts index ae19926a337..4ecfdab66a1 100644 --- a/packages/plugin-starknet/src/providers/portfolioProvider.ts +++ b/packages/plugin-starknet/src/providers/portfolioProvider.ts @@ -100,10 +100,11 @@ const walletProvider: Provider = { if (rawBalance === undefined) return null; const decimalBalance = - Number(rawBalance) / Math.pow(10, token.decimals); + Number(rawBalance) / (10 ** token.decimals); // Fix: Use exponentiation operator instead of Math.pow const price = tokenUsdValues[token.coingeckoId]?.usd ?? 0; const usdValue = decimalBalance * price; + if (decimalBalance === 0 && usdValue === 0) return null; return `${symbol.padEnd(9)}| ${decimalBalance diff --git a/packages/plugin-starknet/src/providers/token.ts b/packages/plugin-starknet/src/providers/token.ts index 8af8de152bd..727ed45be55 100644 --- a/packages/plugin-starknet/src/providers/token.ts +++ b/packages/plugin-starknet/src/providers/token.ts @@ -119,7 +119,7 @@ export class TokenProvider { lastError = error as Error; if (i < PROVIDER_CONFIG.MAX_RETRIES - 1) { - const delay = PROVIDER_CONFIG.RETRY_DELAY * Math.pow(2, i); + const delay = PROVIDER_CONFIG.RETRY_DELAY * (2 ** i); // Fix: Use exponentiation operator instead of Math.pow await new Promise((resolve) => setTimeout(resolve, delay)); } } @@ -156,10 +156,10 @@ export class TokenProvider { // Check if the tokenAddress exists in the TokenBalances if (items[tokenAddress]) { return tokenAddress; - } else { - console.warn(`Token with address ${tokenAddress} not found in wallet`); - return null; } + + console.warn(`Token with address ${tokenAddress} not found in wallet`); + return null; } catch (error) { console.error("Error checking token in wallet:", error); return null; @@ -401,7 +401,7 @@ export class TokenProvider { return dexData; } catch (error) { - console.error(`Error fetching DexScreener data:`, error); + console.error("Error fetching DexScreener data:", error); return { schemaVersion: "1.0.0", pairs: [], @@ -444,7 +444,7 @@ export class TokenProvider { // Return the pair with the highest liquidity and market cap return this.getHighestLiquidityPair(dexData); } catch (error) { - console.error(`Error fetching DexScreener data:`, error); + console.error("Error fetching DexScreener data:", error); return null; } } @@ -504,11 +504,11 @@ export class TokenProvider { if (averageChange > increaseThreshold) { return "increasing"; - } else if (averageChange < decreaseThreshold) { + } + if (averageChange < decreaseThreshold) { return "decreasing"; - } else { - return "stable"; } + return "stable"; } // TODO: Update to Starknet @@ -523,7 +523,10 @@ export class TokenProvider { const allHoldersMap = new Map(); let page = 1; const limit = 1000; - let cursor; + // let cursor; + // Fix: Add type annotation to prevent implicit any + let cursor: string | undefined; + //HELIOUS_API_KEY needs to be added const url = `https://mainnet.helius-rpc.com/?api-key=${ settings.HELIUS_API_KEY || "" @@ -538,7 +541,8 @@ export class TokenProvider { mint: this.tokenAddress, cursor: cursor, }; - if (cursor != undefined) { + // Fix: Replace != with !== + if (cursor !== undefined) { params.cursor = cursor; } console.log(`Fetching holders - Page ${page}`); diff --git a/packages/plugin-starknet/src/providers/trustScoreProvider.ts b/packages/plugin-starknet/src/providers/trustScoreProvider.ts index ff84353aa17..33e9ed0f0cb 100644 --- a/packages/plugin-starknet/src/providers/trustScoreProvider.ts +++ b/packages/plugin-starknet/src/providers/trustScoreProvider.ts @@ -30,8 +30,15 @@ interface sellDetails { sell_amount: number; sell_recommender_id: string | null; } +// Fix: Replace explicit any with proper type +interface Recommendation { + // Add actual properties based on usage + score: number; + // ... other properties +} + interface _RecommendationGroup { - recommendation: any; + recommendation: Recommendation; trustScore: number; } @@ -123,10 +130,13 @@ export class TrustScoreManager { const inactiveDays = Math.floor( (now.getTime() - lastActive.getTime()) / (1000 * 60 * 60 * 24) ); - const decayFactor = Math.pow( - this.DECAY_RATE, - Math.min(inactiveDays, this.MAX_DECAY_DAYS) - ); + // const decayFactor = Math.pow( + // this.DECAY_RATE, + // Math.min(inactiveDays, this.MAX_DECAY_DAYS) + // ); + // Fix: Replace Math.pow with ** operator + const decayFactor = this.DECAY_RATE ** Math.min(inactiveDays, this.MAX_DECAY_DAYS); + const decayedScore = recommenderMetrics.trustScore * decayFactor; const validationTrustScore = this.trustScoreDb.calculateValidationTrust(tokenAddress); @@ -213,10 +223,13 @@ export class TrustScoreManager { const inactiveDays = Math.floor( (now.getTime() - lastActive.getTime()) / (1000 * 60 * 60 * 24) ); - const decayFactor = Math.pow( - this.DECAY_RATE, - Math.min(inactiveDays, this.MAX_DECAY_DAYS) - ); + // const decayFactor = Math.pow( + // this.DECAY_RATE, + // Math.min(inactiveDays, this.MAX_DECAY_DAYS) + // ); + // Fix: Replace Math.pow with ** operator + const decayFactor = this.DECAY_RATE ** Math.min(inactiveDays, this.MAX_DECAY_DAYS); + const decayedScore = recommenderMetrics.trustScore * decayFactor; const newRecommenderMetrics: RecommenderMetrics = { @@ -468,7 +481,7 @@ export class TrustScoreManager { */ async updateSellDetails( - runtime: IAgentRuntime, + _runtime: IAgentRuntime, tokenAddress: string, recommenderId: string, sellTimeStamp: string, @@ -558,27 +571,71 @@ export class TrustScoreManager { {} as Record> ); + // const result = Object.keys(groupedRecommendations).map( + // (tokenAddress) => { + // const tokenRecommendations = + // groupedRecommendations[tokenAddress]; + + // // Initialize variables to compute averages + // let totalTrustScore = 0; + // let totalRiskScore = 0; + // let totalConsistencyScore = 0; + // const recommenderData = []; + + // tokenRecommendations.forEach((recommendation) => { + // const tokenPerformance = + // this.trustScoreDb.getTokenPerformance( + // recommendation.tokenAddress + // ); + // const recommenderMetrics = + // this.trustScoreDb.getRecommenderMetrics( + // recommendation.recommenderId + // ); + + // const trustScore = this.calculateTrustScore( + // tokenPerformance, + // recommenderMetrics + // ); + // const consistencyScore = this.calculateConsistencyScore( + // tokenPerformance, + // recommenderMetrics + // ); + // const riskScore = this.calculateRiskScore(tokenPerformance); + + // // Accumulate scores for averaging + // totalTrustScore += trustScore; + // totalRiskScore += riskScore; + // totalConsistencyScore += consistencyScore; + + // recommenderData.push({ + // recommenderId: recommendation.recommenderId, + // trustScore, + // riskScore, + // consistencyScore, + // recommenderMetrics, + // }); + // }); + + const result = Object.keys(groupedRecommendations).map( (tokenAddress) => { - const tokenRecommendations = - groupedRecommendations[tokenAddress]; - + const tokenRecommendations = groupedRecommendations[tokenAddress]; + // Initialize variables to compute averages let totalTrustScore = 0; let totalRiskScore = 0; let totalConsistencyScore = 0; const recommenderData = []; - - tokenRecommendations.forEach((recommendation) => { - const tokenPerformance = - this.trustScoreDb.getTokenPerformance( - recommendation.tokenAddress - ); - const recommenderMetrics = - this.trustScoreDb.getRecommenderMetrics( - recommendation.recommenderId - ); - + + // Changed from forEach to for...of + for (const recommendation of tokenRecommendations) { + const tokenPerformance = this.trustScoreDb.getTokenPerformance( + recommendation.tokenAddress + ); + const recommenderMetrics = this.trustScoreDb.getRecommenderMetrics( + recommendation.recommenderId + ); + const trustScore = this.calculateTrustScore( tokenPerformance, recommenderMetrics @@ -588,12 +645,12 @@ export class TrustScoreManager { recommenderMetrics ); const riskScore = this.calculateRiskScore(tokenPerformance); - + // Accumulate scores for averaging totalTrustScore += trustScore; totalRiskScore += riskScore; totalConsistencyScore += consistencyScore; - + recommenderData.push({ recommenderId: recommendation.recommenderId, trustScore, @@ -601,7 +658,7 @@ export class TrustScoreManager { consistencyScore, recommenderMetrics, }); - }); + } // Calculate averages for this token const averageTrustScore = diff --git a/packages/plugin-starknet/src/utils/ERC20Token.ts b/packages/plugin-starknet/src/utils/ERC20Token.ts index 5225a658f44..1c27893f072 100644 --- a/packages/plugin-starknet/src/utils/ERC20Token.ts +++ b/packages/plugin-starknet/src/utils/ERC20Token.ts @@ -21,7 +21,8 @@ export type TransferCall = { }; export class ERC20Token { - abi: any; + // abi: any; + abi: typeof erc20Abi; // Fix: Use the actual type of the ABI contract: Contract; calldata: CallData; constructor( diff --git a/packages/plugin-starknet/src/utils/cache.ts b/packages/plugin-starknet/src/utils/cache.ts index f8fc6eb8b28..1e6a3eca541 100644 --- a/packages/plugin-starknet/src/utils/cache.ts +++ b/packages/plugin-starknet/src/utils/cache.ts @@ -1,6 +1,6 @@ import NodeCache from "node-cache"; -import fs from "fs"; -import path from "path"; +import fs from "node:fs"; +import path from "node:path"; export class Cache { private cache: NodeCache; @@ -24,6 +24,34 @@ export class Cache { } } + // private readCacheFromFile(cacheKey: string): T | null { + // const filePath = path.join(this.cacheDir, `${cacheKey}.json`); + // if (fs.existsSync(filePath)) { + // try { + // const fileContent = fs.readFileSync(filePath, "utf-8"); + // const parsed = JSON.parse(fileContent); + // const now = Date.now(); + // if (now < parsed.expiry) { + // return parsed.data as T; + // } else { + // fs.unlinkSync(filePath); + // } + // } catch (error) { + // console.error( + // `Error reading cache file for key ${cacheKey}:`, + // error + // ); + // // Delete corrupted cache file + // try { + // fs.unlinkSync(filePath); + // } catch (e) { + // console.error(`Error deleting corrupted cache file:`, e); + // } + // } + // } + // return null; + // } + private readCacheFromFile(cacheKey: string): T | null { const filePath = path.join(this.cacheDir, `${cacheKey}.json`); if (fs.existsSync(filePath)) { @@ -33,19 +61,20 @@ export class Cache { const now = Date.now(); if (now < parsed.expiry) { return parsed.data as T; - } else { - fs.unlinkSync(filePath); } + // Fix: Remove unnecessary else clause + fs.unlinkSync(filePath); } catch (error) { console.error( `Error reading cache file for key ${cacheKey}:`, error ); + // Delete corrupted cache file try { fs.unlinkSync(filePath); } catch (e) { - console.error(`Error deleting corrupted cache file:`, e); + console.error("Error deleting corrupted cache file:", e); } } } diff --git a/packages/plugin-starknet/src/utils/index.ts b/packages/plugin-starknet/src/utils/index.ts index 9620e7aba43..cc2d00090fe 100644 --- a/packages/plugin-starknet/src/utils/index.ts +++ b/packages/plugin-starknet/src/utils/index.ts @@ -60,8 +60,10 @@ export const formatCurrenyAmount = ( const fixedAmount = amount.toFixed(fixed); const significantAmount = amount.toSignificant(significant); + // if (+significantAmount > +fixedAmount) return significantAmount; + // else return +fixedAmount.toString(); if (+significantAmount > +fixedAmount) return significantAmount; - else return +fixedAmount.toString(); + return +fixedAmount.toString(); }; export const formatPercentage = (percentage: Percent) => { @@ -90,7 +92,8 @@ export async function fetchWithRetry( delay = 1000, maxDelay = 10000, backoff = (retryCount, baseDelay, maxDelay) => - Math.min(baseDelay * Math.pow(2, retryCount), maxDelay), + // Math.min(baseDelay * Math.pow(2, retryCount), maxDelay), + Math.min(baseDelay * 2 ** retryCount, maxDelay), // Fix: Use ** instead of Math.pow } = config; let lastError: Error | null = null;