@stellar/typescript-wallet-sdk 1.1.3 → 1.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/examples/sep24/README.md +22 -0
  2. package/examples/sep24/sep24.ts +199 -0
  3. package/lib/bundle.js +369 -36
  4. package/lib/bundle.js.map +1 -1
  5. package/lib/bundle_browser.js +369 -36
  6. package/lib/bundle_browser.js.map +1 -1
  7. package/lib/index.d.ts +1 -1
  8. package/lib/walletSdk/Auth/WalletSigner.d.ts +23 -1
  9. package/lib/walletSdk/Exceptions/index.d.ts +5 -1
  10. package/lib/walletSdk/Horizon/Transaction/CommonTransactionBuilder.d.ts +18 -0
  11. package/lib/walletSdk/Horizon/Transaction/SponsoringBuilder.d.ts +10 -0
  12. package/lib/walletSdk/Horizon/Transaction/TransactionBuilder.d.ts +42 -9
  13. package/lib/walletSdk/Horizon/index.d.ts +1 -0
  14. package/lib/walletSdk/Types/auth.d.ts +3 -0
  15. package/lib/walletSdk/Types/horizon.d.ts +11 -1
  16. package/lib/walletSdk/Types/index.d.ts +7 -0
  17. package/lib/walletSdk/Utils/extractAxiosErrorData.d.ts +2 -0
  18. package/lib/walletSdk/Utils/index.d.ts +1 -0
  19. package/lib/walletSdk/index.d.ts +2 -1
  20. package/package.json +5 -3
  21. package/src/index.ts +1 -0
  22. package/src/walletSdk/Anchor/Sep24.ts +2 -0
  23. package/src/walletSdk/Auth/WalletSigner.ts +64 -1
  24. package/src/walletSdk/Auth/index.ts +1 -1
  25. package/src/walletSdk/Exceptions/index.ts +22 -2
  26. package/src/walletSdk/Horizon/Stellar.ts +1 -0
  27. package/src/walletSdk/Horizon/Transaction/CommonTransactionBuilder.ts +75 -0
  28. package/src/walletSdk/Horizon/Transaction/SponsoringBuilder.ts +58 -0
  29. package/src/walletSdk/Horizon/Transaction/TransactionBuilder.ts +116 -34
  30. package/src/walletSdk/Horizon/index.ts +1 -0
  31. package/src/walletSdk/Types/auth.ts +4 -0
  32. package/src/walletSdk/Types/horizon.ts +12 -1
  33. package/src/walletSdk/Types/index.ts +8 -1
  34. package/src/walletSdk/Utils/extractAxiosErrorData.ts +28 -0
  35. package/src/walletSdk/Utils/index.ts +1 -0
  36. package/src/walletSdk/index.ts +7 -1
  37. package/test/stellar.test.ts +198 -1
  38. package/test/transaction.test.ts +325 -0
  39. package/test/wallet.test.ts +43 -0
@@ -17,15 +17,19 @@ import {
17
17
  WithdrawalTxMemoError,
18
18
  } from "../../Exceptions";
19
19
  import { IssuedAssetId, StellarAssetId } from "../../Asset";
