Skip to content

Commit f354fbd

Browse files
committed
token balance, transactions, data simulation update on buys and sells
Signed-off-by: MarcoMandar <malicemandar@gmail.com>
1 parent ee9929c commit f354fbd

File tree

2 files changed

+160
-0
lines changed

2 files changed

+160
-0
lines changed

packages/plugin-solana/src/providers/trustScoreProvider.ts

+40
Original file line numberDiff line numberDiff line change
@@ -351,10 +351,14 @@ export class TrustScoreManager {
351351
new PublicKey(Wallet!)
352352
);
353353

354+
let tokensBalance = 0;
354355
const prices = await wallet.fetchPrices(runtime);
355356
const solPrice = prices.solana.usd;
356357
const buySol = data.buy_amount / parseFloat(solPrice);
357358
const buy_value_usd = data.buy_amount * processedData.tradeData.price;
359+
const token = await this.tokenProvider.fetchTokenTradeData();
360+
const tokenPrice = token.price;
361+
tokensBalance = buy_value_usd / tokenPrice;
358362

359363
const creationData = {
360364
token_address: tokenAddress,
@@ -383,6 +387,23 @@ export class TrustScoreManager {
383387
rapidDump: false,
384388
};
385389
this.trustScoreDb.addTradePerformance(creationData, data.is_simulation);
390+
391+
if (data.is_simulation) {
392+
// If the trade is a simulation update the balance
393+
this.trustScoreDb.updateTokenBalance(tokenAddress, tokensBalance);
394+
// generate some random hash for simulations
395+
const hash = Math.random().toString(36).substring(7);
396+
const transaction = {
397+
tokenAddress: tokenAddress,
398+
type: "buy",
399+
transactionHash: hash,
400+
amount: data.buy_amount,
401+
price: processedData.tradeData.price,
402+
isSimulation: true,
403+
timestamp: new Date().toISOString(),
404+
};
405+
this.trustScoreDb.addTransaction(transaction);
406+
}
386407
// api call to update trade performance
387408
this.createTradeInBe(tokenAddress, recommenderId, data);
388409
return creationData;
@@ -507,6 +528,25 @@ export class TrustScoreManager {
507528
sellDetailsData,
508529
isSimulation
509530
);
531+
if (isSimulation) {
532+
// If the trade is a simulation update the balance
533+
const oldBalance = this.trustScoreDb.getTokenBalance(tokenAddress);
534+
const tokenBalance = oldBalance - sellDetails.sell_amount;
535+
this.trustScoreDb.updateTokenBalance(tokenAddress, tokenBalance);
536+
// generate some random hash for simulations
537+
const hash = Math.random().toString(36).substring(7);
538+
const transaction = {
539+
tokenAddress: tokenAddress,
540+
type: "sell",
541+
transactionHash: hash,
542+
amount: sellDetails.sell_amount,
543+
price: processedData.tradeData.price,
544+
isSimulation: true,
545+
timestamp: new Date().toISOString(),
546+
};
547+
this.trustScoreDb.addTransaction(transaction);
548+
}
549+
510550
return sellDetailsData;
511551
}
512552

packages/plugin-trustdb/src/adapters/trustScoreDatabase.ts

+120
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,7 @@ export interface TokenPerformance {
4040
rapidDump: boolean;
4141
suspiciousVolume: boolean;
4242
validationTrust: number;
43+
balance: number;
4344
lastUpdated: Date;
4445
}
4546

@@ -120,9 +121,20 @@ interface TokenPerformanceRow {
120121
rapid_dump: number;
121122
suspicious_volume: number;
122123
validation_trust: number;
124+
balance: number;
123125
last_updated: string;
124126
}
125127

128+
interface Transaction {
129+
tokenAddress: string;
130+
transactionHash: string;
131+
type: "buy" | "sell";
132+
amount: number;
133+
price: number;
134+
isSimulation: boolean;
135+
timestamp: string;
136+
}
137+
126138
export class TrustScoreDatabase {
127139
private db: Database;
128140

@@ -192,6 +204,7 @@ export class TrustScoreDatabase {
192204
rapid_dump BOOLEAN DEFAULT FALSE,
193205
suspicious_volume BOOLEAN DEFAULT FALSE,
194206
validation_trust REAL DEFAULT 0,
207+
balance REAL DEFAULT 0,
195208
last_updated DATETIME DEFAULT CURRENT_TIMESTAMP
196209
);
197210
`);
@@ -289,6 +302,20 @@ export class TrustScoreDatabase {
289302
FOREIGN KEY (recommender_id) REFERENCES recommenders(id) ON DELETE CASCADE
290303
);
291304
`);
305+
306+
// create transactions table
307+
this.db.exec(`
308+
CREATE TABLE IF NOT EXISTS transactions (
309+
token_address TEXT NOT NULL,
310+
transaction_hash TEXT PRIMARY KEY,
311+
type TEXT NOT NULL,
312+
amount REAL NOT NULL,
313+
price REAL NOT NULL,
314+
timestamp TEXT NOT NULL,
315+
is_simulation BOOLEAN DEFAULT FALSE,
316+
FOREIGN KEY (token_address) REFERENCES token_performance(token_address) ON DELETE CASCADE
317+
);
318+
`);
292319
}
293320

