forked from FlowwStar/FlowStar
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontract.ts
More file actions
814 lines (720 loc) · 25.1 KB
/
Copy pathcontract.ts
File metadata and controls
814 lines (720 loc) · 25.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
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
import {
Address,
Contract,
TransactionBuilder,
nativeToScVal,
scValToNative,
xdr,
rpc as StellarRpc,
} from '@stellar/stellar-sdk'
import { type NetworkName, getNetworkConfig, getServer, getAllTokens } from '@/lib/stellar'
import { mockStore } from '@/lib/mock-data'
import type { CreateStreamInput, StreamData, TokenInfo } from '@/types/stream'
// ─── Helpers ──────────────────────────────────────────────────────────────────
/** Wallet sign callback — must be set by WalletProvider before any write. */
let _signTransaction: ((xdr: string) => Promise<string>) | null = null
export function setSignTransaction(fn: (xdr: string) => Promise<string>) {
_signTransaction = fn
}
async function signTx(xdrStr: string): Promise<string> {
if (!_signTransaction) throw new Error('Wallet not connected')
return _signTransaction(xdrStr)
}
const FEE_BUFFER = 1.15 // 15% above minimum to ensure inclusion
// ─── Retry / timeout ──────────────────────────────────────────────────────────
const REQUEST_TIMEOUT_MS = 30_000
const POLL_TIMEOUT_MS = 60_000
const MAX_RETRIES = 3
const RETRY_DELAYS_MS = [1_000, 2_000, 4_000] as const
function isRetryableError(err: unknown): boolean {
if (err instanceof TypeError) return true // network failure
if (err instanceof Error && (err.message.includes('503') || err.message.includes('429')))
return true
const status =
(err as { status?: number })?.status ??
(err as { response?: { status?: number } })?.response?.status
return status === 429 || status === 503
}
async function fetchWithRetry(url: string, init: RequestInit): Promise<Response> {
let lastErr: unknown
for (let attempt = 0; attempt <= MAX_RETRIES; attempt++) {
const controller = new AbortController()
const timer = setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS)
try {
const res = await fetch(url, { ...init, signal: controller.signal })
if (res.status !== 429 && res.status !== 503) return res
lastErr = new Error(`HTTP ${res.status}`)
} catch (err) {
lastErr = err
} finally {
clearTimeout(timer)
}
if (attempt < MAX_RETRIES)
await new Promise<void>((r) => setTimeout(r, RETRY_DELAYS_MS[attempt]))
}
throw lastErr
}
async function withRetry<T>(fn: () => Promise<T>): Promise<T> {
let lastErr: unknown
for (let attempt = 0; attempt <= MAX_RETRIES; attempt++) {
try {
return await fn()
} catch (err) {
lastErr = err
if (!isRetryableError(err)) throw err
}
if (attempt < MAX_RETRIES)
await new Promise<void>((r) => setTimeout(r, RETRY_DELAYS_MS[attempt]))
}
throw lastErr
}
/** Build and simulate a contract call, returning the prepared tx and estimated fee. */
async function buildAndSimulate(
network: NetworkName,
method: string,
args: xdr.ScVal[],
signerAddress: string,
contractAddress: string,
) {
const config = getNetworkConfig(network)
const server = getServer(network)
const contract = new Contract(contractAddress)
const account = await withRetry(() => server.getAccount(signerAddress))
const tx = new TransactionBuilder(account, {
fee: '100000',
networkPassphrase: config.passphrase,
})
.addOperation(contract.call(method, ...args))
.setTimeout(180)
.build()
const sim = await withRetry(() => server.simulateTransaction(tx))
if (StellarRpc.Api.isSimulationError(sim)) {
throw new Error(`Simulation failed: ${sim.error}`)
}
const successSim = sim as StellarRpc.Api.SimulateTransactionSuccessResponse
const minFee = Number(successSim.minResourceFee ?? 0)
const estimatedFee = Math.ceil(minFee * FEE_BUFFER)
const prepared = StellarRpc.assembleTransaction(tx, sim).build()
return { prepared, estimatedFee, minFee }
}
export type TxStep = 'simulating' | 'signing' | 'submitting' | 'confirming'
/** Build, simulate, sign, and submit a contract call. Returns the transaction hash. */
async function invoke(
network: NetworkName,
method: string,
args: xdr.ScVal[],
signerAddress: string,
contractAddress: string,
onStep?: (step: TxStep) => void,
): Promise<string> {
const config = getNetworkConfig(network)
onStep?.('simulating')
const { prepared } = await buildAndSimulate(network, method, args, signerAddress, contractAddress)
onStep?.('signing')
const signedXdr = await signTx(prepared.toXDR())
onStep?.('submitting')
// Submit the signed XDR directly via the RPC JSON-RPC endpoint.
// We bypass TransactionBuilder.fromXDR because Freighter may return a
// FeeBumpTransaction envelope (type 4) which fromXDR can't handle.
const rpcResponse = await fetchWithRetry(config.rpcUrl, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
jsonrpc: '2.0',
id: 1,
method: 'sendTransaction',
params: { transaction: signedXdr },
}),
})
const rpcJson = (await rpcResponse.json()) as {
result?: { hash: string; status: string; errorResultXdr?: string }
error?: { message: string }
}
if (rpcJson.error) {
throw new Error(`Transaction failed: ${rpcJson.error.message}`)
}
const sendResult = rpcJson.result!
if (sendResult.status === 'ERROR') {
throw new Error(`Transaction failed: ${sendResult.errorResultXdr ?? 'unknown error'}`)
}
// Poll until finalized (max 60 s)
const hash = sendResult.hash
onStep?.('confirming')
let pollStatus = 'PENDING'
const pollDeadline = Date.now() + POLL_TIMEOUT_MS
while (pollStatus !== 'SUCCESS' && pollStatus !== 'FAILED') {
if (Date.now() >= pollDeadline) throw new Error('Transaction confirmation timed out after 60s')
await new Promise<void>((r) => setTimeout(r, 2000))
const pollRes = await fetchWithRetry(config.rpcUrl, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
jsonrpc: '2.0',
id: 1,
method: 'getTransaction',
params: { hash },
}),
})
const pollJson = (await pollRes.json()) as {
result?: { status: string; resultMetaXdr?: string }
error?: { message: string }
}
if (pollJson.error) throw new Error(`Poll failed: ${pollJson.error.message}`)
pollStatus = pollJson.result!.status
}
if (pollStatus === 'FAILED') throw new Error('Transaction failed on-chain')
return hash
}
/** Simulate a read-only call (no signing). */
async function query(
network: NetworkName,
method: string,
args: xdr.ScVal[],
contractAddress: string,
): Promise<xdr.ScVal> {
const config = getNetworkConfig(network)
const server = getServer(network)
const contract = new Contract(contractAddress)
// Use a dummy account for simulation reads
const dummyKeypair = {
accountId: () => 'GAAZI4TCR3TY5OJHCTJC2A4QSY6CJWJH5IAJTGKIN2ER7LBNVKOCCWN',
sequence: () => BigInt(0),
incrementSequenceNumber: () => {},
}
const account = await withRetry(() => server.getAccount(dummyKeypair.accountId()))
const tx = new TransactionBuilder(account, {
fee: '100',
networkPassphrase: config.passphrase,
})
.addOperation(contract.call(method, ...args))
.setTimeout(10)
.build()
const sim = await withRetry(() => server.simulateTransaction(tx))
if (StellarRpc.Api.isSimulationError(sim)) {
throw new Error(`Query failed: ${sim.error}`)
}
return (
(sim as StellarRpc.Api.SimulateTransactionSuccessResponse).result?.retval ?? xdr.ScVal.scvVoid()
)
}
/** Map a contract Stream ScVal → StreamData. */
function scValToStreamData(network: NetworkName, val: xdr.ScVal): StreamData {
const raw = scValToNative(val) as Record<string, unknown>
const tokenAddress = String(raw.token)
const knownTokens = getAllTokens(network)
const knownToken = knownTokens.find((t) => t.address === tokenAddress)
const token: TokenInfo = knownToken ?? {
address: tokenAddress,
symbol: 'UNK',
decimals: 7,
}
return {
id: String(raw.id),
sender: String(raw.sender),
recipient: String(raw.recipient),
token,
depositedAmount: BigInt(raw.deposited_amount as string | number),
withdrawnAmount: BigInt(raw.withdrawn_amount as string | number),
startTime: BigInt(raw.start_time as string | number),
endTime: BigInt(raw.end_time as string | number),
cliffTime: BigInt(raw.cliff_time as string | number),
cliffAmount: BigInt(raw.cliff_amount as string | number),
amountPerSecond: BigInt(raw.amount_per_second as string | number),
linearAmount: BigInt(raw.linear_amount as string | number),
duration: BigInt(raw.duration as string | number),
cancelled: Boolean(raw.cancelled),
}
}
// ─── Public API ───────────────────────────────────────────────────────────────
export interface FeeEstimate {
minFee: number
estimatedFee: number
estimatedFeeXlm: string
}
export interface SimulationPreview {
success: boolean
estimatedFeeXlm: string
estimatedFeeUsd: string
cpuInstructions: number
memoryBytes: number
errorMessage?: string
}
/** Run a dry-run simulation and return a structured preview for display. */
export async function simulateCreateStreamPreview(
network: NetworkName,
input: CreateStreamInput,
sender: string,
): Promise<SimulationPreview> {
const config = getNetworkConfig(network)
const isMockMode = !config.streamContractId
if (isMockMode) {
return {
success: true,
estimatedFeeXlm: '0.0115',
estimatedFeeUsd: '~$0.001',
cpuInstructions: 42_000,
memoryBytes: 128,
}
}
try {
const server = getServer(network)
const contract = new Contract(config.streamContractId)
const account = await withRetry(() => server.getAccount(sender))
const params = xdr.ScVal.scvMap(
[
['cliff_amount', nativeToScVal(input.cliffAmount, { type: 'i128' })],
['cliff_time', nativeToScVal(input.cliffTime, { type: 'u64' })],
['end_time', nativeToScVal(input.endTime, { type: 'u64' })],
['recipient', new Address(input.recipient).toScVal()],
['start_time', nativeToScVal(input.startTime, { type: 'u64' })],
['token', new Address(input.token.address).toScVal()],
['total_amount', nativeToScVal(input.totalAmount, { type: 'i128' })],
].map(
([k, v]) =>
new xdr.ScMapEntry({
key: xdr.ScVal.scvSymbol(k as string),
val: v as xdr.ScVal,
}),
),
)
const tx = new TransactionBuilder(account, {
fee: '100000',
networkPassphrase: config.passphrase,
})
.addOperation(contract.call('create_stream', new Address(sender).toScVal(), params))
.setTimeout(180)
.build()
const sim = await withRetry(() => server.simulateTransaction(tx))
if (StellarRpc.Api.isSimulationError(sim)) {
return {
success: false,
estimatedFeeXlm: '0',
estimatedFeeUsd: '—',
cpuInstructions: 0,
memoryBytes: 0,
errorMessage: sim.error,
}
}
const successSim = sim as StellarRpc.Api.SimulateTransactionSuccessResponse
const minFee = Number(successSim.minResourceFee ?? 0)
const estimatedFee = Math.ceil(minFee * FEE_BUFFER)
const feeXlm = (estimatedFee / 1e7).toFixed(4)
const feeUsd = `~$${((estimatedFee / 1e7) * 0.08).toFixed(4)}`
const resources = successSim.transactionData.build().resources()
return {
success: true,
estimatedFeeXlm: feeXlm,
estimatedFeeUsd: feeUsd,
cpuInstructions: resources.instructions(),
memoryBytes: resources.readBytes() + resources.writeBytes(),
}
} catch (err) {
return {
success: false,
estimatedFeeXlm: '0',
estimatedFeeUsd: '—',
cpuInstructions: 0,
memoryBytes: 0,
errorMessage: err instanceof Error ? err.message : String(err),
}
}
}
export async function estimateCreateStreamFee(
network: NetworkName,
input: CreateStreamInput,
sender: string,
): Promise<FeeEstimate> {
const config = getNetworkConfig(network)
const isMockMode = !config.streamContractId
if (isMockMode) {
return { minFee: 100000, estimatedFee: 115000, estimatedFeeXlm: '0.0115' }
}
const params = xdr.ScVal.scvMap(
[
['cliff_amount', nativeToScVal(input.cliffAmount, { type: 'i128' })],
['cliff_time', nativeToScVal(input.cliffTime, { type: 'u64' })],
['end_time', nativeToScVal(input.endTime, { type: 'u64' })],
['recipient', new Address(input.recipient).toScVal()],
['start_time', nativeToScVal(input.startTime, { type: 'u64' })],
['token', new Address(input.token.address).toScVal()],
['total_amount', nativeToScVal(input.totalAmount, { type: 'i128' })],
].map(
([k, v]) =>
new xdr.ScMapEntry({
key: xdr.ScVal.scvSymbol(k as string),
val: v as xdr.ScVal,
}),
),
)
const { minFee, estimatedFee } = await buildAndSimulate(
network,
'create_stream',
[new Address(sender).toScVal(), params],
sender,
config.streamContractId,
)
return {
minFee,
estimatedFee,
estimatedFeeXlm: (estimatedFee / 1e7).toFixed(4),
}
}
function buildCreateStreamInputScVal(input: CreateStreamInput): xdr.ScVal {
return xdr.ScVal.scvMap(
[
['recipient', new Address(input.recipient).toScVal()],
['token', new Address(input.token.address).toScVal()],
['total_amount', nativeToScVal(input.totalAmount, { type: 'i128' })],
['start_time', nativeToScVal(input.startTime, { type: 'u64' })],
['end_time', nativeToScVal(input.endTime, { type: 'u64' })],
['cliff_time', nativeToScVal(input.cliffTime, { type: 'u64' })],
['cliff_amount', nativeToScVal(input.cliffAmount, { type: 'i128' })],
].map(
([k, v]) =>
new xdr.ScMapEntry({
key: xdr.ScVal.scvSymbol(k as string),
val: v as xdr.ScVal,
}),
),
)
}
function buildCreateStreamParamsScVal(input: CreateStreamInput): xdr.ScVal {
return xdr.ScVal.scvMap(
[
['cliff_amount', nativeToScVal(input.cliffAmount, { type: 'i128' })],
['cliff_time', nativeToScVal(input.cliffTime, { type: 'u64' })],
['end_time', nativeToScVal(input.endTime, { type: 'u64' })],
['recipient', new Address(input.recipient).toScVal()],
['start_time', nativeToScVal(input.startTime, { type: 'u64' })],
['token', new Address(input.token.address).toScVal()],
['total_amount', nativeToScVal(input.totalAmount, { type: 'i128' })],
].map(
([k, v]) =>
new xdr.ScMapEntry({
key: xdr.ScVal.scvSymbol(k as string),
val: v as xdr.ScVal,
}),
),
)
}
export async function createStream(
input: CreateStreamInput,
sender: string,
network: NetworkName = 'testnet',
onStep?: (step: TxStep) => void,
): Promise<string> {
const config = getNetworkConfig(network)
const isMockMode = !config.streamContractId
if (isMockMode) {
await new Promise((r) => setTimeout(r, 700))
return mockStore.create(input, sender).id
}
// Step 1: approve the streaming contract to pull `totalAmount` from the sender.
// The allowance needs to outlast the simulation ledger — set it to current + 500 ledgers.
const server = getServer(network)
const currentLedger = (await withRetry(() => server.getLatestLedger())).sequence
const expirationLedger = currentLedger + 500
await invoke(
network,
'approve',
[
new Address(sender).toScVal(), // from
new Address(config.streamContractId).toScVal(), // spender
nativeToScVal(input.totalAmount, { type: 'i128' }), // amount
nativeToScVal(expirationLedger, { type: 'u32' }), // expiration_ledger
],
sender,
input.token.address, // invoke on the token contract, not the streaming contract
onStep,
)
// Step 2: create the stream.
const params = xdr.ScVal.scvMap(
[
['cliff_amount', nativeToScVal(input.cliffAmount, { type: 'i128' })],
['cliff_time', nativeToScVal(input.cliffTime, { type: 'u64' })],
['end_time', nativeToScVal(input.endTime, { type: 'u64' })],
['recipient', new Address(input.recipient).toScVal()],
['start_time', nativeToScVal(input.startTime, { type: 'u64' })],
['token', new Address(input.token.address).toScVal()],
['total_amount', nativeToScVal(input.totalAmount, { type: 'i128' })],
].map(
([k, v]) =>
new xdr.ScMapEntry({
key: xdr.ScVal.scvSymbol(k as string),
val: v as xdr.ScVal,
}),
),
)
await invoke(
network,
'create_stream',
[new Address(sender).toScVal(), params],
sender,
config.streamContractId,
onStep,
)
// SDK v13 can't parse TransactionMetaV4 (protocol 22+) so returnValue is void.
// Instead, query the sender's stream list and return the highest ID — that's the new stream.
const sentResult = await query(
network,
'get_sent_streams',
[
new Address(sender).toScVal(),
nativeToScVal(0, { type: 'u32' }),
nativeToScVal(1000, { type: 'u32' }),
],
config.streamContractId,
)
const ids = scValToNative(sentResult) as bigint[]
if (!ids || ids.length === 0) throw new Error('Stream created but could not retrieve ID')
const newId = ids.reduce((a, b) => (a > b ? a : b))
return String(newId)
}
export async function createStreamsBatch(
inputs: CreateStreamInput[],
sender: string,
network: NetworkName = 'testnet',
onStep?: (step: TxStep) => void,
): Promise<string[]> {
if (inputs.length === 0) throw new Error('No streams to create')
const config = getNetworkConfig(network)
const isMockMode = !config.streamContractId
if (isMockMode) {
return inputs.map((input) => mockStore.create(input, sender).id)
}
const server = getServer(network)
const currentLedger = (await withRetry(() => server.getLatestLedger())).sequence
const expirationLedger = currentLedger + 500
const approvalsByToken = new Map<string, bigint>()
for (const input of inputs) {
const current = approvalsByToken.get(input.token.address) ?? 0n
approvalsByToken.set(input.token.address, current + input.totalAmount)
}
for (const [tokenAddress, totalAmount] of approvalsByToken.entries()) {
await invoke(
network,
'approve',
[
new Address(sender).toScVal(),
new Address(config.streamContractId).toScVal(),
nativeToScVal(totalAmount, { type: 'i128' }),
nativeToScVal(expirationLedger, { type: 'u32' }),
],
sender,
tokenAddress,
onStep,
)
}
const params = xdr.ScVal.scvVec(inputs.map(buildCreateStreamInputScVal))
await invoke(
network,
'create_streams_batch',
[new Address(sender).toScVal(), params],
sender,
config.streamContractId,
onStep,
)
const sentResult = await query(
network,
'get_sent_streams',
[
new Address(sender).toScVal(),
nativeToScVal(0, { type: 'u32' }),
nativeToScVal(1000, { type: 'u32' }),
],
config.streamContractId,
)
const ids = scValToNative(sentResult) as bigint[]
if (!ids || ids.length < inputs.length) {
throw new Error('Streams created but could not retrieve IDs')
}
const createdIds = [...ids]
.sort((a, b) => Number(a - b))
.slice(-inputs.length)
.map((id) => String(id))
return createdIds
}
export async function withdrawFromStream(
id: string,
amount: bigint,
network: NetworkName = 'testnet',
onStep?: (step: TxStep) => void,
): Promise<string | null> {
const config = getNetworkConfig(network)
const isMockMode = !config.streamContractId
if (isMockMode) {
await new Promise((r) => setTimeout(r, 700))
mockStore.withdraw(id, amount)
return null
}
const stream = await fetchStream(network, id)
if (!stream) throw new Error('Stream not found')
return invoke(
network,
'withdraw',
[nativeToScVal(BigInt(id), { type: 'u64' }), nativeToScVal(amount, { type: 'i128' })],
stream.recipient,
config.streamContractId,
onStep,
)
}
export async function cancelStream(
id: string,
network: NetworkName = 'testnet',
onStep?: (step: TxStep) => void,
): Promise<string | null> {
const config = getNetworkConfig(network)
const isMockMode = !config.streamContractId
if (isMockMode) {
await new Promise((r) => setTimeout(r, 700))
mockStore.cancel(id)
return null
}
const stream = await fetchStream(network, id)
if (!stream) throw new Error('Stream not found')
return invoke(
network,
'cancel',
[nativeToScVal(BigInt(id), { type: 'u64' })],
stream.sender,
config.streamContractId,
onStep,
)
}
export async function getTokenMetadata(
tokenAddress: string,
network: NetworkName = 'testnet',
): Promise<TokenInfo | null> {
try {
const config = getNetworkConfig(network)
const server = getServer(network)
const contract = new Contract(tokenAddress)
const dummyAccount = await withRetry(() =>
server.getAccount('GAAZI4TCR3TY5OJHCTJC2A4QSY6CJWJH5IAJTGKIN2ER7LBNVKOCCWN'),
)
const buildSimTx = (method: string) => {
const tx = new TransactionBuilder(dummyAccount, {
fee: '100',
networkPassphrase: config.passphrase,
})
.addOperation(contract.call(method))
.setTimeout(10)
.build()
return withRetry(() => server.simulateTransaction(tx))
}
const [symSim, decSim] = await Promise.all([buildSimTx('symbol'), buildSimTx('decimals')])
if (StellarRpc.Api.isSimulationError(symSim) || StellarRpc.Api.isSimulationError(decSim)) {
return null
}
const symResult = (symSim as StellarRpc.Api.SimulateTransactionSuccessResponse).result?.retval
const decResult = (decSim as StellarRpc.Api.SimulateTransactionSuccessResponse).result?.retval
if (!symResult || !decResult) return null
const symbol = scValToNative(symResult) as string
const decimals = Number(scValToNative(decResult))
return { address: tokenAddress, symbol, decimals }
} catch {
return null
}
}
export async function getTokenBalance(
tokenAddress: string,
accountAddress: string,
network: NetworkName = 'testnet',
): Promise<bigint> {
const config = getNetworkConfig(network)
const isMockMode = !config.streamContractId
if (isMockMode) return BigInt(1_000_000_0000000) // 1,000,000 units mock
try {
const server = getServer(network)
const contract = new Contract(tokenAddress)
const account = await withRetry(() =>
server.getAccount('GAAZI4TCR3TY5OJHCTJC2A4QSY6CJWJH5IAJTGKIN2ER7LBNVKOCCWN'),
)
const tx = new TransactionBuilder(account, {
fee: '100',
networkPassphrase: config.passphrase,
})
.addOperation(contract.call('balance', new Address(accountAddress).toScVal()))
.setTimeout(10)
.build()
const sim = await withRetry(() => server.simulateTransaction(tx))
if (StellarRpc.Api.isSimulationError(sim)) return 0n
const retval = (sim as StellarRpc.Api.SimulateTransactionSuccessResponse).result?.retval
if (!retval) return 0n
return BigInt(scValToNative(retval) as string | number)
} catch {
return 0n
}
}
export async function bumpStreamTtl(
network: NetworkName,
id: string,
signerAddress: string,
): Promise<void> {
const config = getNetworkConfig(network)
const isMockMode = !config.streamContractId
if (isMockMode) return
await invoke(
network,
'bump_stream',
[nativeToScVal(BigInt(id), { type: 'u64' })],
signerAddress,
config.streamContractId,
)
}
export async function fetchStream(network: NetworkName, id: string): Promise<StreamData | null> {
const config = getNetworkConfig(network)
const isMockMode = !config.streamContractId
if (isMockMode) return mockStore.getById(id) ?? null
try {
const result = await query(
network,
'get_stream',
[nativeToScVal(BigInt(id), { type: 'u64' })],
config.streamContractId,
)
return scValToStreamData(network, result)
} catch {
return null
}
}
export async function fetchStreamsForAddress(
network: NetworkName,
address: string,
): Promise<StreamData[]> {
const config = getNetworkConfig(network)
const isMockMode = !config.streamContractId
if (isMockMode) {
return mockStore.getAll().filter((s) => s.sender === address || s.recipient === address)
}
const [sentIds, receivedIds] = await Promise.all([
query(
network,
'get_sent_streams',
[
new Address(address).toScVal(),
nativeToScVal(0, { type: 'u32' }),
nativeToScVal(1000, { type: 'u32' }),
],
config.streamContractId,
),
query(
network,
'get_received_streams',
[
new Address(address).toScVal(),
nativeToScVal(0, { type: 'u32' }),
nativeToScVal(1000, { type: 'u32' }),
],
config.streamContractId,
),
])
const allIds = [
...(scValToNative(sentIds) as bigint[]),
...(scValToNative(receivedIds) as bigint[]),
]
// Deduplicate (self-streams appear in both)
const unique = [...new Set(allIds.map(String))]
const streams = await Promise.all(unique.map((id) => fetchStream(network, id)))
return streams.filter((s): s is StreamData => s !== null)
}