Skip to content

Commit a8bafc7

Browse files
committedNov 22, 2024
dev(starknet): plugin cleanup
1 parent e31e666 commit a8bafc7

File tree

9 files changed

+113
-97
lines changed

9 files changed

+113
-97
lines changed
 

‎packages/plugin-starknet/src/actions/swap.ts

+5-5
Original file line numberDiff line numberDiff line change
@@ -1,22 +1,22 @@
11
import {
2+
Action,
23
ActionExample,
4+
composeContext,
35
elizaLogger,
6+
generateObject,
47
HandlerCallback,
58
IAgentRuntime,
69
Memory,
710
ModelClass,
811
State,
9-
type Action,
1012
} from "@ai16z/eliza";
11-
import { composeContext } from "@ai16z/eliza";
12-
import { generateObject } from "@ai16z/eliza";
1313
import {
1414
executeSwap as executeAvnuSwap,
1515
fetchQuotes,
1616
QuoteRequest,
1717
} from "@avnu/avnu-sdk";
1818

19-
import { getStarknetAccount, validateSettings } from "../utils/index.ts";
19+
import { getStarknetAccount } from "../utils/index.ts";
2020
import { validateStarknetConfig } from "../enviroment.ts";
2121

2222
interface SwapContent {
@@ -67,7 +67,7 @@ Example response:
6767
6868
Extract the following information about the requested token swap:
6969
- Sell token address
70-
- Buy token address
70+
- Buy token address
7171
- Amount to sell (in wei)
7272
7373
Respond with a JSON markdown block containing only the extracted values. Use null for any values that cannot be determined.`;

‎packages/plugin-starknet/src/actions/takeOrder.ts

+5-5
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,15 @@
11
import {
22
Action,
3+
ActionExample,
4+
composeContext,
5+
Content,
6+
generateText,
37
IAgentRuntime,
48
Memory,
5-
Content,
6-
ActionExample,
79
ModelClass,
10+
settings,
811
} from "@ai16z/eliza";
912
import * as fs from "fs";
10-
import { settings } from "@ai16z/eliza";
11-
import { composeContext } from "@ai16z/eliza";
12-
import { generateText } from "@ai16z/eliza";
1313
import { validateStarknetConfig } from "../enviroment";
1414

1515
interface Order {

‎packages/plugin-starknet/src/actions/transfer.ts

+35-9
Original file line numberDiff line numberDiff line change
@@ -2,25 +2,51 @@
22
// It should just transfer tokens from the agent's wallet to the recipient.
33

44
import {
5+
type Action,
56
ActionExample,
7+
composeContext,
8+
Content,
9+
elizaLogger,
10+
generateObject,
611
HandlerCallback,
712
IAgentRuntime,
813
Memory,
914
ModelClass,
1015
State,
11-
type Action,
12-
composeContext,
13-
generateObject,
14-
elizaLogger,
1516
} from "@ai16z/eliza";
16-
import {
17-
getStarknetAccount,
18-
isTransferContent,
19-
validateSettings,
20-
} from "../utils";
17+
import { getStarknetAccount } from "../utils";
2118
import { ERC20Token } from "../utils/ERC20Token";
2219
import { validateStarknetConfig } from "../enviroment";
2320

21+
export interface TransferContent extends Content {
22+
tokenAddress: string;
23+
recipient: string;
24+
amount: string | number;
25+
}
26+
27+
export function isTransferContent(
28+
content: TransferContent
29+
): content is TransferContent {
30+
// Validate types
31+
const validTypes =
32+
typeof content.tokenAddress === "string" &&
33+
typeof content.recipient === "string" &&
34+
(typeof content.amount === "string" ||
35+
typeof content.amount === "number");
36+
if (!validTypes) {
37+
return false;
38+
}
39+
40+
// Validate addresses (must be 32-bytes long with 0x prefix)
41+
const validAddresses =
42+
content.tokenAddress.startsWith("0x") &&
43+
content.tokenAddress.length === 66 &&
44+
content.recipient.startsWith("0x") &&
45+
content.recipient.length === 66;
46+
47+
return validAddresses;
48+
}
49+
2450
const transferTemplate = `Respond with a JSON markdown block containing only the extracted values. Use null for any values that cannot be determined.
2551
2652
For the amount to send, use a value from 1 - 100. Determine this based on your judgement of the recipient.

‎packages/plugin-starknet/src/actions/unruggable.ts

+4-5
Original file line numberDiff line numberDiff line change
@@ -1,22 +1,21 @@
11
import {
2+
type Action,
23
ActionExample,
4+
composeContext,
35
elizaLogger,
6+
generateObject,
47
HandlerCallback,
58
IAgentRuntime,
69
Memory,
710
ModelClass,
811
State,
9-
type Action,
1012
} from "@ai16z/eliza";
11-
import { composeContext } from "@ai16z/eliza";
12-
import { generateObject } from "@ai16z/eliza";
1313
import { Percent } from "@uniswap/sdk-core";
1414
import {
1515
getStarknetAccount,
1616
getStarknetProvider,
1717
parseFormatedAmount,
1818
parseFormatedPercentage,
19-
validateSettings,
2019
} from "../utils/index.ts";
2120
import { DeployData, Factory } from "@unruggable_starknet/core";
2221
import {
@@ -69,7 +68,7 @@ Example response:
6968
7069
Extract the following information about the requested token deployment:
7170
- Token Name
72-
- Token Symbol
71+
- Token Symbol
7372
- Token Owner
7473
- Token initial supply
7574

‎packages/plugin-starknet/src/enviroment.ts

+4-1
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
import { IAgentRuntime } from "@ai16z/eliza";
22
import { z } from "zod";
33

4+
const STARKNET_PUBLIC_RPC = "https://starknet-mainnet.public.blastapi.io";
5+
46
export const starknetEnvSchema = z.object({
57
STARKNET_ADDRESS: z.string().min(1, "Starknet address is required"),
68
STARKNET_PRIVATE_KEY: z.string().min(1, "Starknet private key is required"),
@@ -22,7 +24,8 @@ export async function validateStarknetConfig(
2224
process.env.STARKNET_PRIVATE_KEY,
2325
STARKNET_RPC_URL:
2426
runtime.getSetting("STARKNET_RPC_URL") ||
25-
process.env.STARKNET_RPC_URL,
27+
process.env.STARKNET_RPC_URL ||
28+
STARKNET_PUBLIC_RPC,
2629
};
2730

2831
return starknetEnvSchema.parse(config);

‎packages/plugin-starknet/src/providers/token.ts

+41-18
Original file line numberDiff line numberDiff line change
@@ -53,7 +53,9 @@ export class TokenProvider {
5353

5454
if (!response.ok) {
5555
throw new Error(
56-
`HTTP error! status: ${response.status}, message: ${await response.text()}`
56+
`HTTP error! status: ${
57+
response.status
58+
}, message: ${await response.text()}`
5759
);
5860
}
5961

@@ -74,8 +76,9 @@ export class TokenProvider {
7476

7577
// TODO: Update to Starknet
7678
async getTokensInWallet(runtime: IAgentRuntime): Promise<Item[]> {
77-
const walletInfo =
78-
await this.walletProvider.fetchPortfolioValue(runtime);
79+
const walletInfo = await this.walletProvider.fetchPortfolioValue(
80+
runtime
81+
);
7982
const items = walletInfo.items;
8083
return items;
8184
}
@@ -136,8 +139,8 @@ export class TokenProvider {
136139
token === STRK
137140
? "starknet"
138141
: token === BTC
139-
? "bitcoin"
140-
: "ethereum";
142+
? "bitcoin"
143+
: "ethereum";
141144

142145
prices[priceKey].usd = tokenInfo.market.currentPrice.toString();
143146
});
@@ -464,7 +467,9 @@ export class TokenProvider {
464467
const limit = 1000;
465468
let cursor;
466469
//HELIOUS_API_KEY needs to be added
467-
const url = `https://mainnet.helius-rpc.com/?api-key=${settings.HELIUS_API_KEY || ""}`;
470+
const url = `https://mainnet.helius-rpc.com/?api-key=${
471+
settings.HELIUS_API_KEY || ""
472+
}`;
468473
console.log({ url });
469474

470475
try {
@@ -505,7 +510,9 @@ export class TokenProvider {
505510
data.result.token_accounts.length === 0
506511
) {
507512
console.log(
508-
`No more holders found. Total pages fetched: ${page - 1}`
513+
`No more holders found. Total pages fetched: ${
514+
page - 1
515+
}`
509516
);
510517
break;
511518
}
@@ -619,8 +626,9 @@ export class TokenProvider {
619626
console.log(
620627
`Filtering high-value holders for token: ${this.tokenAddress}`
621628
);
622-
const highValueHolders =
623-
await this.filterHighValueHolders(tradeData);
629+
const highValueHolders = await this.filterHighValueHolders(
630+
tradeData
631+
);
624632

625633
console.log(
626634
`Checking recent trades for token: ${this.tokenAddress}`
@@ -632,8 +640,9 @@ export class TokenProvider {
632640
console.log(
633641
`Counting high-supply holders for token: ${this.tokenAddress}`
634642
);
635-
const highSupplyHoldersCount =
636-
await this.countHighSupplyHolders(security);
643+
const highSupplyHoldersCount = await this.countHighSupplyHolders(
644+
security
645+
);
637646

638647
console.log(
639648
`Determining DexScreener listing status for token: ${this.tokenAddress}`
@@ -748,25 +757,39 @@ export class TokenProvider {
748757
output += `\n`;
749758

750759
// Recent Trades
751-
output += `**Recent Trades (Last 24h):** ${data.recentTrades ? "Yes" : "No"}\n\n`;
760+
output += `**Recent Trades (Last 24h):** ${
761+
data.recentTrades ? "Yes" : "No"
762+
}\n\n`;
752763

753764
// High-Supply Holders
754765
output += `**Holders with >2% Supply:** ${data.highSupplyHoldersCount}\n\n`;
755766

756767
// DexScreener Status
757-
output += `**DexScreener Listing:** ${data.isDexScreenerListed ? "Yes" : "No"}\n`;
768+
output += `**DexScreener Listing:** ${
769+
data.isDexScreenerListed ? "Yes" : "No"
770+
}\n`;
758771
if (data.isDexScreenerListed) {
759-
output += `- Listing Type: ${data.isDexScreenerPaid ? "Paid" : "Free"}\n`;
772+
output += `- Listing Type: ${
773+
data.isDexScreenerPaid ? "Paid" : "Free"
774+
}\n`;
760775
output += `- Number of DexPairs: ${data.dexScreenerData.pairs.length}\n\n`;
761776
output += `**DexScreener Pairs:**\n`;
762777
data.dexScreenerData.pairs.forEach((pair, index) => {
763778
output += `\n**Pair ${index + 1}:**\n`;
764779
output += `- DEX: ${pair.dexId}\n`;
765780
output += `- URL: ${pair.url}\n`;
766-
output += `- Price USD: $${num.toBigInt(pair.priceUsd).toString()}\n`;
767-
output += `- Volume (24h USD): $${num.toBigInt(pair.volume.h24).toString()}\n`;
768-
output += `- Boosts Active: ${pair.boosts && pair.boosts.active}\n`;
769-
output += `- Liquidity USD: $${num.toBigInt(pair.liquidity.usd).toString()}\n`;
781+
output += `- Price USD: $${num
782+
.toBigInt(pair.priceUsd)
783+
.toString()}\n`;
784+
output += `- Volume (24h USD): $${num
785+
.toBigInt(pair.volume.h24)
786+
.toString()}\n`;
787+
output += `- Boosts Active: ${
788+
pair.boosts && pair.boosts.active
789+
}\n`;
790+
output += `- Liquidity USD: $${num
791+
.toBigInt(pair.liquidity.usd)
792+
.toString()}\n`;
770793
});
771794
}
772795
output += `\n`;

‎packages/plugin-starknet/src/providers/trustScoreProvider.ts

+9-4
Original file line numberDiff line numberDiff line change
@@ -621,8 +621,9 @@ export const trustScoreProvider: Provider = {
621621
}
622622

623623
// Get the recommender metrics for the user
624-
const recommenderMetrics =
625-
await trustScoreDb.getRecommenderMetrics(userId);
624+
const recommenderMetrics = await trustScoreDb.getRecommenderMetrics(
625+
userId
626+
);
626627

627628
if (!recommenderMetrics) {
628629
console.error("No recommender metrics found for user:", userId);
@@ -635,12 +636,16 @@ export const trustScoreProvider: Provider = {
635636
const user = await runtime.databaseAdapter.getAccountById(userId);
636637

637638
// Format the trust score string
638-
const trustScoreString = `${user.name}'s trust score: ${trustScore.toFixed(2)}`;
639+
const trustScoreString = `${
640+
user.name
641+
}'s trust score: ${trustScore.toFixed(2)}`;
639642

640643
return trustScoreString;
641644
} catch (error) {
642645
console.error("Error in trust score provider:", error.message);
643-
return `Failed to fetch trust score: ${error instanceof Error ? error.message : "Unknown error"}`;
646+
return `Failed to fetch trust score: ${
647+
error instanceof Error ? error.message : "Unknown error"
648+
}`;
644649
}
645650
},
646651
};

‎packages/plugin-starknet/src/providers/walletProvider.ts

+9-3
Original file line numberDiff line numberDiff line change
@@ -108,7 +108,9 @@ export class WalletProvider {
108108

109109
async fetchPortfolioValue(runtime): Promise<WalletPortfolio> {
110110
try {
111-
const cacheKey = `portfolio-${this.runtime.getSetting("STARKNET_WALLET_ADDRESS")}`;
111+
const cacheKey = `portfolio-${this.runtime.getSetting(
112+
"STARKNET_WALLET_ADDRESS"
113+
)}`;
112114
const cachedValue = this.cache.get<WalletPortfolio>(cacheKey);
113115

114116
if (cachedValue) {
@@ -223,7 +225,9 @@ export class WalletProvider {
223225
prices: Prices
224226
): string {
225227
let output = `${runtime.character.description}\n`;
226-
output += `Wallet Address: ${this.runtime.getSetting("STARKNET_WALLET_ADDRESS")}\n\n`;
228+
output += `Wallet Address: ${this.runtime.getSetting(
229+
"STARKNET_WALLET_ADDRESS"
230+
)}\n\n`;
227231

228232
const totalUsdFormatted = new BigNumber(portfolio.totalUsd).toFixed(2);
229233
const totalSolFormatted = portfolio.totalSol;
@@ -285,7 +289,9 @@ const walletProvider: Provider = {
285289
return await provider.getFormattedPortfolio(runtime);
286290
} catch (error) {
287291
console.error("Error in wallet provider:", error.message);
288-
return `Failed to fetch wallet information: ${error instanceof Error ? error.message : "Unknown error"}`;
292+
return `Failed to fetch wallet information: ${
293+
error instanceof Error ? error.message : "Unknown error"
294+
}`;
289295
}
290296
},
291297
};

‎packages/plugin-starknet/src/utils/index.ts

+1-47
Original file line numberDiff line numberDiff line change
@@ -1,24 +1,7 @@
1-
import { Content, IAgentRuntime } from "@ai16z/eliza";
1+
import { IAgentRuntime } from "@ai16z/eliza";
22
import { Fraction, Percent } from "@uniswap/sdk-core";
3-
43
import { Account, Contract, RpcProvider } from "starknet";
54

6-
export const validateSettings = (runtime: IAgentRuntime) => {
7-
const requiredSettings = [
8-
"STARKNET_ADDRESS",
9-
"STARKNET_PRIVATE_KEY",
10-
"STARKNET_RPC_URL",
11-
];
12-
13-
for (const setting of requiredSettings) {
14-
if (!runtime.getSetting(setting)) {
15-
return false;
16-
}
17-
}
18-
19-
return true;
20-
};
21-
225
export const getTokenBalance = async (
236
runtime: IAgentRuntime,
247
tokenAddress: string
@@ -51,35 +34,6 @@ export const getStarknetAccount = (runtime: IAgentRuntime) => {
5134
);
5235
};
5336

54-
export interface TransferContent extends Content {
55-
tokenAddress: string;
56-
recipient: string;
57-
amount: string | number;
58-
}
59-
60-
export function isTransferContent(
61-
content: TransferContent
62-
): content is TransferContent {
63-
// Validate types
64-
const validTypes =
65-
typeof content.tokenAddress === "string" &&
66-
typeof content.recipient === "string" &&
67-
(typeof content.amount === "string" ||
68-
typeof content.amount === "number");
69-
if (!validTypes) {
70-
return false;
71-
}
72-
73-
// Validate addresses (must be 32-bytes long with 0x prefix)
74-
const validAddresses =
75-
content.tokenAddress.startsWith("0x") &&
76-
content.tokenAddress.length === 66 &&
77-
content.recipient.startsWith("0x") &&
78-
content.recipient.length === 66;
79-
80-
return validAddresses;
81-
}
82-
8337
export const getPercent = (amount: string | number, decimals: number) => {
8438
return new Percent(amount, decimals);
8539
};

0 commit comments

Comments
 (0)
Please sign in to comment.