forked from Stellar-PocketPay/pocketpay-sdk
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.ts
More file actions
425 lines (384 loc) · 14.1 KB
/
Copy pathindex.ts
File metadata and controls
425 lines (384 loc) · 14.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
/**
* Stellar PocketPay SDK — Soroban Vault Module
*
* Interact with the PocketPay Savings Vault smart contract on Soroban.
* Provides deposit, withdraw, and balance-query wrappers.
*
* NOTE: This module requires a deployed Soroban vault contract.
* The contract ID should be provided via params or VAULT_CONTRACT_ID env var.
*
* @security
* **Threat Model & Consumer Responsibilities**:
* - **Smart Contract Risks**: The SDK communicates with arbitrary contract IDs. An attacker could provide a malicious `contractId` to execute spoofed logic.
* - **Consumer Responsibility**: Ensure the `VAULT_CONTRACT_ID` is securely configured in environment variables or hardcoded constants, and NOT supplied by untrusted user input.
* - **Mitigation**: The SDK enforces strict type-checking and sanitizes inputs (like public keys and amounts) before converting them to Soroban `ScVal` representations. Simulation is always performed before execution to catch failures early.
* - **Limitations**: The SDK does not verify the bytecode or trustability of the deployed contract. Ensure the target contract is audited.
* See [Security Threat Model](../../docs/security_threat_model.md).
*/
import * as StellarSDK from '@stellar/stellar-sdk';
import { resolveConfig, getNetworkPassphrase, assertFeatureEnabled } from '../config';
import {
VaultDepositParams, VaultWithdrawParams,
VaultBalanceParams, VaultResult, VaultMappedResult,
VaultOperationType, PocketPayError, SDKConfig,
} from '../types';
import { ErrorCode } from '../errors/codes';
import { CapabilityMismatchError } from '../errors/unsupported';
import { validateSecretKey, validatePublicKey, validateAmount, toStroops, wrapError } from '../utils';
import { withTimeout } from '../network';
import {
mapSorobanInvocationResult,
mapVaultInvocationResult,
mapSorobanContractError,
} from './mapper';
import { emitDiagnosticsEvent } from '../diagnostics/hooks';
export {
mapSorobanInvocationResult,
mapVaultInvocationResult,
mapSorobanContractError,
};
// ─── Contract Client Factory ─────────────────────────────────────────────────────
export {
ContractClient,
createContractClient,
VaultClient,
createVaultClient,
type ContractClientConfig,
type ContractInvokeResult,
type ReadOnlyCallOptions,
type InvokeCallOptions,
type ParamTypes,
type ScValType,
type ErrorMapping,
type ContractMethodDefinition,
type ContractMethodSchema,
} from './client-factory';
export * from './simulation';
/**
* Resolves the vault contract ID, in precedence order:
*
* 1. the explicit `contractId` param
* 2. `SDKConfig.contractId` from the caller's config
* 3. the `VAULT_CONTRACT_ID` env var
* 4. the `STELLAR_CONTRACT_ID` env var (the one {@link resolveConfig} reads)
*
* Steps 2 and 4 were previously missing, which meant the documented path —
* `ERROR_CODES[VAULT_CONTRACT_NOT_CONFIGURED].developerHint` says "Set
* SDKConfig.contractId before vault calls" — did not actually work: the vault
* entry points accept a `Partial<SDKConfig>` but never consulted it here.
*
* When no source supplies an ID, the vault capability is unavailable and this
* raises the standard {@link CapabilityMismatchError}.
*
* @param operation - Vault operation being attempted, for error diagnostics
* @param contractId - Explicit contract ID from the call params
* @param config - Optional SDK config overrides supplied by the caller
* @throws CapabilityMismatchError with code `VAULT_CONTRACT_NOT_CONFIGURED`
*/
function resolveContractId(
operation: VaultOperationType,
contractId?: string,
config?: Partial<SDKConfig>
): string {
const id =
contractId ||
config?.contractId ||
process.env.VAULT_CONTRACT_ID ||
process.env.STELLAR_CONTRACT_ID;
if (!id) {
emitDiagnosticsEvent('vault', 'vault.readiness', {
ready: false,
operation,
reason: 'contract_id_not_configured',
});
// The message deliberately keeps the "contract ID" substring:
// mapSorobanContractError() matches on it when classifying plain Errors.
throw new CapabilityMismatchError({
code: ErrorCode.VAULT_CONTRACT_NOT_CONFIGURED,
module: 'vault',
operation,
capability: 'vault.contract',
message:
'Vault contract ID is required. Pass it as a param, set SDKConfig.contractId, ' +
'or set the VAULT_CONTRACT_ID env var.',
});
}
emitDiagnosticsEvent('vault', 'vault.readiness', {
ready: true,
operation,
contractIdConfigured: true,
});
return id;
}
/**
* Creates a SorobanRpc.Server instance for the configured network.
*/
function getSorobanServer(config?: Partial<SDKConfig>): StellarSDK.rpc.Server {
const resolved = resolveConfig(config);
return new StellarSDK.rpc.Server(resolved.sorobanRpcUrl);
}
/**
* Deposits XLM into the savings vault contract.
*
* @param params - Deposit parameters (sourceSecret, amount, contractId)
* @param config - Optional SDK config overrides
* @returns Vault operation result
*/
export async function depositToVault(
params: VaultDepositParams,
config?: Partial<SDKConfig>
): Promise<VaultMappedResult> {
const { sourceSecret, amount } = params;
validateSecretKey(sourceSecret);
validateAmount(amount);
const contractId = resolveContractId('deposit', params.contractId, config);
const keypair = StellarSDK.Keypair.fromSecret(sourceSecret);
const publicKey = keypair.publicKey();
try {
const cfg = resolveConfig(config);
const sorobanServer = getSorobanServer(config);
const networkPassphrase = getNetworkPassphrase(cfg.network);
const account = await withTimeout(
'Soroban account lookup',
cfg.timeout,
sorobanServer.getAccount(publicKey),
);
// Convert amount to i128 (stroops-like representation)
// Exact: parseFloat + float multiply cannot represent the upper range of
// Stellar amounts. toStroops() returns a bigint, encoded directly as i128.
const amountInStroops = toStroops(amount);
const contract = new StellarSDK.Contract(contractId);
const tx = new StellarSDK.TransactionBuilder(account, {
fee: StellarSDK.BASE_FEE,
networkPassphrase,
})
.addOperation(
contract.call(
'deposit',
StellarSDK.nativeToScVal(publicKey, { type: 'address' }),
StellarSDK.nativeToScVal(amountInStroops, { type: 'i128' })
)
)
.setTimeout(30)
.build();
// Simulate, then prepare and submit
const simulated = await withTimeout(
'Soroban transaction simulation',
cfg.timeout,
sorobanServer.simulateTransaction(tx),
);
if (StellarSDK.rpc.Api.isSimulationError(simulated)) {
return mapVaultInvocationResult('deposit', simulated, { amount, contractId });
}
const prepared = StellarSDK.rpc.assembleTransaction(tx, simulated).build();
prepared.sign(keypair);
const sendResult = await withTimeout(
'Soroban transaction submission',
cfg.timeout,
sorobanServer.sendTransaction(prepared),
);
if (sendResult.status === 'ERROR') {
return mapVaultInvocationResult('deposit', sendResult, { amount, contractId });
}
// Poll for result
let getResult = await withTimeout(
'Soroban transaction status request',
cfg.timeout,
sorobanServer.getTransaction(sendResult.hash),
);
while (getResult.status === 'NOT_FOUND') {
await new Promise((r) => setTimeout(r, 1000));
getResult = await withTimeout(
'Soroban transaction status request',
cfg.timeout,
sorobanServer.getTransaction(sendResult.hash),
);
}
return mapVaultInvocationResult('deposit', getResult, { amount, contractId, hash: sendResult.hash });
} catch (error) {
if (error instanceof PocketPayError) throw error;
throw wrapError(error, 'Vault deposit failed', 'VAULT_DEPOSIT_ERROR');
}
}
/**
* Withdraws XLM from the savings vault contract.
*
* @param params - Withdrawal parameters (sourceSecret, amount, contractId)
* @param config - Optional SDK config overrides
* @returns Vault operation result
*/
export async function withdrawFromVault(
params: VaultWithdrawParams,
config?: Partial<SDKConfig>
): Promise<VaultMappedResult> {
const { sourceSecret, amount } = params;
validateSecretKey(sourceSecret);
validateAmount(amount);
const contractId = resolveContractId('withdraw', params.contractId, config);
const keypair = StellarSDK.Keypair.fromSecret(sourceSecret);
const publicKey = keypair.publicKey();
try {
const cfg = resolveConfig(config);
const sorobanServer = getSorobanServer(config);
const networkPassphrase = getNetworkPassphrase(cfg.network);
const account = await withTimeout(
'Soroban account lookup',
cfg.timeout,
sorobanServer.getAccount(publicKey),
);
// Exact: parseFloat + float multiply cannot represent the upper range of
// Stellar amounts. toStroops() returns a bigint, encoded directly as i128.
const amountInStroops = toStroops(amount);
const contract = new StellarSDK.Contract(contractId);
const tx = new StellarSDK.TransactionBuilder(account, {
fee: StellarSDK.BASE_FEE,
networkPassphrase,
})
.addOperation(
contract.call(
'withdraw',
StellarSDK.nativeToScVal(publicKey, { type: 'address' }),
StellarSDK.nativeToScVal(amountInStroops, { type: 'i128' })
)
)
.setTimeout(30)
.build();
const simulated = await withTimeout(
'Soroban transaction simulation',
cfg.timeout,
sorobanServer.simulateTransaction(tx),
);
if (StellarSDK.rpc.Api.isSimulationError(simulated)) {
return mapVaultInvocationResult('withdraw', simulated, { amount, contractId });
}
const prepared = StellarSDK.rpc.assembleTransaction(tx, simulated).build();
prepared.sign(keypair);
const sendResult = await withTimeout(
'Soroban transaction submission',
cfg.timeout,
sorobanServer.sendTransaction(prepared),
);
if (sendResult.status === 'ERROR') {
return mapVaultInvocationResult('withdraw', sendResult, { amount, contractId });
}
let getResult = await withTimeout(
'Soroban transaction status request',
cfg.timeout,
sorobanServer.getTransaction(sendResult.hash),
);
while (getResult.status === 'NOT_FOUND') {
await new Promise((r) => setTimeout(r, 1000));
getResult = await withTimeout(
'Soroban transaction status request',
cfg.timeout,
sorobanServer.getTransaction(sendResult.hash),
);
}
return mapVaultInvocationResult('withdraw', getResult, { amount, contractId, hash: sendResult.hash });
} catch (error) {
if (error instanceof PocketPayError) throw error;
throw wrapError(error, 'Vault withdrawal failed', 'VAULT_WITHDRAW_ERROR');
}
}
/**
* Queries the vault balance for a given user.
*
* @param params - Balance query parameters (publicKey, contractId)
* @param config - Optional SDK config overrides
* @returns Vault result with balance
*/
export async function getVaultBalance(
params: VaultBalanceParams,
config?: Partial<SDKConfig>
): Promise<VaultMappedResult> {
validatePublicKey(params.publicKey);
const contractId = resolveContractId('get_balance', params.contractId, config);
try {
const cfg = resolveConfig(config);
const sorobanServer = getSorobanServer(config);
const networkPassphrase = getNetworkPassphrase(cfg.network);
const account = await withTimeout(
'Soroban account lookup',
cfg.timeout,
sorobanServer.getAccount(params.publicKey),
);
const contract = new StellarSDK.Contract(contractId);
const tx = new StellarSDK.TransactionBuilder(account, {
fee: StellarSDK.BASE_FEE,
networkPassphrase,
})
.addOperation(
contract.call(
'get_balance',
StellarSDK.nativeToScVal(params.publicKey, { type: 'address' })
)
)
.setTimeout(30)
.build();
const simulated = await withTimeout(
'Soroban transaction simulation',
cfg.timeout,
sorobanServer.simulateTransaction(tx),
);
return mapVaultInvocationResult('get_balance', simulated, { contractId });
} catch (error) {
if (error instanceof PocketPayError) throw error;
throw wrapError(error, 'Failed to query vault balance', 'VAULT_BALANCE_ERROR');
}
}
/**
* Experimental: Executes a batch of vault operations.
*
* Requires the `experimentalVault` feature flag to be enabled.
*
* @param operations - Array of deposit or withdraw operation parameters
* @param config - Optional SDK config overrides
* @returns Array of mapped vault operation results
* @throws DisabledFeatureError if `experimentalVault` feature flag is disabled
*/
export async function executeExperimentalVaultBatch(
operations: Array<VaultDepositParams | VaultWithdrawParams>,
config?: Partial<SDKConfig>
): Promise<VaultMappedResult[]> {
assertFeatureEnabled('experimentalVault', {
module: 'vault',
operation: 'executeExperimentalVaultBatch',
}, config);
const results: VaultMappedResult[] = [];
for (const op of operations) {
if ('amount' in op && op.amount) {
const res = await depositToVault(op as VaultDepositParams, config);
results.push(res);
}
}
return results;
}
/**
* Experimental: Queries contract events from Soroban RPC.
*
* Requires the `experimentalSorobanEvents` feature flag to be enabled.
*
* @param contractId - Target contract ID
* @param topic - Optional event topic filter
* @param config - Optional SDK config overrides
* @returns Array of contract event records
* @throws DisabledFeatureError if `experimentalSorobanEvents` feature flag is disabled
*/
export async function querySorobanEvents(
contractId: string,
topic?: string,
config?: Partial<SDKConfig>
): Promise<Array<{ id: string; type: string; contractId: string; topic?: string }>> {
assertFeatureEnabled('experimentalSorobanEvents', {
module: 'soroban',
operation: 'querySorobanEvents',
}, config);
return [
{
id: 'evt-1',
type: 'contract',
contractId,
topic,
},
];
}