Repository navigation
Expand file tree
/
Copy pathstellar.js
More file actions
867 lines (748 loc) · 24.7 KB
/
Copy pathstellar.js
File metadata and controls
867 lines (748 loc) · 24.7 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
/**
* Shared Stellar / Soroban constants and utility helpers.
*
* Centralizes configuration and common routines so that Landing, ClaimRewards,
* and future components can reuse them without duplication.
*/
import {
Address,
Contract,
TransactionBuilder,
BASE_FEE,
scValToNative,
nativeToScVal,
} from '@stellar/stellar-sdk';
import {
createSorobanServer,
getCampaignContractId,
getHorizonUrl,
getNetworkPassphrase,
getCampaignContract,
getRewardsContract,
getStellarNetwork,
getRewardsContractId,
getSorobanRpcUrl,
} from './config';
import { Client as RewardsClient } from './contracts/rewards';
import { Client as CampaignClient } from './contracts/campaign';
import { ERROR_MESSAGES, getErrorMessage } from './lib/errorMapping';
import { walletManager } from './lib/wallet/index.js';
export {
getCampaignContractId,
getNetworkPassphrase,
getStellarNetwork,
getRewardsContractId,
} from './config';
/* ---------- Wallet helpers ---------- */
export async function connectWallet(providerName = 'Freighter') {
return walletManager.connect(providerName);
}
export async function disconnectWallet() {
return walletManager.disconnect();
}
export async function getWalletAddress() {
return walletManager.getAddress();
}
export async function isWalletConnected() {
return walletManager.isConnected();
}
export async function getAvailableWallets() {
return walletManager.getAvailableProviders();
}
export function getActiveWallet() {
return walletManager.getActiveProviderName();
}
/* ---------- Legacy Freighter helpers (deprecated) ---------- */
export function getFreighterApi() {
const freighterApi = window.freighterApi;
if (!freighterApi) {
throw new Error(
'Freighter API is unavailable. Install or unlock the Freighter browser extension.',
);
}
return freighterApi;
}
/* ---------- contract call results ---------- */
/**
* `AssembledTransaction.simulate()` and `.signAndSend()` resolve to a transaction object whose
* decoded return value is on `.result` (see the generated bindings in ./contracts). Callers need the
* value, so unwrap it; plain values pass through unchanged.
*/
export function unwrapContractResult(value) {
if (value !== null && typeof value === 'object' && 'result' in value) {
return value.result;
}
return value;
}
/* ---------- formatting ---------- */
export function formatPoints(points) {
if (typeof points === 'bigint') return points.toString();
if (typeof points === 'number') return String(points);
return '0';
}
/**
* Format a native XLM balance string for compact UI display.
*/
export function formatWalletBalance(balance) {
const numericBalance = Number(balance);
if (!Number.isFinite(numericBalance)) return '0 XLM';
return `${numericBalance.toFixed(2)} XLM`;
}
/**
* Turn an unknown error value into a human-readable message.
*/
export function normalizeError(error) {
if (!error) return 'Unable to load points right now.';
const extractErrorCode = (value) => {
const text = typeof value === 'string' ? value : value?.message || value?.toString?.() || '';
const patterns = [/Error\(Contract,\s*#(\d+)\)/i, /contract.*?#(\d+)/i, /code[:\s]+(\d+)/i];
for (const pattern of patterns) {
const match = text.match(pattern);
if (match) return Number(match[1]);
}
return null;
};
const message =
typeof error === 'string'
? error
: error.message || error.toString?.() || 'Unable to load points right now.';
const errorCode = extractErrorCode(error);
if (typeof errorCode === 'number' && Number.isFinite(errorCode)) {
if (ERROR_MESSAGES[errorCode]) return getErrorMessage(errorCode);
}
if (/not found|missing|404/i.test(message)) {
return 'Rewards contract is not deployed on the configured Soroban network yet.';
}
if (/unsupported address type/i.test(message)) {
return 'Connected wallet address is invalid for Soroban calls.';
}
return message;
}
/* ---------- contract read helpers ---------- */
/**
* Fetch the connected account's native XLM balance from Horizon.
*/
export async function fetchWalletBalance(walletAddress) {
const response = await fetch(`${getHorizonUrl()}/accounts/${encodeURIComponent(walletAddress)}`);
if (!response.ok) {
throw new Error(`Horizon returned ${response.status} while loading the wallet balance.`);
}
const account = await response.json();
const nativeBalance = account.balances?.find((balance) => balance.asset_type === 'native');
return nativeBalance?.balance || '0';
}
/**
* Simulate a read-only `balance(user)` call and return the raw result.
*/
export async function fetchRewardsBalance(walletAddress) {
const contractId = getRewardsContractId();
if (!contractId) {
throw new Error('Set VITE_REWARDS_CONTRACT_ID to load on-chain points.');
}
const client = new RewardsClient({
rpcUrl: getSorobanRpcUrl(),
networkPassphrase: getNetworkPassphrase(),
contractId,
});
const tx = await client.balance({ user: walletAddress });
return unwrapContractResult(await tx.simulate());
}
/* ---------- contract write helpers ---------- */
export async function submitClaimTransaction(walletAddress, amount) {
const contractId = getRewardsContractId();
if (!contractId) {
throw new Error('Set VITE_REWARDS_CONTRACT_ID before claiming rewards.');
}
const client = new RewardsClient({
rpcUrl: getSorobanRpcUrl(),
networkPassphrase: getNetworkPassphrase(),
contractId,
publicKey: walletAddress,
signTransaction: async (txXdr) => {
const signedTxXdr = await walletManager.signTransaction(txXdr, {
networkPassphrase: getNetworkPassphrase(),
address: walletAddress,
});
return { signedTxXdr };
},
});
const tx = await client.claim({
user: walletAddress,
amount: BigInt(amount),
});
const newBalanceVal = unwrapContractResult(await tx.signAndSend());
const hash = tx.signed.hash().toString('hex');
const newBalance = formatPoints(newBalanceVal);
return { hash, newBalance };
}
/**
* Build, sign, submit, and poll a `redeem(user, points_amount)` call
* on the rewards contract. Returns the amount of asset tokens received.
*
* @param {string} walletAddress - The user's Stellar public key
* @param {number} pointsAmount - Points to redeem
* @returns {Promise<{ hash: string, assetAmount: string }>}
*/
export async function submitRedeemTransaction(walletAddress, pointsAmount) {
const contractId = getRewardsContractId();
if (!contractId) {
throw new Error('Set VITE_REWARDS_CONTRACT_ID before redeeming.');
}
const client = new RewardsClient({
rpcUrl: getSorobanRpcUrl(),
networkPassphrase: getNetworkPassphrase(),
contractId,
publicKey: walletAddress,
signTransaction: async (txXdr) => {
const signedTxXdr = await walletManager.signTransaction(txXdr, {
networkPassphrase: getNetworkPassphrase(),
address: walletAddress,
});
return { signedTxXdr };
},
});
const tx = await client.redeem({
user: walletAddress,
points_amount: BigInt(pointsAmount),
});
const assetAmountVal = unwrapContractResult(await tx.signAndSend());
const hash = tx.signed.hash().toString('hex');
const assetAmount = formatPoints(assetAmountVal);
return { hash, assetAmount };
}
/**
* Fetch the current payout reserve balance from the rewards contract.
* @returns {Promise<string>}
*/
export async function fetchPayoutReserveBalance() {
const contractId = getRewardsContractId();
if (!contractId) return '0';
const client = new RewardsClient({
rpcUrl: getSorobanRpcUrl(),
networkPassphrase: getNetworkPassphrase(),
contractId,
});
const tx = await client.payout_reserve_balance();
const result = unwrapContractResult(await tx.simulate());
return formatPoints(result);
}
/* ---------- campaign contract helpers ---------- */
export async function fetchCampaignOnChainState(contractId) {
const resolvedId = contractId || getCampaignContractId();
if (!resolvedId) {
return null;
}
const client = new CampaignClient({
rpcUrl: getSorobanRpcUrl(),
networkPassphrase: getNetworkPassphrase(),
contractId: resolvedId,
});
const [isActive, isWithinWindow, participantCount, maxCap, window] = await Promise.all([
client
.is_active()
.then((tx) => tx.simulate())
.then(unwrapContractResult),
client
.is_within_window()
.then((tx) => tx.simulate())
.then(unwrapContractResult),
client
.get_participant_count()
.then((tx) => tx.simulate())
.then(unwrapContractResult),
client
.get_max_cap()
.then((tx) => tx.simulate())
.then(unwrapContractResult),
client
.get_window()
.then((tx) => tx.simulate())
.then(unwrapContractResult),
]);
// get_window() returns (start, end) as ledger-timestamp (unix seconds).
// Defaults to (0, u64::MAX) on-chain when unset -- treat that as "no
// window configured" rather than a real, extremely-far-future end date.
const [windowStart, windowEnd] = window;
const hasWindow = !(windowStart === 0n && windowEnd === 18446744073709551615n);
return {
isActive,
isWithinWindow,
participantCount: Number(participantCount),
// get_max_cap() == 0 means unlimited, per the contract's own convention
// (issue #317).
maxCap: Number(maxCap),
windowStart: hasWindow ? Number(windowStart) : null,
windowEnd: hasWindow ? Number(windowEnd) : null,
};
}
export async function checkParticipantStatus(walletAddress) {
const contractId = getCampaignContractId();
if (!contractId) {
throw new Error('Set VITE_CAMPAIGN_CONTRACT_ID to check participant status.');
}
const client = new CampaignClient({
rpcUrl: getSorobanRpcUrl(),
networkPassphrase: getNetworkPassphrase(),
contractId,
});
const tx = await client.is_participant({ participant: walletAddress });
return unwrapContractResult(await tx.simulate());
}
/**
* Build, sign (Freighter), submit, and poll a `register(participant, leaf, proof)` call
* on the campaign contract.
*
* Returns `{ hash: string, alreadyRegistered: boolean }`.
* - `alreadyRegistered === false` means the user was freshly registered.
* - `alreadyRegistered === true` means they were already registered (contract returned false).
*/
export async function submitRegisterTransaction(walletAddress) {
const contractId = getCampaignContractId();
if (!contractId) {
throw new Error('Set VITE_CAMPAIGN_CONTRACT_ID before registering.');
}
const client = new CampaignClient({
rpcUrl: getSorobanRpcUrl(),
networkPassphrase: getNetworkPassphrase(),
contractId,
publicKey: walletAddress,
signTransaction: async (txXdr) => {
const signedTxXdr = await walletManager.signTransaction(txXdr, {
networkPassphrase: getNetworkPassphrase(),
address: walletAddress,
});
return { signedTxXdr };
},
});
const emptyLeaf = new Uint8Array(32); // 32 bytes of zeros
const emptyProof = []; // Empty proof array
const tx = await client.register({
participant: walletAddress,
leaf: emptyLeaf,
proof: emptyProof,
});
const wasNew = unwrapContractResult(await tx.signAndSend());
const hash = tx.signed.hash().toString('hex');
return { hash, alreadyRegistered: !wasNew };
}
/**
* Initialize a campaign contract with the admin address.
*
* This is a simplified version that assumes the contract is already deployed
* and just needs to be initialized with an admin.
*
* For full deployment (WASM upload + contract creation), use backend deployment
* service or stellar-cli.
*
* Returns `{ hash: string }`.
*
* @param {string} walletAddress - The admin wallet address
* @param {string} contractId - The deployed contract ID
*/
export async function initializeCampaignContract(walletAddress, contractId) {
const client = new CampaignClient({
rpcUrl: getSorobanRpcUrl(),
networkPassphrase: getNetworkPassphrase(),
contractId,
publicKey: walletAddress,
signTransaction: async (txXdr) => {
const signedTxXdr = await walletManager.signTransaction(txXdr, {
networkPassphrase: getNetworkPassphrase(),
address: walletAddress,
});
return { signedTxXdr };
},
});
const tx = await client.initialize({ admin: walletAddress });
await tx.signAndSend();
const hash = tx.signed.hash().toString('hex');
return { hash };
}
/* ---------- Admin campaign contract helpers ---------- */
/**
* Get the current admin nonce for the campaign contract
*/
export async function getCampaignAdminNonce(contractId) {
const client = new CampaignClient({
rpcUrl: getSorobanRpcUrl(),
networkPassphrase: getNetworkPassphrase(),
contractId,
});
const tx = await client.admin_nonce();
return unwrapContractResult(await tx.simulate());
}
/**
* Set campaign active status (admin only)
*/
export async function setCampaignActive(walletAddress, contractId, active) {
const nonce = await getCampaignAdminNonce(contractId);
const client = new CampaignClient({
rpcUrl: getSorobanRpcUrl(),
networkPassphrase: getNetworkPassphrase(),
contractId,
publicKey: walletAddress,
signTransaction: async (txXdr) => {
const signedTxXdr = await walletManager.signTransaction(txXdr, {
networkPassphrase: getNetworkPassphrase(),
address: walletAddress,
});
return { signedTxXdr };
},
});
const tx = await client.set_active({
admin: walletAddress,
nonce,
active,
});
await tx.signAndSend();
const hash = tx.signed.hash().toString('hex');
return { hash };
}
/**
* Set campaign registration window (admin only)
*/
export async function setCampaignWindow(walletAddress, contractId, startTime, endTime) {
const nonce = await getCampaignAdminNonce(contractId);
const client = new CampaignClient({
rpcUrl: getSorobanRpcUrl(),
networkPassphrase: getNetworkPassphrase(),
contractId,
publicKey: walletAddress,
signTransaction: async (txXdr) => {
const signedTxXdr = await walletManager.signTransaction(txXdr, {
networkPassphrase: getNetworkPassphrase(),
address: walletAddress,
});
return { signedTxXdr };
},
});
const tx = await client.set_window({
admin: walletAddress,
nonce,
start: BigInt(startTime),
end: BigInt(endTime),
});
await tx.signAndSend();
const hash = tx.signed.hash().toString('hex');
return { hash };
}
/**
* Set campaign maximum participant cap (admin only)
*/
export async function setCampaignMaxCap(walletAddress, contractId, maxCap) {
const nonce = await getCampaignAdminNonce(contractId);
const client = new CampaignClient({
rpcUrl: getSorobanRpcUrl(),
networkPassphrase: getNetworkPassphrase(),
contractId,
publicKey: walletAddress,
signTransaction: async (txXdr) => {
const signedTxXdr = await walletManager.signTransaction(txXdr, {
networkPassphrase: getNetworkPassphrase(),
address: walletAddress,
});
return { signedTxXdr };
},
});
const tx = await client.set_max_cap({
admin: walletAddress,
nonce,
max_cap: BigInt(maxCap),
});
await tx.signAndSend();
const hash = tx.signed.hash().toString('hex');
return { hash };
}
/* ---------- SEP-41 token helpers (#550) ---------- */
/**
* Grant `spender` an allowance to spend `amount` from `walletAddress`'s balance.
* Pass `expirationLedger = 0` for a non-expiring allowance.
*
* @param {string} walletAddress
* @param {string} spender
* @param {number} amount
* @param {number} expirationLedger
*/
export async function submitApproveTransaction(
walletAddress,
spender,
amount,
expirationLedger = 0,
) {
const contractId = getRewardsContractId();
if (!contractId) throw new Error('Set VITE_REWARDS_CONTRACT_ID before approving.');
const client = new RewardsClient({
rpcUrl: getSorobanRpcUrl(),
networkPassphrase: getNetworkPassphrase(),
contractId,
publicKey: walletAddress,
signTransaction: async (txXdr) => {
const signedTxXdr = await walletManager.signTransaction(txXdr, {
networkPassphrase: getNetworkPassphrase(),
address: walletAddress,
});
return { signedTxXdr };
},
});
const tx = await client.sep41_approve({
from: walletAddress,
spender,
amount: BigInt(amount),
expiration_ledger: expirationLedger,
});
await tx.signAndSend();
const hash = tx.signed.hash().toString('hex');
return { hash };
}
/**
* Read the current allowance `owner` has granted to `spender`.
* Returns the amount as a number (0 if no allowance or expired).
*
* @param {string} owner
* @param {string} spender
* @returns {Promise<number>}
*/
export async function fetchAllowance(owner, spender) {
const contractId = getRewardsContractId();
if (!contractId) return 0;
const client = new RewardsClient({
rpcUrl: getSorobanRpcUrl(),
networkPassphrase: getNetworkPassphrase(),
contractId,
});
const tx = await client.sep41_allowance({ owner, spender });
const result = unwrapContractResult(await tx.simulate());
return Number(result ?? 0);
}
/**
* Transfer `amount` from `from` to `to` using a pre-approved allowance.
* The caller (`spender`) must have an active, sufficient allowance from `from`.
*
* @param {string} spenderAddress - the wallet signing the tx (must be the approved spender)
* @param {string} from
* @param {string} to
* @param {number} amount
*/
export async function submitTransferFromTransaction(spenderAddress, from, to, amount) {
const contractId = getRewardsContractId();
if (!contractId) throw new Error('Set VITE_REWARDS_CONTRACT_ID before using transfer_from.');
const client = new RewardsClient({
rpcUrl: getSorobanRpcUrl(),
networkPassphrase: getNetworkPassphrase(),
contractId,
publicKey: spenderAddress,
signTransaction: async (txXdr) => {
const signedTxXdr = await walletManager.signTransaction(txXdr, {
networkPassphrase: getNetworkPassphrase(),
address: spenderAddress,
});
return { signedTxXdr };
},
});
const tx = await client.sep41_transfer_from({
spender: spenderAddress,
from,
to,
amount: BigInt(amount),
});
await tx.signAndSend();
const hash = tx.signed.hash().toString('hex');
return { hash };
}
/**
* Burn `amount` from `from`'s balance using a pre-approved allowance.
*
* @param {string} spenderAddress
* @param {string} from
* @param {number} amount
*/
export async function submitBurnFromTransaction(spenderAddress, from, amount) {
const contractId = getRewardsContractId();
if (!contractId) throw new Error('Set VITE_REWARDS_CONTRACT_ID before using burn_from.');
const client = new RewardsClient({
rpcUrl: getSorobanRpcUrl(),
networkPassphrase: getNetworkPassphrase(),
contractId,
publicKey: spenderAddress,
signTransaction: async (txXdr) => {
const signedTxXdr = await walletManager.signTransaction(txXdr, {
networkPassphrase: getNetworkPassphrase(),
address: spenderAddress,
});
return { signedTxXdr };
},
});
const tx = await client.sep41_burn_from({
spender: spenderAddress,
from,
amount: BigInt(amount),
});
await tx.signAndSend();
const hash = tx.signed.hash().toString('hex');
return { hash };
}
/* ---------- Path payment helpers (#549) ---------- */
/**
* Fetch available payment paths from the backend (which proxies Horizon /paths).
*
* @param {string} sourceAccount
* @param {string} destinationAsset - "native" or "CODE:ISSUER"
* @param {string|number} destinationAmount
* @param {string} [sourceAsset] - "native" or "CODE:ISSUER"
* @returns {Promise<Array<{ sourceAmount: string; sourceAsset: string; path: any[] }>>}
*/
export async function fetchPaymentPaths(
sourceAccount,
destinationAsset,
destinationAmount,
sourceAsset = 'native',
) {
const params = new URLSearchParams({
source_account: sourceAccount,
destination_asset: destinationAsset,
destination_amount: String(destinationAmount),
source_asset: sourceAsset,
});
const resp = await fetch(`/api/v1/payment-paths?${params.toString()}`);
if (!resp.ok) {
const body = await resp.json().catch(() => ({}));
throw new Error(body.error ?? `Path-finding failed (${resp.status})`);
}
const data = await resp.json();
return data.paths ?? [];
}
/**
* Build, sign, and submit a PathPaymentStrictReceive transaction.
* The user sends at most `sendMax` of `sendAsset` and receives exactly
* `destinationAmount` of `destinationAsset`.
*
* @param {string} walletAddress
* @param {{ code: string; issuer?: string }} sendAsset
* @param {string} sendMax - max amount willing to send (with slippage already applied)
* @param {{ code: string; issuer?: string }} destinationAsset
* @param {string} destinationAmount
* @param {Array<{ asset_type: string; asset_code?: string; asset_issuer?: string }>} path
* @returns {Promise<{ hash: string }>}
*/
export async function submitPathPaymentClaimTransaction(
walletAddress,
sendAsset,
sendMax,
destinationAsset,
destinationAmount,
path = [],
) {
const {
Horizon: HorizonSdk,
TransactionBuilder: TxBuilder,
Operation,
Asset,
BASE_FEE: FEE,
} = await import('@stellar/stellar-sdk');
const networkPassphrase = getNetworkPassphrase();
const { horizonUrl } = await import('./config').then((m) => ({
horizonUrl:
m.getHorizonUrl?.() ??
import.meta.env.VITE_HORIZON_URL ??
'https://horizon-testnet.stellar.org',
}));
const server = new HorizonSdk.Server(horizonUrl);
const account = await server.loadAccount(walletAddress);
function buildAsset({ code, issuer }) {
return code === 'XLM' && !issuer ? Asset.native() : new Asset(code, issuer);
}
const intermediaryAssets = path.map((p) =>
p.asset_type === 'native' ? Asset.native() : new Asset(p.asset_code, p.asset_issuer),
);
const tx = new TxBuilder(account, { fee: String(Number(FEE) * 2), networkPassphrase })
.addOperation(
Operation.pathPaymentStrictReceive({
sendAsset: buildAsset(sendAsset),
sendMax,
destination: walletAddress,
destAsset: buildAsset(destinationAsset),
destAmount: destinationAmount,
path: intermediaryAssets,
}),
)
.setTimeout(180)
.build();
const txXdr = tx.toEnvelope().toXDR('base64');
const signedTxXdr = await walletManager.signTransaction(txXdr, {
networkPassphrase,
address: walletAddress,
});
const { Transaction } = await import('@stellar/stellar-sdk');
const signedTx = new Transaction(signedTxXdr, networkPassphrase);
const result = await server.submitTransaction(signedTx);
return { hash: result.hash };
}
/* ---------- Fee-bump / sponsorship helpers (#555) ---------- */
/**
* Minimum XLM balance required to pay Soroban fees without sponsorship.
* Below this, `isEligibleForSponsorship` returns true.
*/
const MIN_XLM_FOR_FEES = 2;
/**
* Returns true when the account has insufficient XLM for self-funded fees.
* Used by registration/claim flows to auto-route through sponsorship.
*
* @param {string} walletAddress
* @returns {Promise<boolean>}
*/
export async function isEligibleForSponsorship(walletAddress) {
try {
const balance = await fetchWalletBalance(walletAddress);
return parseFloat(balance) < MIN_XLM_FOR_FEES;
} catch {
return false;
}
}
/**
* Wrap a signed inner transaction XDR with a backend-issued fee-bump.
* The backend covers the fee from the sponsor account.
* Returns the fee-bump XDR ready to submit to Horizon.
*
* @param {string} innerXdr - signed inner transaction XDR
* @param {string} walletAddress - the submitting wallet (for quota tracking)
* @returns {Promise<string>} feeBumpXdr
*/
export async function wrapWithFeeBump(innerXdr, walletAddress) {
const resp = await fetch('/api/v1/fee-bump', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ innerXdr, walletAddress }),
});
const data = await resp.json();
if (!resp.ok) {
throw new Error(data.error ?? `Fee-bump failed (${resp.status})`);
}
return data.feeBumpXdr;
}
/**
* Set campaign Merkle root for allowlist (admin only)
*/
export async function setCampaignMerkleRoot(walletAddress, contractId, merkleRoot) {
const nonce = await getCampaignAdminNonce(contractId);
const client = new CampaignClient({
rpcUrl: getSorobanRpcUrl(),
networkPassphrase: getNetworkPassphrase(),
contractId,
publicKey: walletAddress,
signTransaction: async (txXdr) => {
const signedTxXdr = await walletManager.signTransaction(txXdr, {
networkPassphrase: getNetworkPassphrase(),
address: walletAddress,
});
return { signedTxXdr };
},
});
const tx = await client.set_merkle_root({
admin: walletAddress,
nonce,
root: merkleRoot,
});
await tx.signAndSend();
const hash = tx.signed.hash().toString('hex');
return { hash };
}