-
Notifications
You must be signed in to change notification settings - Fork 106
Expand file tree
/
Copy pathstellar.ts
More file actions
1687 lines (1459 loc) · 54.1 KB
/
Copy pathstellar.ts
File metadata and controls
1687 lines (1459 loc) · 54.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
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* stellar.ts — thin wrapper around @stellar/stellar-sdk for FlowPay
*
* All contract interactions go through here so the UI stays clean.
*/
import {
Contract,
Networks,
TransactionBuilder,
BASE_FEE,
nativeToScVal,
Address,
Account,
xdr,
} from "@stellar/stellar-sdk";
import { Server, assembleTransaction } from "@stellar/stellar-sdk/rpc";
import type { Subscription, ChargeEvent, SubscriptionValidationReport } from "./types";
import { ScValDecoder } from "./services/scval";
import { dedupedCall } from "./services/rpcCache";
// ── Config ────────────────────────────────────────────────────────────────────
export const RPC_URL = import.meta.env.VITE_RPC_URL ?? "https://soroban-testnet.stellar.org";
export const NETWORK_PASSPHRASE = import.meta.env.VITE_NETWORK_PASSPHRASE || Networks.TESTNET;
// Replace with your deployed contract ID after `soroban contract deploy`
export const CONTRACT_ID = import.meta.env.VITE_CONTRACT_ID ?? "";
export const TOKEN_CONTRACT_ID = import.meta.env.VITE_TOKEN_CONTRACT_ID ?? "";
// Default token address (XLM) - replace with your actual token
export const DEFAULT_TOKEN =
import.meta.env.VITE_DEFAULT_TOKEN ?? "CAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABSC4";
export const server = new Server(RPC_URL);
/**
* Returns a Server instance pointing at the active RPC URL.
* If the user has saved a custom RPC URL in localStorage it takes precedence;
* otherwise the build-time VITE_RPC_URL (or its fallback) is used.
*
* Every call creates a new Server instance so callers always get the latest URL.
* For high-frequency work (polling hooks) the module-level `server` singleton is
* still appropriate, but one-off transaction calls should prefer getServer().
*/
export function getServer(): Server {
try {
const stored =
typeof localStorage !== "undefined" ? localStorage.getItem("flowpay_custom_rpc_url") : null;
const customUrl: string | null = stored ? (JSON.parse(stored) as string) : null;
if (customUrl) return new Server(customUrl);
} catch {
// localStorage unavailable or invalid JSON
}
return server;
}
// Stellar.expert explorer link for a transaction, on the active network.
export function explorerTxUrl(hash: string): string {
const network = NETWORK_PASSPHRASE === Networks.PUBLIC ? "public" : "testnet";
return `https://stellar.expert/explorer/${network}/tx/${hash}`;
}
export interface MerchantSubscriber {
subscriber: string;
amount: string;
interval: number;
lastCharged: number;
nextChargeAt: number;
}
export interface ContractEvent {
eventName: string;
address: string;
data: unknown;
ledger: number;
timestamp: string;
txHash: string;
}
// ── Helpers ────────────────────────────────────────────────────────────────────
/** Practical C-prefixed Stellar contract ID shape check */
export function isValidContractIdShape(id: string): boolean {
return (
typeof id === "string" && id.startsWith("C") && id.length === 56 && /^[A-Z0-9]+$/i.test(id)
);
}
/** Convert a Stellar public key string to an ScVal Address */
function addressVal(addr: string): xdr.ScVal {
return nativeToScVal(Address.fromString(addr), { type: "address" });
}
/** Build, simulate, and return a ready-to-sign XDR transaction */
async function buildTx(
sourcePublicKey: string,
method: string,
args: xdr.ScVal[]
): Promise<string> {
if (!CONTRACT_ID) {
throw new Error("VITE_CONTRACT_ID environment variable is not set");
}
if (!isValidContractIdShape(CONTRACT_ID)) {
throw new Error("VITE_CONTRACT_ID is not a valid Soroban contract address");
}
if (typeof window !== "undefined" && window.freighter) {
try {
const { networkPassphrase } = await window.freighter.getNetwork();
if (networkPassphrase !== NETWORK_PASSPHRASE) {
throw new Error(
"Wallet network passphrase mismatch with configured VITE_NETWORK_PASSPHRASE"
);
}
} catch {
// Older Freighter or getNetwork failure
}
}
const s = getServer();
const account = await s.getAccount(sourcePublicKey);
const contract = new Contract(CONTRACT_ID);
const tx = new TransactionBuilder(account, {
fee: BASE_FEE,
networkPassphrase: NETWORK_PASSPHRASE,
})
.addOperation(contract.call(method, ...args))
.setTimeout(30)
.build();
const simResult = await s.simulateTransaction(tx);
if ("error" in simResult) throw new Error(simResult.error);
const assembled = assembleTransaction(tx, simResult) as unknown as { toXDR(): string };
return assembled.toXDR();
}
// ── Public API ────────────────────────────────────────────────────────────────
export async function buildSubscribeTx(
user: string,
merchant: string,
amount: bigint,
intervalSec: bigint,
tokenAddr: string,
referrer: string | null,
label: string
): Promise<string> {
const referrerVal = referrer ? { tag: "Some", val: addressVal(referrer) } : { tag: "None" };
return buildTx(user, "subscribe", [
addressVal(user),
addressVal(merchant),
nativeToScVal(amount, { type: "i128" }),
nativeToScVal(intervalSec, { type: "u64" }),
addressVal(tokenAddr),
nativeToScVal(referrerVal, { type: "option" }),
nativeToScVal(label, { type: "symbol" }),
]);
}
export async function buildCancelTx(user: string): Promise<string> {
return buildTx(user, "cancel", [addressVal(user)]);
}
export async function buildPayPerUseTx(user: string, amount: bigint): Promise<string> {
return buildTx(user, "pay_per_use", [addressVal(user), nativeToScVal(amount, { type: "i128" })]);
}
export async function buildPauseTx(user: string): Promise<string> {
return buildTx(user, "pause", [addressVal(user)]);
}
/**
* Builds a `pause_until` transaction that pauses the subscription up to a
* specific Unix timestamp (seconds). The contract rejects (InvalidPauseExpiry)
* any `expiry` that is not strictly in the future, so callers should validate
* client-side before building the transaction to avoid a wasted round trip.
*/
export async function buildPauseUntilTx(user: string, expiry: bigint): Promise<string> {
return buildTx(user, "pause_until", [addressVal(user), nativeToScVal(expiry, { type: "u64" })]);
}
export async function buildResumeTx(user: string): Promise<string> {
return buildTx(user, "resume", [addressVal(user)]);
}
export async function buildTransferSubscriptionTx(user: string, newUser: string): Promise<string> {
return buildTx(user, "transfer_subscription", [addressVal(user), addressVal(newUser)]);
}
export async function buildSetDailyLimitTx(user: string, amount: bigint): Promise<string> {
return buildTx(user, "set_daily_limit", [
addressVal(user),
nativeToScVal(amount, { type: "i128" }),
]);
}
export type BatchChargeOutcome =
| "Charged"
| "Skipped"
| "NoSubscription"
| "Inactive"
| "Paused"
| "GracePeriodElapsed"
| "Failed";
export async function buildBatchChargeTx(merchantWallet: string, users: string[]): Promise<string> {
return buildTx(merchantWallet, "batch_charge", [
// batch_charge(users: Vec<Address>)
users.map((u) => addressVal(u)),
] as unknown as xdr.ScVal[]);
}
export async function simulateBatchCharge(
merchantWallet: string,
users: string[]
): Promise<BatchChargeOutcome[]> {
if (users.length === 0) return [];
const s = getServer();
const account = await s.getAccount(merchantWallet);
const contract = new Contract(CONTRACT_ID);
const tx = new TransactionBuilder(account, {
fee: BASE_FEE,
networkPassphrase: NETWORK_PASSPHRASE,
})
.addOperation(
// call batch_charge(users: Vec<Address>)
contract.call("batch_charge", [users.map((u) => addressVal(u))] as any)
)
.setTimeout(30)
.build();
const simResult = await s.simulateTransaction(tx);
if ("error" in simResult) throw new Error(simResult.error);
// Best-effort decode of return Vec<ChargeResult>
try {
const retval = (simResult as any)?.result?.[0]?.retval ?? (simResult as any)?.result?.retval;
if (!retval) return [];
// ScVal Vec access patterns differ across SDK versions; do best-effort.
const vecItems =
typeof retval.vec === "function"
? (retval.vec() as any[])
: (retval._value?.vec ?? retval._value?.vec);
if (!Array.isArray(vecItems)) return [];
return vecItems.map((item: any) => {
const variantName = item?.switch?.()?.name ?? item?.switch?.().name ?? item?.name;
if (
variantName === "Charged" ||
variantName === "Skipped" ||
variantName === "NoSubscription" ||
variantName === "Inactive" ||
variantName === "Paused" ||
variantName === "GracePeriodElapsed"
) {
return variantName;
}
return "Failed";
});
} catch {
return [];
}
}
/**
* Returns the trial end timestamp (Unix seconds) for a user's subscription,
* or null if no trial is active (contract returns None).
*
* The contract encodes the trial end directly in `last_charged` — it returns
* `Some(last_charged)` when `last_charged > now`, and `None` once the trial
* has expired.
*/
export function getTrialEnd(user: string): Promise<bigint | null> {
return dedupedCall(`getTrialEnd:${user}`, async () => {
const s = getServer();
const contract = new Contract(CONTRACT_ID);
const account = await s.getAccount(user);
const tx = new TransactionBuilder(account, {
fee: BASE_FEE,
networkPassphrase: NETWORK_PASSPHRASE,
})
.addOperation(contract.call("get_trial_end", addressVal(user)))
.setTimeout(30)
.build();
const result = await s.simulateTransaction(tx);
if ("error" in result) throw new Error((result as { error: string }).error);
const retval = (result as { result?: { retval?: xdr.ScVal } }).result?.retval;
if (!retval) return null;
return ScValDecoder.decodeOption(retval, ScValDecoder.decodeU64);
});
}
export function getDailyLimit(user: string): Promise<bigint | null> {
return dedupedCall(`getDailyLimit:${user}`, async () => {
const s = getServer();
const contract = new Contract(CONTRACT_ID);
const account = await s.getAccount(user);
const tx = new TransactionBuilder(account, {
fee: BASE_FEE,
networkPassphrase: NETWORK_PASSPHRASE,
})
.addOperation(contract.call("get_daily_limit", addressVal(user)))
.setTimeout(30)
.build();
const result = await s.simulateTransaction(tx);
if ("error" in result) throw new Error((result as { error: string }).error);
const retval = (result as { result?: { retval?: xdr.ScVal } }).result?.retval;
if (!retval) return null;
return ScValDecoder.decodeOption(retval, ScValDecoder.decodeI128);
});
}
export function getDailySpent(user: string): Promise<bigint> {
return dedupedCall(`getDailySpent:${user}`, async () => {
const s = getServer();
const contract = new Contract(CONTRACT_ID);
const account = await s.getAccount(user);
const tx = new TransactionBuilder(account, {
fee: BASE_FEE,
networkPassphrase: NETWORK_PASSPHRASE,
})
.addOperation(contract.call("get_daily_spent", addressVal(user)))
.setTimeout(30)
.build();
const result = await s.simulateTransaction(tx);
if ("error" in result) throw new Error((result as { error: string }).error);
const retval = (result as { result?: { retval?: xdr.ScVal } }).result?.retval;
if (!retval) return 0n;
try {
return ScValDecoder.decodeI128(retval);
} catch {
return 0n;
}
});
}
export function getDayStart(user: string): Promise<bigint | null> {
return dedupedCall(`getDayStart:${user}`, async () => {
const contract = new Contract(CONTRACT_ID);
const account = await server.getAccount(user);
const tx = new TransactionBuilder(account, {
fee: BASE_FEE,
networkPassphrase: NETWORK_PASSPHRASE,
})
.addOperation(contract.call("get_day_start", addressVal(user)))
.setTimeout(30)
.build();
const result = await server.simulateTransaction(tx);
if ("error" in result) throw new Error((result as { error: string }).error);
const retval = (result as { result?: { retval?: xdr.ScVal } }).result?.retval;
if (!retval || retval.switch().name === "scvVoid") return null;
// Contract returns Option<u64> (timestamp of window start). Some deployments may return bool.
const type = retval.switch().name;
if (type === "scvBool") {
return retval.b() ? 1n : null;
}
try {
const decoded = ScValDecoder.decodeOption(retval, ScValDecoder.decodeU64);
return decoded;
} catch {
// Fallback: try direct u64
try {
return ScValDecoder.decodeU64(retval);
} catch {
return null;
}
}
});
}
export interface DailyLimitStatus {
limit: bigint | null;
spent: bigint;
remaining: bigint | null;
dayActive: boolean;
dayStart: bigint | null;
}
export async function getDailyLimitStatus(user: string): Promise<DailyLimitStatus> {
const [limit, spent, dayStart] = await Promise.all([
getDailyLimit(user),
getDailySpent(user),
getDayStart(user),
]);
const dayActive = dayStart !== null;
const remaining = limit !== null ? (limit > spent ? limit - spent : 0n) : null;
return { limit, spent, remaining, dayActive, dayStart };
}
export async function buildApproveTx(
user: string,
tokenId: string,
spender: string,
amount: bigint
): Promise<string> {
const tokenContract = new Contract(tokenId);
const s = getServer();
const account = await s.getAccount(user);
const tx = new TransactionBuilder(account, {
fee: BASE_FEE,
networkPassphrase: NETWORK_PASSPHRASE,
})
.addOperation(
tokenContract.call(
"approve",
addressVal(user),
addressVal(spender),
nativeToScVal(amount, { type: "i128" }),
nativeToScVal(999999999n, { type: "u64" })
)
)
.setTimeout(30)
.build();
const simResult = await s.simulateTransaction(tx);
if ("error" in simResult) throw new Error(simResult.error);
const assembled = assembleTransaction(tx, simResult) as unknown as { toXDR(): string };
return assembled.toXDR();
}
export function getSubscription(user: string): Promise<Subscription | null> {
return dedupedCall(`getSubscription:${user}`, async () => {
const s = getServer();
const contract = new Contract(CONTRACT_ID);
const account = await s.getAccount(user);
const tx = new TransactionBuilder(account, {
fee: BASE_FEE,
networkPassphrase: NETWORK_PASSPHRASE,
})
.addOperation(contract.call("get_subscription", addressVal(user)))
.setTimeout(30)
.build();
const result = await s.simulateTransaction(tx);
if ("error" in result) throw new Error((result as { error: string }).error);
const retval = (result as { result?: { retval?: xdr.ScVal } }).result?.retval;
if (!retval || retval.switch().name === "scvVoid") return null;
const subscriptionData = ScValDecoder.decodeStruct(retval, {
merchant: ScValDecoder.decodeAddress,
amount: (v) => ScValDecoder.decodeI128(v).toString(),
interval: (v) => Number(ScValDecoder.decodeU64(v)),
last_charged: (v) => Number(ScValDecoder.decodeU64(v)),
active: ScValDecoder.decodeBool,
paused: ScValDecoder.decodeBool,
token: ScValDecoder.decodeAddress,
referrer: (v) => ScValDecoder.decodeOption(v, ScValDecoder.decodeAddress),
label: ScValDecoder.decodeSymbol,
trial_duration: (v) => Number(ScValDecoder.decodeU64(v)),
});
const label = await getSubscriptionMetadata(user);
return {
merchant: subscriptionData.merchant,
amount: subscriptionData.amount,
interval: subscriptionData.interval,
last_charged: subscriptionData.last_charged,
active: subscriptionData.active,
paused: subscriptionData.paused,
trial_duration: subscriptionData.trial_duration,
label: label || undefined,
};
});
}
export async function getSubscriptionMetadata(user: string): Promise<string | null> {
try {
const s = getServer();
const contract = new Contract(CONTRACT_ID);
const account = await s.getAccount(user);
const tx = new TransactionBuilder(account, {
fee: BASE_FEE,
networkPassphrase: NETWORK_PASSPHRASE,
})
.addOperation(contract.call("get_metadata", addressVal(user)))
.setTimeout(30)
.build();
const result = await s.simulateTransaction(tx);
if ("error" in result) return null;
const retval = (result as { result?: { retval?: xdr.ScVal } }).result?.retval;
if (!retval) return null;
return ScValDecoder.decodeOption(retval, ScValDecoder.decodeString);
} catch {
return null;
}
}
/** Mirrors contract `SubscriptionHealth` from `get_subscription_health`. */
export interface SubscriptionHealth {
active: boolean;
charge_due: boolean;
within_grace: boolean;
has_sufficient_allowance: boolean;
is_paused: boolean;
trial_active: boolean;
daily_limit_set: boolean;
}
export const CHARGE_SIM_RESULTS = [
"WouldSucceed",
"NotDue",
"Inactive",
"InsufficientAllowance",
"GracePeriodElapsed",
"ContractPaused",
"SubscriptionPaused",
] as const;
export type ChargeSimResult = (typeof CHARGE_SIM_RESULTS)[number];
export const CHARGE_SIM_LABELS: Record<ChargeSimResult, string> = {
WouldSucceed: "Next charge would succeed",
NotDue: "Next charge is not due yet",
Inactive: "No active subscription to charge",
InsufficientAllowance: "Allowance is too low for the next charge",
GracePeriodElapsed: "Grace period has elapsed — recurring charge would fail",
ContractPaused: "Protocol is paused",
SubscriptionPaused: "Subscription is paused — charge would fail",
};
export function normalizeSubscriptionHealth(
raw: Partial<SubscriptionHealth> | null | undefined
): SubscriptionHealth | null {
if (!raw) return null;
return {
active: !!raw.active,
charge_due: !!raw.charge_due,
within_grace: !!raw.within_grace,
has_sufficient_allowance: !!raw.has_sufficient_allowance,
is_paused: !!raw.is_paused,
trial_active: !!raw.trial_active,
daily_limit_set: !!raw.daily_limit_set,
};
}
export function isSubscriptionHealthy(health: SubscriptionHealth): boolean {
return health.active && health.has_sufficient_allowance && !health.is_paused;
}
export function subscriptionHasWarnings(health: SubscriptionHealth): boolean {
return !isSubscriptionHealthy(health) || health.within_grace || health.charge_due;
}
/** States that would make pay-per-use fail on-chain. */
export function subscriptionHealthBlocksPay(health: SubscriptionHealth | null): boolean {
if (!health) return false;
return !health.active || health.is_paused;
}
export function chargeSimIsRisky(result: ChargeSimResult | null): boolean {
return (
result === "InsufficientAllowance" ||
result === "GracePeriodElapsed" ||
result === "ContractPaused" ||
result === "SubscriptionPaused" ||
result === "Inactive"
);
}
export function chargeSimBlocksPay(result: ChargeSimResult | null): boolean {
return result === "ContractPaused" || result === "SubscriptionPaused" || result === "Inactive";
}
export function payBlockedReason(
health: SubscriptionHealth | null,
sim: ChargeSimResult | null
): string | null {
if (health?.is_paused || sim === "SubscriptionPaused") {
return "Pay-per-use is unavailable while the subscription is paused. Resume first.";
}
if ((health && !health.active) || sim === "Inactive") {
return "Pay-per-use requires an active subscription.";
}
if (sim === "ContractPaused") {
return "Pay-per-use is unavailable while the protocol is paused.";
}
return null;
}
export function payWarningReason(
health: SubscriptionHealth | null,
sim: ChargeSimResult | null
): string | null {
if (payBlockedReason(health, sim)) return null;
if ((health && !health.has_sufficient_allowance) || sim === "InsufficientAllowance") {
return "Token allowance is insufficient. Increase allowance before paying or the charge may fail.";
}
if (health?.within_grace) {
return "Subscription is in its grace period. Recurring charge is overdue.";
}
if (sim === "GracePeriodElapsed") {
return "Grace period has elapsed. Recurring charge would fail until the subscription is repaired.";
}
if (health?.charge_due) {
return "A recurring charge is currently due.";
}
return null;
}
/** Decode a unit `ChargeSimResult` enum (symbol or vec-wrapped symbol). */
export function decodeChargeSimResult(
retval: xdr.ScVal | null | undefined
): ChargeSimResult | null {
if (!retval) return null;
try {
const type = retval.switch().name;
let name: string | null = null;
if (type === "scvSymbol") {
name = retval.sym().toString();
} else if (type === "scvVec") {
const vec = retval.vec() ?? [];
if (vec.length > 0 && vec[0].switch().name === "scvSymbol") {
name = vec[0].sym().toString();
}
}
if (name && (CHARGE_SIM_RESULTS as readonly string[]).includes(name)) {
return name as ChargeSimResult;
}
return null;
} catch {
return null;
}
}
export function getSubscriptionHealth(user: string): Promise<SubscriptionHealth | null> {
return dedupedCall(`getSubscriptionHealth:${user}`, async () => {
try {
const s = getServer();
const contract = new Contract(CONTRACT_ID);
const account = await s.getAccount(user);
const tx = new TransactionBuilder(account, {
fee: BASE_FEE,
networkPassphrase: NETWORK_PASSPHRASE,
})
.addOperation(contract.call("get_subscription_health", addressVal(user)))
.setTimeout(30)
.build();
const result = await s.simulateTransaction(tx);
if ("error" in result) throw new Error((result as { error: string }).error);
const retval = (result as { result?: { retval?: xdr.ScVal } }).result?.retval;
if (!retval || retval.switch().name === "scvVoid") return null;
return normalizeSubscriptionHealth(
ScValDecoder.decodeStruct(retval, {
active: ScValDecoder.decodeBool,
charge_due: ScValDecoder.decodeBool,
within_grace: ScValDecoder.decodeBool,
has_sufficient_allowance: ScValDecoder.decodeBool,
is_paused: ScValDecoder.decodeBool,
trial_active: ScValDecoder.decodeBool,
daily_limit_set: ScValDecoder.decodeBool,
})
);
} catch {
return null;
}
});
}
/** Dry-run of on-chain `simulate_charge` — no storage writes or transfers. */
export function simulateCharge(user: string): Promise<ChargeSimResult | null> {
return dedupedCall(`simulateCharge:${user}`, async () => {
try {
const contract = new Contract(CONTRACT_ID);
const account = await server.getAccount(user);
const tx = new TransactionBuilder(account, {
fee: BASE_FEE,
networkPassphrase: NETWORK_PASSPHRASE,
})
.addOperation(contract.call("simulate_charge", addressVal(user)))
.setTimeout(30)
.build();
const result = await server.simulateTransaction(tx);
if ("error" in result) throw new Error((result as { error: string }).error);
const retval = (result as { result?: { retval?: xdr.ScVal } }).result?.retval;
return decodeChargeSimResult(retval);
} catch {
return null;
}
});
}
function parseEventValueField(value: any, field: string): string {
if (!value) return "";
const base = value._value?.[field] ?? value[field];
if (base == null) return "";
if (typeof base === "string") return base;
if (typeof base === "number" || typeof base === "bigint") return base.toString();
if (typeof base.toString === "function") return base.toString();
return "";
}
function parseEventTime(event: any): number {
if (typeof event.ledgerCloseTime === "number") return event.ledgerCloseTime;
if (typeof event.ledgerCloseTime === "string") return Number(event.ledgerCloseTime) || 0;
if (typeof event.timestamp === "string") return Math.floor(Date.parse(event.timestamp) / 1000);
return 0;
}
export async function getMerchantSubscribers(merchant: string): Promise<MerchantSubscriber[]> {
try {
const response = await server.getEvents({
startLedger: undefined,
filters: [{ type: "contract", contractIds: [CONTRACT_ID] }],
limit: 1000,
});
const latestSubscribeByUser = new Map<
string,
{
merchant: string;
amount: string;
interval: number;
timestamp: number;
}
>();
const latestCancelByUser = new Map<string, number>();
const latestChargeByUserAndMerchant = new Map<string, number>();
for (const event of response.events) {
if (!event.topic || event.topic.length < 2) continue;
const eventType = event.topic[0]?.toString();
const userAddress = event.topic[1]?.toString();
if (!userAddress) continue;
const eventTime = parseEventTime(event);
switch (eventType) {
case "subscribed": {
const subscribedMerchant = parseEventValueField(event.value, "merchant");
const amount = parseEventValueField(event.value, "amount");
const intervalString = parseEventValueField(event.value, "interval");
const interval = Number(intervalString) || 0;
const existing = latestSubscribeByUser.get(userAddress);
if (!existing || eventTime > existing.timestamp) {
latestSubscribeByUser.set(userAddress, {
merchant: subscribedMerchant,
amount,
interval,
timestamp: eventTime,
});
}
break;
}
case "cancelled": {
const existingCancel = latestCancelByUser.get(userAddress) || 0;
if (eventTime > existingCancel) {
latestCancelByUser.set(userAddress, eventTime);
}
break;
}
case "charged": {
const chargedMerchant = parseEventValueField(event.value, "merchant");
const key = `${userAddress}:${chargedMerchant}`;
const existingCharge = latestChargeByUserAndMerchant.get(key) || 0;
if (eventTime > existingCharge) {
latestChargeByUserAndMerchant.set(key, eventTime);
}
break;
}
}
}
const subscribers: MerchantSubscriber[] = [];
for (const [userAddress, subscribe] of latestSubscribeByUser.entries()) {
if (subscribe.merchant !== merchant) continue;
const cancelAt = latestCancelByUser.get(userAddress) ?? 0;
if (cancelAt >= subscribe.timestamp) continue;
const chargeKey = `${userAddress}:${merchant}`;
const lastCharged = Math.max(
subscribe.timestamp,
latestChargeByUserAndMerchant.get(chargeKey) ?? 0
);
const nextChargeAt = lastCharged + subscribe.interval;
subscribers.push({
subscriber: userAddress,
amount: subscribe.amount,
interval: subscribe.interval,
lastCharged,
nextChargeAt,
});
}
return subscribers.sort((a, b) => a.subscriber.localeCompare(b.subscriber));
} catch {
return [];
}
}
export async function getMerchantRevenueHistory(merchant: string, days = 7): Promise<bigint[]> {
try {
const s = getServer();
const contract = new Contract(CONTRACT_ID);
const account = await s.getAccount(merchant);
const tx = new TransactionBuilder(account, {
fee: BASE_FEE,
networkPassphrase: NETWORK_PASSPHRASE,
})
.addOperation(
contract.call(
"get_merchant_revenue_history",
addressVal(merchant),
nativeToScVal(days, { type: "u32" })
)
)
.setTimeout(30)
.build();
const result = await s.simulateTransaction(tx);
if ("error" in result) return [];
const retval = (result as { result?: { retval?: xdr.ScVal } }).result?.retval;
if (!retval) return [];
return ScValDecoder.decodeVec(retval, ScValDecoder.decodeI128);
} catch {
return [];
}
}
export function getMerchantRevenue(merchant: string): Promise<bigint> {
return dedupedCall(`getMerchantRevenue:${merchant}`, async () => {
try {
const s = getServer();
const contract = new Contract(CONTRACT_ID);
const account = await s.getAccount(merchant);
const tx = new TransactionBuilder(account, {
fee: BASE_FEE,
networkPassphrase: NETWORK_PASSPHRASE,
})
.addOperation(contract.call("get_merchant_revenue", addressVal(merchant)))
.setTimeout(30)
.build();
const result = await s.simulateTransaction(tx);
if ("error" in result) return 0n;
const retval = (result as { result?: { retval?: xdr.ScVal } }).result?.retval;
if (!retval) return 0n;
try {
return ScValDecoder.decodeI128(retval);
} catch {
return 0n;
}
} catch {
return 0n;
}
});
}
export async function buildWithdrawMerchantRevenueTx(merchant: string): Promise<string> {
return buildTx(merchant, "withdraw_merchant_revenue", [addressVal(merchant)]);
}
export async function getBalance(
publicKey: string,
fields?: { asset_type?: string }
): Promise<string> {
try {
// Note: Horizon /accounts/{id} endpoint does not support filtering by asset_type,
// so we append the query parameter but still parse client-side.
const query = fields?.asset_type ? `?asset_type=${fields.asset_type}` : "";
const resp = await fetch(`https://horizon-testnet.stellar.org/accounts/${publicKey}${query}`);
if (!resp.ok) throw new Error(`Horizon API error: ${resp.status}`);
const data = await resp.json();
const assetType = fields?.asset_type ?? "native";
const nativeBalance = data.balances?.find(
(b: { asset_type: string; balance: string }) => b.asset_type === assetType
);
return nativeBalance?.balance ?? "0";
} catch {
return "0";
}
}
export function getTokenBalance(owner: string, tokenId: string): Promise<bigint> {
if (!tokenId) return Promise.reject(new Error("Token ID is required."));
return dedupedCall(`getTokenBalance:${owner}:${tokenId}`, async () => {
try {
const tokenContract = new Contract(tokenId);
const account = await server.getAccount(owner);
const tx = new TransactionBuilder(account, {
fee: BASE_FEE,
networkPassphrase: NETWORK_PASSPHRASE,
})
.addOperation(tokenContract.call("balance", addressVal(owner)))
.setTimeout(30)
.build();
const result = await server.simulateTransaction(tx);
if ("error" in result) return 0n;
const retval = (result as { result?: { retval?: xdr.ScVal } }).result?.retval;
if (!retval) return 0n;
try {
return ScValDecoder.decodeI128(retval);
} catch {
return 0n;
}
} catch {
return 0n;
}
});
}
export function getAllowance(owner: string, tokenId = TOKEN_CONTRACT_ID): Promise<bigint> {
if (!tokenId) return Promise.reject(new Error("VITE_TOKEN_CONTRACT_ID is not configured."));
return dedupedCall(`getAllowance:${owner}:${tokenId}`, async () => {
try {
const s = getServer();
const tokenContract = new Contract(tokenId);
const account = await s.getAccount(owner);
const tx = new TransactionBuilder(account, {
fee: BASE_FEE,
networkPassphrase: NETWORK_PASSPHRASE,
})
.addOperation(
tokenContract.call(
"allowance",
addressVal(owner),
nativeToScVal(CONTRACT_ID, { type: "address" })
)
)
.setTimeout(30)
.build();
const result = await s.simulateTransaction(tx);
if ("error" in result) return 0n;
const retval = (result as { result?: { retval?: xdr.ScVal } }).result?.retval;
if (!retval) return 0n;
try {
return ScValDecoder.decodeI128(retval);
} catch {
return 0n;
}
} catch {
return 0n;
}
});
}
// ── Event Fetching ────────────────────────────────────────────────────────────
/**
* Fetch contract events by event name, optionally filtered by address.
* eventName matches the first topic (e.g. "subscribed", "charged", "cancelled", "pay_per_use").
*/
export async function fetchEvents(