logiqical 0.2.0 → 0.3.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +402 -81
- package/dist/cli.mjs +3278 -0
- package/dist/index.d.mts +749 -792
- package/dist/index.d.ts +749 -792
- package/dist/index.js +2283 -774
- package/dist/index.js.map +1 -0
- package/dist/index.mjs +2268 -773
- package/dist/index.mjs.map +1 -0
- package/package.json +20 -10
package/dist/cli.mjs
ADDED
|
@@ -0,0 +1,3278 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
// src/mcp/cli.ts
|
|
4
|
+
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
|
|
5
|
+
|
|
6
|
+
// src/client.ts
|
|
7
|
+
import { ethers as ethers8, JsonRpcProvider as JsonRpcProvider2, Contract } from "ethers";
|
|
8
|
+
|
|
9
|
+
// src/wallet.ts
|
|
10
|
+
import {
|
|
11
|
+
Wallet,
|
|
12
|
+
JsonRpcProvider
|
|
13
|
+
} from "ethers";
|
|
14
|
+
import { readFileSync, writeFileSync, mkdirSync, existsSync } from "fs";
|
|
15
|
+
import { join } from "path";
|
|
16
|
+
import { homedir } from "os";
|
|
17
|
+
var CHAINS = {
|
|
18
|
+
avalanche: {
|
|
19
|
+
chainId: 43114,
|
|
20
|
+
name: "Avalanche C-Chain",
|
|
21
|
+
rpcUrl: "https://api.avax.network/ext/bc/C/rpc",
|
|
22
|
+
nativeCurrency: { name: "Avalanche", symbol: "AVAX", decimals: 18 },
|
|
23
|
+
blockExplorer: "https://snowtrace.io"
|
|
24
|
+
},
|
|
25
|
+
fuji: {
|
|
26
|
+
chainId: 43113,
|
|
27
|
+
name: "Avalanche Fuji Testnet",
|
|
28
|
+
rpcUrl: "https://api.avax-test.network/ext/bc/C/rpc",
|
|
29
|
+
nativeCurrency: { name: "Avalanche", symbol: "AVAX", decimals: 18 },
|
|
30
|
+
blockExplorer: "https://testnet.snowtrace.io"
|
|
31
|
+
},
|
|
32
|
+
ethereum: {
|
|
33
|
+
chainId: 1,
|
|
34
|
+
name: "Ethereum",
|
|
35
|
+
rpcUrl: "https://eth.llamarpc.com",
|
|
36
|
+
nativeCurrency: { name: "Ether", symbol: "ETH", decimals: 18 },
|
|
37
|
+
blockExplorer: "https://etherscan.io"
|
|
38
|
+
},
|
|
39
|
+
base: {
|
|
40
|
+
chainId: 8453,
|
|
41
|
+
name: "Base",
|
|
42
|
+
rpcUrl: "https://mainnet.base.org",
|
|
43
|
+
nativeCurrency: { name: "Ether", symbol: "ETH", decimals: 18 },
|
|
44
|
+
blockExplorer: "https://basescan.org"
|
|
45
|
+
},
|
|
46
|
+
arbitrum: {
|
|
47
|
+
chainId: 42161,
|
|
48
|
+
name: "Arbitrum One",
|
|
49
|
+
rpcUrl: "https://arb1.arbitrum.io/rpc",
|
|
50
|
+
nativeCurrency: { name: "Ether", symbol: "ETH", decimals: 18 },
|
|
51
|
+
blockExplorer: "https://arbiscan.io"
|
|
52
|
+
},
|
|
53
|
+
optimism: {
|
|
54
|
+
chainId: 10,
|
|
55
|
+
name: "Optimism",
|
|
56
|
+
rpcUrl: "https://mainnet.optimism.io",
|
|
57
|
+
nativeCurrency: { name: "Ether", symbol: "ETH", decimals: 18 },
|
|
58
|
+
blockExplorer: "https://optimistic.etherscan.io"
|
|
59
|
+
},
|
|
60
|
+
polygon: {
|
|
61
|
+
chainId: 137,
|
|
62
|
+
name: "Polygon",
|
|
63
|
+
rpcUrl: "https://polygon-rpc.com",
|
|
64
|
+
nativeCurrency: { name: "MATIC", symbol: "MATIC", decimals: 18 },
|
|
65
|
+
blockExplorer: "https://polygonscan.com"
|
|
66
|
+
},
|
|
67
|
+
bsc: {
|
|
68
|
+
chainId: 56,
|
|
69
|
+
name: "BNB Smart Chain",
|
|
70
|
+
rpcUrl: "https://bsc-dataseed.binance.org",
|
|
71
|
+
nativeCurrency: { name: "BNB", symbol: "BNB", decimals: 18 },
|
|
72
|
+
blockExplorer: "https://bscscan.com"
|
|
73
|
+
},
|
|
74
|
+
fantom: {
|
|
75
|
+
chainId: 250,
|
|
76
|
+
name: "Fantom Opera",
|
|
77
|
+
rpcUrl: "https://rpc.ftm.tools",
|
|
78
|
+
nativeCurrency: { name: "Fantom", symbol: "FTM", decimals: 18 },
|
|
79
|
+
blockExplorer: "https://ftmscan.com"
|
|
80
|
+
},
|
|
81
|
+
gnosis: {
|
|
82
|
+
chainId: 100,
|
|
83
|
+
name: "Gnosis Chain",
|
|
84
|
+
rpcUrl: "https://rpc.gnosischain.com",
|
|
85
|
+
nativeCurrency: { name: "xDAI", symbol: "xDAI", decimals: 18 },
|
|
86
|
+
blockExplorer: "https://gnosisscan.io"
|
|
87
|
+
},
|
|
88
|
+
zksync: {
|
|
89
|
+
chainId: 324,
|
|
90
|
+
name: "zkSync Era",
|
|
91
|
+
rpcUrl: "https://mainnet.era.zksync.io",
|
|
92
|
+
nativeCurrency: { name: "Ether", symbol: "ETH", decimals: 18 },
|
|
93
|
+
blockExplorer: "https://explorer.zksync.io"
|
|
94
|
+
},
|
|
95
|
+
linea: {
|
|
96
|
+
chainId: 59144,
|
|
97
|
+
name: "Linea",
|
|
98
|
+
rpcUrl: "https://rpc.linea.build",
|
|
99
|
+
nativeCurrency: { name: "Ether", symbol: "ETH", decimals: 18 },
|
|
100
|
+
blockExplorer: "https://lineascan.build"
|
|
101
|
+
},
|
|
102
|
+
scroll: {
|
|
103
|
+
chainId: 534352,
|
|
104
|
+
name: "Scroll",
|
|
105
|
+
rpcUrl: "https://rpc.scroll.io",
|
|
106
|
+
nativeCurrency: { name: "Ether", symbol: "ETH", decimals: 18 },
|
|
107
|
+
blockExplorer: "https://scrollscan.com"
|
|
108
|
+
},
|
|
109
|
+
blast: {
|
|
110
|
+
chainId: 81457,
|
|
111
|
+
name: "Blast",
|
|
112
|
+
rpcUrl: "https://rpc.blast.io",
|
|
113
|
+
nativeCurrency: { name: "Ether", symbol: "ETH", decimals: 18 },
|
|
114
|
+
blockExplorer: "https://blastscan.io"
|
|
115
|
+
},
|
|
116
|
+
mantle: {
|
|
117
|
+
chainId: 5e3,
|
|
118
|
+
name: "Mantle",
|
|
119
|
+
rpcUrl: "https://rpc.mantle.xyz",
|
|
120
|
+
nativeCurrency: { name: "MNT", symbol: "MNT", decimals: 18 },
|
|
121
|
+
blockExplorer: "https://mantlescan.xyz"
|
|
122
|
+
},
|
|
123
|
+
celo: {
|
|
124
|
+
chainId: 42220,
|
|
125
|
+
name: "Celo",
|
|
126
|
+
rpcUrl: "https://forno.celo.org",
|
|
127
|
+
nativeCurrency: { name: "CELO", symbol: "CELO", decimals: 18 },
|
|
128
|
+
blockExplorer: "https://celoscan.io"
|
|
129
|
+
},
|
|
130
|
+
moonbeam: {
|
|
131
|
+
chainId: 1284,
|
|
132
|
+
name: "Moonbeam",
|
|
133
|
+
rpcUrl: "https://rpc.api.moonbeam.network",
|
|
134
|
+
nativeCurrency: { name: "GLMR", symbol: "GLMR", decimals: 18 },
|
|
135
|
+
blockExplorer: "https://moonscan.io"
|
|
136
|
+
},
|
|
137
|
+
sei: {
|
|
138
|
+
chainId: 1329,
|
|
139
|
+
name: "Sei",
|
|
140
|
+
rpcUrl: "https://evm-rpc.sei-apis.com",
|
|
141
|
+
nativeCurrency: { name: "SEI", symbol: "SEI", decimals: 18 },
|
|
142
|
+
blockExplorer: "https://seitrace.com"
|
|
143
|
+
},
|
|
144
|
+
mode: {
|
|
145
|
+
chainId: 34443,
|
|
146
|
+
name: "Mode",
|
|
147
|
+
rpcUrl: "https://mainnet.mode.network",
|
|
148
|
+
nativeCurrency: { name: "Ether", symbol: "ETH", decimals: 18 },
|
|
149
|
+
blockExplorer: "https://explorer.mode.network"
|
|
150
|
+
},
|
|
151
|
+
aurora: {
|
|
152
|
+
chainId: 1313161554,
|
|
153
|
+
name: "Aurora",
|
|
154
|
+
rpcUrl: "https://mainnet.aurora.dev",
|
|
155
|
+
nativeCurrency: { name: "Ether", symbol: "ETH", decimals: 18 },
|
|
156
|
+
blockExplorer: "https://explorer.aurora.dev"
|
|
157
|
+
}
|
|
158
|
+
};
|
|
159
|
+
var KEYSTORE_DIR = join(homedir(), ".logiqical", "keys");
|
|
160
|
+
function ensureKeystoreDir() {
|
|
161
|
+
if (!existsSync(KEYSTORE_DIR)) {
|
|
162
|
+
mkdirSync(KEYSTORE_DIR, { recursive: true });
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
var AgentWallet = class _AgentWallet {
|
|
166
|
+
wallet;
|
|
167
|
+
provider;
|
|
168
|
+
chain;
|
|
169
|
+
address;
|
|
170
|
+
constructor(wallet, provider, chain) {
|
|
171
|
+
this.wallet = wallet;
|
|
172
|
+
this.provider = provider;
|
|
173
|
+
this.chain = chain;
|
|
174
|
+
this.address = wallet.address;
|
|
175
|
+
}
|
|
176
|
+
/** The private key (use carefully) */
|
|
177
|
+
get privateKey() {
|
|
178
|
+
return this.wallet.privateKey;
|
|
179
|
+
}
|
|
180
|
+
// ── Factory Methods ──
|
|
181
|
+
/** Generate a brand new wallet with a random private key */
|
|
182
|
+
static generate(config = {}) {
|
|
183
|
+
const { provider, chain } = _AgentWallet.resolveProvider(config);
|
|
184
|
+
const hdWallet = Wallet.createRandom();
|
|
185
|
+
const wallet = new Wallet(hdWallet.privateKey, provider);
|
|
186
|
+
return new _AgentWallet(wallet, provider, chain);
|
|
187
|
+
}
|
|
188
|
+
/** Import an existing wallet from a private key */
|
|
189
|
+
static fromPrivateKey(privateKey, config = {}) {
|
|
190
|
+
const { provider, chain } = _AgentWallet.resolveProvider(config);
|
|
191
|
+
const wallet = new Wallet(privateKey, provider);
|
|
192
|
+
return new _AgentWallet(wallet, provider, chain);
|
|
193
|
+
}
|
|
194
|
+
/** Boot from encrypted keystore, or generate + save if none exists */
|
|
195
|
+
static async boot(config = {}) {
|
|
196
|
+
const password = config.password ?? "logiqical-agent";
|
|
197
|
+
const name = config.keystoreName ?? "agent";
|
|
198
|
+
const keystorePath = join(KEYSTORE_DIR, `${name}.json`);
|
|
199
|
+
const { provider, chain } = _AgentWallet.resolveProvider(config);
|
|
200
|
+
if (existsSync(keystorePath)) {
|
|
201
|
+
const data = JSON.parse(readFileSync(keystorePath, "utf-8"));
|
|
202
|
+
const decrypted = await Wallet.fromEncryptedJson(data.encryptedJson, password);
|
|
203
|
+
const connected = new Wallet(decrypted.privateKey, provider);
|
|
204
|
+
return new _AgentWallet(connected, provider, chain);
|
|
205
|
+
}
|
|
206
|
+
const hdWallet = Wallet.createRandom();
|
|
207
|
+
const wallet = new Wallet(hdWallet.privateKey, provider);
|
|
208
|
+
const agentWallet = new _AgentWallet(wallet, provider, chain);
|
|
209
|
+
await agentWallet.saveKeystore(password, name);
|
|
210
|
+
return agentWallet;
|
|
211
|
+
}
|
|
212
|
+
// ── Keystore Operations ──
|
|
213
|
+
/** Encrypt and save the wallet to the keystore directory */
|
|
214
|
+
async saveKeystore(password, name) {
|
|
215
|
+
const pw = password ?? "logiqical-agent";
|
|
216
|
+
const n = name ?? "agent";
|
|
217
|
+
ensureKeystoreDir();
|
|
218
|
+
const encryptedJson = await this.wallet.encrypt(pw);
|
|
219
|
+
const data = {
|
|
220
|
+
address: this.address,
|
|
221
|
+
encryptedJson,
|
|
222
|
+
network: this.chain.name,
|
|
223
|
+
createdAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
224
|
+
};
|
|
225
|
+
const keystorePath = join(KEYSTORE_DIR, `${n}.json`);
|
|
226
|
+
writeFileSync(keystorePath, JSON.stringify(data, null, 2));
|
|
227
|
+
return keystorePath;
|
|
228
|
+
}
|
|
229
|
+
// ── Core Operations ──
|
|
230
|
+
/** Get native token balance (formatted) */
|
|
231
|
+
async getBalance() {
|
|
232
|
+
const balance = await this.provider.getBalance(this.address);
|
|
233
|
+
const { formatEther } = await import("ethers");
|
|
234
|
+
return formatEther(balance);
|
|
235
|
+
}
|
|
236
|
+
/** Get balance of any address */
|
|
237
|
+
async getBalanceOf(address) {
|
|
238
|
+
const balance = await this.provider.getBalance(address);
|
|
239
|
+
const { formatEther } = await import("ethers");
|
|
240
|
+
return formatEther(balance);
|
|
241
|
+
}
|
|
242
|
+
/** Sign a message */
|
|
243
|
+
async signMessage(message) {
|
|
244
|
+
return this.wallet.signMessage(message);
|
|
245
|
+
}
|
|
246
|
+
/** Sign typed data (EIP-712) */
|
|
247
|
+
async signTypedData(domain, types, value) {
|
|
248
|
+
return this.wallet.signTypedData(domain, types, value);
|
|
249
|
+
}
|
|
250
|
+
/** Sign a transaction without broadcasting */
|
|
251
|
+
async signTransaction(tx) {
|
|
252
|
+
return this.wallet.signTransaction(tx);
|
|
253
|
+
}
|
|
254
|
+
/** Sign and broadcast a transaction */
|
|
255
|
+
async sendTransaction(tx) {
|
|
256
|
+
return this.wallet.sendTransaction(tx);
|
|
257
|
+
}
|
|
258
|
+
/** Send native token to an address */
|
|
259
|
+
async send(to, amount) {
|
|
260
|
+
const { parseEther } = await import("ethers");
|
|
261
|
+
return this.wallet.sendTransaction({
|
|
262
|
+
to,
|
|
263
|
+
value: parseEther(amount)
|
|
264
|
+
});
|
|
265
|
+
}
|
|
266
|
+
/**
|
|
267
|
+
* Sign and broadcast an unsigned tx object returned by the Logiqical API.
|
|
268
|
+
* Handles the { to, data, value, chainId, gas/gasLimit } format.
|
|
269
|
+
*/
|
|
270
|
+
async signAndBroadcast(unsignedTx) {
|
|
271
|
+
const tx = {
|
|
272
|
+
to: unsignedTx.to,
|
|
273
|
+
data: unsignedTx.data,
|
|
274
|
+
value: unsignedTx.value
|
|
275
|
+
};
|
|
276
|
+
if (unsignedTx.gasLimit || unsignedTx.gas) {
|
|
277
|
+
tx.gasLimit = unsignedTx.gasLimit || unsignedTx.gas;
|
|
278
|
+
}
|
|
279
|
+
return this.wallet.sendTransaction(tx);
|
|
280
|
+
}
|
|
281
|
+
/**
|
|
282
|
+
* Sign and broadcast multiple unsigned txs in sequence.
|
|
283
|
+
* Waits for each to confirm before sending the next.
|
|
284
|
+
*/
|
|
285
|
+
async signAndBroadcastAll(unsignedTxs, confirmations = 1) {
|
|
286
|
+
const results = [];
|
|
287
|
+
for (const utx of unsignedTxs) {
|
|
288
|
+
const txResponse = await this.signAndBroadcast(utx);
|
|
289
|
+
await txResponse.wait(confirmations);
|
|
290
|
+
results.push(txResponse);
|
|
291
|
+
}
|
|
292
|
+
return results;
|
|
293
|
+
}
|
|
294
|
+
/** Call a read-only contract method (no gas, no signing) */
|
|
295
|
+
async call(tx) {
|
|
296
|
+
return this.provider.call(tx);
|
|
297
|
+
}
|
|
298
|
+
/** Switch to a different network (returns new AgentWallet instance) */
|
|
299
|
+
switchNetwork(network) {
|
|
300
|
+
const { provider, chain } = _AgentWallet.resolveProvider({ network });
|
|
301
|
+
const wallet = new Wallet(this.privateKey, provider);
|
|
302
|
+
return new _AgentWallet(wallet, provider, chain);
|
|
303
|
+
}
|
|
304
|
+
// ── Internal ──
|
|
305
|
+
static resolveProvider(config) {
|
|
306
|
+
const networkKey = config.network ?? "avalanche";
|
|
307
|
+
const chain = CHAINS[networkKey];
|
|
308
|
+
if (!chain && !config.rpcUrl) {
|
|
309
|
+
throw new Error(`Unknown network "${networkKey}". Use a known chain (${Object.keys(CHAINS).join(", ")}) or provide rpcUrl.`);
|
|
310
|
+
}
|
|
311
|
+
const rpcUrl = config.rpcUrl ?? chain.rpcUrl;
|
|
312
|
+
const resolvedChain = chain ?? {
|
|
313
|
+
chainId: 0,
|
|
314
|
+
name: networkKey,
|
|
315
|
+
rpcUrl,
|
|
316
|
+
nativeCurrency: { name: "ETH", symbol: "ETH", decimals: 18 }
|
|
317
|
+
};
|
|
318
|
+
const provider = new JsonRpcProvider(rpcUrl, resolvedChain.chainId || void 0);
|
|
319
|
+
return { provider, chain: resolvedChain };
|
|
320
|
+
}
|
|
321
|
+
};
|
|
322
|
+
|
|
323
|
+
// src/policy.ts
|
|
324
|
+
import { ethers } from "ethers";
|
|
325
|
+
var PolicyEngine = class {
|
|
326
|
+
policy;
|
|
327
|
+
spendLog = [];
|
|
328
|
+
constructor(policy = {}) {
|
|
329
|
+
this.policy = policy;
|
|
330
|
+
}
|
|
331
|
+
getPolicy() {
|
|
332
|
+
return { ...this.policy };
|
|
333
|
+
}
|
|
334
|
+
setPolicy(policy) {
|
|
335
|
+
this.policy = policy;
|
|
336
|
+
}
|
|
337
|
+
updatePolicy(updates) {
|
|
338
|
+
this.policy = { ...this.policy, ...updates };
|
|
339
|
+
}
|
|
340
|
+
/** Check a transaction against the policy. Throws if rejected. */
|
|
341
|
+
check(tx) {
|
|
342
|
+
const value = tx.value ? BigInt(tx.value) : 0n;
|
|
343
|
+
if (this.policy.maxPerTx) {
|
|
344
|
+
const max = ethers.parseEther(this.policy.maxPerTx);
|
|
345
|
+
if (value > max) {
|
|
346
|
+
throw new PolicyError(
|
|
347
|
+
`Transaction value ${ethers.formatEther(value)} exceeds per-tx limit of ${this.policy.maxPerTx}`,
|
|
348
|
+
"MAX_PER_TX_EXCEEDED"
|
|
349
|
+
);
|
|
350
|
+
}
|
|
351
|
+
}
|
|
352
|
+
if (this.policy.allowedContracts && this.policy.allowedContracts.length > 0) {
|
|
353
|
+
const to = tx.to.toLowerCase();
|
|
354
|
+
const allowed = this.policy.allowedContracts.map((a) => a.toLowerCase());
|
|
355
|
+
if (!allowed.includes(to)) {
|
|
356
|
+
throw new PolicyError(
|
|
357
|
+
`Contract ${tx.to} not in allowlist`,
|
|
358
|
+
"CONTRACT_NOT_ALLOWED"
|
|
359
|
+
);
|
|
360
|
+
}
|
|
361
|
+
}
|
|
362
|
+
if (this.policy.blockedContracts && this.policy.blockedContracts.length > 0) {
|
|
363
|
+
const to = tx.to.toLowerCase();
|
|
364
|
+
const blocked = this.policy.blockedContracts.map((b) => b.toLowerCase());
|
|
365
|
+
if (blocked.includes(to)) {
|
|
366
|
+
throw new PolicyError(
|
|
367
|
+
`Contract ${tx.to} is blocked`,
|
|
368
|
+
"CONTRACT_BLOCKED"
|
|
369
|
+
);
|
|
370
|
+
}
|
|
371
|
+
}
|
|
372
|
+
if (this.policy.maxPerHour) {
|
|
373
|
+
const max = ethers.parseEther(this.policy.maxPerHour);
|
|
374
|
+
const hourSpend = this.getSpendSince(Date.now() - 36e5);
|
|
375
|
+
if (hourSpend + value > max) {
|
|
376
|
+
throw new PolicyError(
|
|
377
|
+
`Would exceed hourly budget of ${this.policy.maxPerHour} AVAX (spent ${ethers.formatEther(hourSpend)} this hour)`,
|
|
378
|
+
"HOURLY_BUDGET_EXCEEDED"
|
|
379
|
+
);
|
|
380
|
+
}
|
|
381
|
+
}
|
|
382
|
+
if (this.policy.maxPerDay) {
|
|
383
|
+
const max = ethers.parseEther(this.policy.maxPerDay);
|
|
384
|
+
const daySpend = this.getSpendSince(Date.now() - 864e5);
|
|
385
|
+
if (daySpend + value > max) {
|
|
386
|
+
throw new PolicyError(
|
|
387
|
+
`Would exceed daily budget of ${this.policy.maxPerDay} AVAX (spent ${ethers.formatEther(daySpend)} today)`,
|
|
388
|
+
"DAILY_BUDGET_EXCEEDED"
|
|
389
|
+
);
|
|
390
|
+
}
|
|
391
|
+
}
|
|
392
|
+
}
|
|
393
|
+
/** Record a spend after successful broadcast */
|
|
394
|
+
recordSpend(value) {
|
|
395
|
+
this.spendLog.push({ amount: value, timestamp: Date.now() });
|
|
396
|
+
const cutoff = Date.now() - 864e5;
|
|
397
|
+
this.spendLog = this.spendLog.filter((r) => r.timestamp > cutoff);
|
|
398
|
+
}
|
|
399
|
+
/** Get budget status */
|
|
400
|
+
getBudgetStatus() {
|
|
401
|
+
const hourSpend = this.getSpendSince(Date.now() - 36e5);
|
|
402
|
+
const daySpend = this.getSpendSince(Date.now() - 864e5);
|
|
403
|
+
return {
|
|
404
|
+
spentLastHour: ethers.formatEther(hourSpend),
|
|
405
|
+
spentLast24h: ethers.formatEther(daySpend),
|
|
406
|
+
remainingHour: this.policy.maxPerHour ? ethers.formatEther(ethers.parseEther(this.policy.maxPerHour) - hourSpend) : null,
|
|
407
|
+
remainingDay: this.policy.maxPerDay ? ethers.formatEther(ethers.parseEther(this.policy.maxPerDay) - daySpend) : null
|
|
408
|
+
};
|
|
409
|
+
}
|
|
410
|
+
get shouldSimulate() {
|
|
411
|
+
return this.policy.simulateBeforeSend ?? false;
|
|
412
|
+
}
|
|
413
|
+
get isDryRun() {
|
|
414
|
+
return this.policy.dryRun ?? false;
|
|
415
|
+
}
|
|
416
|
+
getSpendSince(since) {
|
|
417
|
+
return this.spendLog.filter((r) => r.timestamp > since).reduce((sum, r) => sum + r.amount, 0n);
|
|
418
|
+
}
|
|
419
|
+
};
|
|
420
|
+
var PolicyError = class extends Error {
|
|
421
|
+
constructor(message, code) {
|
|
422
|
+
super(message);
|
|
423
|
+
this.code = code;
|
|
424
|
+
this.name = "PolicyError";
|
|
425
|
+
}
|
|
426
|
+
};
|
|
427
|
+
|
|
428
|
+
// src/modules/swap.ts
|
|
429
|
+
import { ethers as ethers2 } from "ethers";
|
|
430
|
+
|
|
431
|
+
// src/constants.ts
|
|
432
|
+
var CHAIN_ID = 43114;
|
|
433
|
+
var ARENA_TOKEN = "0xB8d7710f7d8349A506b75dD184F05777c82dAd0C";
|
|
434
|
+
var WAVAX = "0xB31f66AA3C1e785363F0875A1B74E27b85FD66c7";
|
|
435
|
+
var ARENA_STAKING = "0xeffb809d99142ce3b51c1796c096f5b01b4aaec4";
|
|
436
|
+
var LB_ROUTER = "0x18556DA13313f3532c54711497A8FedAC273220E";
|
|
437
|
+
var LB_QUOTER = "0x9A550a522BBaDFB69019b0432800Ed17855A51C3";
|
|
438
|
+
var LAUNCH_CONTRACT = "0x8315f1eb449Dd4B779495C3A0b05e5d194446c6e";
|
|
439
|
+
var TOKEN_MANAGER = "0x2196e106af476f57618373ec028924767c758464";
|
|
440
|
+
var AVAX_HELPER = "0x03f1a18519abedbef210fa44e13b71fec01b8dfa";
|
|
441
|
+
var ARENA_PAIRED_THRESHOLD = 100000000000n;
|
|
442
|
+
var GRANULARITY_SCALER = 10n ** 18n;
|
|
443
|
+
var ARENA_SHARES_CONTRACT = "0xc605c2cf66ee98ea925b1bb4fea584b71c00cc4c";
|
|
444
|
+
var FRACTION_SCALER = 100;
|
|
445
|
+
var ARENA_SOCIAL_API = "https://api.starsarena.com";
|
|
446
|
+
var LIFI_API = "https://li.quest/v1";
|
|
447
|
+
var HL_INFO = "https://api.hyperliquid.xyz/info";
|
|
448
|
+
var DEFAULT_SLIPPAGE_BPS = 500;
|
|
449
|
+
var ERC20_ABI = [
|
|
450
|
+
"function balanceOf(address owner) view returns (uint256)",
|
|
451
|
+
"function approve(address spender, uint256 amount) returns (bool)",
|
|
452
|
+
"function allowance(address owner, address spender) view returns (uint256)",
|
|
453
|
+
"function decimals() view returns (uint8)",
|
|
454
|
+
"function symbol() view returns (string)",
|
|
455
|
+
"function name() view returns (string)",
|
|
456
|
+
"function totalSupply() view returns (uint256)"
|
|
457
|
+
];
|
|
458
|
+
var ARENA_STAKING_ABI = [
|
|
459
|
+
"function deposit(uint256 _amount)",
|
|
460
|
+
"function withdraw(uint256 _amount)",
|
|
461
|
+
"function emergencyWithdraw()",
|
|
462
|
+
"function pendingReward(address _user, address _token) view returns (uint256)",
|
|
463
|
+
"function getUserInfo(address _user, address _rewardToken) view returns (uint256, uint256)",
|
|
464
|
+
"function rewardTokensLength() view returns (uint256)"
|
|
465
|
+
];
|
|
466
|
+
var LB_ROUTER_ABI = [
|
|
467
|
+
"function swapExactNATIVEForTokens(uint256 amountOutMin, tuple(uint256[] pairBinSteps, uint8[] versions, address[] tokenPath) path, address to, uint256 deadline) payable returns (uint256 amountOut)",
|
|
468
|
+
"function swapExactTokensForNATIVE(uint256 amountIn, uint256 amountOutMin, tuple(uint256[] pairBinSteps, uint8[] versions, address[] tokenPath) path, address payable to, uint256 deadline) returns (uint256 amountOut)"
|
|
469
|
+
];
|
|
470
|
+
var LB_QUOTER_ABI = [
|
|
471
|
+
"function findBestPathFromAmountIn(address[] calldata route, uint128 amountIn) view returns (tuple(address[] route, address[] pairs, uint256[] binSteps, uint256[] versions, uint128[] amounts, uint128[] virtualAmountsWithoutSlippage, uint128[] fees) quote)"
|
|
472
|
+
];
|
|
473
|
+
var LAUNCH_CONTRACT_ABI = [
|
|
474
|
+
"function createToken(uint16 a, uint8 b, uint128 curveScaler, uint8 creatorFeeBasisPoints, address tokenCreatorAddress, uint256 tokenSplit, string name, string symbol, uint256 amount) payable",
|
|
475
|
+
"function buyAndCreateLpIfPossible(uint256 amount, uint256 tokenId) payable",
|
|
476
|
+
"function sell(uint256 amount, uint256 tokenId)",
|
|
477
|
+
"function calculateCostWithFees(uint256 amountInToken, uint256 tokenId) view returns (uint256)",
|
|
478
|
+
"function calculateRewardWithFees(uint256 amount, uint256 tokenId) view returns (uint256)",
|
|
479
|
+
"function getMaxTokensForSale(uint256 tokenId) view returns (uint256)",
|
|
480
|
+
"function tokenSupply(uint256 tokenId) view returns (uint256)",
|
|
481
|
+
"function getTokenParameters(uint256 tokenId) view returns (uint128 curveScaler, uint16 a, uint8 b, bool lpDeployed, uint8 lpPercentage, uint8 salePercentage, uint8 creatorFeeBasisPoints, address creatorAddress, address pairAddress, address tokenContractAddress)",
|
|
482
|
+
"function tokenIdentifier() view returns (uint256)",
|
|
483
|
+
"function protocolFeeBasisPoint() view returns (uint256)",
|
|
484
|
+
"event Buy(address indexed user, uint256 indexed tokenId, uint256 tokenAmount, uint256 cost, uint256 tokenSupply, address referrerAddress, uint256 referralFee, uint256 creatorFee, uint256 protocolFee)",
|
|
485
|
+
"event Sell(address indexed user, uint256 indexed tokenId, uint256 tokenAmount, uint256 reward, uint256 tokenSupply, address referrerAddress, uint256 referralFee, uint256 creatorFee, uint256 protocolFee)"
|
|
486
|
+
];
|
|
487
|
+
var TOKEN_MANAGER_ABI = [
|
|
488
|
+
"function createToken(uint32 a, uint8 b, uint128 curveScaler, uint8 creatorFeeBasisPoints, address tokenCreatorAddress, uint256 tokenSplit, string name, string symbol, uint256 amount)",
|
|
489
|
+
"function calculateCostWithFees(uint256 amountInToken, uint256 tokenId) view returns (uint256)",
|
|
490
|
+
"function calculateRewardWithFees(uint256 amount, uint256 tokenId) view returns (uint256)",
|
|
491
|
+
"function getMaxTokensForSale(uint256 tokenId) view returns (uint256)",
|
|
492
|
+
"function tokenSupply(uint256 tokenId) view returns (uint256)",
|
|
493
|
+
"function getTokenParameters(uint256 tokenId) view returns (uint128 curveScaler, uint32 a, uint8 b, bool lpDeployed, uint8 lpPercentage, uint8 salePercentage, uint8 creatorFeeBasisPoints, address creatorAddress, address pairAddress, address tokenContractAddress)",
|
|
494
|
+
"function tokenIdentifier() view returns (uint256)",
|
|
495
|
+
"function protocolFeeBasisPoint() view returns (uint256)",
|
|
496
|
+
"event Buy(address indexed user, uint256 indexed tokenId, uint256 tokenAmount, uint256 cost, uint256 tokenSupply, address referrerAddress, uint256 referralFee, uint256 creatorFee, uint256 protocolFee)",
|
|
497
|
+
"event Sell(address indexed user, uint256 indexed tokenId, uint256 tokenAmount, uint256 reward, uint256 tokenSupply, address referrerAddress, uint256 referralFee, uint256 creatorFee, uint256 protocolFee)"
|
|
498
|
+
];
|
|
499
|
+
var AVAX_HELPER_ABI = [
|
|
500
|
+
"function buyAndCreateLpIfPossibleWithAvax(uint256 tokenId, uint256 amountOutMin) payable returns (uint256)",
|
|
501
|
+
"function sellToAvax(uint256 tokenId, uint256 amount, uint256 amountOutAvaxMin) returns (uint256)"
|
|
502
|
+
];
|
|
503
|
+
var SHARES_ABI = [
|
|
504
|
+
"function buyFractionalShares(address sharesSubject, address user, uint256 amount) payable",
|
|
505
|
+
"function sellFractionalShares(address sharesSubject, address user, uint256 amount) payable",
|
|
506
|
+
"function getBuyPriceForFractionalSharesAfterFee(address sharesSubject, uint256 amount) view returns (uint256)",
|
|
507
|
+
"function getSellPriceForFractionalSharesAfterFee(address sharesSubject, uint256 amount) view returns (uint256)",
|
|
508
|
+
"function getBuyPriceForFractionalShares(address sharesSubject, uint256 amount) view returns (uint256)",
|
|
509
|
+
"function getSellPriceForFractionalShares(address sharesSubject, uint256 amount) view returns (uint256)",
|
|
510
|
+
"function getMyFractionalShares(address sharesSubject, address user) view returns (uint256)",
|
|
511
|
+
"function getSharesSupply(address sharesSubject) view returns (uint256)",
|
|
512
|
+
"function getTotalFractionalSupply(address sharesSubject) view returns (uint256)",
|
|
513
|
+
"function fractionalSharesBalance(address, address) view returns (uint256)",
|
|
514
|
+
"function protocolFeePercent() view returns (uint256)",
|
|
515
|
+
"function subjectFeePercent() view returns (uint256)",
|
|
516
|
+
"function referralFeePercent() view returns (uint256)"
|
|
517
|
+
];
|
|
518
|
+
|
|
519
|
+
// src/modules/swap.ts
|
|
520
|
+
var SwapModule = class {
|
|
521
|
+
constructor(provider) {
|
|
522
|
+
this.provider = provider;
|
|
523
|
+
this.arenaToken = new ethers2.Contract(ethers2.getAddress(ARENA_TOKEN), ERC20_ABI, provider);
|
|
524
|
+
this.lbQuoter = new ethers2.Contract(ethers2.getAddress(LB_QUOTER), LB_QUOTER_ABI, provider);
|
|
525
|
+
}
|
|
526
|
+
arenaToken;
|
|
527
|
+
lbQuoter;
|
|
528
|
+
/** Get AVAX and ARENA balances for a wallet */
|
|
529
|
+
async getBalances(wallet) {
|
|
530
|
+
const [avax, arena] = await Promise.all([
|
|
531
|
+
this.provider.getBalance(wallet),
|
|
532
|
+
this.arenaToken.balanceOf(wallet)
|
|
533
|
+
]);
|
|
534
|
+
const decimals = await this.arenaToken.decimals();
|
|
535
|
+
return {
|
|
536
|
+
avax: avax.toString(),
|
|
537
|
+
arena: arena.toString(),
|
|
538
|
+
avaxFormatted: ethers2.formatEther(avax),
|
|
539
|
+
arenaFormatted: ethers2.formatUnits(arena, decimals)
|
|
540
|
+
};
|
|
541
|
+
}
|
|
542
|
+
/** Quote how much ARENA for a given AVAX amount (includes 0.3% fee) */
|
|
543
|
+
async quote(avaxAmount) {
|
|
544
|
+
const amountIn = ethers2.parseEther(avaxAmount);
|
|
545
|
+
const fee = amountIn * 30n / 10000n;
|
|
546
|
+
const netAmount = amountIn - fee;
|
|
547
|
+
const route = [WAVAX, ARENA_TOKEN];
|
|
548
|
+
const quote = await this.lbQuoter.findBestPathFromAmountIn(route, netAmount);
|
|
549
|
+
const arenaOut = quote.amounts[quote.amounts.length - 1];
|
|
550
|
+
const decimals = await this.arenaToken.decimals();
|
|
551
|
+
const arenaFormatted = ethers2.formatUnits(arenaOut, decimals);
|
|
552
|
+
return {
|
|
553
|
+
arenaOut: arenaFormatted,
|
|
554
|
+
fee: ethers2.formatEther(fee),
|
|
555
|
+
netAvax: ethers2.formatEther(netAmount),
|
|
556
|
+
rate: (parseFloat(arenaFormatted) / parseFloat(ethers2.formatEther(netAmount))).toFixed(2)
|
|
557
|
+
};
|
|
558
|
+
}
|
|
559
|
+
/** Quote how much AVAX for selling ARENA */
|
|
560
|
+
async sellQuote(arenaAmount) {
|
|
561
|
+
const decimals = await this.arenaToken.decimals();
|
|
562
|
+
const amountIn = ethers2.parseUnits(arenaAmount, decimals);
|
|
563
|
+
const route = [ARENA_TOKEN, WAVAX];
|
|
564
|
+
const quote = await this.lbQuoter.findBestPathFromAmountIn(route, amountIn);
|
|
565
|
+
const avaxOut = quote.amounts[quote.amounts.length - 1];
|
|
566
|
+
const avaxFormatted = ethers2.formatEther(avaxOut);
|
|
567
|
+
return {
|
|
568
|
+
avaxOut: avaxFormatted,
|
|
569
|
+
arenaIn: arenaAmount,
|
|
570
|
+
rate: (parseFloat(arenaAmount) / parseFloat(avaxFormatted)).toFixed(2)
|
|
571
|
+
};
|
|
572
|
+
}
|
|
573
|
+
/** Build unsigned tx to buy ARENA with AVAX via LFJ DEX */
|
|
574
|
+
async buildBuy(wallet, avaxAmount, slippageBps = DEFAULT_SLIPPAGE_BPS) {
|
|
575
|
+
const amountIn = ethers2.parseEther(avaxAmount);
|
|
576
|
+
const route = [WAVAX, ARENA_TOKEN];
|
|
577
|
+
const quote = await this.lbQuoter.findBestPathFromAmountIn(route, amountIn);
|
|
578
|
+
const expectedOut = quote.amounts[quote.amounts.length - 1];
|
|
579
|
+
if (expectedOut === 0n) throw new Error("Quote returned zero \u2014 pool may have no liquidity");
|
|
580
|
+
const clampedSlippage = BigInt(Math.max(0, Math.min(1e4, Number(slippageBps))));
|
|
581
|
+
const amountOutMin = expectedOut - expectedOut * clampedSlippage / 10000n;
|
|
582
|
+
const deadline = Math.floor(Date.now() / 1e3) + 3600;
|
|
583
|
+
const path = {
|
|
584
|
+
pairBinSteps: [...quote.binSteps].map((b) => b.toString()),
|
|
585
|
+
versions: [...quote.versions].map((v) => Number(v)),
|
|
586
|
+
tokenPath: [...route]
|
|
587
|
+
};
|
|
588
|
+
const iface = new ethers2.Interface(LB_ROUTER_ABI);
|
|
589
|
+
const data = iface.encodeFunctionData("swapExactNATIVEForTokens", [amountOutMin, path, wallet, deadline]);
|
|
590
|
+
const decimals = await this.arenaToken.decimals();
|
|
591
|
+
return {
|
|
592
|
+
transactions: [{
|
|
593
|
+
to: ethers2.getAddress(LB_ROUTER),
|
|
594
|
+
data,
|
|
595
|
+
value: ethers2.toBeHex(amountIn, 32),
|
|
596
|
+
chainId: CHAIN_ID,
|
|
597
|
+
gasLimit: "500000",
|
|
598
|
+
description: `Buy ARENA with ${avaxAmount} AVAX (~${ethers2.formatUnits(expectedOut, decimals)} ARENA)`
|
|
599
|
+
}],
|
|
600
|
+
summary: `Swap ${avaxAmount} AVAX \u2192 ~${ethers2.formatUnits(expectedOut, decimals)} ARENA`
|
|
601
|
+
};
|
|
602
|
+
}
|
|
603
|
+
/** Build unsigned txs to sell ARENA for AVAX: [approve, swap] */
|
|
604
|
+
async buildSell(wallet, arenaAmount, slippageBps = DEFAULT_SLIPPAGE_BPS) {
|
|
605
|
+
const decimals = await this.arenaToken.decimals();
|
|
606
|
+
let sellAmount;
|
|
607
|
+
if (arenaAmount === "max") {
|
|
608
|
+
sellAmount = await this.arenaToken.balanceOf(wallet);
|
|
609
|
+
if (sellAmount === 0n) throw new Error("No ARENA balance to sell");
|
|
610
|
+
} else {
|
|
611
|
+
sellAmount = ethers2.parseUnits(arenaAmount, decimals);
|
|
612
|
+
}
|
|
613
|
+
const route = [ARENA_TOKEN, WAVAX];
|
|
614
|
+
const quote = await this.lbQuoter.findBestPathFromAmountIn(route, sellAmount);
|
|
615
|
+
const expectedOut = quote.amounts[quote.amounts.length - 1];
|
|
616
|
+
if (expectedOut === 0n) throw new Error("Quote returned zero \u2014 pool may have no liquidity");
|
|
617
|
+
const clampedSlippage = BigInt(Math.max(0, Math.min(1e4, Number(slippageBps))));
|
|
618
|
+
const amountOutMin = expectedOut - expectedOut * clampedSlippage / 10000n;
|
|
619
|
+
const deadline = Math.floor(Date.now() / 1e3) + 3600;
|
|
620
|
+
const path = {
|
|
621
|
+
pairBinSteps: [...quote.binSteps].map((b) => b.toString()),
|
|
622
|
+
versions: [...quote.versions].map((v) => Number(v)),
|
|
623
|
+
tokenPath: [...route]
|
|
624
|
+
};
|
|
625
|
+
const approveIface = new ethers2.Interface(ERC20_ABI);
|
|
626
|
+
const approveData = approveIface.encodeFunctionData("approve", [ethers2.getAddress(LB_ROUTER), sellAmount]);
|
|
627
|
+
const swapIface = new ethers2.Interface(LB_ROUTER_ABI);
|
|
628
|
+
const swapData = swapIface.encodeFunctionData("swapExactTokensForNATIVE", [sellAmount, amountOutMin, path, wallet, deadline]);
|
|
629
|
+
return {
|
|
630
|
+
transactions: [
|
|
631
|
+
{
|
|
632
|
+
to: ethers2.getAddress(ARENA_TOKEN),
|
|
633
|
+
data: approveData,
|
|
634
|
+
value: "0",
|
|
635
|
+
chainId: CHAIN_ID,
|
|
636
|
+
gasLimit: "60000",
|
|
637
|
+
description: `Approve ${ethers2.formatUnits(sellAmount, decimals)} ARENA for swap`
|
|
638
|
+
},
|
|
639
|
+
{
|
|
640
|
+
to: ethers2.getAddress(LB_ROUTER),
|
|
641
|
+
data: swapData,
|
|
642
|
+
value: "0",
|
|
643
|
+
chainId: CHAIN_ID,
|
|
644
|
+
gasLimit: "500000",
|
|
645
|
+
description: `Sell ${ethers2.formatUnits(sellAmount, decimals)} ARENA for ~${ethers2.formatEther(expectedOut)} AVAX`
|
|
646
|
+
}
|
|
647
|
+
]
|
|
648
|
+
};
|
|
649
|
+
}
|
|
650
|
+
};
|
|
651
|
+
|
|
652
|
+
// src/modules/staking.ts
|
|
653
|
+
import { ethers as ethers3 } from "ethers";
|
|
654
|
+
var StakingModule = class {
|
|
655
|
+
constructor(provider) {
|
|
656
|
+
this.provider = provider;
|
|
657
|
+
this.arenaToken = new ethers3.Contract(ethers3.getAddress(ARENA_TOKEN), ERC20_ABI, provider);
|
|
658
|
+
this.staking = new ethers3.Contract(ethers3.getAddress(ARENA_STAKING), ARENA_STAKING_ABI, provider);
|
|
659
|
+
}
|
|
660
|
+
arenaToken;
|
|
661
|
+
staking;
|
|
662
|
+
/** Get staking info — staked amount, pending rewards */
|
|
663
|
+
async getInfo(wallet) {
|
|
664
|
+
const decimals = await this.arenaToken.decimals();
|
|
665
|
+
const [stakedRaw] = await this.staking.getUserInfo(wallet, ethers3.getAddress(ARENA_TOKEN));
|
|
666
|
+
const pendingRaw = await this.staking.pendingReward(wallet, ethers3.getAddress(ARENA_TOKEN));
|
|
667
|
+
return {
|
|
668
|
+
staked: stakedRaw.toString(),
|
|
669
|
+
stakedFormatted: ethers3.formatUnits(stakedRaw, decimals),
|
|
670
|
+
rewards: pendingRaw.toString(),
|
|
671
|
+
rewardsFormatted: ethers3.formatUnits(pendingRaw, decimals)
|
|
672
|
+
};
|
|
673
|
+
}
|
|
674
|
+
/** Build txs to stake ARENA: [approve, deposit] */
|
|
675
|
+
async buildStake(wallet, amount) {
|
|
676
|
+
const decimals = await this.arenaToken.decimals();
|
|
677
|
+
let stakeAmount;
|
|
678
|
+
if (amount === "max") {
|
|
679
|
+
stakeAmount = await this.arenaToken.balanceOf(wallet);
|
|
680
|
+
} else {
|
|
681
|
+
stakeAmount = ethers3.parseUnits(amount, decimals);
|
|
682
|
+
}
|
|
683
|
+
const approveIface = new ethers3.Interface(ERC20_ABI);
|
|
684
|
+
const approveData = approveIface.encodeFunctionData("approve", [ethers3.getAddress(ARENA_STAKING), stakeAmount]);
|
|
685
|
+
const stakingIface = new ethers3.Interface(ARENA_STAKING_ABI);
|
|
686
|
+
const stakeData = stakingIface.encodeFunctionData("deposit", [stakeAmount]);
|
|
687
|
+
return {
|
|
688
|
+
transactions: [
|
|
689
|
+
{
|
|
690
|
+
to: ethers3.getAddress(ARENA_TOKEN),
|
|
691
|
+
data: approveData,
|
|
692
|
+
value: "0",
|
|
693
|
+
chainId: CHAIN_ID,
|
|
694
|
+
gasLimit: "60000",
|
|
695
|
+
description: `Approve ${ethers3.formatUnits(stakeAmount, decimals)} ARENA for staking`
|
|
696
|
+
},
|
|
697
|
+
{
|
|
698
|
+
to: ethers3.getAddress(ARENA_STAKING),
|
|
699
|
+
data: stakeData,
|
|
700
|
+
value: "0",
|
|
701
|
+
chainId: CHAIN_ID,
|
|
702
|
+
gasLimit: "300000",
|
|
703
|
+
description: `Stake ${ethers3.formatUnits(stakeAmount, decimals)} ARENA`
|
|
704
|
+
}
|
|
705
|
+
]
|
|
706
|
+
};
|
|
707
|
+
}
|
|
708
|
+
/** Build tx to unstake ARENA + claim rewards */
|
|
709
|
+
async buildUnstake(wallet, amount) {
|
|
710
|
+
const decimals = await this.arenaToken.decimals();
|
|
711
|
+
let withdrawAmount;
|
|
712
|
+
if (amount === "max") {
|
|
713
|
+
const [stakedRaw] = await this.staking.getUserInfo(wallet, ethers3.getAddress(ARENA_TOKEN));
|
|
714
|
+
withdrawAmount = stakedRaw;
|
|
715
|
+
} else {
|
|
716
|
+
withdrawAmount = ethers3.parseUnits(amount, decimals);
|
|
717
|
+
}
|
|
718
|
+
const iface = new ethers3.Interface(ARENA_STAKING_ABI);
|
|
719
|
+
const data = iface.encodeFunctionData("withdraw", [withdrawAmount]);
|
|
720
|
+
return {
|
|
721
|
+
transactions: [{
|
|
722
|
+
to: ethers3.getAddress(ARENA_STAKING),
|
|
723
|
+
data,
|
|
724
|
+
value: "0",
|
|
725
|
+
chainId: CHAIN_ID,
|
|
726
|
+
gasLimit: "300000",
|
|
727
|
+
description: `Unstake ${ethers3.formatUnits(withdrawAmount, decimals)} ARENA + claim rewards`
|
|
728
|
+
}]
|
|
729
|
+
};
|
|
730
|
+
}
|
|
731
|
+
/** Build buy-and-stake flow (3 txs): buy ARENA via LFJ, approve, stake */
|
|
732
|
+
async buildBuyAndStake(wallet, avaxAmount, slippageBps = DEFAULT_SLIPPAGE_BPS) {
|
|
733
|
+
const lbQuoter = new ethers3.Contract(ethers3.getAddress(LB_QUOTER), LB_QUOTER_ABI, this.provider);
|
|
734
|
+
const amountIn = ethers3.parseEther(avaxAmount);
|
|
735
|
+
const route = [WAVAX, ARENA_TOKEN];
|
|
736
|
+
const quote = await lbQuoter.findBestPathFromAmountIn(route, amountIn);
|
|
737
|
+
const expectedOut = quote.amounts[quote.amounts.length - 1];
|
|
738
|
+
const clampedSlippage = BigInt(Math.max(0, Math.min(1e4, Number(slippageBps))));
|
|
739
|
+
const amountOutMin = expectedOut - expectedOut * clampedSlippage / 10000n;
|
|
740
|
+
const deadline = Math.floor(Date.now() / 1e3) + 3600;
|
|
741
|
+
const decimals = await this.arenaToken.decimals();
|
|
742
|
+
const path = {
|
|
743
|
+
pairBinSteps: [...quote.binSteps].map((b) => b.toString()),
|
|
744
|
+
versions: [...quote.versions].map((v) => Number(v)),
|
|
745
|
+
tokenPath: [...route]
|
|
746
|
+
};
|
|
747
|
+
const routerIface = new ethers3.Interface(LB_ROUTER_ABI);
|
|
748
|
+
const buyData = routerIface.encodeFunctionData("swapExactNATIVEForTokens", [amountOutMin, path, wallet, deadline]);
|
|
749
|
+
const erc20Iface = new ethers3.Interface(ERC20_ABI);
|
|
750
|
+
const approveData = erc20Iface.encodeFunctionData("approve", [ethers3.getAddress(ARENA_STAKING), ethers3.MaxUint256]);
|
|
751
|
+
const stakingIface = new ethers3.Interface(ARENA_STAKING_ABI);
|
|
752
|
+
const stakeData = stakingIface.encodeFunctionData("deposit", [expectedOut]);
|
|
753
|
+
return {
|
|
754
|
+
transactions: [
|
|
755
|
+
{
|
|
756
|
+
to: ethers3.getAddress(LB_ROUTER),
|
|
757
|
+
data: buyData,
|
|
758
|
+
value: ethers3.toBeHex(amountIn, 32),
|
|
759
|
+
chainId: CHAIN_ID,
|
|
760
|
+
gasLimit: "500000",
|
|
761
|
+
description: `Step 1/3: Buy ~${ethers3.formatUnits(expectedOut, decimals)} ARENA with ${avaxAmount} AVAX`
|
|
762
|
+
},
|
|
763
|
+
{
|
|
764
|
+
to: ethers3.getAddress(ARENA_TOKEN),
|
|
765
|
+
data: approveData,
|
|
766
|
+
value: "0",
|
|
767
|
+
chainId: CHAIN_ID,
|
|
768
|
+
gasLimit: "60000",
|
|
769
|
+
description: `Step 2/3: Approve ARENA for staking`
|
|
770
|
+
},
|
|
771
|
+
{
|
|
772
|
+
to: ethers3.getAddress(ARENA_STAKING),
|
|
773
|
+
data: stakeData,
|
|
774
|
+
value: "0",
|
|
775
|
+
chainId: CHAIN_ID,
|
|
776
|
+
gasLimit: "300000",
|
|
777
|
+
description: `Step 3/3: Stake ~${ethers3.formatUnits(expectedOut, decimals)} ARENA`
|
|
778
|
+
}
|
|
779
|
+
]
|
|
780
|
+
};
|
|
781
|
+
}
|
|
782
|
+
};
|
|
783
|
+
|
|
784
|
+
// src/modules/launchpad.ts
|
|
785
|
+
import { ethers as ethers4 } from "ethers";
|
|
786
|
+
var LaunchpadModule = class {
|
|
787
|
+
constructor(provider) {
|
|
788
|
+
this.provider = provider;
|
|
789
|
+
this.launchContract = new ethers4.Contract(ethers4.getAddress(LAUNCH_CONTRACT), LAUNCH_CONTRACT_ABI, provider);
|
|
790
|
+
this.tokenManager = new ethers4.Contract(ethers4.getAddress(TOKEN_MANAGER), TOKEN_MANAGER_ABI, provider);
|
|
791
|
+
this.avaxHelper = new ethers4.Contract(ethers4.getAddress(AVAX_HELPER), AVAX_HELPER_ABI, provider);
|
|
792
|
+
}
|
|
793
|
+
launchContract;
|
|
794
|
+
tokenManager;
|
|
795
|
+
avaxHelper;
|
|
796
|
+
isArenaPaired(tokenId) {
|
|
797
|
+
return BigInt(tokenId) >= ARENA_PAIRED_THRESHOLD;
|
|
798
|
+
}
|
|
799
|
+
getContract(tokenId) {
|
|
800
|
+
return this.isArenaPaired(tokenId) ? this.tokenManager : this.launchContract;
|
|
801
|
+
}
|
|
802
|
+
/** Get platform overview — total tokens, fees, contract addresses */
|
|
803
|
+
async getOverview() {
|
|
804
|
+
const [avaxLatest, arenaLatest, protocolFeeAvax, protocolFeeArena] = await Promise.all([
|
|
805
|
+
this.launchContract.tokenIdentifier(),
|
|
806
|
+
this.tokenManager.tokenIdentifier(),
|
|
807
|
+
this.launchContract.protocolFeeBasisPoint(),
|
|
808
|
+
this.tokenManager.protocolFeeBasisPoint()
|
|
809
|
+
]);
|
|
810
|
+
return {
|
|
811
|
+
totalAvaxPairedTokens: (avaxLatest - 1n).toString(),
|
|
812
|
+
totalArenaPairedTokens: (arenaLatest - ARENA_PAIRED_THRESHOLD).toString(),
|
|
813
|
+
totalTokens: (avaxLatest - 1n + (arenaLatest - ARENA_PAIRED_THRESHOLD)).toString(),
|
|
814
|
+
protocolFeeBps: { avaxPaired: protocolFeeAvax.toString(), arenaPaired: protocolFeeArena.toString() },
|
|
815
|
+
contracts: { launchContract: LAUNCH_CONTRACT, tokenManager: TOKEN_MANAGER, avaxHelper: AVAX_HELPER }
|
|
816
|
+
};
|
|
817
|
+
}
|
|
818
|
+
/** Get full token info by ID */
|
|
819
|
+
async getToken(tokenId) {
|
|
820
|
+
const contract = this.getContract(tokenId);
|
|
821
|
+
const id = BigInt(tokenId);
|
|
822
|
+
const [params, supply, maxForSale] = await Promise.all([
|
|
823
|
+
contract.getTokenParameters(id),
|
|
824
|
+
contract.tokenSupply(id),
|
|
825
|
+
contract.getMaxTokensForSale(id)
|
|
826
|
+
]);
|
|
827
|
+
const tokenAddress = params.tokenContractAddress;
|
|
828
|
+
if (tokenAddress === ethers4.ZeroAddress) throw new Error(`Token ID ${tokenId} not found`);
|
|
829
|
+
const token = new ethers4.Contract(tokenAddress, ERC20_ABI, this.provider);
|
|
830
|
+
let name = "Unknown", symbol = "UNKNOWN";
|
|
831
|
+
try {
|
|
832
|
+
[name, symbol] = await Promise.all([token.name(), token.symbol()]);
|
|
833
|
+
} catch {
|
|
834
|
+
}
|
|
835
|
+
let priceAvax = "0";
|
|
836
|
+
if (!params.lpDeployed) {
|
|
837
|
+
try {
|
|
838
|
+
const cost = await contract.calculateCostWithFees(1n, id);
|
|
839
|
+
priceAvax = ethers4.formatEther(cost);
|
|
840
|
+
} catch {
|
|
841
|
+
}
|
|
842
|
+
}
|
|
843
|
+
const salePerc = BigInt(params.salePercentage);
|
|
844
|
+
const saleAllocation = supply * salePerc / 100n;
|
|
845
|
+
const amountSold = saleAllocation > maxForSale ? saleAllocation - maxForSale : 0n;
|
|
846
|
+
const graduationProgress = saleAllocation > 0n ? Number(amountSold * 10000n / saleAllocation) / 100 : 0;
|
|
847
|
+
return {
|
|
848
|
+
tokenId,
|
|
849
|
+
type: this.isArenaPaired(tokenId) ? "ARENA-paired" : "AVAX-paired",
|
|
850
|
+
name,
|
|
851
|
+
symbol,
|
|
852
|
+
tokenAddress,
|
|
853
|
+
creator: params.creatorAddress,
|
|
854
|
+
priceAvax,
|
|
855
|
+
graduationProgress: `${graduationProgress.toFixed(2)}%`,
|
|
856
|
+
graduated: params.lpDeployed,
|
|
857
|
+
amountSold: ethers4.formatUnits(amountSold, 18),
|
|
858
|
+
totalSupply: ethers4.formatUnits(supply, 18),
|
|
859
|
+
remainingForSale: ethers4.formatUnits(maxForSale, 18)
|
|
860
|
+
};
|
|
861
|
+
}
|
|
862
|
+
/** Get a buy or sell quote */
|
|
863
|
+
async quote(tokenId, side, amount) {
|
|
864
|
+
const contract = this.getContract(tokenId);
|
|
865
|
+
const id = BigInt(tokenId);
|
|
866
|
+
if (side === "buy") {
|
|
867
|
+
const avaxWei = ethers4.parseEther(amount);
|
|
868
|
+
if (!this.isArenaPaired(tokenId)) {
|
|
869
|
+
const tokenAmountWei2 = await this.binarySearchTokenAmount(avaxWei, id);
|
|
870
|
+
if (tokenAmountWei2 === 0n) return { tokenId, side, avaxIn: amount, tokensOut: "0", note: "Insufficient liquidity" };
|
|
871
|
+
const exactCost = await this.launchContract.calculateCostWithFees(tokenAmountWei2 / GRANULARITY_SCALER, id);
|
|
872
|
+
return { tokenId, side, avaxIn: ethers4.formatEther(exactCost), tokensOut: ethers4.formatUnits(tokenAmountWei2, 18) };
|
|
873
|
+
}
|
|
874
|
+
return { tokenId, side, avaxIn: amount, tokensOut: "determined at execution (ARENA-paired)" };
|
|
875
|
+
}
|
|
876
|
+
const tokenAmountWei = ethers4.parseUnits(amount, 18);
|
|
877
|
+
const reward = await contract.calculateRewardWithFees(tokenAmountWei, id);
|
|
878
|
+
return {
|
|
879
|
+
tokenId,
|
|
880
|
+
side,
|
|
881
|
+
tokenAmount: amount,
|
|
882
|
+
rewardAvax: this.isArenaPaired(tokenId) ? void 0 : ethers4.formatEther(reward),
|
|
883
|
+
rewardArena: this.isArenaPaired(tokenId) ? ethers4.formatUnits(reward, 18) : void 0
|
|
884
|
+
};
|
|
885
|
+
}
|
|
886
|
+
/** Get recent token launches */
|
|
887
|
+
async getRecent(count = 10) {
|
|
888
|
+
const results = [];
|
|
889
|
+
const fetchToken = async (id, contract, pairType) => {
|
|
890
|
+
try {
|
|
891
|
+
const params = await contract.getTokenParameters(id);
|
|
892
|
+
if (params.tokenContractAddress === ethers4.ZeroAddress) return null;
|
|
893
|
+
const token = new ethers4.Contract(params.tokenContractAddress, ERC20_ABI, this.provider);
|
|
894
|
+
let name = "Unknown", symbol = "UNKNOWN";
|
|
895
|
+
try {
|
|
896
|
+
[name, symbol] = await Promise.all([token.name(), token.symbol()]);
|
|
897
|
+
} catch {
|
|
898
|
+
}
|
|
899
|
+
return { tokenId: id.toString(), type: pairType, name, symbol, tokenAddress: params.tokenContractAddress, graduated: params.lpDeployed };
|
|
900
|
+
} catch {
|
|
901
|
+
return null;
|
|
902
|
+
}
|
|
903
|
+
};
|
|
904
|
+
const latestAvax = await this.launchContract.tokenIdentifier();
|
|
905
|
+
const avaxPromises = [];
|
|
906
|
+
for (let i = 0; i < Math.ceil(count / 2) && latestAvax - BigInt(i) > 0n; i++) {
|
|
907
|
+
avaxPromises.push(fetchToken(latestAvax - BigInt(i) - 1n, this.launchContract, "AVAX-paired"));
|
|
908
|
+
}
|
|
909
|
+
const latestArena = await this.tokenManager.tokenIdentifier();
|
|
910
|
+
const arenaPromises = [];
|
|
911
|
+
for (let i = 0; i < Math.ceil(count / 2) && latestArena - BigInt(i) >= ARENA_PAIRED_THRESHOLD; i++) {
|
|
912
|
+
arenaPromises.push(fetchToken(latestArena - BigInt(i) - 1n, this.tokenManager, "ARENA-paired"));
|
|
913
|
+
}
|
|
914
|
+
results.push(...(await Promise.all([...avaxPromises, ...arenaPromises])).filter(Boolean));
|
|
915
|
+
return { count: results.length, tokens: results.slice(0, count) };
|
|
916
|
+
}
|
|
917
|
+
/** Build unsigned tx to buy a launchpad token */
|
|
918
|
+
async buildBuy(wallet, tokenId, avax, slippageBps = DEFAULT_SLIPPAGE_BPS) {
|
|
919
|
+
const id = BigInt(tokenId);
|
|
920
|
+
const avaxWei = ethers4.parseEther(avax);
|
|
921
|
+
const contract = this.getContract(tokenId);
|
|
922
|
+
const params = await contract.getTokenParameters(id);
|
|
923
|
+
if (params.lpDeployed) throw new Error("Token graduated to DEX \u2014 use dex.buildSwap() instead");
|
|
924
|
+
if (!this.isArenaPaired(tokenId)) {
|
|
925
|
+
const tokenAmountWei = await this.binarySearchTokenAmount(avaxWei, id);
|
|
926
|
+
if (tokenAmountWei === 0n) throw new Error("Cannot calculate buy amount \u2014 token may be sold out");
|
|
927
|
+
const iface2 = new ethers4.Interface(LAUNCH_CONTRACT_ABI);
|
|
928
|
+
const data2 = iface2.encodeFunctionData("buyAndCreateLpIfPossible", [tokenAmountWei, id]);
|
|
929
|
+
return { transactions: [{ to: ethers4.getAddress(LAUNCH_CONTRACT), data: data2, value: ethers4.toBeHex(avaxWei, 32), chainId: CHAIN_ID, gasLimit: "500000", description: `Buy ~${ethers4.formatUnits(tokenAmountWei, 18)} tokens (ID ${tokenId})` }] };
|
|
930
|
+
}
|
|
931
|
+
const iface = new ethers4.Interface(AVAX_HELPER_ABI);
|
|
932
|
+
const data = iface.encodeFunctionData("buyAndCreateLpIfPossibleWithAvax", [id, 0n]);
|
|
933
|
+
return { transactions: [{ to: ethers4.getAddress(AVAX_HELPER), data, value: ethers4.toBeHex(avaxWei, 32), chainId: CHAIN_ID, gasLimit: "500000", description: `Buy tokens (ID ${tokenId}) with ${avax} AVAX` }] };
|
|
934
|
+
}
|
|
935
|
+
/** Build unsigned txs to sell a launchpad token: [approve, sell] */
|
|
936
|
+
async buildSell(wallet, tokenId, amount, slippageBps = DEFAULT_SLIPPAGE_BPS) {
|
|
937
|
+
const id = BigInt(tokenId);
|
|
938
|
+
const contract = this.getContract(tokenId);
|
|
939
|
+
const params = await contract.getTokenParameters(id);
|
|
940
|
+
if (params.lpDeployed) throw new Error("Token graduated to DEX \u2014 use dex.buildSwap() instead");
|
|
941
|
+
const tokenAddress = params.tokenContractAddress;
|
|
942
|
+
if (tokenAddress === ethers4.ZeroAddress) throw new Error(`Token ID ${tokenId} not found`);
|
|
943
|
+
const token = new ethers4.Contract(tokenAddress, ERC20_ABI, this.provider);
|
|
944
|
+
let sellAmount;
|
|
945
|
+
if (amount === "max") {
|
|
946
|
+
sellAmount = await token.balanceOf(wallet);
|
|
947
|
+
} else {
|
|
948
|
+
sellAmount = ethers4.parseUnits(amount, 18);
|
|
949
|
+
}
|
|
950
|
+
if (sellAmount === 0n) throw new Error("Zero balance");
|
|
951
|
+
if (!this.isArenaPaired(tokenId)) {
|
|
952
|
+
sellAmount = sellAmount / GRANULARITY_SCALER * GRANULARITY_SCALER;
|
|
953
|
+
if (sellAmount === 0n) throw new Error("Balance too small");
|
|
954
|
+
}
|
|
955
|
+
const spender = this.isArenaPaired(tokenId) ? ethers4.getAddress(AVAX_HELPER) : ethers4.getAddress(LAUNCH_CONTRACT);
|
|
956
|
+
const erc20Iface = new ethers4.Interface(ERC20_ABI);
|
|
957
|
+
const approveTx = { to: tokenAddress, data: erc20Iface.encodeFunctionData("approve", [spender, ethers4.MaxUint256]), value: "0", chainId: CHAIN_ID, gasLimit: "60000", description: "Approve token for selling" };
|
|
958
|
+
let sellData;
|
|
959
|
+
let sellTo;
|
|
960
|
+
if (!this.isArenaPaired(tokenId)) {
|
|
961
|
+
sellData = new ethers4.Interface(LAUNCH_CONTRACT_ABI).encodeFunctionData("sell", [sellAmount, id]);
|
|
962
|
+
sellTo = ethers4.getAddress(LAUNCH_CONTRACT);
|
|
963
|
+
} else {
|
|
964
|
+
let minOut = 0n;
|
|
965
|
+
try {
|
|
966
|
+
const reward = await contract.calculateRewardWithFees(sellAmount, id);
|
|
967
|
+
minOut = reward - reward * BigInt(slippageBps) / 10000n;
|
|
968
|
+
} catch {
|
|
969
|
+
}
|
|
970
|
+
sellData = new ethers4.Interface(AVAX_HELPER_ABI).encodeFunctionData("sellToAvax", [id, sellAmount, minOut]);
|
|
971
|
+
sellTo = ethers4.getAddress(AVAX_HELPER);
|
|
972
|
+
}
|
|
973
|
+
return { transactions: [approveTx, { to: sellTo, data: sellData, value: "0", chainId: CHAIN_ID, gasLimit: "500000", description: `Sell ${ethers4.formatUnits(sellAmount, 18)} tokens (ID ${tokenId})` }] };
|
|
974
|
+
}
|
|
975
|
+
/** Binary search for max tokens purchasable with given AVAX */
|
|
976
|
+
async binarySearchTokenAmount(avaxBudgetWei, tokenId) {
|
|
977
|
+
let maxForSale;
|
|
978
|
+
try {
|
|
979
|
+
maxForSale = await this.launchContract.getMaxTokensForSale(tokenId);
|
|
980
|
+
} catch {
|
|
981
|
+
maxForSale = 100000000n * GRANULARITY_SCALER;
|
|
982
|
+
}
|
|
983
|
+
const maxWhole = maxForSale / GRANULARITY_SCALER;
|
|
984
|
+
if (maxWhole <= 0n) return 0n;
|
|
985
|
+
let lo = 1n;
|
|
986
|
+
let hi = maxWhole;
|
|
987
|
+
let best = 0n;
|
|
988
|
+
for (let i = 0; i < 30 && lo <= hi; i++) {
|
|
989
|
+
const mid = (lo + hi) / 2n;
|
|
990
|
+
try {
|
|
991
|
+
const cost = await this.launchContract.calculateCostWithFees(mid, tokenId);
|
|
992
|
+
if (cost <= avaxBudgetWei) {
|
|
993
|
+
best = mid;
|
|
994
|
+
lo = mid + 1n;
|
|
995
|
+
} else {
|
|
996
|
+
hi = mid - 1n;
|
|
997
|
+
}
|
|
998
|
+
} catch {
|
|
999
|
+
hi = mid - 1n;
|
|
1000
|
+
}
|
|
1001
|
+
}
|
|
1002
|
+
return best > 0n ? best * GRANULARITY_SCALER : 0n;
|
|
1003
|
+
}
|
|
1004
|
+
};
|
|
1005
|
+
|
|
1006
|
+
// src/modules/dex.ts
|
|
1007
|
+
import { ethers as ethers5 } from "ethers";
|
|
1008
|
+
var KNOWN_TOKENS = {
|
|
1009
|
+
AVAX: WAVAX,
|
|
1010
|
+
WAVAX,
|
|
1011
|
+
USDC: "0xB97EF9Ef8734C71904D8002F8b6Bc66Dd9c48a6E",
|
|
1012
|
+
"USDC.e": "0xA7D7079b0FEaD91F3e65f86E8915Cb59c1a4C664",
|
|
1013
|
+
USDT: "0x9702230A8Ea53601f5cD2dc00fDBc13d4dF4A8c7",
|
|
1014
|
+
"USDT.e": "0xc7198437980c041c805A1EDcbA50c1Ce5db95118",
|
|
1015
|
+
JOE: "0x6e84a6216eA6dACC71eE8E6b0a5B7322EEbC0fDd",
|
|
1016
|
+
ARENA: "0xB8d7710f7d8349A506b75dD184F05777c82dAd0C",
|
|
1017
|
+
"BTC.b": "0x152b9d0FdC40C096DE20232Db5A0dF62B48dEeEB",
|
|
1018
|
+
"WETH.e": "0x49D5c2BdFfac6CE2BFdB6640F4F80f226bc10bAB",
|
|
1019
|
+
GMX: "0x62edc0692BD897D2295872a9FFCac5425011c661",
|
|
1020
|
+
sAVAX: "0x2b2C81e08f1Af8835a78Bb2A90AE924ACE0eA4bE"
|
|
1021
|
+
};
|
|
1022
|
+
var DexModule = class {
|
|
1023
|
+
constructor(provider) {
|
|
1024
|
+
this.provider = provider;
|
|
1025
|
+
this.lbQuoter = new ethers5.Contract(ethers5.getAddress(LB_QUOTER), LB_QUOTER_ABI, provider);
|
|
1026
|
+
}
|
|
1027
|
+
lbQuoter;
|
|
1028
|
+
/** Resolve token symbol or address to a checksummed address */
|
|
1029
|
+
resolveToken(tokenOrAddress) {
|
|
1030
|
+
const upper = tokenOrAddress.toUpperCase();
|
|
1031
|
+
if (KNOWN_TOKENS[upper]) return ethers5.getAddress(KNOWN_TOKENS[upper]);
|
|
1032
|
+
if (KNOWN_TOKENS[tokenOrAddress]) return ethers5.getAddress(KNOWN_TOKENS[tokenOrAddress]);
|
|
1033
|
+
if (tokenOrAddress.startsWith("0x")) return ethers5.getAddress(tokenOrAddress);
|
|
1034
|
+
throw new Error(`Unknown token: ${tokenOrAddress}. Use a symbol (AVAX, USDC, JOE, ARENA) or a 0x contract address.`);
|
|
1035
|
+
}
|
|
1036
|
+
/** List known tokens */
|
|
1037
|
+
getTokens() {
|
|
1038
|
+
const tokens = Object.entries(KNOWN_TOKENS).map(([symbol, address]) => ({ symbol, address }));
|
|
1039
|
+
return { tokens, note: "You can also pass any ERC-20 contract address directly." };
|
|
1040
|
+
}
|
|
1041
|
+
/** Look up any ERC-20 token by address */
|
|
1042
|
+
async getTokenInfo(address) {
|
|
1043
|
+
const addr = ethers5.getAddress(address);
|
|
1044
|
+
const token = new ethers5.Contract(addr, ERC20_ABI, this.provider);
|
|
1045
|
+
const [name, symbol, decimals] = await Promise.all([token.name(), token.symbol(), token.decimals()]);
|
|
1046
|
+
return { address: addr, symbol, name, decimals: Number(decimals) };
|
|
1047
|
+
}
|
|
1048
|
+
/** Get balance of any token */
|
|
1049
|
+
async getBalance(wallet, tokenOrAddress) {
|
|
1050
|
+
const address = this.resolveToken(tokenOrAddress);
|
|
1051
|
+
if (address.toLowerCase() === WAVAX.toLowerCase() && tokenOrAddress.toUpperCase() === "AVAX") {
|
|
1052
|
+
const balance2 = await this.provider.getBalance(wallet);
|
|
1053
|
+
return { wallet, token: "AVAX", balance: balance2.toString(), formatted: ethers5.formatEther(balance2), symbol: "AVAX" };
|
|
1054
|
+
}
|
|
1055
|
+
const token = new ethers5.Contract(address, ERC20_ABI, this.provider);
|
|
1056
|
+
const [balance, symbol, decimals] = await Promise.all([token.balanceOf(wallet), token.symbol(), token.decimals()]);
|
|
1057
|
+
return { wallet, token: address, balance: balance.toString(), formatted: ethers5.formatUnits(balance, decimals), symbol };
|
|
1058
|
+
}
|
|
1059
|
+
/** Quote a swap between any two tokens */
|
|
1060
|
+
async quote(from, to, amount) {
|
|
1061
|
+
const fromAddr = this.resolveToken(from);
|
|
1062
|
+
const toAddr = this.resolveToken(to);
|
|
1063
|
+
const fromToken = new ethers5.Contract(fromAddr, ERC20_ABI, this.provider);
|
|
1064
|
+
const decimals = fromAddr.toLowerCase() === WAVAX.toLowerCase() ? 18 : Number(await fromToken.decimals());
|
|
1065
|
+
const amountIn = ethers5.parseUnits(amount, decimals);
|
|
1066
|
+
const route = [fromAddr, toAddr];
|
|
1067
|
+
const quoteResult = await this.lbQuoter.findBestPathFromAmountIn(route, amountIn);
|
|
1068
|
+
const amountOut = quoteResult.amounts[quoteResult.amounts.length - 1];
|
|
1069
|
+
const toToken = new ethers5.Contract(toAddr, ERC20_ABI, this.provider);
|
|
1070
|
+
const toDecimals = toAddr.toLowerCase() === WAVAX.toLowerCase() ? 18 : Number(await toToken.decimals());
|
|
1071
|
+
const outFormatted = ethers5.formatUnits(amountOut, toDecimals);
|
|
1072
|
+
return {
|
|
1073
|
+
from,
|
|
1074
|
+
to,
|
|
1075
|
+
amountIn: amount,
|
|
1076
|
+
amountOut: outFormatted,
|
|
1077
|
+
rate: (parseFloat(outFormatted) / parseFloat(amount)).toFixed(6),
|
|
1078
|
+
path: route
|
|
1079
|
+
};
|
|
1080
|
+
}
|
|
1081
|
+
/** Build swap transactions (1 tx for AVAX→token, 2 txs for token→token with approve) */
|
|
1082
|
+
async buildSwap(wallet, from, to, amount, slippageBps = DEFAULT_SLIPPAGE_BPS) {
|
|
1083
|
+
const fromAddr = this.resolveToken(from);
|
|
1084
|
+
const toAddr = this.resolveToken(to);
|
|
1085
|
+
const isFromNative = from.toUpperCase() === "AVAX";
|
|
1086
|
+
const isToNative = to.toUpperCase() === "AVAX";
|
|
1087
|
+
const fromToken = new ethers5.Contract(fromAddr, ERC20_ABI, this.provider);
|
|
1088
|
+
const fromDecimals = isFromNative ? 18 : Number(await fromToken.decimals());
|
|
1089
|
+
let amountIn;
|
|
1090
|
+
if (amount === "max" && !isFromNative) {
|
|
1091
|
+
amountIn = await fromToken.balanceOf(wallet);
|
|
1092
|
+
if (amountIn === 0n) throw new Error("No balance to swap");
|
|
1093
|
+
} else {
|
|
1094
|
+
amountIn = ethers5.parseUnits(amount, fromDecimals);
|
|
1095
|
+
}
|
|
1096
|
+
const route = [fromAddr, toAddr];
|
|
1097
|
+
const quoteResult = await this.lbQuoter.findBestPathFromAmountIn(route, amountIn);
|
|
1098
|
+
const expectedOut = quoteResult.amounts[quoteResult.amounts.length - 1];
|
|
1099
|
+
if (expectedOut === 0n) throw new Error("Quote returned zero \u2014 no liquidity for this pair");
|
|
1100
|
+
const clampedSlippage = BigInt(Math.max(0, Math.min(1e4, Number(slippageBps))));
|
|
1101
|
+
const amountOutMin = expectedOut - expectedOut * clampedSlippage / 10000n;
|
|
1102
|
+
const deadline = Math.floor(Date.now() / 1e3) + 3600;
|
|
1103
|
+
const path = {
|
|
1104
|
+
pairBinSteps: [...quoteResult.binSteps].map((b) => b.toString()),
|
|
1105
|
+
versions: [...quoteResult.versions].map((v) => Number(v)),
|
|
1106
|
+
tokenPath: [...route]
|
|
1107
|
+
};
|
|
1108
|
+
const txs = [];
|
|
1109
|
+
const routerIface = new ethers5.Interface(LB_ROUTER_ABI);
|
|
1110
|
+
if (isFromNative) {
|
|
1111
|
+
const data = routerIface.encodeFunctionData("swapExactNATIVEForTokens", [amountOutMin, path, wallet, deadline]);
|
|
1112
|
+
txs.push({ to: ethers5.getAddress(LB_ROUTER), data, value: ethers5.toBeHex(amountIn, 32), chainId: CHAIN_ID, gasLimit: "500000", description: `Swap ${amount} AVAX \u2192 ${to}` });
|
|
1113
|
+
} else if (isToNative) {
|
|
1114
|
+
const erc20Iface = new ethers5.Interface(ERC20_ABI);
|
|
1115
|
+
txs.push({
|
|
1116
|
+
to: fromAddr,
|
|
1117
|
+
data: erc20Iface.encodeFunctionData("approve", [ethers5.getAddress(LB_ROUTER), amountIn]),
|
|
1118
|
+
value: "0",
|
|
1119
|
+
chainId: CHAIN_ID,
|
|
1120
|
+
gasLimit: "60000",
|
|
1121
|
+
description: `Approve ${from} for swap`
|
|
1122
|
+
});
|
|
1123
|
+
const data = routerIface.encodeFunctionData("swapExactTokensForNATIVE", [amountIn, amountOutMin, path, wallet, deadline]);
|
|
1124
|
+
txs.push({ to: ethers5.getAddress(LB_ROUTER), data, value: "0", chainId: CHAIN_ID, gasLimit: "500000", description: `Swap ${from} \u2192 AVAX` });
|
|
1125
|
+
} else {
|
|
1126
|
+
const erc20Iface = new ethers5.Interface(ERC20_ABI);
|
|
1127
|
+
txs.push({
|
|
1128
|
+
to: fromAddr,
|
|
1129
|
+
data: erc20Iface.encodeFunctionData("approve", [ethers5.getAddress(LB_ROUTER), amountIn]),
|
|
1130
|
+
value: "0",
|
|
1131
|
+
chainId: CHAIN_ID,
|
|
1132
|
+
gasLimit: "60000",
|
|
1133
|
+
description: `Approve ${from} for swap`
|
|
1134
|
+
});
|
|
1135
|
+
throw new Error("Direct token\u2192token swaps not yet supported. Route through AVAX: swap TOKEN\u2192AVAX, then AVAX\u2192TOKEN.");
|
|
1136
|
+
}
|
|
1137
|
+
const toToken = new ethers5.Contract(toAddr, ERC20_ABI, this.provider);
|
|
1138
|
+
const toDecimals = isToNative ? 18 : Number(await toToken.decimals());
|
|
1139
|
+
return { transactions: txs, summary: `Swap ${amount} ${from} \u2192 ~${ethers5.formatUnits(expectedOut, toDecimals)} ${to}` };
|
|
1140
|
+
}
|
|
1141
|
+
};
|
|
1142
|
+
|
|
1143
|
+
// src/modules/perps.ts
|
|
1144
|
+
var PerpsModule = class {
|
|
1145
|
+
constructor(arenaApiKey) {
|
|
1146
|
+
this.arenaApiKey = arenaApiKey;
|
|
1147
|
+
}
|
|
1148
|
+
setArenaApiKey(key) {
|
|
1149
|
+
this.arenaApiKey = key;
|
|
1150
|
+
}
|
|
1151
|
+
async arenaRequest(method, path, body, query) {
|
|
1152
|
+
if (!this.arenaApiKey) throw new Error("Arena API key required for perps. Pass arenaApiKey in config.");
|
|
1153
|
+
let url = `${ARENA_SOCIAL_API}${path}`;
|
|
1154
|
+
if (query) {
|
|
1155
|
+
const params = new URLSearchParams(query);
|
|
1156
|
+
url += `?${params.toString()}`;
|
|
1157
|
+
}
|
|
1158
|
+
const headers = { "x-api-key": this.arenaApiKey, "Content-Type": "application/json" };
|
|
1159
|
+
const res = await fetch(url, { method, headers, body: body ? JSON.stringify(body) : void 0 });
|
|
1160
|
+
const data = await res.json();
|
|
1161
|
+
if (!res.ok) {
|
|
1162
|
+
throw new Error(data.message || data.error || `Arena perps error ${res.status}`);
|
|
1163
|
+
}
|
|
1164
|
+
return data;
|
|
1165
|
+
}
|
|
1166
|
+
async hlPost(body) {
|
|
1167
|
+
const res = await fetch(HL_INFO, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) });
|
|
1168
|
+
if (!res.ok) throw new Error(`Hyperliquid API error ${res.status}`);
|
|
1169
|
+
return res.json();
|
|
1170
|
+
}
|
|
1171
|
+
// ── Setup (via Arena API) ──
|
|
1172
|
+
async register() {
|
|
1173
|
+
return this.arenaRequest("POST", "/agents/perp/register", { provider: "HYPERLIQUID" });
|
|
1174
|
+
}
|
|
1175
|
+
async getRegistrationStatus() {
|
|
1176
|
+
return this.arenaRequest("GET", "/agents/perp/registration-status", void 0, { provider: "HYPERLIQUID" });
|
|
1177
|
+
}
|
|
1178
|
+
async getWalletAddress() {
|
|
1179
|
+
return this.arenaRequest("GET", "/agents/perp/wallet-address", void 0, { provider: "HYPERLIQUID" });
|
|
1180
|
+
}
|
|
1181
|
+
// ── Auth Flow (via Arena API — EIP-712 signing) ──
|
|
1182
|
+
async getAuthStatus() {
|
|
1183
|
+
return this.arenaRequest("POST", "/agents/perp/auth/status", { provider: "HYPERLIQUID" });
|
|
1184
|
+
}
|
|
1185
|
+
async getAuthPayload(step, mainWalletAddress) {
|
|
1186
|
+
const body = { provider: "HYPERLIQUID" };
|
|
1187
|
+
if (mainWalletAddress) body.mainWalletAddress = mainWalletAddress;
|
|
1188
|
+
return this.arenaRequest("POST", `/agents/perp/auth/${step}/payload`, body);
|
|
1189
|
+
}
|
|
1190
|
+
async submitAuthSignature(step, signature, mainWalletAddress, metadata) {
|
|
1191
|
+
return this.arenaRequest("POST", `/agents/perp/auth/${step}/submit`, { provider: "HYPERLIQUID", mainWalletAddress, signature, metadata });
|
|
1192
|
+
}
|
|
1193
|
+
async enableHip3() {
|
|
1194
|
+
return this.arenaRequest("POST", "/agents/perp/auth/enable-hip3", { provider: "HYPERLIQUID" });
|
|
1195
|
+
}
|
|
1196
|
+
// ── Market Data (direct Hyperliquid) ──
|
|
1197
|
+
async getTradingPairs() {
|
|
1198
|
+
const raw = await this.hlPost({ type: "metaAndAssetCtxs" });
|
|
1199
|
+
const universe = raw[0].universe;
|
|
1200
|
+
const pairs = universe.map((m, i) => ({
|
|
1201
|
+
name: m.name,
|
|
1202
|
+
symbol: m.name,
|
|
1203
|
+
baseAssetId: i,
|
|
1204
|
+
sizePrecision: m.szDecimals,
|
|
1205
|
+
maxLeverage: m.maxLeverage,
|
|
1206
|
+
isDelisted: false,
|
|
1207
|
+
marginMode: m.onlyIsolated ? "isolated" : "cross"
|
|
1208
|
+
}));
|
|
1209
|
+
return { pairs, count: pairs.length };
|
|
1210
|
+
}
|
|
1211
|
+
// ── Trading (via Arena API — they hold the signing keys) ──
|
|
1212
|
+
async updateLeverage(symbol, leverage, leverageType = "cross") {
|
|
1213
|
+
return this.arenaRequest("POST", "/agents/perp/leverage/update", { provider: "HYPERLIQUID", symbol, leverage, leverageType });
|
|
1214
|
+
}
|
|
1215
|
+
async placeOrder(orders) {
|
|
1216
|
+
return this.arenaRequest("POST", "/agents/perp/orders/place", { provider: "HYPERLIQUID", orders });
|
|
1217
|
+
}
|
|
1218
|
+
async cancelOrders(cancels) {
|
|
1219
|
+
return this.arenaRequest("POST", "/agents/perp/orders/cancel", { provider: "HYPERLIQUID", cancels });
|
|
1220
|
+
}
|
|
1221
|
+
async closePosition(symbol, positionSide, size, currentPrice, closePercent = 100) {
|
|
1222
|
+
return this.arenaRequest("POST", "/agents/perp/orders/close-position", { provider: "HYPERLIQUID", symbol, positionSide, size, currentPrice, closePercent });
|
|
1223
|
+
}
|
|
1224
|
+
async getOrders() {
|
|
1225
|
+
return this.arenaRequest("GET", "/agents/perp/orders", void 0, { provider: "HYPERLIQUID" });
|
|
1226
|
+
}
|
|
1227
|
+
async getTradeExecutions() {
|
|
1228
|
+
return this.arenaRequest("GET", "/agents/perp/trade-executions", void 0, { provider: "HYPERLIQUID" });
|
|
1229
|
+
}
|
|
1230
|
+
// ── Positions (direct Hyperliquid — read-only, no auth needed) ──
|
|
1231
|
+
async getPositions(wallet) {
|
|
1232
|
+
return this.hlPost({ type: "clearinghouseState", user: wallet });
|
|
1233
|
+
}
|
|
1234
|
+
async getOpenOrders(wallet) {
|
|
1235
|
+
return this.hlPost({ type: "openOrders", user: wallet });
|
|
1236
|
+
}
|
|
1237
|
+
};
|
|
1238
|
+
|
|
1239
|
+
// src/modules/bridge.ts
|
|
1240
|
+
var BRIDGE_CHAINS = {
|
|
1241
|
+
ethereum: 1,
|
|
1242
|
+
base: 8453,
|
|
1243
|
+
arbitrum: 42161,
|
|
1244
|
+
optimism: 10,
|
|
1245
|
+
polygon: 137,
|
|
1246
|
+
bsc: 56,
|
|
1247
|
+
avalanche: 43114,
|
|
1248
|
+
fantom: 250,
|
|
1249
|
+
gnosis: 100,
|
|
1250
|
+
zksync: 324,
|
|
1251
|
+
linea: 59144,
|
|
1252
|
+
scroll: 534352,
|
|
1253
|
+
blast: 81457,
|
|
1254
|
+
mantle: 5e3
|
|
1255
|
+
};
|
|
1256
|
+
var USDC = {
|
|
1257
|
+
"1": "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48",
|
|
1258
|
+
"42161": "0xaf88d065e77c8cC2239327C5EDb3A432268e5831",
|
|
1259
|
+
"43114": "0xB97EF9Ef8734C71904D8002F8b6Bc66Dd9c48a6E",
|
|
1260
|
+
"8453": "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",
|
|
1261
|
+
"10": "0x0b2C639c533813f4Aa9D7837CAf62653d097Ff85",
|
|
1262
|
+
"137": "0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359"
|
|
1263
|
+
};
|
|
1264
|
+
var NATIVE_TOKEN = "0x0000000000000000000000000000000000000000";
|
|
1265
|
+
var BridgeModule = class {
|
|
1266
|
+
async getChains() {
|
|
1267
|
+
const res = await fetch(`${LIFI_API}/chains`);
|
|
1268
|
+
if (!res.ok) throw new Error(`Li.Fi chains failed (${res.status})`);
|
|
1269
|
+
const data = await res.json();
|
|
1270
|
+
return { chains: data.chains, count: data.chains.length };
|
|
1271
|
+
}
|
|
1272
|
+
async getTokens(chains) {
|
|
1273
|
+
const res = await fetch(`${LIFI_API}/tokens?chains=${chains}`);
|
|
1274
|
+
if (!res.ok) throw new Error(`Li.Fi tokens failed (${res.status})`);
|
|
1275
|
+
const data = await res.json();
|
|
1276
|
+
return { tokens: data.tokens };
|
|
1277
|
+
}
|
|
1278
|
+
async getToken(chainId, address) {
|
|
1279
|
+
const res = await fetch(`${LIFI_API}/token?chain=${chainId}&token=${address}`);
|
|
1280
|
+
if (!res.ok) throw new Error(`Li.Fi token failed (${res.status})`);
|
|
1281
|
+
return await res.json();
|
|
1282
|
+
}
|
|
1283
|
+
async getConnections(fromChainId, toChainId, fromToken, toToken) {
|
|
1284
|
+
const params = new URLSearchParams({ fromChain: fromChainId.toString(), toChain: toChainId.toString() });
|
|
1285
|
+
if (fromToken) params.set("fromToken", fromToken);
|
|
1286
|
+
if (toToken) params.set("toToken", toToken);
|
|
1287
|
+
const res = await fetch(`${LIFI_API}/connections?${params}`);
|
|
1288
|
+
if (!res.ok) throw new Error(`Li.Fi connections failed (${res.status})`);
|
|
1289
|
+
const data = await res.json();
|
|
1290
|
+
return { connections: data.connections };
|
|
1291
|
+
}
|
|
1292
|
+
async getQuote(fromChainId, toChainId, fromToken, toToken, fromAmount, fromAddress, toAddress, slippage, fromDecimals) {
|
|
1293
|
+
const decimals = fromDecimals ?? 18;
|
|
1294
|
+
const amountWei = this.parseUnits(fromAmount, decimals);
|
|
1295
|
+
const params = new URLSearchParams({
|
|
1296
|
+
fromChain: fromChainId.toString(),
|
|
1297
|
+
toChain: toChainId.toString(),
|
|
1298
|
+
fromToken,
|
|
1299
|
+
toToken,
|
|
1300
|
+
fromAmount: amountWei,
|
|
1301
|
+
fromAddress,
|
|
1302
|
+
toAddress: toAddress ?? fromAddress,
|
|
1303
|
+
slippage: (slippage ?? 0.03).toString(),
|
|
1304
|
+
integrator: "logiqical"
|
|
1305
|
+
});
|
|
1306
|
+
const res = await fetch(`${LIFI_API}/quote?${params}`);
|
|
1307
|
+
if (!res.ok) {
|
|
1308
|
+
const body = await res.text().catch(() => "");
|
|
1309
|
+
throw new Error(`Li.Fi quote failed (${res.status}): ${body}`);
|
|
1310
|
+
}
|
|
1311
|
+
return this.parseQuote(await res.json());
|
|
1312
|
+
}
|
|
1313
|
+
async getRoutes(fromChainId, toChainId, fromToken, toToken, fromAmount, fromAddress, toAddress, slippage, fromDecimals) {
|
|
1314
|
+
const decimals = fromDecimals ?? 18;
|
|
1315
|
+
const amountWei = this.parseUnits(fromAmount, decimals);
|
|
1316
|
+
const body = {
|
|
1317
|
+
fromChainId,
|
|
1318
|
+
toChainId,
|
|
1319
|
+
fromTokenAddress: fromToken,
|
|
1320
|
+
toTokenAddress: toToken,
|
|
1321
|
+
fromAmount: amountWei,
|
|
1322
|
+
fromAddress,
|
|
1323
|
+
toAddress: toAddress ?? fromAddress,
|
|
1324
|
+
options: { slippage: slippage ?? 0.03, integrator: "logiqical", order: "RECOMMENDED" }
|
|
1325
|
+
};
|
|
1326
|
+
const res = await fetch(`${LIFI_API}/advanced/routes`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) });
|
|
1327
|
+
if (!res.ok) {
|
|
1328
|
+
const b = await res.text().catch(() => "");
|
|
1329
|
+
throw new Error(`Li.Fi routes failed (${res.status}): ${b}`);
|
|
1330
|
+
}
|
|
1331
|
+
const data = await res.json();
|
|
1332
|
+
const routes = (data.routes ?? []).map((r) => this.parseRoute(r));
|
|
1333
|
+
return { routes, count: routes.length };
|
|
1334
|
+
}
|
|
1335
|
+
async getStatus(txHash, fromChainId, toChainId, bridge) {
|
|
1336
|
+
const params = new URLSearchParams({ txHash, fromChain: fromChainId.toString(), toChain: toChainId.toString() });
|
|
1337
|
+
if (bridge) params.set("bridge", bridge);
|
|
1338
|
+
const res = await fetch(`${LIFI_API}/status?${params}`);
|
|
1339
|
+
if (!res.ok) throw new Error(`Li.Fi status failed (${res.status})`);
|
|
1340
|
+
return await res.json();
|
|
1341
|
+
}
|
|
1342
|
+
getInfo() {
|
|
1343
|
+
return { chains: BRIDGE_CHAINS, usdc: USDC, nativeToken: NATIVE_TOKEN, tip: "Use 0x0000...0000 for native tokens" };
|
|
1344
|
+
}
|
|
1345
|
+
parseUnits(amount, decimals) {
|
|
1346
|
+
const parts = amount.split(".");
|
|
1347
|
+
const whole = parts[0] || "0";
|
|
1348
|
+
const frac = (parts[1] || "").slice(0, decimals).padEnd(decimals, "0");
|
|
1349
|
+
return (BigInt(whole) * BigInt(10) ** BigInt(decimals) + BigInt(frac)).toString();
|
|
1350
|
+
}
|
|
1351
|
+
parseQuote(data) {
|
|
1352
|
+
const action = data.action ?? {};
|
|
1353
|
+
const estimate = data.estimate ?? {};
|
|
1354
|
+
const txReq = data.transactionRequest;
|
|
1355
|
+
const quote = {
|
|
1356
|
+
id: data.id ?? data.tool ?? "unknown",
|
|
1357
|
+
fromChainId: action.fromChainId ?? 0,
|
|
1358
|
+
toChainId: action.toChainId ?? 0,
|
|
1359
|
+
fromToken: action.fromToken?.address ?? "",
|
|
1360
|
+
toToken: action.toToken?.address ?? "",
|
|
1361
|
+
fromAmount: action.fromAmount ?? "0",
|
|
1362
|
+
toAmount: estimate.toAmount ?? "0",
|
|
1363
|
+
estimatedGas: estimate.gasCosts?.[0]?.amountUSD ?? "0",
|
|
1364
|
+
estimatedTime: estimate.executionDuration ?? 0,
|
|
1365
|
+
tool: data.tool ?? "unknown"
|
|
1366
|
+
};
|
|
1367
|
+
if (txReq) {
|
|
1368
|
+
quote.transaction = { to: txReq.to, data: txReq.data, value: txReq.value ?? "0x0", gasLimit: txReq.gasLimit, chainId: txReq.chainId ?? action.fromChainId };
|
|
1369
|
+
}
|
|
1370
|
+
return quote;
|
|
1371
|
+
}
|
|
1372
|
+
parseRoute(route) {
|
|
1373
|
+
const steps = route.steps ?? [];
|
|
1374
|
+
const firstStep = steps[0] ?? {};
|
|
1375
|
+
const action = firstStep.action ?? {};
|
|
1376
|
+
const estimate = firstStep.estimate ?? {};
|
|
1377
|
+
return {
|
|
1378
|
+
id: route.id ?? "unknown",
|
|
1379
|
+
fromChainId: route.fromChainId ?? 0,
|
|
1380
|
+
toChainId: route.toChainId ?? 0,
|
|
1381
|
+
fromToken: route.fromToken?.address ?? "",
|
|
1382
|
+
toToken: route.toToken?.address ?? "",
|
|
1383
|
+
fromAmount: route.fromAmount ?? "0",
|
|
1384
|
+
toAmount: route.toAmount ?? "0",
|
|
1385
|
+
estimatedGas: route.gasCostUSD ?? "0",
|
|
1386
|
+
estimatedTime: steps.reduce((t, s) => t + (s.estimate?.executionDuration ?? 0), 0),
|
|
1387
|
+
tool: firstStep.tool ?? "unknown"
|
|
1388
|
+
};
|
|
1389
|
+
}
|
|
1390
|
+
};
|
|
1391
|
+
|
|
1392
|
+
// src/modules/tickets.ts
|
|
1393
|
+
import { ethers as ethers6 } from "ethers";
|
|
1394
|
+
var TicketsModule = class {
|
|
1395
|
+
constructor(provider) {
|
|
1396
|
+
this.provider = provider;
|
|
1397
|
+
this.contract = new ethers6.Contract(ethers6.getAddress(ARENA_SHARES_CONTRACT), SHARES_ABI, provider);
|
|
1398
|
+
}
|
|
1399
|
+
contract;
|
|
1400
|
+
async getBuyPrice(subject, amount = "1") {
|
|
1401
|
+
const fractionalAmount = this.ticketsToFractional(amount);
|
|
1402
|
+
const subjectAddr = ethers6.getAddress(subject);
|
|
1403
|
+
const [price, priceWithFee] = await Promise.all([
|
|
1404
|
+
this.contract.getBuyPriceForFractionalShares(subjectAddr, fractionalAmount),
|
|
1405
|
+
this.contract.getBuyPriceForFractionalSharesAfterFee(subjectAddr, fractionalAmount)
|
|
1406
|
+
]);
|
|
1407
|
+
return { price: ethers6.formatEther(price), priceWithFee: ethers6.formatEther(priceWithFee), tickets: amount, fractionalAmount };
|
|
1408
|
+
}
|
|
1409
|
+
async getSellPrice(subject, amount = "1") {
|
|
1410
|
+
const fractionalAmount = this.ticketsToFractional(amount);
|
|
1411
|
+
const subjectAddr = ethers6.getAddress(subject);
|
|
1412
|
+
const [price, priceAfterFee] = await Promise.all([
|
|
1413
|
+
this.contract.getSellPriceForFractionalShares(subjectAddr, fractionalAmount),
|
|
1414
|
+
this.contract.getSellPriceForFractionalSharesAfterFee(subjectAddr, fractionalAmount)
|
|
1415
|
+
]);
|
|
1416
|
+
return { price: ethers6.formatEther(price), priceAfterFee: ethers6.formatEther(priceAfterFee), tickets: amount, fractionalAmount };
|
|
1417
|
+
}
|
|
1418
|
+
async getBalance(subject, user) {
|
|
1419
|
+
const frac = await this.contract.getMyFractionalShares(ethers6.getAddress(subject), ethers6.getAddress(user));
|
|
1420
|
+
return { tickets: (Number(frac) / FRACTION_SCALER).toString(), fractionalAmount: frac.toString() };
|
|
1421
|
+
}
|
|
1422
|
+
async getSupply(subject) {
|
|
1423
|
+
const subjectAddr = ethers6.getAddress(subject);
|
|
1424
|
+
const [wholeSupply, fracSupply] = await Promise.all([
|
|
1425
|
+
this.contract.getSharesSupply(subjectAddr),
|
|
1426
|
+
this.contract.getTotalFractionalSupply(subjectAddr)
|
|
1427
|
+
]);
|
|
1428
|
+
return { wholeSupply: wholeSupply.toString(), fractionalSupply: fracSupply.toString(), tickets: (Number(fracSupply) / FRACTION_SCALER).toString() };
|
|
1429
|
+
}
|
|
1430
|
+
async getFees() {
|
|
1431
|
+
const [protocol, subject, referral] = await Promise.all([
|
|
1432
|
+
this.contract.protocolFeePercent(),
|
|
1433
|
+
this.contract.subjectFeePercent(),
|
|
1434
|
+
this.contract.referralFeePercent()
|
|
1435
|
+
]);
|
|
1436
|
+
const toPercent = (v) => (Number(v) / 1e16).toFixed(1) + "%";
|
|
1437
|
+
return { protocolFee: toPercent(protocol), subjectFee: toPercent(subject), referralFee: toPercent(referral), totalFeePercent: toPercent(protocol + subject + referral) };
|
|
1438
|
+
}
|
|
1439
|
+
async buildBuyTx(wallet, subject, amount = "1") {
|
|
1440
|
+
const fractionalAmount = this.ticketsToFractional(amount);
|
|
1441
|
+
const subjectAddr = ethers6.getAddress(subject);
|
|
1442
|
+
const userAddr = ethers6.getAddress(wallet);
|
|
1443
|
+
const cost = await this.contract.getBuyPriceForFractionalSharesAfterFee(subjectAddr, fractionalAmount);
|
|
1444
|
+
if (cost === 0n) throw new Error("Could not get buy price \u2014 subject may not exist");
|
|
1445
|
+
const iface = new ethers6.Interface(SHARES_ABI);
|
|
1446
|
+
const data = iface.encodeFunctionData("buyFractionalShares", [subjectAddr, userAddr, fractionalAmount]);
|
|
1447
|
+
return {
|
|
1448
|
+
transaction: {
|
|
1449
|
+
to: ethers6.getAddress(ARENA_SHARES_CONTRACT),
|
|
1450
|
+
data,
|
|
1451
|
+
value: ethers6.toBeHex(cost, 32),
|
|
1452
|
+
chainId: CHAIN_ID,
|
|
1453
|
+
gasLimit: "200000",
|
|
1454
|
+
description: `Buy ${amount} ticket(s) for ~${ethers6.formatEther(cost)} AVAX`
|
|
1455
|
+
}
|
|
1456
|
+
};
|
|
1457
|
+
}
|
|
1458
|
+
async buildSellTx(wallet, subject, amount = "1") {
|
|
1459
|
+
const fractionalAmount = this.ticketsToFractional(amount);
|
|
1460
|
+
const subjectAddr = ethers6.getAddress(subject);
|
|
1461
|
+
const userAddr = ethers6.getAddress(wallet);
|
|
1462
|
+
const balance = await this.contract.getMyFractionalShares(subjectAddr, userAddr);
|
|
1463
|
+
if (balance < BigInt(fractionalAmount)) {
|
|
1464
|
+
throw new Error(`Insufficient tickets: have ${Number(balance) / FRACTION_SCALER}, trying to sell ${amount}`);
|
|
1465
|
+
}
|
|
1466
|
+
const proceeds = await this.contract.getSellPriceForFractionalSharesAfterFee(subjectAddr, fractionalAmount);
|
|
1467
|
+
const iface = new ethers6.Interface(SHARES_ABI);
|
|
1468
|
+
const data = iface.encodeFunctionData("sellFractionalShares", [subjectAddr, userAddr, fractionalAmount]);
|
|
1469
|
+
return {
|
|
1470
|
+
transaction: {
|
|
1471
|
+
to: ethers6.getAddress(ARENA_SHARES_CONTRACT),
|
|
1472
|
+
data,
|
|
1473
|
+
value: "0x0",
|
|
1474
|
+
chainId: CHAIN_ID,
|
|
1475
|
+
gasLimit: "200000",
|
|
1476
|
+
description: `Sell ${amount} ticket(s) for ~${ethers6.formatEther(proceeds)} AVAX`
|
|
1477
|
+
}
|
|
1478
|
+
};
|
|
1479
|
+
}
|
|
1480
|
+
ticketsToFractional(tickets) {
|
|
1481
|
+
const num = parseFloat(tickets);
|
|
1482
|
+
if (isNaN(num) || num <= 0) throw new Error(`Invalid ticket amount: ${tickets}`);
|
|
1483
|
+
return Math.round(num * FRACTION_SCALER);
|
|
1484
|
+
}
|
|
1485
|
+
};
|
|
1486
|
+
|
|
1487
|
+
// src/modules/social.ts
|
|
1488
|
+
var SocialModule = class {
|
|
1489
|
+
constructor(arenaApiKey) {
|
|
1490
|
+
this.arenaApiKey = arenaApiKey;
|
|
1491
|
+
}
|
|
1492
|
+
setArenaApiKey(key) {
|
|
1493
|
+
this.arenaApiKey = key;
|
|
1494
|
+
}
|
|
1495
|
+
async request(method, path, body, query) {
|
|
1496
|
+
if (!this.arenaApiKey) throw new Error("Arena API key required for social endpoints. Pass arenaApiKey in config.");
|
|
1497
|
+
let url = `${ARENA_SOCIAL_API}${path}`;
|
|
1498
|
+
if (query) {
|
|
1499
|
+
const params = new URLSearchParams(query);
|
|
1500
|
+
url += `?${params.toString()}`;
|
|
1501
|
+
}
|
|
1502
|
+
const headers = { "x-api-key": this.arenaApiKey, "Content-Type": "application/json" };
|
|
1503
|
+
const res = await fetch(url, { method, headers, body: body ? JSON.stringify(body) : void 0 });
|
|
1504
|
+
const data = await res.json();
|
|
1505
|
+
if (!res.ok) {
|
|
1506
|
+
const msg = data.message || data.error || `Arena API error ${res.status}`;
|
|
1507
|
+
throw new Error(msg);
|
|
1508
|
+
}
|
|
1509
|
+
return data;
|
|
1510
|
+
}
|
|
1511
|
+
// ── User Discovery ──
|
|
1512
|
+
async searchUsers(q, page = 1, pageSize = 20) {
|
|
1513
|
+
return this.request("GET", "/agents/user/search", void 0, { searchString: q, page: String(page), pageSize: String(pageSize) });
|
|
1514
|
+
}
|
|
1515
|
+
async getUserByHandle(handle) {
|
|
1516
|
+
return this.request("GET", "/agents/user/handle", void 0, { handle });
|
|
1517
|
+
}
|
|
1518
|
+
async getUserById(userId) {
|
|
1519
|
+
return this.request("GET", "/agents/user/id", void 0, { userId });
|
|
1520
|
+
}
|
|
1521
|
+
async getTopUsers(page = 1, pageSize = 20) {
|
|
1522
|
+
return this.request("GET", "/agents/user/top", void 0, { page: String(page), pageSize: String(pageSize) });
|
|
1523
|
+
}
|
|
1524
|
+
async getMe() {
|
|
1525
|
+
return this.request("GET", "/agents/user/me");
|
|
1526
|
+
}
|
|
1527
|
+
// ── Profile ──
|
|
1528
|
+
async updateProfile(updates) {
|
|
1529
|
+
return this.request("PATCH", "/agents/user/profile", updates);
|
|
1530
|
+
}
|
|
1531
|
+
async updateBanner(bannerUrl) {
|
|
1532
|
+
return this.request("POST", "/agents/profile/banner", { bannerUrl });
|
|
1533
|
+
}
|
|
1534
|
+
// ── Follow ──
|
|
1535
|
+
async follow(userId) {
|
|
1536
|
+
return this.request("POST", "/agents/follow/follow", { userId });
|
|
1537
|
+
}
|
|
1538
|
+
async unfollow(userId) {
|
|
1539
|
+
return this.request("POST", "/agents/follow/unfollow", { userId });
|
|
1540
|
+
}
|
|
1541
|
+
async getFollowers(userId, page = 1, pageSize = 20) {
|
|
1542
|
+
return this.request("GET", "/agents/follow/followers/list", void 0, { followersOfUserId: userId, pageNumber: String(page), pageSize: String(pageSize) });
|
|
1543
|
+
}
|
|
1544
|
+
async getFollowing(userId, page = 1, pageSize = 20) {
|
|
1545
|
+
return this.request("GET", "/agents/follow/following/list", void 0, { followingUserId: userId, pageNumber: String(page), pageSize: String(pageSize) });
|
|
1546
|
+
}
|
|
1547
|
+
// ── Shares ──
|
|
1548
|
+
async getSharesStats(userId) {
|
|
1549
|
+
return this.request("GET", "/agents/shares/stats", void 0, { userId });
|
|
1550
|
+
}
|
|
1551
|
+
async getShareHolders(userId, page = 1, pageSize = 20) {
|
|
1552
|
+
const q = { page: String(page), pageSize: String(pageSize) };
|
|
1553
|
+
if (userId) q.userId = userId;
|
|
1554
|
+
return this.request("GET", "/agents/shares/holders", void 0, q);
|
|
1555
|
+
}
|
|
1556
|
+
async getHoldings(page = 1, pageSize = 20) {
|
|
1557
|
+
return this.request("GET", "/agents/shares/holdings", void 0, { page: String(page), pageSize: String(pageSize) });
|
|
1558
|
+
}
|
|
1559
|
+
// ── Chat: Conversations ──
|
|
1560
|
+
async getConversations(page = 1) {
|
|
1561
|
+
return this.request("GET", "/agents/chat/conversations", void 0, { page: String(page), pageSize: "20" });
|
|
1562
|
+
}
|
|
1563
|
+
async getDirectMessages() {
|
|
1564
|
+
return this.request("GET", "/agents/chat/direct-messages", void 0, { page: "1", pageSize: "20" });
|
|
1565
|
+
}
|
|
1566
|
+
async getGroupChats() {
|
|
1567
|
+
return this.request("GET", "/agents/chat/project-chats", void 0, { page: "1", pageSize: "20" });
|
|
1568
|
+
}
|
|
1569
|
+
async getGroup(groupId) {
|
|
1570
|
+
return this.request("GET", "/agents/chat/group", void 0, { groupId });
|
|
1571
|
+
}
|
|
1572
|
+
async getMembers(groupId) {
|
|
1573
|
+
return this.request("GET", "/agents/chat/members", void 0, { groupId, page: "1", pageSize: "20" });
|
|
1574
|
+
}
|
|
1575
|
+
async getOrCreateDM(userId) {
|
|
1576
|
+
return this.request("GET", "/agents/chat/group/by/user", void 0, { userId });
|
|
1577
|
+
}
|
|
1578
|
+
async acceptChat(groupId) {
|
|
1579
|
+
return this.request("GET", "/agents/chat/accept-chat", void 0, { groupId });
|
|
1580
|
+
}
|
|
1581
|
+
// ── Chat: Messages ──
|
|
1582
|
+
async sendMessage(groupId, text, replyId) {
|
|
1583
|
+
const body = { groupId, text, files: [] };
|
|
1584
|
+
if (replyId) body.replyId = replyId;
|
|
1585
|
+
return this.request("POST", "/agents/chat/message", body);
|
|
1586
|
+
}
|
|
1587
|
+
async getMessages(groupId, after) {
|
|
1588
|
+
const q = { groupId };
|
|
1589
|
+
if (after) q.timeFrom = after;
|
|
1590
|
+
return this.request("GET", "/agents/chat/messages/a", void 0, q);
|
|
1591
|
+
}
|
|
1592
|
+
async searchMessages(q, groupId) {
|
|
1593
|
+
const query = { searchQuery: q, limit: "20" };
|
|
1594
|
+
if (groupId) query.groupId = groupId;
|
|
1595
|
+
return this.request("GET", "/agents/chat/messages/search", void 0, query);
|
|
1596
|
+
}
|
|
1597
|
+
async getMentions(groupId) {
|
|
1598
|
+
const q = { limit: "50" };
|
|
1599
|
+
if (groupId) q.groupId = groupId;
|
|
1600
|
+
return this.request("GET", "/agents/chat/messages/mentions", void 0, q);
|
|
1601
|
+
}
|
|
1602
|
+
// ── Chat: Reactions & Pins ──
|
|
1603
|
+
async react(messageId, groupId, reaction) {
|
|
1604
|
+
return this.request("POST", "/agents/chat/react", { messageId, groupId, reaction });
|
|
1605
|
+
}
|
|
1606
|
+
async pinMessage(messageId, groupId, isPinned = true) {
|
|
1607
|
+
return this.request("POST", "/agents/chat/message/pin", { messageId, groupId, isPinned });
|
|
1608
|
+
}
|
|
1609
|
+
async getPinnedMessages(groupId) {
|
|
1610
|
+
return this.request("GET", `/agents/chat/messages/pinned/${groupId}`);
|
|
1611
|
+
}
|
|
1612
|
+
// ── Threads ──
|
|
1613
|
+
async createThread(content, replyToId) {
|
|
1614
|
+
const body = { content };
|
|
1615
|
+
if (replyToId) body.replyToId = replyToId;
|
|
1616
|
+
return this.request("POST", "/agents/threads", body);
|
|
1617
|
+
}
|
|
1618
|
+
async likeThread(threadId) {
|
|
1619
|
+
return this.request("POST", "/agents/threads/like", { threadId });
|
|
1620
|
+
}
|
|
1621
|
+
async repost(threadId) {
|
|
1622
|
+
return this.request("POST", "/agents/threads/repost", { threadId });
|
|
1623
|
+
}
|
|
1624
|
+
};
|
|
1625
|
+
|
|
1626
|
+
// src/modules/signals.ts
|
|
1627
|
+
var SignalsModule = class {
|
|
1628
|
+
assetCache = null;
|
|
1629
|
+
candleCache = /* @__PURE__ */ new Map();
|
|
1630
|
+
async hlPost(body) {
|
|
1631
|
+
const res = await fetch(HL_INFO, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) });
|
|
1632
|
+
if (!res.ok) throw new Error(`Hyperliquid API error ${res.status}`);
|
|
1633
|
+
return res.json();
|
|
1634
|
+
}
|
|
1635
|
+
/** Get all asset contexts (cached 10s) */
|
|
1636
|
+
async getAssetContexts() {
|
|
1637
|
+
if (this.assetCache && Date.now() - this.assetCache.ts < 1e4) return this.assetCache.data;
|
|
1638
|
+
const raw = await this.hlPost({ type: "metaAndAssetCtxs" });
|
|
1639
|
+
const result = { meta: raw[0].universe, contexts: raw[1] };
|
|
1640
|
+
this.assetCache = { data: result, ts: Date.now() };
|
|
1641
|
+
return result;
|
|
1642
|
+
}
|
|
1643
|
+
/** Get market signal for a specific asset */
|
|
1644
|
+
async getMarketSignal(coin) {
|
|
1645
|
+
const { meta, contexts } = await this.getAssetContexts();
|
|
1646
|
+
const idx = meta.findIndex((m2) => m2.name.toUpperCase() === coin.toUpperCase());
|
|
1647
|
+
if (idx === -1) throw new Error(`Asset ${coin} not found on Hyperliquid`);
|
|
1648
|
+
const m = meta[idx];
|
|
1649
|
+
const ctx = contexts[idx];
|
|
1650
|
+
const price = parseFloat(ctx.markPx);
|
|
1651
|
+
const prevPrice = parseFloat(ctx.prevDayPx);
|
|
1652
|
+
const funding = parseFloat(ctx.funding);
|
|
1653
|
+
const change24h = price - prevPrice;
|
|
1654
|
+
const change24hPct = prevPrice > 0 ? change24h / prevPrice * 100 : 0;
|
|
1655
|
+
let fundingBias = "neutral";
|
|
1656
|
+
if (funding > 1e-4) fundingBias = "long-heavy";
|
|
1657
|
+
else if (funding < -1e-4) fundingBias = "short-heavy";
|
|
1658
|
+
return {
|
|
1659
|
+
coin: m.name,
|
|
1660
|
+
price,
|
|
1661
|
+
oraclePrice: parseFloat(ctx.oraclePx),
|
|
1662
|
+
change24h,
|
|
1663
|
+
change24hPct: Math.round(change24hPct * 100) / 100,
|
|
1664
|
+
volume24h: Math.round(parseFloat(ctx.dayNtlVlm)),
|
|
1665
|
+
openInterest: Math.round(parseFloat(ctx.openInterest)),
|
|
1666
|
+
fundingRate: funding,
|
|
1667
|
+
fundingAnnualized: Math.round(funding * 8760 * 1e4) / 100,
|
|
1668
|
+
fundingBias,
|
|
1669
|
+
maxLeverage: m.maxLeverage
|
|
1670
|
+
};
|
|
1671
|
+
}
|
|
1672
|
+
/** Get funding rate extremes across all markets */
|
|
1673
|
+
async getFundingExtremes(count = 10) {
|
|
1674
|
+
const { meta, contexts } = await this.getAssetContexts();
|
|
1675
|
+
const signals = meta.map((m, i) => this.buildSignal(m, contexts[i]));
|
|
1676
|
+
const sorted = [...signals].sort((a, b) => b.fundingRate - a.fundingRate);
|
|
1677
|
+
return { mostPositive: sorted.slice(0, count), mostNegative: sorted.slice(-count).reverse() };
|
|
1678
|
+
}
|
|
1679
|
+
/** Get candle data for technical analysis (cached 60s) */
|
|
1680
|
+
async getCandles(coin, interval = "1h", count = 100) {
|
|
1681
|
+
const cacheKey = `${coin}-${interval}`;
|
|
1682
|
+
const cached = this.candleCache.get(cacheKey);
|
|
1683
|
+
if (cached && Date.now() - cached.ts < 6e4) return cached.data.slice(-count);
|
|
1684
|
+
const startTime = Date.now() - count * this.intervalToMs(interval);
|
|
1685
|
+
const data = await this.hlPost({ type: "candleSnapshot", req: { coin: coin.toUpperCase(), interval, startTime, endTime: Date.now() } });
|
|
1686
|
+
const candles = data.map((c) => [c.t, parseFloat(c.o), parseFloat(c.h), parseFloat(c.l), parseFloat(c.c), parseFloat(c.v)]);
|
|
1687
|
+
this.candleCache.set(cacheKey, { data: candles, ts: Date.now() });
|
|
1688
|
+
return candles.slice(-count);
|
|
1689
|
+
}
|
|
1690
|
+
/** Compute technical signals from candle data */
|
|
1691
|
+
async getTechnicalSignal(coin, interval = "1h") {
|
|
1692
|
+
const candles = await this.getCandles(coin, interval, 100);
|
|
1693
|
+
const closes = candles.map((c) => c[4]);
|
|
1694
|
+
const highs = candles.map((c) => c[2]);
|
|
1695
|
+
const lows = candles.map((c) => c[3]);
|
|
1696
|
+
const price = closes[closes.length - 1];
|
|
1697
|
+
const sma20 = this.sma(closes, 20);
|
|
1698
|
+
const sma50 = this.sma(closes, 50);
|
|
1699
|
+
const rsi14 = this.rsi(closes, 14);
|
|
1700
|
+
let trend = "neutral";
|
|
1701
|
+
if (price > sma20 && price > sma50) trend = "bullish";
|
|
1702
|
+
else if (price < sma20 && price < sma50) trend = "bearish";
|
|
1703
|
+
let momentum = "moderate";
|
|
1704
|
+
if (rsi14 > 70 || rsi14 < 30) momentum = "strong";
|
|
1705
|
+
else if (rsi14 > 60 || rsi14 < 40) momentum = "moderate";
|
|
1706
|
+
else momentum = "weak";
|
|
1707
|
+
const returns = closes.slice(-21).map((c, i, arr) => i === 0 ? 0 : (c - arr[i - 1]) / arr[i - 1]);
|
|
1708
|
+
returns.shift();
|
|
1709
|
+
const volatility = Math.sqrt(returns.reduce((sum, r) => sum + r * r, 0) / returns.length) * 100;
|
|
1710
|
+
const resistance = Math.max(...highs.slice(-20));
|
|
1711
|
+
const support = Math.min(...lows.slice(-20));
|
|
1712
|
+
return {
|
|
1713
|
+
coin: coin.toUpperCase(),
|
|
1714
|
+
price,
|
|
1715
|
+
sma20: Math.round(sma20 * 100) / 100,
|
|
1716
|
+
sma50: Math.round(sma50 * 100) / 100,
|
|
1717
|
+
rsi14: Math.round(rsi14 * 100) / 100,
|
|
1718
|
+
trend,
|
|
1719
|
+
momentum,
|
|
1720
|
+
priceVsSma20: Math.round((price - sma20) / sma20 * 1e4) / 100,
|
|
1721
|
+
priceVsSma50: Math.round((price - sma50) / sma50 * 1e4) / 100,
|
|
1722
|
+
volatility: Math.round(volatility * 100) / 100,
|
|
1723
|
+
support: Math.round(support * 100) / 100,
|
|
1724
|
+
resistance: Math.round(resistance * 100) / 100
|
|
1725
|
+
};
|
|
1726
|
+
}
|
|
1727
|
+
/** Get whale positions from orderbook depth */
|
|
1728
|
+
async getWhalePositions(coin, minPositionUsd = 1e5) {
|
|
1729
|
+
const book = await this.hlPost({ type: "l2Book", coin: coin.toUpperCase() });
|
|
1730
|
+
const whales = [];
|
|
1731
|
+
for (const level of book.levels[0] ?? []) {
|
|
1732
|
+
const px = parseFloat(level.px);
|
|
1733
|
+
const sz = parseFloat(level.sz);
|
|
1734
|
+
const value = px * sz;
|
|
1735
|
+
if (value >= minPositionUsd) whales.push({ coin: coin.toUpperCase(), size: sz, entryPrice: px, side: "long", positionValue: Math.round(value) });
|
|
1736
|
+
}
|
|
1737
|
+
for (const level of book.levels[1] ?? []) {
|
|
1738
|
+
const px = parseFloat(level.px);
|
|
1739
|
+
const sz = parseFloat(level.sz);
|
|
1740
|
+
const value = px * sz;
|
|
1741
|
+
if (value >= minPositionUsd) whales.push({ coin: coin.toUpperCase(), size: sz, entryPrice: px, side: "short", positionValue: Math.round(value) });
|
|
1742
|
+
}
|
|
1743
|
+
return whales.sort((a, b) => b.positionValue - a.positionValue);
|
|
1744
|
+
}
|
|
1745
|
+
/** Full signal summary — everything an agent needs to decide */
|
|
1746
|
+
async summary(coin) {
|
|
1747
|
+
const [market, technical, whalePositions] = await Promise.all([
|
|
1748
|
+
this.getMarketSignal(coin),
|
|
1749
|
+
this.getTechnicalSignal(coin),
|
|
1750
|
+
this.getWhalePositions(coin)
|
|
1751
|
+
]);
|
|
1752
|
+
const topLongs = whalePositions.filter((w) => w.side === "long").slice(0, 5);
|
|
1753
|
+
const topShorts = whalePositions.filter((w) => w.side === "short").slice(0, 5);
|
|
1754
|
+
const longValue = topLongs.reduce((s, w) => s + w.positionValue, 0);
|
|
1755
|
+
const shortValue = topShorts.reduce((s, w) => s + w.positionValue, 0);
|
|
1756
|
+
let netBias = "neutral";
|
|
1757
|
+
if (longValue > shortValue * 1.3) netBias = "long";
|
|
1758
|
+
else if (shortValue > longValue * 1.3) netBias = "short";
|
|
1759
|
+
const reasons = [];
|
|
1760
|
+
let longScore = 0;
|
|
1761
|
+
let shortScore = 0;
|
|
1762
|
+
if (technical.trend === "bullish") {
|
|
1763
|
+
longScore += 2;
|
|
1764
|
+
reasons.push("Price above SMA20 & SMA50 (bullish trend)");
|
|
1765
|
+
} else if (technical.trend === "bearish") {
|
|
1766
|
+
shortScore += 2;
|
|
1767
|
+
reasons.push("Price below SMA20 & SMA50 (bearish trend)");
|
|
1768
|
+
}
|
|
1769
|
+
if (technical.rsi14 < 30) {
|
|
1770
|
+
longScore += 2;
|
|
1771
|
+
reasons.push(`RSI ${technical.rsi14} \u2014 oversold`);
|
|
1772
|
+
} else if (technical.rsi14 > 70) {
|
|
1773
|
+
shortScore += 2;
|
|
1774
|
+
reasons.push(`RSI ${technical.rsi14} \u2014 overbought`);
|
|
1775
|
+
}
|
|
1776
|
+
if (market.fundingBias === "long-heavy") {
|
|
1777
|
+
shortScore += 1;
|
|
1778
|
+
reasons.push("Crowded long \u2014 contrarian short signal");
|
|
1779
|
+
} else if (market.fundingBias === "short-heavy") {
|
|
1780
|
+
longScore += 1;
|
|
1781
|
+
reasons.push("Crowded short \u2014 contrarian long signal");
|
|
1782
|
+
}
|
|
1783
|
+
if (netBias === "long") {
|
|
1784
|
+
longScore += 1;
|
|
1785
|
+
reasons.push("Whale bias: more large bids");
|
|
1786
|
+
} else if (netBias === "short") {
|
|
1787
|
+
shortScore += 1;
|
|
1788
|
+
reasons.push("Whale bias: more large asks");
|
|
1789
|
+
}
|
|
1790
|
+
if (market.change24hPct > 3) {
|
|
1791
|
+
longScore += 1;
|
|
1792
|
+
reasons.push(`+${market.change24hPct}% momentum`);
|
|
1793
|
+
} else if (market.change24hPct < -3) {
|
|
1794
|
+
shortScore += 1;
|
|
1795
|
+
reasons.push(`${market.change24hPct}% selling`);
|
|
1796
|
+
}
|
|
1797
|
+
const diff = Math.abs(longScore - shortScore);
|
|
1798
|
+
let direction = "wait";
|
|
1799
|
+
let confidence = "low";
|
|
1800
|
+
if (diff >= 4) {
|
|
1801
|
+
direction = longScore > shortScore ? "long" : "short";
|
|
1802
|
+
confidence = "high";
|
|
1803
|
+
} else if (diff >= 2) {
|
|
1804
|
+
direction = longScore > shortScore ? "long" : "short";
|
|
1805
|
+
confidence = "medium";
|
|
1806
|
+
} else {
|
|
1807
|
+
reasons.push("Mixed signals \u2014 wait for better setup.");
|
|
1808
|
+
}
|
|
1809
|
+
return {
|
|
1810
|
+
coin: coin.toUpperCase(),
|
|
1811
|
+
timestamp: (/* @__PURE__ */ new Date()).toISOString(),
|
|
1812
|
+
market,
|
|
1813
|
+
technical,
|
|
1814
|
+
whaleActivity: { topLongs, topShorts, netBias, largestPosition: whalePositions[0] ?? null },
|
|
1815
|
+
verdict: { direction, confidence, reasons }
|
|
1816
|
+
};
|
|
1817
|
+
}
|
|
1818
|
+
/** Scan for top trading opportunities */
|
|
1819
|
+
async scan(count = 5) {
|
|
1820
|
+
const [movers, funding] = await Promise.all([this.getTopMovers(10), this.getFundingExtremes(10)]);
|
|
1821
|
+
const candidates = /* @__PURE__ */ new Set(["BTC", "ETH", "SOL"]);
|
|
1822
|
+
movers.gainers.slice(0, 3).forEach((s) => candidates.add(s.coin));
|
|
1823
|
+
movers.losers.slice(0, 3).forEach((s) => candidates.add(s.coin));
|
|
1824
|
+
funding.mostPositive.slice(0, 2).forEach((s) => candidates.add(s.coin));
|
|
1825
|
+
funding.mostNegative.slice(0, 2).forEach((s) => candidates.add(s.coin));
|
|
1826
|
+
const summaries = await Promise.all(Array.from(candidates).slice(0, 15).map((c) => this.summary(c).catch(() => null)));
|
|
1827
|
+
const valid = summaries.filter((s) => s !== null && s.verdict.direction !== "wait");
|
|
1828
|
+
const order = { high: 3, medium: 2, low: 1 };
|
|
1829
|
+
valid.sort((a, b) => order[b.verdict.confidence] - order[a.verdict.confidence]);
|
|
1830
|
+
return valid.slice(0, count);
|
|
1831
|
+
}
|
|
1832
|
+
async getTopMovers(count) {
|
|
1833
|
+
const { meta, contexts } = await this.getAssetContexts();
|
|
1834
|
+
const signals = meta.map((m, i) => this.buildSignal(m, contexts[i]));
|
|
1835
|
+
const sorted = [...signals].sort((a, b) => b.change24hPct - a.change24hPct);
|
|
1836
|
+
return { gainers: sorted.slice(0, count), losers: sorted.slice(-count).reverse() };
|
|
1837
|
+
}
|
|
1838
|
+
buildSignal(m, ctx) {
|
|
1839
|
+
const price = parseFloat(ctx.markPx);
|
|
1840
|
+
const prevPrice = parseFloat(ctx.prevDayPx);
|
|
1841
|
+
const funding = parseFloat(ctx.funding);
|
|
1842
|
+
const change24hPct = prevPrice > 0 ? (price - prevPrice) / prevPrice * 100 : 0;
|
|
1843
|
+
let fundingBias = "neutral";
|
|
1844
|
+
if (funding > 1e-4) fundingBias = "long-heavy";
|
|
1845
|
+
else if (funding < -1e-4) fundingBias = "short-heavy";
|
|
1846
|
+
return {
|
|
1847
|
+
coin: m.name,
|
|
1848
|
+
price,
|
|
1849
|
+
oraclePrice: parseFloat(ctx.oraclePx),
|
|
1850
|
+
change24h: price - prevPrice,
|
|
1851
|
+
change24hPct: Math.round(change24hPct * 100) / 100,
|
|
1852
|
+
volume24h: Math.round(parseFloat(ctx.dayNtlVlm)),
|
|
1853
|
+
openInterest: Math.round(parseFloat(ctx.openInterest)),
|
|
1854
|
+
fundingRate: funding,
|
|
1855
|
+
fundingAnnualized: Math.round(funding * 8760 * 1e4) / 100,
|
|
1856
|
+
fundingBias,
|
|
1857
|
+
maxLeverage: m.maxLeverage
|
|
1858
|
+
};
|
|
1859
|
+
}
|
|
1860
|
+
sma(data, period) {
|
|
1861
|
+
const s = data.slice(-period);
|
|
1862
|
+
return s.reduce((sum, v) => sum + v, 0) / s.length;
|
|
1863
|
+
}
|
|
1864
|
+
rsi(closes, period) {
|
|
1865
|
+
const changes = closes.slice(-period - 1).map((c, i, arr) => i === 0 ? 0 : c - arr[i - 1]);
|
|
1866
|
+
changes.shift();
|
|
1867
|
+
let avgGain = 0;
|
|
1868
|
+
let avgLoss = 0;
|
|
1869
|
+
for (const ch of changes) {
|
|
1870
|
+
if (ch > 0) avgGain += ch;
|
|
1871
|
+
else avgLoss += Math.abs(ch);
|
|
1872
|
+
}
|
|
1873
|
+
avgGain /= period;
|
|
1874
|
+
avgLoss /= period;
|
|
1875
|
+
if (avgLoss === 0) return 100;
|
|
1876
|
+
return 100 - 100 / (1 + avgGain / avgLoss);
|
|
1877
|
+
}
|
|
1878
|
+
intervalToMs(interval) {
|
|
1879
|
+
const map = { "1m": 6e4, "5m": 3e5, "15m": 9e5, "1h": 36e5, "4h": 144e5, "1d": 864e5 };
|
|
1880
|
+
return map[interval] ?? 36e5;
|
|
1881
|
+
}
|
|
1882
|
+
};
|
|
1883
|
+
|
|
1884
|
+
// src/modules/market.ts
|
|
1885
|
+
var COINGECKO_API = "https://api.coingecko.com/api/v3";
|
|
1886
|
+
var MarketModule = class {
|
|
1887
|
+
/** Get prices for one or more coins (by CoinGecko ID) */
|
|
1888
|
+
async price(ids) {
|
|
1889
|
+
const idStr = Array.isArray(ids) ? ids.join(",") : ids;
|
|
1890
|
+
const res = await fetch(`${COINGECKO_API}/simple/price?ids=${idStr}&vs_currencies=usd&include_24hr_change=true&include_market_cap=true&include_24hr_vol=true`);
|
|
1891
|
+
if (!res.ok) throw new Error(`CoinGecko price error ${res.status}`);
|
|
1892
|
+
return res.json();
|
|
1893
|
+
}
|
|
1894
|
+
/** Get trending coins */
|
|
1895
|
+
async trending() {
|
|
1896
|
+
const res = await fetch(`${COINGECKO_API}/search/trending`);
|
|
1897
|
+
if (!res.ok) throw new Error(`CoinGecko trending error ${res.status}`);
|
|
1898
|
+
const data = await res.json();
|
|
1899
|
+
const coins = (data.coins ?? []).map((c) => ({
|
|
1900
|
+
id: c.item.id,
|
|
1901
|
+
name: c.item.name,
|
|
1902
|
+
symbol: c.item.symbol,
|
|
1903
|
+
market_cap_rank: c.item.market_cap_rank,
|
|
1904
|
+
thumb: c.item.thumb,
|
|
1905
|
+
price_btc: c.item.price_btc
|
|
1906
|
+
}));
|
|
1907
|
+
return { coins };
|
|
1908
|
+
}
|
|
1909
|
+
/** Get top coins by market cap */
|
|
1910
|
+
async markets(count = 20, page = 1) {
|
|
1911
|
+
const res = await fetch(`${COINGECKO_API}/coins/markets?vs_currency=usd&order=market_cap_desc&per_page=${count}&page=${page}&sparkline=false`);
|
|
1912
|
+
if (!res.ok) throw new Error(`CoinGecko markets error ${res.status}`);
|
|
1913
|
+
const data = await res.json();
|
|
1914
|
+
const coins = data.map((c) => ({
|
|
1915
|
+
id: c.id,
|
|
1916
|
+
symbol: c.symbol,
|
|
1917
|
+
name: c.name,
|
|
1918
|
+
current_price: c.current_price,
|
|
1919
|
+
market_cap: c.market_cap,
|
|
1920
|
+
price_change_percentage_24h: c.price_change_percentage_24h,
|
|
1921
|
+
total_volume: c.total_volume,
|
|
1922
|
+
market_cap_rank: c.market_cap_rank
|
|
1923
|
+
}));
|
|
1924
|
+
return { coins };
|
|
1925
|
+
}
|
|
1926
|
+
/** Search for coins by query */
|
|
1927
|
+
async search(query) {
|
|
1928
|
+
const res = await fetch(`${COINGECKO_API}/search?query=${encodeURIComponent(query)}`);
|
|
1929
|
+
if (!res.ok) throw new Error(`CoinGecko search error ${res.status}`);
|
|
1930
|
+
const data = await res.json();
|
|
1931
|
+
return { coins: (data.coins ?? []).map((c) => ({ id: c.id, name: c.name, symbol: c.symbol, market_cap_rank: c.market_cap_rank })) };
|
|
1932
|
+
}
|
|
1933
|
+
/** Get AVAX price specifically */
|
|
1934
|
+
async avaxPrice() {
|
|
1935
|
+
const data = await this.price("avalanche-2");
|
|
1936
|
+
const avax = data["avalanche-2"];
|
|
1937
|
+
return { usd: avax?.usd ?? 0, change24h: avax?.usd_24h_change ?? 0 };
|
|
1938
|
+
}
|
|
1939
|
+
/** Get ARENA price specifically */
|
|
1940
|
+
async arenaPrice() {
|
|
1941
|
+
const data = await this.price("arena-social");
|
|
1942
|
+
const arena = data["arena-social"];
|
|
1943
|
+
return { usd: arena?.usd ?? 0, change24h: arena?.usd_24h_change ?? 0 };
|
|
1944
|
+
}
|
|
1945
|
+
};
|
|
1946
|
+
|
|
1947
|
+
// src/modules/defi.ts
|
|
1948
|
+
import { ethers as ethers7 } from "ethers";
|
|
1949
|
+
var SAVAX_ADDRESS = "0x2b2C81e08f1Af8835a78Bb2A90AE924ACE0eA4bE";
|
|
1950
|
+
var SAVAX_ABI = [
|
|
1951
|
+
"function submit() payable returns (uint256)",
|
|
1952
|
+
"function requestUnlock(uint256 shareAmount) returns (uint256)",
|
|
1953
|
+
"function getPooledAvaxByShares(uint256 shareAmount) view returns (uint256)",
|
|
1954
|
+
"function getSharesByPooledAvax(uint256 avaxAmount) view returns (uint256)",
|
|
1955
|
+
"function totalPooledAvax() view returns (uint256)",
|
|
1956
|
+
"function totalShares() view returns (uint256)",
|
|
1957
|
+
"function balanceOf(address) view returns (uint256)",
|
|
1958
|
+
"function cooldownPeriod() view returns (uint256)",
|
|
1959
|
+
"function exchangeRate() view returns (uint256)",
|
|
1960
|
+
"function approve(address,uint256) returns (bool)"
|
|
1961
|
+
];
|
|
1962
|
+
var VAULT_ABI = [
|
|
1963
|
+
"function asset() view returns (address)",
|
|
1964
|
+
"function totalAssets() view returns (uint256)",
|
|
1965
|
+
"function totalSupply() view returns (uint256)",
|
|
1966
|
+
"function balanceOf(address) view returns (uint256)",
|
|
1967
|
+
"function convertToShares(uint256 assets) view returns (uint256)",
|
|
1968
|
+
"function convertToAssets(uint256 shares) view returns (uint256)",
|
|
1969
|
+
"function maxDeposit(address) view returns (uint256)",
|
|
1970
|
+
"function maxWithdraw(address) view returns (uint256)",
|
|
1971
|
+
"function previewDeposit(uint256 assets) view returns (uint256)",
|
|
1972
|
+
"function previewWithdraw(uint256 assets) view returns (uint256)",
|
|
1973
|
+
"function deposit(uint256 assets, address receiver) returns (uint256)",
|
|
1974
|
+
"function withdraw(uint256 assets, address receiver, address owner) returns (uint256)",
|
|
1975
|
+
"function decimals() view returns (uint8)",
|
|
1976
|
+
"function symbol() view returns (string)",
|
|
1977
|
+
"function name() view returns (string)"
|
|
1978
|
+
];
|
|
1979
|
+
var ERC20_ABI2 = [
|
|
1980
|
+
"function balanceOf(address) view returns (uint256)",
|
|
1981
|
+
"function approve(address,uint256) returns (bool)",
|
|
1982
|
+
"function allowance(address,address) view returns (uint256)",
|
|
1983
|
+
"function decimals() view returns (uint8)",
|
|
1984
|
+
"function symbol() view returns (string)"
|
|
1985
|
+
];
|
|
1986
|
+
var DefiModule = class {
|
|
1987
|
+
constructor(provider) {
|
|
1988
|
+
this.provider = provider;
|
|
1989
|
+
this.savax = new ethers7.Contract(ethers7.getAddress(SAVAX_ADDRESS), SAVAX_ABI, provider);
|
|
1990
|
+
}
|
|
1991
|
+
savax;
|
|
1992
|
+
// ── sAVAX Liquid Staking ──
|
|
1993
|
+
/** Get sAVAX staking info: exchange rate, total staked, your balance */
|
|
1994
|
+
async sAvaxInfo(wallet) {
|
|
1995
|
+
const [totalPooled, totalShares] = await Promise.all([
|
|
1996
|
+
this.savax.totalPooledAvax(),
|
|
1997
|
+
this.savax.totalShares()
|
|
1998
|
+
]);
|
|
1999
|
+
const exchangeRate = totalShares > 0n ? ethers7.formatEther(totalPooled * ethers7.parseEther("1") / totalShares) : "1.0";
|
|
2000
|
+
const result = {
|
|
2001
|
+
exchangeRate,
|
|
2002
|
+
totalPooledAvax: ethers7.formatEther(totalPooled),
|
|
2003
|
+
totalShares: ethers7.formatEther(totalShares)
|
|
2004
|
+
};
|
|
2005
|
+
if (wallet) {
|
|
2006
|
+
const balance = await this.savax.balanceOf(wallet);
|
|
2007
|
+
const avaxValue = await this.savax.getPooledAvaxByShares(balance);
|
|
2008
|
+
result.balance = ethers7.formatEther(balance);
|
|
2009
|
+
result.balanceInAvax = ethers7.formatEther(avaxValue);
|
|
2010
|
+
}
|
|
2011
|
+
return result;
|
|
2012
|
+
}
|
|
2013
|
+
/** Quote: how much sAVAX for staking AVAX */
|
|
2014
|
+
async sAvaxStakeQuote(avaxAmount) {
|
|
2015
|
+
const avaxWei = ethers7.parseEther(avaxAmount);
|
|
2016
|
+
const shares = await this.savax.getSharesByPooledAvax(avaxWei);
|
|
2017
|
+
return { avaxIn: avaxAmount, savaxOut: ethers7.formatEther(shares) };
|
|
2018
|
+
}
|
|
2019
|
+
/** Build tx to stake AVAX → sAVAX */
|
|
2020
|
+
async buildSAvaxStake(avaxAmount) {
|
|
2021
|
+
const avaxWei = ethers7.parseEther(avaxAmount);
|
|
2022
|
+
const iface = new ethers7.Interface(SAVAX_ABI);
|
|
2023
|
+
const data = iface.encodeFunctionData("submit", []);
|
|
2024
|
+
return {
|
|
2025
|
+
transactions: [{
|
|
2026
|
+
to: ethers7.getAddress(SAVAX_ADDRESS),
|
|
2027
|
+
data,
|
|
2028
|
+
value: ethers7.toBeHex(avaxWei, 32),
|
|
2029
|
+
chainId: CHAIN_ID,
|
|
2030
|
+
gasLimit: "300000",
|
|
2031
|
+
description: `Stake ${avaxAmount} AVAX \u2192 sAVAX`
|
|
2032
|
+
}]
|
|
2033
|
+
};
|
|
2034
|
+
}
|
|
2035
|
+
/** Build tx to request unstake sAVAX → AVAX (delayed) */
|
|
2036
|
+
async buildSAvaxUnstake(wallet, amount) {
|
|
2037
|
+
let shareAmount;
|
|
2038
|
+
if (amount === "max") {
|
|
2039
|
+
shareAmount = await this.savax.balanceOf(wallet);
|
|
2040
|
+
} else {
|
|
2041
|
+
shareAmount = ethers7.parseEther(amount);
|
|
2042
|
+
}
|
|
2043
|
+
if (shareAmount === 0n) throw new Error("Zero sAVAX balance");
|
|
2044
|
+
const iface = new ethers7.Interface(SAVAX_ABI);
|
|
2045
|
+
const data = iface.encodeFunctionData("requestUnlock", [shareAmount]);
|
|
2046
|
+
return {
|
|
2047
|
+
transactions: [{
|
|
2048
|
+
to: ethers7.getAddress(SAVAX_ADDRESS),
|
|
2049
|
+
data,
|
|
2050
|
+
value: "0",
|
|
2051
|
+
chainId: CHAIN_ID,
|
|
2052
|
+
gasLimit: "300000",
|
|
2053
|
+
description: `Request unstake ${ethers7.formatEther(shareAmount)} sAVAX`
|
|
2054
|
+
}]
|
|
2055
|
+
};
|
|
2056
|
+
}
|
|
2057
|
+
// ── ERC-4626 Vaults ──
|
|
2058
|
+
/** Get info about any ERC-4626 vault */
|
|
2059
|
+
async vaultInfo(vaultAddress, wallet) {
|
|
2060
|
+
const vault = new ethers7.Contract(ethers7.getAddress(vaultAddress), VAULT_ABI, this.provider);
|
|
2061
|
+
const [name, symbol, asset, totalAssets, totalSupply, decimals] = await Promise.all([
|
|
2062
|
+
vault.name(),
|
|
2063
|
+
vault.symbol(),
|
|
2064
|
+
vault.asset(),
|
|
2065
|
+
vault.totalAssets(),
|
|
2066
|
+
vault.totalSupply(),
|
|
2067
|
+
vault.decimals()
|
|
2068
|
+
]);
|
|
2069
|
+
const sharePrice = totalSupply > 0n ? ethers7.formatUnits(totalAssets * 10n ** BigInt(decimals) / totalSupply, decimals) : "1.0";
|
|
2070
|
+
const result = {
|
|
2071
|
+
name,
|
|
2072
|
+
symbol,
|
|
2073
|
+
asset,
|
|
2074
|
+
totalAssets: ethers7.formatUnits(totalAssets, decimals),
|
|
2075
|
+
totalSupply: ethers7.formatUnits(totalSupply, decimals),
|
|
2076
|
+
sharePrice
|
|
2077
|
+
};
|
|
2078
|
+
if (wallet) {
|
|
2079
|
+
const shares = await vault.balanceOf(wallet);
|
|
2080
|
+
const assets = shares > 0n ? await vault.convertToAssets(shares) : 0n;
|
|
2081
|
+
result.userShares = ethers7.formatUnits(shares, decimals);
|
|
2082
|
+
result.userAssets = ethers7.formatUnits(assets, decimals);
|
|
2083
|
+
}
|
|
2084
|
+
return result;
|
|
2085
|
+
}
|
|
2086
|
+
/** Quote vault deposit — how many shares for given assets */
|
|
2087
|
+
async vaultDepositQuote(vaultAddress, amount) {
|
|
2088
|
+
const vault = new ethers7.Contract(ethers7.getAddress(vaultAddress), VAULT_ABI, this.provider);
|
|
2089
|
+
const decimals = Number(await vault.decimals());
|
|
2090
|
+
const assetsWei = ethers7.parseUnits(amount, decimals);
|
|
2091
|
+
const shares = await vault.previewDeposit(assetsWei);
|
|
2092
|
+
return { assetsIn: amount, sharesOut: ethers7.formatUnits(shares, decimals) };
|
|
2093
|
+
}
|
|
2094
|
+
/** Build txs to deposit into an ERC-4626 vault: [approve, deposit] */
|
|
2095
|
+
async buildVaultDeposit(wallet, vaultAddress, amount) {
|
|
2096
|
+
const vaultAddr = ethers7.getAddress(vaultAddress);
|
|
2097
|
+
const vault = new ethers7.Contract(vaultAddr, VAULT_ABI, this.provider);
|
|
2098
|
+
const assetAddr = await vault.asset();
|
|
2099
|
+
const assetToken = new ethers7.Contract(assetAddr, ERC20_ABI2, this.provider);
|
|
2100
|
+
const decimals = Number(await assetToken.decimals());
|
|
2101
|
+
let depositAmount;
|
|
2102
|
+
if (amount === "max") {
|
|
2103
|
+
depositAmount = await assetToken.balanceOf(wallet);
|
|
2104
|
+
} else {
|
|
2105
|
+
depositAmount = ethers7.parseUnits(amount, decimals);
|
|
2106
|
+
}
|
|
2107
|
+
if (depositAmount === 0n) throw new Error("Zero balance to deposit");
|
|
2108
|
+
const erc20Iface = new ethers7.Interface(ERC20_ABI2);
|
|
2109
|
+
const approveData = erc20Iface.encodeFunctionData("approve", [vaultAddr, depositAmount]);
|
|
2110
|
+
const vaultIface = new ethers7.Interface(VAULT_ABI);
|
|
2111
|
+
const depositData = vaultIface.encodeFunctionData("deposit", [depositAmount, wallet]);
|
|
2112
|
+
return {
|
|
2113
|
+
transactions: [
|
|
2114
|
+
{ to: assetAddr, data: approveData, value: "0", chainId: CHAIN_ID, gasLimit: "60000", description: `Approve asset for vault deposit` },
|
|
2115
|
+
{ to: vaultAddr, data: depositData, value: "0", chainId: CHAIN_ID, gasLimit: "300000", description: `Deposit ${ethers7.formatUnits(depositAmount, decimals)} into vault` }
|
|
2116
|
+
]
|
|
2117
|
+
};
|
|
2118
|
+
}
|
|
2119
|
+
/** Build tx to withdraw from an ERC-4626 vault */
|
|
2120
|
+
async buildVaultWithdraw(wallet, vaultAddress, amount) {
|
|
2121
|
+
const vaultAddr = ethers7.getAddress(vaultAddress);
|
|
2122
|
+
const vault = new ethers7.Contract(vaultAddr, VAULT_ABI, this.provider);
|
|
2123
|
+
const decimals = Number(await vault.decimals());
|
|
2124
|
+
let withdrawAmount;
|
|
2125
|
+
if (amount === "max") {
|
|
2126
|
+
const shares = await vault.balanceOf(wallet);
|
|
2127
|
+
withdrawAmount = await vault.convertToAssets(shares);
|
|
2128
|
+
} else {
|
|
2129
|
+
withdrawAmount = ethers7.parseUnits(amount, decimals);
|
|
2130
|
+
}
|
|
2131
|
+
if (withdrawAmount === 0n) throw new Error("Nothing to withdraw");
|
|
2132
|
+
const iface = new ethers7.Interface(VAULT_ABI);
|
|
2133
|
+
const data = iface.encodeFunctionData("withdraw", [withdrawAmount, wallet, wallet]);
|
|
2134
|
+
return {
|
|
2135
|
+
transactions: [{
|
|
2136
|
+
to: vaultAddr,
|
|
2137
|
+
data,
|
|
2138
|
+
value: "0",
|
|
2139
|
+
chainId: CHAIN_ID,
|
|
2140
|
+
gasLimit: "300000",
|
|
2141
|
+
description: `Withdraw ${ethers7.formatUnits(withdrawAmount, decimals)} from vault`
|
|
2142
|
+
}]
|
|
2143
|
+
};
|
|
2144
|
+
}
|
|
2145
|
+
};
|
|
2146
|
+
|
|
2147
|
+
// src/client.ts
|
|
2148
|
+
var Logiqical = class _Logiqical {
|
|
2149
|
+
/** Buy/sell ARENA tokens via LFJ DEX */
|
|
2150
|
+
swap;
|
|
2151
|
+
/** Stake ARENA tokens for rewards */
|
|
2152
|
+
staking;
|
|
2153
|
+
/** Discover, research, and trade launchpad tokens on bonding curves */
|
|
2154
|
+
launchpad;
|
|
2155
|
+
/** Swap any Avalanche token via LFJ DEX */
|
|
2156
|
+
dex;
|
|
2157
|
+
/** Trade perpetual futures on Hyperliquid via Arena */
|
|
2158
|
+
perps;
|
|
2159
|
+
/** Cross-chain token bridging via Li.Fi */
|
|
2160
|
+
bridge;
|
|
2161
|
+
/** Buy/sell Arena tickets */
|
|
2162
|
+
tickets;
|
|
2163
|
+
/** Arena social: chat, DMs, posts, follow, user discovery */
|
|
2164
|
+
social;
|
|
2165
|
+
/** Market signals intelligence — scan, funding rates, whale tracking */
|
|
2166
|
+
signals;
|
|
2167
|
+
/** Market data — prices, trending, top coins via CoinGecko */
|
|
2168
|
+
market;
|
|
2169
|
+
/** DeFi — sAVAX liquid staking + ERC-4626 vaults */
|
|
2170
|
+
defi;
|
|
2171
|
+
/** The agent's wallet address */
|
|
2172
|
+
address;
|
|
2173
|
+
/** The local wallet (null if read-only mode) */
|
|
2174
|
+
agentWallet;
|
|
2175
|
+
/** The JSON-RPC provider for direct chain reads */
|
|
2176
|
+
provider;
|
|
2177
|
+
/** The spending policy engine */
|
|
2178
|
+
policyEngine;
|
|
2179
|
+
config;
|
|
2180
|
+
constructor(config) {
|
|
2181
|
+
this.config = config;
|
|
2182
|
+
this.policyEngine = new PolicyEngine(config.policy);
|
|
2183
|
+
if (config.privateKey) {
|
|
2184
|
+
this.agentWallet = AgentWallet.fromPrivateKey(config.privateKey, {
|
|
2185
|
+
network: config.network,
|
|
2186
|
+
rpcUrl: config.rpcUrl
|
|
2187
|
+
});
|
|
2188
|
+
this.provider = this.agentWallet.provider;
|
|
2189
|
+
this.address = this.agentWallet.address;
|
|
2190
|
+
} else if (config.mnemonic) {
|
|
2191
|
+
const hdWallet = ethers8.HDNodeWallet.fromPhrase(config.mnemonic);
|
|
2192
|
+
this.agentWallet = AgentWallet.fromPrivateKey(hdWallet.privateKey, {
|
|
2193
|
+
network: config.network,
|
|
2194
|
+
rpcUrl: config.rpcUrl
|
|
2195
|
+
});
|
|
2196
|
+
this.provider = this.agentWallet.provider;
|
|
2197
|
+
this.address = this.agentWallet.address;
|
|
2198
|
+
} else if (config.wallet) {
|
|
2199
|
+
this.agentWallet = null;
|
|
2200
|
+
const { provider } = _Logiqical.resolveProvider(config);
|
|
2201
|
+
this.provider = provider;
|
|
2202
|
+
this.address = config.wallet;
|
|
2203
|
+
} else {
|
|
2204
|
+
throw new Error("Provide privateKey, mnemonic, or wallet (read-only).");
|
|
2205
|
+
}
|
|
2206
|
+
this.swap = new SwapModule(this.provider);
|
|
2207
|
+
this.staking = new StakingModule(this.provider);
|
|
2208
|
+
this.launchpad = new LaunchpadModule(this.provider);
|
|
2209
|
+
this.dex = new DexModule(this.provider);
|
|
2210
|
+
this.tickets = new TicketsModule(this.provider);
|
|
2211
|
+
this.perps = new PerpsModule(config.arenaApiKey);
|
|
2212
|
+
this.social = new SocialModule(config.arenaApiKey);
|
|
2213
|
+
this.bridge = new BridgeModule();
|
|
2214
|
+
this.signals = new SignalsModule();
|
|
2215
|
+
this.market = new MarketModule();
|
|
2216
|
+
this.defi = new DefiModule(this.provider);
|
|
2217
|
+
}
|
|
2218
|
+
// ── Factory Methods ──
|
|
2219
|
+
/** Generate a brand new agent wallet */
|
|
2220
|
+
static generate(config = {}) {
|
|
2221
|
+
const wallet = AgentWallet.generate({ network: config.network, rpcUrl: config.rpcUrl });
|
|
2222
|
+
return new _Logiqical({ ...config, privateKey: wallet.privateKey });
|
|
2223
|
+
}
|
|
2224
|
+
/** Boot from encrypted keystore — creates wallet on first run, loads on subsequent runs */
|
|
2225
|
+
static async boot(config = {}) {
|
|
2226
|
+
const wallet = await AgentWallet.boot({
|
|
2227
|
+
network: config.network,
|
|
2228
|
+
rpcUrl: config.rpcUrl,
|
|
2229
|
+
password: config.password,
|
|
2230
|
+
keystoreName: config.keystoreName
|
|
2231
|
+
});
|
|
2232
|
+
return new _Logiqical({ ...config, privateKey: wallet.privateKey });
|
|
2233
|
+
}
|
|
2234
|
+
// ── Core Agent Operations ──
|
|
2235
|
+
/**
|
|
2236
|
+
* Execute any module result — policy check + simulate + sign + broadcast.
|
|
2237
|
+
*
|
|
2238
|
+
* ```ts
|
|
2239
|
+
* await agent.execute(agent.dex.buildSwap(agent.address, "AVAX", "USDC", "1.0"));
|
|
2240
|
+
* await agent.execute(agent.launchpad.buildBuy(agent.address, "42", "0.5"));
|
|
2241
|
+
* ```
|
|
2242
|
+
*/
|
|
2243
|
+
async execute(resultOrPromise, confirmations = 1) {
|
|
2244
|
+
this.requireWallet("execute");
|
|
2245
|
+
const result = await resultOrPromise;
|
|
2246
|
+
const txs = result.transactions ?? (result.transaction ? [result.transaction] : []);
|
|
2247
|
+
if (txs.length === 0) throw new Error("No transactions to execute.");
|
|
2248
|
+
const results = [];
|
|
2249
|
+
for (const utx of txs) {
|
|
2250
|
+
this.policyEngine.check(utx);
|
|
2251
|
+
if (this.policyEngine.shouldSimulate) {
|
|
2252
|
+
await this.simulate(utx);
|
|
2253
|
+
}
|
|
2254
|
+
if (this.policyEngine.isDryRun) {
|
|
2255
|
+
results.push({
|
|
2256
|
+
hash: "0x_dry_run",
|
|
2257
|
+
receipt: { status: 1, blockNumber: 0, gasUsed: "0", transactionHash: "0x_dry_run" }
|
|
2258
|
+
});
|
|
2259
|
+
continue;
|
|
2260
|
+
}
|
|
2261
|
+
const txResponse = await this.agentWallet.signAndBroadcast(utx);
|
|
2262
|
+
const receipt = await txResponse.wait(confirmations);
|
|
2263
|
+
if (!receipt) throw new Error(`Transaction ${txResponse.hash} failed \u2014 no receipt.`);
|
|
2264
|
+
const value = utx.value ? BigInt(utx.value) : 0n;
|
|
2265
|
+
if (value > 0n) this.policyEngine.recordSpend(value);
|
|
2266
|
+
results.push({
|
|
2267
|
+
hash: txResponse.hash,
|
|
2268
|
+
receipt: {
|
|
2269
|
+
status: receipt.status ?? 0,
|
|
2270
|
+
blockNumber: receipt.blockNumber,
|
|
2271
|
+
gasUsed: receipt.gasUsed.toString(),
|
|
2272
|
+
transactionHash: receipt.hash
|
|
2273
|
+
}
|
|
2274
|
+
});
|
|
2275
|
+
}
|
|
2276
|
+
return results;
|
|
2277
|
+
}
|
|
2278
|
+
/**
|
|
2279
|
+
* Call any smart contract method — policy check + simulate + sign + broadcast.
|
|
2280
|
+
*
|
|
2281
|
+
* ```ts
|
|
2282
|
+
* await agent.call({
|
|
2283
|
+
* contract: "0x...",
|
|
2284
|
+
* abi: ["function transfer(address,uint256) returns (bool)"],
|
|
2285
|
+
* method: "transfer",
|
|
2286
|
+
* args: ["0xRecipient", ethers.parseUnits("100", 18)],
|
|
2287
|
+
* });
|
|
2288
|
+
* ```
|
|
2289
|
+
*/
|
|
2290
|
+
async call(intent) {
|
|
2291
|
+
this.requireWallet("call");
|
|
2292
|
+
const iface = new ethers8.Interface(intent.abi);
|
|
2293
|
+
const data = iface.encodeFunctionData(intent.method, intent.args ?? []);
|
|
2294
|
+
const valueWei = intent.value ? ethers8.parseEther(intent.value).toString() : "0";
|
|
2295
|
+
const policyTx = { to: intent.contract, data, value: valueWei, chainId: 43114 };
|
|
2296
|
+
this.policyEngine.check(policyTx);
|
|
2297
|
+
if (this.policyEngine.shouldSimulate) {
|
|
2298
|
+
await this.simulate(policyTx);
|
|
2299
|
+
}
|
|
2300
|
+
if (this.policyEngine.isDryRun) {
|
|
2301
|
+
return { hash: "0x_dry_run", receipt: { status: 1, blockNumber: 0, gasUsed: "0", transactionHash: "0x_dry_run" } };
|
|
2302
|
+
}
|
|
2303
|
+
const contract = new Contract(
|
|
2304
|
+
ethers8.getAddress(intent.contract),
|
|
2305
|
+
intent.abi,
|
|
2306
|
+
this.agentWallet.wallet
|
|
2307
|
+
);
|
|
2308
|
+
const tx = await contract[intent.method](
|
|
2309
|
+
...intent.args ?? [],
|
|
2310
|
+
{
|
|
2311
|
+
value: intent.value ? ethers8.parseEther(intent.value) : void 0,
|
|
2312
|
+
gasLimit: intent.gasLimit ?? void 0
|
|
2313
|
+
}
|
|
2314
|
+
);
|
|
2315
|
+
const receipt = await tx.wait(1);
|
|
2316
|
+
if (!receipt) throw new Error(`Transaction ${tx.hash} failed \u2014 no receipt.`);
|
|
2317
|
+
if (intent.value) {
|
|
2318
|
+
this.policyEngine.recordSpend(ethers8.parseEther(intent.value));
|
|
2319
|
+
}
|
|
2320
|
+
return {
|
|
2321
|
+
hash: tx.hash,
|
|
2322
|
+
receipt: {
|
|
2323
|
+
status: receipt.status ?? 0,
|
|
2324
|
+
blockNumber: receipt.blockNumber,
|
|
2325
|
+
gasUsed: receipt.gasUsed.toString(),
|
|
2326
|
+
transactionHash: receipt.hash
|
|
2327
|
+
}
|
|
2328
|
+
};
|
|
2329
|
+
}
|
|
2330
|
+
/** Send native token (AVAX) — policy check + simulate + sign + broadcast */
|
|
2331
|
+
async send(to, amount) {
|
|
2332
|
+
this.requireWallet("send");
|
|
2333
|
+
const valueWei = ethers8.parseEther(amount);
|
|
2334
|
+
const policyTx = { to, data: "0x", value: valueWei.toString(), chainId: 43114 };
|
|
2335
|
+
this.policyEngine.check(policyTx);
|
|
2336
|
+
if (this.policyEngine.isDryRun) {
|
|
2337
|
+
return { hash: "0x_dry_run", receipt: { status: 1, blockNumber: 0, gasUsed: "0", transactionHash: "0x_dry_run" } };
|
|
2338
|
+
}
|
|
2339
|
+
const tx = await this.agentWallet.send(to, amount);
|
|
2340
|
+
const receipt = await tx.wait(1);
|
|
2341
|
+
if (!receipt) throw new Error(`Transaction ${tx.hash} failed \u2014 no receipt.`);
|
|
2342
|
+
this.policyEngine.recordSpend(valueWei);
|
|
2343
|
+
return {
|
|
2344
|
+
hash: tx.hash,
|
|
2345
|
+
receipt: {
|
|
2346
|
+
status: receipt.status ?? 0,
|
|
2347
|
+
blockNumber: receipt.blockNumber,
|
|
2348
|
+
gasUsed: receipt.gasUsed.toString(),
|
|
2349
|
+
transactionHash: receipt.hash
|
|
2350
|
+
}
|
|
2351
|
+
};
|
|
2352
|
+
}
|
|
2353
|
+
/** Simulate a transaction via eth_call — throws PolicyError if it would revert */
|
|
2354
|
+
async simulate(tx) {
|
|
2355
|
+
try {
|
|
2356
|
+
await this.provider.call({
|
|
2357
|
+
to: tx.to,
|
|
2358
|
+
data: tx.data,
|
|
2359
|
+
value: tx.value ? BigInt(tx.value) : void 0,
|
|
2360
|
+
from: this.address
|
|
2361
|
+
});
|
|
2362
|
+
} catch (e) {
|
|
2363
|
+
throw new PolicyError(
|
|
2364
|
+
`Simulation failed: ${e.reason || e.message || "transaction would revert"}`,
|
|
2365
|
+
"SIMULATION_FAILED"
|
|
2366
|
+
);
|
|
2367
|
+
}
|
|
2368
|
+
}
|
|
2369
|
+
// ── Policy ──
|
|
2370
|
+
/** Get the current spending policy */
|
|
2371
|
+
getPolicy() {
|
|
2372
|
+
return this.policyEngine.getPolicy();
|
|
2373
|
+
}
|
|
2374
|
+
/** Replace the entire spending policy */
|
|
2375
|
+
setPolicy(policy) {
|
|
2376
|
+
this.policyEngine.setPolicy(policy);
|
|
2377
|
+
}
|
|
2378
|
+
/** Update specific policy fields */
|
|
2379
|
+
updatePolicy(updates) {
|
|
2380
|
+
this.policyEngine.updatePolicy(updates);
|
|
2381
|
+
}
|
|
2382
|
+
/** Get budget status: spent this hour, today, remaining */
|
|
2383
|
+
getBudgetStatus() {
|
|
2384
|
+
return this.policyEngine.getBudgetStatus();
|
|
2385
|
+
}
|
|
2386
|
+
// ── Read Operations (no signing needed) ──
|
|
2387
|
+
/** Check if this client has a local wallet for signing */
|
|
2388
|
+
get canSign() {
|
|
2389
|
+
return this.agentWallet !== null;
|
|
2390
|
+
}
|
|
2391
|
+
/** The private key (only available in wallet mode) */
|
|
2392
|
+
get privateKey() {
|
|
2393
|
+
this.requireWallet("privateKey");
|
|
2394
|
+
return this.agentWallet.privateKey;
|
|
2395
|
+
}
|
|
2396
|
+
/** Get native token balance (formatted) */
|
|
2397
|
+
async getBalance() {
|
|
2398
|
+
if (this.agentWallet) return this.agentWallet.getBalance();
|
|
2399
|
+
const balance = await this.provider.getBalance(this.address);
|
|
2400
|
+
return ethers8.formatEther(balance);
|
|
2401
|
+
}
|
|
2402
|
+
/** Sign a message */
|
|
2403
|
+
async signMessage(message) {
|
|
2404
|
+
this.requireWallet("signMessage");
|
|
2405
|
+
return this.agentWallet.signMessage(message);
|
|
2406
|
+
}
|
|
2407
|
+
/** Sign EIP-712 typed data */
|
|
2408
|
+
async signTypedData(domain, types, value) {
|
|
2409
|
+
this.requireWallet("signTypedData");
|
|
2410
|
+
return this.agentWallet.signTypedData(domain, types, value);
|
|
2411
|
+
}
|
|
2412
|
+
/** Switch to a different network (returns new Logiqical instance with same keys) */
|
|
2413
|
+
switchNetwork(network) {
|
|
2414
|
+
this.requireWallet("switchNetwork");
|
|
2415
|
+
return new _Logiqical({
|
|
2416
|
+
...this.config,
|
|
2417
|
+
privateKey: this.agentWallet.privateKey,
|
|
2418
|
+
mnemonic: void 0,
|
|
2419
|
+
wallet: void 0,
|
|
2420
|
+
network
|
|
2421
|
+
});
|
|
2422
|
+
}
|
|
2423
|
+
/** Save the wallet to an encrypted keystore file */
|
|
2424
|
+
async saveKeystore(password, name) {
|
|
2425
|
+
this.requireWallet("saveKeystore");
|
|
2426
|
+
return this.agentWallet.saveKeystore(password, name);
|
|
2427
|
+
}
|
|
2428
|
+
// ── Low-level (advanced — bypasses policy) ──
|
|
2429
|
+
/** Sign and broadcast a single unsigned tx — bypasses policy engine */
|
|
2430
|
+
async signAndBroadcast(unsignedTx) {
|
|
2431
|
+
this.requireWallet("signAndBroadcast");
|
|
2432
|
+
return this.agentWallet.signAndBroadcast(unsignedTx);
|
|
2433
|
+
}
|
|
2434
|
+
/** Sign and broadcast multiple unsigned txs — bypasses policy engine */
|
|
2435
|
+
async signAndBroadcastAll(unsignedTxs, confirmations = 1) {
|
|
2436
|
+
this.requireWallet("signAndBroadcastAll");
|
|
2437
|
+
return this.agentWallet.signAndBroadcastAll(unsignedTxs, confirmations);
|
|
2438
|
+
}
|
|
2439
|
+
// ── Internal ──
|
|
2440
|
+
requireWallet(method) {
|
|
2441
|
+
if (!this.agentWallet) throw new Error(`No local wallet \u2014 cannot ${method}(). Provide privateKey or use Logiqical.boot().`);
|
|
2442
|
+
}
|
|
2443
|
+
static resolveProvider(config) {
|
|
2444
|
+
const networkKey = config.network ?? "avalanche";
|
|
2445
|
+
const chain = CHAINS[networkKey];
|
|
2446
|
+
if (!chain && !config.rpcUrl) {
|
|
2447
|
+
throw new Error(`Unknown network "${networkKey}". Use: ${Object.keys(CHAINS).join(", ")} \u2014 or provide rpcUrl.`);
|
|
2448
|
+
}
|
|
2449
|
+
const rpcUrl = config.rpcUrl ?? chain.rpcUrl;
|
|
2450
|
+
const chainId = chain?.chainId ?? void 0;
|
|
2451
|
+
return { provider: new JsonRpcProvider2(rpcUrl, chainId) };
|
|
2452
|
+
}
|
|
2453
|
+
};
|
|
2454
|
+
|
|
2455
|
+
// src/mcp/server.ts
|
|
2456
|
+
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
2457
|
+
import { z } from "zod";
|
|
2458
|
+
function ok(data) {
|
|
2459
|
+
return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
|
|
2460
|
+
}
|
|
2461
|
+
function err(e) {
|
|
2462
|
+
const msg = e instanceof Error ? e.message : String(e);
|
|
2463
|
+
return { content: [{ type: "text", text: `Error: ${msg}` }], isError: true };
|
|
2464
|
+
}
|
|
2465
|
+
function createMcpServer(agent) {
|
|
2466
|
+
const server = new McpServer({ name: "logiqical", version: "0.3.0" });
|
|
2467
|
+
const w = agent.address;
|
|
2468
|
+
server.tool("get_address", "Get the agent's wallet address", {}, async () => {
|
|
2469
|
+
return ok({ address: w, canSign: agent.canSign });
|
|
2470
|
+
});
|
|
2471
|
+
server.tool("get_balance", "Get native token balance (AVAX)", {}, async () => {
|
|
2472
|
+
try {
|
|
2473
|
+
return ok({ balance: await agent.getBalance(), token: "AVAX" });
|
|
2474
|
+
} catch (e) {
|
|
2475
|
+
return err(e);
|
|
2476
|
+
}
|
|
2477
|
+
});
|
|
2478
|
+
server.tool("send_avax", "Send AVAX to an address", {
|
|
2479
|
+
to: z.string().describe("Recipient address"),
|
|
2480
|
+
amount: z.string().describe("Amount of AVAX (e.g. '0.1')")
|
|
2481
|
+
}, async ({ to, amount }) => {
|
|
2482
|
+
try {
|
|
2483
|
+
return ok(await agent.send(to, amount));
|
|
2484
|
+
} catch (e) {
|
|
2485
|
+
return err(e);
|
|
2486
|
+
}
|
|
2487
|
+
});
|
|
2488
|
+
server.tool("sign_message", "Sign a message with the agent's wallet", {
|
|
2489
|
+
message: z.string().describe("Message to sign")
|
|
2490
|
+
}, async ({ message }) => {
|
|
2491
|
+
try {
|
|
2492
|
+
return ok({ signature: await agent.signMessage(message) });
|
|
2493
|
+
} catch (e) {
|
|
2494
|
+
return err(e);
|
|
2495
|
+
}
|
|
2496
|
+
});
|
|
2497
|
+
server.tool("get_balances", "Get AVAX and ARENA balances", {
|
|
2498
|
+
wallet: z.string().optional().describe("Wallet address (defaults to agent wallet)")
|
|
2499
|
+
}, async ({ wallet }) => {
|
|
2500
|
+
try {
|
|
2501
|
+
return ok(await agent.swap.getBalances(wallet || w));
|
|
2502
|
+
} catch (e) {
|
|
2503
|
+
return err(e);
|
|
2504
|
+
}
|
|
2505
|
+
});
|
|
2506
|
+
server.tool("swap_quote_buy", "Quote: how much ARENA for a given AVAX amount", {
|
|
2507
|
+
avax: z.string().describe("AVAX amount (e.g. '0.1')")
|
|
2508
|
+
}, async ({ avax }) => {
|
|
2509
|
+
try {
|
|
2510
|
+
return ok(await agent.swap.quote(avax));
|
|
2511
|
+
} catch (e) {
|
|
2512
|
+
return err(e);
|
|
2513
|
+
}
|
|
2514
|
+
});
|
|
2515
|
+
server.tool("swap_quote_sell", "Quote: how much AVAX for selling ARENA", {
|
|
2516
|
+
arena: z.string().describe("ARENA amount")
|
|
2517
|
+
}, async ({ arena }) => {
|
|
2518
|
+
try {
|
|
2519
|
+
return ok(await agent.swap.sellQuote(arena));
|
|
2520
|
+
} catch (e) {
|
|
2521
|
+
return err(e);
|
|
2522
|
+
}
|
|
2523
|
+
});
|
|
2524
|
+
server.tool("swap_buy_arena", "Buy ARENA with AVAX \u2014 signs and broadcasts", {
|
|
2525
|
+
avax: z.string().describe("AVAX to spend"),
|
|
2526
|
+
slippage: z.number().optional().describe("Slippage bps (default 500)")
|
|
2527
|
+
}, async ({ avax, slippage }) => {
|
|
2528
|
+
try {
|
|
2529
|
+
return ok(await agent.execute(agent.swap.buildBuy(w, avax, slippage)));
|
|
2530
|
+
} catch (e) {
|
|
2531
|
+
return err(e);
|
|
2532
|
+
}
|
|
2533
|
+
});
|
|
2534
|
+
server.tool("swap_sell_arena", "Sell ARENA for AVAX \u2014 signs and broadcasts", {
|
|
2535
|
+
amount: z.string().describe("ARENA to sell, or 'max'"),
|
|
2536
|
+
slippage: z.number().optional().describe("Slippage bps (default 500)")
|
|
2537
|
+
}, async ({ amount, slippage }) => {
|
|
2538
|
+
try {
|
|
2539
|
+
return ok(await agent.execute(agent.swap.buildSell(w, amount, slippage)));
|
|
2540
|
+
} catch (e) {
|
|
2541
|
+
return err(e);
|
|
2542
|
+
}
|
|
2543
|
+
});
|
|
2544
|
+
server.tool("stake_info", "Get staking position: staked amount + pending rewards", {
|
|
2545
|
+
wallet: z.string().optional().describe("Wallet address")
|
|
2546
|
+
}, async ({ wallet }) => {
|
|
2547
|
+
try {
|
|
2548
|
+
return ok(await agent.staking.getInfo(wallet || w));
|
|
2549
|
+
} catch (e) {
|
|
2550
|
+
return err(e);
|
|
2551
|
+
}
|
|
2552
|
+
});
|
|
2553
|
+
server.tool("stake_arena", "Stake ARENA tokens \u2014 signs and broadcasts", {
|
|
2554
|
+
amount: z.string().describe("ARENA to stake, or 'max'")
|
|
2555
|
+
}, async ({ amount }) => {
|
|
2556
|
+
try {
|
|
2557
|
+
return ok(await agent.execute(agent.staking.buildStake(w, amount)));
|
|
2558
|
+
} catch (e) {
|
|
2559
|
+
return err(e);
|
|
2560
|
+
}
|
|
2561
|
+
});
|
|
2562
|
+
server.tool("unstake_arena", "Unstake ARENA + claim rewards \u2014 signs and broadcasts", {
|
|
2563
|
+
amount: z.string().describe("ARENA to unstake, or 'max'")
|
|
2564
|
+
}, async ({ amount }) => {
|
|
2565
|
+
try {
|
|
2566
|
+
return ok(await agent.execute(agent.staking.buildUnstake(w, amount)));
|
|
2567
|
+
} catch (e) {
|
|
2568
|
+
return err(e);
|
|
2569
|
+
}
|
|
2570
|
+
});
|
|
2571
|
+
server.tool("buy_and_stake", "Buy ARENA with AVAX and stake in one flow \u2014 signs and broadcasts", {
|
|
2572
|
+
avax: z.string().describe("AVAX to spend")
|
|
2573
|
+
}, async ({ avax }) => {
|
|
2574
|
+
try {
|
|
2575
|
+
return ok(await agent.execute(agent.staking.buildBuyAndStake(w, avax)));
|
|
2576
|
+
} catch (e) {
|
|
2577
|
+
return err(e);
|
|
2578
|
+
}
|
|
2579
|
+
});
|
|
2580
|
+
server.tool("dex_tokens", "List known tokens available for swapping on Avalanche", {}, async () => {
|
|
2581
|
+
try {
|
|
2582
|
+
return ok(agent.dex.getTokens());
|
|
2583
|
+
} catch (e) {
|
|
2584
|
+
return err(e);
|
|
2585
|
+
}
|
|
2586
|
+
});
|
|
2587
|
+
server.tool("dex_token_info", "Look up any ERC-20 token by address", {
|
|
2588
|
+
address: z.string().describe("Token contract address")
|
|
2589
|
+
}, async ({ address }) => {
|
|
2590
|
+
try {
|
|
2591
|
+
return ok(await agent.dex.getTokenInfo(address));
|
|
2592
|
+
} catch (e) {
|
|
2593
|
+
return err(e);
|
|
2594
|
+
}
|
|
2595
|
+
});
|
|
2596
|
+
server.tool("dex_balance", "Check balance of any token", {
|
|
2597
|
+
token: z.string().describe("Token symbol (USDC, JOE) or address"),
|
|
2598
|
+
wallet: z.string().optional().describe("Wallet address")
|
|
2599
|
+
}, async ({ token, wallet }) => {
|
|
2600
|
+
try {
|
|
2601
|
+
return ok(await agent.dex.getBalance(wallet || w, token));
|
|
2602
|
+
} catch (e) {
|
|
2603
|
+
return err(e);
|
|
2604
|
+
}
|
|
2605
|
+
});
|
|
2606
|
+
server.tool("dex_quote", "Get a swap quote between any two tokens", {
|
|
2607
|
+
from: z.string().describe("Source token"),
|
|
2608
|
+
to: z.string().describe("Destination token"),
|
|
2609
|
+
amount: z.string().describe("Amount of source token")
|
|
2610
|
+
}, async ({ from, to, amount }) => {
|
|
2611
|
+
try {
|
|
2612
|
+
return ok(await agent.dex.quote(from, to, amount));
|
|
2613
|
+
} catch (e) {
|
|
2614
|
+
return err(e);
|
|
2615
|
+
}
|
|
2616
|
+
});
|
|
2617
|
+
server.tool("dex_swap", "Swap any tokens \u2014 signs and broadcasts", {
|
|
2618
|
+
from: z.string().describe("Source token"),
|
|
2619
|
+
to: z.string().describe("Destination token"),
|
|
2620
|
+
amount: z.string().describe("Amount to swap, or 'max'"),
|
|
2621
|
+
slippage: z.number().optional().describe("Slippage bps (default 500)")
|
|
2622
|
+
}, async ({ from, to, amount, slippage }) => {
|
|
2623
|
+
try {
|
|
2624
|
+
return ok(await agent.execute(agent.dex.buildSwap(w, from, to, amount, slippage)));
|
|
2625
|
+
} catch (e) {
|
|
2626
|
+
return err(e);
|
|
2627
|
+
}
|
|
2628
|
+
});
|
|
2629
|
+
server.tool("launchpad_overview", "Get platform overview: total tokens, fees, contracts", {}, async () => {
|
|
2630
|
+
try {
|
|
2631
|
+
return ok(await agent.launchpad.getOverview());
|
|
2632
|
+
} catch (e) {
|
|
2633
|
+
return err(e);
|
|
2634
|
+
}
|
|
2635
|
+
});
|
|
2636
|
+
server.tool("launchpad_recent", "Get recently launched tokens", {
|
|
2637
|
+
count: z.number().optional().describe("Number of tokens (default 10)")
|
|
2638
|
+
}, async ({ count }) => {
|
|
2639
|
+
try {
|
|
2640
|
+
return ok(await agent.launchpad.getRecent(count));
|
|
2641
|
+
} catch (e) {
|
|
2642
|
+
return err(e);
|
|
2643
|
+
}
|
|
2644
|
+
});
|
|
2645
|
+
server.tool("launchpad_token", "Get full token info by ID", {
|
|
2646
|
+
tokenId: z.string().describe("Token ID")
|
|
2647
|
+
}, async ({ tokenId }) => {
|
|
2648
|
+
try {
|
|
2649
|
+
return ok(await agent.launchpad.getToken(tokenId));
|
|
2650
|
+
} catch (e) {
|
|
2651
|
+
return err(e);
|
|
2652
|
+
}
|
|
2653
|
+
});
|
|
2654
|
+
server.tool("launchpad_quote", "Get buy or sell quote for a launchpad token", {
|
|
2655
|
+
tokenId: z.string().describe("Token ID"),
|
|
2656
|
+
side: z.enum(["buy", "sell"]).describe("Trade side"),
|
|
2657
|
+
amount: z.string().describe("AVAX amount (buy) or token amount (sell)")
|
|
2658
|
+
}, async ({ tokenId, side, amount }) => {
|
|
2659
|
+
try {
|
|
2660
|
+
return ok(await agent.launchpad.quote(tokenId, side, amount));
|
|
2661
|
+
} catch (e) {
|
|
2662
|
+
return err(e);
|
|
2663
|
+
}
|
|
2664
|
+
});
|
|
2665
|
+
server.tool("launchpad_buy", "Buy a launchpad token \u2014 signs and broadcasts", {
|
|
2666
|
+
tokenId: z.string().describe("Token ID"),
|
|
2667
|
+
avax: z.string().describe("AVAX to spend"),
|
|
2668
|
+
slippage: z.number().optional().describe("Slippage bps")
|
|
2669
|
+
}, async ({ tokenId, avax, slippage }) => {
|
|
2670
|
+
try {
|
|
2671
|
+
return ok(await agent.execute(agent.launchpad.buildBuy(w, tokenId, avax, slippage)));
|
|
2672
|
+
} catch (e) {
|
|
2673
|
+
return err(e);
|
|
2674
|
+
}
|
|
2675
|
+
});
|
|
2676
|
+
server.tool("launchpad_sell", "Sell a launchpad token \u2014 signs and broadcasts", {
|
|
2677
|
+
tokenId: z.string().describe("Token ID"),
|
|
2678
|
+
amount: z.string().describe("Token amount, or 'max'"),
|
|
2679
|
+
slippage: z.number().optional().describe("Slippage bps")
|
|
2680
|
+
}, async ({ tokenId, amount, slippage }) => {
|
|
2681
|
+
try {
|
|
2682
|
+
return ok(await agent.execute(agent.launchpad.buildSell(w, tokenId, amount, slippage)));
|
|
2683
|
+
} catch (e) {
|
|
2684
|
+
return err(e);
|
|
2685
|
+
}
|
|
2686
|
+
});
|
|
2687
|
+
server.tool("tickets_buy_price", "Get buy price for Arena tickets", {
|
|
2688
|
+
subject: z.string().describe("Subject wallet address"),
|
|
2689
|
+
amount: z.string().optional().describe("Tickets (default 1, supports 0.5)")
|
|
2690
|
+
}, async ({ subject, amount }) => {
|
|
2691
|
+
try {
|
|
2692
|
+
return ok(await agent.tickets.getBuyPrice(subject, amount));
|
|
2693
|
+
} catch (e) {
|
|
2694
|
+
return err(e);
|
|
2695
|
+
}
|
|
2696
|
+
});
|
|
2697
|
+
server.tool("tickets_sell_price", "Get sell price for Arena tickets", {
|
|
2698
|
+
subject: z.string().describe("Subject wallet address"),
|
|
2699
|
+
amount: z.string().optional().describe("Tickets (default 1)")
|
|
2700
|
+
}, async ({ subject, amount }) => {
|
|
2701
|
+
try {
|
|
2702
|
+
return ok(await agent.tickets.getSellPrice(subject, amount));
|
|
2703
|
+
} catch (e) {
|
|
2704
|
+
return err(e);
|
|
2705
|
+
}
|
|
2706
|
+
});
|
|
2707
|
+
server.tool("tickets_balance", "Get ticket balance", {
|
|
2708
|
+
subject: z.string().describe("Subject wallet"),
|
|
2709
|
+
user: z.string().optional().describe("User wallet")
|
|
2710
|
+
}, async ({ subject, user }) => {
|
|
2711
|
+
try {
|
|
2712
|
+
return ok(await agent.tickets.getBalance(subject, user || w));
|
|
2713
|
+
} catch (e) {
|
|
2714
|
+
return err(e);
|
|
2715
|
+
}
|
|
2716
|
+
});
|
|
2717
|
+
server.tool("tickets_supply", "Get total ticket supply for a subject", {
|
|
2718
|
+
subject: z.string().describe("Subject wallet")
|
|
2719
|
+
}, async ({ subject }) => {
|
|
2720
|
+
try {
|
|
2721
|
+
return ok(await agent.tickets.getSupply(subject));
|
|
2722
|
+
} catch (e) {
|
|
2723
|
+
return err(e);
|
|
2724
|
+
}
|
|
2725
|
+
});
|
|
2726
|
+
server.tool("tickets_fees", "Get ticket fee structure", {}, async () => {
|
|
2727
|
+
try {
|
|
2728
|
+
return ok(await agent.tickets.getFees());
|
|
2729
|
+
} catch (e) {
|
|
2730
|
+
return err(e);
|
|
2731
|
+
}
|
|
2732
|
+
});
|
|
2733
|
+
server.tool("tickets_buy", "Buy Arena tickets \u2014 signs and broadcasts", {
|
|
2734
|
+
subject: z.string().describe("Subject wallet"),
|
|
2735
|
+
amount: z.string().optional().describe("Tickets (default 1)")
|
|
2736
|
+
}, async ({ subject, amount }) => {
|
|
2737
|
+
try {
|
|
2738
|
+
return ok(await agent.execute(agent.tickets.buildBuyTx(w, subject, amount)));
|
|
2739
|
+
} catch (e) {
|
|
2740
|
+
return err(e);
|
|
2741
|
+
}
|
|
2742
|
+
});
|
|
2743
|
+
server.tool("tickets_sell", "Sell Arena tickets \u2014 signs and broadcasts", {
|
|
2744
|
+
subject: z.string().describe("Subject wallet"),
|
|
2745
|
+
amount: z.string().optional().describe("Tickets (default 1)")
|
|
2746
|
+
}, async ({ subject, amount }) => {
|
|
2747
|
+
try {
|
|
2748
|
+
return ok(await agent.execute(agent.tickets.buildSellTx(w, subject, amount)));
|
|
2749
|
+
} catch (e) {
|
|
2750
|
+
return err(e);
|
|
2751
|
+
}
|
|
2752
|
+
});
|
|
2753
|
+
server.tool("bridge_info", "Get supported chains, USDC addresses, native token constant", {}, async () => {
|
|
2754
|
+
try {
|
|
2755
|
+
return ok(agent.bridge.getInfo());
|
|
2756
|
+
} catch (e) {
|
|
2757
|
+
return err(e);
|
|
2758
|
+
}
|
|
2759
|
+
});
|
|
2760
|
+
server.tool("bridge_chains", "Get all supported chains for bridging", {}, async () => {
|
|
2761
|
+
try {
|
|
2762
|
+
return ok(await agent.bridge.getChains());
|
|
2763
|
+
} catch (e) {
|
|
2764
|
+
return err(e);
|
|
2765
|
+
}
|
|
2766
|
+
});
|
|
2767
|
+
server.tool("bridge_tokens", "Get tokens available on specified chains", {
|
|
2768
|
+
chains: z.string().describe("Comma-separated chain IDs (e.g. '43114,42161')")
|
|
2769
|
+
}, async ({ chains }) => {
|
|
2770
|
+
try {
|
|
2771
|
+
return ok(await agent.bridge.getTokens(chains));
|
|
2772
|
+
} catch (e) {
|
|
2773
|
+
return err(e);
|
|
2774
|
+
}
|
|
2775
|
+
});
|
|
2776
|
+
server.tool("bridge_quote", "Get a cross-chain bridge quote with transaction", {
|
|
2777
|
+
fromChainId: z.number().describe("Source chain ID"),
|
|
2778
|
+
toChainId: z.number().describe("Destination chain ID"),
|
|
2779
|
+
fromToken: z.string().describe("Source token address"),
|
|
2780
|
+
toToken: z.string().describe("Destination token address"),
|
|
2781
|
+
fromAmount: z.string().describe("Amount (human-readable)"),
|
|
2782
|
+
fromAddress: z.string().optional().describe("Sender (defaults to agent)"),
|
|
2783
|
+
slippage: z.number().optional().describe("Slippage decimal (default 0.03)")
|
|
2784
|
+
}, async ({ fromChainId, toChainId, fromToken, toToken, fromAmount, fromAddress, slippage }) => {
|
|
2785
|
+
try {
|
|
2786
|
+
return ok(await agent.bridge.getQuote(
|
|
2787
|
+
fromChainId,
|
|
2788
|
+
toChainId,
|
|
2789
|
+
fromToken,
|
|
2790
|
+
toToken,
|
|
2791
|
+
fromAmount,
|
|
2792
|
+
fromAddress || w,
|
|
2793
|
+
void 0,
|
|
2794
|
+
slippage
|
|
2795
|
+
));
|
|
2796
|
+
} catch (e) {
|
|
2797
|
+
return err(e);
|
|
2798
|
+
}
|
|
2799
|
+
});
|
|
2800
|
+
server.tool("bridge_routes", "Get multiple route options for bridging", {
|
|
2801
|
+
fromChainId: z.number().describe("Source chain ID"),
|
|
2802
|
+
toChainId: z.number().describe("Destination chain ID"),
|
|
2803
|
+
fromToken: z.string().describe("Source token address"),
|
|
2804
|
+
toToken: z.string().describe("Destination token address"),
|
|
2805
|
+
fromAmount: z.string().describe("Amount (human-readable)"),
|
|
2806
|
+
fromAddress: z.string().optional().describe("Sender (defaults to agent)")
|
|
2807
|
+
}, async ({ fromChainId, toChainId, fromToken, toToken, fromAmount, fromAddress }) => {
|
|
2808
|
+
try {
|
|
2809
|
+
return ok(await agent.bridge.getRoutes(
|
|
2810
|
+
fromChainId,
|
|
2811
|
+
toChainId,
|
|
2812
|
+
fromToken,
|
|
2813
|
+
toToken,
|
|
2814
|
+
fromAmount,
|
|
2815
|
+
fromAddress || w
|
|
2816
|
+
));
|
|
2817
|
+
} catch (e) {
|
|
2818
|
+
return err(e);
|
|
2819
|
+
}
|
|
2820
|
+
});
|
|
2821
|
+
server.tool("bridge_status", "Check status of a cross-chain transfer", {
|
|
2822
|
+
txHash: z.string().describe("Source chain tx hash"),
|
|
2823
|
+
fromChainId: z.number().describe("Source chain ID"),
|
|
2824
|
+
toChainId: z.number().describe("Destination chain ID")
|
|
2825
|
+
}, async ({ txHash, fromChainId, toChainId }) => {
|
|
2826
|
+
try {
|
|
2827
|
+
return ok(await agent.bridge.getStatus(txHash, fromChainId, toChainId));
|
|
2828
|
+
} catch (e) {
|
|
2829
|
+
return err(e);
|
|
2830
|
+
}
|
|
2831
|
+
});
|
|
2832
|
+
server.tool("perps_register", "Register for perpetual futures on Hyperliquid", {}, async () => {
|
|
2833
|
+
try {
|
|
2834
|
+
return ok(await agent.perps.register());
|
|
2835
|
+
} catch (e) {
|
|
2836
|
+
return err(e);
|
|
2837
|
+
}
|
|
2838
|
+
});
|
|
2839
|
+
server.tool("perps_registration_status", "Check perps registration status", {}, async () => {
|
|
2840
|
+
try {
|
|
2841
|
+
return ok(await agent.perps.getRegistrationStatus());
|
|
2842
|
+
} catch (e) {
|
|
2843
|
+
return err(e);
|
|
2844
|
+
}
|
|
2845
|
+
});
|
|
2846
|
+
server.tool("perps_wallet_address", "Get Hyperliquid wallet address", {}, async () => {
|
|
2847
|
+
try {
|
|
2848
|
+
return ok(await agent.perps.getWalletAddress());
|
|
2849
|
+
} catch (e) {
|
|
2850
|
+
return err(e);
|
|
2851
|
+
}
|
|
2852
|
+
});
|
|
2853
|
+
server.tool("perps_trading_pairs", "Get all 250+ perpetual trading pairs", {}, async () => {
|
|
2854
|
+
try {
|
|
2855
|
+
return ok(await agent.perps.getTradingPairs());
|
|
2856
|
+
} catch (e) {
|
|
2857
|
+
return err(e);
|
|
2858
|
+
}
|
|
2859
|
+
});
|
|
2860
|
+
server.tool("perps_update_leverage", "Set leverage for a market", {
|
|
2861
|
+
symbol: z.string().describe("Market symbol (BTC, ETH, SOL)"),
|
|
2862
|
+
leverage: z.number().describe("Leverage (1-50)"),
|
|
2863
|
+
leverageType: z.enum(["cross", "isolated"]).optional()
|
|
2864
|
+
}, async ({ symbol, leverage, leverageType }) => {
|
|
2865
|
+
try {
|
|
2866
|
+
return ok(await agent.perps.updateLeverage(symbol, leverage, leverageType));
|
|
2867
|
+
} catch (e) {
|
|
2868
|
+
return err(e);
|
|
2869
|
+
}
|
|
2870
|
+
});
|
|
2871
|
+
server.tool("perps_place_order", "Place a perpetual futures order", {
|
|
2872
|
+
orders: z.array(z.record(z.any())).describe("Array of order objects")
|
|
2873
|
+
}, async ({ orders }) => {
|
|
2874
|
+
try {
|
|
2875
|
+
return ok(await agent.perps.placeOrder(orders));
|
|
2876
|
+
} catch (e) {
|
|
2877
|
+
return err(e);
|
|
2878
|
+
}
|
|
2879
|
+
});
|
|
2880
|
+
server.tool("perps_cancel_orders", "Cancel open perps orders", {
|
|
2881
|
+
cancels: z.array(z.object({
|
|
2882
|
+
assetIndex: z.number(),
|
|
2883
|
+
oid: z.number()
|
|
2884
|
+
})).describe("Orders to cancel")
|
|
2885
|
+
}, async ({ cancels }) => {
|
|
2886
|
+
try {
|
|
2887
|
+
return ok(await agent.perps.cancelOrders(cancels));
|
|
2888
|
+
} catch (e) {
|
|
2889
|
+
return err(e);
|
|
2890
|
+
}
|
|
2891
|
+
});
|
|
2892
|
+
server.tool("perps_close_position", "Close a perpetual position", {
|
|
2893
|
+
symbol: z.string(),
|
|
2894
|
+
positionSide: z.enum(["long", "short"]),
|
|
2895
|
+
size: z.number(),
|
|
2896
|
+
currentPrice: z.number(),
|
|
2897
|
+
closePercent: z.number().optional()
|
|
2898
|
+
}, async ({ symbol, positionSide, size, currentPrice, closePercent }) => {
|
|
2899
|
+
try {
|
|
2900
|
+
return ok(await agent.perps.closePosition(symbol, positionSide, size, currentPrice, closePercent));
|
|
2901
|
+
} catch (e) {
|
|
2902
|
+
return err(e);
|
|
2903
|
+
}
|
|
2904
|
+
});
|
|
2905
|
+
server.tool("perps_orders", "Get open perps orders", {}, async () => {
|
|
2906
|
+
try {
|
|
2907
|
+
return ok(await agent.perps.getOrders());
|
|
2908
|
+
} catch (e) {
|
|
2909
|
+
return err(e);
|
|
2910
|
+
}
|
|
2911
|
+
});
|
|
2912
|
+
server.tool("perps_positions", "Get perps positions and margin summary", {
|
|
2913
|
+
wallet: z.string().describe("Hyperliquid wallet address")
|
|
2914
|
+
}, async ({ wallet }) => {
|
|
2915
|
+
try {
|
|
2916
|
+
return ok(await agent.perps.getPositions(wallet));
|
|
2917
|
+
} catch (e) {
|
|
2918
|
+
return err(e);
|
|
2919
|
+
}
|
|
2920
|
+
});
|
|
2921
|
+
server.tool("signals_market", "Get market signal for an asset (price, funding, OI, volume)", {
|
|
2922
|
+
coin: z.string().describe("Asset symbol (BTC, ETH, SOL)")
|
|
2923
|
+
}, async ({ coin }) => {
|
|
2924
|
+
try {
|
|
2925
|
+
return ok(await agent.signals.getMarketSignal(coin));
|
|
2926
|
+
} catch (e) {
|
|
2927
|
+
return err(e);
|
|
2928
|
+
}
|
|
2929
|
+
});
|
|
2930
|
+
server.tool("signals_technical", "Get technical analysis (SMA, RSI, trend, support/resistance)", {
|
|
2931
|
+
coin: z.string().describe("Asset symbol"),
|
|
2932
|
+
interval: z.string().optional().describe("Candle interval (1m, 5m, 15m, 1h, 4h, 1d)")
|
|
2933
|
+
}, async ({ coin, interval }) => {
|
|
2934
|
+
try {
|
|
2935
|
+
return ok(await agent.signals.getTechnicalSignal(coin, interval));
|
|
2936
|
+
} catch (e) {
|
|
2937
|
+
return err(e);
|
|
2938
|
+
}
|
|
2939
|
+
});
|
|
2940
|
+
server.tool("signals_whales", "Get whale positions from orderbook depth", {
|
|
2941
|
+
coin: z.string().describe("Asset symbol"),
|
|
2942
|
+
minUsd: z.number().optional().describe("Minimum position USD (default 100000)")
|
|
2943
|
+
}, async ({ coin, minUsd }) => {
|
|
2944
|
+
try {
|
|
2945
|
+
return ok(await agent.signals.getWhalePositions(coin, minUsd));
|
|
2946
|
+
} catch (e) {
|
|
2947
|
+
return err(e);
|
|
2948
|
+
}
|
|
2949
|
+
});
|
|
2950
|
+
server.tool("signals_funding", "Get funding rate extremes across all markets", {
|
|
2951
|
+
count: z.number().optional().describe("Top N (default 10)")
|
|
2952
|
+
}, async ({ count }) => {
|
|
2953
|
+
try {
|
|
2954
|
+
return ok(await agent.signals.getFundingExtremes(count));
|
|
2955
|
+
} catch (e) {
|
|
2956
|
+
return err(e);
|
|
2957
|
+
}
|
|
2958
|
+
});
|
|
2959
|
+
server.tool("signals_summary", "Full signal summary: market + technicals + whales + verdict", {
|
|
2960
|
+
coin: z.string().describe("Asset symbol")
|
|
2961
|
+
}, async ({ coin }) => {
|
|
2962
|
+
try {
|
|
2963
|
+
return ok(await agent.signals.summary(coin));
|
|
2964
|
+
} catch (e) {
|
|
2965
|
+
return err(e);
|
|
2966
|
+
}
|
|
2967
|
+
});
|
|
2968
|
+
server.tool("signals_scan", "Scan all markets for top trading opportunities", {
|
|
2969
|
+
count: z.number().optional().describe("Max opportunities (default 5)")
|
|
2970
|
+
}, async ({ count }) => {
|
|
2971
|
+
try {
|
|
2972
|
+
return ok(await agent.signals.scan(count));
|
|
2973
|
+
} catch (e) {
|
|
2974
|
+
return err(e);
|
|
2975
|
+
}
|
|
2976
|
+
});
|
|
2977
|
+
server.tool("social_search_users", "Search Arena users", {
|
|
2978
|
+
q: z.string().describe("Search query")
|
|
2979
|
+
}, async ({ q }) => {
|
|
2980
|
+
try {
|
|
2981
|
+
return ok(await agent.social.searchUsers(q));
|
|
2982
|
+
} catch (e) {
|
|
2983
|
+
return err(e);
|
|
2984
|
+
}
|
|
2985
|
+
});
|
|
2986
|
+
server.tool("social_user_by_handle", "Get user by Arena handle", {
|
|
2987
|
+
handle: z.string().describe("Arena handle")
|
|
2988
|
+
}, async ({ handle }) => {
|
|
2989
|
+
try {
|
|
2990
|
+
return ok(await agent.social.getUserByHandle(handle));
|
|
2991
|
+
} catch (e) {
|
|
2992
|
+
return err(e);
|
|
2993
|
+
}
|
|
2994
|
+
});
|
|
2995
|
+
server.tool("social_me", "Get your agent's Arena profile", {}, async () => {
|
|
2996
|
+
try {
|
|
2997
|
+
return ok(await agent.social.getMe());
|
|
2998
|
+
} catch (e) {
|
|
2999
|
+
return err(e);
|
|
3000
|
+
}
|
|
3001
|
+
});
|
|
3002
|
+
server.tool("social_top_users", "Get top Arena users", {}, async () => {
|
|
3003
|
+
try {
|
|
3004
|
+
return ok(await agent.social.getTopUsers());
|
|
3005
|
+
} catch (e) {
|
|
3006
|
+
return err(e);
|
|
3007
|
+
}
|
|
3008
|
+
});
|
|
3009
|
+
server.tool("social_follow", "Follow an Arena user", {
|
|
3010
|
+
userId: z.string().describe("User UUID")
|
|
3011
|
+
}, async ({ userId }) => {
|
|
3012
|
+
try {
|
|
3013
|
+
return ok(await agent.social.follow(userId));
|
|
3014
|
+
} catch (e) {
|
|
3015
|
+
return err(e);
|
|
3016
|
+
}
|
|
3017
|
+
});
|
|
3018
|
+
server.tool("social_unfollow", "Unfollow an Arena user", {
|
|
3019
|
+
userId: z.string().describe("User UUID")
|
|
3020
|
+
}, async ({ userId }) => {
|
|
3021
|
+
try {
|
|
3022
|
+
return ok(await agent.social.unfollow(userId));
|
|
3023
|
+
} catch (e) {
|
|
3024
|
+
return err(e);
|
|
3025
|
+
}
|
|
3026
|
+
});
|
|
3027
|
+
server.tool("social_update_profile", "Update Arena profile", {
|
|
3028
|
+
userName: z.string().optional(),
|
|
3029
|
+
bio: z.string().optional(),
|
|
3030
|
+
profilePicture: z.string().optional()
|
|
3031
|
+
}, async (params) => {
|
|
3032
|
+
try {
|
|
3033
|
+
return ok(await agent.social.updateProfile(params));
|
|
3034
|
+
} catch (e) {
|
|
3035
|
+
return err(e);
|
|
3036
|
+
}
|
|
3037
|
+
});
|
|
3038
|
+
server.tool("social_conversations", "List chat conversations", {}, async () => {
|
|
3039
|
+
try {
|
|
3040
|
+
return ok(await agent.social.getConversations());
|
|
3041
|
+
} catch (e) {
|
|
3042
|
+
return err(e);
|
|
3043
|
+
}
|
|
3044
|
+
});
|
|
3045
|
+
server.tool("social_send_message", "Send a chat message", {
|
|
3046
|
+
groupId: z.string().describe("Chat group UUID"),
|
|
3047
|
+
text: z.string().describe("Message text"),
|
|
3048
|
+
replyId: z.string().optional()
|
|
3049
|
+
}, async ({ groupId, text, replyId }) => {
|
|
3050
|
+
try {
|
|
3051
|
+
return ok(await agent.social.sendMessage(groupId, text, replyId));
|
|
3052
|
+
} catch (e) {
|
|
3053
|
+
return err(e);
|
|
3054
|
+
}
|
|
3055
|
+
});
|
|
3056
|
+
server.tool("social_messages", "Read messages from a chat", {
|
|
3057
|
+
groupId: z.string().describe("Chat group UUID"),
|
|
3058
|
+
after: z.string().optional().describe("Get messages after this timestamp")
|
|
3059
|
+
}, async ({ groupId, after }) => {
|
|
3060
|
+
try {
|
|
3061
|
+
return ok(await agent.social.getMessages(groupId, after));
|
|
3062
|
+
} catch (e) {
|
|
3063
|
+
return err(e);
|
|
3064
|
+
}
|
|
3065
|
+
});
|
|
3066
|
+
server.tool("social_create_thread", "Create a post/thread", {
|
|
3067
|
+
content: z.string().describe("Post content"),
|
|
3068
|
+
replyToId: z.string().optional()
|
|
3069
|
+
}, async ({ content, replyToId }) => {
|
|
3070
|
+
try {
|
|
3071
|
+
return ok(await agent.social.createThread(content, replyToId));
|
|
3072
|
+
} catch (e) {
|
|
3073
|
+
return err(e);
|
|
3074
|
+
}
|
|
3075
|
+
});
|
|
3076
|
+
server.tool("social_like_thread", "Like a thread", {
|
|
3077
|
+
threadId: z.string()
|
|
3078
|
+
}, async ({ threadId }) => {
|
|
3079
|
+
try {
|
|
3080
|
+
return ok(await agent.social.likeThread(threadId));
|
|
3081
|
+
} catch (e) {
|
|
3082
|
+
return err(e);
|
|
3083
|
+
}
|
|
3084
|
+
});
|
|
3085
|
+
server.tool("market_price", "Get price, 24h change, market cap, volume for coins", {
|
|
3086
|
+
ids: z.string().describe("CoinGecko IDs, comma-separated (e.g. 'bitcoin,ethereum,avalanche-2')")
|
|
3087
|
+
}, async ({ ids }) => {
|
|
3088
|
+
try {
|
|
3089
|
+
return ok(await agent.market.price(ids.split(",").map((s) => s.trim())));
|
|
3090
|
+
} catch (e) {
|
|
3091
|
+
return err(e);
|
|
3092
|
+
}
|
|
3093
|
+
});
|
|
3094
|
+
server.tool("market_trending", "Get trending coins on CoinGecko", {}, async () => {
|
|
3095
|
+
try {
|
|
3096
|
+
return ok(await agent.market.trending());
|
|
3097
|
+
} catch (e) {
|
|
3098
|
+
return err(e);
|
|
3099
|
+
}
|
|
3100
|
+
});
|
|
3101
|
+
server.tool("market_top", "Get top coins by market cap", {
|
|
3102
|
+
count: z.number().optional().describe("Number of coins (default 20)"),
|
|
3103
|
+
page: z.number().optional().describe("Page number (default 1)")
|
|
3104
|
+
}, async ({ count, page }) => {
|
|
3105
|
+
try {
|
|
3106
|
+
return ok(await agent.market.markets(count, page));
|
|
3107
|
+
} catch (e) {
|
|
3108
|
+
return err(e);
|
|
3109
|
+
}
|
|
3110
|
+
});
|
|
3111
|
+
server.tool("market_search", "Search for coins by name or symbol", {
|
|
3112
|
+
query: z.string().describe("Search query")
|
|
3113
|
+
}, async ({ query }) => {
|
|
3114
|
+
try {
|
|
3115
|
+
return ok(await agent.market.search(query));
|
|
3116
|
+
} catch (e) {
|
|
3117
|
+
return err(e);
|
|
3118
|
+
}
|
|
3119
|
+
});
|
|
3120
|
+
server.tool("market_avax_price", "Get current AVAX price and 24h change", {}, async () => {
|
|
3121
|
+
try {
|
|
3122
|
+
return ok(await agent.market.avaxPrice());
|
|
3123
|
+
} catch (e) {
|
|
3124
|
+
return err(e);
|
|
3125
|
+
}
|
|
3126
|
+
});
|
|
3127
|
+
server.tool("market_arena_price", "Get current ARENA price and 24h change", {}, async () => {
|
|
3128
|
+
try {
|
|
3129
|
+
return ok(await agent.market.arenaPrice());
|
|
3130
|
+
} catch (e) {
|
|
3131
|
+
return err(e);
|
|
3132
|
+
}
|
|
3133
|
+
});
|
|
3134
|
+
server.tool("defi_savax_info", "Get sAVAX staking info: exchange rate, total staked, your balance", {
|
|
3135
|
+
wallet: z.string().optional().describe("Wallet to check balance (defaults to agent)")
|
|
3136
|
+
}, async ({ wallet }) => {
|
|
3137
|
+
try {
|
|
3138
|
+
return ok(await agent.defi.sAvaxInfo(wallet || w));
|
|
3139
|
+
} catch (e) {
|
|
3140
|
+
return err(e);
|
|
3141
|
+
}
|
|
3142
|
+
});
|
|
3143
|
+
server.tool("defi_savax_quote", "Quote: how much sAVAX for staking AVAX", {
|
|
3144
|
+
avax: z.string().describe("AVAX amount to stake")
|
|
3145
|
+
}, async ({ avax }) => {
|
|
3146
|
+
try {
|
|
3147
|
+
return ok(await agent.defi.sAvaxStakeQuote(avax));
|
|
3148
|
+
} catch (e) {
|
|
3149
|
+
return err(e);
|
|
3150
|
+
}
|
|
3151
|
+
});
|
|
3152
|
+
server.tool("defi_savax_stake", "Stake AVAX \u2192 sAVAX (Benqi liquid staking) \u2014 signs and broadcasts", {
|
|
3153
|
+
avax: z.string().describe("AVAX to stake")
|
|
3154
|
+
}, async ({ avax }) => {
|
|
3155
|
+
try {
|
|
3156
|
+
return ok(await agent.execute(agent.defi.buildSAvaxStake(avax)));
|
|
3157
|
+
} catch (e) {
|
|
3158
|
+
return err(e);
|
|
3159
|
+
}
|
|
3160
|
+
});
|
|
3161
|
+
server.tool("defi_savax_unstake", "Request unstake sAVAX \u2192 AVAX (delayed) \u2014 signs and broadcasts", {
|
|
3162
|
+
amount: z.string().describe("sAVAX amount, or 'max'")
|
|
3163
|
+
}, async ({ amount }) => {
|
|
3164
|
+
try {
|
|
3165
|
+
return ok(await agent.execute(agent.defi.buildSAvaxUnstake(w, amount)));
|
|
3166
|
+
} catch (e) {
|
|
3167
|
+
return err(e);
|
|
3168
|
+
}
|
|
3169
|
+
});
|
|
3170
|
+
server.tool("defi_vault_info", "Get info about an ERC-4626 vault", {
|
|
3171
|
+
vault: z.string().describe("Vault contract address"),
|
|
3172
|
+
wallet: z.string().optional().describe("Wallet to check position")
|
|
3173
|
+
}, async ({ vault, wallet }) => {
|
|
3174
|
+
try {
|
|
3175
|
+
return ok(await agent.defi.vaultInfo(vault, wallet || w));
|
|
3176
|
+
} catch (e) {
|
|
3177
|
+
return err(e);
|
|
3178
|
+
}
|
|
3179
|
+
});
|
|
3180
|
+
server.tool("defi_vault_quote", "Quote vault deposit \u2014 how many shares for given assets", {
|
|
3181
|
+
vault: z.string().describe("Vault contract address"),
|
|
3182
|
+
amount: z.string().describe("Asset amount to deposit")
|
|
3183
|
+
}, async ({ vault, amount }) => {
|
|
3184
|
+
try {
|
|
3185
|
+
return ok(await agent.defi.vaultDepositQuote(vault, amount));
|
|
3186
|
+
} catch (e) {
|
|
3187
|
+
return err(e);
|
|
3188
|
+
}
|
|
3189
|
+
});
|
|
3190
|
+
server.tool("defi_vault_deposit", "Deposit into an ERC-4626 vault \u2014 signs and broadcasts", {
|
|
3191
|
+
vault: z.string().describe("Vault contract address"),
|
|
3192
|
+
amount: z.string().describe("Asset amount, or 'max'")
|
|
3193
|
+
}, async ({ vault, amount }) => {
|
|
3194
|
+
try {
|
|
3195
|
+
return ok(await agent.execute(agent.defi.buildVaultDeposit(w, vault, amount)));
|
|
3196
|
+
} catch (e) {
|
|
3197
|
+
return err(e);
|
|
3198
|
+
}
|
|
3199
|
+
});
|
|
3200
|
+
server.tool("defi_vault_withdraw", "Withdraw from an ERC-4626 vault \u2014 signs and broadcasts", {
|
|
3201
|
+
vault: z.string().describe("Vault contract address"),
|
|
3202
|
+
amount: z.string().describe("Asset amount, or 'max'")
|
|
3203
|
+
}, async ({ vault, amount }) => {
|
|
3204
|
+
try {
|
|
3205
|
+
return ok(await agent.execute(agent.defi.buildVaultWithdraw(w, vault, amount)));
|
|
3206
|
+
} catch (e) {
|
|
3207
|
+
return err(e);
|
|
3208
|
+
}
|
|
3209
|
+
});
|
|
3210
|
+
server.tool("policy_get", "Get the current spending policy", {}, async () => {
|
|
3211
|
+
try {
|
|
3212
|
+
return ok(agent.getPolicy());
|
|
3213
|
+
} catch (e) {
|
|
3214
|
+
return err(e);
|
|
3215
|
+
}
|
|
3216
|
+
});
|
|
3217
|
+
server.tool("policy_set", "Replace the entire spending policy", {
|
|
3218
|
+
maxPerTx: z.string().optional().describe("Max AVAX per transaction"),
|
|
3219
|
+
maxPerHour: z.string().optional().describe("Max AVAX per hour"),
|
|
3220
|
+
maxPerDay: z.string().optional().describe("Max AVAX per day"),
|
|
3221
|
+
allowedContracts: z.array(z.string()).optional().describe("Allowlisted contract addresses"),
|
|
3222
|
+
blockedContracts: z.array(z.string()).optional().describe("Blocklisted contract addresses"),
|
|
3223
|
+
simulateBeforeSend: z.boolean().optional().describe("Simulate transactions before sending"),
|
|
3224
|
+
dryRun: z.boolean().optional().describe("Dry run mode (no broadcasting)")
|
|
3225
|
+
}, async (policy) => {
|
|
3226
|
+
try {
|
|
3227
|
+
agent.setPolicy(policy);
|
|
3228
|
+
return ok({ status: "policy_updated", policy: agent.getPolicy() });
|
|
3229
|
+
} catch (e) {
|
|
3230
|
+
return err(e);
|
|
3231
|
+
}
|
|
3232
|
+
});
|
|
3233
|
+
server.tool("policy_budget", "Get budget status: spent this hour, today, remaining", {}, async () => {
|
|
3234
|
+
try {
|
|
3235
|
+
return ok(agent.getBudgetStatus());
|
|
3236
|
+
} catch (e) {
|
|
3237
|
+
return err(e);
|
|
3238
|
+
}
|
|
3239
|
+
});
|
|
3240
|
+
server.tool("call_contract", "Call any smart contract method \u2014 signs and broadcasts", {
|
|
3241
|
+
contract: z.string().describe("Contract address"),
|
|
3242
|
+
abi: z.array(z.string()).describe("Human-readable ABI array"),
|
|
3243
|
+
method: z.string().describe("Method name"),
|
|
3244
|
+
args: z.array(z.any()).optional().describe("Method arguments"),
|
|
3245
|
+
value: z.string().optional().describe("Native token to send (e.g. '0.1')")
|
|
3246
|
+
}, async ({ contract, abi, method, args, value }) => {
|
|
3247
|
+
try {
|
|
3248
|
+
return ok(await agent.call({ contract, abi, method, args, value }));
|
|
3249
|
+
} catch (e) {
|
|
3250
|
+
return err(e);
|
|
3251
|
+
}
|
|
3252
|
+
});
|
|
3253
|
+
return server;
|
|
3254
|
+
}
|
|
3255
|
+
|
|
3256
|
+
// src/mcp/cli.ts
|
|
3257
|
+
async function main() {
|
|
3258
|
+
const privateKey = process.env.LOGIQICAL_PRIVATE_KEY;
|
|
3259
|
+
const network = process.env.LOGIQICAL_NETWORK || "avalanche";
|
|
3260
|
+
const rpcUrl = process.env.LOGIQICAL_RPC_URL;
|
|
3261
|
+
const arenaApiKey = process.env.ARENA_API_KEY;
|
|
3262
|
+
let agent;
|
|
3263
|
+
if (privateKey) {
|
|
3264
|
+
agent = new Logiqical({ privateKey, network, rpcUrl, arenaApiKey });
|
|
3265
|
+
console.error(`Logiqical MCP \u2014 wallet ${agent.address}`);
|
|
3266
|
+
} else {
|
|
3267
|
+
agent = await Logiqical.boot({ network, rpcUrl, arenaApiKey });
|
|
3268
|
+
console.error(`Logiqical MCP \u2014 booted from keystore: ${agent.address}`);
|
|
3269
|
+
}
|
|
3270
|
+
const server = createMcpServer(agent);
|
|
3271
|
+
const transport = new StdioServerTransport();
|
|
3272
|
+
await server.connect(transport);
|
|
3273
|
+
console.error("Logiqical MCP server running (stdio)");
|
|
3274
|
+
}
|
|
3275
|
+
main().catch((e) => {
|
|
3276
|
+
console.error("Fatal:", e);
|
|
3277
|
+
process.exit(1);
|
|
3278
|
+
});
|