-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcreatePool.js
More file actions
285 lines (242 loc) Β· 9.08 KB
/
createPool.js
File metadata and controls
285 lines (242 loc) Β· 9.08 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
import StellarSdk from "@stellar/stellar-sdk";
import config from "../config.json" with { type: "json" };
const {
accounts: { issuer, distributor, buyer },
network: { serverUrl, networkPassphrase },
asset: { code: assetCode }
} = config;
const server = new StellarSdk.Horizon.Server(serverUrl);
/**
* Create a new liquidity pool with custom parameters
*/
const createNewPool = async (poolConfig) => {
try {
const {
assetA,
assetB,
feeBp = 30, // Default 0.3% fee
initialAmountA,
initialAmountB,
accountType = "distributor",
poolName = "Custom Pool"
} = poolConfig;
console.log(`π Creating new pool: ${poolName}\n`);
console.log(`π Assets: ${assetA} β ${assetB}`);
console.log(`π° Fee: ${feeBp} basis points (${(feeBp / 100).toFixed(2)}%)`);
console.log(`π§ Initial liquidity: ${initialAmountA} + ${initialAmountB}\n`);
// Choose account
const account = accountType === "buyer" ? buyer : distributor;
const accountName = accountType === "buyer" ? "Buyer" : "Distributor";
console.log(`π€ Using ${accountName} account: ${account.publicKey}`);
// Load account
const accountData = await server.loadAccount(account.publicKey);
const txOptions = {
fee: await server.fetchBaseFee(),
networkPassphrase: networkPassphrase
};
// Create assets
let stellarAssetA, stellarAssetB;
if (assetA === "native" || assetA === "Test-Ο") {
stellarAssetA = StellarSdk.Asset.native();
} else {
stellarAssetA = new StellarSdk.Asset(assetA, issuer.publicKey);
}
if (assetB === "native" || assetB === "Test-Ο") {
stellarAssetB = StellarSdk.Asset.native();
} else {
stellarAssetB = new StellarSdk.Asset(assetB, issuer.publicKey);
}
// Check account balances
const balanceA = accountData.balances.find(b => {
if (assetA === "native" || assetA === "Test-Ο") {
return b.asset_type === "native";
} else {
return b.asset_code === assetA && b.asset_issuer === issuer.publicKey;
}
});
const balanceB = accountData.balances.find(b => {
if (assetB === "native" || assetB === "Test-Ο") {
return b.asset_type === "native";
} else {
return b.asset_code === assetB && b.asset_issuer === issuer.publicKey;
}
});
console.log(`π Current ${accountName} balances:`);
console.log(` ${assetA}: ${balanceA?.balance || '0'}`);
console.log(` ${assetB}: ${balanceB?.balance || '0'}`);
// Validate balances
if (!balanceA || parseFloat(balanceA.balance) < parseFloat(initialAmountA)) {
throw new Error(`Insufficient ${assetA} balance. Required: ${initialAmountA}, Available: ${balanceA?.balance || '0'}`);
}
if (!balanceB || parseFloat(balanceB.balance) < parseFloat(initialAmountB)) {
throw new Error(`Insufficient ${assetB} balance. Required: ${initialAmountB}, Available: ${balanceB?.balance || '0'}`);
}
// Create liquidity pool asset with standard fee (30 basis points)
console.log(`β οΈ Using standard fee: 30 basis points (0.3%)`);
const liquidityPoolAsset = new StellarSdk.LiquidityPoolAsset(
stellarAssetA,
stellarAssetB,
StellarSdk.LiquidityPoolFeeV18
);
const transactionBuilder = new StellarSdk.TransactionBuilder(accountData, txOptions);
// Step 1: Establish trustline to the liquidity pool
console.log("π Step 1: Establishing trustline to liquidity pool...");
transactionBuilder.addOperation(
StellarSdk.Operation.changeTrust({
asset: liquidityPoolAsset,
})
);
const transaction = transactionBuilder.setTimeout(0).build();
transaction.sign(StellarSdk.Keypair.fromSecret(account.secret));
console.log("β³ Submitting trustline transaction...");
const trustResult = await server.submitTransaction(transaction);
console.log("β
Trustline established:", trustResult.hash);
// Step 2: Get the pool ID and deposit initial liquidity
console.log("\nπ° Step 2: Depositing initial liquidity...");
const accountDataReloaded = await server.loadAccount(account.publicKey);
let poolId = null;
// Find the liquidity pool share balance
for (const balance of accountDataReloaded.balances) {
if (balance.asset_type === "liquidity_pool_shares") {
poolId = balance.liquidity_pool_id;
console.log("π New Pool ID:", poolId);
break;
}
}
if (!poolId) {
throw new Error("Could not find new liquidity pool ID");
}
// Deposit initial liquidity
const depositTransaction = new StellarSdk.TransactionBuilder(accountDataReloaded, txOptions)
.addOperation(
StellarSdk.Operation.liquidityPoolDeposit({
liquidityPoolId: poolId,
maxAmountA: initialAmountA,
maxAmountB: initialAmountB,
minPrice: "0.01",
maxPrice: "100",
})
)
.setTimeout(0)
.build();
depositTransaction.sign(StellarSdk.Keypair.fromSecret(account.secret));
const depositResult = await server.submitTransaction(depositTransaction);
console.log("β
Initial liquidity deposited:", depositResult.hash);
console.log("π New pool created successfully!");
// Get final pool details
const poolDetails = await server.liquidityPools().liquidityPoolId(poolId).call();
console.log(`\nπ Final pool details:`);
console.log(` Pool ID: ${poolId}`);
console.log(` Asset A: ${poolDetails.reserves[0].asset} (${poolDetails.reserves[0].amount})`);
console.log(` Asset B: ${poolDetails.reserves[1].asset} (${poolDetails.reserves[1].amount})`);
console.log(` Total Shares: ${poolDetails.total_shares}`);
console.log(` Fee: ${poolDetails.fee_bp} basis points`);
return {
poolId,
trustTransaction: trustResult,
depositTransaction: depositResult,
poolDetails
};
} catch (error) {
console.error("β Failed to create new pool:", error.message);
if (error.response?.data?.extras) {
console.error("Details:", JSON.stringify(error.response.data.extras, null, 2));
}
throw error;
}
};
/**
* Create predefined pool configurations
*/
const createPredefinedPools = async () => {
const poolConfigs = [
{
name: "MEME-USPI Pool",
assetA: "MEME",
assetB: "USPI",
feeBp: 50, // 0.5% fee
initialAmountA: "100",
initialAmountB: "100",
accountType: "distributor"
},
{
name: "MEME-BBC Pool",
assetA: "MEME",
assetB: "BBC",
feeBp: 100, // 1% fee
initialAmountA: "50",
initialAmountB: "50",
accountType: "distributor"
},
{
name: "High Fee Test-Ο-MEME Pool",
assetA: "Test-Ο",
assetB: "MEME",
feeBp: 500, // 5% fee
initialAmountA: "20",
initialAmountB: "200",
accountType: "distributor"
}
];
console.log("π Creating predefined pools...\n");
for (const config of poolConfigs) {
try {
console.log(`\n${'='.repeat(50)}`);
await createNewPool(config);
console.log(`${'='.repeat(50)}\n`);
} catch (error) {
console.error(`β Failed to create ${config.name}:`, error.message);
}
}
};
// Command line usage
const main = async () => {
const args = process.argv.slice(2);
if (args.length === 0) {
console.log("π Usage: node createPool.js <COMMAND> [OPTIONS]");
console.log("\nCommands:");
console.log(" predefined - Create predefined pool configurations");
console.log(" custom - Create custom pool with parameters");
console.log("\nCustom pool options:");
console.log(" node createPool.js custom MEME USPI 30 100 100");
console.log(" node createPool.js custom Test-Ο MEME 50 20 200");
console.log("\nParameters for custom:");
console.log(" ASSET_A - First asset (MEME, USPI, Test-Ο, etc.)");
console.log(" ASSET_B - Second asset");
console.log(" FEE_BP - Fee in basis points (default: 30)");
console.log(" AMOUNT_A - Initial amount of asset A");
console.log(" AMOUNT_B - Initial amount of asset B");
console.log(" ACCOUNT - Account to use (distributor/buyer)");
process.exit(1);
}
const command = args[0];
if (command === "predefined") {
await createPredefinedPools();
} else if (command === "custom") {
if (args.length < 6) {
console.error("β Custom pool requires: ASSET_A ASSET_B FEE_BP AMOUNT_A AMOUNT_B");
process.exit(1);
}
const poolConfig = {
assetA: args[1],
assetB: args[2],
feeBp: parseInt(args[3]) || 30,
initialAmountA: args[4],
initialAmountB: args[5],
accountType: args[6] || "distributor",
poolName: `${args[1]}-${args[2]} Pool`
};
await createNewPool(poolConfig);
} else {
console.error("β Invalid command. Use 'predefined' or 'custom'");
process.exit(1);
}
};
// Only run main if this file is executed directly
if (process.argv[1].endsWith('createPool.js')) {
main().catch((error) => {
console.error("\nβ Error:", error.message);
process.exit(1);
});
}
export { createNewPool, createPredefinedPools };