forked from StellarSend/frontend
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstellar.ts
More file actions
426 lines (363 loc) · 13.1 KB
/
Copy pathstellar.ts
File metadata and controls
426 lines (363 loc) · 13.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
import {
Asset,
Keypair,
Memo,
MemoType,
Networks,
Operation,
Horizon,
TransactionBuilder,
BASE_FEE,
} from '@stellar/stellar-sdk'
import type { Network, StellarAsset, Quote, PathHop } from '@/types'
// ─── Horizon servers ──────────────────────────────────────────────────────────
export function getServer(network: Network): Horizon.Server {
const url =
network === 'testnet'
? 'https://horizon-testnet.stellar.org'
: 'https://horizon.stellar.org'
return new Horizon.Server(url)
}
export function getNetworkPassphrase(network: Network): string {
return network === 'testnet' ? Networks.TESTNET : Networks.PUBLIC
}
// ─── Asset helpers ────────────────────────────────────────────────────────────
export function toStellarAsset(asset: StellarAsset): Asset {
if (asset.code === 'XLM' && !asset.issuer) {
return Asset.native()
}
if (!asset.issuer) throw new Error(`Non-native asset "${asset.code}" is missing issuer`)
return new Asset(asset.code, asset.issuer)
}
export function pathHopToAsset(hop: PathHop): Asset {
if (hop.assetCode === 'XLM' && !hop.assetIssuer) return Asset.native()
if (!hop.assetIssuer) throw new Error(`Path hop asset "${hop.assetCode}" missing issuer`)
return new Asset(hop.assetCode, hop.assetIssuer)
}
export function assetFromCodeIssuer(code: string, issuer: string | null): Asset {
if (code === 'XLM' && !issuer) return Asset.native()
if (!issuer) throw new Error(`Asset ${code} requires an issuer`)
return new Asset(code, issuer)
}
// ─── Fee estimation ───────────────────────────────────────────────────────────
export async function estimateFee(network: Network): Promise<string> {
try {
const server = getServer(network)
const feeStats = await server.feeStats()
// Use the p70 fee rate for reliable inclusion
const feeRate = parseInt(feeStats.fee_charged.p70, 10) || parseInt(BASE_FEE, 10)
return String(Math.max(feeRate, parseInt(BASE_FEE, 10)))
} catch {
return BASE_FEE
}
}
// ─── Build payment transaction ────────────────────────────────────────────────
interface BuildPaymentParams {
sourcePublicKey: string
destinationAddress: string
asset: StellarAsset
amount: string
memo?: string
network: Network
timeoutSeconds?: number
}
export async function buildPaymentTransaction(
params: BuildPaymentParams,
): Promise<string> {
const {
sourcePublicKey,
destinationAddress,
asset,
amount,
memo,
network,
timeoutSeconds = 30,
} = params
const server = getServer(network)
const passphrase = getNetworkPassphrase(network)
const fee = await estimateFee(network)
const sourceAccount = await server.loadAccount(sourcePublicKey)
const stellarAsset = toStellarAsset(asset)
const builder = new TransactionBuilder(sourceAccount, {
fee,
networkPassphrase: passphrase,
})
.addOperation(
Operation.payment({
destination: destinationAddress,
asset: stellarAsset,
amount,
}),
)
.setTimeout(timeoutSeconds)
if (memo) {
const trimmed = memo.trim()
if (trimmed) {
// Auto-detect memo type
if (/^\d+$/.test(trimmed) && BigInt(trimmed) <= BigInt('18446744073709551615')) {
builder.addMemo(Memo.id(trimmed))
} else {
builder.addMemo(Memo.text(trimmed.slice(0, 28)))
}
}
}
const tx = builder.build()
return tx.toXDR()
}
// ─── Build path payment transaction ──────────────────────────────────────────
interface BuildPathPaymentParams {
sourcePublicKey: string
destinationAddress: string
sendAsset: StellarAsset
destAsset: StellarAsset
sendAmount: string
destMin: string // minimum destination amount (after slippage)
path: PathHop[]
memo?: string
network: Network
timeoutSeconds?: number
}
export async function buildPathPaymentTransaction(
params: BuildPathPaymentParams,
): Promise<string> {
const {
sourcePublicKey,
destinationAddress,
sendAsset,
destAsset,
sendAmount,
destMin,
path,
memo,
network,
timeoutSeconds = 30,
} = params
const server = getServer(network)
const passphrase = getNetworkPassphrase(network)
const fee = await estimateFee(network)
const sourceAccount = await server.loadAccount(sourcePublicKey)
const stellarSendAsset = toStellarAsset(sendAsset)
const stellarDestAsset = toStellarAsset(destAsset)
const stellarPath = path.map(pathHopToAsset)
const builder = new TransactionBuilder(sourceAccount, {
fee,
networkPassphrase: passphrase,
})
.addOperation(
Operation.pathPaymentStrictSend({
sendAsset: stellarSendAsset,
sendAmount,
destination: destinationAddress,
destAsset: stellarDestAsset,
destMin,
path: stellarPath,
}),
)
.setTimeout(timeoutSeconds)
if (memo?.trim()) {
const trimmed = memo.trim()
if (/^\d+$/.test(trimmed) && BigInt(trimmed) <= BigInt('18446744073709551615')) {
builder.addMemo(Memo.id(trimmed))
} else {
builder.addMemo(Memo.text(trimmed.slice(0, 28)))
}
}
return builder.build().toXDR()
}
// ─── Build from quote ─────────────────────────────────────────────────────────
export async function buildTransactionFromQuote(
quote: Quote,
sourcePublicKey: string,
destinationAddress: string,
network: Network,
memo?: string,
): Promise<string> {
const slippage = parseFloat(quote.slippageTolerance) / 100
const destMin = (
parseFloat(quote.receiveAmount) * (1 - slippage)
).toFixed(7)
if (quote.path.length > 0) {
return buildPathPaymentTransaction({
sourcePublicKey,
destinationAddress,
sendAsset: quote.sourceAsset,
destAsset: quote.destinationAsset,
sendAmount: quote.sendAmount,
destMin,
path: quote.path,
memo,
network,
})
}
return buildPaymentTransaction({
sourcePublicKey,
destinationAddress,
asset: quote.sourceAsset,
amount: quote.sendAmount,
memo,
network,
})
}
// ─── Build batch / split payment transaction ─────────────────────────────────
// One transaction, one payment operation per recipient — this is what makes it
// a true "batch": either every payment in the batch lands atomically, or (if
// the transaction fails) none of them do.
interface BatchRecipientInput {
destinationAddress: string
amount: string
}
interface BuildBatchPaymentParams {
sourcePublicKey: string
asset: StellarAsset
recipients: BatchRecipientInput[]
memo?: string
network: Network
timeoutSeconds?: number
}
export const MAX_BATCH_RECIPIENTS = 100
export async function buildBatchPaymentTransaction(
params: BuildBatchPaymentParams,
): Promise<string> {
const { sourcePublicKey, asset, recipients, memo, network, timeoutSeconds = 30 } = params
if (recipients.length === 0) {
throw new Error('A batch payment needs at least one recipient')
}
if (recipients.length > MAX_BATCH_RECIPIENTS) {
throw new Error(`A batch payment supports at most ${MAX_BATCH_RECIPIENTS} recipients`)
}
const server = getServer(network)
const passphrase = getNetworkPassphrase(network)
const fee = await estimateFee(network)
const sourceAccount = await server.loadAccount(sourcePublicKey)
const stellarAsset = toStellarAsset(asset)
// `estimateFee` returns a per-operation fee. `TransactionBuilder.build()`
// multiplies it by the operation count internally (baseFee x ops.length), so
// passing the raw value — like buildPaymentTransaction/buildPathPaymentTransaction
// do — yields a total fee that scales linearly with the number of recipients.
const builder = new TransactionBuilder(sourceAccount, {
fee,
networkPassphrase: passphrase,
})
for (const recipient of recipients) {
builder.addOperation(
Operation.payment({
destination: recipient.destinationAddress,
asset: stellarAsset,
amount: recipient.amount,
}),
)
}
builder.setTimeout(timeoutSeconds)
if (memo?.trim()) {
const trimmed = memo.trim()
if (/^\d+$/.test(trimmed) && BigInt(trimmed) <= BigInt('18446744073709551615')) {
builder.addMemo(Memo.id(trimmed))
} else {
builder.addMemo(Memo.text(trimmed.slice(0, 28)))
}
}
return builder.build().toXDR()
}
// ─── Submit transaction ───────────────────────────────────────────────────────
export async function submitTransaction(
signedXdr: string,
network: Network,
): Promise<{ hash: string; ledger: number }> {
const server = getServer(network)
const tx = TransactionBuilder.fromXDR(signedXdr, getNetworkPassphrase(network))
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const result = await server.submitTransaction(tx as any)
return {
hash: result.hash,
ledger: result.ledger,
}
}
// ─── Validate Stellar address ─────────────────────────────────────────────────
export function isValidStellarAddress(address: string): boolean {
try {
Keypair.fromPublicKey(address)
return true
} catch {
return false
}
}
// ─── Truncate address ─────────────────────────────────────────────────────────
export function truncateAddress(address: string, chars = 6): string {
if (!address) return ''
return `${address.slice(0, chars)}...${address.slice(-chars)}`
}
// ─── Format amounts ───────────────────────────────────────────────────────────
export function formatAmount(
amount: string | number,
decimals = 2,
symbol = '',
): string {
const num = typeof amount === 'string' ? parseFloat(amount) : amount
if (isNaN(num)) return '—'
const formatted = new Intl.NumberFormat('en-US', {
minimumFractionDigits: decimals,
maximumFractionDigits: decimals,
}).format(num)
return symbol ? `${formatted} ${symbol}` : formatted
}
export function formatXLM(amount: string | number): string {
return formatAmount(amount, 4, 'XLM')
}
export function formatUSD(amount: string | number): string {
const num = typeof amount === 'string' ? parseFloat(amount) : amount
if (isNaN(num)) return '—'
return new Intl.NumberFormat('en-US', {
style: 'currency',
currency: 'USD',
minimumFractionDigits: 2,
maximumFractionDigits: 2,
}).format(num)
}
// ─── Apply slippage ───────────────────────────────────────────────────────────
export function applySlippage(amount: string, slippagePct: string): string {
const a = parseFloat(amount)
const s = parseFloat(slippagePct) / 100
return (a * (1 - s)).toFixed(7)
}
// ─── Resolve asset from Horizon ───────────────────────────────────────────────
export async function resolveAsset(
code: string,
network: Network,
): Promise<StellarAsset[]> {
if (code.toUpperCase() === 'XLM') {
return [{ code: 'XLM', issuer: null, name: 'Stellar Lumens', decimals: 7 }]
}
const server = getServer(network)
const records = await server
.assets()
.forCode(code.toUpperCase())
.limit(5)
.call()
return records.records.map((r) => ({
code: r.asset_code,
issuer: r.asset_issuer,
name: r.asset_code,
decimals: 7,
}))
}
// ─── Find payment paths ───────────────────────────────────────────────────────
export async function findPaymentPaths(
sourcePublicKey: string,
destinationAsset: StellarAsset,
destinationAmount: string,
network: Network,
): Promise<PathHop[][]> {
const server = getServer(network)
const destAsset = toStellarAsset(destinationAsset)
const result = await server
.strictReceivePaths(sourcePublicKey, destAsset, destinationAmount)
.call()
return result.records.map((r) =>
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(r.path || []).map((p: any) => ({
assetCode: p.asset_type === 'native' ? 'XLM' : p.asset_code,
assetIssuer: p.asset_type === 'native' ? null : p.asset_issuer,
})),
)
}
export type { MemoType }