forked from SmartDropLabs/smartdrop-frontend
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsoroban.ts
More file actions
2291 lines (1988 loc) · 71.9 KB
/
Copy pathsoroban.ts
File metadata and controls
2291 lines (1988 loc) · 71.9 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
/**
* Comprehensive Soroban Contract Integration Layer
* Handles all smart contract interactions for SmartDrop
*/
import {
Contract,
TransactionBuilder,
BASE_FEE,
xdr,
Address,
nativeToScVal,
scValToNative,
rpc,
Networks,
Transaction,
FeeBumpTransaction,
Account,
} from '@stellar/stellar-sdk';
import {
factoryContractId,
horizonUrl,
networkPassphrase,
sorobanRpcUrl,
simulationAccount,
stellarNetwork,
} from '@/config';
import { ConfigError, FreighterError, SecurityError } from './error-handler';
import { fetchAccountBalances } from './stellar';
import {
bigintToDisplayAmount,
parsePoolsFromNative,
parseUserPositionFromNative,
} from './soroban-parsers';
import type {
AssetInfo,
PoolInfo,
UserPosition,
} from './soroban-parsers';
export type { AssetInfo, PoolInfo, UserPosition } from './soroban-parsers';
// Soroban RPC Configuration
const RPC_URL = process.env.NEXT_PUBLIC_SOROBAN_RPC_URL || 'https://soroban-testnet.stellar.org:443';
const NETWORK_PASSPHRASE = process.env.NEXT_PUBLIC_NETWORK_PASSPHRASE || Networks.TESTNET;
// Contract Addresses (will be set via environment variables in production)
const FACTORY_CONTRACT_ADDRESS = process.env.NEXT_PUBLIC_FACTORY_CONTRACT_ADDRESS || '';
const LEADERBOARD_API_URL = process.env.NEXT_PUBLIC_LEADERBOARD_API_URL || '';
const LEADERBOARD_LOOKBACK_LEDGERS = 120960; // ~7 days at ~5s per ledger
export type LeaderboardSortKey = 'credits' | 'stake';
export interface LeaderboardRow {
address: string;
totalCredits: number;
totalStake: number;
/** null when the data source (e.g. the event-scan fallback) cannot derive
* boost utilization — distinct from a genuine 0% (issue #142). */
boostUtilization: number | null;
}
export interface LeaderboardPage {
entries: LeaderboardRow[];
total: number;
}
// Initialize Soroban RPC Server
export const rpcServer = new rpc.Server(sorobanRpcUrl);
export interface BoostConfig {
multiplier: number;
allocationPercentage: number;
isActive: boolean;
}
export interface TransactionResult {
success: boolean;
transactionHash?: string;
hash?: string;
status?: string;
error?: string;
errorCode?: string;
resultXdr?: string;
gasUsed?: string;
}
export interface ContractCallOptions {
caller?: string;
fee?: number;
memo?: string;
}
// ── XDR-level wrappers (pure parsing logic lives in ./soroban-parsers) ───────
export function parsePoolsFromXdrResult(xdrResult: xdr.ScVal): PoolInfo[] {
let native: unknown;
try {
native = scValToNative(xdrResult);
} catch (err) {
console.warn('[SmartDrop] parsePoolsFromXdr: failed to deserialise ScVal:', err);
return [];
}
if (!Array.isArray(native)) {
console.warn('[SmartDrop] parsePoolsFromXdr: expected Vec (array), got', typeof native);
return [];
}
return parsePoolsFromNative(native);
}
export function parseUserPositionFromXdrResult(
xdrResult: xdr.ScVal,
poolId: string,
userAddress: string,
): UserPosition | null {
let native: unknown;
try {
native = scValToNative(xdrResult);
} catch (err) {
console.warn('[SmartDrop] parseUserPositionFromXdr: failed to deserialise ScVal:', err);
return null;
}
if (native == null) return null;
if (typeof native !== 'object' || Array.isArray(native)) {
console.warn('[SmartDrop] parseUserPositionFromXdr: expected Map (object), got', typeof native);
return null;
}
return parseUserPositionFromNative(native as Record<string, unknown>, poolId, userAddress);
}
export function parseCreditsFromXdrResult(xdrResult: xdr.ScVal): string {
try {
const native = scValToNative(xdrResult);
return bigintToDisplayAmount(native);
} catch (err) {
console.warn('[SmartDrop] parseCreditsFromXdr: failed to parse:', err);
return '0';
}
}
type FreighterSignTransactionResult =
| string
| {
signedTxXdr?: string;
signerAddress?: string;
error?: unknown;
};
export interface FreighterWalletApi {
signTransaction: (
transactionXdr: string,
options: { networkPassphrase: string; address?: string },
) => Promise<FreighterSignTransactionResult>;
getNetworkDetails?: () => Promise<{
network: string;
networkPassphrase: string;
}>;
}
type LockAssetsStep = 'simulating' | 'signing' | 'submitting';
type UnlockAssetsStep = 'simulating' | 'signing' | 'submitting' | 'confirming';
export interface LockAssetsCallbacks {
onHash?: (hash: string) => void;
onStep?: (step: LockAssetsStep) => void;
}
export interface UnlockAssetsCallbacks {
onHash?: (hash: string) => void;
onStep?: (step: UnlockAssetsStep) => void;
}
export interface BuildLockAssetsTransactionArgs {
poolContractId: string;
publicKey: string;
amount: string;
}
export type LockAssetsRpc = Pick<
rpc.Server,
'getAccount' | 'simulateTransaction'
>;
export function amountToStroops(amount: string, decimals = 7): bigint {
const normalized = amount.trim();
if (!Number.isInteger(decimals) || decimals < 0) {
throw new Error('Decimal precision must be a non-negative integer.');
}
if (!/^\d+(?:\.\d+)?$/.test(normalized)) {
throw new Error('Enter a valid positive decimal amount.');
}
const [whole, fraction = ''] = normalized.split('.');
if (fraction.length > decimals) {
throw new Error(`Amount supports at most ${decimals} decimal places.`);
}
const scale = 10n ** BigInt(decimals);
const stroops =
BigInt(whole) * scale +
BigInt((fraction || '0').padEnd(decimals, '0'));
if (stroops <= 0n) {
throw new Error('Amount must be greater than 0.');
}
return stroops;
}
export async function getStellarBalance(publicKey: string): Promise<number> {
const response = await fetch(
`${horizonUrl.replace(/\/$/, '')}/accounts/${publicKey}`,
);
if (!response.ok) {
throw new Error(
`Unable to fetch Stellar balance from Horizon (${response.status}).`,
);
}
const account = (await response.json()) as {
balances?: Array<{
asset_type?: string;
balance?: string;
}>;
};
const nativeBalance = account.balances?.find(
(balance) => balance.asset_type === 'native',
);
if (!nativeBalance?.balance) {
throw new Error('Horizon account response did not include a native XLM balance.');
}
return Number(nativeBalance.balance);
}
/**
* Wraps an inner transaction in a fee-bump transaction sponsored by a sponsor.
*/
export function buildFeeBumpTransaction(
innerTx: Transaction | string,
sponsorPublicKey: string,
networkPassphrase: string,
): FeeBumpTransaction {
const txObj = typeof innerTx === 'string'
? TransactionBuilder.fromXDR(innerTx, networkPassphrase) as Transaction
: innerTx;
const innerOps = txObj.operations.length || 1;
const innerFee = typeof txObj.fee === 'string' ? parseInt(txObj.fee, 10) : Number(txObj.fee);
const baseFee = Math.max(100, Math.ceil(innerFee / innerOps));
return TransactionBuilder.buildFeeBumpTransaction(
sponsorPublicKey,
String(baseFee),
txObj,
networkPassphrase,
);
}
export async function buildLockAssetsTransaction(
args: BuildLockAssetsTransactionArgs,
rpcOverride?: LockAssetsRpc,
) {
const server = rpcOverride ?? rpcServer;
const account = await server.getAccount(args.publicKey);
const contract = new Contract(args.poolContractId);
const operation = contract.call(
'lock_assets',
Address.fromString(args.publicKey).toScVal(),
nativeToScVal(amountToStroops(args.amount), { type: 'i128' }),
);
return new TransactionBuilder(account, {
fee: BASE_FEE,
networkPassphrase,
})
.addOperation(operation)
.setTimeout(300)
.build();
}
export async function simulateLockAssets(
args: BuildLockAssetsTransactionArgs,
rpcOverride?: LockAssetsRpc,
) {
const server = rpcOverride ?? rpcServer;
const transaction = await buildLockAssetsTransaction(args, server);
const simulation = await server.simulateTransaction(transaction);
if ('error' in simulation) {
throw new Error(`Simulation failed: ${simulation.error}`);
}
return {
transaction,
simulation,
feePreview: String(simulation.minResourceFee ?? '0'),
};
}
/**
* Read-only unlock_assets simulation for a fee preview (issue #240) — no
* signing, no submission. Mirrors buildLockAssetsTransaction/simulateLockAssets.
*/
export async function buildUnlockAssetsTransaction(
args: BuildLockAssetsTransactionArgs,
rpcOverride?: LockAssetsRpc,
) {
const server = rpcOverride ?? rpcServer;
const account = await server.getAccount(args.publicKey);
const contract = new Contract(args.poolContractId);
const operation = contract.call(
'unlock_assets',
Address.fromString(args.publicKey).toScVal(),
nativeToScVal(amountToStroops(args.amount), { type: 'i128' }),
);
return new TransactionBuilder(account, {
fee: BASE_FEE,
networkPassphrase,
})
.addOperation(operation)
.setTimeout(300)
.build();
}
export async function simulateUnlockAssets(
args: BuildLockAssetsTransactionArgs,
rpcOverride?: LockAssetsRpc,
) {
const server = rpcOverride ?? rpcServer;
const transaction = await buildUnlockAssetsTransaction(args, server);
const simulation = await server.simulateTransaction(transaction);
if ('error' in simulation) {
throw new Error(`Simulation failed: ${simulation.error}`);
}
return {
transaction,
simulation,
feePreview: String(simulation.minResourceFee ?? '0'),
};
}
/**
* Unwraps Freighter's signTransaction response, verifying that the account
* which actually signed (`result.signerAddress`) is the account SmartDrop
* believes is connected (`expectedSigner`). Passing `address` in the
* request (see the three call sites below) lets Freighter itself refuse a
* mismatched-account attempt before ever producing a signature, but that's
* a request the extension can choose to honor or not — this is the
* client-side backstop that fails fast with a clear error instead of
* letting a signer mismatch surface only as an opaque on-chain
* authorization failure after a real transaction submission (#139).
*
* Older Freighter responses (or the legacy bare-string return shape) may
* not include `signerAddress` at all — nothing to check against in that
* case, so this only rejects when the field is present and disagrees.
*/
function getSignedTransactionXdr(
result: FreighterSignTransactionResult,
expectedSigner: string,
): string {
if (typeof result === 'string') {
return result;
}
if (result.error) {
throw new Error(
typeof result.error === 'string'
? result.error
: 'Freighter failed to sign the transaction',
);
}
if (result.signerAddress && result.signerAddress !== expectedSigner) {
throw new SecurityError(
`Transaction signing was blocked because it was signed by ${result.signerAddress}, not the connected account ${expectedSigner}. Please sign with the correct Freighter account.`,
);
}
if (result.signedTxXdr) {
return result.signedTxXdr;
}
throw new Error('Freighter did not return a signed transaction XDR');
}
type PollTransactionResult = {
status: 'SUCCESS' | 'FAILED' | 'TIMEOUT';
resultXdr?: string;
errorCode?: string;
};
// Codes 2-9 are sourced directly from the deployed farming-pool contract's
// `PoolError` enum (SmartDropLabs/smartdrop-contracts,
// soroban/contracts/farming-pool/src/types.rs) — the authoritative,
// currently-deployed error set, rather than a guess (#146). Code '1'
// predates this table and is left as-is: the contract's own code 1 is
// `AlreadyInitialized`, which doesn't match "Assets are still locked" — that
// specific failure (`unlock_assets` before `unlock_ledger`) is actually a
// plain Rust `assert!` in the current contract, not a typed `PoolError`, so
// it wouldn't surface via this numeric-code path at all. Left unchanged
// rather than silently reinterpreted, since there's no way to confirm here
// whether it reflects an intentional mapping against an older contract
// build or a stale assumption; worth a follow-up with the contracts team.
const CONTRACT_ERROR_MESSAGES: Record<string, string> = {
'1': 'Assets are still locked',
'2': 'The pool has not been initialized yet',
'3': 'Invalid credit rate configuration',
'4': 'Invalid boost multiplier configuration',
'5': 'This wallet is not on the whitelist for this pool',
'6': 'Amount is below the minimum stake for this pool',
'7': 'This action requires the pool to be paused first',
'8': 'No active stake or locked position was found for this wallet',
'9': 'This pool is currently paused',
};
function sleep(ms: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, ms));
}
function normalizeResultXdr(resultXdr: unknown): string | undefined {
if (!resultXdr) return undefined;
if (typeof resultXdr === 'string') return resultXdr;
if (
typeof resultXdr === 'object' &&
resultXdr !== null &&
'toXDR' in resultXdr &&
typeof (resultXdr as { toXDR: (format: 'base64') => unknown }).toXDR === 'function'
) {
const encoded = (resultXdr as { toXDR: (format: 'base64') => unknown }).toXDR('base64');
return typeof encoded === 'string' ? encoded : undefined;
}
return undefined;
}
function normalizeTransactionStatus(status: unknown): string {
return enumName(status).toUpperCase();
}
function normalizeContractErrorCode(value: unknown): string | undefined {
if (typeof value === 'bigint') return value.toString();
if (typeof value === 'number' && Number.isFinite(value)) return String(value);
if (typeof value !== 'string') return undefined;
const trimmed = value.trim();
if (/^\d+$/.test(trimmed)) return trimmed;
const hexMatch = trimmed.match(/0x([0-9a-f]+)/i);
if (hexMatch) return String(Number.parseInt(hexMatch[1], 16));
const decimalMatch = trimmed.match(/(?:contract[_\s-]?code|error[_\s-]?code|code)[^\d]*(\d+)/i);
return decimalMatch?.[1];
}
function findContractErrorCode(
value: unknown,
depth = 0,
seen = new WeakSet<object>(),
): string | undefined {
if (depth > 8 || value == null) return undefined;
if (typeof value === 'object') {
if (seen.has(value)) return undefined;
seen.add(value);
const xdrLike = value as {
switch?: () => unknown;
value?: () => unknown;
};
if (typeof xdrLike.switch === 'function') {
const armName = enumName(xdrLike.switch());
if (armName === 'sceContract' && typeof xdrLike.value === 'function') {
return normalizeContractErrorCode(xdrLike.value());
}
}
for (const method of [
'contractCode',
'errorCode',
'code',
'value',
'result',
'results',
'tr',
'invokeHostFunction',
]) {
const accessor = (value as Record<string, unknown>)[method];
if (typeof accessor !== 'function') continue;
try {
const raw = accessor.call(value);
const directCode = /^(contractCode|errorCode|code)$/.test(method)
? normalizeContractErrorCode(raw)
: undefined;
if (directCode) return directCode;
const code = findContractErrorCode(raw, depth + 1, seen);
if (code) return code;
} catch {
// Ignore accessors that are not valid for this XDR union arm.
}
}
if (Array.isArray(value)) {
for (const item of value) {
const code = findContractErrorCode(item, depth + 1, seen);
if (code) return code;
}
return undefined;
}
for (const [key, item] of Object.entries(value as Record<string, unknown>)) {
if (!/(contract|error|code|result)/i.test(key)) continue;
const directCode = normalizeContractErrorCode(item);
if (directCode) return directCode;
const nestedCode = findContractErrorCode(item, depth + 1, seen);
if (nestedCode) return nestedCode;
}
}
return undefined;
}
function extractContractErrorCodeFromXdr(resultXdr?: string): string | undefined {
if (!resultXdr) return undefined;
for (const decoder of [xdr.TransactionResult, xdr.ScError]) {
try {
const decoded = decoder.fromXDR(resultXdr, 'base64');
const code = findContractErrorCode(decoded);
if (code) return code;
} catch {
// The result might not be this XDR type.
}
}
return normalizeContractErrorCode(resultXdr);
}
function extractContractErrorCode(tx: unknown, resultXdr?: string): string | undefined {
const directCode = findContractErrorCode(tx);
if (directCode) return directCode;
if (tx && typeof tx === 'object') {
const rawResultXdr = normalizeResultXdr((tx as { resultXdr?: unknown }).resultXdr);
const code = extractContractErrorCodeFromXdr(rawResultXdr);
if (code) return code;
}
return extractContractErrorCodeFromXdr(resultXdr);
}
export function getContractErrorMessage(errorCode?: string): string | undefined {
const normalized = normalizeContractErrorCode(errorCode);
if (!normalized) return undefined;
const message = CONTRACT_ERROR_MESSAGES[normalized];
if (!message) {
console.warn('[SmartDrop] Unmapped contract error code:', normalized);
}
return message;
}
/**
* Parse raw Soroban simulation error strings into user-friendly messages.
* Catches common failure patterns (insufficient balance, contract errors,
* auth failures) and returns a clear message BEFORE the wallet signing
* prompt so users are not confused by opaque XDR error strings.
*/
export function parseSimulationError(rawError: string): string {
const lower = rawError.toLowerCase();
// Insufficient balance / funding
if (lower.includes('insufficient') || lower.includes('underfunded') || lower.includes('balance')) {
return 'Insufficient balance to cover this transaction. Please ensure your wallet has enough funds.';
}
// Contract-level numeric error code: "HostError(Contract, #N)"
const contractCodeMatch = rawError.match(/HostError\(Contract,\s*#(\d+)\)/i);
if (contractCodeMatch) {
const code = contractCodeMatch[1];
const mapped = CONTRACT_ERROR_MESSAGES[code];
return mapped ?? `Contract error #${code}. Please check your position and try again.`;
}
// Authorization / auth failures
if (lower.includes('auth') || lower.includes('unauthorized') || lower.includes('not authorized')) {
return 'Authorization failed. Make sure your wallet is connected to the correct account.';
}
// Expired / time-related
if (lower.includes('expired') || lower.includes('too old') || lower.includes('deadline')) {
return 'Transaction expired. Please try again.';
}
// Budget exceeded
if (lower.includes('budget') || lower.includes('exceeded') || lower.includes('resource')) {
return 'Transaction exceeds the network resource budget. Try a smaller amount.';
}
// Fallback with the raw error for debugging
return `Transaction simulation failed: ${rawError}`;
}
/** `getContractErrorMessage(errorCode) ?? this` — always includes the raw
* code (when one was extracted) so a user or support agent has something
* concrete to reference, even for a still-unmapped code (#146). */
function genericOnChainFailureMessage(hash: string, errorCode?: string): string {
return errorCode
? `Transaction ${hash} failed on-chain (code ${errorCode})`
: `Transaction ${hash} failed on-chain`;
}
// ── Transaction signing safety ───────────────────────────────────────────────
export interface ExpectedSimulationAuth {
contractId: string;
functionName: string;
}
type SimulationAuthResult = {
result?: {
auth?: xdr.SorobanAuthorizationEntry[] | null;
} | null;
};
function normalizeExpectedAuthKey(auth: ExpectedSimulationAuth): string {
return `${auth.contractId.trim().toUpperCase()}:${auth.functionName.trim()}`;
}
function enumName(value: unknown): string {
if (typeof value === 'string') return value;
if (value && typeof value === 'object') {
const enumLike = value as { name?: unknown; toString?: () => string };
if (typeof enumLike.name === 'string') return enumLike.name;
if (typeof enumLike.name === 'function') {
const name = (enumLike.name as () => unknown)();
if (typeof name === 'string') return name;
}
if (typeof enumLike.toString === 'function') return enumLike.toString();
}
return String(value);
}
function scSymbolToString(value: unknown): string {
if (typeof value === 'string') return value;
if (value instanceof Uint8Array) return new TextDecoder().decode(value);
if (value && typeof value === 'object' && 'toString' in value) {
return String((value as { toString: () => string }).toString());
}
return String(value);
}
function decodeAuthEntryContractFunction(
entry: xdr.SorobanAuthorizationEntry,
): ExpectedSimulationAuth {
try {
const authEntry = entry as unknown as {
credentials?: () => unknown;
rootInvocation?: () => unknown;
};
// Decode/access credentials as part of validating the full authorization entry shape.
// The target contract/function is carried by rootInvocation.contractFn.
if (typeof authEntry.credentials !== 'function') {
throw new Error('Authorization entry is missing credentials');
}
authEntry.credentials();
if (typeof authEntry.rootInvocation !== 'function') {
throw new Error('Authorization entry is missing root invocation');
}
const invocation = authEntry.rootInvocation() as {
function?: () => unknown;
subInvocations?: () => unknown;
};
if (!invocation || typeof invocation.function !== 'function') {
throw new Error('Authorization entry root invocation is malformed');
}
const authorizedFunction = invocation.function() as {
switch?: () => unknown;
contractFn?: () => unknown;
};
const functionType =
typeof authorizedFunction.switch === 'function'
? enumName(authorizedFunction.switch())
: '';
if (!functionType.toLowerCase().includes('contract')) {
throw new Error(`Unexpected authorization function type: ${functionType}`);
}
if (typeof authorizedFunction.contractFn !== 'function') {
throw new Error('Authorization entry does not contain a contract function');
}
const contractFn = authorizedFunction.contractFn() as {
contractAddress?: () => xdr.ScAddress;
functionName?: () => unknown;
};
if (
!contractFn ||
typeof contractFn.contractAddress !== 'function' ||
typeof contractFn.functionName !== 'function'
) {
throw new Error('Authorization contract function is malformed');
}
const decoded = {
contractId: Address.fromScAddress(contractFn.contractAddress()).toString(),
functionName: scSymbolToString(contractFn.functionName()),
};
assertNoUnexpectedSubInvocations(invocation);
return decoded;
} catch (error) {
if (error instanceof SecurityError) {
throw error;
}
throw new SecurityError(
'Transaction signing was blocked because SmartDrop could not verify the simulated authorization request.',
error instanceof Error ? error : undefined,
);
}
}
function assertNoUnexpectedSubInvocations(invocation: {
subInvocations?: () => unknown;
}): void {
if (typeof invocation.subInvocations !== 'function') {
throw new SecurityError(
'Transaction signing was blocked because SmartDrop could not verify nested authorization requests.',
);
}
const subInvocations = invocation.subInvocations();
if (!Array.isArray(subInvocations)) {
throw new SecurityError(
'Transaction signing was blocked because SmartDrop could not verify nested authorization requests.',
);
}
if (subInvocations.length > 0) {
throw new SecurityError(
'Transaction signing was blocked because the simulation returned nested authorization requests that SmartDrop did not expect.',
);
}
}
export function validateSimulationAuth(
simResult: SimulationAuthResult,
expected: ExpectedSimulationAuth[],
): void {
const authEntries = simResult.result?.auth;
if (!Array.isArray(authEntries)) {
throw new SecurityError(
'Transaction signing was blocked because the simulation did not return authorization entries.',
);
}
if (authEntries.length !== expected.length) {
throw new SecurityError(
`Transaction signing was blocked because the simulation returned ${authEntries.length} authorization entr${authEntries.length === 1 ? 'y' : 'ies'}, but SmartDrop expected ${expected.length}.`,
);
}
const remainingExpected = expected.map((entry) => normalizeExpectedAuthKey(entry));
for (const entry of authEntries) {
const actual = decodeAuthEntryContractFunction(entry);
const actualKey = normalizeExpectedAuthKey(actual);
const matchIndex = remainingExpected.indexOf(actualKey);
if (matchIndex === -1) {
throw new SecurityError(
`Transaction signing was blocked because the simulated authorization targets ${actual.contractId}.${actual.functionName}, which is not expected for this SmartDrop action.`,
);
}
remainingExpected.splice(matchIndex, 1);
}
if (remainingExpected.length > 0) {
throw new SecurityError(
'Transaction signing was blocked because the simulation is missing an expected SmartDrop authorization entry.',
);
}
}
// ── SorobanService class ──────────────────────────────────────────────────────
/**
* SorobanService class - Main interface for contract interactions
*/
export class SorobanService {
private rpcServer: rpc.Server;
private factoryContract?: Contract;
private poolContracts: Map<string, Contract> = new Map();
private simulationAccountAddress: string;
// Short-lived cache for getAccount results keyed by address.
// Collapses N concurrent calls for the same simulation account
// (e.g. useAllUserPositions fanning out over N pools) into one RPC fetch.
private accountCache: Map<string, { account: Account; expiresAt: number }> = new Map();
// Tracks in-flight getAccount requests so truly concurrent calls share
// the same promise rather than each firing a separate RPC round trip.
private inflightAccount: Map<string, Promise<Account>> = new Map();
private static ACCOUNT_CACHE_TTL_MS = 3_000;
constructor() {
this.rpcServer = rpcServer;
this.simulationAccountAddress = simulationAccount;
if (factoryContractId) {
this.factoryContract = new Contract(factoryContractId);
}
}
/**
* Returns a cached Account object for read-only simulation calls.
* Uses cachedGetAccount for TTL + in-flight deduplication. Throws
* ConfigError if NEXT_PUBLIC_SIMULATION_ACCOUNT is not set.
*/
private async getSimulationAccount(): Promise<Account> {
if (!this.simulationAccountAddress) {
throw new ConfigError(
'NEXT_PUBLIC_SIMULATION_ACCOUNT is not configured. Set it to a funded Stellar account on the active network.',
);
}
try {
return await this.cachedGetAccount(this.simulationAccountAddress);
} catch (err) {
throw new ConfigError(
`Simulation account ${this.simulationAccountAddress} could not be resolved: ${err instanceof Error ? err.message : 'unknown error'}. Fund this account or set NEXT_PUBLIC_SIMULATION_ACCOUNT to a funded account on ${stellarNetwork}.`,
);
}
}
/**
* Cached getAccount — returns a fresh Account object but deduplicates
* concurrent and near-concurrent calls for the same address within a
* short TTL window. Used by every method that needs a simulation
* account (getFactoryPools, getUserPosition, calculateUserCredits, …).
*/
async cachedGetAccount(address: string): Promise<Account> {
const now = Date.now();
const cached = this.accountCache.get(address);
if (cached && cached.expiresAt > now) {
return cached.account;
}
// If a request is already in flight for this address, share it
const inflight = this.inflightAccount.get(address);
if (inflight) return inflight;
const promise = this.rpcServer.getAccount(address).then((account) => {
this.accountCache.set(address, {
account,
expiresAt: Date.now() + SorobanService.ACCOUNT_CACHE_TTL_MS,
});
this.inflightAccount.delete(address);
return account;
}).catch((err) => {
this.inflightAccount.delete(address);
throw err;
});
this.inflightAccount.set(address, promise);
return promise;
}
/**
* Verify the wallet's active network matches the expected network passphrase.
* Defense-in-depth: runs before signTransaction to catch network mismatches
* that UI-level gating might miss (e.g. race conditions).
*/
private async verifyWalletNetwork(walletApi: FreighterWalletApi): Promise<void> {
if (!walletApi.getNetworkDetails) return;
try {
const details = await walletApi.getNetworkDetails();
if (details.networkPassphrase !== networkPassphrase) {
throw new FreighterError(
'FREIGHTER_NETWORK_MISMATCH',
`Wallet network mismatch: expected "${networkPassphrase}", got "${details.networkPassphrase}". Switch your Freighter wallet to the correct network.`,
);
}
} catch (err) {
if (err instanceof FreighterError) throw err;
// If getNetworkDetails fails for other reasons, log and continue —
// the signing step will surface its own error if the network is wrong.
console.warn('[SmartDrop] Could not verify wallet network:', err);
}
}
/**
* Initialize the service with contract addresses
*/
async initialize(factoryAddress?: string) {
if (factoryAddress) {
this.factoryContract = new Contract(factoryAddress);
}
// Load existing pools
await this.loadPoolContracts();
}
/**
* Load all pool contracts from the factory
*/
private async loadPoolContracts() {
try {
const pools = await this.getFactoryPools();
pools.forEach(pool => {
const contract = new Contract(pool.contractAddress);
this.poolContracts.set(pool.id, contract);
this.poolContracts.set(pool.contractAddress, contract);
});
} catch (error) {
console.warn('Failed to load pool contracts:', error);
}
}
/**
* Get all pools from the factory contract
*/
async getFactoryPools(): Promise<PoolInfo[]> {
if (!this.factoryContract) {
console.warn('Factory contract not initialized; returning empty pool list');
return [];
}
try {
const call = this.factoryContract.call("get_pools");
const account = await this.getSimulationAccount();
const transaction = new TransactionBuilder(account, {
fee: BASE_FEE,
networkPassphrase,
})
.addOperation(call)
.setTimeout(30)
.build();
const simulation = await this.rpcServer.simulateTransaction(transaction);
if ("error" in simulation) {
throw new Error(`Simulation failed: ${simulation.error}`);
}
const result = simulation.result?.retval;
if (!result) {
return [];
}
return this.parsePoolsFromXdr(result);
} catch (error) {
console.error('Error fetching factory pools:', error);
return [];
}
}
/**
* Get user position for a specific pool
*/
async getUserPosition(
poolId: string,
userAddress: string
): Promise<UserPosition | null> {
const poolContract = this.poolContracts.get(poolId);
if (!poolContract) {
console.warn(`Pool contract not found for ID: ${poolId}`);
return null;
}
try {
const call = poolContract.call(
"get_user_position",
Address.fromString(userAddress).toScVal(),
);
const account = await this.getSimulationAccount();
const transaction = new TransactionBuilder(account, {