-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathstellar.ts
More file actions
517 lines (480 loc) · 21.1 KB
/
stellar.ts
File metadata and controls
517 lines (480 loc) · 21.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
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
import * as StellarSdk from "@stellar/stellar-sdk";
import { ExtrinsicResult } from "@threefold/tfchain_client";
import { GridClientError, RequestError, ValidationError } from "@threefold/types";
import axios, { AxiosError } from "axios";
import { Buffer } from "buffer";
import * as PATH from "path";
import { TFClient } from "../clients/tf-grid/client";
import { GridClientConfig } from "../config";
import { expose } from "../helpers/expose";
import { validateInput } from "../helpers/validator";
import { appPath, BackendStorage, BackendStorageType, StorageUpdateAction } from "../storage/backend";
import {
BlockchainAssetModel,
BlockchainAssetsModel,
BlockchainCreateResultModel,
BlockchainDeleteModel,
BlockchainGetModel,
BlockchainGetResultModel,
BlockchainListResultModel,
BlockchainSignModel,
StellarWalletBalanceByAddressModel,
StellarWalletCreateModel,
StellarWalletInitModel,
StellarWalletTransferModel,
StellarWalletVerifyModel,
} from ".";
import blockchainInterface, { blockchainType } from "./blockchainInterface";
const server = new StellarSdk.Horizon.Server("https://horizon-testnet.stellar.org");
class Stellar implements blockchainInterface {
fileName = "stellar.json";
backendStorage: BackendStorage;
mnemonic: string;
tfClient: TFClient;
/**
* Class representing a Stellar blockchain implementation that implements the blockchainInterface.
*
* This class provides methods for creating, initializing, signing, verifying, updating, checking existence,
* listing, retrieving assets, checking balance by address, and making payments for Stellar wallets.
*
* @class Stellar
* @param {GridClientConfig} config - The configuration object for initializing the client.
*/
constructor(public config: GridClientConfig) {
this.mnemonic = config.mnemonic;
this.backendStorage = new BackendStorage(
config.backendStorageType,
config.substrateURL,
config.mnemonic,
config.storeSecret,
config.keypairType,
config.backendStorage,
config.seed,
);
this.tfClient = config.tfclient;
}
/**
* Saves the extrinsics to the `key-value` store backend if the backend storage type is `tfkvstore` and extrinsics are provided.
*
* @param {ExtrinsicResult[]} extrinsics - The extrinsics to be saved to the `key-value` store backend.
* @returns {Promise<void>} - A promise that resolves once the extrinsics are saved to the backend.
*/
private async saveIfKVStoreBackend(extrinsics: ExtrinsicResult<string>[]) {
if (this.config.backendStorageType === BackendStorageType.tfkvstore && extrinsics && extrinsics.length > 0) {
extrinsics = extrinsics.filter(e => e !== undefined);
if (extrinsics.length > 0) {
await this.tfClient.connect();
await this.tfClient.applyAllExtrinsics(extrinsics);
}
}
}
/**
* Loads data from the backend storage using the specified path.
*
* @returns {Promise<[string, any]>} A promise that resolves with an array containing the path and the loaded data.
*/
async _load(): Promise<[string, any]> {
const path = PATH.join(appPath, this.fileName);
let data = await this.backendStorage.load(path);
if (!data) {
data = {};
}
return [path, data];
}
/**
* Saves a wallet with the provided name and secret to the backend storage.
*
* @param {string} name - The name of the wallet to be saved.
* @param {string} secret - The secret key of the wallet to be saved.
* @throws {`ValidationError`} - If there is another wallet with the same name.
* @returns {Promise<void>} - A promise that resolves once the wallet is saved to the backend storage.
*/
async save(name: string, secret: string): Promise<void> {
const [path, data] = await this._load();
if (data[name]) {
throw new ValidationError(`A wallet with the same name ${name} already exists.`);
}
const updateOperations = await this.backendStorage.update(path as string, name, secret);
await this.saveIfKVStoreBackend(updateOperations);
}
/**
* Retrieves the secret key of a wallet by its name from the backend storage.
*
* @param {string} name - The name of the wallet to retrieve the secret key for.
* @throws {`ValidationError`} - If the wallet with the provided name is not found in the backend storage.
* @returns {Promise<string>} - A promise that resolves with the secret key of the wallet.
*/
async getWalletSecret(name: string): Promise<string> {
const [, data] = await this._load();
if (!data[name]) {
throw new ValidationError(`Couldn't find a wallet with name ${name}.`);
}
return data[name];
}
/**
* Creates a new Stellar wallet with the provided name and saves it to the backend storage.
*
* @param {StellarWalletCreateModel} options - The options for creating the Stellar wallet, including the name.
* @returns {Promise<BlockchainCreateResultModel>} - A promise that resolves with the details of the created wallet, including name, public key, secret, and blockchain type.
* @throws {`ValidationError`} - If a wallet with the same name already exists.
* @throws {`RequestError`} - If an error occurs while creating the account.
* @decorators
* - `@expose`: Exposes the method for external use.
* - `@validateInput`: Validates the input options.
*/
@expose
@validateInput
async create(options: StellarWalletCreateModel): Promise<BlockchainCreateResultModel> {
const account_exists = await this.exist({ name: options.name });
if (account_exists) throw new ValidationError(`Name ${options.name} already exists`);
const account = StellarSdk.Keypair.random();
const publicKey = account.publicKey();
try {
await axios.get(`https://friendbot.stellar.org?addr=${encodeURIComponent(publicKey)}`);
} catch (e) {
throw new RequestError(`An error happened while creating your account. ${e}`, (e as AxiosError).response?.status);
}
await this.save(options.name, account.secret());
return {
name: options.name,
public_key: publicKey,
secret: account.secret(),
blockchain_type: blockchainType.stellar,
};
}
/**
* Signs the provided content using the secret key of the wallet associated with the given name.
*
* @param {BlockchainSignModel} options - The options containing the name of the wallet and the content to sign.
* @returns {Promise<string>} A Promise that resolves the signed content in `hexadecimal` format.
* @throws {`ValidationError`} - If the wallet with the provided name is not found in the backend storage.
* @decorators
* - `@expose`: Exposes the method for external use.
* - `@validateInput`: Validates the input options.
*/
@expose
@validateInput
async sign(options: BlockchainSignModel): Promise<string> {
const secret = await this.getWalletSecret(options.name);
const walletKeypair = StellarSdk.Keypair.fromSecret(secret);
const contentBuffer = Buffer.from(options.content);
const signed_content = walletKeypair.sign(contentBuffer);
return signed_content.toString("hex");
}
/**
* Verifies the provided signed content using the public key and content.
*
* @param {StellarWalletVerifyModel} options - The options containing the public key, content, and signed content.
* @returns {boolean} - A boolean indicating whether the content is successfully verified.
* @throws {`ValidationError`} - If the provided public key is invalid or the verification fails.
* @decorators
* - `@expose`: Exposes the method for external use.
* - `@validateInput`: Validates the input options.
*/
@expose
@validateInput
verify(options: StellarWalletVerifyModel): boolean {
const walletKeypair = StellarSdk.Keypair.fromPublicKey(options.public_key);
const contentBuffer = Buffer.from(options.content);
const signatureBuffer = Buffer.from(options.signedContent, "hex");
return walletKeypair.verify(contentBuffer, signatureBuffer);
}
/**
* Loads `Stellar wallet` based on the provided `name` and `secret key`.
*
* This method loads the account associated with the wallet's `public key`, and saves the wallet to the backend storage.
*
* @param {StellarWalletInitModel} options - The options for initializing the `Stellar` wallet, including the name and `secret key`.
* @returns {Promise<string>} A Promise that resolves the `public key` of the initialized `Stellar` wallet.
* @throws {`ValidationError`} - If the provided `secret key` is invalid or the account cannot be loaded.
* @decorators
* - `@expose`: Exposes the method for external use.
* - `@validateInput`: Validates the input options.
*/
@expose
@validateInput
async init(options: StellarWalletInitModel): Promise<string> {
const walletKeypair = StellarSdk.Keypair.fromSecret(options.secret);
const walletPublicKey = walletKeypair.publicKey();
await server.loadAccount(walletPublicKey);
await this.save(options.name, options.secret);
return walletPublicKey;
}
/**
* Retrieves the details of a `Stellar wallet` by its name from the backend storage.
*
* This method fetches the public key and `secret key` associated with the provided wallet `name`.
*
* @param {BlockchainGetModel} options - The options containing the name of the wallet to retrieve.
* @returns {Promise<BlockchainGetResultModel>} - A promise that resolves with the details of the wallet, including `name`, `public key`, `secret key`, and `blockchain type`.
* @throws {`ValidationError`} - If the wallet with the provided name is not found in the backend storage.
* @decorators
* - `@expose`: Exposes the method for external use.
* - `@validateInput`: Validates the input options.
*/
@expose
@validateInput
async get(options: BlockchainGetModel): Promise<BlockchainGetResultModel> {
const secret = await this.getWalletSecret(options.name);
const walletKeypair = StellarSdk.Keypair.fromSecret(secret);
return {
name: options.name,
public_key: walletKeypair.publicKey(),
secret: secret,
blockchain_type: blockchainType.stellar,
};
// TODO: return wallet secret after adding security context on the server calls
}
/**
* Updates an existing `Stellar wallet` with the provided `name` and `secret key`.
*
* This method first checks if a wallet with the provided `name` exists, then deletes the wallet and reinitializes it with the new `secret key`.
*
* @param {StellarWalletInitModel} options - The options for updating the `Stellar wallet`, including the `name` and new `secret key`.
* @returns {Promise<string>} - A promise that resolves with the public key of the updated `Stellar wallet`.
* @throws {`ValidationError`} - If the wallet with the provided `name` is not found or if there is an issue during the update process.
* @decorators
* - `@expose`: Exposes the method for external use.
* - `@validateInput`: Validates the input options.
*/
@expose
@validateInput
async update(options: StellarWalletInitModel): Promise<string> {
if (!(await this.exist(options))) {
throw new ValidationError(`Couldn't find a wallet with name ${options.name} to update.`);
}
const secret = await this.getWalletSecret(options.name);
const deleteWallet = new BlockchainDeleteModel();
deleteWallet.name = options.name;
await this.delete(deleteWallet);
try {
return await this.init(options);
} catch (e) {
const oldSecret = options.secret;
options.secret = secret;
await this.init(options);
throw new GridClientError(`Couldn't import wallet with the secret ${oldSecret} due to: ${e}`);
}
}
/**
* Checks if a wallet with the provided `name` exists in the backend storage.
*
* @param {BlockchainGetModel} options - The options containing the `name` of the wallet to check.
* @returns {Promise<boolean>} - A promise that resolves with a boolean indicating whether the wallet exists.
* @decorators
* - `@expose`: Exposes the method for external use.
* - `@validateInput`: Validates the input options.
*/
@expose
@validateInput
async exist(options: BlockchainGetModel): Promise<boolean> {
return (await this.list()).map(account => account.name == options.name).includes(true);
}
/**
* Retrieves a list of `Stellar wallets` from the backend storage.
*
* This method fetches the `names`, `public keys`, and `blockchain types` of all `Stellar wallets` stored in the backend.
*
* @returns {Promise<BlockchainListResultModel[]>} - A promise that resolves with an array of objects representing each `Stellar wallet`, including `name`, `public key`, and `blockchain type`.
* @throws {ValidationError} - If there is an issue while retrieving the list of wallets from the backend storage.
* @decorators
* - `@expose`: Exposes the method for external use.
* - `@validateInput`: Validates the input options.
*/
@expose
@validateInput
async list(): Promise<BlockchainListResultModel[]> {
const [, data] = await this._load();
const accounts: BlockchainListResultModel[] = [];
for (const [name, secret] of Object.entries(data)) {
accounts.push({
name: name,
public_key: StellarSdk.Keypair.fromSecret(secret as string).publicKey(),
blockchain_type: blockchainType.stellar,
});
}
return accounts;
}
/**
* Retrieves the assets associated with a `Stellar wallet` by its `name` from the backend storage.
*
* This method fetches the `public key` of the wallet, retrieves the balances by address, and returns the assets including the asset code and balance.
*
* @param {BlockchainGetModel} options - The options containing the `name` of the wallet to retrieve assets for.
* @returns {Promise<BlockchainAssetsModel>} - A promise that resolves with the assets of the wallet, including `name`, `public key`, `blockchain type`, and `assets array`.
* @throws {`ValidationError`} - If the wallet with the provided `name` is not found in the backend storage.
* @decorators
* - `@expose`: Exposes the method for external use.
* - `@validateInput`: Validates the input options.
*/
@expose
@validateInput
async assets(options: BlockchainGetModel): Promise<BlockchainAssetsModel> {
const secret = await this.getWalletSecret(options.name);
if (!secret) {
throw new ValidationError(`Couldn't find a wallet with name ${options.name}.`);
}
const walletKeypair = StellarSdk.Keypair.fromSecret(secret);
const walletPublicKey = walletKeypair.publicKey();
const walletAddress = new StellarWalletBalanceByAddressModel();
walletAddress.address = walletPublicKey;
const balances = await this.balance_by_address(walletAddress);
return {
name: options.name,
public_key: walletPublicKey,
blockchain_type: blockchainType.stellar,
assets: balances ? balances : [],
};
}
/**
* Retrieves the assets associated with a `Stellar wallet` by its `address`.
*
* This method fetches the `balances` of the account associated with the provided `address` and returns the assets including the `asset code` and `balance`.
*
* @param {StellarWalletBalanceByAddressModel} options - The options containing the `address` of the wallet to retrieve assets for.
* @returns {Promise<BlockchainAssetModel[]>} - A promise that resolves with the assets of the wallet, including `asset` and `amount`.
* @throws {`ValidationError`} - If the wallet with the provided `address` is not found in the backend storage.
* @decorators
* - `@expose`: Exposes the method for external use.
* - `@validateInput`: Validates the input options.
*/
@expose
@validateInput
async balance_by_address(options: StellarWalletBalanceByAddressModel): Promise<BlockchainAssetModel[]> {
const account = await server.loadAccount(options.address);
const balances: BlockchainAssetModel[] = [];
for (const balance of account.balances) {
let assetCode = "XLM";
// Check if it's a non-native asset (has asset_code)
if ("asset_type" in balance && balance.asset_type !== "native") {
if ("asset_code" in balance) {
assetCode = balance.asset_code;
}
}
balances.push({
asset: assetCode,
amount: +balance.balance,
});
}
return balances;
}
/**
* Pays the specified `amount` of a given `asset` to a destination `address` from a `Stellar wallet`.
*
* This method retrieves the `secret key` of the wallet associated with the provided `name`, loads the source account,
* constructs a transaction to make a payment to the destination address with the specified asset and amount,
* signs the transaction with the wallet's secret key, and submits the transaction to the Stellar network.
*
* @param {StellarWalletTransferModel} options - The options for making the payment, including the name of the wallet, destination address, amount, asset, and optional description.
* @returns {Promise<string>} - A promise that resolves with the URL to view the transaction details on the Stellar network.
* @throws {`ValidationError`} - If the wallet with the provided name is not found or if there is an issue during the payment process.
* @decorators
* - `@expose`: Exposes the method for external use.
* - `@validateInput`: Validates the input options.
*/
@expose
@validateInput
async pay(options: StellarWalletTransferModel): Promise<string> {
const secret = await this.getWalletSecret(options.name);
if (!secret) {
throw new ValidationError(`Couldn't find a wallet with name ${options.name}`);
}
const sourceKeypair = StellarSdk.Keypair.fromSecret(secret);
const sourcePublicKey = sourceKeypair.publicKey();
const sourceAccount = await server.loadAccount(sourcePublicKey);
let asset;
if (options.asset != "XLM") {
let issuer;
for (const balance of sourceAccount.balances) {
if (
"asset_type" in balance &&
balance.asset_type !== "native" &&
"asset_code" in balance &&
balance.asset_code === options.asset &&
"asset_issuer" in balance
) {
issuer = balance.asset_issuer;
}
}
if (!issuer) {
throw new ValidationError(`couldn't find this asset ${options.asset} on source wallet.`);
}
asset = new StellarSdk.Asset(options.asset, issuer);
} else {
asset = StellarSdk.Asset.native();
}
const fee = await server.fetchBaseFee();
const memo = options.description ? StellarSdk.Memo.text(options.description) : undefined;
const transaction = new StellarSdk.TransactionBuilder(sourceAccount, {
fee: fee.toString(),
networkPassphrase: StellarSdk.Networks.TESTNET,
memo: memo,
})
.addOperation(
StellarSdk.Operation.payment({
destination: options.address_dest,
asset: asset,
amount: options.amount.toString(),
}),
)
.setTimeout(30)
.build();
transaction.sign(sourceKeypair);
console.log(transaction.toEnvelope().toXDR("base64"));
try {
const transactionResult = await server.submitTransaction(transaction);
console.log(JSON.stringify(transactionResult, null, 2));
let transactionUrl = "";
const result = transactionResult as Record<string, any>;
if (
result &&
result._links &&
typeof result._links === "object" &&
result._links.transaction &&
typeof result._links.transaction === "object" &&
result._links.transaction.href &&
typeof result._links.transaction.href === "string"
) {
transactionUrl = result._links.transaction.href;
console.log("Success! View the transaction at: ", transactionUrl);
} else {
console.log("Transaction successful, but URL not available in response");
const txHash = result && typeof result.hash === "string" ? result.hash : "";
transactionUrl = `https://horizon-testnet.stellar.org/transactions/${txHash}`;
}
return transactionUrl;
} catch (e) {
throw new GridClientError(`An error has occurred: ${e}`);
}
}
/**
* Deletes a wallet with the provided `name` from the backend storage.
*
* This method checks if a wallet with the given `name` exists, deletes it from the backend storage,
* and saves the changes to the backend storage.
*
* @param {BlockchainDeleteModel} options - The options containing the name of the wallet to delete.
* @returns {Promise<string>} - A promise that resolves with a message indicating the deletion was successful.
* @throws {`ValidationError`} - If the wallet with the provided name is not found in the backend storage.
* @decorators
* - `@expose`: Exposes the method for external use.
* - `@validateInput`: Validates the input options.
*/
@expose
@validateInput
async delete(options: BlockchainDeleteModel): Promise<string> {
const [path, data] = await this._load();
if (!data[options.name]) {
throw new ValidationError(`Couldn't find a wallet with name ${options.name}.`);
}
const updateOperations = await this.backendStorage.update(
path as string,
options.name,
"",
StorageUpdateAction.delete,
);
await this.saveIfKVStoreBackend(updateOperations);
return "Deleted";
}
}
export { Stellar as stellar };