logiqical 0.3.1 → 0.5.0

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