-
Notifications
You must be signed in to change notification settings - Fork 173
Expand file tree
/
Copy pathfreighter.ts
More file actions
471 lines (414 loc) · 13.4 KB
/
Copy pathfreighter.ts
File metadata and controls
471 lines (414 loc) · 13.4 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
import {
getNetworkDetails,
isConnected,
requestAccess,
signTransaction,
} from '@stellar/freighter-api';
import {
Address,
BASE_FEE,
Contract,
TransactionBuilder,
nativeToScVal,
rpc,
} from '@stellar/stellar-sdk';
import { AppConfig, PledgeTransactionResult, WalletConnection } from '../types/campaign';
type AppErrorLike = Error & { code?: string };
const TESTNET_PASSPHRASE = 'Test SDF Network ; September 2015';
const MAINNET_PASSPHRASE = 'Public Global Stellar Network ; September 2015';
function buildError(code: string, message: string): AppErrorLike {
const error = new Error(message) as AppErrorLike;
error.code = code;
return error;
}
function getErrorMessage(error: unknown, fallback: string): string {
if (error instanceof Error && error.message.trim().length > 0) {
return error.message;
}
if (typeof error === 'string' && error.trim().length > 0) {
return error;
}
return fallback;
}
function getRpcServer(rpcUrl: string): rpc.Server {
return new rpc.Server(rpcUrl, { allowHttp: rpcUrl.startsWith('http://') });
}
function networkLabel(passphrase: string | undefined): string {
if (!passphrase) {
return 'unknown network';
}
if (passphrase === TESTNET_PASSPHRASE) {
return 'Stellar Testnet';
}
if (passphrase === MAINNET_PASSPHRASE) {
return 'Stellar Mainnet';
}
return 'the configured network';
}
function sleep(ms: number): Promise<void> {
return new Promise((resolve) => {
window.setTimeout(resolve, ms);
});
}
const STROOPS_PER_XLM = 10_000_000;
export interface EstimatedFee {
stroops: number;
xlm: string;
}
function formatStroopsAsXlm(stroops: number): string {
return (stroops / STROOPS_PER_XLM).toFixed(7).replace(/\.?0+$/, "");
}
/**
* Derives the estimated network fee from a transaction that has already been
* prepared from a Soroban simulation. The prepared transaction's fee covers the
* inclusion fee plus the simulated resource fee, i.e. what the wallet will be
* asked to pay. Returns null when the fee cannot be parsed so the UI can fall
* back to a "Calculating..." state instead of showing a misleading value.
*/
function estimateFeeFromTransaction(transaction: { fee: string }): EstimatedFee | null {
try {
const feeStroops = Number(transaction.fee);
if (!Number.isFinite(feeStroops) || feeStroops < 0) {
return null;
}
return { stroops: feeStroops, xlm: formatStroopsAsXlm(feeStroops) };
} catch {
return null;
}
}
export function amountToContractUnits(amount: number, decimals: number): bigint {
if (!Number.isFinite(amount) || amount <= 0) {
throw buildError('INVALID_AMOUNT', 'Pledge amount must be greater than zero.');
}
if (!Number.isInteger(decimals) || decimals < 0 || decimals > 12) {
throw buildError('INVALID_DECIMALS', 'Invalid contract amount decimals configuration.');
}
const factor = 10 ** decimals;
const scaled = amount * factor;
const rounded = Math.round(scaled);
if (Math.abs(scaled - rounded) > 1e-8) {
throw buildError(
'INVALID_AMOUNT_PRECISION',
`Amount must use no more than ${decimals} decimal place${decimals === 1 ? '' : 's'}.`,
);
}
return BigInt(rounded);
}
export async function connectFreighterWallet(
expectedNetworkPassphrase: string,
): Promise<WalletConnection> {
const connected = await isConnected();
if (!connected) {
throw buildError(
'FREIGHTER_UNAVAILABLE',
'Freighter was not detected. Install or unlock the extension and try again.',
);
}
let publicKey: string;
try {
publicKey = await requestAccess();
} catch (error) {
throw buildError(
'FREIGHTER_ACCESS_DENIED',
getErrorMessage(error, 'Freighter access was rejected.'),
);
}
let details:
| {
networkPassphrase: string;
sorobanRpcUrl?: string;
}
| undefined;
try {
const networkDetails = await getNetworkDetails();
details = {
networkPassphrase: networkDetails.networkPassphrase,
sorobanRpcUrl: networkDetails.sorobanRpcUrl,
};
} catch {
details = undefined;
}
if (details?.networkPassphrase && details.networkPassphrase !== expectedNetworkPassphrase) {
throw buildError(
'FREIGHTER_NETWORK_MISMATCH',
`Freighter is connected to ${networkLabel(details.networkPassphrase)}, but this app expects ${networkLabel(expectedNetworkPassphrase)}.`,
);
}
return {
publicKey,
networkPassphrase: details?.networkPassphrase,
sorobanRpcUrl: details?.sorobanRpcUrl,
};
}
async function waitForTransaction(
server: rpc.Server,
transactionHash: string,
): Promise<PledgeTransactionResult> {
for (let attempt = 0; attempt < 25; attempt += 1) {
const result = await server.getTransaction(transactionHash);
if (result.status === rpc.Api.GetTransactionStatus.SUCCESS) {
return {
transactionHash,
confirmedAt: result.createdAt,
};
}
if (result.status === rpc.Api.GetTransactionStatus.FAILED) {
throw buildError(
'TRANSACTION_FAILED',
`The network rejected transaction ${transactionHash}.`,
);
}
await sleep(1200);
}
throw buildError(
'TRANSACTION_TIMEOUT',
`Transaction ${transactionHash} was submitted but did not confirm before the UI timeout.`,
);
}
export async function submitFreighterClaim(params: {
campaignId: string;
creator: string;
config: AppConfig;
onPreview?: (preview: {
operation: string;
amount?: number;
assetCode?: string;
contract: string;
xdr: string;
estimatedFee?: EstimatedFee;
}) => Promise<boolean>;
}): Promise<PledgeTransactionResult> {
const { campaignId, creator, config } = params;
if (!config.contractId || !config.sorobanRpcUrl) {
throw buildError(
'CONFIG_MISSING',
'Wallet signing is not configured yet. Set CONTRACT_ID and SOROBAN_RPC_URL on the backend.',
);
}
const server = getRpcServer(config.sorobanRpcUrl);
const sourceAccount = await server.getAccount(creator).catch((error) => {
throw buildError(
'SOURCE_ACCOUNT_LOAD_FAILED',
getErrorMessage(error, 'Unable to load the creator account from Soroban RPC.'),
);
});
const operation = new Contract(config.contractId).call(
'claim',
nativeToScVal(BigInt(campaignId), { type: 'u64' }),
Address.fromString(creator).toScVal(),
);
const transaction = new TransactionBuilder(sourceAccount, {
fee: BASE_FEE,
networkPassphrase: config.networkPassphrase,
})
.addOperation(operation)
.setTimeout(60)
.build();
const simulation = await server.simulateTransaction(transaction).catch((error) => {
throw buildError(
'SIMULATION_FAILED',
getErrorMessage(error, 'Unable to simulate the claim transaction.'),
);
});
if ('error' in simulation) {
throw buildError('SIMULATION_FAILED', `Simulation failed: ${simulation.error}`);
}
if ('restorePreamble' in simulation) {
throw buildError(
'STATE_RESTORE_REQUIRED',
'The contract state is archived and must be restored before claiming.',
);
}
const preparedTransaction = await server.prepareTransaction(transaction).catch((error) => {
throw buildError(
'SIMULATION_PREPARE_FAILED',
getErrorMessage(error, 'Failed to prepare the simulated claim transaction.'),
);
});
if (params.onPreview) {
const isApproved = await params.onPreview({
operation: 'claim',
contract: config.contractId,
xdr: preparedTransaction.toXDR(),
estimatedFee: estimateFeeFromTransaction(preparedTransaction) ?? undefined,
});
if (!isApproved) {
throw buildError('USER_CANCELLED', 'User cancelled the transaction from the preview panel.');
}
}
let signedXdr: string;
try {
signedXdr = await signTransaction(preparedTransaction.toXDR(), {
accountToSign: creator,
networkPassphrase: config.networkPassphrase,
});
} catch (error) {
throw buildError(
'SIGNING_FAILED',
getErrorMessage(error, 'Freighter rejected or failed to sign the claim transaction.'),
);
}
if (!signedXdr) {
throw buildError('SIGNING_FAILED', 'Freighter did not return a signed transaction.');
}
const signedTransaction = TransactionBuilder.fromXDR(signedXdr, config.networkPassphrase);
const sendResult = await server.sendTransaction(signedTransaction).catch((error) => {
throw buildError(
'SUBMISSION_FAILED',
getErrorMessage(error, 'Failed to submit the signed claim transaction to Soroban RPC.'),
);
});
if (sendResult.status === 'ERROR') {
throw buildError(
'CONTRACT_CALL_FAILED',
`Soroban RPC rejected the claim transaction ${sendResult.hash}.`,
);
}
if (sendResult.status === 'TRY_AGAIN_LATER') {
throw buildError(
'SUBMISSION_RETRY',
'Soroban RPC asked the client to retry claim submission later.',
);
}
return waitForTransaction(server, sendResult.hash);
}
export async function submitFreighterPledge(params: {
campaignId: string;
contributor: string;
amount: number;
assetCode: string;
config: AppConfig;
onPreview?: (preview: {
operation: string;
amount?: number;
assetCode?: string;
contract: string;
xdr: string;
estimatedFee?: EstimatedFee;
}) => Promise<boolean>;
}): Promise<PledgeTransactionResult> {
const { campaignId, contributor, amount, config, assetCode } = params;
if (!config.contractId || !config.sorobanRpcUrl) {
throw buildError(
'CONFIG_MISSING',
'Wallet signing is not configured yet. Set CONTRACT_ID and SOROBAN_RPC_URL on the backend.',
);
}
const server = getRpcServer(config.sorobanRpcUrl);
const amountUnits = amountToContractUnits(amount, config.contractAmountDecimals);
const tokenAddress = config.assetAddresses[assetCode.toUpperCase()];
if (!tokenAddress) {
throw buildError(
'ASSET_NOT_CONFIGURED',
`Soroban contract address for ${assetCode} is not configured.`,
);
}
const sourceAccount = await server.getAccount(contributor).catch((error) => {
throw buildError(
'SOURCE_ACCOUNT_LOAD_FAILED',
getErrorMessage(error, 'Unable to load the contributor account from Soroban RPC.'),
);
});
const operation = new Contract(config.contractId).call(
'contribute',
nativeToScVal(BigInt(campaignId), { type: 'u64' }),
Address.fromString(contributor).toScVal(),
Address.fromString(tokenAddress).toScVal(),
nativeToScVal(amountUnits, { type: 'i128' }),
);
const transaction = new TransactionBuilder(sourceAccount, {
fee: BASE_FEE,
networkPassphrase: config.networkPassphrase,
})
.addOperation(operation)
.setTimeout(60)
.build();
const simulation = await server.simulateTransaction(transaction).catch((error) => {
throw buildError(
'SIMULATION_FAILED',
getErrorMessage(error, 'Unable to simulate the pledge transaction.'),
);
});
if ('error' in simulation) {
throw buildError('SIMULATION_FAILED', `Simulation failed: ${simulation.error}`);
}
if ('restorePreamble' in simulation) {
throw buildError(
'STATE_RESTORE_REQUIRED',
'The contract state is archived and must be restored before pledging.',
);
}
const preparedTransaction = await server.prepareTransaction(transaction).catch((error) => {
throw buildError(
'SIMULATION_PREPARE_FAILED',
getErrorMessage(error, 'Failed to prepare the simulated transaction.'),
);
});
if (params.onPreview) {
const isApproved = await params.onPreview({
operation: 'contribute',
amount: params.amount,
assetCode: params.assetCode,
contract: config.contractId,
xdr: preparedTransaction.toXDR(),
estimatedFee: estimateFeeFromTransaction(preparedTransaction) ?? undefined,
});
if (!isApproved) {
throw buildError('USER_CANCELLED', 'User cancelled the transaction from the preview panel.');
}
}
let signedXdr: string;
try {
signedXdr = await signTransaction(preparedTransaction.toXDR(), {
accountToSign: contributor,
networkPassphrase: config.networkPassphrase,
});
} catch (error) {
throw buildError(
'SIGNING_FAILED',
getErrorMessage(error, 'Freighter rejected or failed to sign the transaction.'),
);
}
if (!signedXdr) {
throw buildError('SIGNING_FAILED', 'Freighter did not return a signed transaction.');
}
const signedTransaction = TransactionBuilder.fromXDR(signedXdr, config.networkPassphrase);
const sendResult = await server.sendTransaction(signedTransaction).catch((error) => {
throw buildError(
'SUBMISSION_FAILED',
getErrorMessage(error, 'Failed to submit the signed transaction to Soroban RPC.'),
);
});
if (sendResult.status === 'ERROR') {
throw buildError(
'SUBMISSION_FAILED',
`Soroban RPC rejected the transaction ${sendResult.hash}.`,
);
}
if (sendResult.status === 'TRY_AGAIN_LATER') {
throw buildError(
'SUBMISSION_RETRY',
'Soroban RPC asked the client to retry transaction submission later.',
);
}
return waitForTransaction(server, sendResult.hash);
}
export function watchFreighterAccount(onChange: (address: string) => void): () => void {
let lastAddress = '';
const id = window.setInterval(async () => {
try {
const address = await requestAccess();
if (address !== lastAddress) {
lastAddress = address;
onChange(address);
}
} catch {
// extension unavailable or locked — treat as disconnected
if (lastAddress !== '') {
lastAddress = '';
onChange('');
}
}
}, 2000);
return () => window.clearInterval(id);
}