forked from StellarSplit/StellarSplit
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpath-payment.service.ts
More file actions
363 lines (327 loc) · 10.2 KB
/
Copy pathpath-payment.service.ts
File metadata and controls
363 lines (327 loc) · 10.2 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
import { Injectable, Logger } from '@nestjs/common';
import {
Horizon,
Asset,
Keypair,
TransactionBuilder,
Operation,
Networks,
} from '@stellar/stellar-sdk';
import { ExchangeRateTrackerService } from './exchange-rate-tracker.service';
export interface PathPaymentOptions {
sourceAccount: string;
sourceSecret?: string; // Optional, only if building transaction
destinationAccount: string;
sourceAsset: Asset;
destinationAsset: Asset;
destinationAmount: number;
maxSourceAmount?: number;
slippageTolerance?: number; // Percentage (0.01 = 1%)
}
export interface PathPaymentResult {
success: boolean;
txHash?: string;
sourceAmount: number;
destinationAmount: number;
path: Asset[];
exchangeRate: number;
slippage?: number;
error?: string;
}
@Injectable()
export class PathPaymentService {
private readonly logger = new Logger(PathPaymentService.name);
private readonly horizonServer: Horizon.Server;
private readonly networkPassphrase: string;
constructor(
private readonly exchangeRateTracker: ExchangeRateTrackerService,
) {
const isMainnet = process.env.STELLAR_NETWORK === 'mainnet';
this.horizonServer = new Horizon.Server(
isMainnet
? 'https://horizon.stellar.org'
: 'https://horizon-testnet.stellar.org',
);
this.networkPassphrase = isMainnet
? Networks.PUBLIC
: Networks.TESTNET;
}
/**
* Find the best path for a path payment
* Uses Stellar's strict receive path payment to find optimal conversion path
*/
async findBestPath(
sourceAsset: Asset,
destinationAsset: Asset,
destinationAmount: number,
): Promise<{
sourceAmount: number;
path: Asset[];
rate: number;
}> {
try {
this.logger.log(
`Finding best path for ${destinationAmount} ${this.exchangeRateTracker.formatAsset(destinationAsset)}`,
);
// Query strict receive paths
// strictReceivePaths expects source assets as array or string
const paths = await this.horizonServer
.strictReceivePaths(
[sourceAsset],
destinationAsset,
destinationAmount.toString(),
)
.call();
if (paths.records.length === 0) {
throw new Error(
`No path found from ${this.exchangeRateTracker.formatAsset(sourceAsset)} to ${this.exchangeRateTracker.formatAsset(destinationAsset)} for amount ${destinationAmount}`,
);
}
// Get the best path (first record is usually the best)
const bestPath = paths.records[0];
const sourceAmount = parseFloat(bestPath.source_amount);
const rate = destinationAmount / sourceAmount;
// Extract path assets
const path: Asset[] = bestPath.path.map((asset: any) => {
if (asset.asset_type === 'native') {
return Asset.native();
}
return new Asset(asset.asset_code, asset.asset_issuer);
});
this.logger.log(
`Best path found: ${sourceAmount} ${this.exchangeRateTracker.formatAsset(sourceAsset)} -> ${destinationAmount} ${this.exchangeRateTracker.formatAsset(destinationAsset)} (rate: ${rate})`,
);
return {
sourceAmount,
path,
rate,
};
} catch (error: any) {
this.logger.error(`Error finding best path: ${error.message}`, error.stack);
throw error;
}
}
/**
* Build a path payment strict receive transaction
* This creates a transaction that can be signed and submitted by the client
*/
async buildPathPaymentTransaction(
options: PathPaymentOptions,
): Promise<{
transactionXDR: string;
sourceAmount: number;
destinationAmount: number;
path: Asset[];
exchangeRate: number;
maxSourceAmount: number;
}> {
try {
const {
sourceAccount,
destinationAccount,
sourceAsset,
destinationAsset,
destinationAmount,
slippageTolerance = 0.01, // 1% default
} = options;
// Find best path
const pathInfo = await this.findBestPath(
sourceAsset,
destinationAsset,
destinationAmount,
);
// Calculate max source amount with slippage tolerance
const maxSourceAmount = pathInfo.sourceAmount * (1 + slippageTolerance);
// Get source account details
const account = await this.horizonServer
.loadAccount(sourceAccount);
// Build transaction
const transaction = new TransactionBuilder(account, {
fee: '100', // Base fee
networkPassphrase: this.networkPassphrase,
})
.addOperation(
Operation.pathPaymentStrictReceive({
sendAsset: sourceAsset,
sendMax: maxSourceAmount.toString(),
destination: destinationAccount,
destAsset: destinationAsset,
destAmount: destinationAmount.toString(),
path: pathInfo.path,
}),
)
.setTimeout(180) // 3 minutes
.build();
const transactionXDR = transaction.toXDR();
this.logger.log(
`Built path payment transaction: ${maxSourceAmount} ${this.exchangeRateTracker.formatAsset(sourceAsset)} -> ${destinationAmount} ${this.exchangeRateTracker.formatAsset(destinationAsset)}`,
);
return {
transactionXDR,
sourceAmount: pathInfo.sourceAmount,
destinationAmount,
path: pathInfo.path,
exchangeRate: pathInfo.rate,
maxSourceAmount,
};
} catch (error: any) {
this.logger.error(
`Error building path payment transaction: ${error.message}`,
error.stack,
);
throw error;
}
}
/**
* Verify a path payment transaction
* Checks if a transaction hash represents a valid path payment
*/
async verifyPathPayment(txHash: string): Promise<PathPaymentResult> {
try {
this.logger.log(`Verifying path payment transaction: ${txHash}`);
// Fetch transaction
const transaction = await this.horizonServer
.transactions()
.transaction(txHash)
.call();
if (!transaction || !transaction.successful) {
return {
success: false,
sourceAmount: 0,
destinationAmount: 0,
path: [],
exchangeRate: 0,
error: 'Transaction not found or unsuccessful',
};
}
// Get operations
const operations = await this.horizonServer
.operations()
.forTransaction(txHash)
.call();
// Find path payment operation
const pathPaymentOp = operations.records.find(
(op: any) =>
op.type === 'path_payment_strict_receive' ||
op.type === 'path_payment_strict_send',
);
if (!pathPaymentOp) {
return {
success: false,
sourceAmount: 0,
destinationAmount: 0,
path: [],
exchangeRate: 0,
error: 'No path payment operation found',
};
}
let sourceAmount = 0;
let destinationAmount = 0;
let sourceAsset: Asset;
let destinationAsset: Asset;
const path: Asset[] = [];
if (pathPaymentOp.type === 'path_payment_strict_receive') {
const op = pathPaymentOp as any;
sourceAmount = parseFloat(op.source_amount);
destinationAmount = parseFloat(op.amount);
sourceAsset =
op.source_asset_type === 'native'
? Asset.native()
: new Asset(op.source_asset_code, op.source_asset_issuer);
destinationAsset =
op.dest_asset_type === 'native'
? Asset.native()
: new Asset(op.dest_asset_code, op.dest_asset_issuer);
// Extract path
if (op.path) {
path.push(
...op.path.map((asset: any) => {
if (asset.asset_type === 'native') {
return Asset.native();
}
return new Asset(asset.asset_code, asset.asset_issuer);
}),
);
}
} else if (pathPaymentOp.type === 'path_payment_strict_send') {
const op = pathPaymentOp as any;
sourceAmount = parseFloat(op.amount);
destinationAmount = parseFloat(op.destination_amount);
sourceAsset =
op.asset_type === 'native'
? Asset.native()
: new Asset(op.asset_code, op.asset_issuer);
destinationAsset =
op.destination_asset_type === 'native'
? Asset.native()
: new Asset(op.destination_asset_code, op.destination_asset_issuer);
// Extract path
if (op.path) {
path.push(
...op.path.map((asset: any) => {
if (asset.asset_type === 'native') {
return Asset.native();
}
return new Asset(asset.asset_code, asset.asset_issuer);
}),
);
}
} else {
return {
success: false,
sourceAmount: 0,
destinationAmount: 0,
path: [],
exchangeRate: 0,
error: 'Invalid path payment operation type',
};
}
const exchangeRate = destinationAmount / sourceAmount;
this.logger.log(
`Path payment verified: ${sourceAmount} ${this.exchangeRateTracker.formatAsset(sourceAsset)} -> ${destinationAmount} ${this.exchangeRateTracker.formatAsset(destinationAsset)}`,
);
return {
success: true,
txHash,
sourceAmount,
destinationAmount,
path,
exchangeRate,
};
} catch (error: any) {
this.logger.error(
`Error verifying path payment: ${error.message}`,
error.stack,
);
return {
success: false,
sourceAmount: 0,
destinationAmount: 0,
path: [],
exchangeRate: 0,
error: error.message,
};
}
}
/**
* Calculate slippage for a path payment
*/
calculateSlippage(
expectedAmount: number,
actualAmount: number,
): number {
if (expectedAmount === 0) return 0;
return Math.abs((actualAmount - expectedAmount) / expectedAmount) * 100;
}
/**
* Check if slippage is within tolerance
*/
isSlippageAcceptable(
expectedAmount: number,
actualAmount: number,
tolerance: number,
): boolean {
const slippage = this.calculateSlippage(expectedAmount, actualAmount);
return slippage <= tolerance * 100; // Convert to percentage
}
}