294321
/**
@@ -749,6 +776,25 @@ export class TrustScoreDatabase {
749776
}
750777
}
751778

779+
// update token balance
780+
781+
updateTokenBalance(tokenAddress: string, balance: number): boolean {
782+
const sql = `
783+
UPDATE token_performance
784+
SET balance = ?,
785+
last_updated = CURRENT_TIMESTAMP
786+
WHERE token_address = ?;
787+
`;
788+
try {
789+
this.db.prepare(sql).run(balance, tokenAddress);
790+
console.log(`Updated token balance for ${tokenAddress}`);
791+
return true;
792+
} catch (error) {
793+
console.error("Error updating token balance:", error);
794+
return false;
795+
}
796+
}
797+
752798
/**
753799
* Retrieves token performance metrics.
754800
* @param tokenAddress Token's address
@@ -776,6 +822,7 @@ export class TrustScoreDatabase {
776822
rapidDump: row.rapid_dump === 1,
777823
suspiciousVolume: row.suspicious_volume === 1,
778824
validationTrust: row.validation_trust,
825+
balance: row.balance,
779826
lastUpdated: new Date(row.last_updated),
780827
};
781828
}
@@ -1247,6 +1294,79 @@ export class TrustScoreDatabase {
12471294
};
12481295
}
12491296

1297+
// ----- Transactions Methods -----
1298+
/**
1299+
* Adds a new transaction to the database.
1300+
* @param transaction Transaction object
1301+
* @returns boolean indicating success
1302+
*/
1303+
1304+
addTransaction(transaction: Transaction): boolean {
1305+
const sql = `
1306+
INSERT INTO transactions (
1307+
token_address,
1308+
transaction_hash,
1309+
type,
1310+
amount,
1311+
price,
1312+
is_simulation,
1313+
timestamp
1314+
) VALUES (?, ?, ?, ?, ?, ?);
1315+
`;
1316+
try {
1317+
this.db
1318+
.prepare(sql)
1319+
.run(
1320+
transaction.tokenAddress,
1321+
transaction.transactionHash,
1322+
transaction.type,
1323+
transaction.amount,
1324+
transaction.price,
1325+
transaction.isSimulation,
1326+
transaction.timestamp
1327+
);
1328+
return true;
1329+
} catch (error) {
1330+
console.error("Error adding transaction:", error);
1331+
return false;
1332+
}
1333+
}
1334+
1335+
/**
1336+
* Retrieves all transactions for a specific token.
1337+
* @param tokenAddress Token's address
1338+
* @returns Array of Transaction objects
1339+
*/
1340+
getTransactionsByToken(tokenAddress: string): Transaction[] {
1341+
const sql = `SELECT * FROM transactions WHERE token_address = ? ORDER BY timestamp DESC;`;
1342+
const rows = this.db.prepare(sql).all(tokenAddress) as Array<{
1343+
token_address: string;
1344+
transaction_hash: string;
1345+
type: string;
1346+
amount: number;
1347+
price: number;
1348+
is_simulation: boolean;
1349+
timestamp: string;
1350+
}>;
1351+
1352+
return rows.map((row) => {
1353+
// Validate and cast 'type' to ensure it matches the expected union type
1354+
if (row.type !== "buy" && row.type !== "sell") {
1355+
throw new Error(`Unexpected transaction type: ${row.type}`);
1356+
}
1357+
1358+
return {
1359+
tokenAddress: row.token_address,
1360+
transactionHash: row.transaction_hash,
1361+
type: row.type as "buy" | "sell",
1362+
amount: row.amount,
1363+
price: row.price,
1364+
isSimulation: row.is_simulation,
1365+
timestamp: new Date(row.timestamp).toISOString(),
1366+
};
1367+
});
1368+
}
1369+
12501370
/**
12511371
* Close the database connection gracefully.
12521372
*/

0 commit comments

Comments
 (0)