forked from ussyalfaks/Grainlify-Stellar-Contracts
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinvocation.ts
More file actions
411 lines (375 loc) · 11.2 KB
/
Copy pathinvocation.ts
File metadata and controls
411 lines (375 loc) · 11.2 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
import {
Account,
Keypair,
TransactionBuilder,
SorobanRpc,
Contract,
xdr,
BASE_FEE,
} from '@stellar/stellar-sdk';
import { NetworkError, ContractError } from './errors';
/**
* Configuration for contract invocation with Soroban RPC
*
* @example
* ```typescript
* const config: InvocationConfig = {
* server: new SorobanRpc.Server('https://soroban-testnet.stellar.org'),
* contract: new Contract('CAAAAAAA...'),
* networkPassphrase: 'Test SDF Network ; September 2015',
* rpcUrl: 'https://soroban-testnet.stellar.org'
* };
* ```
*/
export interface InvocationConfig {
/** Soroban RPC server instance for simulating and submitting transactions */
server: SorobanRpc.Server;
/** Contract instance containing the contract ID */
contract: Contract;
/** Network passphrase (e.g., "Test SDF Network ; September 2015" for testnet) */
networkPassphrase: string;
/** RPC endpoint URL for error messages and diagnostics */
rpcUrl: string;
}
/**
* Options for contract method invocation behavior
*
* @example
* ```typescript
* // State-changing operation
* const opts: InvokeOptions = {
* sourceKeypair: keypair,
* maxRetries: 30
* };
*
* // Read-only operation
* const readOnlyOpts: InvokeOptions = {
* readOnly: true
* };
* ```
*/
export interface InvokeOptions {
/** Keypair for signing transactions (required for state-changing operations) */
sourceKeypair?: Keypair;
/** If true, only simulates without submitting the transaction */
readOnly?: boolean;
/** Custom timeout in milliseconds (reserved for future use) */
timeoutMs?: number;
/** Maximum confirmation polling attempts (default: 30) */
maxRetries?: number;
}
/**
* Wait for a submitted transaction to be confirmed on the Soroban network.
*
* Polls transaction status with exponential backoff, starting at `baseDelayMs`
* and doubling on each retry (capped at 30 seconds). Returns immediately on
* SUCCESS, throws on FAILED, and retries on PENDING.
*
* **Security:** Signing keys are never logged or exposed in error messages.
*
* @param server - Soroban RPC server instance
* @param txHash - Transaction hash returned from server.sendTransaction()
* @param maxRetries - Maximum polling attempts (default: 30)
* @param baseDelayMs - Initial delay in milliseconds (default: 1000)
* @returns Confirmed transaction response
* @throws {ContractError} If transaction status is FAILED
* @throws {NetworkError} If max retries exceeded or connection fails
*
* @example
* ```typescript
* const submitResult = await server.sendTransaction(signedTx);
* if (submitResult.status === 'SUCCESS') {
* const confirmed = await waitForConfirmation(
* server,
* submitResult.hash,
* 30, // maxRetries
* 1000 // baseDelayMs
* );
* console.log('Transaction confirmed:', confirmed);
* }
* ```
*/
export async function waitForConfirmation(
server: SorobanRpc.Server,
txHash: string,
maxRetries: number = 30,
baseDelayMs: number = 1000
): Promise<any> {
let lastError: Error | null = null;
for (let attempt = 0; attempt < maxRetries; attempt++) {
try {
const response = await server.getTransaction(txHash);
if (response.status === 'SUCCESS') {
return response;
}
if (response.status === 'FAILED') {
throw new ContractError(
`Transaction failed`,
'TRANSACTION_FAILED',
undefined
);
}
// PENDING status, wait and retry
const delayMs = Math.min(
baseDelayMs * Math.pow(2, attempt),
30000 // max 30 seconds
);
await new Promise(resolve => setTimeout(resolve, delayMs));
} catch (error: any) {
if (error instanceof ContractError) {
throw error;
}
lastError = error;
// Continue retrying on transient errors
if (attempt < maxRetries - 1) {
const delayMs = Math.min(
baseDelayMs * Math.pow(2, attempt),
30000
);
await new Promise(resolve => setTimeout(resolve, delayMs));
}
}
}
if (lastError) {
throw new NetworkError(
`Failed to confirm transaction after ${maxRetries} attempts`,
undefined,
lastError
);
}
throw new NetworkError(
`Transaction confirmation timeout after ${maxRetries} attempts`,
undefined
);
}
/**
* Invoke a contract method with full transaction lifecycle management.
*
* Implements the complete Soroban invocation flow:
* 1. Build - Create contract invocation operation
* 2. Simulate - Validate against network state (always done first)
* 3. Sign - Sign with keypair (if provided)
* 4. Submit - Send to network (if keypair provided)
* 5. Confirm - Poll for completion (if submitted)
*
* For read-only calls (no keypair), returns simulation result immediately.
* For state-changing calls, builds, signs, submits, and confirms the transaction.
*
* **Security:** Simulation always precedes submission. Simulation errors are
* surfaced to caller. Keypairs are never logged. Always validate input with
* your own ValidationError checks before calling this function.
*
* @param method - Contract method name to invoke
* @param args - Array of method arguments (will be converted to Soroban types)
* @param config - Invocation configuration (server, contract, network)
* @param options - Optional behavior modifiers
* @returns The contract method's return value (parsed from XDR)
* @throws {ValidationError} If parameters are invalid
* @throws {NetworkError} If connection fails or RPC error occurs
* @throws {ContractError} If simulation or contract execution fails
*
* @example
* ```typescript
* import { invokeContract } from '@grainlify/contracts-sdk';
* import { Keypair } from '@stellar/stellar-sdk';
*
* // Read-only call
* const balance = await invokeContract(
* 'get_balance',
* [],
* config,
* { readOnly: true }
* );
*
* // State-changing call
* const keypair = Keypair.fromSecret(process.env.SECRET_KEY);
* await invokeContract(
* 'lock_funds',
* [depositor, bountyId, amount, deadline],
* config,
* { sourceKeypair: keypair, maxRetries: 30 }
* );
* ```
*/
export async function invokeContract(
method: string,
args: any[],
config: InvocationConfig,
options: InvokeOptions = {}
): Promise<any> {
const { sourceKeypair, readOnly = false, maxRetries = 30 } = options;
try {
// Build the invocation
const invocation = config.contract.call(method, ...args);
// If no keypair provided, do simulation only (for read operations)
if (!sourceKeypair) {
const simulationResult = await simulateTransaction(
invocation,
config,
null
);
return parseInvocationResult(simulationResult);
}
// Get account information for the source keypair
const account = await getAccount(config.server, sourceKeypair.publicKey());
// Build the transaction
const transaction = new TransactionBuilder(account, {
fee: BASE_FEE,
networkPassphrase: config.networkPassphrase,
})
.addOperation(invocation)
.setTimeout(30)
.build();
// Simulate the transaction
let simulationResult = await simulateTransaction(
transaction,
config,
sourceKeypair
);
// Assemble the transaction
const assembled = SorobanRpc.assembleTransaction(
transaction,
simulationResult
).build();
// Sign the transaction
assembled.sign(sourceKeypair);
// For read-only operations, return simulation result
if (readOnly) {
return parseInvocationResult(simulationResult);
}
// Submit the transaction
const submitResult = await config.server.sendTransaction(assembled);
if (submitResult.status === 'ERROR') {
throw new ContractError(
`Failed to submit transaction`,
'SUBMIT_FAILED'
);
}
// Wait for confirmation
const confirmed = await waitForConfirmation(
config.server,
submitResult.hash,
maxRetries
);
// Parse and return the result
return parseInvocationResult(confirmed);
} catch (error: any) {
// Re-throw known errors
if (error instanceof ContractError || error instanceof NetworkError) {
throw error;
}
// Handle network errors
if (
error.code === 'ECONNREFUSED' ||
error.code === 'ETIMEDOUT' ||
error.code === 'ENOTFOUND'
) {
throw new NetworkError(
`Failed to connect to RPC server: ${config.rpcUrl}`,
undefined,
error
);
}
// Handle RPC response errors
if (error.response?.status) {
throw new NetworkError(
`RPC request failed with status ${error.response.status}`,
error.response.status,
error
);
}
// Wrap unknown errors
throw new ContractError(
`Contract invocation failed: ${error.message}`,
'INVOCATION_FAILED',
undefined
);
}
}
/**
* Simulate a transaction without submitting it
*/
async function simulateTransaction(
transaction: any,
config: InvocationConfig,
sourceKeypair: Keypair | null
): Promise<any> {
try {
const response = await config.server.simulateTransaction(transaction);
// Check if it's an error response
if ((response as any).error || (response as any).errorMessage) {
throw new ContractError(
`Simulation failed: ${(response as any).error || (response as any).errorMessage}`,
'SIMULATION_FAILED'
);
}
return response;
} catch (error: any) {
if (error instanceof ContractError) {
throw error;
}
// Let the invokeContract handler deal with network errors
throw error;
}
}
/**
* Get account information from the server
*/
async function getAccount(
server: SorobanRpc.Server,
publicKey: string
): Promise<Account> {
try {
const response = await server.getAccount(publicKey);
// Handle both possible return types for sequence
const sequence = typeof (response as any).sequence === 'string'
? (response as any).sequence
: ((response as any).sequence?.toString() || '0');
return new Account(publicKey, sequence);
} catch (error: any) {
if (
error.code === 'ECONNREFUSED' ||
error.code === 'ETIMEDOUT' ||
error.code === 'ENOTFOUND'
) {
throw new NetworkError(
'Failed to fetch account information',
undefined,
error
);
}
throw new NetworkError(
`Failed to get account: ${error.message}`,
undefined,
error
);
}
}
/**
* Parse the result from a simulation or confirmed transaction
*/
function parseInvocationResult(response: any): any {
try {
if (!response.result && !response.results) {
return null;
}
// For GetTransactionResponse (confirmed transaction)
if (response.resultMetaXdr) {
// Parse from confirmed transaction meta
return response;
}
// For SimulateTransactionSuccessResponse
if (response.results && response.results.length > 0) {
const firstResult = response.results[0];
if (firstResult.xdr) {
return xdr.ScVal.fromXDR(firstResult.xdr, 'base64');
}
}
return response.result || null;
} catch (error: any) {
throw new ContractError(
`Failed to parse invocation result: ${error.message}`,
'PARSE_FAILED'
);
}
}