forked from Stellar-Tools/Stellar-AgentKit
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathagent.ts
More file actions
530 lines (480 loc) · 16.1 KB
/
Copy pathagent.ts
File metadata and controls
530 lines (480 loc) · 16.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
import {
swap as contractSwap,
deposit as contractDeposit,
withdraw as contractWithdraw,
getReserves as contractGetReserves,
getShareId as contractGetShareId,
} from "./lib/contract";
import {
quoteSwap as quoteDexSwap,
swapBestRoute as executeBestRouteSwap,
type StellarAssetInput,
type QuoteSwapParams,
type RouteQuote,
type SwapBestRouteParams,
type SwapBestRouteResult,
} from "./lib/dex";
import { bridgeTokenTool } from "./tools/bridge";
import {
Horizon,
Keypair,
Asset,
TransactionBuilder,
Operation,
Networks,
BASE_FEE
} from "@stellar/stellar-sdk";
const { Server } = Horizon;
export interface AgentConfig {
network: "testnet" | "mainnet";
rpcUrl?: string;
publicKey?: string;
allowMainnet?: boolean; // Optional mainnet opt-in flag for general operations
}
export interface LaunchTokenParams {
code: string;
issuerSecret: string;
distributorSecret: string;
initialSupply: string;
/**
* Optional display/metadata decimals.
*
* NOTE: Stellar assets always have a fixed on-chain precision of 7 decimal places.
* This field is currently ignored by the implementation and does NOT affect the
* actual asset precision on the Stellar network.
*/
decimals?: number;
lockIssuer?: boolean;
}
export interface LaunchTokenResult {
transactionHash: string;
asset: {
code: string;
issuer: string;
};
distributorPublicKey: string;
issuerLocked: boolean;
}
export type {
StellarAssetInput,
QuoteSwapParams,
RouteQuote,
SwapBestRouteParams,
SwapBestRouteResult,
};
export class AgentClient {
private network: "testnet" | "mainnet";
private publicKey: string;
private rpcUrl: string;
constructor(config: AgentConfig) {
// Mainnet safety check for general operations
if (config.network === "mainnet" && !config.allowMainnet) {
throw new Error(
"🚫 Mainnet execution blocked for safety.\n" +
"Stellar AgentKit requires explicit opt-in for mainnet operations to prevent accidental use of real funds.\n" +
"To enable mainnet, set allowMainnet: true in your config:\n" +
" new AgentClient({ network: 'mainnet', allowMainnet: true, ... })"
);
}
// Warning for mainnet usage (when opted in)
if (config.network === "mainnet" && config.allowMainnet) {
console.warn(
"\n⚠️ WARNING: STELLAR MAINNET ACTIVE ⚠️\n" +
"You are executing transactions on Stellar mainnet.\n" +
"Real funds will be used. Double-check all parameters before proceeding.\n"
);
}
this.network = config.network;
this.publicKey = config.publicKey || process.env.STELLAR_PUBLIC_KEY || "";
this.rpcUrl = config.rpcUrl || (config.network === "mainnet"
? "https://horizon.stellar.org"
: "https://horizon-testnet.stellar.org");
if (!this.publicKey && this.network === "testnet") {
// In a real SDK, we might not throw here if only read-only methods are used,
// but for this implementation, we'll assume it's needed for most actions.
}
}
/**
* Perform a swap on the Stellar network.
* @param params Swap parameters
*/
async swap(params: {
to: string;
buyA: boolean;
out: string;
inMax: string;
contractAddress?: string;
}) {
return await contractSwap(
this.publicKey,
params.to,
params.buyA,
params.out,
params.inMax,
{ network: this.network, rpcUrl: this.rpcUrl, contractAddress: params.contractAddress }
);
}
/**
* Bridge USDC from Stellar to an EVM-compatible chain.
*
* ⚠️ IMPORTANT: Mainnet bridging requires BOTH:
* 1. AgentClient initialized with allowMainnet: true
* 2. ALLOW_MAINNET_BRIDGE=true in your .env file
*
* Supported target chains: "ethereum" | "polygon" | "arbitrum" | "base"
*
* @example
* await agent.bridge({ amount: "100", toAddress: "0x...", targetChain: "polygon" });
*
* @param params Bridge parameters
* @returns Bridge transaction result with status, hash, network, and targetChain
*/
async bridge(params: {
amount: string;
toAddress: string;
targetChain?: "ethereum" | "polygon" | "arbitrum" | "base";
}) {
return await bridgeTokenTool.func({
amount: params.amount,
toAddress: params.toAddress,
targetChain: params.targetChain ?? "ethereum",
fromNetwork:
this.network === "mainnet"
? "stellar-mainnet"
: "stellar-testnet",
});
}
/**
* Liquidity Pool operations.
*/
public lp = {
deposit: async (params: {
to: string;
desiredA: string;
minA: string;
desiredB: string;
minB: string;
contractAddress?: string;
}) => {
return await contractDeposit(
this.publicKey,
params.to,
params.desiredA,
params.minA,
params.desiredB,
params.minB,
{ network: this.network, rpcUrl: this.rpcUrl, contractAddress: params.contractAddress }
);
},
withdraw: async (params: {
to: string;
shareAmount: string;
minA: string;
minB: string;
contractAddress?: string;
}) => {
return await contractWithdraw(
this.publicKey,
params.to,
params.shareAmount,
params.minA,
params.minB,
{ network: this.network, rpcUrl: this.rpcUrl, contractAddress: params.contractAddress }
);
},
getReserves: async (params?: { contractAddress?: string }) => {
return await contractGetReserves(this.publicKey, { network: this.network, rpcUrl: this.rpcUrl, contractAddress: params?.contractAddress });
},
getShareId: async (params?: { contractAddress?: string }) => {
return await contractGetShareId(this.publicKey, { network: this.network, rpcUrl: this.rpcUrl, contractAddress: params?.contractAddress });
},
};
/**
* Stellar Classic DEX routing.
*
* These methods use Horizon pathfinding and path payment operations, which can
* route through the SDEX and built-in liquidity pools.
*/
public dex = {
quoteSwap: async (params: QuoteSwapParams): Promise<RouteQuote[]> => {
return await quoteDexSwap(
{
network: this.network,
horizonUrl: this.rpcUrl,
publicKey: this.publicKey,
},
params
);
},
swapBestRoute: async (
params: SwapBestRouteParams
): Promise<SwapBestRouteResult> => {
return await executeBestRouteSwap(
{
network: this.network,
horizonUrl: this.rpcUrl,
publicKey: this.publicKey,
},
params
);
},
};
/**
* Launch a new token on the Stellar network.
*
* ⚠️ SECURITY CRITICAL: This function handles sensitive operations:
* - Creates new assets with issuer/distributor accounts
* - Optionally locks issuer account (IRREVERSIBLE on mainnet)
* - Requires explicit mainnet opt-in via allowMainnet config
*
* NEVER log secrets or store them in class variables.
* All secret keys are used in-memory only and discarded after use.
*
* @param params Token launch parameters including secrets and configuration
* @returns Transaction hash and asset details
*/
async launchToken(params: LaunchTokenParams): Promise<LaunchTokenResult> {
// 🔒 SECURITY: Additional mainnet safeguard for token launches
if (this.network === "mainnet") {
throw new Error(
"🚫 Token launches on mainnet are disabled for security.\n" +
"This prevents accidental creation of assets on the live network.\n" +
"Token launches should be thoroughly tested on testnet first."
);
}
const {
code,
issuerSecret,
distributorSecret,
initialSupply,
decimals = 7,
lockIssuer = false
} = params;
// 🔒 SECURITY: Validate inputs before processing
if (!code || code.length === 0 || code.length > 12) {
throw new Error("Asset code must be between 1 and 12 characters");
}
if (!/^[A-Za-z0-9]+$/.test(code)) {
throw new Error("Asset code must contain only alphanumeric characters");
}
// 🔒 SECURITY: Warn about issuer locking - this is IRREVERSIBLE
if (lockIssuer) {
console.warn(
"\n⚠️ WARNING: ISSUER ACCOUNT LOCKING ENABLED ⚠️\n" +
"This will set the issuer's master weight to 0, making the account immutable.\n" +
"This action is IRREVERSIBLE - no more tokens can ever be minted.\n" +
"Ensure you have thoroughly tested token functionality before locking.\n"
);
}
try {
// Create keypairs from secrets (in-memory only, never stored)
const issuerKeypair = Keypair.fromSecret(issuerSecret);
const distributorKeypair = Keypair.fromSecret(distributorSecret);
const issuerPublicKey = issuerKeypair.publicKey();
const distributorPublicKey = distributorKeypair.publicKey();
// Connect to Stellar network
const server = new Horizon.Server(this.rpcUrl);
const networkPassphrase = Networks.TESTNET;
// Step 1: Load or create issuer account
let issuerAccount;
try {
issuerAccount = await server.loadAccount(issuerPublicKey);
console.log(`✓ Issuer account exists: ${issuerPublicKey}`);
} catch (error) {
throw new Error(
`Issuer account ${issuerPublicKey} not found. ` +
`Please fund the account before launching the token.`
);
}
// Step 2: Load or create distributor account
let distributorAccount;
try {
distributorAccount = await server.loadAccount(distributorPublicKey);
console.log(`✓ Distributor account exists: ${distributorPublicKey}`);
} catch (error) {
throw new Error(
`Distributor account ${distributorPublicKey} not found. ` +
`Please fund the account before launching the token.`
);
}
// Step 3: Create the asset
const asset = new Asset(code, issuerPublicKey);
console.log(`✓ Created asset: ${code}:${issuerPublicKey}`);
// Step 4: Check and create trustline if needed
const trustlineExists = await this.checkTrustlineExists(
server,
distributorPublicKey,
asset
);
let trustlineHash: string | null = null;
if (!trustlineExists) {
console.log("Creating trustline from distributor to asset...");
trustlineHash = await this.createTrustline(
server,
distributorKeypair,
asset,
networkPassphrase
);
console.log(`✓ Trustline created: ${trustlineHash}`);
} else {
console.log("✓ Trustline already exists");
}
// Step 5: Send initial supply from issuer to distributor
console.log(`Minting ${initialSupply} ${code} tokens...`);
const paymentTransaction = new TransactionBuilder(issuerAccount, {
fee: BASE_FEE,
networkPassphrase
})
.addOperation(
Operation.payment({
destination: distributorPublicKey,
asset: asset,
amount: initialSupply
})
)
.setTimeout(300)
.build();
paymentTransaction.sign(issuerKeypair);
const paymentResult = await server.submitTransaction(paymentTransaction);
console.log(`✓ Initial supply minted: ${paymentResult.hash}`);
let lockResult: { hash: string } | null = null;
// Step 6: Optionally lock issuer account
if (lockIssuer) {
console.log("Locking issuer account...");
lockResult = await this.lockIssuerAccount(
server,
issuerKeypair,
networkPassphrase
);
console.log(`✓ Issuer account locked: ${lockResult.hash}`);
}
// Return the final transaction hash (payment or lock transaction)
const finalTransactionHash = lockResult?.hash || paymentResult.hash;
return {
transactionHash: finalTransactionHash,
asset: {
code: code,
issuer: issuerPublicKey
},
distributorPublicKey: distributorPublicKey,
issuerLocked: lockIssuer
};
} catch (error) {
console.error("Token launch failed:", error);
throw new Error(`Token launch failed: ${error instanceof Error ? error.message : String(error)}`);
}
}
/**
* Check if a trustline exists between an account and an asset.
*
* @param server Stellar server instance
* @param accountPublicKey Account to check
* @param asset Asset to check trustline for
* @returns true if trustline exists, false otherwise
*/
private async checkTrustlineExists(
server: Horizon.Server,
accountPublicKey: string,
asset: Asset
): Promise<boolean> {
try {
const account = await server.loadAccount(accountPublicKey);
return account.balances.some((balance: Horizon.HorizonApi.BalanceLine) => {
if (balance.asset_type === 'native' || balance.asset_type === 'liquidity_pool_shares') return false;
return (
balance.asset_code === asset.code &&
balance.asset_issuer === asset.issuer
);
});
} catch (error: any) {
// If the account does not exist, there can be no trustline.
const status = error?.response?.status;
if (status === 404) {
return false;
}
console.error(`Error checking trustline: ${error instanceof Error ? error.message : String(error)}`);
throw error;
}
}
/**
* Create a trustline between an account and an asset.
*
* @param server Stellar server instance
* @param accountKeypair Account keypair that will trust the asset
* @param asset Asset to create trustline for
* @param networkPassphrase Network passphrase
* @returns Transaction hash of the trustline creation
*/
private async createTrustline(
server: Horizon.Server,
accountKeypair: Keypair,
asset: Asset,
networkPassphrase: string
): Promise<string> {
try {
const account = await server.loadAccount(accountKeypair.publicKey());
const transaction = new TransactionBuilder(account, {
fee: BASE_FEE,
networkPassphrase
})
.addOperation(
Operation.changeTrust({
asset: asset,
// No limit specified means unlimited trust
})
)
.setTimeout(30)
.build();
transaction.sign(accountKeypair);
const result = await server.submitTransaction(transaction);
return result.hash;
} catch (error) {
throw new Error(`Failed to create trustline: ${error instanceof Error ? error.message : String(error)}`);
}
}
/**
* Lock an issuer account by setting master weight to 0.
*
* ⚠️ SECURITY WARNING: This operation is IRREVERSIBLE!
* Once an issuer account is locked:
* - No more tokens can ever be minted
* - Account becomes immutable (cannot change signers, thresholds, etc.)
* - This provides trust guarantees that supply is truly fixed
*
* Use cases:
* - Fixed supply tokens where no future minting is desired
* - Decentralized assets where issuer control should be removed
* - Compliance with certain token standards requiring immutable supply
*
* @param server Stellar server instance
* @param issuerKeypair Issuer account keypair
* @param networkPassphrase Network passphrase
* @returns Transaction hash of the locking operation
*/
private async lockIssuerAccount(
server: Horizon.Server,
issuerKeypair: Keypair,
networkPassphrase: string
): Promise<{ hash: string }> {
try {
const issuerAccount = await server.loadAccount(issuerKeypair.publicKey());
const transaction = new TransactionBuilder(issuerAccount, {
fee: BASE_FEE,
networkPassphrase
})
.addOperation(
Operation.setOptions({
// Set master weight to 0 - this makes the account immutable
masterWeight: 0
})
)
.setTimeout(30)
.build();
transaction.sign(issuerKeypair);
const result = await server.submitTransaction(transaction);
return { hash: result.hash };
} catch (error) {
throw new Error(`Failed to lock issuer account: ${error instanceof Error ? error.message : String(error)}`);
}
}
}