20
- import { WithdrawTransaction, TransactionStatus } from "../../Types";
21
-
22
- export class TransactionBuilder {
23
- private network: Networks;
24
- private operations: Array<xdr.Operation>;
20
+ import {
21
+ WithdrawTransaction,
22
+ TransactionStatus,
23
+ PathPayParams,
24
+ } from "../../Types";
25
+ import { PathPayOnlyOneAmountError } from "../../Exceptions";
26
+ import { CommonTransactionBuilder } from "./CommonTransactionBuilder";
27
+ import { SponsoringBuilder } from "./SponsoringBuilder";
28
+
29
+ export class TransactionBuilder extends CommonTransactionBuilder<TransactionBuilder> {
30
+ private cfg: Config;
25
31
  private builder: StellarTransactionBuilder;
26
32
 
27
- sourceAccount: string;
28
-
29
33
  constructor(
30
34
  cfg: Config,
31
35
  sourceAccount: StellarAccount,
@@ -33,8 +37,7 @@ export class TransactionBuilder {
33
37
  memo?: Memo,
34
38
  timebounds?: Server.Timebounds,
35
39
  ) {
36
- this.network = cfg.stellar.network;
37
- this.operations = [];
40
+ super(sourceAccount.accountId(), []);
38
41
  this.builder = new StellarTransactionBuilder(sourceAccount, {
39
42
  fee: baseFee ? baseFee.toString() : cfg.stellar.baseFee.toString(),
40
43
  timebounds,
@@ -44,8 +47,20 @@ export class TransactionBuilder {
44
47
  if (!timebounds) {
45
48
  this.builder.setTimeout(cfg.stellar.defaultTimeout);
46
49
  }
50
+ }
47
51
 
48
- this.sourceAccount = sourceAccount.accountId();
52
+ sponsoring(
53
+ sponsorAccount: AccountKeypair,
54
+ buildingFunction: (SponsoringBuilder) => SponsoringBuilder,
55
+ sponsoredAccount?: AccountKeypair,
56
+ ): TransactionBuilder {
57
+ new SponsoringBuilder(
58
+ sponsoredAccount ? sponsoredAccount.publicKey : this.sourceAddress,
59
+ sponsorAccount,
60
+ this.operations,
61
+ buildingFunction,
62
+ );
63
+ return this;
49
64
  }
50
65
 
51
66
  createAccount(
@@ -60,7 +75,7 @@ export class TransactionBuilder {
60
75
  StellarSdk.Operation.createAccount({
61
76
  destination: newAccount.publicKey,
62
77
  startingBalance: startingBalance.toString(),
63
- source: this.sourceAccount,
78
+ source: this.sourceAddress,
64
79
  }),
65
80
  );
66
81
  return this;
@@ -81,39 +96,99 @@ export class TransactionBuilder {
81
96
  return this;
82
97
  }
83
98
 
84
- addOperation(op: xdr.Operation): TransactionBuilder {
85
- this.builder.addOperation(op);
86
- return this;
87
- }
99
+ /**
100
+ * Creates and adds a path payment operation to the transaction builder.
101
+ *
102
+ * @param {string} destinationAddress - The destination Stellar address to which the payment is sent.
103
+ * @param {StellarAssetId} sendAsset - The asset to be sent.
104
+ * @param {StellarAssetId} destAsset - The asset the destination will receive.
105
+ * @param {string} [sendAmount] - The amount to be sent. Must specify either sendAmount or destAmount,
106
+ * but not both.
107
+ * @param {string} [destAmount] - The amount to be received by the destination. Must specify either sendAmount or destAmount,
108
+ * but not both.
109
+ * @param {string} [destMin] - The minimum amount of the destination asset to be receive. This is a
110
+ * protective measure, it allows you to specify a lower bound for an acceptable conversion. Only used
111
+ * if using sendAmount.
112
+ * (optional, default is ".0000001").
113
+ * @param {string} [sendMax] - The maximum amount of the destination asset to be sent. This is a
114
+ * protective measure, it allows you to specify an upper bound for an acceptable conversion. Only used
115
+ * if using destAmount.
116
+ * (optional, default is int64 max).
117
+ *
118
+ * @returns {TransactionBuilder} - Returns the current TransactionBuilder instance for method chaining.
119
+ */
120
+ pathPay({
121
+ destinationAddress,
122
+ sendAsset,
123
+ destAsset,
124
+ sendAmount,
125
+ destAmount,
126
+ destMin,
127
+ sendMax,
128
+ }: PathPayParams): TransactionBuilder {
129
+ if ((sendAmount && destAmount) || (!sendAmount && !destAmount)) {
130
+ throw new PathPayOnlyOneAmountError();
131
+ }
132
+ if (sendAmount) {
133
+ this.operations.push(
134
+ StellarSdk.Operation.pathPaymentStrictSend({
135
+ destination: destinationAddress,
136
+ sendAsset: sendAsset.toAsset(),
137
+ sendAmount,
138
+ destAsset: destAsset.toAsset(),
139
+ destMin: destMin || ".0000001",
140
+ }),
141
+ );
142
+ } else {
143
+ this.operations.push(
144
+ StellarSdk.Operation.pathPaymentStrictReceive({
145
+ destination: destinationAddress,
146
+ sendAsset: sendAsset.toAsset(),
147
+ destAmount,
148
+ destAsset: destAsset.toAsset(),
149
+ sendMax: sendMax || "922337203685.4775807",
150
+ }),
151
+ );
152
+ }
88
153
 
89
- setMemo(memo: Memo): TransactionBuilder {
90
- this.builder.addMemo(memo);
91
154
  return this;
92
155
  }
93
156
 
94
- addAssetSupport(
95
- asset: IssuedAssetId,
96
- trustLimit?: string,
157
+ /**
158
+ * Swap assets using the Stellar network. This swaps using the
159
+ * pathPaymentStrictReceive operation.
160
+ *
161
+ * @param {StellarAssetId} fromAsset - The source asset to be sent.
162
+ * @param {StellarAssetId} toAsset - The destination asset to receive.
163
+ * @param {string} amount - The amount of the source asset to be sent.
164
+ * @param {string} [destMin] - (Optional) The minimum amount of the destination asset to be received.
165
+ *
166
+ * @returns {TransactionBuilder} Returns the current instance of the TransactionBuilder for method chaining.
167
+ */
168
+ swap(
169
+ fromAsset: StellarAssetId,
170
+ toAsset: StellarAssetId,
171
+ amount: string,
172
+ destMin?: string,
97
173
  ): TransactionBuilder {
98
- this.operations.push(
99
- StellarSdk.Operation.changeTrust({
100
- asset: asset.toAsset(),
101
- limit: trustLimit,
102
- source: this.sourceAccount,
103
- }),
104
- );
174
+ this.pathPay({
175
+ destinationAddress: this.sourceAddress,
176
+ sendAsset: fromAsset,
177
+ destAsset: toAsset,
178
+ sendAmount: amount,
179
+ destMin,
180
+ });
105
181
  return this;
106
182
  }
107
183
 
108
- removeAssetSupport(asset: IssuedAssetId): TransactionBuilder {
109
- return this.addAssetSupport(asset, "0");
184
+ addOperation(op: xdr.Operation): TransactionBuilder {
185
+ this.builder.addOperation(op);
186
+ return this;
110
187
  }
111
188
 
112
- build(): Transaction {
113
- this.operations.forEach((op) => {
114
- this.builder.addOperation(op);
115
- });
116
- return this.builder.build();
189
+ setMemo(memo: Memo): TransactionBuilder {
190
+ this.builder.addMemo(memo);
191
+ return this;
117
192
  }
118
193
 
119
194
  transferWithdrawalTransaction(
@@ -150,4 +225,11 @@ export class TransactionBuilder {
150
225
  transaction.amount_in,
151
226
  );
152
227
  }
228
+
229
+ build(): Transaction {
230
+ this.operations.forEach((op) => {
231
+ this.builder.addOperation(op);
232
+ });
233
+ return this.builder.build();
234
+ }
153
235
  }
@@ -2,3 +2,4 @@ export { PublicKeypair, SigningKeypair } from "./Account";
2
2
  export { AccountService } from "./AccountService";
3
3
  export { Stellar } from "./Stellar";
4
4
  export { TransactionBuilder } from "./Transaction/TransactionBuilder";
5
+ export { SponsoringBuilder } from "./Transaction/SponsoringBuilder";
@@ -41,3 +41,7 @@ export type SignWithDomainAccountParams = {
41
41
  networkPassphrase: NetworkPassphrase;
42
42
  accountKp: AccountKeypair;
43
43
  };
44
+
45
+ export type HttpHeaders = {
46
+ [key: string]: string;
47
+ };
@@ -1,6 +1,7 @@
1
1
  import { Memo, Server, xdr, Transaction } from "stellar-sdk";
2
2
  import { AccountKeypair } from "../Horizon/Account";
3
3
  import { TransactionBuilder } from "../Horizon/Transaction/TransactionBuilder";
4
+ import { StellarAssetId } from "../Asset";
4
5
 
5
6
  export enum NETWORK_URLS {
6
7
  PUBLIC = "https://horizon.stellar.org",
@@ -9,7 +10,7 @@ export enum NETWORK_URLS {
9
10
 
10
11
  export type TransactionParams = {
11
12
  sourceAddress: AccountKeypair;
12
- baseFee: number;
13
+ baseFee?: number;
13
14
  memo?: Memo;
14
15
  timebounds?: Server.Timebounds | number;
15
16
  };
@@ -38,3 +39,13 @@ export enum HORIZON_ORDER {
38
39
  ASC = "asc",
39
40
  DESC = "desc",
40
41
  }
42
+
43
+ export type PathPayParams = {
44
+ destinationAddress: string;
45
+ sendAsset: StellarAssetId;
46
+ destAsset: StellarAssetId;
47
+ sendAmount?: string;
48
+ destAmount?: string;
49
+ destMin?: string;
50
+ sendMax?: string;
51
+ };
@@ -1,4 +1,4 @@
1
- import { AxiosRequestConfig } from "axios";
1
+ import { RawAxiosRequestHeaders } from "axios";
2
2
  import { Server, Networks } from "stellar-sdk";
3
3
  import { ApplicationConfiguration, StellarConfiguration } from "walletSdk";
4
4
 
@@ -30,6 +30,13 @@ export type StellarConfigurationParams = {
30
30
  defaultTimeout?: number;
31
31
  };
32
32
 
33
+ export type AxiosErrorData = {
34
+ status?: number;
35
+ statusText?: string;
36
+ responseData?: any;
37
+ headers?: RawAxiosRequestHeaders;
38
+ };
39
+
33
40
  // Export all other types from walletSdk/Types.ts
34
41
  export * from "./anchor";
35
42
  export * from "./auth";
@@ -0,0 +1,28 @@
1
+ import axios from "axios";
2
+ import { AxiosErrorData } from "../Types";
3
+
4
+ // Based on https://axios-http.com/docs/handling_errors
5
+
6
+ export const extractAxiosErrorData = (error: Error): AxiosErrorData => {
7
+ if (!axios.isAxiosError(error)) {
8
+ return { responseData: JSON.stringify(error) };
9
+ }
10
+ if (error.response) {
11
+ return {
12
+ status: error.response.status,
13
+ statusText: error.response.statusText,
14
+ responseData: error.response.data,
15
+ headers: error.response.headers,
16
+ };
17
+ } else if (error.request) {
18
+ // The request was made but no response was received
19
+ return {
20
+ statusText: `No response received from request: ${JSON.stringify(
21
+ error.request,
22
+ )}`,
23
+ };
24
+ } else {
25
+ // Something happened in setting up the request that triggered an Error
26
+ return { statusText: `Failed request with error: ${error.message}` };
27
+ }
28
+ };
@@ -1,3 +1,4 @@
1
1
  export * from "./camelToSnakeCase";
2
2
  export * from "./toml";
3
3
  export * from "./url";
4
+ export * from "./extractAxiosErrorData";
@@ -131,9 +131,15 @@ export const DefaultClient = axios.create({
131
131
  export class ApplicationConfiguration {
132
132
  defaultSigner: WalletSigner;
133
133
  defaultClient: AxiosInstance;
134
+ defaultClientDomain?: string;
134
135
 
135
- constructor(defaultSigner?: WalletSigner, defaultClient?: AxiosInstance) {
136
+ constructor(
137
+ defaultSigner?: WalletSigner,
138
+ defaultClient?: AxiosInstance,
139
+ defaultClientDomain?: string,
140
+ ) {
136
141
  this.defaultSigner = defaultSigner || DefaultSigner;
137
142
  this.defaultClient = defaultClient || DefaultClient;
143
+ this.defaultClientDomain = defaultClientDomain;
138
144
  }
139
145
  }
@@ -43,7 +43,6 @@ describe("Stellar", () => {
43
43
  const txBuilderParams = [
44
44
  {
45
45
  sourceAddress: kp,
46
- baseFee: 100,
47
46
  startingBalance: 2,
48
47
  },
49
48
  {
@@ -247,6 +246,127 @@ describe("Stellar", () => {
247
246
  }, 20000);
248
247
  });
249
248
 
249
+ let txnSourceKp;
250
+ let sponsorKp;
251
+ let newKp;
252
+ describe("SponsoringBuilder", () => {
253
+ beforeAll(async () => {
254
+ wal = Wallet.TestNet();
255
+ stellar = wal.stellar();
256
+
257
+ txnSourceKp = new SigningKeypair(Keypair.random());
258
+ sponsorKp = new SigningKeypair(Keypair.random());
259
+ newKp = new SigningKeypair(Keypair.random());
260
+ await axios.get(
261
+ "https://friendbot.stellar.org/?addr=" + sponsorKp.publicKey,
262
+ );
263
+ await axios.get(
264
+ "https://friendbot.stellar.org/?addr=" + txnSourceKp.publicKey,
265
+ );
266
+ }, 15000);
267
+
268
+ it("should sponsor creating an account", async () => {
269
+ const wal = Wallet.TestNet();
270
+ const stellar = wal.stellar();
271
+
272
+ const txBuilder = await stellar.transaction({
273
+ sourceAddress: txnSourceKp,
274
+ baseFee: 100,
275
+ });
276
+ const buildingFunction = (bldr) => bldr.createAccount(newKp, 0);
277
+ // scenario of different txn source account from sponsor account
278
+ const txn = txBuilder
279
+ .sponsoring(sponsorKp, buildingFunction, newKp)
280
+ .build();
281
+ newKp.sign(txn);
282
+ txnSourceKp.sign(txn);
283
+ sponsorKp.sign(txn);
284
+
285
+ const res = await stellar.submitTransaction(txn);
286
+ expect(res).toBe(true);
287
+
288
+ const sponsoredLoaded = (await stellar.server.loadAccount(
289
+ newKp.publicKey,
290
+ )) as any;
291
+ expect(sponsoredLoaded.num_sponsored).toBe(2);
292
+ }, 15000);
293
+
294
+ it("should sponsor adding trustlines", async () => {
295
+ const txBuilder = await stellar.transaction({
296
+ sourceAddress: txnSourceKp,
297
+ baseFee: 100,
298
+ });
299
+ const buildingFunction = (bldr) =>
300
+ bldr.addAssetSupport(
301
+ new IssuedAssetId(
302
+ "USDC",
303
+ "GBBD47IF6LWK7P7MDEVSCWR7DPUWV3NY3DTQEVFL4NAT4AQH3ZLLFLA5",
304
+ ),
305
+ );
306
+ const txn = txBuilder.sponsoring(sponsorKp, buildingFunction).build();
307
+ sponsorKp.sign(txn);
308
+ txnSourceKp.sign(txn);
309
+
310
+ const res = await stellar.submitTransaction(txn);
311
+ expect(res).toBe(true);
312
+
313
+ const sponsorLoaded = (await stellar.server.loadAccount(
314
+ sponsorKp.publicKey,
315
+ )) as any;
316
+ expect(sponsorLoaded.num_sponsoring).toBe(3);
317
+ }, 15000);
318
+
319
+ it("should allow sponsoring and regular operations in same transaction", async () => {
320
+ const txBuilder = await stellar.transaction({
321
+ sourceAddress: txnSourceKp,
322
+ baseFee: 100,
323
+ });
324
+ const buildingFunction = (bldr) =>
325
+ bldr.addAssetSupport(
326
+ new IssuedAssetId(
327
+ "USDC",
328
+ "GBBD47IF6LWK7P7MDEVSCWR7DPUWV3NY3DTQEVFL4NAT4AQH3ZLLFLA5",
329
+ ),
330
+ );
331
+ const txn = txBuilder
332
+ .sponsoring(sponsorKp, buildingFunction)
333
+ .transfer(sponsorKp.publicKey, new NativeAssetId(), "5")
334
+ .build();
335
+ sponsorKp.sign(txn);
336
+ txnSourceKp.sign(txn);
337
+
338
+ const res = await stellar.submitTransaction(txn);
339
+ expect(res).toBe(true);
340
+
341
+ const sponsorLoaded = (await stellar.server.loadAccount(
342
+ sponsorKp.publicKey,
343
+ )) as any;
344
+ expect(sponsorLoaded.num_sponsoring).toBe(3);
345
+ }, 15000);
346
+ it("should sponsor account modification", async () => {
347
+ const txBuilder = await stellar.transaction({
348
+ sourceAddress: txnSourceKp,
349
+ baseFee: 100,
350
+ });
351
+ const otherKp = new SigningKeypair(Keypair.random());
352
+
353
+ const txn = txBuilder
354
+ .sponsoring(sponsorKp, (bldr) => bldr.addAccountSigner(otherKp, 2))
355
+ .build();
356
+ sponsorKp.sign(txn);
357
+ txnSourceKp.sign(txn);
358
+
359
+ await stellar.submitTransaction(txn);
360
+ const sourceLoaded = (await stellar.server.loadAccount(
361
+ txnSourceKp.publicKey,
362
+ )) as any;
363
+ expect(
364
+ sourceLoaded.signers.find((signer) => signer.key === otherKp.publicKey)
365
+ .weight,
366
+ ).toBe(2);
367
+ }, 15000);
368
+ });
369
+
250
370
  describe("Asset", () => {
251
371
  it("should create an asset", () => {
252
372
  const issued = new IssuedAssetId(
@@ -266,3 +386,80 @@ describe("Asset", () => {
266
386
  expect(fiat.sep38).toBe("iso4217:USD");
267
387
  });
268
388
  });
389
+
390
+ describe("Account Modifying", () => {
391
+ it("should modify account ", async () => {
392
+ const wallet = Wallet.TestNet();
393
+ const stellar = wallet.stellar();
394
+
395
+ const sourceKp = new SigningKeypair(Keypair.random());
396
+ const otherKp = new SigningKeypair(Keypair.random());
397
+ await axios.get(
398
+ "https://friendbot.stellar.org/?addr=" + sourceKp.publicKey,
399
+ );
400
+ await axios.get("https://friendbot.stellar.org/?addr=" + otherKp.publicKey);
401
+
402
+ // Add account signer
403
+ let txBuilder = await stellar.transaction({
404
+ sourceAddress: sourceKp,
405
+ baseFee: 1000,
406
+ });
407
+ const tx = txBuilder.addAccountSigner(otherKp, 1).build();
408
+ tx.sign(sourceKp.keypair);
409
+ await stellar.submitTransaction(tx);
410
+
411
+ let resp = await stellar.server.loadAccount(sourceKp.publicKey);
412
+
413
+ expect(
414
+ resp.signers.find((signer) => signer.key === sourceKp.publicKey),
415
+ ).toBeTruthy();
416
+ expect(
417
+ resp.signers.find((signer) => signer.key === otherKp.publicKey),
418
+ ).toBeTruthy();
419
+
420
+ // Remove account signer
421
+ txBuilder = await stellar.transaction({
422
+ sourceAddress: sourceKp,
423
+ baseFee: 1000,
424
+ });
425
+ const removeTx = txBuilder.removeAccountSigner(otherKp).build();
426
+ removeTx.sign(sourceKp.keypair);
427
+ await stellar.submitTransaction(removeTx);
428
+
429
+ resp = await stellar.server.loadAccount(sourceKp.publicKey);
430
+ expect(
431
+ resp.signers.find((signer) => signer.key === sourceKp.publicKey),
432
+ ).toBeTruthy();
433
+ expect(
434
+ resp.signers.find((signer) => signer.key === otherKp.publicKey),
435
+ ).toBeFalsy();
436
+
437
+ // Change account thresholds
438
+ txBuilder = await stellar.transaction({
439
+ sourceAddress: sourceKp,
440
+ baseFee: 1000,
441
+ });
442
+ const thresholdTx = txBuilder.setThreshold({ low: 0, high: 1 }).build();
443
+ thresholdTx.sign(sourceKp.keypair);
444
+ await stellar.submitTransaction(thresholdTx);
445
+
446
+ resp = await stellar.server.loadAccount(sourceKp.publicKey);
447
+ expect(resp.thresholds).toEqual({
448
+ low_threshold: 0,
449
+ med_threshold: 0,
450
+ high_threshold: 1,
451
+ });
452
+
453
+ // Lock master account
454
+ txBuilder = await stellar.transaction({
455
+ sourceAddress: sourceKp,
456
+ baseFee: 1000,
457
+ });
458
+ const lockTx = txBuilder.lockAccountMasterKey().build();
459
+ lockTx.sign(sourceKp.keypair);
460
+ await stellar.submitTransaction(lockTx);
461
+
462
+ resp = await stellar.server.loadAccount(sourceKp.publicKey);
463
+ expect(resp.signers[0].weight).toBe(0);
464
+ }, 45000);
465
+ });